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
475b9aa8146e6e4307c0fac0df76e3810c4eb9d3
tests/unit/utils/round-number-test.js
tests/unit/utils/round-number-test.js
import roundNumber from 'dummy/utils/round-number'; import { module, test } from 'qunit'; module('Unit | Utility | round number'); test('it rounds a number to two decimal places by default', function(assert) { let result = roundNumber(123.123); assert.equal(result, 123.12); }); test('it rounds a number to a configurable number of decimal places', function(assert) { let result = roundNumber(123.123123, 1); assert.equal(result, 123.1); }); test('it returns undefined when nothing provided', function(assert) { let result = roundNumber(); assert.equal(result, undefined); }); test('it parses a String number', function(assert) { let result = roundNumber('34.3333'); assert.equal(result, 34.33); }); test('it returns undefined when provided a string that is not a number', function(assert) { let result = roundNumber('boogers'); assert.equal(result, undefined); });
import roundNumber from 'dummy/utils/round-number'; import { module, test } from 'qunit'; module('Unit | Utility | round number'); test('it rounds a number to two decimal places by default', function(assert) { let result = roundNumber(123.123); assert.equal(result, 123.12); }); test('it rounds a number to a configurable number of decimal places', function(assert) { let result = roundNumber(123.123123, 1); assert.equal(result, 123.1); }); test('it rounds a number to a whole number if precision is 0', function(assert) { let result = roundNumber(123.123123, 0); assert.equal(result, 123); }); test('it returns undefined when nothing provided', function(assert) { let result = roundNumber(); assert.equal(result, undefined); }); test('it parses a String number', function(assert) { let result = roundNumber('34.3333'); assert.equal(result, 34.33); }); test('it returns undefined when provided a string that is not a number', function(assert) { let result = roundNumber('boogers'); assert.equal(result, undefined); });
Add Unit Test For precision=0
Add Unit Test For precision=0
JavaScript
mit
PrecisionNutrition/unit-utils,PrecisionNutrition/unit-utils
09a038dde6ea453fafad4899c43746e461c24a40
test/index.js
test/index.js
var assert = require('chai').assert; var StorageService = require('../'); var AmazonStorage = StorageService.AmazonStorage; describe('Factory Method', function () { it('Should properly export', function () { assert.isObject(StorageService); assert.isFunction(StorageService.create); assert.isFunction(StorageService.AmazonStorage); }); it('Should properly create storage instances', function () { assert.instanceOf(StorageService.create('amazon'), AmazonStorage); }); });
var assert = require('chai').assert; var StorageService = require('../'); var AmazonStorage = StorageService.AmazonStorage; describe('Factory Method', function () { it('Should properly export', function () { assert.isObject(StorageService); assert.isFunction(StorageService.create); assert.isFunction(StorageService.AmazonStorage); }); it('Should properly create storage instances', function () { assert.instanceOf(StorageService.create('amazon'), AmazonStorage); }); it('Should properly throw error on unrecognized type', function () { assert.throws(function () { StorageService.create('NOT_EXISTS'); }, Error); }); });
Improve test coverage for StorageService
Improve test coverage for StorageService
JavaScript
mit
ghaiklor/sails-service-storage
fe00fb8e58535abb1818bcbe3dfb4a780c4d8558
providers/latest-provider/index.js
providers/latest-provider/index.js
import { useEffect, useMemo } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import reducerRegistry from 'redux/registry'; import * as actions from './actions'; import { getLatestProps } from './selectors'; import reducers, { initialState } from './reducers'; const LatestProvider = ({ latestEndpoints, getLatest }) => { const endpoint = useMemo(() => { return latestEndpoints; }, [latestEndpoints]); useEffect(() => { getLatest(endpoint); }, [endpoint]); return null; }; LatestProvider.propTypes = { getLatest: PropTypes.func.isRequired, latestEndpoints: PropTypes.array, }; reducerRegistry.registerModule('latest', { actions, reducers, initialState, }); export default connect(getLatestProps, actions)(LatestProvider);
import { PureComponent } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import reducerRegistry from 'redux/registry'; import isEqual from 'lodash/isEqual'; import * as actions from './actions'; import { getLatestProps } from './selectors'; import reducers, { initialState } from './reducers'; class LatestProvider extends PureComponent { componentDidUpdate(prevProps) { const { getLatest, latestEndpoints } = this.props; const { latestEndpoints: prevLatestEndpoints } = prevProps; if (!isEqual(latestEndpoints, prevLatestEndpoints)) { getLatest(latestEndpoints); } } render() { return null; } } LatestProvider.propTypes = { getLatest: PropTypes.func.isRequired, latestEndpoints: PropTypes.array, }; reducerRegistry.registerModule('latest', { actions, reducers, initialState, }); export default connect(getLatestProps, actions)(LatestProvider);
Fix loop if same provider endpoints
Fix loop if same provider endpoints
JavaScript
mit
Vizzuality/gfw,Vizzuality/gfw
6d3ae8de4e99fc2fb925b3a645b8549756ccdb11
website/mcapp.projects/src/app/project/home/mc-project-home-reminders.components.js
website/mcapp.projects/src/app/project/home/mc-project-home-reminders.components.js
class MCProjectHomeRemindersComponentController { /*@ngInject*/ constructor(projectsAPI) { this.projectsAPI = projectsAPI; } removeReminder(index) { this.project.reminders.splice(index, 1); } addReminder() { this.project.reminders.push({note: '', status: 'none'}); } updateReminders() { this.projectsAPI.updateProject(this.project.id, {reminders: this.project.reminders}); } } angular.module('materialscommons').component('mcProjectHomeReminders', { templateUrl: 'app/project/home/mc-project-home-reminders.html', controller: MCProjectHomeRemindersComponentController, bindings: { project: '<' } });
class MCProjectHomeRemindersComponentController { /*@ngInject*/ constructor(projectsAPI) { this.projectsAPI = projectsAPI; } removeReminder(index) { this.project.reminders.splice(index, 1); this.projectsAPI.updateProject(this.project.id, {reminders: this.project.reminders}); } addReminder() { this.project.reminders.push({note: '', status: 'none'}); } updateReminders() { this.projectsAPI.updateProject(this.project.id, {reminders: this.project.reminders}); } } angular.module('materialscommons').component('mcProjectHomeReminders', { templateUrl: 'app/project/home/mc-project-home-reminders.html', controller: MCProjectHomeRemindersComponentController, bindings: { project: '<' } });
Delete project reminder on backend
Delete project reminder on backend When a reminder is deleted on the front-end ensure that it is also deleted on the backend.
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
413642773139e4d18c3c07193a873f98136fbad8
src/components/panel/editForm/Panel.edit.display.js
src/components/panel/editForm/Panel.edit.display.js
export default [ { weight: 10, type: 'textfield', input: true, placeholder: 'Panel Title', label: 'Title', key: 'title', tooltip: 'The title text that appears in the header of this panel.' }, { weight: 20, type: 'textarea', input: true, key: 'tooltip', label: 'Tooltip', placeholder: 'To add a tooltip to this field, enter text here.', tooltip: 'Adds a tooltip to the side of this field.' }, { weight: 30, type: 'select', input: true, label: 'Theme', key: 'theme', dataSrc: 'values', data: { values: [ { label: 'Default', value: 'default' }, { label: 'Primary', value: 'primary' }, { label: 'Info', value: 'info' }, { label: 'Success', value: 'success' }, { label: 'Danger', value: 'danger' }, { label: 'Warning', value: 'warning' } ] } }, { weight: 40, type: 'select', input: true, label: 'Show Breadcrumb', key: 'breadcrumb', dataSrc: 'values', data: { values: [ { label: 'Yes', value: 'default' }, { label: 'No', value: 'none' } ] } } ];
export default [ { key: 'label', hidden: true, calculateValue: 'value = data.title' }, { weight: 1, type: 'textfield', input: true, placeholder: 'Panel Title', label: 'Title', key: 'title', tooltip: 'The title text that appears in the header of this panel.' }, { weight: 20, type: 'textarea', input: true, key: 'tooltip', label: 'Tooltip', placeholder: 'To add a tooltip to this field, enter text here.', tooltip: 'Adds a tooltip to the side of this field.' }, { weight: 30, type: 'select', input: true, label: 'Theme', key: 'theme', dataSrc: 'values', data: { values: [ { label: 'Default', value: 'default' }, { label: 'Primary', value: 'primary' }, { label: 'Info', value: 'info' }, { label: 'Success', value: 'success' }, { label: 'Danger', value: 'danger' }, { label: 'Warning', value: 'warning' } ] } }, { weight: 40, type: 'select', input: true, label: 'Show Breadcrumb', key: 'breadcrumb', dataSrc: 'values', data: { values: [ { label: 'Yes', value: 'default' }, { label: 'No', value: 'none' } ] } } ];
Hide the label settings for Panels since they have a title field.
Hide the label settings for Panels since they have a title field.
JavaScript
mit
formio/formio.js,formio/formio.js,formio/formio.js
ede88730cd71028cf01cd6a43d80e0b14622eccc
apps/jsgi/main.js
apps/jsgi/main.js
// start the web server. (we'll soon write a dedicated script to do this.) if (module.id === require.main) { require('ringo/httpserver').start(); }
// start the web server. (we'll soon write a dedicated script to do this.) if (module == require.main) { require('ringo/webapp').start(); }
Make jsgi demo app run again
Make jsgi demo app run again
JavaScript
apache-2.0
oberhamsi/ringojs,Transcordia/ringojs,ashwinrayaprolu1984/ringojs,ringo/ringojs,ashwinrayaprolu1984/ringojs,ashwinrayaprolu1984/ringojs,Transcordia/ringojs,ringo/ringojs,Transcordia/ringojs,Transcordia/ringojs,ringo/ringojs,ashwinrayaprolu1984/ringojs,oberhamsi/ringojs,oberhamsi/ringojs,ringo/ringojs
eb0bf2ff537bf74fc8027074380870d473af03b7
Restaurant.js
Restaurant.js
import React from 'react' import RestaurantModel from './RestaurantModel' class Restaurant extends React.Component { constructor(props) { super(props) this.displayName = "Restaurant" } render() { // helper for code simplicity. var model = this.props.model // Controller calculats food icon for HTML View presentation. var foodTypeImage = ""; if (model.foodType === "Burger") { foodTypeImage = "assets/img/Burger.png" } else { foodTypeImage = "http://placeponi.es/48/48" } // Prepare rating JSX var ratings = []; for (var i=0; i < model.rating; i++) { ratings.push(<span className="glyphicon glyphicon-star" key={i}/>); } return ( <li className="media" onClick={this.props.onClick}> <div className="media-left"> <img className="media-object" src={foodTypeImage} /> </div> <div className={"media-body" + (this.props.selected ? " selected" : "")}> <h4 className="media-heading">{model.name}</h4> <p> Rating: {ratings} </p> </div> </li> ) } } Restaurant.propTypes = { model: React.PropTypes.instanceOf(RestaurantModel) } Restaurant.defaultProps = { restaurant : new RestaurantModel("NameOfPlace", "Burger", 2, "Dubnov 7, Tel Aviv-Yafo, Israel") } export default Restaurant
import React from 'react' import RestaurantModel from './RestaurantModel' class Restaurant extends React.Component { constructor(props) { super(props) this.displayName = "Restaurant" } render() { // helper for code simplicity. var model = this.props.model // Controller calculats food icon for HTML View presentation. var foodTypeImage = ""; if (model.foodType === "Burger") { foodTypeImage = "assets/img/Burger.png" } else { foodTypeImage = "http://placeponi.es/48/48" } // Prepare rating JSX var ratings = []; for (var i=0; i < model.rating; i++) { ratings.push(<span className="glyphicon glyphicon-star" key={i}/>); } return ( <li className="media" onClick={this.props.onClick}> <div className="media-left"> <img className="media-object" src={foodTypeImage} /> </div> <div className={"media-body" + (this.props.selected ? " selected-restaurant-row" : "")}> <h4 className="media-heading">{model.name}</h4> <p> Rating: {ratings} </p> </div> </li> ) } } Restaurant.propTypes = { model: React.PropTypes.instanceOf(RestaurantModel) } Restaurant.defaultProps = { restaurant : new RestaurantModel("NameOfPlace", "Burger", 2, "Dubnov 7, Tel Aviv-Yafo, Israel") } export default Restaurant
Use better css selector naming.
Use better css selector naming. Fixes https://github.com/maximveksler/EatWell/pull/2#discussion_r60944809
JavaScript
apache-2.0
maximveksler/EatWell,maximveksler/EatWell
b02b5ddc87d50fd64808f54d026c3e5675fd9973
app/store/configureStore.js
app/store/configureStore.js
import { createStore, applyMiddleware } from 'redux' import rootReducer from '../reducers' import thunkMiddleware from 'redux-thunk' import createLogger from 'redux-logger' const loggerMiddleware = createLogger() export default function configureStore(initialState) { return createStore( rootReducer, applyMiddleware( thunkMiddleware, // lets us dispatch() functions loggerMiddleware // neat middleware that logs actions ), initialState ) }
import { createStore, applyMiddleware } from 'redux' import rootReducer from '../reducers' import thunkMiddleware from 'redux-thunk' import createLogger from 'redux-logger' const loggerMiddleware = createLogger() export default function configureStore(initialState) { const store = createStore( rootReducer, applyMiddleware( thunkMiddleware, // lets us dispatch() functions loggerMiddleware // neat middleware that logs actions ), initialState ) if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('../reducers', () => { const nextRootReducer = require('../reducers'); store.replaceReducer(nextRootReducer); }); } return store; }
Enable store module hot loading
Enable store module hot loading
JavaScript
mit
UCSD/campus-mobile,UCSD/campus-mobile,UCSD/campus-mobile,UCSD/now-mobile,UCSD/now-mobile,UCSD/now-mobile,UCSD/campus-mobile,UCSD/campus-mobile,UCSD/campus-mobile
90423ebf435d8c3dbb66af12729ad9d2a0475a0c
src/foam/apploader/ModelRefines.js
src/foam/apploader/ModelRefines.js
foam.CLASS({ package: 'foam.apploader', name: 'ModelRefines', refines: 'foam.core.Model', methods: [ { name: 'getClassDeps', code: function() { var deps = this.requires ? this.requires.map(function(r) { return r.path }) : []; deps = deps.concat(this.implements ? this.implements.map(function(i) { return i.path }) : []); if ( this.extends ) deps.push(this.extends); return deps; } }, ], });
foam.CLASS({ package: 'foam.apploader', name: 'ModelRefines', refines: 'foam.core.Model', methods: [ { name: 'getClassDeps', code: function() { var deps = this.requires ? this.requires.map(function(r) { return r.path }) : []; deps = deps.concat(this.implements ? this.implements.map(function(i) { return i.path }) : []); if ( this.extends ) deps.push(this.extends); if ( this.refines ) deps.push(this.refines); return deps.map(function(d) { if ( d.indexOf('.') == -1 ) return 'foam.core.' + d; return d; }); return deps; } }, ], });
Add refines to getClassDeps and prepend any deps with no package with 'foam.core.'
Add refines to getClassDeps and prepend any deps with no package with 'foam.core.'
JavaScript
apache-2.0
jacksonic/vjlofvhjfgm,jacksonic/vjlofvhjfgm,foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2,foam-framework/foam2,foam-framework/foam2,foam-framework/foam2
3c48a5d5af10d9b9d6a13fcde859b1d7d91f70e5
commands/randomness_commands.js
commands/randomness_commands.js
module.exports = { factcheck: (message, _, msg) => { const bool1 = (Math.random() > 0.5); const bool2 = (Math.random() > 0.5); let str; if (msg) { str = `${message.author}'s claim, "${msg}",`; str = bool1 ? `${str} is obviously ${bool2.toString()}.` : `${str} can't possibly be ${bool2.toString()}.`; } else { str = bool1 ? `${message.author} is always ${bool2 ? 'right' : 'wrong'}.` : `${message.author} is never ${bool2 ? 'right' : 'wrong'}.`; } message.channel.send(str); }, coin: (message) => { const bool = (Math.random() > 0.5); message.channel.send(bool ? 'Heads.' : 'Tails.'); }, dice: (message, _, __, n) => { n = Math.max(Number(n), 0) || 6; message.channel.send(Math.floor(Math.random() * n) + 1) .catch(() => message.channel.send('Input a valid number!')); }, };
module.exports = { factcheck: (message, _, msg) => { const bool1 = (Math.random() > 0.5); const bool2 = (Math.random() > 0.5); let str; if (msg) { str = `${message.author}'s claim, "${msg}",`; str = bool1 ? `${str} is obviously ${bool2.toString()}.` : `${str} can't possibly be ${bool2.toString()}.`; } else { str = bool1 ? `${message.author} is always ${bool2 ? 'right' : 'wrong'}.` : `${message.author} is never ${bool2 ? 'right' : 'wrong'}.`; } message.channel.send(str); }, coin: (message) => { const bool = (Math.random() > 0.5); const headsUrl = 'http://www.antheads.co.uk/_/rsrc/1467896244461/catguide/heads/Heads-21-30.jpg'; const tailsUrl = 'https://upload.wikimedia.org/wikipedia/en/7/73/Sonicchannel_tails_cg.png'; message.channel.send(bool ? `Heads.\n${headsUrl}` : `Tails.\n${tailsUrl}`); }, dice: (message, _, __, n) => { n = Math.max(Number(n), 0) || 6; message.channel.send(Math.floor(Math.random() * n) + 1) .catch(() => message.channel.send('Input a valid number!')); }, };
Add images to coin command
Add images to coin command
JavaScript
mit
Rafer45/soup
6489f67e37a39828a2553c0913c4f1ee5b201835
test/let_tests.js
test/let_tests.js
var expect = require('chai').expect; describe('let', function() { it('variables declared with let are accessible within nested blocks', function() { 'use strict'; let foo = 'bar'; if (true) { expect(foo).to.equal('bar'); } }); });
'use strict'; var expect = require('chai').expect; describe('let', function() { it('variables declared with let are accessible within nested blocks', function() { let foo = 'bar'; if (true) { expect(foo).to.equal('bar'); } }); });
Use string for all tests
Use string for all tests
JavaScript
mit
chrisneave/es2015-demo
5ec387aa829d0f9bef9b1e2871491c4c30fcf188
shells/browser/shared/src/renderer.js
shells/browser/shared/src/renderer.js
/** * In order to support reload-and-profile functionality, the renderer needs to be injected before any other scripts. * Since it is a complex file (with imports) we can't just toString() it like we do with the hook itself, * So this entry point (one of the web_accessible_resources) provcides a way to eagerly inject it. * The hook will look for the presence of a global __REACT_DEVTOOLS_ATTACH__ and attach an injected renderer early. * The normal case (not a reload-and-profile) will not make use of this entry point though. * * @flow */ import { attach } from 'src/backend/renderer'; Object.defineProperty( window, '__REACT_DEVTOOLS_ATTACH__', ({ enumerable: false, get() { return attach; }, }: Object) );
/** * In order to support reload-and-profile functionality, the renderer needs to be injected before any other scripts. * Since it is a complex file (with imports) we can't just toString() it like we do with the hook itself, * So this entry point (one of the web_accessible_resources) provcides a way to eagerly inject it. * The hook will look for the presence of a global __REACT_DEVTOOLS_ATTACH__ and attach an injected renderer early. * The normal case (not a reload-and-profile) will not make use of this entry point though. * * @flow */ import { attach } from 'src/backend/renderer'; Object.defineProperty( window, '__REACT_DEVTOOLS_ATTACH__', ({ enumerable: false, configurable: true, get() { return attach; }, }: Object) );
Mark reload-and-profile attach as configurable
Mark reload-and-profile attach as configurable
JavaScript
mit
rickbeerendonk/react,billfeller/react,chenglou/react,billfeller/react,acdlite/react,acdlite/react,trueadm/react,flarnie/react,acdlite/react,glenjamin/react,yungsters/react,terminatorheart/react,camsong/react,tomocchino/react,Simek/react,mjackson/react,tomocchino/react,trueadm/react,TheBlasfem/react,rickbeerendonk/react,mosoft521/react,yungsters/react,chenglou/react,billfeller/react,ericyang321/react,facebook/react,ericyang321/react,jzmq/react,tomocchino/react,mosoft521/react,mjackson/react,flarnie/react,billfeller/react,jzmq/react,mosoft521/react,cpojer/react,TheBlasfem/react,chenglou/react,camsong/react,glenjamin/react,Simek/react,chenglou/react,facebook/react,tomocchino/react,ArunTesco/react,chicoxyzzy/react,jzmq/react,rricard/react,rickbeerendonk/react,TheBlasfem/react,camsong/react,ericyang321/react,mjackson/react,trueadm/react,terminatorheart/react,mosoft521/react,rickbeerendonk/react,facebook/react,Simek/react,mosoft521/react,terminatorheart/react,terminatorheart/react,ArunTesco/react,ericyang321/react,tomocchino/react,flarnie/react,cpojer/react,flarnie/react,tomocchino/react,chicoxyzzy/react,rricard/react,rricard/react,facebook/react,flarnie/react,rickbeerendonk/react,chenglou/react,yungsters/react,terminatorheart/react,trueadm/react,cpojer/react,yungsters/react,ArunTesco/react,mjackson/react,ericyang321/react,rricard/react,glenjamin/react,trueadm/react,cpojer/react,jzmq/react,billfeller/react,Simek/react,cpojer/react,rricard/react,chicoxyzzy/react,mosoft521/react,glenjamin/react,camsong/react,chicoxyzzy/react,facebook/react,trueadm/react,rickbeerendonk/react,TheBlasfem/react,Simek/react,chicoxyzzy/react,rricard/react,billfeller/react,jzmq/react,cpojer/react,jzmq/react,chenglou/react,glenjamin/react,acdlite/react,flarnie/react,chicoxyzzy/react,terminatorheart/react,acdlite/react,yungsters/react,mjackson/react,acdlite/react,ericyang321/react,rickbeerendonk/react,chicoxyzzy/react,yungsters/react,cpojer/react,glenjamin/react,billfeller/react,jzmq/react,camsong/react,glenjamin/react,acdlite/react,Simek/react,chenglou/react,facebook/react,Simek/react,flarnie/react,camsong/react,camsong/react,facebook/react,tomocchino/react,yungsters/react,mosoft521/react,trueadm/react,mjackson/react,ericyang321/react,TheBlasfem/react,mjackson/react,TheBlasfem/react
d4aea530dd9588dd23cfb0a914be138626a4bd43
input/fixture.js
input/fixture.js
'use strict'; /* eslint-disable indent */ module.exports = function(tx) { var body = tx.get('body'); tx.create({ id: 'title', type: 'heading', level: 1, content: 'Input Element' }); body.show('title'); tx.create({ id: 'intro', type: 'paragraph', content: [ "You can use custom elements with an HTML input element" ].join('') }); body.show('intro'); tx.create({ type: 'input', id: 'input', content: 'Lorem ipsum...' }); body.show('input'); tx.create({ id: 'the-end', type: 'paragraph', content: [ "That's it." ].join('') }); body.show('the-end'); };
'use strict'; /* eslint-disable indent */ module.exports = function(tx) { var body = tx.get('body'); tx.create({ id: 'title', type: 'heading', level: 1, content: 'Input Element' }); body.show('title'); tx.create({ id: 'intro', type: 'paragraph', content: [ "You can use custom elements with an HTML input element" ].join('') }); body.show('intro'); tx.create({ type: 'input', id: 'input', content: 'Lorem ipsum...' }); body.show('input'); tx.create({ id: 'the-end', type: 'paragraph', content: [ "That way you can implement editor functionality using class web development practices." ].join('') }); body.show('the-end'); };
Add more description to input example.
Add more description to input example.
JavaScript
mit
philschatz/substance-editor,substance/examples,substance/examples,philschatz/substance-editor,substance/demos,substance/demos
f5ae5d64c43915af9e2da0ab1f1c08c94b7249e1
app/containers/NavigationContainer/sagas.js
app/containers/NavigationContainer/sagas.js
// import { take, call, put, select } from 'redux-saga/effects'; import { REQUEST_TOPICS } from './constants'; import { takeLatest } from 'redux-saga'; import { call } from 'redux-saga/effects'; export function fetchTopicsFromServer() { return fetch('http://locahost:3000/api/topics') .then(response => response.json()); } // Generator functions: do async logic without // using callbacks. function* fetchTopics() { const topics = yield call(fetchTopicsFromServer); console.log('Topics from server: ', topics); } export function* fetchTopicsSaga() { yield* takeLatest(REQUEST_TOPICS, fetchTopics); } // All sagas to be loaded export default [ fetchTopicsSaga, ];
// import { take, call, put, select } from 'redux-saga/effects'; import { REQUEST_TOPICS } from './constants'; import { takeLatest } from 'redux-saga'; import { call, put } from 'redux-saga/effects'; import { requestTopicsSucceeded, requestTopicsFailed } from './actions'; export function fetchTopicsFromServer() { return fetch('http://localhost:3000/api/topics') .then(response => response.json()); } // Generator functions: do async logic without // using callbacks. function* fetchTopics() { try { const topics = yield call(fetchTopicsFromServer); yield put(requestTopicsSucceeded(topics)); } catch (e) { yield put(requestTopicsFailed(e.message)); } } export function* fetchTopicsSaga() { yield* takeLatest(REQUEST_TOPICS, fetchTopics); } // All sagas to be loaded export default [ fetchTopicsSaga, ];
Handle response from server in saga
Handle response from server in saga
JavaScript
mit
GeertHuls/react-async-saga-example,GeertHuls/react-async-saga-example
9703839e2484f4bd603c65f02ca6ca3dad30f2d2
src/main/webapp/js/imcms/components/imcms_displacing_array.js
src/main/webapp/js/imcms/components/imcms_displacing_array.js
/** * Array with fixed max length and displacing first element on oversize. * * @author Serhii Maksymchuk from Ubrainians for imCode * 10.05.18 */ Imcms.define('imcms-displacing-array', [], function () { var DisplacingArray = function (size) { if (typeof size !== 'number') throw new Error("Size should be integer!"); if (size < 1) throw new Error("Size should be >= 1"); this.size = size; this.elements = []; }; DisplacingArray.prototype = { push: function (content) { if (this.elements.length > this.size) { this.elements.splice(0, 1); // removes first element } this.elements.push(content); }, forEach: function (doForEach) { this.elements.forEach(doForEach); } }; return DisplacingArray; });
/** * Array with fixed max length and displacing first element on oversize. * * @author Serhii Maksymchuk from Ubrainians for imCode * 10.05.18 */ Imcms.define('imcms-displacing-array', [], function () { var DisplacingArray = function (size) { if (typeof size !== 'number') throw new Error("Size should be integer!"); if (size < 1) throw new Error("Size should be >= 1"); this.size = size; this.elements = []; }; DisplacingArray.prototype = { push: function (content) { if (this.elements.length > this.size) { this.elements.splice(0, 1); // removes first element } this.elements.push(content); this.length = this.elements.length; }, forEach: function (doForEach) { this.elements.forEach(doForEach); } }; return DisplacingArray; });
Add a "pin" icon to imCMS's panel: - Refreshing elements length for displacing array.
IMCMS-290: Add a "pin" icon to imCMS's panel: - Refreshing elements length for displacing array.
JavaScript
agpl-3.0
imCodePartnerAB/imcms,imCodePartnerAB/imcms,imCodePartnerAB/imcms
d9a3ed959f61ddf0af6a393305486cfd02ac988d
js/shiv-test-util.js
js/shiv-test-util.js
if (!shiv) { throw(new Error("Don't load this file directly! Use shiv.load()")); } shiv.test( "shiv.map", function() { return shiv.map([1,2,3], function(x) { return x * 2; }); }, function(res) { return ( (res[0] == 1) && (res[1] == 4) && (res[2] == 6) ); } );
if (!shiv) { throw(new Error("Don't load this file directly! Use shiv.load()")); } shiv.test( "shiv.map", function() { return shiv.map([1,2,3], function(x) { return x * 2; }); }, function(res) { // // Array equality has to be tested element by element in JS // return ( (res[0] == 1) && (res[1] == 4) && (res[2] == 6) ); } );
Comment added to shiv.map test
Comment added to shiv.map test
JavaScript
mit
michiel/shivjs
e033432500d70b2a0ea04fd0548a665d6ec4bf2f
api/src/lib/form-handler.js
api/src/lib/form-handler.js
const logger = require('./logger'); module.exports = ( userService, themeService, clientService ) => { return (templateName, getView, postHandler) => async (request, reply, source, error) => { if (error && error.output.statusCode === 404) { reply(error); } try { const client = await clientService.findById(request.query.client_id); let user = null; if (request.auth.isAuthenticated) { user = request.auth.strategy === 'email_token' ? request.auth.credentials.user : await userService.findById(request.auth.credentials.accountId()); } const render = async e => { const viewContext = getView(user, client, request, e); const template = await themeService.renderThemedTemplate(request.query.client_id, templateName, viewContext); if (template) { reply(template); } else { reply.view(templateName, viewContext); } } if (!error && request.method === 'post') { error = await postHandler(request, reply, user, client, render); } else { await render(error); } } catch(e) { reply(e); } }; }; module.exports['@singleton'] = true; module.exports['@require'] = [ 'user/user-service', 'theme/theme-service', 'client/client-service', ];
const logger = require('./logger'); module.exports = ( userService, themeService, clientService ) => { return (templateName, getView, postHandler) => async (request, reply, source, error) => { if (error && error.output.statusCode === 404) { return reply(error); } try { const client = await clientService.findById(request.query.client_id); let user = null; if (request.auth.isAuthenticated) { user = request.auth.strategy === 'email_token' ? request.auth.credentials.user : await userService.findById(request.auth.credentials.accountId()); } const render = async e => { const viewContext = getView(user, client, request, e); const template = await themeService.renderThemedTemplate(request.query.client_id, templateName, viewContext); if (template) { return reply(template); } else { return reply.view(templateName, viewContext); } } if (!error && request.method === 'post') { error = await postHandler(request, reply, user, client, render); } else { await render(error); } } catch(e) { return reply(e); } }; }; module.exports['@singleton'] = true; module.exports['@require'] = [ 'user/user-service', 'theme/theme-service', 'client/client-service', ];
Add return to replies so they don't get called multiple times
Add return to replies so they don't get called multiple times
JavaScript
mit
synapsestudios/oidc-platform,synapsestudios/oidc-platform,synapsestudios/oidc-platform,synapsestudios/oidc-platform
33b118bba40c4cd86e6bef67d375422e9bb02490
src/actions/settings.js
src/actions/settings.js
import * as types from './types'; export function updateField(key, value) { return { type: types.SETTING_UPDATE, payload: { key, value, }, }; }
import { CHECKBOX_UPDATE, RANGE_UPDATE, FUZZY, } from './types'; export function updateCheckbox(key, value) { return { type: CHECKBOX_UPDATE, payload: { key, value, }, }; } export function updateFuzzyCheckbox(key, value) { return { type: FUZZY + CHECKBOX_UPDATE, payload: { key, value, }, }; } export function updateFuzzyRange(key, value) { return { type: FUZZY + RANGE_UPDATE, payload: { key, value, }, }; }
Add actions for handling setting state in the background
Add actions for handling setting state in the background
JavaScript
mit
reblws/tab-search,reblws/tab-search
469dc586285709a67cd2b1ebc0470df9baba5a90
packages/react-proxy/modules/requestForceUpdateAll.js
packages/react-proxy/modules/requestForceUpdateAll.js
var deepForceUpdate = require('./deepForceUpdate'); var isRequestPending = false; module.exports = function requestForceUpdateAll(getRootInstances, React) { if (isRequestPending) { return; } /** * Forces deep re-render of all mounted React components. * Hat's off to Omar Skalli (@Chetane) for suggesting this approach: * https://gist.github.com/Chetane/9a230a9fdcdca21a4e29 */ function forceUpdateAll() { isRequestPending = false; var rootInstances = getRootInstances(), rootInstance; for (var key in rootInstances) { if (rootInstances.hasOwnProperty(key)) { deepForceUpdate(rootInstances[key], React); } } } setTimeout(forceUpdateAll); };
var deepForceUpdate = require('./deepForceUpdate'); var isRequestPending = false; module.exports = function requestForceUpdateAll(getRootInstances, React) { if (isRequestPending) { return; } /** * Forces deep re-render of all mounted React components. * Hat's off to Omar Skalli (@Chetane) for suggesting this approach: * https://gist.github.com/Chetane/9a230a9fdcdca21a4e29 */ function forceUpdateAll() { isRequestPending = false; var rootInstances = getRootInstances(), rootInstance; for (var key in rootInstances) { if (rootInstances.hasOwnProperty(key)) { rootInstance = rootInstances[key]; // `|| rootInstance` for React 0.12 and earlier rootInstance = rootInstance._reactInternalInstance || rootInstance; deepForceUpdate(rootInstance, React); } } } setTimeout(forceUpdateAll); };
Fix usage with external React on 0.13+
Fix usage with external React on 0.13+
JavaScript
mit
gaearon/react-hot-loader,gaearon/react-hot-loader
8c69a9c5faf7d8a6238be02fca5b026e33dede48
adapters/axios.js
adapters/axios.js
require('native-promise-only'); var axios = require('axios'); var Axios = function(settings) { return new Promise(function(resolve, reject) { var options = { method: settings.type.toLowerCase(), url: settings.url, responseType: "text" }; if (settings.headers) { options.headers = settings.headers; } if (settings.processData) { options.params = settings.data; } else { options.data = settings.data; } return axios(options).then(function(response) { settings.success(response.data); return resolve(response); }).catch(function(response) { var error = response.data || response; settings.error(error); return reject(response); }); }); }; module.exports = Axios;
var extend = require('../utils').extend; require('native-promise-only'); var axios = require('axios'); var Axios = function(settings) { return new Promise(function(resolve, reject) { var options = { method: settings.type.toLowerCase(), url: settings.url, responseType: "text", headers: { 'Content-Type': 'application/json;charset=utf-8' } }; if (settings.headers) { options.headers = extend(options.headers, settings.headers); } if (settings.processData) { options.params = settings.data; } else { options.data = settings.data; } return axios(options).then(function(response) { settings.success(response.data); return resolve(response); }).catch(function(response) { var error = response.data || response; settings.error(error); return reject(response); }); }); }; module.exports = Axios;
Use application/json as default content-type with Axios
Use application/json as default content-type with Axios
JavaScript
mit
hoppula/vertebrae,hoppula/vertebrae
d87500c1aadbfb56a059a8855c79448a11ed9d99
tests/integration/components/froala-content-test.js
tests/integration/components/froala-content-test.js
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; module('Integration | Component | froala-content', function(hooks) { setupRenderingTest(hooks); test('.fr-view class is applied', async function(assert) { await render(hbs`{{froala-content elementId="editor"}}`); assert.ok(this.$('#editor').hasClass('fr-view')); }); test("'content' is output inside the block", async function(assert) { await render(hbs`{{froala-content content="foobar"}}`); assert.equal(this.element.textContent.trim(), 'foobar'); }); test("positional param 'content' is output inside the block", async function(assert) { await render(hbs`{{froala-content "foobar"}}`); assert.equal(this.element.textContent.trim(), 'foobar'); }); test("block content is properly yield'ed", async function(assert) { await render(hbs`{{#froala-content}}foobar{{/froala-content}}`); assert.equal(this.element.textContent.trim(), 'foobar'); }); });
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import $ from 'jquery'; module('Integration | Component | froala-content', function(hooks) { setupRenderingTest(hooks); test('.fr-view class is applied', async function(assert) { await render(hbs`{{froala-content elementId="editor"}}`); assert.ok($('#editor', this.element).hasClass('fr-view')); }); test("'content' is output inside the block", async function(assert) { await render(hbs`{{froala-content content="foobar"}}`); assert.equal(this.element.textContent.trim(), 'foobar'); }); test("positional param 'content' is output inside the block", async function(assert) { await render(hbs`{{froala-content "foobar"}}`); assert.equal(this.element.textContent.trim(), 'foobar'); }); test("block content is properly yield'ed", async function(assert) { await render(hbs`{{#froala-content}}foobar{{/froala-content}}`); assert.equal(this.element.textContent.trim(), 'foobar'); }); });
Remove usage of ember jquery integration in tests
Remove usage of ember jquery integration in tests Note, the ember-jquery addon re-enables usage of this.$() within components without a depreciation warning. https://deprecations.emberjs.com/v3.x/#toc_jquery-apis
JavaScript
mit
Panman8201/ember-froala-editor,froala/ember-froala-editor,froala/ember-froala-editor,Panman8201/ember-froala-editor
82c9a371707bd8d85b1f6ebf0004bdfccde4f231
src/app/index.module.js
src/app/index.module.js
/* global malarkey:false, toastr:false, moment:false */ import config from './index.config'; import routerConfig from './index.route'; import runBlock from './index.run'; import MainController from './main/main.controller'; import GithubContributorService from '../app/components/githubContributor/githubContributor.service'; import WebDevTecService from '../app/components/webDevTec/webDevTec.service'; import NavbarDirective from '../app/components/navbar/navbar.directive'; import MalarkeyDirective from '../app/components/malarkey/malarkey.directive'; import './bookmarks/bookmarks.module'; angular.module('ngBookmarks', ['restangular', 'ngRoute', 'ui.bootstrap', 'bookmarks']) .constant('malarkey', malarkey) .constant('toastr', toastr) .constant('moment', moment) .config(config) .config(routerConfig) .run(runBlock) .service('githubContributor', GithubContributorService) .service('webDevTec', WebDevTecService) .controller('MainController', MainController) .directive('acmeNavbar', () => new NavbarDirective()) .directive('acmeMalarkey', () => new MalarkeyDirective(malarkey));
/* global malarkey:false, toastr:false, moment:false */ import config from './index.config'; import routerConfig from './index.route'; import runBlock from './index.run'; import MainController from './main/main.controller'; import GithubContributorService from '../app/components/githubContributor/githubContributor.service'; import WebDevTecService from '../app/components/webDevTec/webDevTec.service'; import NavbarDirective from '../app/components/navbar/navbar.directive'; import MalarkeyDirective from '../app/components/malarkey/malarkey.directive'; import './bookmarks/bookmarks.module'; angular.module('ngBookmarks', ['ngRoute', 'ui.bootstrap', 'bookmarks']) .constant('malarkey', malarkey) .constant('toastr', toastr) .constant('moment', moment) .config(config) .config(routerConfig) .run(runBlock) .service('githubContributor', GithubContributorService) .service('webDevTec', WebDevTecService) .controller('MainController', MainController) .directive('acmeNavbar', () => new NavbarDirective()) .directive('acmeMalarkey', () => new MalarkeyDirective(malarkey));
Remove 'restangular' as a direct dependency of the top level app
Remove 'restangular' as a direct dependency of the top level app
JavaScript
mit
tekerson/ng-bookmarks,tekerson/ng-bookmarks
231c2560393d2766e924fed02b4a2268aa6e1dc7
lib/tasks/extra/DocTask.js
lib/tasks/extra/DocTask.js
"use strict"; const Task = require('../Task'), gulp = require('gulp'), mocha = require('gulp-mocha'), fs = require('fs'); class DocTask extends Task { constructor(buildManager) { super(buildManager); this.command = "doc"; } action() { //Dirty trick to capture Mocha output into a file //since gulp-mocha does not pipe the test output fs.writeFileSync('./doc.html', ''); var originalWrite = process.stdout.write; process.stdout.write = function (chunk) { var textChunk = chunk.toString('utf8'); if (!textChunk.match(/finished.+after/gmi)) { fs.appendFile('./doc.html', chunk); } originalWrite.apply(this, arguments); }; return gulp.src(this._buildManager.options.test, {read: false}) .pipe(mocha({reporter: 'doc'})); } } module.exports = DocTask;
"use strict"; const Task = require('../Task'), gulp = require('gulp'), mocha = require('gulp-mocha'), fs = require('fs'); class DocTask extends Task { constructor(buildManager) { super(buildManager); this.command = "doc"; } action() { //Dirty trick to capture Mocha output into a file //since gulp-mocha does not pipe the test output fs.writeFileSync('./doc.html', ''); var originalWrite = process.stdout.write; process.stdout.write = function (chunk) { var textChunk = chunk.toString('utf8'); if (!textChunk.match(/finished.+after/gmi)) { fs.appendFile('./doc.html', chunk); } originalWrite.apply(this, arguments); }; return gulp.src(this._buildManager.options.test, {read: false}) .pipe(mocha({ reporter: 'doc', compilers: { ts: require('ts-node/register'), js: require('babel-core/register') } })); } } module.exports = DocTask;
Add compilers to doc task
Add compilers to doc task
JavaScript
mit
mtfranchetto/smild,mtfranchetto/smild,mtfranchetto/smild
76813e0e74d12a2ec47830b811fd143f0f1a6781
zoltar/zoltar.js
zoltar/zoltar.js
// Module for interacting with zoltar const rp = require('request-promise-native') const buildUrl = require('build-url') async function get (url) { return rp(url, { json: true }) } async function gets (url) { return rp(url, { json: false }) } function proxifyObject (obj, root) { let handler = { get(target, propKey, receiver) { let value = target[propKey] if (typeof value === 'string' && (value.toString()).startsWith(root)) { return (async () => { let resp = await get(value) return proxifyObject(resp, root) })() } else if (typeof value === 'object') { return proxifyObject(value, root) } else { return value } } } return new Proxy(obj, handler) } function zoltar (rootUrl) { let baseObject = { projects: `${rootUrl}/projects` } return proxifyObject(baseObject, rootUrl) } module.exports.zoltar = zoltar
// Module for interacting with zoltar const rp = require('request-promise-native') const buildUrl = require('build-url') async function get (url) { return rp(url, { json: true }) } async function gets (url) { return rp(url, { json: false }) } function proxifyObject (obj, root) { let handler = { get(target, propKey, receiver) { let value = target[propKey] switch (propKey.toString()) { case 'url': return value case 'csv': { if ('forecast_data' in target) { return (async () => { let resp = await gets(`${target['forecast_data']}?format=csv`) return resp })() } else { throw new Error('This is not a forecast object') } } } if (typeof value === 'string' && (value.toString()).startsWith(root)) { return (async () => { let resp = await get(value) return proxifyObject(resp, root) })() } else if (typeof value === 'object') { return proxifyObject(value, root) } else { return value } } } return new Proxy(obj, handler) } function zoltar (rootUrl) { let baseObject = { projects: `${rootUrl}/projects` } return proxifyObject(baseObject, rootUrl) } module.exports.zoltar = zoltar
Handle url and csv getters separately
Handle url and csv getters separately
JavaScript
mit
reichlab/flusight,reichlab/flusight,reichlab/flusight
c3888cc45823cb0bb5112b8e20eaacbf7ff58d7b
app/assets/javascripts/angular/common/services/auth-service.js
app/assets/javascripts/angular/common/services/auth-service.js
(function(){ 'use strict'; angular.module('secondLead.common') .factory('Auth', ['$http', 'store', function($http, store) { return { isAuthenticated: function() { return store.get('jwt'); }, login: function(credentials) { var login = $http.post('/auth/login', credentials); login.success(function(result) { store.set('jwt', result.token); store.set('user', result.user); }); return login; }, logout: function() { store.remove('jwt'); store.remove('user'); } }; }]) })();
(function(){ 'use strict'; angular.module('secondLead.common') .factory('Auth', ['$http', 'store', function($http, store) { return { isAuthenticated: function() { return store.get('jwt'); }, login: function(credentials) { var login = $http.post('/auth/login', credentials); login.success(function(result) { store.set('jwt', result.token); store.set('user', result.user); }); return login; }, logout: function() { var clearJWT = store.remove('jwt'); var clearUser = store.remove('user'); return { jwt: clearJWT, user: clearUser }; } }; }]) })();
Refactor logout in auth service
Refactor logout in auth service
JavaScript
mit
ac-adekunle/secondlead,ac-adekunle/secondlead,ac-adekunle/secondlead
064be8a3d6833c5cbe591cbc9241b8c7bbc32796
client/app/states/marketplace/details/details.state.js
client/app/states/marketplace/details/details.state.js
(function() { 'use strict'; angular.module('app.states') .run(appRun); /** @ngInject */ function appRun(routerHelper) { routerHelper.configureStates(getStates()); } function getStates() { return { 'marketplace.details': { url: '/:serviceTemplateId', templateUrl: 'app/states/marketplace/details/details.html', controller: StateController, controllerAs: 'vm', title: 'Service Template Details', resolve: { serviceTemplate: resolveServiceTemplate } } }; } /** @ngInject */ function resolveServiceTemplate($stateParams, CollectionsApi) { return CollectionsApi.get('service_templates', $stateParams.serviceTemplateId); } /** @ngInject */ function StateController(serviceTemplate) { var vm = this; vm.title = 'Service Template Details'; vm.serviceTemplate = serviceTemplate; } })();
(function() { 'use strict'; angular.module('app.states') .run(appRun); /** @ngInject */ function appRun(routerHelper) { routerHelper.configureStates(getStates()); } function getStates() { return { 'marketplace.details': { url: '/:serviceTemplateId', templateUrl: 'app/states/marketplace/details/details.html', controller: StateController, controllerAs: 'vm', title: 'Service Template Details', resolve: { dialogs: resolveDialogs, serviceTemplate: resolveServiceTemplate } } }; } /** @ngInject */ function resolveServiceTemplate($stateParams, CollectionsApi) { return CollectionsApi.get('service_templates', $stateParams.serviceTemplateId); } /** @ngInject */ function resolveDialogs($stateParams, CollectionsApi) { var options = {expand: true, attributes: 'content'}; return CollectionsApi.query('service_templates/' + $stateParams.serviceTemplateId + '/service_dialogs', options); } /** @ngInject */ function StateController(dialogs, serviceTemplate) { var vm = this; vm.title = 'Service Template Details'; vm.dialogs = dialogs.resources[0].content; vm.serviceTemplate = serviceTemplate; } })();
Add API call to return service dialogs
Add API call to return service dialogs https://trello.com/c/qfdnTNlk
JavaScript
apache-2.0
ManageIQ/manageiq-ui-self_service,AllenBW/manageiq-ui-service,AllenBW/manageiq-ui-service,ManageIQ/manageiq-ui-service,dtaylor113/manageiq-ui-self_service,AllenBW/manageiq-ui-service,ManageIQ/manageiq-ui-service,ManageIQ/manageiq-ui-self_service,dtaylor113/manageiq-ui-self_service,ManageIQ/manageiq-ui-self_service,AllenBW/manageiq-ui-service,dtaylor113/manageiq-ui-self_service,ManageIQ/manageiq-ui-service
ce58e8eb67d354f624a4965e965fdf0c047433bf
ReactTests/mocks/MockPromise.js
ReactTests/mocks/MockPromise.js
class MockPromise { constructor(returnSuccess, result) { this.returnSuccess = returnSuccess; this.result = result || (returnSuccess ? 'my data': 'my error') } then(success, failure) { if (this.returnSuccess) { success(this.result); } else { failure(this.result); } } } export default MockPromise
//This is a super-simple mock of a JavaScript Promise //It only implement the 'then(success, failure)' function //as that is the only function that the kanban calls //in the modules that use the KanbanApi class MockPromise { constructor(returnSuccess, result) { this.returnSuccess = returnSuccess; this.result = result || (returnSuccess ? 'my data': 'my error') } then(success, failure) { if (this.returnSuccess) { success(this.result); } else { failure(this.result); } } } export default MockPromise
Comment to say its a limited mock of a promise
Comment to say its a limited mock of a promise
JavaScript
mit
JonPSmith/AspNetReactSamples,JonPSmith/AspNetReactSamples,JonPSmith/AspNetReactSamples
0159ff31725252f1a04451c297258e17872a4a01
app/js/app.js
app/js/app.js
window.ContactManager = { Models: {}, Collections: {}, Views: {}, start: function(data) { var contacts = new ContactManager.Collections.Contacts(data.contacts), router = new ContactManager.Router(); router.on('route:home', function() { router.navigate('contacts', { trigger: true, replace: true }); }); router.on('route:showContacts', function() { var contactsView = new ContactManager.Views.Contacts({ collection: contacts }); $('.main-container').html(contactsView.render().$el); }); router.on('route:newContact', function() { var newContactForm = new ContactManager.Views.ContactForm({ model: new ContactManager.Models.Contact() }); newContactForm.on('form:submitted', function(attrs) { attrs.id = contacts.isEmpty() ? 1 : (_.max(contacts.pluck('id')) + 1); contacts.add(attrs); router.navigate('contacts', true); }); $('.main-container').html(newContactForm.render().$el); }); router.on('route:editContact', function(id) { var contact = contacts.get(id), editContactForm; if (contact) { editContactForm = new ContactManager.Views.ContactForm({ model: contact }); $('.main-container').html(editContactForm.render().$el); } else { router.navigate('contacts', true); } }); Backbone.history.start(); } };
window.ContactManager = { Models: {}, Collections: {}, Views: {}, start: function(data) { var contacts = new ContactManager.Collections.Contacts(data.contacts), router = new ContactManager.Router(); router.on('route:home', function() { router.navigate('contacts', { trigger: true, replace: true }); }); router.on('route:showContacts', function() { var contactsView = new ContactManager.Views.Contacts({ collection: contacts }); $('.main-container').html(contactsView.render().$el); }); router.on('route:newContact', function() { var newContactForm = new ContactManager.Views.ContactForm({ model: new ContactManager.Models.Contact() }); newContactForm.on('form:submitted', function(attrs) { attrs.id = contacts.isEmpty() ? 1 : (_.max(contacts.pluck('id')) + 1); contacts.add(attrs); router.navigate('contacts', true); }); $('.main-container').html(newContactForm.render().$el); }); router.on('route:editContact', function(id) { var contact = contacts.get(id), editContactForm; if (contact) { editContactForm = new ContactManager.Views.ContactForm({ model: contact }); editContactForm.on('form:submitted', function(attrs) { contact.set(attrs); router.navigate('contacts', true); }); $('.main-container').html(editContactForm.render().$el); } else { router.navigate('contacts', true); } }); Backbone.history.start(); } };
Update contact on form submitted
Update contact on form submitted
JavaScript
mit
giastfader/backbone-contact-manager,EaswarRaju/angular-contact-manager,SomilKumar/backbone-contact-manager,vinnu-313/backbone-contact-manager,dmytroyarmak/backbone-contact-manager,SomilKumar/backbone-contact-manager,hrundik/angular-contact-manager,hrundik/angular-contact-manager,giastfader/backbone-contact-manager,hrundik/angular-contact-manager,vinnu-313/backbone-contact-manager
fa025070c1eeb7e751b4b7210cce4e088781e2bc
app/assets/javascripts/messages.js
app/assets/javascripts/messages.js
function scrollToBottom() { var $messages = $('#messages'); if ($messages.length > 0) { $messages.scrollTop($messages[0].scrollHeight); } } $(document).ready(scrollToBottom);
function scrollToBottom() { var $messages = $('#messages'); if ($messages.length > 0) { $messages.scrollTop($messages[0].scrollHeight); } } $(document).ready(scrollToBottom); $(document).on('turbolinks:load', scrollToBottom);
Fix scrollToBottom action on turbolinks:load
Fix scrollToBottom action on turbolinks:load
JavaScript
mit
JulianNicholls/BuffetCar-5,JulianNicholls/BuffetCar-5,JulianNicholls/BuffetCar-5
4deeb7ddc71647bafc1f932e6590d9b58e6b7af3
Resize/script.js
Resize/script.js
function adjustStyle() { var width = 0; // get the width.. more cross-browser issues if (window.innerHeight) { width = window.innerWidth; } else if (document.documentElement && document.documentElement.clientHeight) { width = document.documentElement.clientWidth; } else if (document.body) { width = document.body.clientWidth; } // now we should have it if (width < 600) { document.getElementById("myCSS").setAttribute("href", "_css/narrow.css"); } else { document.getElementById("myCSS").setAttribute("href", "_css/main.css"); } } // now call it when the window is resized. window.onresize = function () { adjustStyle(); };
function adjustStyle() { var width = 0; // get the width.. more cross-browser issues if (window.innerHeight) { width = window.innerWidth; } else if (document.documentElement && document.documentElement.clientHeight) { width = document.documentElement.clientWidth; } else if (document.body) { width = document.body.clientWidth; } // now we should have it if (width < 600) { document.getElementById("myCSS").setAttribute("href", "_css/narrow.css"); } else { document.getElementById("myCSS").setAttribute("href", "_css/main.css"); } } // now call it when the window is resized. window.onresize = function () { adjustStyle(); }; window.onload = function () { adjustStyle(); };
Add window.onload for style adjust
Add window.onload for style adjust
JavaScript
mit
SHoar/lynda_essentialJStraining
43d771162f5993035a231857d02e97d94e74c3a6
koans/AboutPromises.js
koans/AboutPromises.js
describe("About Promises", function () { describe("Asynchronous Flow", function () { it("should understand promise usage", function () { function isZero(number) { return new Promise(function(resolve, reject) { if(number === 0) { resolve(); } else { reject(number + ' is not zero!'); } }) } expect(isZero(0) instanceof Promise).toEqual(FILL_ME_IN); expect(typeof isZero(0)).toEqual(FILL_ME_IN); }); }); });
describe("About Promises", function () { describe("Asynchronous Flow", function () { it("should understand Promise type", function () { function promise(number) { return new Promise(function(resolve, reject) { resolve(); }) } // expect(promise() instanceof Promise).toEqual(FILL_ME_IN); // expect(typeof promise()).toEqual(FILL_ME_IN); }); it('should understand a Promise can be fulfilled / resolved', function(done) { function promiseResolved() { return new Promise(function(resolve, reject) { resolve('promise me this'); }); } promiseResolved() .then(function(promiseValue) { expect(promiseValue).toEqual(promiseValue); }) .then(done) }) }); });
Add in extra promise koan
feat: Add in extra promise koan
JavaScript
mit
tawashley/es6-javascript-koans,tawashley/es6-javascript-koans,tawashley/es6-javascript-koans
4e1b78d76157761c251ecdf10cf6126ea03479e5
app/templates/src/main/webapp/scripts/app/account/social/directive/_social.directive.js
app/templates/src/main/webapp/scripts/app/account/social/directive/_social.directive.js
'use strict'; angular.module('<%=angularAppName%>') .directive('jhSocial', function($translatePartialLoader, $translate, $filter, SocialService) { return { restrict: 'E', scope: { provider: "@ngProvider" }, templateUrl: 'scripts/app/account/social/directive/social.html', link: function(scope, element, attrs) { $translatePartialLoader.addPart('social'); $translate.refresh(); scope.label = $filter('capitalize')(scope.provider); scope.providerSetting = SocialService.getProviderSetting(scope.provider); scope.providerURL = SocialService.getProviderURL(scope.provider); scope.csrf = SocialService.getCSRF(); } } });
'use strict'; angular.module('<%=angularAppName%>') .directive('jhSocial', function(<% if (enableTranslation){ %>$translatePartialLoader, $translate, <% } %>$filter, SocialService) { return { restrict: 'E', scope: { provider: "@ngProvider" }, templateUrl: 'scripts/app/account/social/directive/social.html', link: function(scope, element, attrs) {<% if (enableTranslation){ %> $translatePartialLoader.addPart('social'); $translate.refresh(); <% } %> scope.label = $filter('capitalize')(scope.provider); scope.providerSetting = SocialService.getProviderSetting(scope.provider); scope.providerURL = SocialService.getProviderURL(scope.provider); scope.csrf = SocialService.getCSRF(); } } });
Fix translation issue in the social login
Fix translation issue in the social login
JavaScript
apache-2.0
yongli82/generator-jhipster,rkohel/generator-jhipster,dimeros/generator-jhipster,danielpetisme/generator-jhipster,Tcharl/generator-jhipster,Tcharl/generator-jhipster,maniacneron/generator-jhipster,sendilkumarn/generator-jhipster,erikkemperman/generator-jhipster,atomfrede/generator-jhipster,ziogiugno/generator-jhipster,cbornet/generator-jhipster,siliconharborlabs/generator-jhipster,dynamicguy/generator-jhipster,wmarques/generator-jhipster,duderoot/generator-jhipster,dalbelap/generator-jhipster,xetys/generator-jhipster,dynamicguy/generator-jhipster,jkutner/generator-jhipster,maniacneron/generator-jhipster,ramzimaalej/generator-jhipster,ruddell/generator-jhipster,sohibegit/generator-jhipster,mosoft521/generator-jhipster,baskeboler/generator-jhipster,duderoot/generator-jhipster,mraible/generator-jhipster,duderoot/generator-jhipster,liseri/generator-jhipster,sendilkumarn/generator-jhipster,dimeros/generator-jhipster,ziogiugno/generator-jhipster,nkolosnjaji/generator-jhipster,gzsombor/generator-jhipster,hdurix/generator-jhipster,mraible/generator-jhipster,sendilkumarn/generator-jhipster,liseri/generator-jhipster,eosimosu/generator-jhipster,dynamicguy/generator-jhipster,xetys/generator-jhipster,lrkwz/generator-jhipster,ctamisier/generator-jhipster,jkutner/generator-jhipster,wmarques/generator-jhipster,ctamisier/generator-jhipster,sohibegit/generator-jhipster,wmarques/generator-jhipster,sohibegit/generator-jhipster,JulienMrgrd/generator-jhipster,lrkwz/generator-jhipster,lrkwz/generator-jhipster,nkolosnjaji/generator-jhipster,JulienMrgrd/generator-jhipster,robertmilowski/generator-jhipster,dalbelap/generator-jhipster,gzsombor/generator-jhipster,ctamisier/generator-jhipster,mosoft521/generator-jhipster,erikkemperman/generator-jhipster,gmarziou/generator-jhipster,vivekmore/generator-jhipster,jhipster/generator-jhipster,rifatdover/generator-jhipster,cbornet/generator-jhipster,hdurix/generator-jhipster,Tcharl/generator-jhipster,eosimosu/generator-jhipster,dimeros/generator-jhipster,yongli82/generator-jhipster,baskeboler/generator-jhipster,duderoot/generator-jhipster,maniacneron/generator-jhipster,nkolosnjaji/generator-jhipster,deepu105/generator-jhipster,stevehouel/generator-jhipster,danielpetisme/generator-jhipster,gzsombor/generator-jhipster,baskeboler/generator-jhipster,JulienMrgrd/generator-jhipster,atomfrede/generator-jhipster,erikkemperman/generator-jhipster,hdurix/generator-jhipster,siliconharborlabs/generator-jhipster,dalbelap/generator-jhipster,gmarziou/generator-jhipster,lrkwz/generator-jhipster,danielpetisme/generator-jhipster,dimeros/generator-jhipster,gzsombor/generator-jhipster,stevehouel/generator-jhipster,ramzimaalej/generator-jhipster,vivekmore/generator-jhipster,jkutner/generator-jhipster,mosoft521/generator-jhipster,jkutner/generator-jhipster,siliconharborlabs/generator-jhipster,pascalgrimaud/generator-jhipster,Tcharl/generator-jhipster,Tcharl/generator-jhipster,yongli82/generator-jhipster,PierreBesson/generator-jhipster,rkohel/generator-jhipster,hdurix/generator-jhipster,eosimosu/generator-jhipster,atomfrede/generator-jhipster,cbornet/generator-jhipster,baskeboler/generator-jhipster,ruddell/generator-jhipster,deepu105/generator-jhipster,mraible/generator-jhipster,ctamisier/generator-jhipster,ruddell/generator-jhipster,gzsombor/generator-jhipster,ruddell/generator-jhipster,erikkemperman/generator-jhipster,gmarziou/generator-jhipster,maniacneron/generator-jhipster,cbornet/generator-jhipster,gmarziou/generator-jhipster,JulienMrgrd/generator-jhipster,siliconharborlabs/generator-jhipster,deepu105/generator-jhipster,jhipster/generator-jhipster,pascalgrimaud/generator-jhipster,yongli82/generator-jhipster,vivekmore/generator-jhipster,pascalgrimaud/generator-jhipster,atomfrede/generator-jhipster,stevehouel/generator-jhipster,atomfrede/generator-jhipster,ctamisier/generator-jhipster,jkutner/generator-jhipster,xetys/generator-jhipster,wmarques/generator-jhipster,mosoft521/generator-jhipster,wmarques/generator-jhipster,deepu105/generator-jhipster,rkohel/generator-jhipster,maniacneron/generator-jhipster,ziogiugno/generator-jhipster,jhipster/generator-jhipster,sendilkumarn/generator-jhipster,mosoft521/generator-jhipster,eosimosu/generator-jhipster,nkolosnjaji/generator-jhipster,cbornet/generator-jhipster,stevehouel/generator-jhipster,ramzimaalej/generator-jhipster,gmarziou/generator-jhipster,jhipster/generator-jhipster,danielpetisme/generator-jhipster,pascalgrimaud/generator-jhipster,lrkwz/generator-jhipster,mraible/generator-jhipster,dimeros/generator-jhipster,erikkemperman/generator-jhipster,jhipster/generator-jhipster,vivekmore/generator-jhipster,siliconharborlabs/generator-jhipster,JulienMrgrd/generator-jhipster,liseri/generator-jhipster,baskeboler/generator-jhipster,PierreBesson/generator-jhipster,ruddell/generator-jhipster,dalbelap/generator-jhipster,hdurix/generator-jhipster,nkolosnjaji/generator-jhipster,danielpetisme/generator-jhipster,liseri/generator-jhipster,vivekmore/generator-jhipster,robertmilowski/generator-jhipster,sendilkumarn/generator-jhipster,xetys/generator-jhipster,deepu105/generator-jhipster,robertmilowski/generator-jhipster,PierreBesson/generator-jhipster,pascalgrimaud/generator-jhipster,liseri/generator-jhipster,rkohel/generator-jhipster,PierreBesson/generator-jhipster,duderoot/generator-jhipster,PierreBesson/generator-jhipster,mraible/generator-jhipster,stevehouel/generator-jhipster,rkohel/generator-jhipster,rifatdover/generator-jhipster,yongli82/generator-jhipster,ziogiugno/generator-jhipster,robertmilowski/generator-jhipster,robertmilowski/generator-jhipster,eosimosu/generator-jhipster,ziogiugno/generator-jhipster,sohibegit/generator-jhipster,sohibegit/generator-jhipster,dynamicguy/generator-jhipster,dalbelap/generator-jhipster,rifatdover/generator-jhipster
afcb675b6681611867be57c523a58b0ba4d831b4
lib/componentHelper.js
lib/componentHelper.js
var fs = require('fs'), Builder = require('component-builder'), rimraf = require('rimraf'), config = require('../config'), utils = require('./utils'), component = require('./component'), options = { dest: config.componentInstallDir }; /** * Installs `model`s component from registry * into the install dir * * @param {Model} model * @param {Function} callback */ exports.install = function (model, callback) { var pkg = component.install(model.repo, '*', options); pkg.on('end', callback); pkg.install(); }; /** * Builds component from model's attributes, * calls callback with err and built js in UTF-8 * * @param {Model} model * @param {Function} callback */ exports.build = function (model, callback) { var builder = new Builder(utils.getInstallDir(model.repo)); builder.addLookup(config.componentInstallDir); builder.build(function (err, res) { if (err || (res && !res.js)) { return callback(err); } callback(err, res.js); }); }; /** * Deletes all components in the install dir * * @param {Function} callback */ exports.clearInstall = function (callback) { rimraf(config.componentInstallDir, function (err) { callback(err); }); };
var fs = require('fs-extra'), Builder = require('component-builder'), config = require('../config'), utils = require('./utils'), component = require('./component'), options = { dest: config.componentInstallDir }; /** * Installs `model`s component from registry * into the install dir * * @param {Model} model * @param {Function} callback */ exports.install = function (model, callback) { var pkg = component.install(model.repo, '*', options); pkg.on('end', callback); pkg.install(); }; /** * Builds component from model's attributes, * calls callback with err and built js in UTF-8 * * @param {Model} model * @param {Function} callback */ exports.build = function (model, callback) { var builder = new Builder(utils.getInstallDir(model.repo)); builder.addLookup(config.componentInstallDir); builder.build(function (err, res) { if (err || (res && !res.js)) { return callback(err); } callback(err, res.js); }); }; /** * Deletes all components in the install dir * * @param {Function} callback */ exports.clearInstall = function (callback) { fs.remove(config.componentInstallDir, function (err) { console.log('fs-extra remove: ', err, err && err.stack); callback(err); }); };
Use fs-extra to remove recurisvely rather than rimraf
Use fs-extra to remove recurisvely rather than rimraf
JavaScript
mit
web-audio-components/web-audio-components-service
f4679665a92b2a34277179615aabd02f2be1db22
src/eventDispatchers/touchEventHandlers/touchStartActive.js
src/eventDispatchers/touchEventHandlers/touchStartActive.js
// State import { getters, state } from './../../store/index.js'; import getActiveToolsForElement from './../../store/getActiveToolsForElement.js'; import addNewMeasurement from './addNewMeasurement.js'; import baseAnnotationTool from '../../base/baseAnnotationTool.js'; export default function (evt) { if (state.isToolLocked) { return; } const element = evt.detail.element; const tools = getActiveToolsForElement(element, getters.touchTools()); const activeTool = tools[0]; // Note: custom `addNewMeasurement` will need to prevent event bubbling if (activeTool.addNewMeasurement) { activeTool.addNewMeasurement(evt, 'touch'); } else if (activeTool instanceof baseAnnotationTool) { addNewMeasurement(evt, activeTool); } }
// State import { getters, state } from './../../store/index.js'; import getActiveToolsForElement from './../../store/getActiveToolsForElement.js'; import addNewMeasurement from './addNewMeasurement.js'; import baseAnnotationTool from '../../base/baseAnnotationTool.js'; export default function (evt) { if (state.isToolLocked) { return; } const element = evt.detail.element; const tools = getActiveToolsForElement(element, getters.touchTools()); const activeTool = tools[0]; // Note: custom `addNewMeasurement` will need to prevent event bubbling if (activeTool && activeTool.addNewMeasurement) { activeTool.addNewMeasurement(evt, 'touch'); } else if (activeTool instanceof baseAnnotationTool) { addNewMeasurement(evt, activeTool); } }
Fix for when no touchTools are active
Fix for when no touchTools are active
JavaScript
mit
cornerstonejs/cornerstoneTools,cornerstonejs/cornerstoneTools,chafey/cornerstoneTools,cornerstonejs/cornerstoneTools
a5820158db8a23a61776a545e9e3f416b3568dd2
server/openstorefront/openstorefront-web/src/main/webapp/client/scripts/component/savedSearchLinkInsertWindow.js
server/openstorefront/openstorefront-web/src/main/webapp/client/scripts/component/savedSearchLinkInsertWindow.js
/* * Copyright 2016 Space Dynamics Laboratory - Utah State University Research Foundation. * * 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. */ /* global Ext, CoreService */ Ext.define('OSF.component.SavedSearchLinkInsertWindow', { extend: 'Ext.window.Window', alias: 'osf.widget.SavedSearchLinkInsertWindow', layout: 'fit', title: 'Insert Link to Saved Search', modal: true, width: '60%', height: '50%', initComponent: function () { this.callParent(); var savedSearchLinkInsertWindow = this; savedSearchLinkInsertWindow.getLink = function() { return "Link text goes here."; }; } });
/* * Copyright 2016 Space Dynamics Laboratory - Utah State University Research Foundation. * * 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. */ /* global Ext, CoreService */ Ext.define('OSF.component.SavedSearchLinkInsertWindow', { extend: 'Ext.window.Window', alias: 'osf.widget.SavedSearchLinkInsertWindow', layout: 'fit', title: 'Insert Link to Saved Search', modal: true, width: '60%', height: '50%', dockedItems: [ { xtype: 'toolbar', dock: 'bottom', items: [ { text: 'Cancel' }, { xtype: 'tbfill' }, { text: 'Insert Link' } ] } ], initComponent: function () { this.callParent(); var savedSearchLinkInsertWindow = this; savedSearchLinkInsertWindow.getLink = function() { return "Link text goes here."; }; } });
Add action buttons for link insert window
Add action buttons for link insert window
JavaScript
apache-2.0
jbottel/openstorefront,jbottel/openstorefront,jbottel/openstorefront,jbottel/openstorefront
d4bc885cc31cf92aafd4fef846a015c58a7e5cbe
client/reactComponents/TankBody.js
client/reactComponents/TankBody.js
import React from 'react'; import { TANK_RADIUS } from '../../simulation/constants'; class TankBody extends React.Component { constructor(props) { super(props); this.radius = props.radius || TANK_RADIUS; this.material = props.material || 'color: red;' } render () { return ( <a-sphere position='0 0 0' rotation={this.props.rotation} material={this.material} socket-controls={`simulationAttribute: tankRotation; characterId: ${this.props.characterId}`} radius={this.radius}> <a-torus position='0 0 0' rotation='90 0 0' material={this.material} radius={this.radius} radius-tubular={0.1}/> <a-sphere // Windows position={`0 0.6 ${0.4 - this.radius}`} radius='0.5' scale='2.5 1 1.5' material='color:black; opacity:0.4;'/> <a-sphere position={`${-(this.radius - 0.5)} 0.6 -1`} radius='0.4' material='color:black; opacity:0.4;'/> <a-sphere position={`${this.radius - 0.5} 0.6 -1`} radius='0.4' material='color:black; opacity:0.4;'/> {this.props.children} </a-sphere> ) } } module.exports = TankBody;
import React from 'react'; import { TANK_RADIUS } from '../../simulation/constants'; class TankBody extends React.Component { constructor(props) { super(props); this.radius = props.radius || TANK_RADIUS; this.material = props.material || 'color: red;' this.socketControlsDisabled = props.socketControlsDisabled || false; } render () { return ( <a-sphere position='0 0 0' rotation={this.props.rotation} material={this.material} socket-controls={`simulationAttribute: tankRotation; `+ `characterId: ${this.props.characterId}; `+ `enabled: ${!this.socketControlsDisabled}`} radius={this.radius}> <a-torus position='0 0 0' rotation='90 0 0' material={this.material} radius={this.radius} radius-tubular={0.1}/> <a-sphere // Windows position={`0 0.6 ${0.4 - this.radius}`} radius='0.5' scale='2.5 1 1.5' material='color:black; opacity:0.4;'/> <a-sphere position={`${-(this.radius - 0.5)} 0.6 -1`} radius='0.4' material='color:black; opacity:0.4;'/> <a-sphere position={`${this.radius - 0.5} 0.6 -1`} radius='0.4' material='color:black; opacity:0.4;'/> {this.props.children} </a-sphere> ) } } module.exports = TankBody;
Enable disabling for inanimate enemy tanks
Enable disabling for inanimate enemy tanks
JavaScript
mit
ourvrisrealerthanyours/tanks,elliotaplant/tanks,ourvrisrealerthanyours/tanks,elliotaplant/tanks
820dc2d669d10d1fe125b4581ed5db9e4249b551
conf/grunt/grunt-release.js
conf/grunt/grunt-release.js
'use strict'; module.exports = function (grunt) { grunt.registerTask('release', 'Create and tag a release', function () { grunt.task.run(['checkbranch:master', 'compile', 'bump']); } ); };
module.exports = function (grunt) { 'use strict'; grunt.registerTask('release', 'Create and tag a release', function (increment) { var bump = 'bump:' + (increment || 'patch'); grunt.task.run(['checkbranch:master', 'compile', bump]); } ); };
Add version increment option to release task.
Add version increment option to release task.
JavaScript
mit
elmarquez/threejs-cad,elmarquez/threejs-cad
37a1762d76945cca5a0bf184fc42ef9ed6dba0f7
packages/tools/addon/components/cs-active-composition-panel.js
packages/tools/addon/components/cs-active-composition-panel.js
import Component from '@ember/component'; import layout from '../templates/components/cs-active-composition-panel'; import { task, timeout } from 'ember-concurrency'; import scrollToBounds from '../scroll-to-bounds'; import { inject as service } from '@ember/service'; export default Component.extend({ layout, classNames: ['cs-active-composition-panel'], validationErrors: null, data: service('cardstack-data'), validate: task(function * () { let errors = yield this.get('data').validate(this.model); this.set('validationErrors', errors); }), highlightAndScrollToField: task(function * (field) { this.get('highlightField')(field); if (field) { yield timeout(500); scrollToBounds(field.bounds()); } }).restartable() });
import Component from '@ember/component'; import layout from '../templates/components/cs-active-composition-panel'; import { task, timeout } from 'ember-concurrency'; import scrollToBounds from '../scroll-to-bounds'; import { inject as service } from '@ember/service'; import { camelize } from '@ember/string'; export default Component.extend({ layout, classNames: ['cs-active-composition-panel'], validationErrors: null, data: service('cardstack-data'), validate: task(function * () { let errors = yield this.get('data').validate(this.model); let errorsForFieldNames = {}; for (let key in errors) { errorsForFieldNames[camelize(key)] = errors[key]; } this.set('validationErrors', errorsForFieldNames); }), highlightAndScrollToField: task(function * (field) { this.get('highlightField')(field); if (field) { yield timeout(500); scrollToBounds(field.bounds()); } }).restartable() });
Fix showing validation errors for dashed field names
Fix showing validation errors for dashed field names
JavaScript
mit
cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack
d61d559936d5a7168e86e928a024cabd53abea60
build/copy.js
build/copy.js
module.exports = { all: { files: [ { expand: true, src: ['config.json'], dest: 'dist' }, { expand: true, src: ['javascript.json'], dest: 'dist' }, { expand: true, cwd: 'src/config/', src: ['**'], dest: 'dist/config/' }, { expand: true, cwd: 'src/images/', src: ['**'], dest: 'dist/images/', }, { expand: true, cwd: 'src/flash/', src: ['**'], dest: 'dist/flash/' }, { expand: true, cwd: 'src/templates/', src: ['**'], dest: 'dist/templates/' }, { expand: true, cwd: 'src/css/external/jquery-ui-custom-theme/images/', src: ['**'], dest: 'dist/css/images' }, { expand: true, cwd: 'src/css/external/jquery-ui-custom-theme/', src: ['*.css'], dest: 'dist/css/' }, { expand: true, cwd: 'src/javascript/', src: ['**'], dest: 'dist/dev/src/javascript/' } ] } };
module.exports = { all: { files: [ { expand: true, src: ['config.json'], dest: 'dist' }, { expand: true, src: ['javascript.json'], dest: 'dist' }, { expand: true, cwd: 'src/config/', src: ['**'], dest: 'dist/config/' }, { expand: true, cwd: 'src/images/', src: ['**'], dest: 'dist/images/', }, { expand: true, cwd: 'src/flash/', src: ['**'], dest: 'dist/flash/' }, { expand: true, cwd: 'src/templates/', src: ['**'], dest: 'dist/templates/' }, { expand: true, cwd: 'src/css/external/jquery-ui-custom-theme/images/', src: ['**'], dest: 'dist/css/images' }, { expand: true, cwd: 'src/css/external/jquery-ui-custom-theme/', src: ['*.css'], dest: 'dist/css/' }, { expand: true, cwd: 'src/javascript/', src: ['**'], dest: 'dist/dev/src/javascript/' }, { expand: true, cwd: 'src/javascript/gtm/', src: ['experimental.js'], dest: 'dist/js/gtm/' } ] } };
Copy gtml file to dist directory
Copy gtml file to dist directory
JavaScript
apache-2.0
junbon/binary-static-www2,einhverfr/binary-static,massihx/binary-static,einhverfr/binary-static,borisyankov/binary-static,massihx/binary-static,animeshsaxena/binary-static,borisyankov/binary-static,brodiecapel16/binary-static,borisyankov/binary-static,einhverfr/binary-static,massihx/binary-static,animeshsaxena/binary-static,animeshsaxena/binary-static,einhverfr/binary-static,tfoertsch/binary-static,brodiecapel16/binary-static,borisyankov/binary-static,tfoertsch/binary-static,animeshsaxena/binary-static,brodiecapel16/binary-static,brodiecapel16/binary-static,massihx/binary-static,junbon/binary-static-www2
e08a21c9a4e067e692dd35e82ffde8608b3f3044
lib/assert-called.js
lib/assert-called.js
var assert = require('assert'); var assertCalled = module.exports = function (cb) { var index = assertCalled.wanted.push({ callback: cb, error: new Error() }); return function () { wanted.splice(index - 1, 1); cb.apply(this, arguments); }; }; var wanted = assertCalled.wanted = []; process.on('exit', function () { var msg; if (wanted.length) { msg = wanted.length + ' callback' + (wanted.length > 1 ? 's' : '') + ' not called:'; wanted.forEach(function (func) { var stack; msg += '\n ' + (func.callback.name ? func.callback.name : '<anonymous>') + '\n'; stack = func.error.stack.split('\n'); stack.splice(0, 2); msg += stack.join('\n') + '\n'; }); throw new assert.AssertionError({ message: msg, actual: wanted.length, expected: 0 }); } });
var assert = require('assert'); var assertCalled = module.exports = function (cb) { var index = assertCalled.wanted.push({ callback: cb, error: new Error() }); return function () { wanted[index - 1] = null; cb.apply(this, arguments); }; }; var wanted = assertCalled.wanted = []; process.on('exit', function () { var msg; wanted = wanted.filter(Boolean); if (wanted.length) { msg = wanted.length + ' callback' + (wanted.length > 1 ? 's' : '') + ' not called:'; wanted.forEach(function (func) { var stack; msg += '\n ' + (func.callback.name ? func.callback.name : '<anonymous>') + '\n'; stack = func.error.stack.split('\n'); stack.splice(0, 2); msg += stack.join('\n') + '\n'; }); throw new assert.AssertionError({ message: msg, actual: wanted.length, expected: 0 }); } });
Fix problem with callbacks called out of order
[fix] Fix problem with callbacks called out of order
JavaScript
mit
mmalecki/assert-called
c78de429e9f6c4d6ecf32ff0cc768a8ef8d0e917
mac/resources/open_wctb.js
mac/resources/open_wctb.js
define(function() { return function(resource) { var dv = new DataView(resource.data.buffer, resource.data.byteOffset, resource.data.byteLength); var entryCount = dv.getInt16(6, false) + 1; if (entryCount < 0) { console.error('color table resource: invalid number of entries'); } var palCanvas = document.createElement('CANVAS'); palCanvas.width = entryCount; palCanvas.height = 1; var palCtx = palCanvas.getContext('2d'); var palData = palCtx.createImageData(entryCount, 1); for (var icolor = 0; icolor < entryCount; icolor++) { var offset = dv.getInt16(8 + icolor*8, false) * 4; if (offset >= 0) { palData.data[offset] = resource.data[8 + icolor*8 + 2]; palData.data[offset + 1] = resource.data[8 + icolor*8 + 4]; palData.data[offset + 2] = resource.data[8 + icolor*8 + 6]; palData.data[offset + 3] = 255; } } palCtx.putImageData(palData, 0, 0); resource.image = { width: entryCount, height: 1, url: palCanvas.toDataURL(), }; }; });
define(function() { return function(resource) { var dv = new DataView(resource.data.buffer, resource.data.byteOffset, resource.data.byteLength); var entryCount = dv.getInt16(6, false) + 1; if (entryCount < 0) { console.error('color table resource: invalid number of entries'); } var palCanvas = document.createElement('CANVAS'); palCanvas.width = entryCount; if (entryCount === 0) { palCanvas.height = 0; } else { palCanvas.height = 1; var palCtx = palCanvas.getContext('2d'); var palData = palCtx.createImageData(entryCount, 1); for (var icolor = 0; icolor < entryCount; icolor++) { var offset = dv.getInt16(8 + icolor*8, false) * 4; if (offset >= 0) { palData.data[offset] = resource.data[8 + icolor*8 + 2]; palData.data[offset + 1] = resource.data[8 + icolor*8 + 4]; palData.data[offset + 2] = resource.data[8 + icolor*8 + 6]; palData.data[offset + 3] = 255; } } palCtx.putImageData(palData, 0, 0); }, resource.image = { width: palCanvas.width, height: palCanvas.height, url: palCanvas.toDataURL(), }; }; });
Fix for zero-length color tables
Fix for zero-length color tables
JavaScript
mit
radishengine/drowsy,radishengine/drowsy
949d26db4397a375e2587a68ea66f099fbe4f3ba
test/integration/saucelabs.conf.js
test/integration/saucelabs.conf.js
exports.config = { sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, capabilities: { 'browserName': 'chrome', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': 'smoke test' }, specs: ['*.spec.js'], jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000 }, baseUrl: 'http://localhost:' + (process.env.HTTP_PORT || '3000') }
exports.config = { sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, capabilities: { 'browserName': 'chrome', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': 'smoke test' }, specs: ['*.spec.js'], jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, isVerbose: true }, baseUrl: 'http://localhost:' + (process.env.HTTP_PORT || '3000') }
Add additional logging setting for Travis CI debugging
Add additional logging setting for Travis CI debugging
JavaScript
bsd-3-clause
CodeForBrazil/streetmix,codeforamerica/streetmix,macGRID-SRN/streetmix,kodujdlapolski/streetmix,magul/streetmix,kodujdlapolski/streetmix,magul/streetmix,kodujdlapolski/streetmix,CodeForBrazil/streetmix,codeforamerica/streetmix,CodeForBrazil/streetmix,macGRID-SRN/streetmix,magul/streetmix,macGRID-SRN/streetmix,codeforamerica/streetmix
b37380d1ea4bc04f07859f8f0b748bbe676e4317
codebrag-ui/app/scripts/common/directives/contactFormPopup.js
codebrag-ui/app/scripts/common/directives/contactFormPopup.js
angular.module('codebrag.common.directives').directive('contactFormPopup', function() { function ContactFormPopup($scope, $http) { $scope.isVisible = false; $scope.submit = function() { sendFeedbackViaUservoice().then(success, failure); function success() { $scope.success = true; clearFormFields(); } function failure() { $scope.failure = true; } }; $scope.$on('openContactFormPopup', function() { $scope.isVisible = true; }); $scope.close = function() { $scope.isVisible = false; delete $scope.success; delete $scope.failure; clearFormFields(); }; function clearFormFields() { $scope.msg = {}; $scope.contactForm.$setPristine(); } function sendFeedbackViaUservoice() { var apiKey = 'vvT4cCa8uOpfhokERahg'; var data = { format: 'json', client: apiKey, ticket: { message: $scope.msg.body, subject: $scope.msg.subject }, email: $scope.msg.email }; var url = 'https://codebrag.uservoice.com/api/v1/tickets/create_via_jsonp.json?' + $.param(data) + '&callback=JSON_CALLBACK'; return $http.jsonp(url); } } return { restrict: 'E', replace: true, scope: {}, templateUrl: 'views/popups/contactForm.html', controller: ContactFormPopup }; });
angular.module('codebrag.common.directives').directive('contactFormPopup', function() { function ContactFormPopup($scope, $http) { $scope.isVisible = false; $scope.submit = function() { clearStatus(); sendFeedbackViaUservoice().then(success, failure); function success() { $scope.success = true; clearFormFields(); } function failure() { $scope.failure = true; } }; $scope.$on('openContactFormPopup', function() { $scope.isVisible = true; }); $scope.close = function() { $scope.isVisible = false; clearStatus(); clearFormFields(); }; function clearStatus() { delete $scope.success; delete $scope.failure; } function clearFormFields() { $scope.msg = {}; $scope.contactForm.$setPristine(); } function sendFeedbackViaUservoice() { var apiKey = 'vvT4cCa8uOpfhokERahg'; var data = { format: 'json', client: apiKey, ticket: { message: $scope.msg.body, subject: $scope.msg.subject }, email: $scope.msg.email }; var url = 'https://codebrag.uservoice.com/api/v1/tickets/create_via_jsonp.json?' + $.param(data) + '&callback=JSON_CALLBACK'; return $http.jsonp(url); } } return { restrict: 'E', replace: true, scope: {}, templateUrl: 'views/popups/contactForm.html', controller: ContactFormPopup }; });
Hide contact form when sending succeeded.
Hide contact form when sending succeeded.
JavaScript
agpl-3.0
cazacugmihai/codebrag,softwaremill/codebrag,cazacugmihai/codebrag,cazacugmihai/codebrag,softwaremill/codebrag,cazacugmihai/codebrag,cazacugmihai/codebrag,softwaremill/codebrag,softwaremill/codebrag
5c714a27bbfb28922771db47a249efbd24dfae31
tests/integration/components/organization-menu-test.js
tests/integration/components/organization-menu-test.js
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('organization-menu', 'Integration | Component | organization menu', { integration: true }); test('it renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... });" this.render(hbs`{{organization-menu}}`); assert.equal(this.$().text().trim(), ''); // Template block usage:" this.render(hbs` {{#organization-menu}} template block text {{/organization-menu}} `); assert.equal(this.$().text().trim(), 'template block text'); });
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('organization-menu', 'Integration | Component | organization menu', { integration: true }); test('it renders', function(assert) { assert.expect(1); this.render(hbs`{{organization-menu}}`); assert.equal(this .$('.organization-menu').length, 1, 'Component\'s element is rendered'); }); test('it renders all required menu elements properly', function(assert) { assert.expect(3); this.render(hbs`{{organization-menu}}`); assert.equal(this.$('.organization-menu li').length, 2, 'All the links rendered'); assert.equal(this.$('.organization-menu li:eq(0)').text().trim(), 'Projects', 'The projects link is rendered'); assert.equal(this.$('.organization-menu li:eq(1)').text().trim(), 'Settings', 'The settings link is rendered'); });
Add organization menu component test
Add organization menu component test
JavaScript
mit
jderr-mx/code-corps-ember,code-corps/code-corps-ember,jderr-mx/code-corps-ember,eablack/code-corps-ember,eablack/code-corps-ember,code-corps/code-corps-ember
32fbe3dc4686e413886911f5d373137648f08614
packages/shim/src/index.js
packages/shim/src/index.js
/* eslint-disable global-require */ require('@webcomponents/template'); if (!window.customElements) require('@webcomponents/custom-elements'); if (!document.body.attachShadow) require('@webcomponents/shadydom'); require('@webcomponents/shadycss/scoping-shim.min'); require('@webcomponents/shadycss/apply-shim.min');
/* eslint-disable global-require */ require('@webcomponents/template'); if (!document.body.attachShadow) require('@webcomponents/shadydom'); if (!window.customElements) require('@webcomponents/custom-elements'); require('@webcomponents/shadycss/scoping-shim.min'); require('@webcomponents/shadycss/apply-shim.min');
Fix ShadyDOM before Custom Elements polyfill
Fix ShadyDOM before Custom Elements polyfill
JavaScript
mit
hybridsjs/hybrids
4643995ca77ef4ed695d337da9fc36fdf7918749
test/events.emitter.test.js
test/events.emitter.test.js
define(['events/lib/emitter'], function(Emitter) { describe("Emitter", function() { it('should alias addListener to on', function() { expect(Emitter.prototype.addListener).to.be.equal(Emitter.prototype.on); }); it('should alias removeListener to off', function() { expect(Emitter.prototype.removeListener).to.be.equal(Emitter.prototype.off); }); }); return { name: "test.events.emitter" } });
define(['events/lib/emitter'], function(Emitter) { describe("Emitter", function() { it('should alias addListener to on', function() { expect(Emitter.prototype.addListener).to.be.equal(Emitter.prototype.on); }); it('should alias removeListener to off', function() { expect(Emitter.prototype.removeListener).to.be.equal(Emitter.prototype.off); }); describe("emit", function() { var emitter = new Emitter(); var fooSpy = []; emitter.on('foo', function() { fooSpy.push({}); }); it('should call listener with zero arguments', function() { var rv = emitter.emit('foo'); expect(rv).to.be.true; expect(fooSpy).to.have.length(1); }); it('should not call unknown listener', function() { var rv = emitter.emit('fubar'); expect(rv).to.be.false; }); }); }); return { name: "test.events.emitter" } });
Test case for zero argument emit.
Test case for zero argument emit.
JavaScript
mit
anchorjs/events,anchorjs/events
c78dbbec9ad549b8a850abce62f3a4757540eae8
server/mongoose-handler.js
server/mongoose-handler.js
var mongoose = require('mongoose'); var log = require('./logger').log; var process = require('process'); var options = require('./options-handler').options; exports.init = function(callback) { mongoose.connect(options['database']['uri']); var db = mongoose.connection; db.on('error', function(err) { log.error(err); process.exit(1); }); db.once('open', callback); };
var mongoose = require('mongoose'); var log = require('./logger').log; var options = require('./options-handler').options; exports.init = function(callback) { mongoose.connect(options['database']['uri']); var db = mongoose.connection; db.on('error', function(err) { log.error(err); setTimeout(function() { process.exit(1); }, 1000); }); db.once('open', callback); };
Fix exiting on DB error.
Fix exiting on DB error.
JavaScript
mit
MisterTea/TidalWave,MisterTea/TidalWave,MisterTea/TidalWave,MisterTea/TidalWave,MisterTea/TidalWave,MisterTea/TidalWave
cd810325efa67beac2cd339cd0bb5beeced14ec1
app/assets/javascripts/transactions.js
app/assets/javascripts/transactions.js
(function () { "use strict" window.GOVUK = window.GOVUK || {}; window.GOVUK.Transactions = { trackStartPageTabs : function (e) { var pagePath = e.target.href; GOVUK.analytics.trackEvent('startpages', 'tab', {label: pagePath, nonInteraction: true}); } }; })(); $(document).ready(function () { $('form#completed-transaction-form'). append('<input type="hidden" name="service_feedback[javascript_enabled]" value="true"/>'). append($('<input type="hidden" name="referrer">').val(document.referrer || "unknown")); $('#completed-transaction-form button.button').click(function() { $(this).attr('disabled', 'disabled'); $(this).parents('form').submit(); }); $('.transaction .govuk-tabs__tab').click(window.GOVUK.Transactions.trackStartPageTabs); });
(function () { "use strict" window.GOVUK = window.GOVUK || {}; window.GOVUK.Transactions = { trackStartPageTabs : function (e) { var pagePath = e.target.href; GOVUK.analytics.trackEvent('startpages', 'tab', {label: pagePath, nonInteraction: true}); } }; })(); $(document).ready(function () { $('form#completed-transaction-form'). append('<input type="hidden" name="service_feedback[javascript_enabled]" value="true"/>'). append($('<input type="hidden" name="referrer">').val(document.referrer || "unknown")); $('#completed-transaction-form button[type="submit"]').click(function() { $(this).attr('disabled', 'disabled'); $(this).parents('form').submit(); }); $('.transaction .govuk-tabs__tab').click(window.GOVUK.Transactions.trackStartPageTabs); });
Update JS following component usage
Update JS following component usage
JavaScript
mit
alphagov/frontend,alphagov/frontend,alphagov/frontend,alphagov/frontend
7bad2ae5ca65ef0572fa90ce46f6a20964b6e8ff
vendor/assets/javascripts/flash.js
vendor/assets/javascripts/flash.js
// refactoring from https://github.com/leonid-shevtsov/cacheable-flash-jquery var Flash = new Object(); Flash.data = {}; Flash.transferFromCookies = function() { var data = JSON.parse(unescape($.cookie("flash"))); if(!data) data = {}; Flash.data = data; $.cookie('flash',null, {path: '/'}); }; Flash.writeDataTo = function(name, element) { element = $(element); var content = ""; if (Flash.data[name]) { message = Flash.data[name].toString().replace(/\+/g, ' '); element.html(message); element.show(); } };
// refactoring from https://github.com/leonid-shevtsov/cacheable-flash-jquery var Flash = new Object(); Flash.data = {}; Flash.transferFromCookies = function() { var data = JSON.parse(unescape($.cookie("flash"))); if(!data) data = {}; Flash.data = data; $.cookie('flash',null, {path: '/'}); }; Flash.writeDataTo = function(name, element, callback) { element = $(element); var content = ""; if (Flash.data[name]) { message = Flash.data[name].toString().replace(/\+/g, ' '); element.html(message); if (callback && typeof(callback) === 'function') { callback(element); } else { element.show(); } } };
Add callback argument to Flash.writeDataTo()
Add callback argument to Flash.writeDataTo()
JavaScript
mit
khoan/cacheable-flash,nickurban/cacheable-flash,ndreckshage/cacheable-flash,efigence/cacheable-flash,ekampp/cacheable-flash,pivotal/cacheable-flash,nickurban/cacheable-flash,ekampp/cacheable-flash,pedrocarrico/cacheable-flash,wandenberg/cacheable-flash,pivotal/cacheable-flash,pboling/cacheable-flash,khoan/cacheable-flash,pedrocarrico/cacheable-flash,pivotal/cacheable-flash,pboling/cacheable-flash,pedrocarrico/cacheable-flash,pboling/cacheable-flash,efigence/cacheable-flash,ndreckshage/cacheable-flash,wandenberg/cacheable-flash,ndreckshage/cacheable-flash,pboling/cacheable-flash
20905777baa711def48620d16507222b9ef50761
concepts/frame-list/main.js
concepts/frame-list/main.js
var mercury = require("mercury") var frameList = require("./views/frame-list") var frameEditor = require("./views/frame-editor") var frameData = require("./data/frames") // Load the data var initialFrameData = frameData.load() var frames = mercury.hash(initialFrameData) // When the data changes, save it frames(frameData.save) // Create the default view using the frame set var frameListEditor = frameList(frames) var state = mercury.hash({ frames: frames, editor: frameList }) // Show the frame editor frameListEditor.onSelectFrame(function (frameId) { var editor = frameEditor(frames[frameId]) editor.onExit(function () { // Restore the frame list state.editor.set(frameList) }) }) function render(state) { // This is a mercury partial rendered with editor.state instead // of globalSoup.state // The immutable internal event list is also passed in // Event listeners are obviously not serializable, but // they can expose their state (listener set) return h(state.editor.partial()) } // setup the loop and go. mercury.app(document.body, render, state)
var mercury = require("mercury") var frameList = require("./views/frame-list") var frameEditor = require("./views/frame-editor") var frameData = require("./data/frames") // Load the data var initialFrameData = frameData.load() // Create the default view using the frame set var frameListEditor = frameList(frames) var state = mercury.hash({ frames: mercury.hash(initialFrameData), editor: frameList }) // When the data changes, save it state.frames(frameData.save) // Show the frame editor frameListEditor.onSelectFrame(function (frameId) { var editor = frameEditor(state.frames[frameId]) editor.onExit(function () { // Restore the frame list state.editor.set(frameList) }) }) function render(state) { // This is a mercury partial rendered with editor.state instead // of globalSoup.state // The immutable internal event list is also passed in // Event listeners are obviously not serializable, but // they can expose their state (listener set) return h(state.editor.partial()) } // setup the loop and go. mercury.app(document.body, render, state)
Consolidate the two pieces of state into a single atom
Consolidate the two pieces of state into a single atom This helps readability of the code by knowing there is only one variable that contains the state and only one variable that can be mutated. This means if you refactor the code into multiple files you only have to pass this one variable into the functions from the other file.
JavaScript
mit
Raynos/mercury,eriser/mercury,staltz/mercury,staltz/mercury,eightyeight/mercury,beni55/mercury,mpal9000/mercury,jxson/mercury,vlad-x/mercury,martintietz/mercury,tommymessbauer/mercury
3c4d2080e1602fbeafcfbc71befbb591a186b2b1
webserver/static/js/main.js
webserver/static/js/main.js
console.log("Hello Console!"); host = window.location.host.split(":")[0]; console.log(host); var conn; $(document).ready(function () { conn = new WebSocket("ws://"+host+":8888/ws"); conn.onclose = function(evt) { console.log("connection closed"); } conn.onmessage = function(evt) { console.log("received : " + evt.data); } }); // Byte String -> Boolean function sendPacket(id, data) { return conn.send(String.fromCharCode(id) + data); } function sendit() { console.log(sendPacket(1, '{"msg": "hi"}')); }
console.log("Hello Console!"); host = window.location.host.split(":")[0]; console.log(host); var conn; $(document).ready(function () { initializePacketHandlers(); conn = new WebSocket("ws://"+host+":8888/ws"); conn.onclose = function(evt) { console.log("connection closed"); } conn.onmessage = function(evt) { console.log("received : " + evt.data); //handlePacket(evt.data) } }); //---- Packet Ids var LOGIN_PID = 0; var PACKET_HANDLERS = {}; function initializePacketHandlers() { //PACKET_HANDLERS[PID] = callback_function; } //--- Packet Senders // String String -> Bool function sendLogin(username, token) { return sendPacket(LOGIN_PID, { Username: username, Token: token }) } // Byte String -> Bool function sendPacket(id, data) { return conn.send(String.fromCharCode(id) + JSON.stringify(data)); } function sendit() { console.log(sendPacket(1, { msg: "hi" })); } //---- Packet Handlers // String -> ? function handlePacket(packet) { var pid = packet.charCodeAt(0); var data = packet.substring(1); handler = PACKET_HANDLERS[pid]; return handler(data); }
Expand the JS code a bit to prepare for networking code
Expand the JS code a bit to prepare for networking code
JavaScript
mit
quintenpalmer/attempt,quintenpalmer/attempt,quintenpalmer/attempt,quintenpalmer/attempt
43f89d6a8a19f87d57ee74b30b7f0e664a958a2f
tests/integration/components/canvas-block-filter/component-test.js
tests/integration/components/canvas-block-filter/component-test.js
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('canvas-block-filter', 'Integration | Component | canvas block filter', { integration: true }); test('it renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{canvas-block-filter}}`); assert.ok(this.$('input[type=text]').get(0)); });
import { moduleForComponent, test } from 'ember-qunit'; import Ember from 'ember'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('canvas-block-filter', 'Integration | Component | canvas block filter', { integration: true }); test('it binds a filter term', function(assert) { this.set('filterTerm', 'Foo'); this.render(hbs`{{canvas-block-filter filterTerm=filterTerm}}`); assert.equal(this.$('input').val(), 'Foo'); this.$('input').val('Bar').trigger('input'); assert.equal(this.get('filterTerm'), 'Bar'); }); test('it clears the filter when closing', function(assert) { this.set('filterTerm', 'Foo'); this.set('onCloseFilter', Ember.K); this.render(hbs`{{canvas-block-filter onCloseFilter=onCloseFilter filterTerm=filterTerm}}`); this.$('button').click(); assert.equal(this.get('filterTerm'), ''); }); test('it calls a close callback', function(assert) { this.set('onCloseFilter', _ => assert.ok(true)); this.render(hbs`{{canvas-block-filter onCloseFilter=onCloseFilter}}`); this.$('button').click(); });
Add meaningful tests to canvas-block-filter
Add meaningful tests to canvas-block-filter
JavaScript
apache-2.0
usecanvas/web-v2,usecanvas/web-v2,usecanvas/web-v2
e9b97e39609d9b592e8c8af0cc00e036d6326cc1
src/lib/listener/onFile.js
src/lib/listener/onFile.js
import {Readable} from "stream" import File from "lib/File" import getFieldPath from "lib/util/getFieldPath" const onFile = (options, cb) => (fieldname, stream, filename, enc, mime) => { try { const path = getFieldPath(fieldname) const contents = new Readable({ read() { /* noop */ } }) const onData = ch => contents.push(ch) const onEnd = () => { contents.push(null) const file = new File({filename, contents, enc, mime}) cb(null, [ path, file ]) } stream .on("data", onData) .on("end", onEnd) } catch (err) { return cb(err) } } export default onFile
import {Readable} from "stream" import File from "lib/File" import getFieldPath from "lib/util/getFieldPath" const onFile = (options, cb) => (fieldname, stream, filename, enc, mime) => { try { const path = getFieldPath(fieldname) const contents = new Readable({ read() { /* noop */ } }) const onData = ch => contents.push(ch) const onEnd = () => { contents.push(null) const file = new File({filename, contents, enc, mime}) cb(null, [ path, file ]) } stream .on("error", cb) .on("data", onData) .on("end", onEnd) } catch (err) { return cb(err) } } export default onFile
Add an error event listener for FileStream.
Add an error event listener for FileStream.
JavaScript
mit
octet-stream/then-busboy,octet-stream/then-busboy
e902c3b71a0ff79ebcb2424098197604d40ed21b
web_external/js/views/body/JobsPanel.js
web_external/js/views/body/JobsPanel.js
minerva.views.JobsPanel = minerva.View.extend({ initialize: function () { var columnEnum = girder.views.jobs_JobListWidget.prototype.columnEnum; var columns = columnEnum.COLUMN_STATUS_ICON | columnEnum.COLUMN_TITLE; this.jobListWidget = new girder.views.jobs_JobListWidget({ columns: columns, showHeader: false, pageLimit: 10, showPaging: false, triggerJobClick: true, parentView: this }).on('g:jobClicked', function (job) { // TODO right way to update specific job? // otherwise can get a detail that is out of sync with actual job status // seems weird to update the entire collection from here // another option is to refresh the job specifically this.jobListWidget.collection.on('g:changed', function () { job = this.jobListWidget.collection.get(job.get('id')); this.jobDetailsWidgetModalWrapper = new minerva.views.JobDetailsWidgetModalWrapper({ job: job, el: $('#g-dialog-container'), parentView: this }); this.jobDetailsWidgetModalWrapper.render(); }, this); this.jobListWidget.collection.fetch({}, true); }, this); girder.events.on('m:job.created', function () { this.jobListWidget.collection.fetch({}, true); }, this); }, render: function () { this.$el.html(minerva.templates.jobsPanel({})); this.jobListWidget.setElement(this.$('.m-jobsListContainer')).render(); return this; } });
minerva.views.JobsPanel = minerva.View.extend({ initialize: function () { var columnEnum = girder.views.jobs_JobListWidget.prototype.columnEnum; var columns = columnEnum.COLUMN_STATUS_ICON | columnEnum.COLUMN_TITLE; this.jobListWidget = new girder.views.jobs_JobListWidget({ columns: columns, showHeader: false, pageLimit: 10, showPaging: false, triggerJobClick: true, parentView: this }).on('g:jobClicked', function (job) { // update the job before displaying, as the job in the collection // could be stale and out of sync from the display in the job panel job.once('g:fetched', function () { this.jobDetailsWidgetModalWrapper = new minerva.views.JobDetailsWidgetModalWrapper({ job: job, el: $('#g-dialog-container'), parentView: this }); this.jobDetailsWidgetModalWrapper.render(); }, this).fetch(); }, this); girder.events.on('m:job.created', function () { this.jobListWidget.collection.fetch({}, true); }, this); }, render: function () { this.$el.html(minerva.templates.jobsPanel({})); this.jobListWidget.setElement(this.$('.m-jobsListContainer')).render(); return this; } });
Update job when job detail clicked
Update job when job detail clicked
JavaScript
apache-2.0
Kitware/minerva,Kitware/minerva,Kitware/minerva
fb73e6394654a38439387994556680215a93c0b3
addon/components/page-pagination.js
addon/components/page-pagination.js
import Ember from 'ember'; import layout from '../templates/components/page-pagination'; export default Ember.Component.extend({ layout: layout, keys: ['first', 'prev', 'next', 'last'], sortedLinks: Ember.computed('keys', 'links', function() { var result = {}; this.get('keys').map( (key) => { result[key] = this.get('links')[key]; }); if (!this.get('links.prev')) { result['first'] = undefined; } if (!this.get('links.next')) { result['last'] = undefined; } return result; }), actions: { changePage(link) { this.set('page', link['number'] || 0); this.set('size', link['size'] || 0); } } });
import Ember from 'ember'; import layout from '../templates/components/page-pagination'; export default Ember.Component.extend({ layout: layout, keys: ['first', 'prev', 'next', 'last'], sortedLinks: Ember.computed('keys', 'links', function() { var result = {}; this.get('keys').map( (key) => { result[key] = this.get('links')[key]; }); if (!this.get('links.prev')) { result['first'] = undefined; } if (!this.get('links.next')) { result['last'] = undefined; } return result; }), actions: { changePage(link) { this.set('page', link['number'] || 0); if (link['size']) { this.set('size', link['size']); } } } });
Fix unsensible default for page size
Fix unsensible default for page size
JavaScript
mit
mu-semtech/ember-data-table,erikap/ember-data-table,erikap/ember-data-table,mu-semtech/ember-data-table
ff552ff6677bbc93ab7a750184dfd79109c1a837
src/mock-get-user-media.js
src/mock-get-user-media.js
// Takes a mockOnStreamAvailable function which when given a webrtcstream returns a new stream // to replace it with. module.exports = function mockGetUserMedia(mockOnStreamAvailable) { let oldGetUserMedia; if (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) { oldGetUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; navigator.webkitGetUserMedia = navigator.getUserMedia = navigator.mozGetUserMedia = function getUserMedia(constraints, onStreamAvailable, onStreamAvailableError, onAccessDialogOpened, onAccessDialogClosed, onAccessDenied) { return oldGetUserMedia.call(navigator, constraints, stream => { onStreamAvailable(mockOnStreamAvailable(stream)); }, onStreamAvailableError, onAccessDialogOpened, onAccessDialogClosed, onAccessDenied); }; } else { console.warn('Could not find getUserMedia function to mock out'); } };
// Takes a mockOnStreamAvailable function which when given a webrtcstream returns a new stream // to replace it with. module.exports = function mockGetUserMedia(mockOnStreamAvailable) { let oldGetUserMedia; if (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) { oldGetUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; navigator.webkitGetUserMedia = navigator.getUserMedia = navigator.mozGetUserMedia = function getUserMedia(constraints, onStreamAvailable, onStreamAvailableError, onAccessDialogOpened, onAccessDialogClosed, onAccessDenied) { return oldGetUserMedia.call(navigator, constraints, stream => { onStreamAvailable(mockOnStreamAvailable(stream)); }, onStreamAvailableError, onAccessDialogOpened, onAccessDialogClosed, onAccessDenied); }; } else if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { oldGetUserMedia = navigator.mediaDevices.getUserMedia; navigator.mediaDevices.getUserMedia = function getUserMedia (constraints) { return new Promise(function (resolve, reject) { oldGetUserMedia.call(navigator.mediaDevices, constraints).then(stream => { resolve(mockOnStreamAvailable(stream)); }, reason => { reject(reason); }).catch(err => { console.error('Error getting mock stream', err); }); }); }; } else { console.warn('Could not find getUserMedia function to mock out'); } };
Add MediaDevices support for mock getUserMedia
Add MediaDevices support for mock getUserMedia Signed-off-by: Kaustav Das Modak <ba1ce5b1e09413a89404909d8d270942c5dadd14@yahoo.co.in>
JavaScript
mit
aullman/opentok-camera-filters,aullman/opentok-camera-filters
fac9a134cafcecd5b2ef52d4c1a99123f9df0ff9
app/scripts/configs/modes/portal.js
app/scripts/configs/modes/portal.js
'use strict'; angular.module('ncsaas') .constant('MODE', { modeName: 'modePortal', toBeFeatures: [ 'localSignup', 'localSignin', 'team', 'monitoring', 'backups', 'templates', 'sizing', 'projectGroups' ], featuresVisible: false, comingFeatures: [ 'applications', ] });
'use strict'; angular.module('ncsaas') .constant('MODE', { modeName: 'modePortal', toBeFeatures: [ 'localSignup', 'localSignin', 'password', 'team', 'monitoring', 'backups', 'templates', 'sizing', 'projectGroups', 'apps', 'premiumSupport' ], featuresVisible: false, appStoreCategories: [ { name: 'VMs', type: 'provider', icon: 'desktop', services: ['Amazon', 'DigitalOcean', 'OpenStack'] }, { name: 'Private clouds', type: 'provider', icon: 'cloud', services: ['OpenStack'] } ], serviceCategories: [ { name: 'Virtual machines', services: ['Amazon', 'DigitalOcean', 'OpenStack'], } ] });
Disable Azure, Gitlab, Application, Support providers (SAAS-1329)
Disable Azure, Gitlab, Application, Support providers (SAAS-1329)
JavaScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
3a5424c8966c899461191654e8b1de3e99dd2914
mezzanine/core/media/js/collapse_inline.js
mezzanine/core/media/js/collapse_inline.js
$(function() { var grappelli = !!$('#bookmarks'); var parentSelector = grappelli ? 'div.items' : 'tbody'; // Hide the exta inlines. $(parentSelector + ' > *:not(.has_original)').hide(); // Re-show inlines with errors, poetentially hidden by previous line. var errors = $(parentSelector + ' ul[class=errorlist]').parent().parent(); if (grappelli) { errors = errors.parent(); } errors.show(); // Add the 'Add another' link to the end of the inlines. var parent = $(parentSelector).parent(); if (!grappelli) { parent = parent.parent(); } parent.append('<p class="add-another"><a href="#">Add another</a></p>'); $('.add-another').click(function() { // Show a new inline when the 'Add another' link is clicked. var rows = $(this).parent().find(parentSelector + ' > *:hidden'); $(rows[0]).show(); if (rows.length == 1) { $(this).hide(); } return false; }); // Show the first hidden inline - grappelli's inline header is actually // part of the selector so for it we run this twice. $('.add-another').click(); if (grappelli) { $('.add-another').click(); } });
$(function() { var grappelli = !!$('#bookmarks'); var parentSelector = grappelli ? 'div.items' : 'tbody'; // Hide the exta inlines. $(parentSelector + ' > *:not(.has_original)').hide(); // Re-show inlines with errors, poetentially hidden by previous line. var errors = $(parentSelector + ' ul[class=errorlist]').parent().parent(); if (grappelli) { errors = errors.parent(); } errors.show(); // Add the 'Add another' link to the end of the inlines. var parent = $(parentSelector).parent(); if (!grappelli) { parent = parent.parent(); } parent.append('<p class="add-another add-another-inline">' + '<a href="#">Add another</a></p>'); $('.add-another-inline').click(function() { // Show a new inline when the 'Add another' link is clicked. var rows = $(this).parent().find(parentSelector + ' > *:hidden'); $(rows[0]).show(); if (rows.length == 1) { $(this).hide(); } return false; }); // Show the first hidden inline - grappelli's inline header is actually // part of the selector so for it we run this twice. $('.add-another-inline').click(); if (grappelli) { $('.add-another-inline').click(); } });
Make class name unique for dynamic inlines.
Make class name unique for dynamic inlines.
JavaScript
bsd-2-clause
dustinrb/mezzanine,tuxinhang1989/mezzanine,ZeroXn/mezzanine,scarcry/snm-mezzanine,nikolas/mezzanine,biomassives/mezzanine,gradel/mezzanine,adrian-the-git/mezzanine,damnfine/mezzanine,wbtuomela/mezzanine,guibernardino/mezzanine,wbtuomela/mezzanine,Cicero-Zhao/mezzanine,molokov/mezzanine,PegasusWang/mezzanine,cccs-web/mezzanine,jjz/mezzanine,eino-makitalo/mezzanine,agepoly/mezzanine,stbarnabas/mezzanine,viaregio/mezzanine,vladir/mezzanine,christianwgd/mezzanine,orlenko/sfpirg,dustinrb/mezzanine,adrian-the-git/mezzanine,mush42/mezzanine,douglaskastle/mezzanine,PegasusWang/mezzanine,stbarnabas/mezzanine,gbosh/mezzanine,saintbird/mezzanine,mush42/mezzanine,spookylukey/mezzanine,jerivas/mezzanine,ZeroXn/mezzanine,Cajoline/mezzanine,jjz/mezzanine,dovydas/mezzanine,jerivas/mezzanine,agepoly/mezzanine,eino-makitalo/mezzanine,theclanks/mezzanine,dekomote/mezzanine-modeltranslation-backport,stephenmcd/mezzanine,Skytorn86/mezzanine,SoLoHiC/mezzanine,frankier/mezzanine,sjdines/mezzanine,jerivas/mezzanine,promil23/mezzanine,stephenmcd/mezzanine,batpad/mezzanine,Skytorn86/mezzanine,Kniyl/mezzanine,tuxinhang1989/mezzanine,gbosh/mezzanine,guibernardino/mezzanine,sjdines/mezzanine,Cajoline/mezzanine,viaregio/mezzanine,theclanks/mezzanine,douglaskastle/mezzanine,dovydas/mezzanine,frankier/mezzanine,theclanks/mezzanine,nikolas/mezzanine,Cajoline/mezzanine,scarcry/snm-mezzanine,webounty/mezzanine,frankier/mezzanine,orlenko/sfpirg,damnfine/mezzanine,dustinrb/mezzanine,emile2016/mezzanine,douglaskastle/mezzanine,dsanders11/mezzanine,readevalprint/mezzanine,sjdines/mezzanine,sjuxax/mezzanine,webounty/mezzanine,spookylukey/mezzanine,ryneeverett/mezzanine,christianwgd/mezzanine,ryneeverett/mezzanine,fusionbox/mezzanine,frankchin/mezzanine,jjz/mezzanine,industrydive/mezzanine,agepoly/mezzanine,promil23/mezzanine,gradel/mezzanine,dekomote/mezzanine-modeltranslation-backport,biomassives/mezzanine,AlexHill/mezzanine,saintbird/mezzanine,molokov/mezzanine,joshcartme/mezzanine,SoLoHiC/mezzanine,PegasusWang/mezzanine,wyzex/mezzanine,christianwgd/mezzanine,gbosh/mezzanine,wrwrwr/mezzanine,wbtuomela/mezzanine,sjuxax/mezzanine,dsanders11/mezzanine,fusionbox/mezzanine,spookylukey/mezzanine,readevalprint/mezzanine,adrian-the-git/mezzanine,orlenko/plei,wyzex/mezzanine,geodesign/mezzanine,viaregio/mezzanine,geodesign/mezzanine,orlenko/plei,Cicero-Zhao/mezzanine,orlenko/plei,orlenko/sfpirg,biomassives/mezzanine,dsanders11/mezzanine,emile2016/mezzanine,industrydive/mezzanine,nikolas/mezzanine,cccs-web/mezzanine,ryneeverett/mezzanine,scarcry/snm-mezzanine,joshcartme/mezzanine,webounty/mezzanine,dekomote/mezzanine-modeltranslation-backport,wrwrwr/mezzanine,mush42/mezzanine,sjuxax/mezzanine,stephenmcd/mezzanine,tuxinhang1989/mezzanine,vladir/mezzanine,dovydas/mezzanine,AlexHill/mezzanine,geodesign/mezzanine,damnfine/mezzanine,readevalprint/mezzanine,eino-makitalo/mezzanine,promil23/mezzanine,vladir/mezzanine,industrydive/mezzanine,ZeroXn/mezzanine,saintbird/mezzanine,joshcartme/mezzanine,Kniyl/mezzanine,wyzex/mezzanine,molokov/mezzanine,emile2016/mezzanine,frankchin/mezzanine,SoLoHiC/mezzanine,Kniyl/mezzanine,batpad/mezzanine,Skytorn86/mezzanine,gradel/mezzanine,frankchin/mezzanine
94d2f1a72a525e0a36cd247b299150a87445d2e4
lib/nrouter/common.js
lib/nrouter/common.js
'use strict'; var Common = module.exports = {}; // iterates through all object keys-value pairs calling iterator on each one // example: $$.each(objOrArr, function (val, key) { /* ... */ }); Common.each = function each(obj, iterator, context) { var keys, i, l; if (null === obj || undefined === obj) { return; } context = context || iterator; if (Array.prototype.forEach && obj.forEach === Array.prototype.forEach) { obj.forEach(iterator, context); } else { keys = Object.getOwnPropertyNames(obj); for (i = 0, l = keys.length; i < l; i += 1) { if (false === iterator.call(context, obj[keys[i]], keys[i], obj)) { // break return; } } } };
'use strict'; var Common = module.exports = {}; // iterates through all object keys-value pairs calling iterator on each one // example: $$.each(objOrArr, function (val, key) { /* ... */ }); Common.each = function each(obj, iterator, context) { var keys, i, l; if (null === obj || undefined === obj) { return; } context = context || iterator; keys = Object.getOwnPropertyNames(obj); // not using Array#forEach, as it does not allows to stop iterator for (i = 0, l = keys.length; i < l; i += 1) { if (false === iterator.call(context, obj[keys[i]], keys[i], obj)) { // break return; } } };
Remove forEach fallback in Common.each
Remove forEach fallback in Common.each
JavaScript
mit
nodeca/pointer
c6578b2bb3652c65bcc5b0342efefde11aad034e
app.js
app.js
$(function(){ var yourSound = new Audio('notification.ogg'); yourSound.loop = true; $('.start button').click(function(ev){ $('.start').toggleClass('hidden'); $(".example").TimeCircles({ "animation": "ticks", "count_past_zero": false, "circle_bg_color": "#f1f1f1", "time": { Days: { show: false }, Hours: { show: false }, Minutes: { color: "#1abc9c" }, Seconds: { color: "#e74c3c" } } }).addListener(function(unit, value, total){ if(!total){ yourSound.play(); $('.stop').toggleClass('hidden'); } }); }); $('.stop button').click(function(ev){ yourSound.pause(); $(".example").TimeCircles().destroy(); $('.stop').toggleClass('hidden'); $('.start').toggleClass('hidden'); }); });
$(function(){ var yourSound = new Audio('notification.ogg'); yourSound.loop = true; $('.start button').click(function(ev){ $('.start').toggleClass('hidden'); $('.stop').toggleClass('hidden'); $(".example").TimeCircles({ "animation": "ticks", "count_past_zero": false, "circle_bg_color": "#f1f1f1", "time": { Days: { show: false }, Hours: { show: false }, Minutes: { color: "#1abc9c" }, Seconds: { color: "#e74c3c" } } }).addListener(function(unit, value, total){ if(!total){ yourSound.play(); } }); }); $('.stop button').click(function(ev){ yourSound.pause(); $(".example").TimeCircles().destroy(); $('.stop').toggleClass('hidden'); $('.start').toggleClass('hidden'); }); });
Stop button always visible when clock is running
Stop button always visible when clock is running
JavaScript
mit
dplesca/getup
32383c5d18a74120da107a708abfee60a601bb27
app/scripts/main.js
app/scripts/main.js
'use strict'; // Toogle asset images - zome in and out $(function() { var Snackbar = window.Snackbar; Snackbar.init(); var AssetPage = window.AssetPage; AssetPage.init(); // We only want zooming on asset's primary images. $('.asset .zoomable').click(function() { var $thisRow = $(this).closest('.image-row'); if ($thisRow.hasClass('col-md-6')) { $thisRow.removeClass('col-md-6').addClass('col-md-12'); $thisRow.next('div').addClass('col-md-offset-3') .removeClass('pull-right'); } else { $thisRow.removeClass('col-md-12').addClass('col-md-6'); $thisRow.next('div').removeClass('col-md-offset-3') .addClass('pull-right'); } }); var hideAllDropdowns = function() { $('.dropdown').removeClass('dropdown--active'); $('body').off('click', hideAllDropdowns); }; $('.dropdown__selected').on('click', function() { var $this = $(this); var $dropdown = $this.closest('.dropdown'); if ($dropdown.hasClass('dropdown--active') === false) { $dropdown.addClass('dropdown--active'); setTimeout(function() { $('body').off('click', hideAllDropdowns).on('click', hideAllDropdowns); }, 1); } }); });
'use strict'; // Toogle asset images - zome in and out $(function() { var Snackbar = window.Snackbar; Snackbar.init(); var AssetPage = window.AssetPage; AssetPage.init(); // We only want zooming on asset's primary images. $('.asset .zoomable').click(function() { var $thisRow = $(this).closest('.image-row'); if ($thisRow.hasClass('col-md-6')) { $thisRow.removeClass('col-md-6').addClass('col-md-12'); $thisRow.next('div').addClass('col-md-offset-3') .removeClass('pull-right'); } else { $thisRow.removeClass('col-md-12').addClass('col-md-6'); $thisRow.next('div').removeClass('col-md-offset-3') .addClass('pull-right'); } }); var hideAllDropdowns = function() { $('.dropdown').removeClass('dropdown--active'); $('body').off('click', hideAllDropdowns); }; $('.dropdown__selected').on('click', function() { var $this = $(this); $('body').off('click', hideAllDropdowns); $('.dropdown').removeClass('dropdown--active'); var $dropdown = $this.closest('.dropdown'); if ($dropdown.hasClass('dropdown--active') === false) { $dropdown.addClass('dropdown--active'); setTimeout(function() { $('body').on('click', hideAllDropdowns); }, 1); } }); });
Fix bug in dropdowns, where they didn’t disappear correctly
Fix bug in dropdowns, where they didn’t disappear correctly
JavaScript
mit
CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder
e7ed223545ffa3fea6d996eb2920908275a69cc9
cli.js
cli.js
#!/usr/bin/env node 'use strict'; const fs = require('fs'); const minimist = require('minimist'); const pkg = require('./package.json'); const oust = require('.'); const argv = minimist(process.argv.slice(2)); function printHelp() { console.log([ pkg.description, '', 'Usage', ' $ oust <filename> <type>', '', 'Example', ' $ oust index.html scripts' ].join('\n')); } if (argv.v || argv.version) { console.log(pkg.version); process.exit(0); } if (argv.h || argv.help || argv._.length === 0) { printHelp(); process.exit(0); } const file = argv._[0]; const type = argv._[1]; fs.readFile(file, (err, data) => { if (err) { console.error('Error opening file:', err.message); process.exit(1); } console.log(oust(data, type).join('\n')); });
#!/usr/bin/env node 'use strict'; const fs = require('fs'); const minimist = require('minimist'); const pkg = require('./package.json'); const oust = require('.'); const argv = minimist(process.argv.slice(2)); function printHelp() { console.log(` ${pkg.description} Usage: $ oust <filename> <type> Example: $ oust index.html scripts`); } if (argv.v || argv.version) { console.log(pkg.version); process.exit(0); } if (argv.h || argv.help || argv._.length === 0) { printHelp(); process.exit(0); } const file = argv._[0]; const type = argv._[1]; fs.readFile(file, (err, data) => { if (err) { console.error('Error opening file:', err.message); process.exit(1); } console.log(oust(data, type).join('\n')); });
Switch to template literals for the help screen.
Switch to template literals for the help screen.
JavaScript
apache-2.0
addyosmani/oust,addyosmani/oust
88305e481396644d88a08605ba786bd1dce35af6
src/scripts/json-minify.js
src/scripts/json-minify.js
function minifyJson(data) { return JSON.stringify(JSON.parse(data)); } export function minifyJsonFile(readFileFn, fileName) { return minifyJson(readFileFn(fileName)); }
export function minifyJsonFile(readFileFn, fileName) { const minifyJson = new MinifyJson(readFileFn); return minifyJson.fromFile(fileName); } class MinifyJson { constructor(readFileFunction) { this.readFileFunction = readFileFunction; } fromFile(fileName) { const fileContent = this.readFileFunction(fileName); return MinifyJson.fromString(fileContent); } static fromString(data) { return JSON.stringify(JSON.parse(data)); } }
Refactor it out into a class.
Refactor it out into a class.
JavaScript
mit
cosmowiki/cosmowiki,cosmowiki/cosmowiki,cosmowiki/cosmowiki,cosmowiki/cosmowiki
084a1d1d7139d96540648a9938749a9d36d2efa4
desktop/src/lib/database.js
desktop/src/lib/database.js
/* eslint-env browser */ const fs = window.require('fs'); const fetchInitialState = () => { const data = fs.readFileSync('.config/db', 'utf-8'); if (data) { return JSON.parse(data); } return {}; }; const update = (state) => { fs.writeFileSync('.config/db', JSON.stringify(state), 'utf-8'); }; export { fetchInitialState, update };
/* eslint-env browser */ const fs = window.require('fs'); const fetchInitialState = () => { let data = fs.readFileSync('.config/db', 'utf-8'); if (data) { data = JSON.parse(data); return { tasks: { past: [], present: data.tasks, future: [], history: [], }, ideas: { past: [], present: data.ideas, future: [], history: [], }, appProperties: data.appProperties, }; } return {}; }; const update = (state) => { fs.writeFileSync('.config/db', JSON.stringify({ tasks: state.tasks.present, ideas: state.ideas.present, appProperties: state.appProperties, }), 'utf-8'); }; export { fetchInitialState, update };
Fix minor issue about making redux-undo state permanent
Fix minor issue about making redux-undo state permanent
JavaScript
mit
mkermani144/wanna,mkermani144/wanna
f5128b1e6c2581a5a1b33977914a23195ac4ad3d
scripts/entry.js
scripts/entry.js
#!/usr/bin/env node import childProcess from 'child_process'; import fs from 'fs-extra'; import moment from 'moment'; const today = new Date(); const path = `pages/posts/${moment(today).format('YYYY-MM-DD')}.md`; /** * Set Weekdays Locale */ moment.locale('jp', {weekdays: ['日', '月', '火', '水', '木', '金', '土']}); /** * Get Post Template * * @return {string} */ function getPostTmp() { return [ '---\n', 'title: "post"\n', `date: "${moment(today).format('YYYY-MM-DD HH:mm:ss (dddd)')}"\n`, 'layout: post\n', `path: "/${moment(today).format('YYYYMMDD')}/"\n`, '---' ].join(''); } /** * If already been created: Open File * else: Create & Open File */ fs.open(path, 'r+', err => { if (err) { const ws = fs.createOutputStream(path); ws.write(getPostTmp()); } childProcess.spawn('vim', [path], {stdio: 'inherit'}); });
#!/usr/bin/env node import childProcess from 'child_process'; import fs from 'fs-extra'; import moment from 'moment'; const today = new Date(); const path = `pages/posts/${moment(today).format('YYYY-MM-DD')}.md`; /** * Set Weekdays Locale */ moment.locale('jp', {weekdays: ['日', '月', '火', '水', '木', '金', '土']}); /** * Get Post Template * * @return {string} */ function getPostTmp() { return [ '---\n', 'title: "post"\n', `date: "${moment(today).format('YYYY-MM-DD HH:mm:ss (dddd)')}"\n`, 'layout: post\n', `path: "/${moment(today).format('YYYYMMDD')}/"\n`, '---' ].join(''); } /** * If already been created: Open File * else: Create & Open File */ fs.open(path, 'r+', err => { if (err) { fs.outputFile(path, getPostTmp()); } childProcess.spawn('vim', [path], {stdio: 'inherit'}); });
Fix fs-extra breaking change :bread:
fix(scripts): Fix fs-extra breaking change :bread:
JavaScript
mit
ideyuta/sofar
ba5f567a44a5d7325f894c42e48f696f6925907b
routes/user/index.js
routes/user/index.js
"use strict"; var db = require('../../models'); var config = require('../../config.js'); var authHelper = require('../../lib/auth-helper'); module.exports = function (app, options) { app.get('/user/tokens', authHelper.ensureAuthenticated, function(req, res, next) { db.ServiceAccessToken .findAll({ include: [db.ServiceProvider] }) .complete(function(err, tokens) { if (err) { next(err); return; } res.render('./user/token_list.ejs', { tokens: tokens }); }); }); };
"use strict"; var config = require('../../config'); var db = require('../../models'); var authHelper = require('../../lib/auth-helper'); module.exports = function (app, options) { app.get('/user/tokens', authHelper.ensureAuthenticated, function(req, res, next) { db.ServiceAccessToken .findAll({ include: [db.ServiceProvider] }) .complete(function(err, tokens) { if (err) { next(err); return; } res.render('./user/token_list.ejs', { tokens: tokens }); }); }); };
Remove .js extension in require()
Remove .js extension in require()
JavaScript
bsd-3-clause
ebu/cpa-auth-provider
7788c984c07d81af3f819a93dac8f663f93063b8
src/clincoded/static/libs/render_variant_title_explanation.js
src/clincoded/static/libs/render_variant_title_explanation.js
'use strict'; import React from 'react'; import { ContextualHelp } from './bootstrap/contextual_help'; /** * Method to render a mouseover explanation for the variant title */ export function renderVariantTitleExplanation() { const explanation = 'The transcript with the longest translation with no stop codons. If no translation, then the longest non-protein-coding transcript.'; return ( <span className="variant-title-explanation"><ContextualHelp content={explanation} /></span> ); }
'use strict'; import React from 'react'; import { ContextualHelp } from './bootstrap/contextual_help'; /** * Method to render a mouseover explanation for the variant title */ export function renderVariantTitleExplanation() { const explanation = 'For ClinVar alleles, this represents the ClinVar Preferred Title. For alleles not in ClinVar, this HGVS is based on the transcript with the longest translation with no stop codons or, if no translation, the longest non-protein-coding transcript. If a single canonical transcript is not discernible the HGVS is based on the GRCh38 genomic coordinates.'; return ( <span className="variant-title-explanation"><ContextualHelp content={explanation} /></span> ); }
Update variant title explanation text
Update variant title explanation text
JavaScript
mit
ClinGen/clincoded,ClinGen/clincoded,ClinGen/clincoded,ClinGen/clincoded,ClinGen/clincoded
00c45bc2e33b6c1236d87c6572cfee3610410bb5
server/fake-users.js
server/fake-users.js
var faker = require('faker'); var _ = require('lodash'); /** * Generate a list of random users. * @return {Array<{ * name: string, * email: string, * phone: string * }>} */ var getUsers = function() { return _.times(3).map(function() { return { name: faker.name.findName(), email: faker.internet.email(), phone: faker.phone.phoneNumber() } }) }; module.exports = { getUsers: getUsers };
var faker = require('faker'); var _ = require('lodash'); /** * Generate a list of random users. * @return {Array<{ * name: string, * email: string, * phone: string * }>} */ var getUsers = function() { var chuckNorris = { name: 'Chuck Norris', email: 'chuck@gmail.com', phone: '212-555-1234' }; var rambo = { name: 'John Rambo', email: 'rambo@gmail.com', phone: '415-555-9876' }; var fakeUsers = _.times(6).map(function() { return { name: faker.name.findName(), email: faker.internet.email(), phone: faker.phone.phoneNumber() }; }); // Add chuck norris at the beginning fakeUsers.unshift(chuckNorris); // Add rambo in the middle (range 1-4) var randomIndex = (new Date()).getTime() % 4 + 1; // removes 0 elements from index 'randomIndex', and inserts item fakeUsers.splice(randomIndex, 0, rambo); return fakeUsers; }; module.exports = { getUsers: getUsers };
Add chuck norris and rambo
Add chuck norris and rambo
JavaScript
mit
andresdominguez/protractor-codelab,andresdominguez/protractor-codelab
85a1333dbd1382da6176352f35481e245c846a8e
src/.eslintrc.js
src/.eslintrc.js
module.exports = { "env": { "browser": true, "commonjs": true, "es6": true }, "extends": "eslint:recommended", "installedESLint": true, "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true, "jsx": true }, "sourceType": "module" }, "plugins": [ "react" ], "rules": { "react/jsx-uses-vars": 1, "indent": [ "error", 4 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "never" ] } };
module.exports = { "env": { "browser": true, "commonjs": true, "es6": true }, "extends": "eslint:recommended", "installedESLint": true, "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true, "jsx": true }, "sourceType": "module" }, "plugins": [ "react" ], "rules": { "react/jsx-uses-vars": 1, "react/jsx-uses-react": [1], "indent": [ "error", 4 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "never" ] } };
Make linter know when JSX is using React variable
Make linter know when JSX is using React variable
JavaScript
bsd-3-clause
rlorenzo/tmlpstats,rlorenzo/tmlpstats,rlorenzo/tmlpstats,rlorenzo/tmlpstats,tmlpstats/tmlpstats,tmlpstats/tmlpstats,tmlpstats/tmlpstats,rlorenzo/tmlpstats,tmlpstats/tmlpstats
55d69b6528833130d4f1e0118368b9a5ed9f587a
src/TcpReader.js
src/TcpReader.js
function TcpReader(callback) { this.callback = callback; this.buffer = ""; }; TcpReader.prototype.read = function(data) { this.buffer = this.buffer.concat(data); size = this.payloadSize( this.buffer ); while ( size > 0 && this.buffer.length >= ( 6 + size ) ) { this.consumeOne( size ); size = this.payloadSize( this.buffer ); } } TcpReader.prototype.payloadSize = function(buffer) { if ( this.buffer.length >= 6 ){ return parseInt( buffer.slice( 0,6 ) ); } else { return -1; } } TcpReader.prototype.consumeOne = function(size) { messageStart = 6; messageEnd = 6 + size; this.callback( this.buffer.slice( messageStart, messageEnd ) ); this.buffer = this.buffer.slice( messageEnd, this.buffer.length ); } if(typeof module !== 'undefined' && module.exports){ module.exports = TcpReader; }
function TcpReader(callback) { this.callback = callback; this.buffer = ""; }; TcpReader.prototype.read = function(data) { this.buffer = this.buffer.concat(data); var size = this.payloadSize( this.buffer ); while ( size > 0 && this.buffer.length >= ( 6 + size ) ) { this.consumeOne( size ); size = this.payloadSize( this.buffer ); } } TcpReader.prototype.payloadSize = function(buffer) { if ( this.buffer.length >= 6 ){ return parseInt( buffer.slice( 0,6 ), 10 ); } else { return -1; } } TcpReader.prototype.consumeOne = function(size) { var messageStart = 6; var messageEnd = 6 + size; this.callback( this.buffer.slice( messageStart, messageEnd ) ); this.buffer = this.buffer.slice( messageEnd, this.buffer.length ); } if(typeof module !== 'undefined' && module.exports){ module.exports = TcpReader; }
Patch parseInt usage to specify radix explicitly
Patch parseInt usage to specify radix explicitly My node install informed me that parseInt('000039') === 3, so: womp womp. This commit also avoids a couple of globals.
JavaScript
bsd-3-clause
noam-io/lemma-javascript,noam-io/lemma-javascript
3a02688886a40dbb922c034811bbdf5399c06929
src/app/wegas.js
src/app/wegas.js
var ServiceURL = "/api/"; angular.module('Wegas', [ 'ui.router', 'wegas.service.auth', 'wegas.behaviours.tools', 'public', 'private' ]) .config(function ($stateProvider, $urlRouterProvider) { $stateProvider .state('wegas', { url: '/', views: { 'main@': { controller: 'WegasMainCtrl', templateUrl: 'app/wegas.tmpl.html' } } }) ; $urlRouterProvider.otherwise('/'); }).controller('WegasMainCtrl', function WegasMainCtrl($state, Auth) { Auth.getAuthenticatedUser().then(function(user){ if(user == null){ $state.go("wegas.public"); }else{ if(user.isScenarist){ $state.go("wegas.private.scenarist"); }else{ if(user.isTrainer){ $state.go("wegas.private.trainer"); }else{ $state.go("wegas.private.player"); } } } }); });
var ServiceURL = "/api/"; angular.module('Wegas', [ 'ui.router', 'ngAnimate', 'wegas.service.auth', 'wegas.behaviours.tools', 'public', 'private' ]) .config(function ($stateProvider, $urlRouterProvider) { $stateProvider .state('wegas', { url: '/', views: { 'main@': { controller: 'WegasMainCtrl', templateUrl: 'app/wegas.tmpl.html' } } }) ; $urlRouterProvider.otherwise('/'); }).controller('WegasMainCtrl', function WegasMainCtrl($state, Auth) { Auth.getAuthenticatedUser().then(function(user){ if(user == null){ $state.go("wegas.public"); }else{ if(user.isScenarist){ $state.go("wegas.private.scenarist"); }else{ if(user.isTrainer){ $state.go("wegas.private.trainer"); }else{ $state.go("wegas.private.player"); } } } }); });
Resolve conflict - add module ngAnimate
Resolve conflict - add module ngAnimate
JavaScript
mit
Heigvd/Wegas,ghiringh/Wegas,ghiringh/Wegas,Heigvd/Wegas,Heigvd/Wegas,Heigvd/Wegas,Heigvd/Wegas,ghiringh/Wegas
139065ee61c1c1322879785fe546fc8374a671e2
example/routes.js
example/routes.js
'use strict'; /** * Sets up the routes. * @param {object} app - Express app */ module.exports.setup = function (app) { /** * @swagger * /: * get: * responses: * 200: * description: hello world */ app.get('/', rootHandler); /** * @swagger * /login: * post: * responses: * 200: * description: login */ app.get('/login', loginHandler); }; function rootHandler(req, res) { res.send('Hello World!'); } function loginHandler(req, res) { var user = {}; user.username = req.param('username'); user.password = req.param('password'); res.json(user); }
'use strict'; /** * Sets up the routes. * @param {object} app - Express app */ module.exports.setup = function (app) { /** * @swagger * /: * get: * responses: * 200: * description: hello world */ app.get('/', rootHandler); /** * @swagger * /login: * post: * responses: * 200: * description: login */ app.post('/login', loginHandler); }; function rootHandler(req, res) { res.send('Hello World!'); } function loginHandler(req, res) { var user = {}; user.username = req.param('username'); user.password = req.param('password'); res.json(user); }
Use 2 spaces for deeply nested objects
Use 2 spaces for deeply nested objects
JavaScript
mit
zeornelas/jsdoc-express-with-swagger,zeornelas/jsdoc-express-with-swagger,devlouisc/jsdoc-express-with-swagger,devlouisc/jsdoc-express-with-swagger
371b5cffd0e20c540b01d00076ec38ccc0bda504
spec/leaflet_spec.js
spec/leaflet_spec.js
describe('LeafletMap Ext Component', function() { describe('Basics', function() { var Map = vrs.ux.touch.LeafletMap; it('provides new mapping events', function() { var map = new Map(); expect(map.events.repPicked).toBeDefined(); }); it('provides new mapping events', function() { var map = new Map(); expect(map.events.repPicked).toBeDefined(); }); }); });
/* Disable Leaflet for now describe('LeafletMap Ext Component', function() { describe('Basics', function() { var Map = vrs.ux.touch.LeafletMap; it('provides new mapping events', function() { var map = new Map(); expect(map.events.repPicked).toBeDefined(); }); it('provides new mapping events', function() { var map = new Map(); expect(map.events.repPicked).toBeDefined(); }); }); }); */
Comment out leaflet test for now since it depends upon manually installing leaflet to a given directory path.
Comment out leaflet test for now since it depends upon manually installing leaflet to a given directory path.
JavaScript
mit
vrsource/vrs.ux.touch,vrsource/vrs.ux.touch,vrsource/vrs.ux.touch,vrsource/vrs.ux.touch
9ab9b55982f39de1b9866ee9ba86e4bbd7d2050d
spec/main/program.js
spec/main/program.js
var test = require('test'); test.assert(require('dot-slash') === 10, 'main with "./"'); test.assert(require('js-ext') === 20, 'main with ".js" extension'); test.assert(require('no-ext') === 30, 'main with no extension'); test.assert(require('dot-js-ext') === 40, 'main with "." in module name and ".js" extension'); test.print('DONE', 'info');
var test = require('test'); test.assert(require('dot-slash') === 10, 'main with "./"'); test.assert(require('js-ext') === 20, 'main with ".js" extension'); test.assert(require('no-ext') === 30, 'main with no extension'); test.assert(require('dot-js-ext') === 40, 'main with "." in module name and ".js" extension'); test.assert(require('js-ext') === require("js-ext/a"), 'can require "main" without extension'); test.print('DONE', 'info');
Add test for requiring a package's main module without .js extension
Add test for requiring a package's main module without .js extension
JavaScript
bsd-3-clause
kriskowal/mr,kriskowal/mr
92b65306960142124ca97a6816bd4ce8596714d3
app/js/main.js
app/js/main.js
(function() { 'use strict'; var params = window.location.search.substring(1) .split( '&' ) .reduce(function( object, param ) { var pair = param.split( '=' ).map( decodeURIComponent ); object[ pair[0] ] = pair[1]; return object; }, {} ); var port = params.port || 8080; var host = window.location.hostname; var socket = new WebSocket( 'ws://' + host + ':' + port ); socket.addEventListener( 'message', function( event ) { console.log( event ); }); }) ();
(function() { 'use strict'; var params = window.location.search.substring(1) .split( '&' ) .reduce(function( object, param ) { var pair = param.split( '=' ).map( decodeURIComponent ); object[ pair[0] ] = pair[1]; return object; }, {} ); var port = params.port || 8080; var host = window.location.hostname; var socket = new WebSocket( 'ws://' + host + ':' + port ); socket.addEventListener( 'message', function( event ) { var data = JSON.parse( event.data ); console.log( data ); }); var types = [ 'push', 'toggle', 'xy', 'fader', 'rotary', 'encoder', 'multitoggle', 'multixy', 'multipush', 'multifader' ]; // Boolean. function Push( value ) { this.value = value || false; } function Toggle( value ) { this.value = value || false; } // Numeric. function Fader( value ) { this.value = value || 0; } function Rotary( value ) { this.value = value || 0; } // Coordinates. function XY( x, y ) { this.x = x || 0; this.y = y || 0; } // Collections. function MultiToggle( values ) { this.values = values || []; } function MultiXY( values ) { this.values = values || []; } function MultiPush( values ) { this.values = values || []; } }) ();
Add basic TouchOSC data structures.
Add basic TouchOSC data structures.
JavaScript
mit
razh/osc-dev
3bfdcb7e7ab642d26498c7b08ec7d014a008c4a6
application.js
application.js
define(['render', 'events', 'class'], function(render, Emitter, clazz) { function Application() { Application.super_.call(this); this.render = render; this.controller = undefined; } clazz.inherits(Application, Emitter); Application.prototype.run = function() { this.willLaunch(); this.launch(); this.didLaunch(); render.$(document).ready(function() { this.willDisplay(); this.display(); this.didDisplay(); }); }; Application.prototype.launch = function() {}; Application.prototype.display = function() { if (!this.controller) throw new Error('No controller initialized by application.'); this.controller.willAddEl(); this.controller.el.prependTo(document.body); this.controller.didAddEl(); }; Application.prototype.willLaunch = function() {}; Application.prototype.didLaunch = function() {}; Application.prototype.willDisplay = function() {}; Application.prototype.didDisplay = function() {}; return Application; });
define(['render', 'events', 'class'], function(render, Emitter, clazz) { function Application() { Application.super_.call(this); this.render = render; this.controller = undefined; } clazz.inherits(Application, Emitter); Application.prototype.run = function() { this.willLaunch(); this.launch(); this.didLaunch(); var self = this; render.$(document).ready(function() { self.willDisplay(); self.display(); self.didDisplay(); }); }; Application.prototype.launch = function() {}; Application.prototype.display = function() { if (!this.controller) throw new Error('No controller initialized by application.'); this.controller.willAddEl(); this.controller.el.prependTo(document.body); this.controller.didAddEl(); }; Application.prototype.willLaunch = function() {}; Application.prototype.didLaunch = function() {}; Application.prototype.willDisplay = function() {}; Application.prototype.didDisplay = function() {}; return Application; });
Fix this context in ready callback.
Fix this context in ready callback.
JavaScript
mit
sailjs/application
8287ca26fd538a3bc9ec68d0dc6cd81a3ff1cda3
node-server/config.js
node-server/config.js
// Don't commit this file to your public repos. This config is for first-run exports.creds = { mongoose_auth_local: 'mongodb://localhost/tasklist', // Your mongo auth uri goes here audience: 'http://localhost:8888/', // the Audience is the App URL when you registered the application. identityMetadata: 'https://login.microsoftonline.com/hypercubeb2c.onmicrosoft.com/.well-known/openid-configuration?p=b2c_1_B2CSI' // Replace the text after p= with your specific policy. };
// Don't commit this file to your public repos. This config is for first-run exports.creds = { mongoose_auth_local: 'mongodb://localhost/tasklist', // Your mongo auth uri goes here audience: 'http://localhost:8888/', // the Audience is the App URL when you registered the application. identityMetadata: 'https://login.microsoftonline.com/common/' // Replace the text after p= with your specific policy. };
Update back to business scenarios
Update back to business scenarios
JavaScript
apache-2.0
AzureADSamples/WebAPI-Nodejs
3b9144acc0031957a1e824d15597a8605cd0be86
examples/index.js
examples/index.js
import 'bootstrap/dist/css/bootstrap.min.css'; import 'nvd3/build/nv.d3.min.css'; import 'react-select/dist/react-select.min.css'; import 'fixed-data-table/dist/fixed-data-table.min.css'; import ReactDOM from 'react-dom'; import React from 'react'; import customDataHandlers from './customDataHandlers'; import { settings } from './settings'; import App from './App'; import { Router, Route, browserHistory } from 'react-router'; console.log('JJ', jeckyll); ReactDOM.render(<App />, document.getElementById('root'));
import 'bootstrap/dist/css/bootstrap.min.css'; import 'nvd3/build/nv.d3.min.css'; import 'react-select/dist/react-select.min.css'; import 'fixed-data-table/dist/fixed-data-table.min.css'; import ReactDOM from 'react-dom'; import React from 'react'; import customDataHandlers from './customDataHandlers'; import { settings } from './settings'; import App from './App'; import { Router, Route, browserHistory } from 'react-router'; ReactDOM.render(<App />, document.getElementById('root'));
Test for jekyll env - 1.1
Test for jekyll env - 1.1
JavaScript
mit
NuCivic/react-dashboard,NuCivic/react-dash,NuCivic/react-dashboard,NuCivic/react-dashboard,NuCivic/react-dash,NuCivic/react-dash
bc97c558b40592bbec42753baf72911f59bc8da6
src/DataProcessor.js
src/DataProcessor.js
export default class DataProcessor { static dataToPoints(data, width, height, limit) { if (limit && limit < data.length) { data = data.slice(data.length - limit); } let max = this.max(data); let min = this.min(data); let vfactor = height / (max - min); let hfactor = width / (limit || data.length); return data.map((d, i) => { return { x: i * hfactor, y: (max - data[i]) * vfactor } }); } static max(data) { return Math.max.apply(Math, data); } static min(data) { return Math.min.apply(Math, data); } static mean(data) { return (this.max(data) - this.min(data)) / 2; } static avg(data) { return data.reduce((a, b) => a + b) / (data.length + 1); } static median(data) { return data.sort()[Math.floor(data.length / 2)]; } static calculateFromData(data, calculationType) { return this[calculationType].call(this, data); } }
export default class DataProcessor { static dataToPoints(data, width, height, limit) { if (limit && limit < data.length) { data = data.slice(data.length - limit); } let max = this.max(data); let min = this.min(data); let vfactor = height / (max - min); let hfactor = width / (limit || data.length); return data.map((d, i) => { return { x: i * hfactor, y: (max - data[i]) * vfactor } }); } static max(data) { return Math.max.apply(Math, data); } static min(data) { return Math.min.apply(Math, data); } static mean(data) { return (this.max(data) - this.min(data)) / 2; } static avg(data) { return data.reduce((a, b) => a + b) / (data.length + 1); } static median(data) { return data.sort()[Math.floor(data.length / 2)]; } static variance(data) { let mean = this.mean(data); let sq = data.map(n => Math.pow(n - mean, 2)); return this.mean(sq); } static stddev(data) { let avg = this.avg(data); let sqDiff = data.map(n => Math.pow(n - mean, 2)); let avgSqDiff = this.avg(sqDiff); return Math.sqrt(avgSqDiff); } static calculateFromData(data, calculationType) { return this[calculationType].call(this, data); } }
Add calcualtion for standard deviation
Add calcualtion for standard deviation
JavaScript
mit
timoxley/react-sparklines,codevlabs/react-sparklines,Jonekee/react-sparklines,okonet/react-sparklines,samsface/react-sparklines,goodeggs/react-sparklines,kidaa/react-sparklines,shaunstanislaus/react-sparklines,rkichenama/react-sparklines,DigitalCoder/react-sparklines,geminiyellow/react-sparklines,rkichenama/react-sparklines,DigitalCoder/react-sparklines,fredericksilva/react-sparklines,fredericksilva/react-sparklines,konsumer/react-sparklines,timoxley/react-sparklines,codevlabs/react-sparklines,samsface/react-sparklines,borisyankov/react-sparklines,okonet/react-sparklines,geminiyellow/react-sparklines,kidaa/react-sparklines,shaunstanislaus/react-sparklines,Jonekee/react-sparklines,konsumer/react-sparklines
4e2ac67d7fc85ec38bc9404a350fcb2126fb0511
_config/task.local-server.js
_config/task.local-server.js
/* jshint node: true */ 'use strict'; function getTaskConfig(projectConfig) { var taskConfig = { server: { baseDir: taskConfig.baseDir } }; return taskConfig; } module.exports = getTaskConfig;
/* jshint node: true */ 'use strict'; function getTaskConfig(projectConfig) { //Browser Sync options object //https://www.browsersync.io/docs/options var taskConfig = { //Server config options server: { baseDir: projectConfig.dirs.build, // directory: true, // directory listing // index: "index.htm", // specific index filename }, ghostMode: false, // Mirror behaviour on all devices online: false, // Speed up startup time (When xip & tunnel aren't being used) // notify: false // Turn off UI notifications // browser: 'google chrome' //Set what browser to open on start - https://www.browsersync.io/docs/options#option-browser // open: false // Stop browser automatically opening }; return taskConfig; } module.exports = getTaskConfig;
Add base browser sync config options
feat: Add base browser sync config options
JavaScript
mit
cartridge/cartridge-local-server
894ac7126415d351ae03c93387bb96436d911044
website/src/app/global.components/mc-show-sample.component.js
website/src/app/global.components/mc-show-sample.component.js
class MCShowSampleComponentController { /*@ngInject*/ constructor($stateParams, samplesService, toast, $mdDialog) { this.projectId = $stateParams.project_id; this.samplesService = samplesService; this.toast = toast; this.$mdDialog = $mdDialog; this.viewHeight = this.viewHeight ? this.viewHeight : "40vh"; } $onInit() { if (this.viewHeight) { } this.samplesService.getProjectSample(this.projectId, this.sampleId) .then( (sample) => this.sample = sample, () => this.toast.error('Unable to retrieve sample') ) } showProcess(process) { this.$mdDialog.show({ templateUrl: 'app/project/experiments/experiment/components/dataset/components/show-process-dialog.html', controllerAs: '$ctrl', controller: ShowProcessDialogController, bindToController: true, locals: { process: process } }); } } class ShowProcessDialogController { /*@ngInject*/ constructor($mdDialog) { this.$mdDialog = $mdDialog; } done() { this.$mdDialog.cancel(); } } angular.module('materialscommons').component('mcShowSample', { templateUrl: 'app/global.components/mc-show-sample.html', controller: MCShowSampleComponentController, bindings: { sampleId: '<', viewHeight: '@' } });
class MCShowSampleComponentController { /*@ngInject*/ constructor($stateParams, samplesService, toast, $mdDialog) { this.projectId = $stateParams.project_id; this.samplesService = samplesService; this.toast = toast; this.$mdDialog = $mdDialog; this.viewHeight = this.viewHeight ? this.viewHeight : "40vh"; } $onInit() { this.samplesService.getProjectSample(this.projectId, this.sampleId) .then( (sample) => this.sample = sample, () => this.toast.error('Unable to retrieve sample') ) } showProcess(process) { this.$mdDialog.show({ templateUrl: 'app/project/experiments/experiment/components/dataset/components/show-process-dialog.html', controllerAs: '$ctrl', controller: ShowProcessDialogController, bindToController: true, locals: { process: process } }); } } class ShowProcessDialogController { /*@ngInject*/ constructor($mdDialog) { this.$mdDialog = $mdDialog; } done() { this.$mdDialog.cancel(); } } angular.module('materialscommons').component('mcShowSample', { templateUrl: 'app/global.components/mc-show-sample.html', controller: MCShowSampleComponentController, bindings: { sampleId: '<', viewHeight: '@' } });
Remove if(this.viewHeight){} since block is empty.
Remove if(this.viewHeight){} since block is empty.
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
b948fe73af2929c0d8a8665eacdaf2de1a94637e
lib/createMockCouchAdapter.js
lib/createMockCouchAdapter.js
var express = require('express'); function createMethodWrapper(app, verb) { var original = app[verb]; return function (route, handler) { var hasSentResponse = false; original.call(app, route, function (req, res, next) { handler(req, { setHeader: function () { // empty }, send: function(statusCode, body) { if (hasSentResponse) { return; } hasSentResponse = true; res.send(statusCode, body); } }, function _next(err) { if (hasSentResponse) { return; } hasSentResponse = true; next(err); }); }); }; } module.exports = function createMockCouchAdapter() { var app = express(); var deferred; var original; ['del', 'head', 'get', 'post'].forEach(function(verb) { var expressVerb = (verb === 'del' ? 'delete' : verb); app[verb] = createMethodWrapper(app, expressVerb); }); // store the put method app.put = function (route, handler) { deferred = handler; }; original = app.use; app.use = function (middleware) { original.call(app, '/:db', middleware); // now add the put method createMethodWrapper(app, 'put')('/:db', deferred); }; return app; };
var express = require('express'); function createMethodWrapper(app, verb) { var original = app[verb]; return function (route, handler) { original.call(app, route, function (req, res, next) { // must be places here in order that it is cleared on every request var hasSentResponse = false; handler(req, { setHeader: function () { // empty }, send: function(statusCode, body) { if (hasSentResponse) { return; } hasSentResponse = true; res.send(statusCode, body); } }, function _next(err) { if (hasSentResponse) { return; } hasSentResponse = true; next(err); }); }); }; } module.exports = function createMockCouchAdapter() { var app = express(); var deferred; var original; ['del', 'head', 'get', 'post'].forEach(function(verb) { var expressVerb = (verb === 'del' ? 'delete' : verb); app[verb] = createMethodWrapper(app, expressVerb); }); // store the put method app.put = function (route, handler) { deferred = handler; }; original = app.use; app.use = function (middleware) { original.call(app, '/:db', middleware); // now add the put method createMethodWrapper(app, 'put')('/:db', deferred); }; return app; };
Fix bug where hasSentResponse would not be reset stalling further requests.
Fix bug where hasSentResponse would not be reset stalling further requests.
JavaScript
bsd-3-clause
alexjeffburke/unexpected-couchdb
21e4abd8902165863e0d9acd49b4402f5341ed15
src/client/gravatar-image-retriever.js
src/client/gravatar-image-retriever.js
import md5 from 'md5'; export default class GravatarImageRetriever { constructor(picturePxSize) { this.picturePxSize = picturePxSize; } getImageUrl(email) { // https://en.gravatar.com/site/implement/hash/ if (email) { // https://en.gravatar.com/site/implement/images/ // https://github.com/blueimp/JavaScript-MD5 return `https://www.gravatar.com/avatar/${md5(email.trim().toLowerCase())}.jpg` + `?s=${this.picturePxSize}&r=g&d=mm`; } } }
import md5 from 'md5'; export default class GravatarImageRetriever { constructor(picturePxSize) { this.picturePxSize = picturePxSize; } getImageUrl(email) { // https://en.gravatar.com/site/implement/hash/ if (email) { // https://en.gravatar.com/site/implement/images/ return `https://www.gravatar.com/avatar/${md5(email.trim().toLowerCase())}.jpg` + `?s=${this.picturePxSize}&r=g&d=mm`; } } }
Remove comment, project using md5 package not blueimp-md5
Remove comment, project using md5 package not blueimp-md5
JavaScript
mit
ritterim/star-orgs,ritterim/star-orgs
4f8eee87a64f675a4f33ff006cf2f059a47d6267
app/assets/javascripts/application.js
app/assets/javascripts/application.js
'use strict'; $(document).ready(() => { $('.new').click((event) => { event.preventDefault(); }); // This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require_tree .
$(document).ready(function() { $('.new').on('click', function(event) { event.preventDefault(); var $link = $(this); var route = $link.attr('href'); var ajaxRequest = $.ajax({ method: 'GET', url: route }); ajaxRequest.done(function(data) { $('.posts').prepend(data); }); }); }); // This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require_tree .
Build ajax request for new snippet form
Build ajax request for new snippet form
JavaScript
mit
dshaps10/snippet,dshaps10/snippet,dshaps10/snippet
70f438378cbadf23f176d5d8bfc1272f1e06a1ad
app/components/SearchResults/index.js
app/components/SearchResults/index.js
import React, { PropTypes } from 'react'; import './index.css'; const SearchResults = React.createClass({ propTypes: { displayOptions: PropTypes.object.isRequired, }, render() { const { options, selectionIndex, onOptionSelected } = this.props; return ( <div className="SearchResults"> <ul className="SearchResults-list"> {options.map((option, index) => { const classNames = ['SearchResults-listItem']; if (selectionIndex === index) { classNames.push('SearchResults-listItem__active'); } return ( <li className={classNames.join(' ')} onClick={() => { onOptionSelected(option); }}> {option.name} {option.type} </li>); })} </ul> </div> ); }, }); export default SearchResults;
import React, { PropTypes } from 'react'; import './index.css'; const SearchResults = React.createClass({ propTypes: { displayOptions: PropTypes.object.isRequired, }, render() { const { options, selectionIndex, onOptionSelected } = this.props; return ( <div className="SearchResults"> <ul className="SearchResults-list"> {options.map((option, index) => { const classNames = ['SearchResults-listItem']; if (selectionIndex === index) { classNames.push('SearchResults-listItem__active'); } return ( <li className={classNames.join(' ')} key={option.id} onClick={() => { onOptionSelected(option); }} > {option.name} {option.type} </li>); })} </ul> </div> ); }, }); export default SearchResults;
Add key to list item
Add key to list item
JavaScript
mit
waagsociety/tnl-relationizer,transparantnederland/relationizer,transparantnederland/browser,transparantnederland/relationizer,transparantnederland/browser,waagsociety/tnl-relationizer
248f547f7fe9c9cfab0d76088fb188ac379ab2fb
gulpfile.babel.js
gulpfile.babel.js
import gulp from 'gulp'; import requireDir from 'require-dir'; import runSequence from 'run-sequence'; // Require individual tasks requireDir('./gulp/tasks', { recurse: true }); gulp.task('default', ['dev']); gulp.task('dev', () => runSequence('clean', 'set-development', 'set-watch-js', [ 'i18n', 'copy-static', 'bower', 'stylesheets', 'webpack', 'cached-lintjs-watch' ], 'watch') ); gulp.task('hot-dev', () => runSequence('clean', 'set-development', [ 'i18n', 'copy-static', 'bower', 'stylesheets-livereload', 'cached-lintjs-watch' ], ['webpack', 'watch']) ); gulp.task('build', cb => runSequence('clean', [ 'i18n', 'copy-static', 'bower', 'stylesheets', 'lintjs' ], 'webpack', 'minify', cb) );
import gulp from 'gulp'; import requireDir from 'require-dir'; import runSequence from 'run-sequence'; // Require individual tasks requireDir('./gulp/tasks', { recurse: true }); gulp.task('default', ['dev']); gulp.task('dev', () => runSequence('clean', 'set-development', 'set-watch-js', [ 'i18n', 'copy-static', 'bower', 'stylesheets', 'cached-lintjs-watch' ], ['webpack', 'watch']) ); gulp.task('hot-dev', () => runSequence('clean', 'set-development', [ 'i18n', 'copy-static', 'bower', 'stylesheets-livereload', 'cached-lintjs-watch' ], ['webpack', 'watch']) ); gulp.task('build', cb => runSequence('clean', [ 'i18n', 'copy-static', 'bower', 'stylesheets', 'lintjs' ], 'webpack', 'minify', cb) );
Fix styl/img watching in gulp tasks
Fix styl/img watching in gulp tasks
JavaScript
mit
MusikAnimal/WikiEduDashboard,Wowu/WikiEduDashboard,MusikAnimal/WikiEduDashboard,KarmaHater/WikiEduDashboard,KarmaHater/WikiEduDashboard,alpha721/WikiEduDashboard,WikiEducationFoundation/WikiEduDashboard,majakomel/WikiEduDashboard,Wowu/WikiEduDashboard,majakomel/WikiEduDashboard,Wowu/WikiEduDashboard,WikiEducationFoundation/WikiEduDashboard,feelfreelinux/WikiEduDashboard,sejalkhatri/WikiEduDashboard,sejalkhatri/WikiEduDashboard,MusikAnimal/WikiEduDashboard,KarmaHater/WikiEduDashboard,sejalkhatri/WikiEduDashboard,sejalkhatri/WikiEduDashboard,sejalkhatri/WikiEduDashboard,alpha721/WikiEduDashboard,feelfreelinux/WikiEduDashboard,MusikAnimal/WikiEduDashboard,alpha721/WikiEduDashboard,Wowu/WikiEduDashboard,WikiEducationFoundation/WikiEduDashboard,majakomel/WikiEduDashboard,feelfreelinux/WikiEduDashboard,WikiEducationFoundation/WikiEduDashboard,alpha721/WikiEduDashboard,feelfreelinux/WikiEduDashboard,majakomel/WikiEduDashboard,WikiEducationFoundation/WikiEduDashboard,KarmaHater/WikiEduDashboard
11329fe25bb2242ecd27745f7b712ce37c0030e4
src/lib/timer.js
src/lib/timer.js
const moment = require('moment'); function Timer(element) { this.element = element; this.secondsElapsed = 0; } Timer.prototype = { start: function() { var self = this; self.timerId = setInterval(function() { self.secondsElapsed++; self.displaySeconds(); }, 1000); }, stop: function() { var self = this; clearInterval(self.timerId); }, displaySeconds: function() { var minutes = Math.floor(this.secondsElapsed / 60); var seconds = this.secondsElapsed % 60; this.element.text(String(minutes).padStart(2, "0") + ":" + String(seconds).padStart(2, "0")); } }; module.exports = Timer;
const moment = require('moment'); function Timer(element) { this.element = element; this.secondsElapsed = 0; } Timer.prototype = { start: function() { var self = this; self.timerId = setInterval(function() { self.secondsElapsed++; self.displaySeconds(); }, 1000); }, stop: function() { var self = this; clearInterval(self.timerId); }, displaySeconds: function() { var minutes = Math.floor(this.secondsElapsed / 60); var seconds = this.secondsElapsed % 60; this.element.text(String(minutes).padStart(2, "0") + ":" + String(seconds).padStart(2, "0")); }, reset: function() { var self = this; clearInterval(self.timerId); self.secondsElapsed = 0; self.displaySeconds(); } }; module.exports = Timer;
Add a reset method to the Timer class.
Add a reset method to the Timer class. Refs #9.
JavaScript
mpl-2.0
jwir3/minuteman,jwir3/minuteman
5f56c522c4d3b2981e6d10b99bbe065e85d37ac4
client/src/js/files/components/File.js
client/src/js/files/components/File.js
import React from "react"; import PropTypes from "prop-types"; import { Col, Row } from "react-bootstrap"; import { byteSize } from "../../utils"; import { Icon, ListGroupItem, RelativeTime } from "../../base"; export default class File extends React.Component { static propTypes = { id: PropTypes.string, name: PropTypes.string, size: PropTypes.number, file: PropTypes.object, uploaded_at: PropTypes.string, user: PropTypes.object, onRemove: PropTypes.func }; handleRemove = () => { this.props.onRemove(this.props.id); }; render () { const { name, size, uploaded_at, user } = this.props; let creation; if (user === null) { creation = ( <span> Retrieved <RelativeTime time={uploaded_at} /> </span> ); } else { creation = ( <span> Uploaded <RelativeTime time={uploaded_at} /> by {user.id} </span> ); } return ( <ListGroupItem className="spaced"> <Row> <Col md={5}> <strong>{name}</strong> </Col> <Col md={2}> {byteSize(size)} </Col> <Col md={4}> {creation} </Col> <Col md={1}> <Icon name="trash" bsStyle="danger" style={{fontSize: "17px"}} onClick={this.handleRemove} pullRight /> </Col> </Row> </ListGroupItem> ); } }
import React from "react"; import PropTypes from "prop-types"; import { Col, Row } from "react-bootstrap"; import { byteSize } from "../../utils"; import { Icon, ListGroupItem, RelativeTime } from "../../base"; export default class File extends React.Component { static propTypes = { id: PropTypes.string, name: PropTypes.string, size: PropTypes.object, file: PropTypes.object, uploaded_at: PropTypes.string, user: PropTypes.object, onRemove: PropTypes.func }; handleRemove = () => { this.props.onRemove(this.props.id); }; render () { const { name, size, uploaded_at, user } = this.props; let creation; if (user === null) { creation = ( <span> Retrieved <RelativeTime time={uploaded_at} /> </span> ); } else { creation = ( <span> Uploaded <RelativeTime time={uploaded_at} /> by {user.id} </span> ); } return ( <ListGroupItem className="spaced"> <Row> <Col md={5}> <strong>{name}</strong> </Col> <Col md={2}> {byteSize(size.size)} </Col> <Col md={4}> {creation} </Col> <Col md={1}> <Icon name="trash" bsStyle="danger" style={{fontSize: "17px"}} onClick={this.handleRemove} pullRight /> </Col> </Row> </ListGroupItem> ); } }
Fix file size prop warning
Fix file size prop warning
JavaScript
mit
virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool
65bfe55ca0448dc941739deea117347798807fc9
app/assets/javascripts/patient_auto_complete.js
app/assets/javascripts/patient_auto_complete.js
$(document).ready(function() { $("[data-autocomplete-source]").each(function() { var url = $(this).data("autocomplete-source"); var target = $(this).data("autocomplete-rel"); $(this).autocomplete({ minLength: 2, source: function(request,response) { var path = url + "?term=" + request.term $.getJSON(path, function(data) { var list = $.map(data, function(patient) { return { label: patient.unique_label, value: patient.unique_label, id: patient.id }; }); response(list); }) }, search: function(event, ui) { $(target).val(""); }, select: function(event, ui) { $(target).val(ui.item.id); } }); }); });
$(document).ready(function() { $("[data-autocomplete-source]").each(function() { var url = $(this).data("autocomplete-source"); var target = $(this).data("autocomplete-rel"); $(this).autocomplete({ minLength: 2, source: function(request,response) { $.ajax({ url: url, data: { term: request.term }, success: function(data) { var list = $.map(data, function(patient) { return { label: patient.unique_label, id: patient.id }; }); response(list); }, error: function(jqXHR, textStatus, errorThrown) { var msg = "An error occurred. Please contact an administrator."; response({ label: msg, id: 0}); } }); }, search: function(event, ui) { $(target).val(""); }, select: function(event, ui) { $(target).val(ui.item.id); } }); }); });
Handle error if autocomplete query fails
Handle error if autocomplete query fails
JavaScript
mit
airslie/renalware-core,airslie/renalware-core,airslie/renalware-core,airslie/renalware-core
cf3200a37bf58f26cf8ffe9f8650bd9d39bffbc5
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { grunt.loadNpmTasks("grunt-mocha-test"); grunt.loadNpmTasks("grunt-mocha-istanbul"); var testOutputLocation = process.env.CIRCLE_TEST_REPORTS || "test_output"; var artifactsLocation = process.env.CIRCLE_ARTIFACTS || "build_artifacts"; grunt.initConfig({ mochaTest: { test: { src: ["test/**/*.js"] }, ci: { src: ["test/**/*.js"], options: { reporter: "xunit", captureFile: testOutputLocation + "/mocha/results.xml", quiet: true } } }, mocha_istanbul: { coverage: { src: ["test/**/*.js"], options: { coverageFolder: artifactsLocation + "/coverage", check: { lines: 100, statements: 100, branches: 100, functions: 100 }, reportFormats: ["lcov"] } } } }); grunt.registerTask("test", ["mochaTest:test", "mocha_istanbul"]); grunt.registerTask("ci-test", ["mochaTest:ci", "mocha_istanbul"]); grunt.registerTask("default", "test"); };
module.exports = function(grunt) { grunt.loadNpmTasks("grunt-mocha-test"); grunt.loadNpmTasks("grunt-mocha-istanbul"); var testOutputLocation = process.env.CIRCLE_TEST_REPORTS || "test_output"; var artifactsLocation = process.env.CIRCLE_ARTIFACTS || "build_artifacts"; grunt.initConfig({ mochaTest: { test: { src: ["test/**/*.js"] }, ci: { src: ["test/**/*.js"], options: { reporter: "xunit", captureFile: testOutputLocation + "/mocha/results.xml", quiet: true } } }, mocha_istanbul: { coverage: { src: ["test/**/*.js"], options: { coverageFolder: artifactsLocation, check: { lines: 100, statements: 100, branches: 100, functions: 100 }, reportFormats: ["lcov"] } } } }); grunt.registerTask("test", ["mochaTest:test", "mocha_istanbul"]); grunt.registerTask("ci-test", ["mochaTest:ci", "mocha_istanbul"]); grunt.registerTask("default", "test"); };
Change artifact location to suite CircleCI
Change artifact location to suite CircleCI
JavaScript
mit
JMiknys/todo-grad-project-justas,JMiknys/todo-grad-project-justas
d48742aa5a3002b347cf284ea28777a91d300f1b
client/app/components/components.js
client/app/components/components.js
import angular from 'angular'; import Dogs from './dogs/dogs'; import DogProfile from './dog-profile/dog-profile'; import Users from './users/users'; import DogPost from './dog-post/dog-post'; import UserPost from './user-post/user-post'; let componentModule = angular.module('app.components', [ Dogs, Users, DogProfile, DogPost, UserPost ]) .name; export default componentModule;
import angular from 'angular'; import Auth from './auth/auth'; import Signup from './signup/signup'; import Dogs from './dogs/dogs'; import DogProfile from './dog-profile/dog-profile'; import Users from './users/users'; import DogPost from './dog-post/dog-post'; import UserPost from './user-post/user-post'; let componentModule = angular.module('app.components', [ Signup, Auth, Dogs, Users, DogProfile, DogPost, UserPost ]) .name; export default componentModule;
Add to auth and signup component
Add to auth and signup component
JavaScript
apache-2.0
nickpeleh/dogs-book,nickpeleh/dogs-book
c343c6ee7fb3c2f545b082c06c21f3fbb93a4585
src/extension/index.js
src/extension/index.js
import { setupTokenEditor, setTokenEditorValue, useDefaultToken } from '../editor'; import { getParameterByName } from '../utils.js'; import { publicKeyTextArea } from './dom-elements.js'; /* For initialization, look at the end of this file */ function parseLocationQuery() { const publicKey = getParameterByName('publicKey'); const value = getParameterByName('value'); const token = getParameterByName('token'); if(publicKey) { publicKeyTextArea.value = publicKey; } if(value) { setTokenEditorValue(value); } if(token) { setTokenEditorValue(token); } } function loadToken() { const lastToken = localStorage.getItem('lastToken'); if(lastToken) { setTokenEditorValue(value); const lastPublicKey = localStorage.getItem('lastPublicKey'); if(lastPublicKey) { publicKeyTextArea.value = lastPublicKey; } } else { useDefaultToken('HS256'); } } // Initialization setupTokenEditor(); loadToken(); parseLocationQuery();
import { setupTokenEditor, setTokenEditorValue, useDefaultToken } from '../editor'; import { publicKeyTextArea } from './dom-elements.js'; /* For initialization, look at the end of this file */ function loadToken() { const lastToken = localStorage.getItem('lastToken'); if(lastToken) { setTokenEditorValue(value); const lastPublicKey = localStorage.getItem('lastPublicKey'); if(lastPublicKey) { publicKeyTextArea.value = lastPublicKey; } } else { useDefaultToken('HS256'); } } // Initialization setupTokenEditor(); loadToken();
Remove unnecessary code for the extension.
Remove unnecessary code for the extension.
JavaScript
mit
nov/jsonwebtoken.github.io,simo5/jsonwebtoken.github.io,simo5/jsonwebtoken.github.io,nov/jsonwebtoken.github.io
8afb86988829ead1404efdfa4bccf77fb983a08e
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { grunt.registerTask("default", ["test-server", "test-client"]); grunt.registerTask("test-client", function() { var done = this.async(); grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["test/testee/client"]}); grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["./node_modules/mocha/bin/mocha", "test/client.js"]}, function(error) { done(!error); }); }); grunt.registerTask("test-server", function() { var done = this.async(); grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["test/testee/server"]}); grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["./node_modules/mocha/bin/mocha", "test/server.js"]}, function(error) { done(!error); }); }); };
module.exports = function(grunt) { grunt.registerTask("default", ["test-server", "test-client"]); grunt.registerTask("test-client", function() { var done = this.async(); grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["test/testee/client"]}); grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["./node_modules/mocha/bin/mocha", "test/client.js", "--reporter", "spec"]}, function(error) { done(!error); }); }); grunt.registerTask("test-server", function() { var done = this.async(); grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["test/testee/server"]}); grunt.util.spawn({cmd: "node", opts: {stdio: 'inherit'}, args: ["./node_modules/mocha/bin/mocha", "test/server.js", "--reporter", "spec"]}, function(error) { done(!error); }); }); };
Change mocha's reporter type to spec
Change mocha's reporter type to spec
JavaScript
apache-2.0
vibe-project/vibe-protocol
a8dc6903bbeb207b63fcde2f318501d27052ec07
js/background.js
js/background.js
chrome.tabs.onCreated.addListener(function(tab) { console.log("Tab Created", tab); }); chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { console.log("Tab changed: #" + tabId, changeInfo, tab ); }); chrome.browserAction.onClicked.addListener(function() { console.log("Browser action clicked!"); });
chrome.tabs.onCreated.addListener(function(tab) { console.log("Tab Created", tab); }); chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { console.log("Tab changed: #" + tabId, changeInfo, tab ); }); chrome.storage.sync.get(null, function(items) { console.log("All items in synced storage", items ); }); chrome.storage.sync.set({name : "Pierce Moore", _config : _config }, function() { console.log("Set name to Pierce Moore"); }); chrome.storage.sync.get("name", function(items) { console.log("Name in synced storage", items ); }); chrome.storage.sync.get(null, function(items) { console.log("All items in synced storage", items ); }); chrome.storage.sync.getBytesInUse(null, function(bytes) { console.log("Total bytes in use:" + bytes + " bytes"); }); var d = new Date(); console.log(d.toUTCString());
Set of generic functions to test the chrome.* APIs
Set of generic functions to test the chrome.* APIs
JavaScript
bsd-3-clause
rex/BANTP
2c001cfd50d80bae25de6adce09a11926de9a991
Gruntfile.js
Gruntfile.js
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), clean: ['.tmp'], babel: { options: { sourceMap: true }, dist: { files: { 'dist/index.js': 'src/index.js' } }, test: { files: { '.tmp/tests.js': 'test/tests.js' } } }, jshint: { all: [ 'Gruntfile.js', 'src/**/*.js', 'test/**/*.js' ], options: { jshintrc: '.jshintrc' } }, mochacli: { all: ['.tmp/**/*.js'], options: { reporter: 'spec', ui: 'tdd', timeout: 10000 } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-mocha-cli'); grunt.loadNpmTasks('grunt-babel'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.registerTask('build', ['babel:dist']); grunt.registerTask('test', ['jshint', 'build', 'babel:test', 'mochacli']); grunt.registerTask('default', ['test']); };
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), clean: ['.tmp'], babel: { options: { sourceMap: true }, dist: { files: { 'dist/index.js': 'src/index.js' } }, test: { files: { '.tmp/tests.js': 'test/tests.js' } } }, jshint: { all: [ 'Gruntfile.js', 'src/**/*.js', 'test/**/*.js' ], options: { jshintrc: '.jshintrc' } }, mochacli: { all: ['.tmp/**/*.js'], options: { reporter: 'spec', ui: 'tdd', timeout: 10000, bail: 'true' } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-mocha-cli'); grunt.loadNpmTasks('grunt-babel'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.registerTask('build', ['babel:dist']); grunt.registerTask('test', ['jshint', 'build', 'babel:test', 'mochacli']); grunt.registerTask('default', ['test']); };
Add bail option to mochacli to halt on the first failed test.
Add bail option to mochacli to halt on the first failed test.
JavaScript
mit
khornberg/simplenote
c8656f406dcefc83c8eec14a6607c7f334f37607
Gruntfile.js
Gruntfile.js
/* * generator-init * https://github.com/use-init/generator-init * */ 'use strict'; module.exports = function (grunt) { // Load all grunt tasks matching the `grunt-*` pattern. require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'app/index.js', '<%= mochaTest.test.src%>' ], options: { jshintrc: '.jshintrc' } }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tests/temp'] }, // Unit tests. mochaTest: { test: { options: { reporter: 'spec' }, src: ['test/*.js'] } } }); // Whenever the "test" task is run, first clean the "temp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'mochaTest']); // By default, lint and run all tests. grunt.registerTask('default', ['clean', 'jshint', 'mochaTest']); };
/* * generator-init * https://github.com/use-init/generator-init * */ 'use strict'; module.exports = function (grunt) { // Load all grunt tasks matching the `grunt-*` pattern. require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'app/index.js', 'lib/*.js', 'page/index.js', 'module/index.js', 'jqueryplugin/index.js', 'page/index.js', '<%= mochaTest.test.src%>' ], options: { jshintrc: '.jshintrc' } }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tests/temp'] }, // Unit tests. mochaTest: { test: { options: { reporter: 'spec' }, src: ['test/*.js'] } } }); // Whenever the "test" task is run, first clean the "temp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'mochaTest']); // By default, lint and run all tests. grunt.registerTask('default', ['clean', 'jshint', 'mochaTest']); };
Add all JS files to JSHint
Add all JS files to JSHint
JavaScript
mit
use-init/generator-init,use-init/generator-init
f0299893c99537b1d23c54fbdbd04b463a6eed26
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { 'use strict'; grunt.initConfig({ benchmark: { all: { src: ['benchmarks/*.js'], options: { times: 10 } } }, nodeunit: { files: ['test/*_test.js'], }, jshint: { options: { jshintrc: '.jshintrc' }, gruntfile: { src: 'Gruntfile.js' }, lib: { src: ['lib/**/*.js'] }, test: { src: ['test/**/*_test.js'] }, } }); grunt.loadNpmTasks('grunt-benchmark'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.registerTask('default', ['jshint', 'nodeunit']); };
module.exports = function(grunt) { 'use strict'; grunt.initConfig({ benchmark: { all: { src: ['benchmarks/*.js'], options: { times: 10 } } }, nodeunit: { files: ['test/*_test.js'], }, jshint: { options: { jshintrc: '.jshintrc' }, gruntfile: { src: 'Gruntfile.js' }, lib: { src: ['lib/**/*.js'] }, test: { src: ['test/**/*_test.js'] }, }, }); // Dynamic alias task to nodeunit. Run individual tests with: grunt test:events grunt.registerTask('test', function(file) { grunt.config('nodeunit.files', String(grunt.config('nodeunit.files')).replace('*', file || '*')); grunt.task.run('nodeunit'); }); grunt.loadNpmTasks('grunt-benchmark'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.registerTask('default', ['jshint', 'nodeunit']); };
Add dynamic alias task for running individual tests
Add dynamic alias task for running individual tests
JavaScript
mit
modulexcite/gaze,prodatakey/gaze,prodatakey/gaze,shama/gaze,modulexcite/gaze,chebum/gaze,bevacqua/gaze,bevacqua/gaze,modulexcite/gaze,bevacqua/gaze,prodatakey/gaze
795bdb81899bff86df89174ceeaa5173999a7de2
hypem-resolver.js
hypem-resolver.js
// Copyright 2015 Fabian Dietenberger 'use-strict' var q = require('q'), request = require('request'); var hypemResolver = {}; hypemResolver.getUrl = function (hypemUrl) { var resultUrl = ""; return resultUrl; }; module.exports = hypemResolver;
// Copyright 2015 Fabian Dietenberger 'use-strict' var q = require('q'), request = require('request'); var hypemResolver = {}; hypemResolver.getByUrl = function (hypemUrl) { var resultUrl = ""; return resultUrl; }; hypemResolver.getById = function (hypemId) { return this.getByUrl("http://hypem.com/track/" + hypemId); }; module.exports = hypemResolver;
Split get method into 2 single methods for url and id
Split get method into 2 single methods for url and id
JavaScript
mit
feedm3/hypem-resolver
fe74c923958c21f8706fbca6e4da8a9cfb1b6a1d
src/server/migrations/0.3.0-0.4.0/index.js
src/server/migrations/0.3.0-0.4.0/index.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const database = require('../../models/database'); const sqlFile = database.sqlFile; module.exports = { fromVersion: '0.3.0', toVersion: '0.4.0', up: async db => { try { await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/preferences/create_language_types_enum.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/preferences/add_language_column.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/logemail/create_log_table.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_baseline_table.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_function_get_average_reading.sql')); } catch (err) { throw new Error('Error while migrating each sql file'); } } };
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const database = require('../../models/database'); const sqlFile = database.sqlFile; module.exports = { fromVersion: '0.3.0', toVersion: '0.4.0', up: async db => { try { await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/preferences/create_language_types_enum.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/preferences/add_language_column.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/logemail/create_log_table.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_baseline_table.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_function_get_average_reading.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/compareReadings/create_function_get_compare_readings.sql')); } catch (err) { throw new Error('Error while migrating each sql file'); } } };
Set migration for compare_readings/group_compare_readings sql functions
Set migration for compare_readings/group_compare_readings sql functions
JavaScript
mpl-2.0
OpenEnergyDashboard/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED
1f71f06920d43c2c8ff3b670e9355033eaed7f11
src/telemetry.js
src/telemetry.js
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. "use strict"; var appInsights = require("applicationinsights"); const telemetry = { appInsights: appInsights, trackEvent: function () { }, trackException: function () { } }; telemetry.instrumentationKey = ""; telemetry.createClient = function () { var client = new appInsights.TelemetryClient(telemetry.instrumentationKey); client.config.maxBatchIntervalMs = 0; return client; }; /** * Sets up collection of telemetry. * @param {String} [instrumentationKey=null] - The optional instrumentation key to use. */ telemetry.setup = function (instrumentationKey) { if (instrumentationKey) { telemetry.instrumentationKey = instrumentationKey; telemetry.appInsights.setup(instrumentationKey).start(); telemetry.trackEvent = function (name, properties) { telemetry.createClient().trackEvent({ name: name, properties: properties }); }; telemetry.trackException = function (exception, properties) { telemetry.createClient().trackException({ exception: exception, properties: properties }); }; } }; module.exports = telemetry;
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. "use strict"; var appInsights = require("applicationinsights"); const telemetry = { appInsights: appInsights, trackEvent: function () { }, trackException: function () { } }; telemetry.instrumentationKey = ""; telemetry.createClient = function () { var client = new appInsights.TelemetryClient(telemetry.instrumentationKey); // Prevent Lambda function from hanging and timing out. // See https://github.com/martincostello/alexa-london-travel/issues/45. client.config.maxBatchIntervalMs = 0; client.config.maxBatchSize = 1; return client; }; /** * Sets up collection of telemetry. * @param {String} [instrumentationKey=null] - The optional instrumentation key to use. */ telemetry.setup = function (instrumentationKey) { if (instrumentationKey) { telemetry.instrumentationKey = instrumentationKey; telemetry.appInsights.setup(instrumentationKey).start(); telemetry.trackEvent = function (name, properties) { telemetry.createClient().trackEvent({ name: name, properties: properties }); }; telemetry.trackException = function (exception, properties) { telemetry.createClient().trackException({ exception: exception, properties: properties }); }; } }; module.exports = telemetry;
Set ApplicationInsights batch size to 1
Set ApplicationInsights batch size to 1 Set the batch size for ApplicationInsights to 1 to try and prevent setTimeout() ever being called and causing the lambda function to timeout from hanging. Relates to #45.
JavaScript
apache-2.0
martincostello/alexa-london-travel