commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
2282d93db4422eac35ad3f8a65ed60e6c821eee7
tasks/mochacli.js
tasks/mochacli.js
'use strict'; var mocha = require('../lib/mocha'); module.exports = function (grunt) { grunt.registerMultiTask('mochacli', 'Run Mocha server-side tests.', function () { var options = this.options(); if (!options.files) { options.files = this.file.srcRaw; } mocha(options, this.async()); }); };
'use strict'; var mocha = require('../lib/mocha'); module.exports = function (grunt) { grunt.registerMultiTask('mochacli', 'Run Mocha server-side tests.', function () { var options = this.options(); var globs = []; if (!options.files) { this.files.forEach(function (glob) { globs = globs.concat(glob.orig.src); }); options.files = globs; } mocha(options, this.async()); }); };
Fix using the Grunt files format
Fix using the Grunt files format
JavaScript
mit
Rowno/grunt-mocha-cli
f65f19bf7d737cffdbe629247ac4913357c9d1ec
test/feature/Classes/NameBinding.js
test/feature/Classes/NameBinding.js
class ElementHolder { element; getElement() { return this.element; } makeFilterCapturedThis() { var capturedThis = this; return function (x) { return x == capturedThis.element; } } makeFilterLostThis() { return function (x) { return x == this.element; } } makeFilterHidden(element) { return function (x) { return x == element; } } } // ---------------------------------------------------------------------------- var obj = new ElementHolder(); obj.element = 40; assertEquals(40, obj.getElement()); assertTrue(obj.makeFilterCapturedThis()(40)); assertFalse(obj.makeFilterLostThis()(40)); obj.element = 39; assertFalse(obj.makeFilterCapturedThis()(40)); assertTrue(obj.makeFilterCapturedThis()(39)); assertFalse(obj.makeFilterHidden(41)(40)); assertTrue(obj.makeFilterHidden(41)(41));
class ElementHolder { element; getElement() { return this.element; } makeFilterCapturedThis() { var capturedThis = this; return function (x) { return x == capturedThis.element; } } makeFilterLostThis() { return function () { return this; } } makeFilterHidden(element) { return function (x) { return x == element; } } } // ---------------------------------------------------------------------------- var obj = new ElementHolder(); obj.element = 40; assertEquals(40, obj.getElement()); assertTrue(obj.makeFilterCapturedThis()(40)); // http://code.google.com/p/v8/issues/detail?id=1381 // assertUndefined(obj.makeFilterLostThis()()); obj.element = 39; assertFalse(obj.makeFilterCapturedThis()(40)); assertTrue(obj.makeFilterCapturedThis()(39)); assertFalse(obj.makeFilterHidden(41)(40)); assertTrue(obj.makeFilterHidden(41)(41));
Fix invalid test and disable it due to V8 bug
Fix invalid test and disable it due to V8 bug
JavaScript
apache-2.0
ide/traceur,ide/traceur,ide/traceur
5b3a341d2d53223775d7e09ab11819a5d433290f
packages/internal-test-helpers/lib/ember-dev/run-loop.js
packages/internal-test-helpers/lib/ember-dev/run-loop.js
import { cancelTimers, end, getCurrentRunLoop, hasScheduledTimers } from '@ember/runloop'; function RunLoopAssertion(env) { this.env = env; } RunLoopAssertion.prototype = { reset: function() {}, inject: function() {}, assert: function() { let { assert } = QUnit.config.current; if (getCurrentRunLoop()) { assert.ok(false, 'Should not be in a run loop at end of test'); while (getCurrentRunLoop()) { end(); } } if (hasScheduledTimers()) { assert.ok(false, 'Ember run should not have scheduled timers at end of test'); cancelTimers(); } }, restore: function() {}, }; export default RunLoopAssertion;
import { cancelTimers, end, getCurrentRunLoop, hasScheduledTimers } from '@ember/runloop'; export default class RunLoopAssertion { constructor(env) { this.env = env; } reset() {} inject() {} assert() { let { assert } = QUnit.config.current; if (getCurrentRunLoop()) { assert.ok(false, 'Should not be in a run loop at end of test'); while (getCurrentRunLoop()) { end(); } } if (hasScheduledTimers()) { assert.ok(false, 'Ember run should not have scheduled timers at end of test'); cancelTimers(); } } restore() {} }
Convert `RunLoopAssert` to ES6 class
internal-test-helpers: Convert `RunLoopAssert` to ES6 class
JavaScript
mit
kellyselden/ember.js,GavinJoyce/ember.js,mfeckie/ember.js,emberjs/ember.js,kellyselden/ember.js,Turbo87/ember.js,sandstrom/ember.js,stefanpenner/ember.js,bekzod/ember.js,kellyselden/ember.js,tildeio/ember.js,qaiken/ember.js,mixonic/ember.js,stefanpenner/ember.js,fpauser/ember.js,elwayman02/ember.js,fpauser/ember.js,givanse/ember.js,jaswilli/ember.js,knownasilya/ember.js,Turbo87/ember.js,miguelcobain/ember.js,cibernox/ember.js,emberjs/ember.js,sandstrom/ember.js,asakusuma/ember.js,cibernox/ember.js,mfeckie/ember.js,bekzod/ember.js,tildeio/ember.js,sly7-7/ember.js,asakusuma/ember.js,qaiken/ember.js,givanse/ember.js,sly7-7/ember.js,miguelcobain/ember.js,knownasilya/ember.js,cibernox/ember.js,jaswilli/ember.js,givanse/ember.js,mfeckie/ember.js,elwayman02/ember.js,miguelcobain/ember.js,asakusuma/ember.js,qaiken/ember.js,emberjs/ember.js,givanse/ember.js,mixonic/ember.js,GavinJoyce/ember.js,intercom/ember.js,fpauser/ember.js,bekzod/ember.js,jaswilli/ember.js,cibernox/ember.js,stefanpenner/ember.js,sly7-7/ember.js,intercom/ember.js,Turbo87/ember.js,elwayman02/ember.js,jaswilli/ember.js,asakusuma/ember.js,qaiken/ember.js,GavinJoyce/ember.js,fpauser/ember.js,GavinJoyce/ember.js,intercom/ember.js,tildeio/ember.js,bekzod/ember.js,intercom/ember.js,elwayman02/ember.js,miguelcobain/ember.js,sandstrom/ember.js,kellyselden/ember.js,Turbo87/ember.js,mfeckie/ember.js,mixonic/ember.js,knownasilya/ember.js
6e3621cb2032e7bf9e6a5ad977efecd70798f8b7
test/util.test.js
test/util.test.js
/* global describe, it, beforeEach */ import React from 'react' import { expect } from 'chai' import { sizeClassNames } from '../src/js/util' describe('Util', () => { describe('sizeClassNames', () => { it('should return one classname given props', () => { const props = { xs: 12 } const actual = sizeClassNames(props) expect(actual).to.equal('col-xs-12') }) it('should not return classnames given undefined props', () => { const props = { xs: 12, sm: undefined, md: undefined, lg: undefined, } const actual = sizeClassNames(props) expect(actual).to.equal('col-xs-12') }) it('should return all classnames given props', () => { const props = { xs: 12, sm: 6, md: 1, lg: 23, } const actual = sizeClassNames(props) expect(actual).to.equal('col-xs-12 col-sm-6 col-md-1 col-lg-23') }) }) })
/* global describe, it, beforeEach */ import React from 'react' import { expect } from 'chai' import { sizeClassNames } from '../src/js/util' describe('Util', () => { describe('sizeClassNames', () => { describe('using props', () => { it('should return one classname given props', () => { const props = { xs: 12 } const actual = sizeClassNames(props) expect(actual).to.equal('col-xs-12') }) it('should not return classnames given undefined props', () => { const props = { xs: 12, sm: undefined, md: undefined, lg: undefined, } const actual = sizeClassNames(props) expect(actual).to.equal('col-xs-12') }) it('should return all classnames given props', () => { const props = { xs: 12, sm: 6, md: 1, lg: 23, } const actual = sizeClassNames(props) expect(actual).to.equal('col-xs-12 col-sm-6 col-md-1 col-lg-23') }) }) describe('using props and offset', () => { it('should return one offset classname given props', () => { const props = { xsOffset: 20 } const actual = sizeClassNames(props) expect(actual).to.equal('col-xs-offset-20') }) it('should not return one offset classname given undefined props', () => { const props = { xsOffset: 2, smOffset: undefined, mdOffset: undefined, lgOffset: undefined, } const actual = sizeClassNames(props) expect(actual).to.equal('col-xs-offset-2') }) it('should return empty when offset is set to false', () => { const actual = sizeClassNames({}, { Offsets: false }) expect(actual).to.equal('') }) }) }) })
Add sizeClassNames Given Props & Offset Tests
Add sizeClassNames Given Props & Offset Tests
JavaScript
mit
frig-js/frigging-bootstrap,frig-js/frigging-bootstrap
31ee8ce20659751cb45fc1fc7c78167ce9171e1a
client/views/home/activities/trend/trend.js
client/views/home/activities/trend/trend.js
Template.homeResidentActivityLevelTrend.rendered = function () { // Get reference to template instance var instance = this; instance.autorun(function () { // Get reference to Route var router = Router.current(); // Get current Home ID var homeId = router.params.homeId; // Get data for trend line chart var data = ReactiveMethod.call("getHomeActivityCountTrend", homeId); if (data) { MG.data_graphic({ title: "Count of residents per activity level for each of last seven days", description: "Daily count of residents with inactive, semi-active, and active status.", data: [data[0], data[1], data[2]], x_axis: false, interpolate: 'basic', full_width: true, height: 200, right: 40, target: '#trend-chart', legend: ['Inactive','Semi-active','Active'], legend_target: '.legend', colors: ['red', 'gold', 'green'], aggregate_rollover: true }); } }); }
Template.homeResidentActivityLevelTrend.rendered = function () { // Get reference to template instance var instance = this; instance.autorun(function () { // Get reference to Route var router = Router.current(); // Get current Home ID var homeId = router.params.homeId; // Get data for trend line chart var data = ReactiveMethod.call("getHomeActivityCountTrend", homeId); if (data) { MG.data_graphic({ title: "Count of residents per activity level for each of last seven days", description: "Daily count of residents with inactive, semi-active, and active status.", data: data, x_axis: true, y_accessor: ['inactive', 'semiActive', 'active'], interpolate: 'basic', full_width: true, height: 333, right: 49, target: '#trend-chart', legend: ['Inactive','Semi-active','Active'], colors: ['red', 'gold', 'green'], aggregate_rollover: true }); } }); }
Use object attributes; adjust appearance
Use object attributes; adjust appearance
JavaScript
agpl-3.0
GeriLife/wellbeing,brylie/juhani-wellbeing,brylie/juhani-wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,GeriLife/wellbeing
ab5f7faeb6b09693c6804b011113ebe6bb8e9cd1
src/components/LandingCanvas/index.js
src/components/LandingCanvas/index.js
import React from 'react'; import Helmet from 'react-helmet'; import styles from './styles'; function calculateViewportFromWindow() { if (window.innerWidth >= 544) return 'sm'; if (window.innerWidth >= 768) return 'md'; if (window.innerWidth >= 992) return 'lg'; if (window.innerWidth >= 1200) return 'xl'; return'xs'; } function renderAugmentedChildren(props) { return React.Children.map(props.children, (child) => { if (!child) return null; return React.cloneElement(child, { viewport: props.viewport }); }); } const LandingCanvas = (props) => { const s = styles(props); let { viewport } = props; viewport = viewport || calculateViewportFromWindow(); return ( <div style={ s.wrapper }> <Helmet link={[ { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Lato' }, { rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css' } ]} /> { renderAugmentedChildren(props) } </div> ); } export default LandingCanvas;
import React from 'react'; import Helmet from 'react-helmet'; import styles from './styles'; function calculateViewportFromWindow() { if (typeof window !== 'undefined') { if (window.innerWidth >= 544) return 'sm'; if (window.innerWidth >= 768) return 'md'; if (window.innerWidth >= 992) return 'lg'; if (window.innerWidth >= 1200) return 'xl'; return'xs'; } else { return null; } } function renderAugmentedChildren(props) { return React.Children.map(props.children, (child) => { if (!child) return null; return React.cloneElement(child, { viewport: props.viewport }); }); } const LandingCanvas = (props) => { const s = styles(props); let { viewport } = props; viewport = viewport || calculateViewportFromWindow(); return ( <div style={ s.wrapper }> <Helmet link={[ { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Lato' }, { rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css' } ]} /> { renderAugmentedChildren(props) } </div> ); } export default LandingCanvas;
Disable viewport calculation in case of server side render
Disable viewport calculation in case of server side render
JavaScript
mit
line64/landricks-components
f43bcef83577cbc4ef82098ee9bae8fdf709b559
ui/src/stores/photos/index.js
ui/src/stores/photos/index.js
const SET_PHOTOS = 'SET_PHOTOS' const initialState = { photos: [], photosDetail: [] } const photos = (state = initialState, action = {}) => { switch (action.type) { case SET_PHOTOS: return {...state, photos: action.payload.ids, photosDetail:action.payload.photoList} default: return state } } export default photos
const SET_PHOTOS = 'SET_PHOTOS' const initialState = { photos: [], photosDetail: [] } const photos = (state = initialState, action = {}) => { switch (action.type) { case SET_PHOTOS: let index = state.photosDetail.filter((el) => { return action.payload.photoList.findIndex( (node) => el.node.id == node.node.id) }); return {...state, photos: Array.from(new Set([...state.photos, ...action.payload.ids])), photosDetail:[...state.photosDetail, ...action.payload.photoList]} default: return state } } export default photos
Add conditions to remove duplicates.
Add conditions to remove duplicates.
JavaScript
agpl-3.0
damianmoore/photo-manager,damianmoore/photo-manager,damianmoore/photo-manager,damianmoore/photo-manager
a73508bdc6301e616eb15a7f3ee88a5eb982e466
lib/registration.js
lib/registration.js
if ('serviceWorker' in navigator) { navigator.serviceWorker.register('./service-worker.js', {scope: './'}) .catch(function(error) { alert('Error registering service worker:'+error); }); } else { alert('service worker not supported'); }
if ('serviceWorker' in navigator) { navigator.serviceWorker.register('./service-worker.js', {scope: './'}) .catch(function(error) { console.error('Error registering service worker:'+error); }); } else { console.log('service worker not supported'); }
Use console.error and console.log instead of alert
Use console.error and console.log instead of alert
JavaScript
mit
marco-c/broccoli-serviceworker,jkleinsc/broccoli-serviceworker
1ebfe684c986124dd8fbf7a951b1c8e8ae94f371
lib/socketServer.js
lib/socketServer.js
const socketio = require('socket.io') const data = require('../data/tasks') let counter = 0 exports.listen = function (server) { io = socketio.listen(server) io.sockets.on('connection', function (socket) { console.log('Connection created') createTask(socket) displayAllTask(socket) }) const createTask = (socket) => { socket.on('createTask', (data) => { console.log('DB call-->', data.title, data.description, data.assignedTo, data.dueDate) //++counter let counter = ++data.seq console.log('Counter = ', counter) data['tasks'][counter] = { title: data.title, desc: data.description, status: 'new', assgnBy: 'current', assgnTo: data.assignedTo, createdOn: new Date().toISOString(), dueDate: data.dueDate } io.emit('updateTaskList', data) }) } const displayAllTask = (socket) => { socket.on('populateAllTask', (data) => { socket.emit('displayAllTask', data) }) } }
const socketio = require('socket.io') const data = require('../data/tasks') exports.listen = function (server) { io = socketio.listen(server) io.sockets.on('connection', function (socket) { console.log('Connection created') createTask(socket) displayAllTask(socket) }) const createTask = (socket) => { socket.on('createTask', (task) => { let counter = ++(data.seq) data['tasks'][counter] = { title: task.title, desc: task.description, status: 'new', assgnBy: 'current', assgnTo: task.assignedTo, createdOn: new Date().toISOString(), dueDate: task.dueDate } io.emit('updateTaskList', {task: task, status: 'new'}) }) } const displayAllTask = (socket) => { socket.on('populateAllTask', (data) => { socket.emit('displayAllTask', data) }) } }
Add createTask on and emit event with mock data
[SocketServer.js] Add createTask on and emit event with mock data
JavaScript
mit
geekskool/taskMaster,geekskool/taskMaster
5cf61c9fb5cb120e1531ac636e12727aee3768a6
lib/rsautl.js
lib/rsautl.js
var fs = require('fs'); var run = require('./runner'); var defaults = { opensslPath : '/usr/bin/openssl', padding : 'pkcs' }; function verifyOptions (options) { if (!fs.existsSync(options.opensslPath)) { throw new Error(options.opensslPath + ': No such file or directory'); } if (options.padding !== 'pkcs' && options.padding !== 'raw') { throw new Error('Unsupported padding: ' + options.padding); } } function operation (data, key, callback, options) { var options = options || {}; for (var attr in defaults) { if (!options[attr]) options[attr] = defaults[attr]; } options.operation = operation.caller.name; try { verifyOptions(options); run(options, data, key, callback); } catch (err) { return callback(err); } } exports.encrypt = function encrypt (data, key, callback, options) { operation(data, key, callback, options); }; exports.decrypt = function decrypt (data, key, callback, options) { operation(data, key, callback, options); }; exports.sign = function sign (data, key, callback, options) { operation(data, key, callback, options); }; exports.verify = function verify (data, key, callback, options) { operation(data, key, callback, options); };
var fs = require('fs'); var run = require('./runner'); var defaults = { opensslPath : '/usr/bin/openssl', padding : 'pkcs' }; function verifyOptions (options) { if (fs.existsSync !== undefined && !fs.existsSync(options.opensslPath)) { throw new Error(options.opensslPath + ': No such file or directory'); } if (options.padding !== 'pkcs' && options.padding !== 'raw') { throw new Error('Unsupported padding: ' + options.padding); } } function operation (data, key, callback, options) { var options = options || {}; for (var attr in defaults) { if (!options[attr]) options[attr] = defaults[attr]; } options.operation = operation.caller.name; try { verifyOptions(options); run(options, data, key, callback); } catch (err) { return callback(err); } } exports.encrypt = function encrypt (data, key, callback, options) { operation(data, key, callback, options); }; exports.decrypt = function decrypt (data, key, callback, options) { operation(data, key, callback, options); }; exports.sign = function sign (data, key, callback, options) { operation(data, key, callback, options); }; exports.verify = function verify (data, key, callback, options) { operation(data, key, callback, options); };
Handle Meteor's stripping out methods from the fs core API.
Handle Meteor's stripping out methods from the fs core API.
JavaScript
bsd-2-clause
ragnar-johannsson/rsautl
43590c27a485c93298bd89be4a1fe84e32aae30b
rollup.config.js
rollup.config.js
import resolve from 'rollup-plugin-node-resolve'; import eslint from 'rollup-plugin-eslint'; import babel from 'rollup-plugin-babel'; import commonjs from 'rollup-plugin-commonjs'; import replace from 'rollup-plugin-replace'; import pkg from './package.json'; export default [ { input: 'src/index.js', external: ['react', 'react-dom'], output: [ { file: pkg.main, format: 'umd', name: 'reactAccessibleAccordion' }, { file: pkg['jsnext:main'], format: 'es' }, ], name: 'reactAccessibleAccordion', plugins: [ resolve({ jsnext: true, main: true, browser: true, }), eslint(), babel(), commonjs(), replace({ exclude: 'node_modules/**', ENV: JSON.stringify(process.env.NODE_ENV || 'development'), }), ], }, ];
import resolve from 'rollup-plugin-node-resolve'; import eslint from 'rollup-plugin-eslint'; import babel from 'rollup-plugin-babel'; import commonjs from 'rollup-plugin-commonjs'; import replace from 'rollup-plugin-replace'; import pkg from './package.json'; export default [ { input: 'src/index.js', external: ['react', 'react-dom'], output: [ { file: pkg.main, format: 'umd', name: 'reactAccessibleAccordion' }, { file: pkg['jsnext:main'], format: 'es' }, ], name: 'reactAccessibleAccordion', plugins: [ replace({ 'process.env.NODE_ENV': JSON.stringify('production'), }), resolve({ jsnext: true, main: true, browser: true, }), eslint(), babel(), commonjs(), ], }, ];
Fix 'rollup-plugin-replace' order and variable name
Fix 'rollup-plugin-replace' order and variable name
JavaScript
mit
springload/react-accessible-accordion,springload/react-accessible-accordion,springload/react-accessible-accordion
206175481008af3ad074840a80f41816dcc2991c
public/app/components/chooseLanguage/chooseLanguage.js
public/app/components/chooseLanguage/chooseLanguage.js
product .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'components/chooseLanguage/chooseLanguage.tpl.html' ,controller: 'ChooseLanguageCtrl' ,resolve: { LanguageService: 'LanguageService', languages: function(LanguageService){ // This line is updated to return the promise //return LanguageService.query().$promise; } } }) .otherwise({ redirectTo: '/whatever' }); } ) .controller("ChooseLanguageCtrl", ['$scope','$http', '$q', '$location', 'LanguageService', ChooseLanguageCtrl]); function ChooseLanguageCtrl($scope, $http, $q, $location, LanguageService) { $scope.languages = LanguageService.query().$promise; $scope.languages.then(function (data) {$scope.languages= data;}); //Methods $scope.getCityWeather = function () { var data = LanguageService.get({city: $scope.select_city}).$promise; data.then(function(data) { $scope.information = data; }); }; } ;
product .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'components/chooseLanguage/chooseLanguage.tpl.html' ,resolve: { $b: ["$q", "LanguageService", function ($q, LanguageService) { return $q.all({ languages: LanguageService.query().$promise }); }] } ,controller: 'ChooseLanguageCtrl' }) .otherwise({ redirectTo: '/whatever' }); } ) .controller("ChooseLanguageCtrl", ['$scope','$http', '$q', '$location', '$b', 'LanguageService', ChooseLanguageCtrl]); function ChooseLanguageCtrl($scope, $http, $q, $location, $b, LanguageService) { angular.extend($scope, $b); //$scope.languages = LanguageService.query().$promise; //$scope.languages.then(function (data) {$scope.languages= data;}); //Methods $scope.getCityWeather = function () { var data = LanguageService.get({city: $scope.select_city}).$promise; data.then(function(data) { $scope.information = data; }); }; } ;
Fix change to resolve promise before controller
Fix change to resolve promise before controller
JavaScript
mit
stevenrojasv21/product-list-steven-rojas,stevenrojasv21/product-list-steven-rojas,stevenrojasv21/product-list-steven-rojas
4817ef6d6d10db74bc67a3f07c8db75bb2e3dd6e
common/predictive-text/unit_tests/headless/default-word-breaker.js
common/predictive-text/unit_tests/headless/default-word-breaker.js
/** * Smoke-test the default */ var assert = require('chai').assert; var breakWords = require('../../build/intermediate').wordBreakers['uax29']; const SHY = '\u00AD'; describe('The default word breaker', function () { it('should break multilingual text', function () { let breaks = breakWords( `ᑖᓂᓯ᙮ рабочий — after working on ka${SHY}wen${SHY}non:${SHY}nis let's eat phở! 🥣` ); let words = breaks.map(span => span.text); assert.deepEqual(words, [ 'ᑖᓂᓯ', '᙮', 'рабочий', '—', 'after', 'working', 'on', `ka${SHY}wen${SHY}non:${SHY}nis`, "let's", 'eat', 'phở', '!', '🥣' ]); }); });
/** * Smoke-test the default */ var assert = require('chai').assert; var breakWords = require('../../build/intermediate').wordBreakers['uax29']; const SHY = '\u00AD'; describe('The default word breaker', function () { it('should break multilingual text', function () { let breaks = breakWords( `Добрый день! ᑕᐻ᙮ — after working on ka${SHY}wen${SHY}non:${SHY}nis, let's eat phở! 🥣` ); let words = breaks.map(span => span.text); assert.deepEqual(words, [ 'Добрый', 'день', '!', 'ᑕᐻ', '᙮', '—', 'after', 'working', 'on', `ka${SHY}wen${SHY}non:${SHY}nis`, ',', "let's", 'eat', 'phở', '!', '🥣' ]); }); });
Make unit test slightly less weird.
Make unit test slightly less weird.
JavaScript
apache-2.0
tavultesoft/keymanweb,tavultesoft/keymanweb
5f079cbed8904f50c273aa5a017172081d91021f
js/projects.js
js/projects.js
/** * Created by sujithkatakam on 3/15/16. */ function pagination() { var monkeyList = new List('test-list', { valueNames: ['name'], page: 4, innerWindow: 4, plugins: [ ListPagination({}) ] }); } window.onload = function() { pagination(); getMonthsCount('experience', new Date(2014, 10, 15)); };
/** * Created by sujithkatakam on 3/15/16. */ function pagination() { var monkeyList = new List('test-list', { valueNames: ['name'], page: 4, innerWindow: 4, plugins: [ ListPagination({}) ] }); } window.onload = function() { pagination(); getMonthsCount('experience', new Date(2014, 10, 15), new Date(2016, 03, 15)); };
Work ex fix in summary
Work ex fix in summary
JavaScript
apache-2.0
sujithktkm/sujithktkm.github.io,sujithktkm/sujithktkm.github.io
1eeb1d49f7214732754b359bea00025d11395e4b
server/game/cards/02.2-FHaG/RaiseTheAlarm.js
server/game/cards/02.2-FHaG/RaiseTheAlarm.js
const DrawCard = require('../../drawcard.js'); class RaiseTheAlarm extends DrawCard { setupCardAbilities(ability) { this.action({ title: 'Flip a dynasty card', condition: context => this.game.isDuringConflict('military') && context.player.isDefendingPlayer(), cannotBeMirrored: true, effect: 'flip the card in the conflict province faceup', gameAction: ability.actions.flipDynasty(context => ({ target: context.player.controller.getDynastyCardInProvince(this.game.currentConflict.conflictProvince.location) })), then: context => ({ handler: () => { let card = context.player.controller.getDynastyCardInProvince(this.game.currentConflict.conflictProvince.location); if(card.type === 'character' && card.allowGameAction('putIntoConflict', context)) { this.game.addMessage('{0} is revealed and brought into the conflict!', card); ability.actions.putIntoConflict().resolve(card, context); } else { this.game.addMessage('{0} is revealed but cannot be brought into the conflict!', card); } } }) }); } } RaiseTheAlarm.id = 'raise-the-alarm'; module.exports = RaiseTheAlarm;
const DrawCard = require('../../drawcard.js'); class RaiseTheAlarm extends DrawCard { setupCardAbilities(ability) { this.action({ title: 'Flip a dynasty card', condition: context => this.game.isDuringConflict('military') && context.player.isDefendingPlayer(), cannotBeMirrored: true, effect: 'flip the card in the conflict province faceup', gameAction: ability.actions.flipDynasty(context => ({ target: context.player.getDynastyCardInProvince(this.game.currentConflict.conflictProvince.location) })), then: context => ({ handler: () => { let card = context.player.controller.getDynastyCardInProvince(this.game.currentConflict.conflictProvince.location); if(card.type === 'character' && card.allowGameAction('putIntoConflict', context)) { this.game.addMessage('{0} is revealed and brought into the conflict!', card); ability.actions.putIntoConflict().resolve(card, context); } else { this.game.addMessage('{0} is revealed but cannot be brought into the conflict!', card); } } }) }); } } RaiseTheAlarm.id = 'raise-the-alarm'; module.exports = RaiseTheAlarm;
Fix Raise the Alarm bug
Fix Raise the Alarm bug
JavaScript
mit
gryffon/ringteki,jeremylarner/ringteki,gryffon/ringteki,gryffon/ringteki,jeremylarner/ringteki,jeremylarner/ringteki
51be095bab5e4c8b34b8e2dda0bd56a565d43bad
app.js
app.js
/** * @module App Main Application Module */ 'use strict'; const express = require('express'); const app = express(); const api = require('./api/api.router'); app.use('/', express.static('public')); app.use('/api', api); module.exports = app;
/** * @module App Main Application Module */ 'use strict'; const express = require('express'); const app = express(); app.set('trust proxy', true); const api = require('./api/api.router'); app.use('/', express.static('public')); app.use('/api', api); module.exports = app;
Set trust proxy to true
Set trust proxy to true
JavaScript
mit
agroupp/test-api,agroupp/test-api
55a86b726335b4dbc2fa45b43e82c6245fdfed82
src/routes/Home/components/HomeView.js
src/routes/Home/components/HomeView.js
import React, { Component } from 'react' import { connect } from 'react-redux' import PropTypes from 'prop-types' import Sidebar from '../../../components/Sidebar' import TopicList from '../../../components/TopicList' import './HomeView.scss' class HomeView extends Component { static propTypes = { topics: PropTypes.object } transformTopicsToArray (obj) { const ids = Object.keys(obj) let arr = ids.map(id => { return { id: id, name: obj[id].name, point: obj[id].point } }) return arr } render () { return ( <div> <div className='column column--main'> <TopicList topics={this.transformTopicsToArray(this.props.topics)} /> </div> <div className='column column--side'> <Sidebar /> </div> </div> ) } } const mapStateToProps = state => { return { topics: state.topic.topics } } export default connect(mapStateToProps, null)(HomeView)
import React, { Component } from 'react' import { connect } from 'react-redux' import PropTypes from 'prop-types' import Sidebar from '../../../components/Sidebar' import TopicList from '../../../components/TopicList' import './HomeView.scss' class HomeView extends Component { static propTypes = { topics: PropTypes.object } constructor (props) { super(props) this.preprocessTopics = this.preprocessTopics.bind(this) } transformTopicsToArray (obj) { const ids = Object.keys(obj) let arr = ids.map(id => { return { id: id, name: obj[id].name, point: obj[id].point } }) return arr } sortTopicsByPoint (topics) { return topics.sort((a, b) => b.point - a.point) } preprocessTopics (topics) { let newTopics = this.transformTopicsToArray(topics) return this.sortTopicsByPoint(newTopics) } render () { return ( <div> <div className='column column--main'> <TopicList topics={this.preprocessTopics(this.props.topics)} /> </div> <div className='column column--side'> <Sidebar /> </div> </div> ) } } const mapStateToProps = state => { return { topics: state.topic.topics } } export default connect(mapStateToProps, null)(HomeView)
Sort topics by the number of upvotes/downvotes
Sort topics by the number of upvotes/downvotes
JavaScript
mit
AdrielLimanthie/carousell-reddit,AdrielLimanthie/carousell-reddit
a9817a7d8b33fa27072d5f5a55cfc49e00eada71
webpack.development.config.js
webpack.development.config.js
//extend webpack.config.js var config = require('./webpack.config'); var path = require('path'); //for more info, look into webpack.config.js //this will add a new object into default settings // config.entry = [ // 'webpack/hot/dev-server', // 'webpack-dev-server/client?http://localhost:8080', // ]; config.entry.app.push('webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:8080'); config.output = { path: path.resolve('dist'), filename: 'app.js', publicPath: '/' }; config.devtool = 'source-map'; config.devServer = { contentBase: 'src', stats: { colors: true }, hot: true }; module.exports = config;
//extend webpack.config.js var config = require('./webpack.config'); var path = require('path'); //for more info, look into webpack.config.js //this will add a new object into default settings // config.entry = [ // 'webpack/hot/dev-server', // 'webpack-dev-server/client?http://localhost:8080', // ]; config.entry.app.push('webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:8080'); config.output = { path: path.resolve('dist'), filename: 'app.js', publicPath: '/' }; config.devtool = 'source-map'; config.devServer = { contentBase: 'src', stats: { colors: true }, host: '0.0.0.0', hot: true, //UNCOMMENT THIS if you need to call you backend server // proxy: { // '/api/**': { // target: 'http://localhost:3000', // secure: false // } // } }; module.exports = config;
Allow server to be accessed via IP
Allow server to be accessed via IP
JavaScript
isc
terryx/react-webpack,terryx/react-webpack
c1439e9e07786a46290a550304f3c9014a1b3d06
src/app/projects/controller/project_list_controller.js
src/app/projects/controller/project_list_controller.js
/* * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ /** * The project list controller handles discovery for all projects, including * search. Note that it is assumed that we implemented a search (inclusive), * rather than a browse (exclusive) approach. */ angular.module('sb.projects').controller('ProjectListController', function ($scope) { 'use strict'; // search results must be of type "project" $scope.resourceTypes = ['Project']; // Projects have no default criteria $scope.defaultCriteria = []; });
/* * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ /** * The project list controller handles discovery for all projects, including * search. Note that it is assumed that we implemented a search (inclusive), * rather than a browse (exclusive) approach. */ angular.module('sb.projects').controller('ProjectListController', function ($scope, isSuperuser) { 'use strict'; // inject superuser flag to properly adjust UI. $scope.is_superuser = isSuperuser; // search results must be of type "project" $scope.resourceTypes = ['Project']; // Projects have no default criteria $scope.defaultCriteria = []; });
Tweak for Superuser UI in projects.
Tweak for Superuser UI in projects. This will properly align the create-project button for superadmin. Change-Id: Id79c7daa66b7db559bda5a41e494f17d519cf6a3
JavaScript
apache-2.0
ColdrickSotK/storyboard-webclient,ColdrickSotK/storyboard-webclient,ColdrickSotK/storyboard-webclient
dbf22af2728160fbe45245c9a779dec2f634cbe4
app/assets/javascripts/tests/helpers/common.js
app/assets/javascripts/tests/helpers/common.js
const chai = require('chai'); const sinon = require('sinon'); const sinonChai = require('sinon-chai'); // Require and load .env vars require('./dotenv'); // Configure chai to use Sinon-Chai chai.should(); chai.use(sinonChai); global.expect = chai.expect; global.sinon = sinon;
/** * This file is globally included on every testcase instance. It is useful to * load constants such as `chai`, `sinon` or any setup phase that we need. In * our case, we need to setup sinon-chai, avoiding repeating a chunk of code * across our test files. */ const chai = require('chai'); const sinon = require('sinon'); const sinonChai = require('sinon-chai'); // Require and load .env vars require('./dotenv'); // Configure chai to use Sinon-Chai chai.should(); chai.use(sinonChai); global.expect = chai.expect; global.sinon = sinon;
Add docs on global test file
Add docs on global test file
JavaScript
bsd-3-clause
kriansa/amelia,kriansa/amelia,kriansa/amelia,kriansa/amelia
b260f27e0176f2615236e78e06c8af045f5b0680
scripts/build.js
scripts/build.js
const buildBaseCss = require(`./_build-base-css.js`); const buildBaseHtml = require(`./_build-base-html.js`); const buildPackageCss = require(`./_build-package-css.js`); const buildPackageHtml = require(`./_build-package-html.js`); const getDirectories = require(`./_get-directories.js`); const packages = getDirectories(`avalanche/packages`); const data = {}; buildBaseHtml({}); buildBaseCss(); packages.forEach((packageName) => { data.title = packageName; data.css = `<link rel="stylesheet" href="css/index.css">`; data.scripts = ``; buildPackageHtml(packageName, data); buildPackageCss(packageName); });
const buildBaseCss = require(`./_build-base-css.js`); const buildBaseHtml = require(`./_build-base-html.js`); const buildPackageCss = require(`./_build-package-css.js`); const buildPackageHtml = require(`./_build-package-html.js`); const getDirectories = require(`./_get-directories.js`); const packages = getDirectories(`avalanche/packages`); const data = { css: `<link rel="stylesheet" href="/base/css/global.css">` }; buildBaseHtml(data); buildBaseCss(); packages.forEach((packageName) => { data.title = packageName; data.css += `<link rel="stylesheet" href="css/index.css">`; data.scripts = ``; buildPackageHtml(packageName, data); buildPackageCss(packageName); });
Add global.css file to pages by default
Add global.css file to pages by default
JavaScript
mit
avalanchesass/avalanche-website,avalanchesass/avalanche-website
c8a608cf64c5fb9ce0f24beee53b7acccfc4cd03
packages/custom/icu/public/components/data/context/context.service.js
packages/custom/icu/public/components/data/context/context.service.js
'use strict'; angular.module('mean.icu').service('context', function ($injector, $q) { var mainMap = { task: 'tasks', user: 'people', project: 'projects', discussion: 'discussions', officeDocument:'officeDocuments', office: 'offices', templateDoc: 'templateDocs', folder: 'folders' }; return { entity: null, entityName: '', entityId: '', main: '', setMain: function (main) { this.main = mainMap[main]; }, getContextFromState: function(state) { var parts = state.name.split('.'); if (parts[0] === 'main') { var reverseMainMap = _(mainMap).invert(); var main = 'task'; if (parts[1] !== 'search') { main = reverseMainMap[parts[1]]; } var params = state.params; var entityName = params.entity; if (!entityName && parts[2] === 'all') { entityName = 'all'; } if (!entityName && parts[2] === 'byassign') { entityName = 'my'; } if (!entityName && parts[2] === 'byparent') { entityName = main; } return { main: main, entityName: entityName, entityId: params.entityId }; } } }; });
'use strict'; angular.module('mean.icu').service('context', function ($injector, $q) { var mainMap = { task: 'tasks', user: 'people', project: 'projects', discussion: 'discussions', officeDocument:'officeDocuments', office: 'offices', templateDoc: 'templateDocs', folder: 'folders' }; return { entity: null, entityName: '', entityId: '', main: '', setMain: function (main) { this.main = mainMap[main]; }, getContextFromState: function(state) { var parts = state.name.split('.'); if (parts[0] === 'main') { var reverseMainMap = _(mainMap).invert(); var main = 'task'; if (parts[1] !== 'search') { main = reverseMainMap[parts[1]]; } // When in context of search, the entity you selected is in parts[2] if (parts[1] == 'search') { main = reverseMainMap[parts[2]]; } var params = state.params; var entityName = params.entity; if (!entityName && parts[2] === 'all') { entityName = 'all'; } if (!entityName && parts[2] === 'byassign') { entityName = 'my'; } if (!entityName && parts[2] === 'byparent') { entityName = main; } return { main: main, entityName: entityName, entityId: params.entityId }; } } }; });
Make correct context when select entity in search
Make correct context when select entity in search
JavaScript
mit
linnovate/icu,linnovate/icu,linnovate/icu
e5985521ee1fd0960dcc6af004e5dd831857685d
app/props/clickable.js
app/props/clickable.js
import Prop from 'props/prop'; import canvas from 'canvas'; import mouse from 'lib/mouse'; // http://stackoverflow.com/questions/16628184/add-onclick-and-onmouseover-to-canvas-element export default class Clickable extends Prop { constructor(x, y, width, height, fn) { super(x, y, width, height); this.fn = fn; this.onClick = this.onClick.bind(this); } onClick(event) { const coords = mouse.getCoordinates(event); if (this.isPointInside(coords.x, coords.y)) { this.fn(); this.destroy(); } } render() { canvas.addEventListener('click', this.onClick); // @TODO: Remove this debug when complete. super.render(null, null, 'rgba(50, 50, 50, 1)'); } destroy() { canvas.removeEventListener('click', this.onClick); } isPointInside(x, y) { return (x >= this.x && x <= this.x + this.width && y >= this.y && y <= this.y + this.height); } }
import Prop from 'props/prop'; import canvas from 'canvas'; import mouse from 'lib/mouse'; // http://stackoverflow.com/questions/16628184/add-onclick-and-onmouseover-to-canvas-element export default class Clickable extends Prop { constructor(x, y, width, height, fn) { super(x, y, width, height); this.fn = fn; this.onClick = this.onClick.bind(this); } onClick(event) { const coords = mouse.getCoordinates(event); if (this.isPointInside(coords.x, coords.y)) { this.fn(); this.destroy(); } } render() { canvas.addEventListener('click', this.onClick); } destroy() { canvas.removeEventListener('click', this.onClick); } isPointInside(x, y) { return (x >= this.x && x <= this.x + this.width && y >= this.y && y <= this.y + this.height); } }
Remove rendering for debugging click handlers
Remove rendering for debugging click handlers
JavaScript
mit
oliverbenns/pong,oliverbenns/pong
2a8cd200a67562a32fcce6dd01e253985e94d18a
05/jjhampton-ch5-every-some.js
05/jjhampton-ch5-every-some.js
// Arrays also come with the standard methods every and some. Both take a predicate function that, when called with an array element as argument, returns true or false. Just like && returns a true value only when the expressions on both sides are true, every returns true only when the predicate returns true for all elements of the array. Similarly, some returns true as soon as the predicate returns true for any of the elements. They do not process more elements than necessary—for example, if some finds that the predicate holds for the first element of the array, it will not look at the values after that. // Write two functions, every and some, that behave like these methods, except that they take the array as their first argument rather than being a method. function every(array, action) { let conditional = true; for (let i = 0; i < array.length; i++) { if (!action(array[i])) conditional = false; } return conditional; } function some(array, action) { let conditional = false; for (let i = 0; i < array.length; i++) { if (action(array[i])) conditional = true; } return conditional; } console.log(every([NaN, NaN, NaN], isNaN)); console.log(every([NaN, NaN, 4], isNaN)); console.log(some([NaN, 3, 4], isNaN)); console.log(some([2, 3, 4], isNaN));
// Arrays also come with the standard methods every and some. Both take a predicate function that, when called with an array element as argument, returns true or false. Just like && returns a true value only when the expressions on both sides are true, every returns true only when the predicate returns true for all elements of the array. Similarly, some returns true as soon as the predicate returns true for any of the elements. They do not process more elements than necessary—for example, if some finds that the predicate holds for the first element of the array, it will not look at the values after that. // Write two functions, every and some, that behave like these methods, except that they take the array as their first argument rather than being a method. function every(array, action) { for (let i = 0; i < array.length; i++) { if (!action(array[i])) return false; } return true; } function some(array, action) { for (let i = 0; i < array.length; i++) { if (action(array[i])) return true; } return false; } console.log(every([NaN, NaN, NaN], isNaN)); console.log(every([NaN, NaN, 4], isNaN)); console.log(some([NaN, 3, 4], isNaN)); console.log(some([2, 3, 4], isNaN));
Enable every/some methods to return early to prevent iterating over entire array
Enable every/some methods to return early to prevent iterating over entire array
JavaScript
mit
OperationCode/eloquent-js
35ead74f1fcb0b20d83be28cc9e187cdfe115373
servers/index.js
servers/index.js
require('coffee-script').register(); var argv = require('minimist')(process.argv); // require('./lib/source-server') module.exports = require('./lib/server');
require('coffee-script').register(); // require('./lib/source-server') module.exports = require('./lib/server');
Remove unused command line options parsing code
Remove unused command line options parsing code Signed-off-by: Sonmez Kartal <d2d15c3d37396a5f2a09f8b42cf5f27d43a3fbde@koding.com>
JavaScript
agpl-3.0
usirin/koding,gokmen/koding,acbodine/koding,alex-ionochkin/koding,mertaytore/koding,kwagdy/koding-1,kwagdy/koding-1,gokmen/koding,jack89129/koding,szkl/koding,drewsetski/koding,andrewjcasal/koding,szkl/koding,usirin/koding,rjeczalik/koding,koding/koding,drewsetski/koding,jack89129/koding,kwagdy/koding-1,rjeczalik/koding,andrewjcasal/koding,usirin/koding,acbodine/koding,sinan/koding,szkl/koding,kwagdy/koding-1,sinan/koding,kwagdy/koding-1,andrewjcasal/koding,mertaytore/koding,koding/koding,szkl/koding,sinan/koding,szkl/koding,rjeczalik/koding,koding/koding,drewsetski/koding,cihangir/koding,kwagdy/koding-1,jack89129/koding,mertaytore/koding,usirin/koding,usirin/koding,koding/koding,sinan/koding,szkl/koding,jack89129/koding,kwagdy/koding-1,sinan/koding,sinan/koding,alex-ionochkin/koding,andrewjcasal/koding,andrewjcasal/koding,acbodine/koding,drewsetski/koding,alex-ionochkin/koding,mertaytore/koding,drewsetski/koding,andrewjcasal/koding,jack89129/koding,rjeczalik/koding,alex-ionochkin/koding,usirin/koding,cihangir/koding,acbodine/koding,gokmen/koding,jack89129/koding,drewsetski/koding,koding/koding,jack89129/koding,usirin/koding,andrewjcasal/koding,acbodine/koding,cihangir/koding,koding/koding,gokmen/koding,sinan/koding,cihangir/koding,cihangir/koding,mertaytore/koding,mertaytore/koding,szkl/koding,alex-ionochkin/koding,szkl/koding,drewsetski/koding,gokmen/koding,koding/koding,jack89129/koding,drewsetski/koding,cihangir/koding,cihangir/koding,acbodine/koding,kwagdy/koding-1,gokmen/koding,alex-ionochkin/koding,gokmen/koding,rjeczalik/koding,andrewjcasal/koding,sinan/koding,mertaytore/koding,gokmen/koding,alex-ionochkin/koding,rjeczalik/koding,usirin/koding,acbodine/koding,cihangir/koding,acbodine/koding,koding/koding,mertaytore/koding,rjeczalik/koding,rjeczalik/koding,alex-ionochkin/koding
59ae7095d382380d0a14871a1a571fb7c99b31f6
examples/hello-world/app.js
examples/hello-world/app.js
var app = module.exports = require('appjs').createApp({CachePath: '/Users/dbartlett/.cache1'}); app.serveFilesFrom(__dirname + '/content'); var window = app.createWindow({ width : 640, height : 460, icons : __dirname + '/content/icons' }); window.on('create', function(){ console.log("Window Created"); window.frame.show(); window.frame.center(); }); window.on('ready', function(){ console.log("Window Ready"); window.require = require; window.process = process; window.module = module; function F12(e){ return e.keyIdentifier === 'F12' } function Command_Option_J(e){ return e.keyCode === 74 && e.metaKey && e.altKey } window.addEventListener('keydown', function(e){ if (F12(e) || Command_Option_J(e)) { window.frame.openDevTools(); } }); }); window.on('close', function(){ console.log("Window Closed"); });
var app = module.exports = require('appjs').createApp(); app.serveFilesFrom(__dirname + '/content'); var window = app.createWindow({ width : 640, height : 460, icons : __dirname + '/content/icons' }); window.on('create', function(){ console.log("Window Created"); window.frame.show(); window.frame.center(); }); window.on('ready', function(){ console.log("Window Ready"); window.require = require; window.process = process; window.module = module; function F12(e){ return e.keyIdentifier === 'F12' } function Command_Option_J(e){ return e.keyCode === 74 && e.metaKey && e.altKey } window.addEventListener('keydown', function(e){ if (F12(e) || Command_Option_J(e)) { window.frame.openDevTools(); } }); }); window.on('close', function(){ console.log("Window Closed"); });
Remove testing CachePath from example.
Remove testing CachePath from example.
JavaScript
mit
tempbottle/appjs,SaravananRajaraman/appjs,yuhangwang/appjs,appjs/appjs,appjs/appjs,imshibaji/appjs,tempbottle/appjs,yuhangwang/appjs,modulexcite/appjs,yuhangwang/appjs,SaravananRajaraman/appjs,eric-seekas/appjs,eric-seekas/appjs,eric-seekas/appjs,SaravananRajaraman/appjs,appjs/appjs,SaravananRajaraman/appjs,modulexcite/appjs,eric-seekas/appjs,tempbottle/appjs,SaravananRajaraman/appjs,tempbottle/appjs,SaravananRajaraman/appjs,imshibaji/appjs,yuhangwang/appjs,appjs/appjs,imshibaji/appjs,modulexcite/appjs,imshibaji/appjs,modulexcite/appjs
dd6f17e4f57e799a6200dec3f339f5ccba75de8d
webpack.config.js
webpack.config.js
var webpack = require('webpack'); var BrowserSyncPlugin = require('browser-sync-webpack-plugin'); module.exports = { context: __dirname, entry: './src/whoami.js', output: { path: './dist', filename: 'whoami.min.js', libraryTarget: 'var', library: 'whoami' }, module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ } ] }, plugins: [ new BrowserSyncPlugin({ host: 'localhost', port: 3000, server: { baseDir: ['dist'] } }), new webpack.optimize.UglifyJsPlugin({ minimize: true }) ], resolve: { extensions: ['', '.js'] } }
var webpack = require('webpack'); var BrowserSyncPlugin = require('browser-sync-webpack-plugin'); module.exports = { context: __dirname, entry: './src/whoami.js', output: { path: './dist', filename: 'whoami.min.js', libraryTarget: 'var', library: 'whoami' }, module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ } ] }, plugins: [ new BrowserSyncPlugin({ host: 'localhost', port: 3000, files: 'dist/*.*', server: { baseDir: ['dist'] } }), new webpack.optimize.UglifyJsPlugin({ minimize: true }) ], resolve: { extensions: ['', '.js'] } }
Watch dist files on browsersync
Watch dist files on browsersync
JavaScript
mit
andersonba/whoami.js
1ab999034c53389d359ab2161492a70e82c1ab47
src/wirecloud/fiware/static/js/WirecloudAPI/NGSIAPI.js
src/wirecloud/fiware/static/js/WirecloudAPI/NGSIAPI.js
(function () { "use strict"; var key, manager = window.parent.NGSIManager, NGSIAPI = {}; NGSIAPI.Connection = function Connection(url, options) { manager.Connection.call(this, 'operator', MashupPlatform.operator.id, url, options); }; NGSIAPI.Connection.prototype = window.parent.NGSIManager.Connection.prototype; Object.freeze(NGSIAPI); window.NGSI = NGSIAPI; })();
(function () { "use strict"; var key, manager = window.parent.NGSIManager, NGSIAPI = {}; if (MashupPlatform.operator != null) { NGSIAPI.Connection = function Connection(url, options) { manager.Connection.call(this, 'operator', MashupPlatform.operator.id, url, options); }; } else if (MashupPlatform.widget != null) { NGSIAPI.Connection = function Connection(url, options) { manager.Connection.call(this, 'widget', MashupPlatform.widget.id, url, options); }; } else { throw new Error('Unknown resource type'); } NGSIAPI.Connection.prototype = window.parent.NGSIManager.Connection.prototype; Object.freeze(NGSIAPI); window.NGSI = NGSIAPI; })();
Fix bug: export NGSI API also for widgets
Fix bug: export NGSI API also for widgets
JavaScript
agpl-3.0
jpajuelo/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud
1dcc6eab08d4df0e01427402503c5e26808e58ca
test/utils/to-date-time-in-time-zone.js
test/utils/to-date-time-in-time-zone.js
'use strict'; module.exports = function (t, a) { var mayanEndOfTheWorld = new Date(2012, 11, 21, 1, 1); a.deep(t(mayanEndOfTheWorld, 'America/Guatemala').valueOf(), new Date(2012, 11, 20, 18, 1).valueOf()); a.deep(t(mayanEndOfTheWorld, 'Europe/Warsaw').valueOf(), new Date(2012, 11, 21, 1, 1).valueOf()); };
'use strict'; module.exports = function (t, a) { var mayanEndOfTheWorld = new Date(Date.UTC(2012, 11, 21, 1, 1)); a.deep(t(mayanEndOfTheWorld, 'America/Guatemala').valueOf(), new Date(2012, 11, 20, 19, 1).valueOf()); a.deep(t(mayanEndOfTheWorld, 'Europe/Warsaw').valueOf(), new Date(2012, 11, 21, 2, 1).valueOf()); };
Fix test so is timezone independent
Fix test so is timezone independent
JavaScript
mit
egovernment/eregistrations,egovernment/eregistrations,egovernment/eregistrations
10c19dabd1178de4f561327e348c3c114b54ea67
Web/Application.js
Web/Application.js
var express = require('express'); var app = express(); var CurrentUser = require('../Architecture/CurrentUser').CurrentUser; var WebService = require('../Architecture/WebService').WebService; var MongoAdapter = require('../Adapters/Mongo').MongoAdapter; var RedisAdapter = require('../Adapters/Redis').RedisAdapter; var webServiceInit = new WebService(new CurrentUser()); var runService = webServiceInit.runWrapper(); // Database adapters. var mongodb = new MongoAdapter(); var redis = new RedisAdapter(); app.use(mongodb.connect()); app.use(redis.connect()); app.use(function (req, res, next) { // Add things to dependencies in everything service. webServiceInit.addDependency('mongo', mongodb); webServiceInit.addDependency('redis', redis); next(); }); app.use(function (req, res, next) { webServiceInit.runRef = webServiceInit.run.bind(webServiceInit); next(); }); app.use(express.static('Resources')); // ### Routing ### app.get('/login', runService('loginGet', [0, 1, 2, 3], { param1: 'value1', param2: 'value2' })); app.get('/secret', runService('secretGet', [2, 3], { param1: 'value1', param2: 'value2' })); app.listen(process.argv[2]); console.log('Server listening on port ' + process.argv[2] + '.');
var express = require('express'); var app = express(); var CurrentUser = require('../Architecture/CurrentUser').CurrentUser; var WebService = require('../Architecture/WebService').WebService; var MongoAdapter = require('../Adapters/Mongo').MongoAdapter; var RedisAdapter = require('../Adapters/Redis').RedisAdapter; var webServiceInit = new WebService(new CurrentUser()); var runService = webServiceInit.runWrapper(); // Database adapters. var mongodb = new MongoAdapter(); var redis = new RedisAdapter(); app.use(mongodb.connect()); app.use(redis.connect()); app.use(function (req, res, next) { // Add things to dependencies in everything service. webServiceInit.addDependency('mongo', mongodb); webServiceInit.addDependency('redis', redis); next(); }); app.use(function (req, res, next) { webServiceInit.runRef = webServiceInit.run.bind(webServiceInit); next(); }); app.use(express.static('Resources')); // ### Routing ### app.get('/login', runService('loginGet', [0, 1, 2, 3])); app.get('/secret', runService('secretGet', [2, 3], { param1: 'value1', param2: 'value2' })); app.listen(process.argv[2]); console.log('Server listening on port ' + process.argv[2] + '.');
Remove params from login route.
Remove params from login route.
JavaScript
mit
rootsher/server-side-portal-framework
61d51a215bed8e447a528c8a65a9d2ba92453790
js/memberlist.js
js/memberlist.js
//Memberlist JavaScript function hookUpMemberlistControls() { $("#orderBy,#order,#sex,#power").change(function(e) { refreshMemberlist(); }); $("#submitQuery").click(function() { refreshMemberlist(); }); refreshMemberlist(); } function refreshMemberlist(page) { var orderBy = document.getElementById("orderBy").value; var order = document.getElementById( "order").value; var sex = document.getElementById( "sex").value; var power = document.getElementById( "power").value; var query = document.getElementById( "query").value; if (typeof page == "undefined") page = 0; $.get("./?page=memberlist", { listing: true, dir: order, sort: orderBy, sex: sex, pow: power, from: page, query: query}, function(data) { $("#memberlist").html(data); }); } $(document).ready(function() { hookUpMemberlistControls(); });
//Memberlist JavaScript function hookUpMemberlistControls() { $("#orderBy,#order,#sex,#power").change(function(e) { refreshMemberlist(); }); $("#submitQuery").click(function() { refreshMemberlist(); }); refreshMemberlist(); } function refreshMemberlist(page) { var orderBy = $("#orderBy").val(); var order = $( "#order").val(); var sex = $( "#sex").val(); var power = $( "#power").val(); var query = $( "#query").val(); if (typeof page == "undefined") page = 0; $.get("./?page=memberlist", { listing: true, dir: order, sort: orderBy, sex: sex, pow: power, from: page, query: query}, function(data) { $("#memberlist").html(data); }); } $(document).ready(function() { hookUpMemberlistControls(); });
Use jQuery instead of document.getElementById.
Use jQuery instead of document.getElementById.
JavaScript
bsd-2-clause
Jceggbert5/ABXD,ABXD/ABXD,carlosfortes/ABXD,carlosfortes/ABXD,carlosfortes/ABXD,Jceggbert5/ABXD,Jceggbert5/ABXD,ABXD/ABXD,ABXD/ABXD
b6d411f8cd7a895394227ec6b1b3e226a69bb5e6
lib/chlg-init.js
lib/chlg-init.js
'use strict'; var fs = require('fs'); var program = require('commander'); program .option('-f, --file [filename]', 'Changelog filename', 'CHANGELOG.md') .parse(process.argv); function chlgInit(file, callback) { file = file || program.file; fs.stat(file, function (err) { if (!err || err.code !== 'ENOENT') { return callback(new Error('cannot create file ‘' + file + '’: File exists')); } fs.writeFile(file, [ '# Change Log', 'All notable changes to this project will be documented in this file.', 'This project adheres to [Semantic Versioning](http://semver.org/).', '', '## [Unreleased][unreleased]', '' ].join('\n'), {encoding: 'utf8'}, function (error) { return callback(error ? new Error('cannot create file ‘' + file + '’: ' + error.message) : null); }); }); } if (require.main === module) { chlgInit(function (err) { if (err) { console.error('chlg-init: ' + err.message); process.exit(1); } }); } else { module.exports = chlgInit; }
'use strict'; var fs = require('fs'); var program = require('commander'); program .option('-f, --file [filename]', 'Changelog filename', 'CHANGELOG.md') .parse(process.argv); function chlgInit(file, callback) { file = file || program.file; fs.stat(file, function (err) { if (!err || err.code !== 'ENOENT') { return callback(new Error('cannot create file ‘' + file + '’: File exists')); } fs.writeFile(file, [ '# Change Log', 'All notable changes to this project will be documented in this file.', 'This project adheres to [Semantic Versioning](http://semver.org/).', '', '## [Unreleased][unreleased]', '' ].join('\n'), {encoding: 'utf8'}, function (error) { return callback(error ? new Error('cannot create file ‘' + file + '’: ' + error.message) : null); }); }); } if (require.main === module) { chlgInit(program.file, function (err) { if (err) { console.error('chlg-init: ' + err.message); process.exit(1); } }); } else { module.exports = chlgInit; }
Fix chld-show command line usage
Fix chld-show command line usage
JavaScript
mit
fldubois/changelog-cli
599c023798d96766d4552ad3619b95f5e84f8ed3
lib/form-data.js
lib/form-data.js
/*global window*/ var isBrowser = typeof window !== 'undefined' && typeof window.FormData !== 'undefined'; // use native FormData in a browser var FD = isBrowser? window.FormData : require('form-data'); module.exports = FormData; module.exports.isBrowser = isBrowser; function FormData() { this.fd = new FD(); } FormData.prototype.append = function (name, data, opt) { if (isBrowser) { if (opt && opt.filename) { return this.fd.append(name, data, opt.filename); } return this.fd.append(name, data); } return this.fd.append.apply(this.fd, arguments); }; FormData.prototype.pipe = function (to) { if (isBrowser && to.end) { return to.end(this.fd); } return this.fd.pipe(to); }; FormData.prototype.getHeaders = function () { if (isBrowser) { return {}; } return this.fd.getHeaders(); };
/*global window*/ var isBrowser = typeof window !== 'undefined' && typeof window.FormData !== 'undefined'; // use native FormData in a browser var FD = isBrowser? window.FormData : require('form-data'); module.exports = FormData; module.exports.isBrowser = isBrowser; function FormData() { this.fd = new FD(); } FormData.prototype.append = function (name, data, opt) { if (isBrowser) { // data must be converted to Blob if it's an arraybuffer if (data instanceof window.ArrayBuffer) { data = new window.Blob([ data ]); } if (opt && opt.filename) { return this.fd.append(name, data, opt.filename); } return this.fd.append(name, data); } return this.fd.append.apply(this.fd, arguments); }; FormData.prototype.pipe = function (to) { if (isBrowser && to.end) { return to.end(this.fd); } return this.fd.pipe(to); }; FormData.prototype.getHeaders = function () { if (isBrowser) { return {}; } return this.fd.getHeaders(); };
Convert ArrayBuffer to Blob in FormData
Convert ArrayBuffer to Blob in FormData
JavaScript
mit
lakenen/node-box-view
daa7c07dc6eaaad441c35c9da540ef4863f2bee3
client/views/activities/latest/latestByType.js
client/views/activities/latest/latestByType.js
Template.latestActivitiesByType.created = function () { // Create 'instance' variable for use througout template logic var instance = this; // Subscribe to all activity types instance.subscribe('allActivityTypes'); // Create variable to hold activity type selection instance.activityTypeSelection = new ReactiveVar(); }; Template.latestActivitiesByType.helpers({ 'activityTypeOptions': function () { // Get all activity types activityTypes = ActivityTypes.find().fetch(); return activityTypes; } });
Template.latestActivitiesByType.created = function () { // Create 'instance' variable for use througout template logic var instance = this; // Subscribe to all activity types instance.subscribe('allActivityTypes'); // Create variable to hold activity type selection instance.activityTypeSelection = new ReactiveVar(); }; Template.latestActivitiesByType.helpers({ 'activityTypeOptions': function () { // Get all activity types activityTypes = ActivityTypes.find().fetch(); return activityTypes; } }); Template.latestActivitiesByType.events({ 'change #activity-type-select': function (event, template) { // Create instance variable for consistency var instance = Template.instance(); var selectedActivityType = event.target.value; instance.activityTypeSelection.set(selectedActivityType); } });
Change activity type selection on change event
Change activity type selection on change event
JavaScript
agpl-3.0
brylie/juhani-wellbeing,brylie/juhani-wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,GeriLife/wellbeing,GeriLife/wellbeing
4b765f32e63599995bef123d47fd9ddd39bdb235
pages/books/read.js
pages/books/read.js
// @flow /** * Part of GDL gdl-frontend. * Copyright (C) 2017 GDL * * See LICENSE */ import * as React from 'react'; import { fetchBook } from '../../fetch'; import type { BookDetails, Context } from '../../types'; import defaultPage from '../../hocs/defaultPage'; import Head from '../../components/Head'; import Reader from '../../components/Reader'; type Props = { book: BookDetails, url: { query: { chapter?: string } } }; class Read extends React.Component<Props> { static async getInitialProps({ query }: Context) { const bookRes = await fetchBook(query.id, query.lang); if (!bookRes.isOk) { return { statusCode: bookRes.statusCode }; } const book = bookRes.data; // Make sure the chapters are sorted by the chapter numbers // Cause further down we rely on the array indexes book.chapters.sort((a, b) => a.seqNo - b.seqNo); return { book }; } render() { let { book, url } = this.props; return ( <React.Fragment> <Head title={book.title} isBookType description={book.description} imageUrl={book.coverPhoto ? book.coverPhoto.large : null} /> <Reader book={book} initialChapter={url.query.chapter} /> </React.Fragment> ); } } export default defaultPage(Read);
// @flow /** * Part of GDL gdl-frontend. * Copyright (C) 2017 GDL * * See LICENSE */ import * as React from 'react'; import { fetchBook } from '../../fetch'; import type { BookDetails, Context } from '../../types'; import defaultPage from '../../hocs/defaultPage'; import errorPage from '../../hocs/errorPage'; import Head from '../../components/Head'; import Reader from '../../components/Reader'; type Props = { book: BookDetails, url: { query: { chapter?: string } } }; class Read extends React.Component<Props> { static async getInitialProps({ query }: Context) { const bookRes = await fetchBook(query.id, query.lang); if (!bookRes.isOk) { return { statusCode: bookRes.statusCode }; } const book = bookRes.data; // Make sure the chapters are sorted by the chapter numbers // Cause further down we rely on the array indexes book.chapters.sort((a, b) => a.seqNo - b.seqNo); return { book }; } render() { let { book, url } = this.props; return ( <React.Fragment> <Head title={book.title} isBookType description={book.description} imageUrl={book.coverPhoto ? book.coverPhoto.large : null} /> <Reader book={book} initialChapter={url.query.chapter} /> </React.Fragment> ); } } export default defaultPage(errorPage(Read));
Add error handling to Read book page
Add error handling to Read book page
JavaScript
apache-2.0
GlobalDigitalLibraryio/gdl-frontend,GlobalDigitalLibraryio/gdl-frontend
56583e9cb09dfbcea6da93af4d10268b51b232e9
js/casper.js
js/casper.js
var fs = require('fs'); var links; function getLinks() { // Scrape the links from primary nav of the website var links = document.querySelectorAll('.nav-link.t-nav-link'); return Array.prototype.map.call(links, function (e) { return e.getAttribute('href') }); } casper.start('http://192.168.13.37/index.php', function() { fs.write('tests/validation/html_output/index.html', this.getPageContent(), 'w'); }); casper.then(function () { links = this.evaluate(getLinks); for(var i in links) { console.log(i,' Outer:', links[i]); casper.start(links[i], function() { console.log(i, ' Inner:', links[i]); fs.write('tests/validation/html_output/page-' + i + '.html', this.getPageContent(), 'w'); }); } }); casper.run(function() { this.exit(); })
var fs = require('fs'); var links; function getLinks() { var links = document.querySelectorAll('.nav-link.t-nav-link'); return Array.prototype.map.call(links, function (e) { return e.getAttribute('href') }); } casper.start('http://192.168.13.37/index.php', function() { fs.write('tests/validation/html_output/homepage.html', this.getPageContent(), 'w'); }); casper.then(function () { var links = this.evaluate(getLinks); var current = 1; var end = links.length; for (;current < end;) { //console.log(current,' Outer:', current); (function(cntr) { casper.thenOpen(links[cntr], function() { console.log(cntr, ' Inner:', links[cntr]); fs.write('tests/validation/html_output/_' + cntr + '.html', this.getPageContent(), 'w'); }); })(current); current++; } }); casper.run(function() { this.exit(); })
Fix For Loop to Iterate Every Link in Primary Nav
Fix For Loop to Iterate Every Link in Primary Nav
JavaScript
mit
jadu/pulsar,jadu/pulsar,jadu/pulsar
626e52c243ee1e82988d4650cbb22d3d8c304ed6
js/modals.js
js/modals.js
/* ======================================================================== * Ratchet: modals.js v2.0.2 * http://goratchet.com/components#modals * ======================================================================== * Copyright 2015 Connor Sears * Licensed under MIT (https://github.com/twbs/ratchet/blob/master/LICENSE) * ======================================================================== */ !(function () { 'use strict'; var findModals = function (target) { var i; var modals = document.querySelectorAll('a'); for (; target && target !== document; target = target.parentNode) { for (i = modals.length; i--;) { if (modals[i] === target) { return target; } } } }; var getModal = function (event) { var modalToggle = findModals(event.target); if (modalToggle && modalToggle.hash) { return document.querySelector(modalToggle.hash); } }; window.addEventListener('touchend', function (event) { var modal = getModal(event); if (modal) { if (modal && modal.classList.contains('modal')) { modal.classList.toggle('active'); } event.preventDefault(); // prevents rewriting url (apps can still use hash values in url) } }); }());
/* ======================================================================== * Ratchet: modals.js v2.0.2 * http://goratchet.com/components#modals * ======================================================================== * Copyright 2015 Connor Sears * Licensed under MIT (https://github.com/twbs/ratchet/blob/master/LICENSE) * ======================================================================== */ !(function () { 'use strict'; var eventModalOpen = new CustomEvent('modalOpen', { bubbles: true, cancelable: true }); var eventModalClose = new CustomEvent('modalClose', { bubbles: true, cancelable: true }); var findModals = function (target) { var i; var modals = document.querySelectorAll('a'); for (; target && target !== document; target = target.parentNode) { for (i = modals.length; i--;) { if (modals[i] === target) { return target; } } } }; var getModal = function (event) { var modalToggle = findModals(event.target); if (modalToggle && modalToggle.hash) { return document.querySelector(modalToggle.hash); } }; window.addEventListener('touchend', function (event) { var modal = getModal(event); if (modal && modal.classList.contains('modal')) { var eventToDispatch = eventModalOpen; if (modal.classList.contains('active')) { eventToDispatch = eventModalClose; } modal.dispatchEvent(eventToDispatch); modal.classList.toggle('active'); } event.preventDefault(); // prevents rewriting url (apps can still use hash values in url) }); }());
Create modalOpen and modalClose events.
Create modalOpen and modalClose events.
JavaScript
mit
jackyzonewen/ratchet,hashg/ratchet,AndBicScadMedia/ratchet,mazong1123/ratchet-pro,Joozo/ratchet,calvintychan/ratchet,asonni/ratchet,aisakeniudun/ratchet,youprofit/ratchet,Diaosir/ratchet,wallynm/ratchet,vebin/ratchet,mbowie5/playground2,arnoo/ratchet,AladdinSonni/ratchet,youzaiyouzai666/ratchet,ctkjose/ratchet-1,liangxiaojuan/ratchet,Samda/ratchet,tranc99/ratchet,guohuadeng/ratchet,jamesrom/ratchet,Artea/ratchet,twbs/ratchet,isathish/ratchet,cslgjiangjinjian/ratchet,twbs/ratchet,kkirsche/ratchet,Holism/ratchet,coderstudy/ratchet,mazong1123/ratchet-pro,jimjin/ratchet,leplatrem/ratchet
65a9b66c2d9f30bad14a06b0646737ec86799f39
src/matchNode.js
src/matchNode.js
/* * Copyright (c) 2015-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. * */ 'use strict'; var hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); /** * Checks whether needle is a strict subset of haystack. * * @param {Object} haystack The object to test * @param {Object|Function} needle The properties to look for in test * @return {bool} */ function matchNode(haystack, needle) { if (typeof needle === 'function') { return needle(haystack); } var props = Object.keys(needle); return props.every(function(prop) { if (!hasOwn(haystack, prop)) { return false; } if (haystack[prop] && typeof haystack[prop] === 'object' && typeof needle[prop] === 'object') { return matchNode(haystack[prop], needle[prop]); } return haystack[prop] === needle[prop]; }); } module.exports = matchNode;
/* * Copyright (c) 2015-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. * */ 'use strict'; var hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); /** * Checks whether needle is a strict subset of haystack. * * @param {Object} haystack The object to test * @param {Object|Function} needle The properties to look for in test * @return {bool} */ function matchNode(haystack, needle) { if (typeof needle === 'function') { return needle(haystack); } var props = Object.keys(needle); return props.every(function(prop) { if (!hasOwn(haystack, prop)) { return false; } if (haystack[prop] && needle[prop] && typeof haystack[prop] === 'object' && typeof needle[prop] === 'object') { return matchNode(haystack[prop], needle[prop]); } return haystack[prop] === needle[prop]; }); } module.exports = matchNode;
Fix fatal when matching null values in needle
Fix fatal when matching null values in needle
JavaScript
mit
facebook/jscodeshift,fkling/jscodeshift
a69af39c3d2f4b1ec80a08bd6abe70e2a431b083
packages/staplegun/test/fixtures/good-plugins/threepack/three.js
packages/staplegun/test/fixtures/good-plugins/threepack/three.js
const R = require('ramda') export default async () => { console.log('1...2...3...') return R.range(1, 4) // return [1, 2, 3] }
const R = require('ramda') export default async () => { return R.range(1, 4) }
Remove the console log from a fixture.
Remove the console log from a fixture.
JavaScript
mit
infinitered/gluegun,infinitered/gluegun,infinitered/gluegun
eef93ee29ecec1f150dc8af0e9277709a39daaed
dotjs.js
dotjs.js
var hostname = location.hostname.replace(/^www\./, ''); var style = document.createElement('link'); style.rel = 'stylesheet'; style.href = chrome.extension.getURL('styles/' + hostname + '.css'); document.documentElement.insertBefore(style); var defaultStyle = document.createElement('link'); defaultStyle.rel = 'stylesheet'; defaultStyle.href = chrome.extension.getURL('styles/default.css'); document.documentElement.insertBefore(defaultStyle); var script = document.createElement('script'); script.src = chrome.extension.getURL('scripts/' + hostname + '.js'); document.documentElement.insertBefore(script); var defaultScript = document.createElement('script'); defaultScript.src = chrome.extension.getURL('scripts/default.js'); document.documentElement.insertBefore(defaultScript);
var hostname = location.hostname.replace(/^www\./, ''); var style = document.createElement('link'); style.rel = 'stylesheet'; style.href = chrome.extension.getURL('styles/' + hostname + '.css'); document.documentElement.appendChild(style); var defaultStyle = document.createElement('link'); defaultStyle.rel = 'stylesheet'; defaultStyle.href = chrome.extension.getURL('styles/default.css'); document.documentElement.appendChild(defaultStyle); var script = document.createElement('script'); script.src = chrome.extension.getURL('scripts/' + hostname + '.js'); document.documentElement.appendChild(script); var defaultScript = document.createElement('script'); defaultScript.src = chrome.extension.getURL('scripts/default.js'); document.documentElement.appendChild(defaultScript);
Use appendChild instead of insertBefore for a small perfomance boost
Use appendChild instead of insertBefore for a small perfomance boost - Fixes #11
JavaScript
mit
p3lim/dotjs-universal,p3lim/dotjs-universal
d0b8c473fa886a208dcdfa4fd8bc97fc4c1b6770
lib/graph.js
lib/graph.js
import _ from 'lodash'; import {Graph, alg} from 'graphlib'; const dijkstra = alg.dijkstra; export function setupGraph(relationships) { let graph = new Graph({ directed: true }); _.each(relationships, function (relationship) { graph.setEdge(relationship.from, relationship.to, relationship.method); }); return graph; } export function getPath(graph, source, destination, path) { let map = dijkstra(graph, source); let predecessor = map[destination].predecessor; if (_.isEqual(predecessor, source)) { path.push(graph.edge(predecessor, destination)); return path.reverse(); } else { path.push(graph.edge(predecessor, destination)); return getPath(graph, source, predecessor, path); } }
import _ from 'lodash'; import {Graph, alg} from 'graphlib'; _.memoize.Cache = WeakMap; let dijkstra = _.memoize(alg.dijkstra); export function setupGraph(pairs) { let graph = new Graph({ directed: true }); _.each(pairs, ({from, to, method}) => graph.setEdge(from, to, method)); return graph; } export function getPath(graph, source, destination, path) { let map = dijkstra(graph, source); let predecessor = map[destination].predecessor; if (_.isEqual(predecessor, source)) { path.push(graph.edge(predecessor, destination)); return path.reverse(); } else { path.push(graph.edge(predecessor, destination)); return getPath(graph, source, predecessor, path); } }
Use ES2015 destructuring and add memoization to dijkstra
Use ES2015 destructuring and add memoization to dijkstra
JavaScript
mit
siddharthkchatterjee/graph-resolver
b20135c356901cd16f8fd94f3ac05af4ab464005
lib/index.js
lib/index.js
import constant from './constant'; import freeze from './freeze'; import is from './is'; import _if from './if'; import ifElse from './ifElse'; import map from './map'; import omit from './omit'; import reject from './reject'; import update from './update'; import updateIn from './updateIn'; import withDefault from './withDefault'; import { _ } from './util/curry'; const u = update; u._ = _; u.constant = constant; u.if = _if; u.ifElse = ifElse; u.is = is; u.freeze = freeze; u.map = map; u.omit = omit; u.reject = reject; u.update = update; u.updateIn = updateIn; u.withDefault = withDefault; export default u;
import constant from './constant'; import freeze from './freeze'; import is from './is'; import _if from './if'; import ifElse from './ifElse'; import map from './map'; import omit from './omit'; import reject from './reject'; import update from './update'; import updateIn from './updateIn'; import withDefault from './withDefault'; import { _ } from './util/curry'; const u = update; u._ = _; u.constant = constant; u.if = _if; u.ifElse = ifElse; u.is = is; u.freeze = freeze; u.map = map; u.omit = omit; u.reject = reject; u.update = update; u.updateIn = updateIn; u.withDefault = withDefault; module.exports = u;
Allow updeep to be require()’d from CommonJS
Allow updeep to be require()’d from CommonJS
JavaScript
mit
substantial/updeep,substantial/updeep
f3735c9b214ea8bbe2cf3619409952fedb1eb7ac
lib/index.js
lib/index.js
'use strict'; var path = require('path'); var BinWrapper = require('bin-wrapper'); var pkg = require('../package.json'); var url = 'https://raw.githubusercontent.com/jihchi/giflossy-bin/v' + pkg.version + '/vendor/'; module.exports = new BinWrapper() .src(url + 'macos/giflossy', 'darwin') .src(url + 'linux/x86/giflossy', 'linux', 'x86') .src(url + 'linux/x64/giflossy', 'linux', 'x64') .src(url + 'freebsd/x86/giflossy', 'freebsd', 'x86') .src(url + 'freebsd/x64/giflossy', 'freebsd', 'x64') .src(url + 'win/x86/giflossy.exe', 'win32', 'x86') .src(url + 'win/x64/giflossy.exe', 'win32', 'x64') .dest(path.join(__dirname, '../vendor')) .use(process.platform === 'win32' ? 'giflossy.exe' : 'giflossy');
'use strict'; var path = require('path'); var BinWrapper = require('bin-wrapper'); var pkg = require('../package.json'); var url = 'https://raw.githubusercontent.com/jihchi/giflossy-bin/v' + pkg.version + '/vendor/'; module.exports = new BinWrapper() .src(url + 'macos/gifsicle', 'darwin') .src(url + 'linux/x86/gifsicle', 'linux', 'x86') .src(url + 'linux/x64/gifsicle', 'linux', 'x64') .src(url + 'freebsd/x86/gifsicle', 'freebsd', 'x86') .src(url + 'freebsd/x64/gifsicle', 'freebsd', 'x64') .src(url + 'win/x86/gifsicle.exe', 'win32', 'x86') .src(url + 'win/x64/gifsicle.exe', 'win32', 'x64') .dest(path.join(__dirname, '../vendor')) .use(process.platform === 'win32' ? 'gifsicle.exe' : 'gifsicle');
Rename binary filename to gifsicle
Rename binary filename to gifsicle
JavaScript
mit
jihchi/giflossy-bin
fec0c1ca4048c3590396cd5609cb3085e6c61bf5
lib/index.js
lib/index.js
'use strict'; var config = require('../config/configuration.js'); function htmlReplace(str) { return str.replace(/<\/?[a-z1-9]+(\s+[a-z]+=["'](.*)["'])*\/?>/g, ' ').replace(/ +/g, ' ').replace(/ ?\n ?/g, '\n').trim(); } module.exports = function(path, document, changes, finalCb) { if(document.data.html === undefined) { changes.data.html = document.metadata.text; } else if(document.metadata.text === undefined) { changes.metadata.text = htmlReplace(document.data.html); } changes.metadata.text = (changes.metadata.text) ? changes.metadata.text : document.metadata.text; if(document.data.html) { config.separators_html.some(function(separator) { var tmpHTML = document.data.html.split(separator)[0]; if(tmpHTML !== document.data.html) { changes.metadata.text = htmlReplace(tmpHTML); return true; } return false; }); } if(changes.metadata.text === document.metadata.text) { config.separators_text.some(function(separator) { var tmpText = changes.metadata.text.split(separator)[0]; if(tmpText !== changes.metadata.text) { changes.metadata.text = tmpText; return true; } return false; }); } finalCb(null, changes); };
'use strict'; var config = require('../config/configuration.js'); function htmlReplace(str) { return str.replace(/<\/?[^>]+\/?>/g, ' ').replace(/ +/g, ' ').replace(/ ?\n ?/g, '\n').trim(); } module.exports = function(path, document, changes, finalCb) { if(document.data.html === undefined) { changes.data.html = document.metadata.text; } else if(document.metadata.text === undefined) { changes.metadata.text = htmlReplace(document.data.html); } changes.metadata.text = (changes.metadata.text) ? changes.metadata.text : document.metadata.text; if(document.data.html) { config.separators_html.some(function(separator) { var tmpHTML = document.data.html.split(separator)[0]; if(tmpHTML !== document.data.html) { changes.metadata.text = htmlReplace(tmpHTML); return true; } return false; }); } if(changes.metadata.text === document.metadata.text) { config.separators_text.some(function(separator) { var tmpText = changes.metadata.text.split(separator)[0]; if(tmpText !== changes.metadata.text) { changes.metadata.text = tmpText; return true; } return false; }); } finalCb(null, changes); };
Update regexp for HTML strip
Update regexp for HTML strip
JavaScript
mit
AnyFetch/embedmail-hydrater.anyfetch.com
7ca1d708a9a9c22e596e9c4a64db74115994d54a
koans/AboutExpects.js
koans/AboutExpects.js
describe("About Expects", function() { //We shall contemplate truth by testing reality, via spec expectations. it("should expect true", function() { expect(false).toBeTruthy(); //This should be true }); //To understand reality, we must compare our expectations against reality. it("should expect equality", function () { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; expect(actualValue === expectedValue).toBeTruthy(); }); //Some ways of asserting equality are better than others. it("should assert equality a better way", function () { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; // toEqual() compares using common sense equality. expect(actualValue).toEqual(expectedValue); }); //Sometimes you need to be really exact about what you "type". it("should assert equality with ===", function () { var expectedValue = FILL_ME_IN; var actualValue = (1 + 1).toString(); // toBe() will always use === to compare. expect(actualValue).toBe(expectedValue); }); //Sometimes we will ask you to fill in the values. it("should have filled in values", function () { expect(1 + 1).toEqual(FILL_ME_IN); }); });
describe("About Expects", function() { // We shall contemplate truth by testing reality, via spec expectations. it("should expect true", function() { expect(false).toBeTruthy(); // This should be true }); // To understand reality, we must compare our expectations against reality. it("should expect equality", function () { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; expect(actualValue === expectedValue).toBeTruthy(); }); // Some ways of asserting equality are better than others. it("should assert equality a better way", function () { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; // toEqual() compares using common sense equality. expect(actualValue).toEqual(expectedValue); }); // Sometimes you need to be precise about what you "type". it("should assert equality with ===", function () { var expectedValue = FILL_ME_IN; var actualValue = (1 + 1).toString(); // toBe() will always use === to compare. expect(actualValue).toBe(expectedValue); }); // Sometimes we will ask you to fill in the values. it("should have filled in values", function () { expect(1 + 1).toEqual(FILL_ME_IN); }); });
Correct spacing and language in comments
Correct spacing and language in comments
JavaScript
mit
DhiMalo/javascript-koans,GMatias93/javascript-koans,JosephSun/javascript-koans,existenzial/javascript-koans,GMatias93/javascript-koans,darrylnu/javascript-koans,JosephSun/javascript-koans,DhiMalo/javascript-koans,existenzial/javascript-koans,GMatias93/javascript-koans,darrylnu/javascript-koans,darrylnu/javascript-koans,JosephSun/javascript-koans,existenzial/javascript-koans,DhiMalo/javascript-koans
6eea14a4d3291b3d6e1088a6cd4eacda056ce56a
tests/dummy/mirage/factories/pledge.js
tests/dummy/mirage/factories/pledge.js
import { Factory, faker } from 'ember-cli-mirage'; export default Factory.extend({ fund: () => faker.random.arrayElement(["WNYC", "WQXR", "Radiolab"]), orderPrice: () => faker.random.arrayElement([60, 72, 120, 12, 90, 100]), orderDate: faker.date.past, orderCode: () => faker.random.arrayElement([1234567,2345678,3456789]), orderType: () => faker.random.arrayElement(["onetime", "sustainer"]), orderKey: () => faker.random.uuid(), premium: () => faker.random.arrayElement(['Brian Lehrer Animated Series', 'BL Mug', 'WNYC Hoodie', '']), creditCardType: 'VISA', creditCardLast4Digits: '0302', isActiveMember: faker.random.boolean, isSustainer: faker.random.boolean, });
import { Factory, faker } from 'ember-cli-mirage'; export default Factory.extend({ fund: () => faker.random.arrayElement(["WNYC", "WQXR", "Radiolab", "J.Schwartz"]), orderPrice: () => faker.random.arrayElement([60, 72, 120, 12, 90, 100]), orderDate: faker.date.past, orderCode: () => faker.random.arrayElement([1234567,2345678,3456789]), orderType: () => faker.random.arrayElement(["onetime", "sustainer"]), orderKey: () => faker.random.uuid(), premium: () => faker.random.arrayElement(['Brian Lehrer Animated Series', 'BL Mug', 'WNYC Hoodie', '']), creditCardType: 'VISA', creditCardLast4Digits: '0302', isActiveMember: faker.random.boolean, isSustainer: faker.random.boolean, });
Add Jonathan Schwartz as fund in mirage factory
Add Jonathan Schwartz as fund in mirage factory
JavaScript
mit
nypublicradio/nypr-account-settings,nypublicradio/nypr-account-settings
c19fc02c3ea90da940bb39a9f59f0c9b06632175
lib/index.js
lib/index.js
var _ = require('lodash'); var path = require('path'); var exec = require('child_process').exec; var LOG_TYPES = [ "ERROR", "WARNING" ]; module.exports = function(filepath, options, callback) { if (!callback) { callback = options; options = {}; } options = _.defaults(options || {}, { epubcheck: "epubcheck" }); filepath = path.resolve(process.cwd(), filepath); var command = options.epubcheck+" "+filepath+" -q"; exec(command, function (error, stdout, stderr) { var output = stderr.toString(); var lines = stderr.split("\n"); error = null; lines = _.chain(lines) .map(function(line) { var parts = line.split(":"); if (!_.contains(LOG_TYPES, parts[0])) return null; var type = parts[0].toLowerCase(); var content = parts.slice(1).join(":"); if (type == "error") { error = new Error(content); } return { 'type': type, 'content': content }; }) .compact() .value(); callback(error, { messages: lines }); }); };
var _ = require('lodash'); var path = require('path'); var exec = require('child_process').exec; var LOG_TYPES = [ "ERROR", "WARNING" ]; module.exports = function(filepath, options, callback) { if (!callback) { callback = options; options = {}; } options = _.defaults(options || {}, { epubcheck: "epubcheck" }); filepath = path.resolve(process.cwd(), filepath); var command = options.epubcheck+" "+filepath+" -q"; exec(command, function (error, stdout, stderr) { var output = stderr.toString(); var lines = stderr.split("\n"); var err = null; lines = _.chain(lines) .map(function(line) { var parts = line.split(":"); if (!_.contains(LOG_TYPES, parts[0])) return null; var type = parts[0].toLowerCase(); var content = parts.slice(1).join(":"); if (type == "error") { err = new Error(content); } return { 'type': type, 'content': content }; }) .compact() .value(); if (error && !err) err = error; callback(err, { messages: lines }); }); };
Handle correctly error from epubcheck
Handle correctly error from epubcheck
JavaScript
apache-2.0
GitbookIO/node-epubcheck
7fbdffa0bb2c82589c2d786f9fa16863780a63db
app/assets/javascripts/download-menu.js
app/assets/javascripts/download-menu.js
function show_download_menu() { $('#download-menu').slideDown(); setTimeout(hide_download_menu, 20000); $('#download-link').html('cancel'); } function hide_download_menu() { $('#download-menu').slideUp(); $('#download-link').html('download'); } function toggle_download_menu() { if ($('#download-link').html() === 'download') { show_download_menu(); } else { hide_download_menu(); } }
function show_download_menu() { $('#download-menu').slideDown({ duration: 200 }); setTimeout(hide_download_menu, 20000); $('#download-link').html('cancel'); } function hide_download_menu() { $('#download-menu').slideUp({ duration: 200 }); $('#download-link').html('download'); } function toggle_download_menu() { if ($('#download-link').html() === 'download') { show_download_menu(); } else { hide_download_menu(); } }
Speed up the download menu appear/disappear a bit
Speed up the download menu appear/disappear a bit
JavaScript
agpl-3.0
BatedUrGonnaDie/splits-io,BatedUrGonnaDie/splits-io,glacials/splits-io,BatedUrGonnaDie/splits-io,glacials/splits-io,glacials/splits-io,BatedUrGonnaDie/splits-io,glacials/splits-io
78a75ddd6de442e9e821a1bb09192d17635ff1b6
config/default.js
config/default.js
module.exports = { Urls: { vault_base_url: '', base_url: process.env.BASE_URL || process.env.HUBOT_ROOT_URL }, Strings: { sorry_dave: 'I\'m sorry %s, I\'m afraid I can\'t do that.' }, };
module.exports = { Urls: { vault_base_url: process.env.HUBOT_VAULT_URL, base_url: process.env.BASE_URL || process.env.HUBOT_ROOT_URL }, Strings: { sorry_dave: 'I\'m sorry %s, I\'m afraid I can\'t do that.' }, };
Add vault url config environment variable
Add vault url config environment variable
JavaScript
mit
uWhisp/hubot-db-heimdall,uWhisp/hubot-db-heimdall
3691387bdf33e6c02899371de63497baea3ab807
app/routes.js
app/routes.js
// @flow import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './containers/App'; import VerticalTree from './containers/VerticalTree'; export default ( <Route path="/" component={App}> <IndexRoute component={VerticalTree} /> </Route> );
// @flow import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './containers/App'; import Menu from './components/Menu'; import VerticalTree from './containers/VerticalTree'; import AVLTree from './containers/AVLTree'; export default ( <Route path="/" component={App}> <IndexRoute component={Menu} /> <Route path="usertree" component={VerticalTree} /> <Route path="treeExamples" component={AVLTree} /> </Route> );
Add route for example structures, and home page
Add route for example structures, and home page
JavaScript
mit
ivtpz/brancher,ivtpz/brancher
2ed2947f05c86d25e47928fa3eedbca0e84b92d8
LayoutTests/http/tests/notifications/resources/update-event-test.js
LayoutTests/http/tests/notifications/resources/update-event-test.js
if (self.importScripts) { importScripts('/resources/testharness.js'); importScripts('worker-helpers.js'); } async_test(function(test) { if (Notification.permission != 'granted') { assert_unreached('No permission has been granted for displaying notifications.'); return; } var notification = new Notification('My Notification', { tag: 'notification-test' }); notification.addEventListener('show', function() { var updatedNotification = new Notification('Second Notification', { tag: 'notification-test' }); updatedNotification.addEventListener('show', function() { test.done(); }); }); // FIXME: Replacing a notification should fire the close event on the // notification that's being replaced. notification.addEventListener('error', function() { assert_unreached('The error event should not be thrown.'); }); }, 'Replacing a notification will discard the previous notification.'); if (isDedicatedOrSharedWorker()) done();
if (self.importScripts) { importScripts('/resources/testharness.js'); importScripts('worker-helpers.js'); } async_test(function(test) { if (Notification.permission != 'granted') { assert_unreached('No permission has been granted for displaying notifications.'); return; } // We require two asynchronous events to happen when a notification gets updated, (1) // the old instance should receive the "close" event, and (2) the new notification // should receive the "show" event, but only after (1) has happened. var closedOriginalNotification = false; var notification = new Notification('My Notification', { tag: 'notification-test' }); notification.addEventListener('show', function() { var updatedNotification = new Notification('Second Notification', { tag: 'notification-test' }); updatedNotification.addEventListener('show', function() { assert_true(closedOriginalNotification); test.done(); }); }); notification.addEventListener('close', function() { closedOriginalNotification = true; }); notification.addEventListener('error', function() { assert_unreached('The error event should not be thrown.'); }); }, 'Replacing a notification will discard the previous notification.'); if (isDedicatedOrSharedWorker()) done();
Verify in a layout test that replacing a notification closes the old one.
Verify in a layout test that replacing a notification closes the old one. We do this by listening to the "close" event on the old notification as well. This test passes with or without the Chrome-sided fix because it's properly implemented in the LayoutTestNotificationManager, but is a good way of verifying the fix manually. BUG=366098 Review URL: https://codereview.chromium.org/750563005 git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@186033 bbb929c8-8fbe-4397-9dbb-9b2b20218538
JavaScript
bsd-3-clause
Bysmyyr/blink-crosswalk,kurli/blink-crosswalk,smishenk/blink-crosswalk,Bysmyyr/blink-crosswalk,jtg-gg/blink,jtg-gg/blink,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,PeterWangIntel/blink-crosswalk,Pluto-tv/blink-crosswalk,modulexcite/blink,Pluto-tv/blink-crosswalk,jtg-gg/blink,nwjs/blink,XiaosongWei/blink-crosswalk,modulexcite/blink,kurli/blink-crosswalk,Pluto-tv/blink-crosswalk,PeterWangIntel/blink-crosswalk,modulexcite/blink,smishenk/blink-crosswalk,Pluto-tv/blink-crosswalk,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,modulexcite/blink,modulexcite/blink,Pluto-tv/blink-crosswalk,XiaosongWei/blink-crosswalk,kurli/blink-crosswalk,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,PeterWangIntel/blink-crosswalk,kurli/blink-crosswalk,smishenk/blink-crosswalk,Pluto-tv/blink-crosswalk,Bysmyyr/blink-crosswalk,PeterWangIntel/blink-crosswalk,nwjs/blink,PeterWangIntel/blink-crosswalk,XiaosongWei/blink-crosswalk,XiaosongWei/blink-crosswalk,modulexcite/blink,XiaosongWei/blink-crosswalk,modulexcite/blink,XiaosongWei/blink-crosswalk,modulexcite/blink,jtg-gg/blink,Bysmyyr/blink-crosswalk,nwjs/blink,smishenk/blink-crosswalk,Bysmyyr/blink-crosswalk,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,smishenk/blink-crosswalk,jtg-gg/blink,jtg-gg/blink,smishenk/blink-crosswalk,smishenk/blink-crosswalk,smishenk/blink-crosswalk,jtg-gg/blink,jtg-gg/blink,Bysmyyr/blink-crosswalk,PeterWangIntel/blink-crosswalk,jtg-gg/blink,PeterWangIntel/blink-crosswalk,modulexcite/blink,nwjs/blink,nwjs/blink,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,nwjs/blink,smishenk/blink-crosswalk,kurli/blink-crosswalk,PeterWangIntel/blink-crosswalk,nwjs/blink,modulexcite/blink,smishenk/blink-crosswalk,PeterWangIntel/blink-crosswalk,nwjs/blink,XiaosongWei/blink-crosswalk,nwjs/blink,kurli/blink-crosswalk,XiaosongWei/blink-crosswalk,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,jtg-gg/blink,nwjs/blink,PeterWangIntel/blink-crosswalk,kurli/blink-crosswalk,kurli/blink-crosswalk
750402603dd7060bec89b98704be75597c6634bd
bin/oust.js
bin/oust.js
#!/usr/bin/env node var oust = require('../index'); var pkg = require('../package.json'); var fs = require('fs'); var argv = require('minimist')((process.argv.slice(2))) var printHelp = function() { console.log('oust'); console.log(pkg.description); console.log(''); console.log('Usage:'); console.log(' $ oust --file <filename> --selector <selector>'); }; if(argv.h || argv.help) { printHelp(); return; } if(argv.v || argv.version) { console.log(pkg.version); return; } var file = argv.f || argv.file; var selector = argv.s || argv.selector; fs.readFile(file, function(err, data) { if(err) { console.log('Error opening file:', err.code); return; } var res = oust(data, selector); console.log(res.join("\n")); });
#!/usr/bin/env node var oust = require('../index'); var pkg = require('../package.json'); var fs = require('fs'); var argv = require('minimist')((process.argv.slice(2))) var printHelp = function() { console.log('oust'); console.log(pkg.description); console.log(''); console.log('Usage:'); console.log(' $ oust <filename> <selector>'); }; if(argv.h || argv.help) { printHelp(); return; } if(argv.v || argv.version) { console.log(pkg.version); return; } var file = argv._[0]; var selector = argv._[1]; fs.readFile(file, function(err, data) { if(err) { console.error('Error opening file:', err.message); process.exit(1); } var res = oust(data, selector); console.log(res.join("\n")); });
Update CLI based on @sindresorhus feedback
Update CLI based on @sindresorhus feedback * don't use flagged args for file and selector * exit properly if error opening file
JavaScript
apache-2.0
addyosmani/oust,addyosmani/oust,actmd/oust,actmd/oust
fdee590648c6fdad1d6b19ef83bb9ce4b33fb0dc
src/merge-request-schema.js
src/merge-request-schema.js
const mongoose = require('mongoose'); const Schema = mongoose.Schema; module.exports = new Schema({ merge_request: { id: Number, url: String, target_branch: String, source_branch: String, created_at: String, updated_at: String, title: String, description: String, status: String, work_in_progress: Boolean }, last_commit: { id: Number, message: String, timestamp: String, url: String, author: { name: String, email: String } }, project: { name: String, namespace: String }, author: { name: String, username: String }, assignee: { claimed_on_slack: Boolean, name: String, username: String } });
const mongoose = require('mongoose'); const Schema = mongoose.Schema; module.exports = { name: 'MergeRequest', schema: new Schema({ merge_request: { id: Number, url: String, target_branch: String, source_branch: String, created_at: String, updated_at: String, title: String, description: String, status: String, work_in_progress: Boolean }, last_commit: { id: Number, message: String, timestamp: String, url: String, author: { name: String, email: String } }, project: { name: String, namespace: String }, author: { name: String, username: String }, assignee: { claimed_on_slack: Boolean, name: String, username: String } }) }
Merge request now exports its desired collection name
refactor: Merge request now exports its desired collection name
JavaScript
mit
NSAppsTeam/nickel-bot
26aca19bd633c7c876099d39b8d688d51bb7e773
spec/specs.js
spec/specs.js
describe('pingPongOutput', function() { it("is the number for most input numbers", function() { expect(pingPongOutput(2)).to.equal(2); }); it("is 'ping' for numbers divisible by 3", function() { expect(pingPongOutput(6)).to.equal("ping"); }); });
describe('pingPongOutput', function() { it("is the number for most input numbers", function() { expect(pingPongOutput(2)).to.equal(2); }); it("is 'ping' for numbers divisible by 3", function() { expect(pingPongOutput(6)).to.equal("ping"); }); it("is 'pong' for numbers divisible by 5", function() { expect(pingPongOutput(5)).to.equal("pong"); }); });
Add spec for numbers divisible by 5
Add spec for numbers divisible by 5
JavaScript
mit
JeffreyRuder/ping-pong-app,JeffreyRuder/ping-pong-app
da15d3de4dca28bb7ade0818b8dc0b97967c067d
lib/widgets/KeyBar.js
lib/widgets/KeyBar.js
'use strict'; const CLI = require('clui'); const clc = require('cli-color'); const gauge = CLI.Gauge; const Line = CLI.Line; module.exports = function (tactile, max) { if (!tactile) { return new Line(); } let name = tactile.label; if (tactile.name) { name += ` (${tactile.name.toUpperCase()})`; } return new Line() .padding(2) .column(name, 15, [clc.cyan]) .column(gauge(tactile.percentHolding * 100, max, 20, 60), 25) .column(gauge(tactile.percentReleasing * 100, max, 20, 60), 25) .column((tactile.action) ? '▼' : '▲', 2, [(tactile.action) ? clc.green : clc.red]) .fill(); };
'use strict'; const CLI = require('clui'); const clc = require('cli-color'); const gauge = CLI.Gauge; const Line = CLI.Line; module.exports = function (tactile, maxIdLength, max) { if (!tactile) { return new Line(); } let id = Array(maxIdLength - tactile.id.toString().length).join(0) + tactile.id.toString(); let name = tactile.label; if (tactile.name) { name += ` (${tactile.name.toUpperCase()})`; } return new Line() .padding(2) .column(id, 5, [clc.magenta]) .column(name, 15, [clc.cyan]) .column(gauge(tactile.percentHolding * 100, max, 20, 60), 25) .column(gauge(tactile.percentReleasing * 100, max, 20, 60), 25) .column((tactile.action) ? '▼' : '▲', 2, [(tactile.action) ? clc.green : clc.red]) .fill(); };
Add tactile id to output
Add tactile id to output
JavaScript
mit
ProbablePrime/interactive-keyboard,ProbablePrime/beam-keyboard
3cd107a985bcfd81b79633f06d3c21fe641f68c5
app/js/services.js
app/js/services.js
'use strict'; /* Services */ var splitcoinServices = angular.module('splitcoin.services', ['ngResource']); // Demonstrate how to register services // In this case it is a simple value service. splitcoinServices.factory('Ticker', ['$resource', function($resource){ return $resource('/sampledata/ticker.json', {}, { query: {method:'GET'} }); } ]);
'use strict'; /* Services */ var splitcoinServices = angular.module('splitcoin.services', ['ngResource']); // Demonstrate how to register services // In this case it is a simple value service. splitcoinServices.factory('Ticker', ['$resource', function($resource){ // For real data use: http://blockchain.info/ticker return $resource('/sampledata/ticker.json', {}, { query: {method:'GET'} }); } ]);
Add comment about real data
Add comment about real data
JavaScript
mit
kpeatt/splitcoin,kpeatt/splitcoin,kpeatt/splitcoin
e324b674c13a39b54141acaa0ab31ebc66177eb2
app/assets/javascripts/umlaut/expand_contract_toggle.js
app/assets/javascripts/umlaut/expand_contract_toggle.js
/* expand_contract_toggle.js: Support for show more/hide more in lists of umlaut content. The JS needs to swap out the image for expand/contract toggle. AND we need the URL it swaps in to be an ABSOLUTE url when we're using partial html widget. So we swap in a non-fingerprinted URL, even if the original was asset pipline fingerprinted. sorry, best way to make it work! */ jQuery(document).ready(function($) { $(".collapse-toggle").live("click", function(event) { $(this).collapse('toggle'); event.preventDefault(); return false; }); $(".collapse").live("shown", function(event) { // Update the icon $(this).parent().find('.collapse-toggle i').removeClass("umlaut_icons-list-closed").addClass("umlaut_icons-list-open"); // Update the action label $(this).parent().find(".expand_contract_action_label").text("Hide "); }); $(".collapse").live("hidden", function(event) { // Update the icon $(this).parent().find('.collapse-toggle i').removeClass("umlaut_icons-list-open").addClass("umlaut_icons-list-closed"); // Update the action label $(this).parent().find(".expand_contract_action_label").text("Show "); }); });
/* expand_contract_toggle.js: Support for show more/hide more in lists of umlaut content. The JS needs to swap out the image for expand/contract toggle. AND we need the URL it swaps in to be an ABSOLUTE url when we're using partial html widget. So we swap in a non-fingerprinted URL, even if the original was asset pipline fingerprinted. sorry, best way to make it work! */ jQuery(document).ready(function($) { $(".collapse-toggle").live("click", function(event) { event.preventDefault(); $(this).collapse('toggle'); return false; }); $(".collapse").live("shown", function(event) { // Hack cuz collapse don't work right if($(this).hasClass('in')) { // Update the icon $(this).parent().find('.collapse-toggle i').removeClass("umlaut_icons-list-closed").addClass("umlaut_icons-list-open"); // Update the action label $(this).parent().find(".expand_contract_action_label").text("Hide "); } }); $(".collapse").live("hidden", function(event) { // Hack cuz collapse don't work right if(!$(this).hasClass('in')) { // Update the icon $(this).parent().find('.collapse-toggle i').removeClass("umlaut_icons-list-open").addClass("umlaut_icons-list-closed"); // Update the action label $(this).parent().find(".expand_contract_action_label").text("Show "); } }); });
Add JS hack cuz Bootstrap don't work right with collapsible.
Add JS hack cuz Bootstrap don't work right with collapsible.
JavaScript
mit
team-umlaut/umlaut,team-umlaut/umlaut,team-umlaut/umlaut
e23a40064468c27be76dbb27efd4e4f2ac91ece5
app/js/arethusa.core/directives/arethusa_grid_handle.js
app/js/arethusa.core/directives/arethusa_grid_handle.js
"use strict"; angular.module('arethusa.core').directive('arethusaGridHandle', [ function() { return { restrict: 'E', scope: true, link: function(scope, element, attrs, ctrl, transclude) { }, templateUrl: 'templates/arethusa.core/arethusa_grid_handle.html' }; } ]);
"use strict"; angular.module('arethusa.core').directive('arethusaGridHandle', [ function() { return { restrict: 'E', scope: true, link: function(scope, element, attrs, ctrl, transclude) { function mouseEnter() { scope.$apply(function() { scope.visible = true; }); } function mouseLeave(event) { scope.$apply(function() { scope.visible = false; }); } var trigger = element.find('.drag-handle-trigger'); var handle = element.find('.drag-handle'); trigger.bind('mouseenter', mouseEnter); handle.bind('mouseleave', mouseLeave); }, templateUrl: 'templates/arethusa.core/arethusa_grid_handle.html' }; } ]);
Fix mouse events in arethusaGridHandle
Fix mouse events in arethusaGridHandle
JavaScript
mit
PonteIneptique/arethusa,Masoumeh/arethusa,Masoumeh/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa
5e579bd846f2fd223688dbfeca19b8a9a9f98295
src/config.js
src/config.js
import dotenv from "dotenv"; import moment from "moment"; dotenv.load(); export const MONGODB_URL = process.env.MONGODB_URL || "mongodb://localhost:27017/test"; export const KINESIS_STREAM_NAME = process.env.KINESIS_STREAM_NAME || "test"; export const AGGREGATES_COLLECTION_NAME = process.env.AGGREGATES_COLLECTION_NAME || "readings-daily-aggregates"; export const LOG_LEVEL = process.env.LOG_LEVEL || "info"; export const ALLOWED_SOURCES = ["reading", "forecast"]; export const DEFAULT_SAMPLE_DELTA_IN_MS = moment.duration(5, "minutes").asMilliseconds(); export const FORMULAS_COLLECTION = "virtual-sensors-formulas"; export const PRODUCER = "iwwa-lambda-virtual-aggregator"; export const EVENT_READING_INSERTED = "element inserted in collection readings";
import dotenv from "dotenv"; import moment from "moment"; dotenv.load(); export const MONGODB_URL = process.env.MONGODB_URL || "mongodb://localhost:27017/test"; export const KINESIS_STREAM_NAME = process.env.KINESIS_STREAM_NAME || "test"; export const AGGREGATES_COLLECTION_NAME = process.env.AGGREGATES_COLLECTION_NAME || "readings-daily-aggregates"; export const LOG_LEVEL = process.env.LOG_LEVEL || "info"; export const ALLOWED_SOURCES = ["reading", "forecast", "reference"]; export const DEFAULT_SAMPLE_DELTA_IN_MS = moment.duration(5, "minutes").asMilliseconds(); export const FORMULAS_COLLECTION = "virtual-sensors-formulas"; export const PRODUCER = "iwwa-lambda-virtual-aggregator"; export const EVENT_READING_INSERTED = "element inserted in collection readings";
Add reference to allowed sources
Add reference to allowed sources
JavaScript
apache-2.0
innowatio/iwwa-lambda-virtual-aggregator,innowatio/iwwa-lambda-virtual-aggregator
eaf923a11d75bbdb5373cd4629d31e4a38c5a659
js/rapido.utilities.js
js/rapido.utilities.js
(function($, window, document, undefined) { $.rapido_Utilities = { // Get class of element object getClass: function(el) { el = $(el).attr('class').replace(/^\s\s*/, '').replace(/\s\s*$/, ''); return '.' + el.split(' ').join('.'); }, // Remove dot from class dotlessClass: function(string) { return string.slice(1); }, // Check if an element exist elemExist: function(string) { return $(string).length !== 0; } }; })(jQuery, window, document);
(function($, window, document, undefined) { $.rapido_Utilities = { // Get class of element object getClass: function(el) { var attr = $(el).attr('class'); if (typeof attr !== 'undefined' && attr !== false) { el = $(el).attr('class').replace(/^\s\s*/, '').replace(/\s\s*$/, ''); return '.' + el.split(' ').join('.'); } }, // Remove dot from class dotlessClass: function(string) { return string.slice(1); }, // Check if an element exist elemExist: function(string) { return $(string).length !== 0; } }; })(jQuery, window, document);
Fix error in IE8 "attr(...)' is null or not an object"
Fix error in IE8 "attr(...)' is null or not an object"
JavaScript
mit
raffone/rapido,raffone/rapido,raffone/rapido
018018062b1a4f127d4861707ec9c438248a8dab
index.js
index.js
"use strict"; var glob = require("glob"); var path = require("path"); module.exports = function (content, sourceMap) { this.cacheable && this.cacheable(); var resourceDir = path.dirname(this.resourcePath); var pattern = content.trim(); var files = glob.sync(pattern, { cwd: resourceDir, realpath: true }); if (!files.length) { this.emitWarning('Did not find anything for glob "' + pattern + '" in directory "' + resourceDir + '"'); } return "module.exports = [\n" + files.map(function (file) { this.addDependency(file); return " require(" + JSON.stringify(file) + ")" }.bind(this)).join(",\n") + "\n];" };
"use strict"; var glob = require("glob"); var path = require("path"); module.exports = function (content, sourceMap) { var resourceDir = path.dirname(this.resourcePath); var pattern = content.trim(); var files = glob.sync(pattern, { cwd: resourceDir, realpath: true }); if (!files.length) { this.emitWarning('Did not find anything for glob "' + pattern + '" in directory "' + resourceDir + '"'); } return "module.exports = [\n" + files.map(function (file) { this.addDependency(file); return " require(" + JSON.stringify(file) + ")" }.bind(this)).join(",\n") + "\n];" };
Revert "feat: make results cacheable"
Revert "feat: make results cacheable" This reverts commit 43ac8eee4f33ac43c97ed6831a3660b1387148cb.
JavaScript
mit
seanchas116/glob-loader
f2ac02fcd69265f4e045883f5b033a91dd4e406d
index.js
index.js
var fs = require('fs'), path = require('path') module.exports = function (target) { var directory = path.dirname(module.parent.filename), rootDirectory = locatePackageJson(directory) return requireFromRoot(target, rootDirectory) } function locatePackageJson(directory) { try { fs.readFileSync(path.join(directory, 'package.json')) return directory } catch (e) {} if (directory === path.resolve('/')) { return } else { directory = path.join(directory, '..') return locatePackageJson(directory) } } function requireFromRoot(target, directory) { return require(path.join(directory, target)) }
"use strict"; // Node var lstatSync = require("fs").lstatSync; var path = require("path"); /** * Attempts to find the project root by finding the nearest package.json file. * @private * @param {String} currentPath - Path of the file doing the including. * @return {String?} */ function findProjectRoot(currentPath) { var result = undefined; try { var packageStats = lstatSync(path.join(currentPath, "package.json")); if (packageStats.isFile()) { result = currentPath; } } catch (error) { if (currentPath !== path.resolve("/")) { result = findProjectRoot(path.join(currentPath, "..")); } } return result; } /** * Creates the include function wrapper around <code>require</code> based on the path of the calling file and not the * install location of the module. * @param {String} callerPath - Path of the calling file. * @return {Function} * @example * * var include = require("include")(__dirname); * * var projectFn = include("src/method"); */ function createInclude(callerPath) { return function (target) { var projectRoot = findProjectRoot(callerPath); return projectRoot ? require(path.join(projectRoot, target)) : require(target); }; } module.exports = createInclude;
Fix relative path being relative to install location and not requesting file
Fix relative path being relative to install location and not requesting file Fixes #2.
JavaScript
mit
anthonynichols/node-include
78da26a359947988dbcacd635600909764b410a3
src/UCP/AbsenceBundle/Resources/public/js/app/views/planningview.js
src/UCP/AbsenceBundle/Resources/public/js/app/views/planningview.js
App.Views.PlanningView = Backbone.View.extend({ className: 'planning', initialize: function() { this.lessons = this.collection; this.lessons.on('add change remove reset', this.render, this); }, render: function() { var lessons = this.lessons.toArray(); // Build day views and keep DOM elements for insertion var elements = []; this.groupByDay(lessons, function(date, lessons) { var view = new App.Views.PlanningDayView({ date: date, lessons: lessons }); view.render(); elements.push(view.el); }); this.$el.append(elements); return this; }, groupByDay: function(lessons, iterator) { // Lessons are expected in date sorted order var lastDate, // The day we are working on lessonDate, // The date of of currently evaluated lesson lessonBag = []; // Temporary array holding holding lessons between each iterator call _.each(lessons, function(lesson) { lessonDate = new Date(lesson.get('start')); lessonDate.setHours(0,0,0,0); // We strip time components to compare date reliablely if (lessonDate > lastDate) { // We changed of day: call iterator and reset lesson bag iterator(lastDate, lessonBag); lessonBag = []; } lessonBag.push(lesson); lastDate = lessonDate; }); } });
App.Views.PlanningView = Backbone.View.extend({ className: 'planning', initialize: function() { this.lessons = this.collection; this.lessons.on('add change remove reset', this.render, this); }, render: function() { var lessons = this.lessons.toArray(); // Build day views and keep DOM elements for insertion var elements = []; this.groupByDay(lessons, function(date, lessons) { var view = new App.Views.PlanningDayView({ date: date, lessons: lessons }); view.render(); elements.push(view.el); }); this.$el.append(elements); return this; }, groupByDay: function(lessons, iterator) { // Lessons are expected in date sorted order var lastDate, // The day we are working on lessonDate, // The date of of currently evaluated lesson lessonBag = []; // Temporary array holding holding lessons between each iterator call _.each(lessons, function(lesson) { lessonDate = moment(lesson.get('start')).toDate(); lessonDate.setHours(0,0,0,0); // We strip time components to compare date reliablely if (lessonDate > lastDate) { // We changed of day: call iterator and reset lesson bag iterator(lastDate, lessonBag); lessonBag = []; } lessonBag.push(lesson); lastDate = lessonDate; }); } });
Fix planning page on Safari
Fix planning page on Safari new Date("…") cannot parse ISO8601 with a timezone on certain non-fully ES5 compliant browsers
JavaScript
mit
mdarse/take-the-register,mdarse/take-the-register
e32792f7b23aa899a083f0618d1b093f93101e9f
src/errors.js
src/errors.js
export function ValidationError(message, details = {}) { const { columns = {}, value = null } = details; this.message = message; this.columns = columns; this.value = value; if (message instanceof Error) { this.message = message.message; this.stack = message.stack; } else if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } ValidationError.prototype = Object.create(Error); ValidationError.prototype.constructor = ValidationError; ValidationError.prototype.toString = Error.prototype.toString; Object.defineProperty(ValidationError, 'name', { value: 'ValidationError' });
export function ValidationError(message, details = {}) { const { columns = {}, value = null } = details; this.message = message; this.columns = columns; this.value = value; if (message instanceof Error) { this.message = message.message; this.stack = message.stack; } else if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } ValidationError.prototype = Object.create(Error); ValidationError.prototype.constructor = ValidationError; ValidationError.prototype.toString = Error.prototype.toString; Object.defineProperty(ValidationError.prototype, 'name', { value: 'ValidationError' });
Define 'name' on the prototype instead of constructor
Define 'name' on the prototype instead of constructor
JavaScript
mit
goodybag/nagoya
951adf61d874553956ac63d2268629d7b2a603ec
core/imagefile.js
core/imagefile.js
function ImageFile(_game) { this.game = _game; this.name = new Array(); this.data = new Array(); this.counter = 0; return this; }; ImageFile.prototype.load = function(_imageSrc, _width, _height) { if(!this.getImageDataByName(_imageSrc)) { var self = this; var _image = new Image(); _image.src = _imageSrc; _image.addEventListener('load', function(){self.counter++}); this.name.push(_imageSrc); this.data.push(_image); } var s = new Sprite(_imageSrc, _width, _height); s.image = this.getImageDataByName(_imageSrc); this.game.current.scene.sprite.push(s); return s; }; ImageFile.prototype.isLoaded = function() { if(this.counter === this.data.length) { return true; } return false; }; ImageFile.prototype.getImageDataByName = function(_imageName) { return this.data[this.name.indexOf(_imageName)]; };
function ImageFile(_game) { this.game = _game; this.name = new Array(); this.data = new Array(); this.counter = 0; return this; }; ImageFile.prototype.load = function(_imageSrc, _width, _height) { if(!this.getImageDataByName(_imageSrc)) { var self = this; var _image = new Image(); _image.src = _imageSrc; _image.addEventListener('load', function(){self.counter++}); this.name.push(_imageSrc); this.data.push(_image); } var s = new Sprite(_imageSrc, _width, _height); s.image = this.getImageDataByName(_imageSrc); this.game.current.scene.sprite.push(s); return s; }; ImageFile.prototype.loadMap = function(_imageSrc, _width, _height) { if(!this.getImageDataByName(_imageSrc)) { var self = this; var _image = new Image(); _image.src = _imageSrc; _image.addEventListener('load', function(){self.counter++}); this.name.push(_imageSrc); this.data.push(_image); } return this.getImageDataByName(_imageSrc); } ImageFile.prototype.isLoaded = function() { if(this.counter === this.data.length) { return true; } return false; }; ImageFile.prototype.getImageDataByName = function(_imageName) { return this.data[this.name.indexOf(_imageName)]; };
Create loadMap function to load map images
Create loadMap function to load map images
JavaScript
mit
fjsantosb/Molecule
9f71330ad43cb188feef6a6c6053ae9f6dd731f5
index.js
index.js
var babelPresetEs2015, commonJsPlugin, es2015PluginList, es2015WebpackPluginList; babelPresetEs2015 = require('babel-preset-es2015'); try { // npm ^2 commonJsPlugin = require('babel-preset-es2015/node_modules/babel-plugin-transform-es2015-modules-commonjs'); } catch (error) { } if (!commonJsPlugin) { try { // npm ^3 commonJsPlugin = require('babel-plugin-transform-es2015-modules-commonjs'); } catch (error) { } } if (!commonJsPlugin) { throw new Error('Cannot resolve "babel-plugin-transform-es2015-modules-commonjs".'); } es2015PluginList = babelPresetEs2015.plugins; es2015WebpackPluginList = es2015PluginList.filter(function (es2015Plugin) { return es2015Plugin !== commonJsPlugin; }); if (es2015PluginList.length !== es2015WebpackPluginList.length + 1) { throw new Error('Cannot remove "babel-plugin-transform-es2015-modules-commonjs" from the plugin list.'); } module.exports = { plugins: es2015WebpackPluginList };
var babelPresetEs2015, commonJsPlugin, es2015PluginList, es2015WebpackPluginList; babelPresetEs2015 = require('babel-preset-es2015'); try { // npm ^3 commonJsPlugin = require('babel-plugin-transform-es2015-modules-commonjs'); } catch (error) { } if (!commonJsPlugin) { try { // npm ^2 commonJsPlugin = require('babel-preset-es2015/node_modules/babel-plugin-transform-es2015-modules-commonjs'); } catch (error) { } } if (!commonJsPlugin) { throw new Error('Cannot resolve "babel-plugin-transform-es2015-modules-commonjs".'); } es2015PluginList = babelPresetEs2015.plugins; es2015WebpackPluginList = es2015PluginList.filter(function (es2015Plugin) { return es2015Plugin !== commonJsPlugin; }); if (es2015PluginList.length !== es2015WebpackPluginList.length + 1) { throw new Error('Cannot remove "babel-plugin-transform-es2015-modules-commonjs" from the plugin list.'); } module.exports = { plugins: es2015WebpackPluginList };
Fix module resolution for npm 3+
Fix module resolution for npm 3+
JavaScript
bsd-3-clause
gajus/babel-preset-es2015-webpack
8929cc57fe95f1802a7676250ed489562f76c8db
index.js
index.js
/* jshint node: true */ 'use strict'; var request = require('request'); var BasePlugin = require('ember-cli-deploy-plugin'); module.exports = { name: 'ember-cli-deploy-cdnify-purge-cache', createDeployPlugin: function(options) { var DeployPlugin = BasePlugin.extend({ name: options.name, requiredConfig: ['cdnifyResourceId', 'cdnifyApiKey'], didDeploy: function(context) { let config = context.config['cdnify-purge-cache'] let apiKey = config['cdnifyApiKey']; let resourceId = config['cdnifyResourceId']; let endpoint = `cdnify.com/api/v1/resources/${resourceId}/cache`; let credentials = `${apiKey}:x`; var self = this; return new Promise(function(resolve, reject) { request({ url: `https://${credentials}@${endpoint}`, method: "DELETE" }, function(error, response, body) { if(error) { self.log("CDNIFY CACHE *NOT* PURGED!", { verbose: true }); reject(error); } else { self.log("CDNIFY CACHE PURGED!", { verbose: true }); resolve(body); } }) }); } }); return new DeployPlugin(); } };
/* jshint node: true */ 'use strict'; var request = require('request'); var BasePlugin = require('ember-cli-deploy-plugin'); module.exports = { name: 'ember-cli-deploy-cdnify-purge-cache', createDeployPlugin: function(options) { var DeployPlugin = BasePlugin.extend({ name: options.name, requiredConfig: ['cdnifyResourceId', 'cdnifyApiKey'], didDeploy: function(context) { var config = context.config['cdnify-purge-cache'] var apiKey = config['cdnifyApiKey']; var resourceId = config['cdnifyResourceId']; var endpoint = `cdnify.com/api/v1/resources/${resourceId}/cache`; var credentials = `${apiKey}:x`; var self = this; return new Promise(function(resolve, reject) { request({ url: `https://${credentials}@${endpoint}`, method: "DELETE" }, function(error, response, body) { if(error) { self.log("CDNIFY CACHE *NOT* PURGED!", { verbose: true }); reject(error); } else { self.log("CDNIFY CACHE PURGED!", { verbose: true }); resolve(body); } }) }); } }); return new DeployPlugin(); } };
Remove let until upstream Ember-CLI issue is fixed
Remove let until upstream Ember-CLI issue is fixed
JavaScript
mit
fauxton/ember-cli-deploy-cdnify-purge-cache,fauxton/ember-cli-deploy-cdnify-purge-cache
fbed9d4aac28c0ef9d5070b31aeec9de09009e26
index.js
index.js
var url = require('url') module.exports = function(uri, cb) { var parsed try { parsed = url.parse(uri) } catch (err) { return cb(err) } if (!parsed.host) { return cb(new Error('Invalid url: ' + uri)) } var opts = { host: parsed.host , port: parsed.port , path: parsed.path , method: 'HEAD' , agent: false } var http = parsed.protocol === 'https:' ? require('https') : require('http') var req = http.request(opts) req.end() req.on('response', function(res) { var code = res.statusCode if (code >= 400) { return cb(new Error('Received invalid status code: ' + code)) } cb(null, +res.headers['content-length']) }) }
var request = require('request') module.exports = function(options, cb) { if ('string' === typeof options) { options = { uri: options } } options = options || {} options.method = 'HEAD' options.followAllRedirects = true request(options, function(err, res, body) { if (err) return cb(err) var code = res.statusCode if (code >= 400) { return cb(new Error('Received invalid status code: ' + code)) } var len = res.headers['content-length'] if (!len) { return cb(new Error('Unable to determine file size')) } if (isNaN(+len)) { return cb(new Error('Invalid Content-Length received')) } cb(null, +res.headers['content-length']) }) }
Use request and allow passing object
Use request and allow passing object
JavaScript
mit
evanlucas/remote-file-size
7920bd541507d35990f146aa45168a4b2f4331be
index.js
index.js
"use strict" const examine = require("./lib/examine") const inspect = require("./lib/inspect") const isPlainObject = require("./lib/is-plain-object") const whereAll = require("./lib/where-all") module.exports = { examine, inspect, isPlainObject, whereAll }
"use strict" const { examine, see } = require("./lib/examine") const inspect = require("./lib/inspect") const isPlainObject = require("./lib/is-plain-object") const whereAll = require("./lib/where-all") module.exports = { examine, inspect, isPlainObject, see, whereAll }
Include the missing `see` function
Include the missing `see` function
JavaScript
mit
icylace/icylace-object-utils
0ed42a900e206c2cd78fdf6b5f6578254394f3e2
src/sprites/Common/index.js
src/sprites/Common/index.js
import Phaser from 'phaser'; export default class extends Phaser.Sprite { constructor(game, x, y, sprite, frame) { super(game, x, y, sprite, frame); this.anchor.setTo(0.5, 0.5); } }
import Phaser from 'phaser'; import { alignToGrid } from '../../tiles'; export default class extends Phaser.Sprite { constructor(game, x, y, sprite, frame) { const alignedCoords = alignToGrid({ x, y }); x = alignedCoords.x; y = alignedCoords.y; super(game, x, y, sprite, frame); this.anchor.setTo(0.5, 0.5); } }
Align to grid before placing object
Align to grid before placing object
JavaScript
mit
ThomasMays/incremental-forest,ThomasMays/incremental-forest
ae1ac92b8884f41656eda30a0949fec0eceb2428
server/services/passport.js
server/services/passport.js
const passport = require('passport'); const GoogleStrategy = require('passport-google-oauth20').Strategy; const keys = require('../config/keys'); const mongoose = require('mongoose'); const User = mongoose.model('users'); // retrieve this collection // Tell passport to use google oauth for authentication passport.use( new GoogleStrategy( { clientID: keys.googleClientID, clientSecret: keys.googleClientSecret, callbackURL: '/auth/google/callback' }, // Get executed when a user is actually executed. we can store this on the database // to link this token to a user for later use. (accessToken, refreshToken, profile, done) => { User.findOne({googleId: profile.id}) .then( existingUser => { if ( existingUser ) { // first arg: no error, second arg: tell passport that this is the user that we just created done(null, existingUser); } else { new User({ googleId: profile.id }) // create a user model instance .save() //save it to db .then(user => done(null, user)); // finish saving, so we need to call done to finish the OAuth process } }); } ) );
const passport = require('passport'); const GoogleStrategy = require('passport-google-oauth20').Strategy; const keys = require('../config/keys'); const mongoose = require('mongoose'); const User = mongoose.model('users'); // retrieve this collection // Tell passport to use google oauth for authentication passport.use( new GoogleStrategy( { clientID: keys.googleClientID, clientSecret: keys.googleClientSecret, callbackURL: '/auth/google/callback' }, // Get executed when a user is actually executed. we can store this on the database // to link this token to a user for later use. (accessToken, refreshToken, profile, done) => { User.findOne({googleId: profile.id}) .then( existingUser => { if ( existingUser ) { // first arg: no error, second arg: tell passport that this is the user that we just created done(null, existingUser); } else { new User({ googleId: profile.id }) // create a user model instance .save() //save it to db .then(user => done(null, user)); // finish saving, so we need to call done to finish the OAuth process } }); } ) ); // Once we get the user instance from the db ( this happens after the authentication process above finishes ) // We ask passport to use user.id ( not googleId ), created by MongoDb, to send this info to the client // by setting it in the cookie, so that future requests from the client will have this information in the cookie // set automatically by the browser passport.serializeUser( (user, done) => { done(null, user.id); }); // Client sends more requests to the server after all the auth process. Passport will use the cookie info // in the request to create or query for the User instance associated with that info passport.deserializeUser( (id, done) => { User.findById(id) .then(user => done( null, user)); }); // Tell passport that it needs to use cookie to keep track of the currently signed in user
Add serialization and deserlization for User
Add serialization and deserlization for User Serialization step: get the user.id as a cookie value and send it back to the client for later user. Deserialization: client sends make a request with cookie value that can be turned into an actual user instance.
JavaScript
mit
chhaymenghong/FullStackReact
4bfa64cf19896baf36af8a21f022771252700c27
ui/app/common/components/pnc-temporary-build-record-label/pncTemporaryBuildRecordLabel.js
ui/app/common/components/pnc-temporary-build-record-label/pncTemporaryBuildRecordLabel.js
/* * JBoss, Home of Professional Open Source. * Copyright 2014-2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function () { 'use strict'; angular.module('pnc.common.components').component('pncTemporaryBuildRecordLabel', { bindings: { /** * Object: a Record object representing Build Record */ buildRecord: '<?', /** * Object: a Record object representing Build Group Record */ buildGroupRecord: '<?', }, templateUrl: 'common/components/pnc-temporary-build-record-label/pnc-temporary-build-record-label.html', controller: [Controller] }); function Controller() { var $ctrl = this; var buildRecord = $ctrl.buildRecord ? $ctrl.buildRecord : $ctrl.buildGroupRecord; // -- Controller API -- $ctrl.isTemporary = isTemporary; // -------------------- function isTemporary() { return buildRecord.temporaryBuild; } } })();
/* * JBoss, Home of Professional Open Source. * Copyright 2014-2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function () { 'use strict'; angular.module('pnc.common.components').component('pncTemporaryBuildRecordLabel', { bindings: { /** * Object: a Record object representing Build Record */ buildRecord: '<?', /** * Object: a Record object representing Build Group Record */ buildGroupRecord: '<?', }, templateUrl: 'common/components/pnc-temporary-build-record-label/pnc-temporary-build-record-label.html', controller: [Controller] }); function Controller() { var $ctrl = this; var buildRecord; $ctrl.$onInit = function() { buildRecord = $ctrl.buildRecord ? $ctrl.buildRecord : $ctrl.buildGroupRecord; $ctrl.isTemporary = isTemporary; }; function isTemporary() { return buildRecord.temporaryBuild; } } })();
Fix temporary build label init process
Fix temporary build label init process
JavaScript
apache-2.0
thescouser89/pnc,jdcasey/pnc,matedo1/pnc,matedo1/pnc,alexcreasy/pnc,alexcreasy/pnc,jdcasey/pnc,rnc/pnc,matejonnet/pnc,alexcreasy/pnc,matedo1/pnc,pkocandr/pnc,jdcasey/pnc,project-ncl/pnc
e39eb6b1f2c4841ddc293428ab0c358214e897ad
src/colors.js
src/colors.js
const colors = { red: '#e42d40', white: '#ffffff', veryLightGray: '#ededed', lightGray: '#cccccc', gray: '#888888', darkGray: '#575757' } const brandPreferences = { primary: colors.red, bg: colors.white, outline: colors.lightGray, placeholder: colors.veryLightGray, userInput: colors.darkGray } export default Object.assign({}, colors, brandPreferences)
const colors = { red: '#e42d40', white: '#ffffff', veryLightGray: '#ededed', lightGray: '#cccccc', gray: '#888888', darkGray: '#575757' } const brandPreferences = { primary: colors.red, bg: colors.white, outline: colors.lightGray, placeholder: colors.veryLightGray, userInput: colors.darkGray } export default { ...colors, ...brandPreferences }
Use spread syntax instead of Object.assign
Use spread syntax instead of Object.assign
JavaScript
mit
hackclub/api,hackclub/api,hackclub/api
edd75a3c15c81feb05d51736af6dd605bb10a72f
src/routes.js
src/routes.js
import React from 'react'; import {IndexRoute, Route} from 'react-router'; import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth'; import { App, Chat, Home, Widgets, About, Login, LoginSuccess, Survey, NotFound, } from 'containers'; export default (store) => { const requireLogin = (nextState, replaceState, cb) => { function checkAuth() { const { auth: { user }} = store.getState(); if (!user) { // oops, not logged in, so can't be here! replaceState(null, '/'); } cb(); } if (!isAuthLoaded(store.getState())) { store.dispatch(loadAuth()).then(checkAuth); } else { checkAuth(); } }; return ( <Route path="/" component={App}> <IndexRoute component={Home}/> <Route path="widgets" component={Widgets}/> <Route path="about" component={About}/> <Route path="login" component={Login}/> <Route onEnter={requireLogin}> <Route path="chat" component={Chat}/> <Route path="loginSuccess" component={LoginSuccess}/> </Route> <Route path="survey" component={Survey}/> <Route path="*" component={NotFound} status={404} /> </Route> ); };
import React from 'react'; import {IndexRoute, Route} from 'react-router'; import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth'; import { App, Chat, Home, Widgets, About, Login, LoginSuccess, Survey, NotFound, } from 'containers'; export default (store) => { const requireLogin = (nextState, replaceState, cb) => { function checkAuth() { const { auth: { user }} = store.getState(); if (!user) { // oops, not logged in, so can't be here! replaceState(null, '/'); } cb(); } if (!isAuthLoaded(store.getState())) { store.dispatch(loadAuth()).then(checkAuth); } else { checkAuth(); } }; /** * Please keep routes in alphabetical order */ return ( <Route path="/" component={App}> { /* Home (main) route */ } <IndexRoute component={Home}/> { /* Routes requiring login */ } <Route onEnter={requireLogin}> <Route path="chat" component={Chat}/> <Route path="loginSuccess" component={LoginSuccess}/> </Route> { /* Routes */ } <Route path="about" component={About}/> <Route path="login" component={Login}/> <Route path="survey" component={Survey}/> <Route path="widgets" component={Widgets}/> { /* Catch all route */ } <Route path="*" component={NotFound} status={404} /> </Route> ); };
Use alphabetical route order for easier merging
Use alphabetical route order for easier merging
JavaScript
mit
ames89/keystone-react-redux,sunh11373/t648,ptim/react-redux-universal-hot-example,andyshora/memory-tools,huangc28/palestine-2,quicksnap/react-redux-universal-hot-example,melodylu/react-redux-universal-hot-example,moje-skoly/web-app,AndriyShepitsen/svredux,dieface/react-redux-universal-hot-example,ThatCheck/AutoLib,dumbNickname/oasp4js-goes-react,lordakshaya/pages,gihrig/react-redux-universal-hot-example,Kronenberg/WebLabsTutorials,PhilNorfleet/pBot,thomastanhb/ericras,delwiv/saphir,TribeMedia/react-redux-universal-hot-example,micooz/react-redux-universal-hot-example,TonyJen/react-redux-universal-hot-example,ames89/keystone-react-redux,tanvip/hackPrinceton,bdefore/universal-redux,MarkPhillips7/happy-holidays,nathanielks/universal-redux,AnthonyWhitaker/react-redux-universal-hot-example,codejunkienick/katakana,sars/appetini-front,CalebEverett/soulpurpose,bdefore/react-redux-universal-hot-example,Widcket/sia,trueter/react-redux-universal-hot-example,hank7444/react-redux-universal-hot-example,PhilNorfleet/pBot,erikras/react-redux-universal-hot-example,tonykung06/realtime-exchange-rates,kiyonish/kiyonishimura,mull/require_hacker_error_reproduction,sfarthin/youtube-search,frankleng/react-redux-universal-hot-example,danieloliveira079/healthy-life-app,guymorita/creditTiger,andbet39/reactPress,eastonqiu/frontend,jeremiahrhall/react-redux-universal-hot-example,sanyamagrawal/royalgeni,reggi/react-shopify-app,avantcontra/react-redux-custom-starter,mscienski/stpauls,bdefore/universal-redux,nase-skoly/web-app,delwiv/tactill-techtest,Dengo/bacon-bacon,elbstack/elbstack-hackreact-web-3,prgits/react-product,vidaaudrey/avanta,hldzlk/wuhao,tpphu/react-pwa,codejunkienick/katakana,Widcket/sia,sseppola/react-redux-universal-hot-example,Smotko/react-redux-universal-hot-example,nathanielks/universal-redux,fforres/coworks,hokustalkshow/friend-landing-page,Trippstan/elephonky,DelvarWorld/some-game,Shabananana/hot-nav,jairoandre/lance-web-hot,RomanovRoman/react-redux-universal-hot-example,hitripod/react-redux-universal-hot-example,user512/teacher_dashboard,Druddigon/react-redux-learn,bertho-zero/react-redux-universal-hot-example,svsool/react-redux-universal-hot-example,TracklistMe/client-web,hldzlk/wuhao,ThatCheck/AutoLib,thingswesaid/seed,fiTTrail/fiTTrail,runnables/react-redux-universal-hot-example,mscienski/stpauls,chrisslater/snapperfish,twomoonsfactory/custom-poll,ipbrennan90/movesort-app,TracklistMe/client-react,thekevinscott/react-redux-universal-starter-kit,ercangursoy/react-dev,EnrikoLabriko/react-redux-universal-hot-example,robertSahm/port,Xvakin/quiz,Widcket/sia,Widcket/react-boilerplate,bazanowsky/react-ssr-exercise,tpphu/react-pwa,delwiv/saphir,yomolify/cc_material
3dfaa509dcae64b13f8b68c74fb6085e18c1ccc2
src/app/auth/auth.service.js
src/app/auth/auth.service.js
(function() { 'use strict'; var app = angular.module('radar.auth'); app.factory('authService', function(session, $q, store, adapter) { return { login: login }; function login(username, password) { var deferred = $q.defer(); adapter.post('/login', {}, {username: username, password: password}).then(function(response) { var userId = response.data.userId; var token = response.data.token; return store.findOne('users', userId) .then(function(user) { deferred.resolve({ user: user, token: token }); }) .catch(function(response) { if (response.status === 422) { deferred.reject(response.data.errors); } else { deferred.reject('Error logging in, please try again.'); } }); }); return deferred.promise; } }); })();
(function() { 'use strict'; var app = angular.module('radar.auth'); app.factory('authService', function(session, $q, store, adapter) { return { login: login }; function login(username, password) { var deferred = $q.defer(); adapter.post('/login', {}, {username: username, password: password}) .then(function(response) { var userId = response.data.userId; var token = response.data.token; return store.findOne('users', userId) .then(function(user) { deferred.resolve({ user: user, token: token }); }) .catch(function() { deferred.reject('Error logging in, please try again.'); }); }) .catch(function(response) { if (response.status === 422) { deferred.reject(response.data.errors); } else { deferred.reject('Error logging in, please try again.'); } }); return deferred.promise; } }); })();
Add pagination support to API
Add pagination support to API
JavaScript
agpl-3.0
renalreg/radar-client,renalreg/radar-client,renalreg/radar-client
ad4f2512ab1e42bf19b877c04eddd831cf747fb0
models/collections.js
models/collections.js
var TreeModel = require('tree-model'); module.exports = function(DataTypes) { return [{ name: { type: DataTypes.STRING, allowNull: false } }, { instanceMethods: { insertIntoDirs: function(UUID, parentUUID) { var tree = new TreeModel(); var dirs = tree.parse(JSON.parse(this.dirs)); var parent; if (parentUUID) { parent = dirs.first(function(node) { return node.model.UUID === parent; }); } if (!parent) { parent = dirs; } parent.addChild(tree.parse({ UUID: UUID })); this.dirs = JSON.stringify(dirs.model); return this.save(['dirs']); } } }]; };
var TreeModel = require('tree-model'); module.exports = function(DataTypes) { return [{ name: { type: DataTypes.STRING, allowNull: false } }]; };
Remove unnecessary instance methods of collection
Remove unnecessary instance methods of collection
JavaScript
mit
wikilab/wikilab-api
f0dc23100b7563c60f62dad82a4aaf364a69c2cb
test/index.js
test/index.js
// require Johnny's static var JohhnysStatic = require("../index") // require http , http = require('http'); // set static server: public folder JohhnysStatic.setStaticServer({root: "./public"}); // set routes JohhnysStatic.setRoutes({ "/": { "url": __dirname + "/html/index.html" } , "/test1/": { "url": __dirname + "/html/test1.html" } , "/test2/": { "url": __dirname + "/html/test2.html" } }); // create http server http.createServer(function(req, res) { // safe serve if (JohhnysStatic.exists(req, res)) { // serve file JohhnysStatic.serve(req, res, function (err) { // not found error if (err.code === "ENOENT") { // write head res.writeHead(404, {"Content-Type": "text/html"}); // send response res.end("404 - Not found."); // return return; } // other error res.end(JSON.stringify(err)); }); // return return; } // if the route doesn't exist, it's a 404! res.end("404 - Not found"); }).listen(8000); // output console.log("Listening on 8000.");
// require Johnny's static var JohhnysStatic = require("../index") // require http , http = require('http'); // set static server: public folder JohhnysStatic.setStaticServer({root: __dirname + "/public"}); // set routes JohhnysStatic.setRoutes({ "/": { "url": "/html/index.html" } , "/test1/": { "url": "/html/test1.html" } , "/test2/": { "url": "/html/test2.html" } }); // create http server http.createServer(function(req, res) { // safe serve if (JohhnysStatic.exists(req, res)) { // serve file JohhnysStatic.serve(req, res, function (err) { // not found error if (err.code === "ENOENT") { // write head res.writeHead(404, {"Content-Type": "text/html"}); // send response res.end("404 - Not found."); // return return; } // other error res.end(JSON.stringify(err)); }); // return return; } // if the route doesn't exist, it's a 404! res.end("404 - Not found"); }).listen(8000); // output console.log("Listening on 8000.");
Use __dirname when setting the root
Use __dirname when setting the root
JavaScript
mit
IonicaBizauTrash/johnnys-node-static,IonicaBizau/statique,IonicaBizauTrash/johnnys-node-static,IonicaBizau/node-statique,IonicaBizau/johnnys-node-static,IonicaBizau/johnnys-node-static
d01325010342043712e1680d4fb577eaa4df3634
test/index.js
test/index.js
'use strict'; const fs = require('fs'); const path = require('path'); const cp = require('child_process'); const sass = require('../'); const root = path.resolve(__dirname, './test-cases'); const cases = fs.readdirSync(root); cases.forEach((test) => { let hasPackageJson; try { hasPackageJson = require(path.resolve(root, test, './package.json')); } catch (e) {} describe(test, () => { before((done) => { if (hasPackageJson) { cp.exec('npm install', { cwd: path.resolve(root, test) }, (err) => { done(err); }); } else { done(); } }); it('can compile from code without error', (done) => { sass(path.resolve(root, test, './index.scss'), (err, output) => { done(err); }); }); it('can compile from cli without error', (done) => { cp.exec(path.resolve(__dirname, '../bin/npm-sass') + ' index.scss', { cwd: path.resolve(root, test) }, (err, stdout) => { done(err); }); }); try {// to load test cases from within test case assertions = require(path.resolve(root, test, './test')); } catch (e) {} }); });
'use strict'; const fs = require('fs'); const path = require('path'); const cp = require('child_process'); const sass = require('../'); const css = require('css'); const root = path.resolve(__dirname, './test-cases'); const cases = fs.readdirSync(root); cases.forEach((test) => { let hasPackageJson; try { hasPackageJson = require(path.resolve(root, test, './package.json')); } catch (e) {} describe(test, () => { before((done) => { if (hasPackageJson) { cp.exec('npm install', { cwd: path.resolve(root, test) }, (err) => { done(err); }); } else { done(); } }); it('can compile from code without error', (done) => { sass(path.resolve(root, test, './index.scss'), (err, output) => { css.parse(output.css.toString()); done(err); }); }); it('can compile from cli without error', (done) => { cp.exec(path.resolve(__dirname, '../bin/npm-sass') + ' index.scss', { cwd: path.resolve(root, test) }, (err, stdout) => { css.parse(stdout); done(err); }); }); try {// to load test cases from within test case assertions = require(path.resolve(root, test, './test')); } catch (e) {} }); });
Check output is valid css in test cases
Check output is valid css in test cases
JavaScript
mit
GeorgeTaveras1231/npm-sass,lennym/npm-sass
98943dcae31dbee0ad3e7a4b2b568128a3d20524
app/controllers/DefaultController.js
app/controllers/DefaultController.js
import AppController from './AppController' export default class DefaultController extends AppController { async indexAction(context) { return context.redirectToRoute('hello', {name: 'Christoph', foo: 'bar'}) } }
import AppController from './AppController' export default class DefaultController extends AppController { async indexAction(context) { return context.redirectToRoute('hello', {name: 'Christoph', foo: 'bar'}) } async missingRouteAction(context) { return context.redirectToRoute('foobarbazboo') } }
Add an action that redirects to a missing route
Add an action that redirects to a missing route
JavaScript
mit
CHH/learning-node,CHH/learning-node
f76d185650f187a509b59e86a09df063a177af78
test/utils.js
test/utils.js
import assert from 'power-assert'; import { camelToKebab } from '../src/utils'; describe('utils', () => { it('translates camelCase to kebab-case', () => { assert(camelToKebab('camelCaseToKebabCase') === 'camel-case-to-kebab-case'); }); it('does not add hyphen to the first position', () => { assert(camelToKebab('FirstPosition') === 'first-position'); }); it('does nothing if there is no camel case string', () => { assert(camelToKebab('no_camel-string0123') === 'no_camel-string0123'); }); it('adds hyphen between a number and a upper case character', () => { assert(camelToKebab('camel012Camel') === 'camel012-camel'); }); });
import assert from 'power-assert'; import { camelToKebab, assign, pick, mapValues } from '../src/utils'; describe('utils', () => { describe('camelToKebab', () => { it('translates camelCase to kebab-case', () => { assert(camelToKebab('camelCaseToKebabCase') === 'camel-case-to-kebab-case'); }); it('does not add hyphen to the first position', () => { assert(camelToKebab('FirstPosition') === 'first-position'); }); it('does nothing if there is no camel case string', () => { assert(camelToKebab('no_camel-string0123') === 'no_camel-string0123'); }); it('adds hyphen between a number and a upper case character', () => { assert(camelToKebab('camel012Camel') === 'camel012-camel'); }); }); describe('assign', () => { it('extends the first argument by latter arguments', () => { const a = { a: 1, b: 1 }; const actual = assign(a, { a: 2, c: 1 }, { d: 1 }, { c: 2 }); assert.deepEqual(a, { a: 2, b: 1, c: 2, d: 1 }); assert(a === actual); }); }); describe('pick', () => { it('picks specified properties', () => { const a = { a: 1, b: 1, c: 1, d: 1 }; const actual = pick(a, ['a', 'c', 'e']); assert.deepEqual(actual, { a: 1, c: 1 }); }); }); describe('mapValues', () => { it('maps the values of an object', () => { const f = n => n + 1; const a = { a: 1, b: 2, c: 3 }; const actual = mapValues(a, f); assert.deepEqual(actual, { a: 2, b: 3, c: 4 }); }); }); });
Add test cases for utility functions
Add test cases for utility functions
JavaScript
mit
ktsn/vuex-connect,ktsn/vuex-connect
073c72bb5caef958a820cdeadc440a042dd4f111
test/_page.js
test/_page.js
import puppeteer from 'puppeteer'; export async function evaluatePage (url, matches, timeout = 4000) { const args = await puppeteer.defaultArgs(); const browser = await puppeteer.launch({ args: [...args, '--enable-experimental-web-platform-features'] }); const page = await browser.newPage(); await page.goto(url); try { return await new Promise((resolve, reject) => { page.on('console', msg => { const text = msg.text(); if (text.match(matches)) { clearTimeout(timer); resolve(text); } }); const timer = setTimeout(() => reject(Error('Timed Out')), timeout); }); } finally { await browser.close(); } }
import puppeteer from 'puppeteer'; export async function evaluatePage (url, matches, timeout = 4000) { const args = await puppeteer.defaultArgs(); const browser = await puppeteer.launch({ args: [ ...args, '--no-sandbox', '--disable-setuid-sandbox', '--enable-experimental-web-platform-features' ] }); const page = await browser.newPage(); await page.goto(url); try { return await new Promise((resolve, reject) => { page.on('console', msg => { const text = msg.text(); if (text.match(matches)) { clearTimeout(timer); resolve(text); } }); const timer = setTimeout(() => reject(Error('Timed Out')), timeout); }); } finally { await browser.close(); } }
Disable chrome sandbox in tests
Disable chrome sandbox in tests
JavaScript
apache-2.0
GoogleChromeLabs/worker-plugin
e5954cf78a8daf138ca1a81ead64f1d38719a970
public/ssr.js
public/ssr.js
var ssr = require('done-ssr-middleware'); module.exports = ssr({ config: __dirname + "/package.json!npm", main: "bitcentive/index.stache!done-autorender", liveReload: true });
var ssr = require('done-ssr-middleware'); module.exports = ssr({ config: __dirname + "/package.json!npm", main: "bitcentive/index.stache!done-autorender", liveReload: true, auth: { cookie: "feathers-jwt", domains: [ "localhost" ] } });
Add auth-cookie options to SSR.
Add auth-cookie options to SSR.
JavaScript
mit
donejs/bitcentive,donejs/bitcentive
04fb2218cd6a5d32a0b4c1d8de9b9ad43994888d
src/api/routes/verifyGET.js
src/api/routes/verifyGET.js
const Route = require('../structures/Route'); class verifyGET extends Route { constructor() { super('/verify', 'get'); } run(req, res, user) { return res.json({ message: 'Successfully verified token', user }); } } module.exports = verifyGET;
const Route = require('../structures/Route'); class verifyGET extends Route { constructor() { super('/verify', 'get'); } run(req, res, user) { const returnUser = { id: user.id, username: user.username, apiKey: user.apiKey, isAdmin: user.isAdmin }; return res.json({ message: 'Successfully verified token', user: returnUser }); } } module.exports = verifyGET;
Return less info to the user when verifying
Return less info to the user when verifying
JavaScript
mit
WeebDev/lolisafe,WeebDev/lolisafe,WeebDev/loli-safe,WeebDev/loli-safe
79078552e7df6cb28ef277a2ecf46b9cacd1c7ee
lib/config/mongostore.js
lib/config/mongostore.js
'use strict'; /* ** Module dependencies */ var mongoose = require('mongoose'); var util = require('util'); var TTL = 24*3600; var Schema = new mongoose.Schema({ sid: { type: String, required: true, unique: true }, data: { type: mongoose.Schema.Types.Mixed, required: true }, usedAt: { type: Date, expires: TTL } }); var Session = mongoose.model('Session', Schema); module.exports = function(session) { var Store = session.Store; function Store(options) { Store.call(this, options); } util.inherits(Store, Store); Store.prototype.get = function(sid, done) { Session.findOne({ sid: sid }, function(err, session) { if (err) return done(err); if (!session) return done(null, false); done(null, session.data); }); }; Store.prototype.set = function(sid, data, done) { Session.update({ sid: sid }, { sid: sid, data: data, usedAt: new Date() }, { upsert: true }, done); }; Store.prototype.destroy = function(sid, done) { Session.remove({ sid: sid }, done); }; Store.prototype.clear = function(done) { Session.collection.drop(done); }; return Store; };
'use strict'; /* ** Module dependencies */ var mongoose = require('mongoose'); var util = require('util'); var TTL = 24*3600; var Schema = new mongoose.Schema({ sid: { type: String, required: true, unique: true }, data: { type: mongoose.Schema.Types.Mixed, required: true }, usedAt: { type: Date, expires: TTL } }); var Session = mongoose.model('Session', Schema); module.exports = function(session) { var Store = session.Store; function MongoStore(options) { Store.call(this, options); } util.inherits(Store, Store); MongoStore.prototype.get = function(sid, done) { Session.findOne({ sid: sid }, function(err, session) { if (err) return done(err); if (!session) return done(null, false); done(null, session.data); }); }; MongoStore.prototype.set = function(sid, data, done) { Session.update({ sid: sid }, { sid: sid, data: data, usedAt: new Date() }, { upsert: true }, done); }; MongoStore.prototype.destroy = function(sid, done) { Session.remove({ sid: sid }, done); }; MongoStore.prototype.clear = function(done) { Session.collection.drop(done); }; return Store; };
Rename Store into MongoStore to pass JSLint
Rename Store into MongoStore to pass JSLint
JavaScript
agpl-3.0
sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui
407a8292712cfa3cc6ae9957e6ba22ed1795ad28
addon/mixins/version-header-handler.js
addon/mixins/version-header-handler.js
import Ember from 'ember'; import config from 'ember-get-config'; const { 'ember-new-version-detection': { appName, }, } = config; const { computed, inject: { service, }, run: { next: runNext, }, Mixin, } = Ember; export default Mixin.create({ newVersionDetector: service(), headers: computed('newVersionDetector.reportedVersion', function() { let reportedVersion = this.get('newVersionDetector.reportedVersion'); return { 'X-App-Version': reportedVersion, 'X-App-Name': appName, }; }), handleResponse(_, headers) { runNext(this, function() { this.set('newVersionDetector.activeVersion', headers['X-Current-Version']); }); return this._super(...arguments); }, });
import Ember from 'ember'; import config from 'ember-get-config'; const { 'ember-new-version-detection': { appName, }, } = config; const { computed, inject: { service, }, run: { next: runNext, }, Mixin, } = Ember; export default Mixin.create({ newVersionDetector: service(), headers: computed('newVersionDetector.reportedVersion', function() { let headers = this._super(...arguments) || {}; headers['X-App-Version'] = this.get('newVersionDetector.reportedVersion'); headers['X-App-Name'] = appName; return headers; }), handleResponse(_, headers) { runNext(this, function() { this.set('newVersionDetector.activeVersion', headers['X-Current-Version']); }); return this._super(...arguments); }, });
Call _super so that we don't stomp on headers returned by other mixins
Call _super so that we don't stomp on headers returned by other mixins
JavaScript
mit
PrecisionNutrition/ember-new-version-detection,PrecisionNutrition/ember-new-version-detection,PrecisionNutrition/ember-new-version-detection,PrecisionNutrition/ember-new-version-detection
7168416a52b9b85f1bdee68614a6324f957b219d
app/assets/javascripts/main-buttons.js
app/assets/javascripts/main-buttons.js
/** * Created by mcgourtyalex on 4/14/15. */ var MainButtons = { // setup sets a callback for #breeder_find keyup setup: function() { $('.button-a').hover( function() { $('#tagline-text').html("Keep breeders <strong>honest</strong> by rating your pup"); }); $('.button-b').click( function() { $('.box-b').toggleClass("hidden"); }).hover( function() { $('#tagline-text').html("Find the <strong>right</strong> breed for you"); }); $('#cancel-b').click( function() { $('.box-b').toggleClass("hidden"); }); $('.button-c').click( function() { $('.box-c').toggleClass("hidden"); }).hover( function() { $('#tagline-text').html("Find a dog breeder with <strong>great</strong> reviews"); }); $('#cancel-c').click( function() { $('.box-c').toggleClass("hidden"); }); } }; $(document).ready(function () { $(MainButtons.setup); });
/** * Created by mcgourtyalex on 4/14/15. */ var MainButtons = { // setup sets a callback for #breeder_find keyup setup: function() { $('.button-a').hover( function() { $('#tagline-text').html("Contribute information about <strong>your<strong> dog to our database"); }); $('.button-b').click( function() { $('.box-b').toggleClass("hidden"); }).hover( function() { $('#tagline-text').html("Find the <strong>right</strong> breed for you"); }); $('#cancel-b').click( function() { $('.box-b').toggleClass("hidden"); }); $('.button-c').click( function() { $('.box-c').toggleClass("hidden"); }).hover( function() { $('#tagline-text').html("Find a dog breeder with <strong>great</strong> reviews"); }); $('#cancel-c').click( function() { $('.box-c').toggleClass("hidden"); }); } }; $(document).ready(function () { $(MainButtons.setup); });
Change text for hover over rate your pup
Change text for hover over rate your pup
JavaScript
mit
hyu596/Simpatico-Pup,hyu596/Simpatico-Pup,eabartlett/ratemypup,cjzcpsyx/rate-my-pup,cjzcpsyx/rate-my-pup,eabartlett/ratemypup,eabartlett/ratemypup,cjzcpsyx/rate-my-pup,cjzcpsyx/rate-my-pup,hyu596/Simpatico-Pup,eabartlett/ratemypup
fbd633276f7c5e126777838ec442c72aed5cfb88
django_fixmystreet/fixmystreet/static/js/leaflet/example/leaflet-dev.js
django_fixmystreet/fixmystreet/static/js/leaflet/example/leaflet-dev.js
function getRandomLatLng(map) { var bounds = map.getBounds(), southWest = bounds.getSouthWest(), northEast = bounds.getNorthEast(), lngSpan = northEast.lng - southWest.lng, latSpan = northEast.lat - southWest.lat; return new L.LatLng(southWest.lat + latSpan * Math.random(), southWest.lng + lngSpan * Math.random()); }
var STATIC_URL = 'http://127.0.0.1:8000/static/'; function getRandomLatLng(map) { var bounds = map.getBounds(), southWest = bounds.getSouthWest(), northEast = bounds.getNorthEast(), lngSpan = northEast.lng - southWest.lng, latSpan = northEast.lat - southWest.lat; return new L.LatLng(southWest.lat + latSpan * Math.random(), southWest.lng + lngSpan * Math.random()); } function gettext(s) { return s; }
Add constant & function for dev.
Add constant & function for dev.
JavaScript
agpl-3.0
IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet
e05370ea9c0a001cee9d9a20ec44e7ea212a3822
DynamixelServo.Quadruped.WebInterface/wwwroot/js/VideoStreaming.js
DynamixelServo.Quadruped.WebInterface/wwwroot/js/VideoStreaming.js
let videoImage = document.getElementById('video_image'); videoImage.src = `http://${document.domain}:8080/?action=stream`; let cameraJoystick = { zone: videoImage, color: 'red' }; let cameraJoystickManager = nipplejs.create(cameraJoystick); const clickTimeout = 500; var lastStartClick = Date.now(); cameraJoystickManager.on('added', function (evt, nipple) { nipple.on('move', function (evt, arg) { var json = JSON.stringify({ joystickType: 'camera', angle: arg.angle.radian, MessageType: 'movement', distance: arg.distance }); serverSocket.send(json); }); nipple.on('start', function () { if (lastStartClick - Date.now() < clickTimeout) { const json = JSON.stringify( { joystickType: 'camera', MessageType: 'reset' }); serverSocket.send(json); } else { const json = JSON.stringify( { joystickType: 'camera', MessageType: 'start' }); serverSocket.send(json); } lastStartClick = Date.now(); }); nipple.on('end', function () { var json = JSON.stringify({ joystickType: 'camera', MessageType: 'stop' }); serverSocket.send(json); }); });
let videoImage = document.getElementById('video_image'); videoImage.src = `http://${document.domain}:8080/?action=stream`; let cameraJoystick = { zone: videoImage, color: 'red' }; let cameraJoystickManager = nipplejs.create(cameraJoystick); const clickTimeout = 500; var lastStartClick = Date.now(); cameraJoystickManager.on('added', function (evt, nipple) { nipple.on('move', function (evt, arg) { var json = JSON.stringify({ joystickType: 'camera', angle: arg.angle.radian, MessageType: 'movement', distance: arg.distance }); serverSocket.send(json); }); nipple.on('start', function () { if (Date.now() - lastStartClick < clickTimeout) { const json = JSON.stringify( { joystickType: 'camera', MessageType: 'reset' }); serverSocket.send(json); } else { const json = JSON.stringify( { joystickType: 'camera', MessageType: 'start' }); serverSocket.send(json); } lastStartClick = Date.now(); }); nipple.on('end', function () { var json = JSON.stringify({ joystickType: 'camera', MessageType: 'stop' }); serverSocket.send(json); }); });
Fix but with reset always triggering
Fix but with reset always triggering
JavaScript
apache-2.0
dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo
ee692dc4d7321e7440b681c13ae82fdb8ed97516
app/assets/javascripts/angular/dramas/dramas-controller.js
app/assets/javascripts/angular/dramas/dramas-controller.js
App.controller('DramasCtrl', [ '$http', function($http, $q) { var dramas = this; dramas.list1 = 'Drag and Drop with default confirmation'; dramas.items = []; $http.get('/dramas').then(function(response) { dramas.items = response.data; console.log(response.data); }, function(errResponse) { console.error('Error while fetching dramas') }); dramas.beforeDrop = function() { var deferred = $q.defer(); if (confirm('Are you sure???')) { deferred.resolve(); } else { deferred.reject(); } return deferred.promise; }; }]);
(function(){ 'use strict'; angular .module('secondLead') .controller('DramasCtrl', [ 'DramaModel', 'Restangular', function(DramaModel, Restangular, $q) { var dramas = this; dramas.items = DramaModel.getAll; dramas.setCurrentDrama = function(item){ dramas.currentDrama = item; }; }]) })();
Update dramactrl to fetch dramas from api using restangular
Update dramactrl to fetch dramas from api using restangular
JavaScript
mit
ac-adekunle/secondlead,ac-adekunle/secondlead,ac-adekunle/secondlead
a8dde15447d79b73ca12a0a7acf2ff0390f24b49
web-client/app/scripts/controllers/profileController.js
web-client/app/scripts/controllers/profileController.js
'use strict'; angular.module('webClientApp') .controller('ProfileCtrl', ['$scope', '$rootScope', '$location', '$routeParams', 'UserArticle', 'UserDraft', 'User', function ($scope, $rootScope, $location, $routeParams, UserArticle, UserDraft, User) { $scope.user = User.get({'userId': $routeParams.userId}); // Only get drafts if the current profile being viewed and the logged in user // are the same person. if ($rootScope.currentUser.id === parseInt($routeParams.userId)) { $scope.drafts = UserDraft.query({}); } $scope.articles = UserArticle.query({'userId': $routeParams.userId}); }]);
'use strict'; angular.module('webClientApp') .controller('ProfileCtrl', ['$scope', '$rootScope', '$location', '$routeParams', 'UserArticle', 'UserDraft', 'User', function ($scope, $rootScope, $location, $routeParams, UserArticle, UserDraft, User) { $scope.user = User.get({'userId': $routeParams.userId}); // Only get drafts if the current profile being viewed and the logged in user // are the same person. if (($rootScope.currentUser && $rootScope.currentUser.id === parseInt($routeParams.userId))) { $scope.drafts = UserDraft.query({}); } $scope.articles = UserArticle.query({'userId': $routeParams.userId}); }]);
Fix non-logged in error when visiting a profile.
Fix non-logged in error when visiting a profile.
JavaScript
bsd-2-clause
ahmgeek/manshar,RashaHussein/manshar,mjalajel/manshar,manshar/manshar,ahmgeek/manshar,RashaHussein/manshar,manshar/manshar,ahmgeek/manshar,manshar/manshar,ahmgeek/manshar,mjalajel/manshar,RashaHussein/manshar,mjalajel/manshar,mjalajel/manshar,RashaHussein/manshar,manshar/manshar
fdaf5bc5b02619d65ee4a2ef2cf6dbef91e0d480
common/predictive-text/unit_tests/headless/worker-intialization.js
common/predictive-text/unit_tests/headless/worker-intialization.js
var assert = require('chai').assert; var worker = require('../../worker'); describe('Dummy worker', function() { describe('#hello()', function() { it('should return "hello"', function() { assert.equal(worker.hello(), 'hello'); }); }); });
var assert = require('chai').assert; var worker = require('../../worker'); describe('LMLayerWorker', function() { describe('#constructor()', function() { it('should construct with zero arguments', function() { assert.isOk(new worker.LMLayerWorker); }); }); });
Test whether the LMLayerWorker can be instantiated.
Test whether the LMLayerWorker can be instantiated.
JavaScript
apache-2.0
tavultesoft/keymanweb,tavultesoft/keymanweb
0241f074b65dbf70f10b5da6ddf0d3bfa161964f
api/src/pages/Html.js
api/src/pages/Html.js
import React, { PropTypes } from 'react' export default class Html extends React.Component { render ({ children, assets, title } = this.props) { return ( <html> <head> <title>{title}</title> <meta name='viewport' content='width=device-width, initial-scale=1' /> <link type='text/css' rel='stylesheet' href={`/${assets.app.css}`} /> <link rel='dns-prefetch' href='https://github.com/' /> <link rel='dns-prefetch' href='https://www.svager.cz/' /> <meta name='description' content='Analyze your site’s speed according to HTTP best practices.' /> <meta name='author' content='Jan Svager <https://www.svager.cz>' /> </head> <body> <div id='app' dangerouslySetInnerHTML={{ __html: children }} /> <script defer src={`/${assets.init.js}`} /> <script defer src={`/${assets.react.js}`} /> <script defer src={`/${assets.app.js}`} /> </body> </html> ) } } Html.propTypes = { children: PropTypes.node.isRequired, title: PropTypes.string.isRequired }
import React, { PropTypes } from 'react' export default class Html extends React.Component { render ({ children, assets, title } = this.props) { return ( <html lang='en'> <head> <title>{title}</title> <meta name='viewport' content='width=device-width, initial-scale=1' /> <link type='text/css' rel='stylesheet' href={`/${assets.app.css}`} /> <link rel='dns-prefetch' href='https://github.com/' /> <link rel='dns-prefetch' href='https://www.svager.cz/' /> <meta name='description' content='Analyze your site’s speed according to HTTP best practices.' /> <meta name='author' content='Jan Svager <https://www.svager.cz>' /> </head> <body> <div id='app' dangerouslySetInnerHTML={{ __html: children }} /> <script defer src={`/${assets.init.js}`} /> <script defer src={`/${assets.react.js}`} /> <script defer src={`/${assets.app.js}`} /> </body> </html> ) } } Html.propTypes = { children: PropTypes.node.isRequired, title: PropTypes.string.isRequired }
Add lang property to the html tag
Add lang property to the html tag
JavaScript
mit
svagi/httptest
9acffe52b1c8dcd806459968c03c96afaad9fb06
client/app/scripts/components/node-details/node-details-health-overflow-item.js
client/app/scripts/components/node-details/node-details-health-overflow-item.js
import React from 'react'; import metricFeeder from '../../hoc/metric-feeder'; import { formatMetric } from '../../utils/string-utils'; function NodeDetailsHealthOverflowItem(props) { return ( <div className="node-details-health-overflow-item"> <div className="node-details-health-overflow-item-value"> {formatMetric(props.value, props)} </div> <div className="node-details-health-overflow-item-label truncate">{props.label}</div> </div> ); } export default metricFeeder(NodeDetailsHealthOverflowItem);
import React from 'react'; import { formatMetric } from '../../utils/string-utils'; function NodeDetailsHealthOverflowItem(props) { return ( <div className="node-details-health-overflow-item"> <div className="node-details-health-overflow-item-value"> {formatMetric(props.value, props)} </div> <div className="node-details-health-overflow-item-label truncate">{props.label}</div> </div> ); } export default NodeDetailsHealthOverflowItem;
Remove the metricFeeder for the overflow items too for now.
Remove the metricFeeder for the overflow items too for now.
JavaScript
apache-2.0
dilgerma/scope,paulbellamy/scope,dilgerma/scope,kinvolk/scope,weaveworks/scope,weaveworks/scope,alban/scope,weaveworks/scope,weaveworks/scope,paulbellamy/scope,kinvolk/scope,kinvolk/scope,alban/scope,paulbellamy/scope,alban/scope,kinvolk/scope,dilgerma/scope,alban/scope,kinvolk/scope,paulbellamy/scope,alban/scope,weaveworks/scope,dilgerma/scope,weaveworks/scope,dilgerma/scope,dilgerma/scope,alban/scope,paulbellamy/scope,kinvolk/scope,paulbellamy/scope
364c445bab29675b8f0992efec57ca70ed6dd989
client/packages/settings-dashboard-extension-worona/src/dashboard/selectorCreators/index.js
client/packages/settings-dashboard-extension-worona/src/dashboard/selectorCreators/index.js
import { createSelector } from 'reselect'; import * as deps from '../deps'; import * as selectors from '../selectors'; export const getSettingsCreator = (packageName) => createSelector( selectors.getSettingsLiveCollection, deps.selectors.getSelectedSiteId, (settings, siteId) => ( settings.find( item => (item.woronaInfo.name === packageName && item.woronaInfo.siteId === siteId) ) || { woronaInfo: {} } // default to empty object til settings collections is loaded ) ); export const getSettingCreator = packageName => (settingName, settingDefault = undefined) => createSelector( getSettingsCreator(packageName), settings => (settings && settings[settingName]) || settingDefault );
import { createSelector } from 'reselect'; import * as deps from '../deps'; import * as selectors from '../selectors'; export const getSettings = packageNamespace => createSelector( selectors.getSettingsLiveCollection, deps.selectors.getSelectedSiteId, (settings, siteId) => settings.find( item => item.woronaInfo.namespace === packageNamespace && item.woronaInfo.siteId === siteId, ) || { woronaInfo: {} }, // default to empty object til settings collections is loaded ); export const getSetting = (packageNamespace, settingName, settingDefault = undefined) => createSelector( getSettings(packageNamespace), settings => settings && settings[settingName] || settingDefault, );
Change getSettings format to match app.
Change getSettings format to match app.
JavaScript
mit
worona/worona,worona/worona-dashboard,worona/worona-core,worona/worona,worona/worona-core,worona/worona,worona/worona-dashboard
e9a8702b3995781cb5ed6b8c2e746c360e36b812
src/js/directive/contacts.js
src/js/directive/contacts.js
'use strict'; var ngModule = angular.module('woDirectives'); ngModule.directive('keyfileInput', function() { return function(scope, elm) { elm.on('change', function(e) { for (var i = 0; i < e.target.files.length; i++) { importKey(e.target.files.item(i)); } }); function importKey(file) { var reader = new FileReader(); reader.onload = function(e) { scope.importKey(e.target.result); }; reader.readAsText(file); } }; });
'use strict'; var ngModule = angular.module('woDirectives'); ngModule.directive('keyfileInput', function() { return function(scope, elm) { elm.on('change', function(e) { for (var i = 0; i < e.target.files.length; i++) { importKey(e.target.files.item(i)); } elm.val(null); // clear input }); function importKey(file) { var reader = new FileReader(); reader.onload = function(e) { scope.importKey(e.target.result); }; reader.readAsText(file); } }; });
Clear file input after key import
[WO-927] Clear file input after key import
JavaScript
mit
whiteout-io/mail,dopry/mail-html5,sheafferusa/mail-html5,dopry/mail-html5,tanx/hoodiecrow,clochix/mail-html5,b-deng/mail-html5,dopry/mail-html5,tanx/hoodiecrow,dopry/mail-html5,whiteout-io/mail-html5,whiteout-io/mail-html5,clochix/mail-html5,whiteout-io/mail,whiteout-io/mail,sheafferusa/mail-html5,kalatestimine/mail-html5,b-deng/mail-html5,whiteout-io/mail-html5,clochix/mail-html5,kalatestimine/mail-html5,tanx/hoodiecrow,b-deng/mail-html5,whiteout-io/mail,b-deng/mail-html5,kalatestimine/mail-html5,sheafferusa/mail-html5,whiteout-io/mail-html5,sheafferusa/mail-html5,clochix/mail-html5,kalatestimine/mail-html5
cbccd67c481080e5e4d65d75dc03c57ea26de763
public/personality.controller.js
public/personality.controller.js
'use strict'; angular.module('personality.controller', []) .controller('PersonalityController', [ '$scope', '$http', 'personalityService', ($scope, $http, personalityService) => { $scope.roastOptions = [ 'light', 'medium', 'dark' ]; $scope.getData = () => { $http.put('/api/watson/' + $scope.twitter) .success(data => { $scope.array = data; $scope.preference = personalityService.determinePreference(data); $scope.curiosity = personalityService.getCuriosityPercentage(data); $scope.liberty = personalityService.getLibertyPercentage(data); }) .error(err => { console.log(err); }); }; $scope.submitFeedback = actualPreference => { $http .post('/api/feedback', { twitter_handle: $scope.twitter, expected_preference: $scope.preference, actual_preference: actualPreference }) .then(() => $scope.feedbackSubmitted = true); }; }]);
'use strict'; angular.module('personality.controller', []) .controller('PersonalityController', [ '$scope', '$http', 'personalityService', ($scope, $http, personalityService) => { $scope.roastOptions = [ 'light', 'medium', 'dark' ]; $scope.getData = () => { resetFeedback(); $http.put('/api/watson/' + $scope.twitter) .success(data => { $scope.array = data; $scope.preference = personalityService.determinePreference(data); $scope.curiosity = personalityService.getCuriosityPercentage(data); $scope.liberty = personalityService.getLibertyPercentage(data); }) .error(err => { console.log(err); }); }; $scope.submitFeedback = actualPreference => { $http .post('/api/feedback', { twitter_handle: $scope.twitter, expected_preference: $scope.preference, actual_preference: actualPreference }) .then(() => $scope.feedbackSubmitted = true); }; function resetFeedback() { $scope.feedbackSubmitted = false; $scope.showRoastFeedbackOptions = false; } }]);
Reset feedback on new submissions
Reset feedback on new submissions
JavaScript
mit
o3world/o3-barista,o3world/o3-barista
000f6aa302cda2e54d2e26ca85e28452dc50c382
src/js/modules/polyfills.js
src/js/modules/polyfills.js
require('svg4everybody')();
require('svg4everybody')(); if (!window.Element.prototype.matches) { window.Element.prototype.matches = window.Element.prototype.msMatchesSelector; }
Add Element.matches fix for IE
Add Element.matches fix for IE
JavaScript
mit
engageinteractive/front-end-baseplate,engageinteractive/core,engageinteractive/core,engageinteractive/front-end-baseplate,engageinteractive/front-end-baseplate
a093a6e38762c35091f46136942a3f469483de6b
app/models/session.js
app/models/session.js
import DS from 'ember-data'; import Session from 'exp-models/models/session'; export default Session.extend({ frameIndex: DS.attr(), surveyPage: DS.attr() });
import DS from 'ember-data'; import Session from 'exp-models/models/session'; export default Session.extend({ frameIndex: DS.attr({defaultValue: 0}), surveyPage: DS.attr({defaultValue: 0}) });
Set default frameIndex & surveyPage to 0
Set default frameIndex & surveyPage to 0
JavaScript
apache-2.0
CenterForOpenScience/isp,CenterForOpenScience/isp,CenterForOpenScience/isp
f9d943aa29eef1367e24e7815d0bc8970e98bd27
app/scripts/routes/application_route.js
app/scripts/routes/application_route.js
App.ApplicationRoute = Ember.Route.extend({ // admittedly, this should be in IndexRoute and not in the // top level ApplicationRoute; we're in transition... :-) model: function () { return ['red', 'yellow', 'blue']; } });
App.ApplicationRoute = Ember.Route.extend({ });
Remove old application route example
Remove old application route example
JavaScript
mit
rjsamson/ember-hapi-base
6334dd1cbe27a8b84df69cc8e450a92c637df3b7
setup.js
setup.js
'use strict'; var serialNumber = require('./index'); var fail = function (err) { console.error('Could not read serial number:', err); }; serialNumber(function (err) { if (process.platform !== 'win32' && err.toString().match(/Permission denied/i)) { [ '\x1B[7m' + // inverse style 'Your system requires root/administrative priviledge to access the serial number.' + '\x1B[27m', '\x1B[31m' + // red 'Attempting to run command with `sudo` and cache your serial for future use.' + '\x1B[39m', '\x1B[31m' + // red 'You will be prompted for password.' + '\x1B[39m' ].forEach(function (msg) {console.info(msg);}); serialNumber.useSudo(function (err, val) { if (err) {return fail(err);} require('fs').writeFile('cached', val, function (err) { if (err) { console.error('Could not write serial number cache file:', err); } else { // green console.info('\x1B[32m' + 'Successfully cached serial number' + '\x1B[39m'); } }); }); } else if (err) { fail(err); } });
'use strict'; var serialNumber = require('./index'); var fail = function (err) { console.error('Could not read serial number:', err); }; serialNumber(function (err) { if (process.platform !== 'win32' && err.toString().match(/Permission denied/i)) { [ '\x1B[7m' + // inverse style 'Your system requires root/administrative priviledge to access the serial number.' + '\x1B[27m', '\x1B[31m' + // red 'Attempting to run command with `sudo` and cache your serial for future use.' + '\x1B[39m' ].forEach(function (msg) {console.info(msg);}); serialNumber.useSudo(function (err, val) { if (err) {return fail(err);} require('fs').writeFile('cached', val, function (err) { if (err) { console.error('Could not write serial number cache file:', err); } else { // green console.info('\x1B[32m' + 'Successfully cached serial number' + '\x1B[39m'); } }); }); } else if (err) { fail(err); } });
Remove redundant console message about password prompt
Remove redundant console message about password prompt
JavaScript
isc
dcrystalj/serial-number,es128/serial-number