commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
6192011404e89449132349044a3e872f90b0f075
src/client/app/states/projects/list/list.state.js
src/client/app/states/projects/list/list.state.js
(function() { 'use strict'; angular.module('app.states') .run(appRun); /** @ngInject */ function appRun(routerHelper) { routerHelper.configureStates(getStates()); } function getStates() { return { 'projects.list': { url: '', // No url, this state is the index of projects templateUrl: 'app/states/projects/list/list.html', controller: StateController, controllerAs: 'vm', title: 'Projects', resolve: { projects: resolveProjects } } }; } /** @ngInject */ function resolveProjects(Project) { return Project.query({archived: false}).$promise; } /** @ngInject */ function StateController(projects, lodash) { var vm = this; vm.projects = projects; vm.activate = activate; vm.title = 'Projects'; activate(); function activate() { vm.projects = lodash.sortBy(vm.projects, "name"); } } })();
(function() { 'use strict'; angular.module('app.states') .run(appRun); /** @ngInject */ function appRun(routerHelper) { routerHelper.configureStates(getStates()); } function getStates() { return { 'projects.list': { url: '', // No url, this state is the index of projects templateUrl: 'app/states/projects/list/list.html', controller: StateController, controllerAs: 'vm', title: 'Projects', resolve: { projects: resolveProjects } } }; } /** @ngInject */ function resolveProjects(Project) { return Project.query({archived: false}).$promise; } /** @ngInject */ function StateController(projects, lodash) { var vm = this; vm.projects = projects; vm.activate = activate; vm.title = 'Projects'; activate(); function activate() { vm.projects = lodash.sortBy(vm.projects, 'name'); } } })();
Update strings to use single quotes for jshint
Update strings to use single quotes for jshint
JavaScript
apache-2.0
mafernando/api,boozallen/projectjellyfish,sonejah21/api,AllenBW/api,sreekantch/JellyFish,sreekantch/JellyFish,AllenBW/api,sonejah21/api,boozallen/projectjellyfish,sonejah21/api,AllenBW/api,mafernando/api,stackus/api,projectjellyfish/api,projectjellyfish/api,projectjellyfish/api,stackus/api,stackus/api,boozallen/projectjellyfish,boozallen/projectjellyfish,mafernando/api,sreekantch/JellyFish
--- +++ @@ -40,7 +40,7 @@ activate(); function activate() { - vm.projects = lodash.sortBy(vm.projects, "name"); + vm.projects = lodash.sortBy(vm.projects, 'name'); } } })();
27cbc851dc68c9326b4958cc3174265712679460
test/util.js
test/util.js
/* global describe it */ 'use strict' const chai = require('chai') const chaiAsPromised = require('chai-as-promised') const requireInject = require('require-inject') const sinon = require('sinon') const sinonChai = require('sinon-chai') require('sinon-as-promised') chai.use(chaiAsPromised) chai.use(sinonChai) const expect = chai.expect describe('exec', function () { it('rejects if childProcess.exec fails', function () { const exec = sinon.stub().yields('some error') const stubs = { child_process: { exec } } const util = requireInject('../lib/util', stubs) return expect(util.exec('command')) .to.be.eventually.rejectedWith('some error') }) it('resolves if childProcess.exec succeeds', function () { const exec = sinon.stub().yields(null, 'stdout', 'stderr') const stubs = { child_process: { exec } } const util = requireInject('../lib/util', stubs) return expect(util.exec('command')).to.eventually.deep.equal({ command: 'command', stdout: 'stdout', stderr: 'stderr' }) }) })
/* global describe it beforeEach */ 'use strict' const chai = require('chai') const chaiAsPromised = require('chai-as-promised') const requireInject = require('require-inject') const sinon = require('sinon') const sinonChai = require('sinon-chai') require('sinon-as-promised') chai.use(chaiAsPromised) chai.use(sinonChai) const expect = chai.expect describe('exec', function () { let exec let stubs beforeEach(function () { exec = sinon.stub() stubs = { child_process: { exec } } }) it('rejects if childProcess.exec fails', function () { exec.yields('some error') const util = requireInject('../lib/util', stubs) return expect(util.exec('command')) .to.be.eventually.rejectedWith('some error') }) it('resolves if childProcess.exec succeeds', function () { exec.yields(null, 'stdout', 'stderr') const util = requireInject('../lib/util', stubs) return expect(util.exec('command')).to.eventually.deep.equal({ command: 'command', stdout: 'stdout', stderr: 'stderr' }) }) })
Refactor to reuse test case initialization code
Refactor to reuse test case initialization code
JavaScript
isc
jcollado/multitest
--- +++ @@ -1,4 +1,4 @@ -/* global describe it */ +/* global describe it beforeEach */ 'use strict' const chai = require('chai') @@ -14,25 +14,27 @@ const expect = chai.expect describe('exec', function () { - it('rejects if childProcess.exec fails', function () { - const exec = sinon.stub().yields('some error') - const stubs = { + let exec + let stubs + + beforeEach(function () { + exec = sinon.stub() + stubs = { child_process: { exec } } + }) + + it('rejects if childProcess.exec fails', function () { + exec.yields('some error') const util = requireInject('../lib/util', stubs) return expect(util.exec('command')) .to.be.eventually.rejectedWith('some error') }) it('resolves if childProcess.exec succeeds', function () { - const exec = sinon.stub().yields(null, 'stdout', 'stderr') - const stubs = { - child_process: { - exec - } - } + exec.yields(null, 'stdout', 'stderr') const util = requireInject('../lib/util', stubs) return expect(util.exec('command')).to.eventually.deep.equal({ command: 'command',
a6ec8b746abad9be76218e8e5dd9948aa358a1b9
GruntTasks/Options/concat.libcss.js
GruntTasks/Options/concat.libcss.js
module.exports = { src: [ 'vendor/bower_components/bootstrap/dist/css/bootstrap.css', 'vendor/bower_components/open-sans/css/open-sans.css', 'vendor/bower_components/jquery-minicolors/jquery.minicolors.css', 'vendor/bower_components/font-awesome/css/font-awesome.css', 'vendor/bower_components/datatables.net-bs/css/dataTables.bootstrap.css', 'vendor/bower_components/datatables.net-buttons-bs/js/buttons.bootstrap.css' ], dest: 'web/built/lib.css' };
module.exports = { src: [ 'vendor/bower_components/open-sans/css/open-sans.css', 'vendor/bower_components/jquery-minicolors/jquery.minicolors.css', 'web/bundles/openorchestrabackoffice/smartadmin/css/bootstrap.css', 'vendor/bower_components/font-awesome/css/font-awesome.css', 'vendor/bower_components/datatables.net-bs/css/dataTables.bootstrap.css', 'vendor/bower_components/datatables.net-buttons-bs/js/buttons.bootstrap.css', ], dest: 'web/built/lib.css' };
Use smartadmin bootraps.css version instead of bower one
Use smartadmin bootraps.css version instead of bower one
JavaScript
apache-2.0
open-orchestra/open-orchestra-cms-bundle,open-orchestra/open-orchestra-cms-bundle,open-orchestra/open-orchestra-cms-bundle
--- +++ @@ -1,11 +1,11 @@ module.exports = { src: [ - 'vendor/bower_components/bootstrap/dist/css/bootstrap.css', 'vendor/bower_components/open-sans/css/open-sans.css', 'vendor/bower_components/jquery-minicolors/jquery.minicolors.css', + 'web/bundles/openorchestrabackoffice/smartadmin/css/bootstrap.css', 'vendor/bower_components/font-awesome/css/font-awesome.css', 'vendor/bower_components/datatables.net-bs/css/dataTables.bootstrap.css', - 'vendor/bower_components/datatables.net-buttons-bs/js/buttons.bootstrap.css' + 'vendor/bower_components/datatables.net-buttons-bs/js/buttons.bootstrap.css', ], dest: 'web/built/lib.css' };
82b91b594c41774f9ea03e2538b0615efdabcfaa
lib/graph.js
lib/graph.js
import _ from 'lodash'; import { Graph, alg } from 'graphlib'; _.memoize.Cache = WeakMap; let dijkstra = _.memoize(alg.dijkstra); export function setupGraph(pairs) { let graph = new Graph({ directed: true }); _.each(pairs, ({ from, to, method }) => graph.setEdge(from, to, method)); return graph; } export function getPath(graph, source, destination, path = []) { let map = dijkstra(graph, source); if (map[destination].distance) { let predecessor = map[destination].predecessor; path.push(graph.edge(predecessor, destination)); return getPath(graph, source, predecessor, path); } else { return path.reverse(); } }
import _ from 'lodash'; import { Graph, alg } from 'graphlib'; _.memoize.Cache = WeakMap; let dijkstra = _.memoize(alg.dijkstra); export function setupGraph(pairs) { let graph = new Graph({ directed: true }); _.each(pairs, ({ from, to, method }) => graph.setEdge(from, to, method)); return graph; } export function getPath(graph, source, destination, path = []) { let map = dijkstra(graph, source); if (map[destination].distance) { let predecessor = map[destination].predecessor; path.push(graph.edge(predecessor, destination)); return getPath(graph, source, predecessor, path); } else { return path.reverse(); } } export function validateRelationship({ from, to, method }) { let validations = [ _.isString(from), _.isString(to), _.isFunction(method) ]; return _.every(validations, Boolean); }
Add a function to validate relationship objects
Add a function to validate relationship objects
JavaScript
mit
siddharthkchatterjee/graph-resolver
--- +++ @@ -20,3 +20,12 @@ return path.reverse(); } } + +export function validateRelationship({ from, to, method }) { + let validations = [ + _.isString(from), + _.isString(to), + _.isFunction(method) + ]; + return _.every(validations, Boolean); +}
14df8efec1598df37a7d6971cee3a4d176f48ea5
app/components/CellTextField/index.js
app/components/CellTextField/index.js
/** * * CellTextField * */ import React from 'react'; import TextField from 'material-ui/TextField'; import styles from './styles.css'; class CellTextField extends React.Component { // eslint-disable-line react/prefer-stateless-function static defaultProps = { label: 'test', width: '50%', }; static propTypes = { label: React.PropTypes.string, }; render() { const { width, label } = this.props; return ( <div className={styles.cellTextField} style={{ width: width }}> <TextField floatingLabelText={label} style={{ fontSize: '0.8vw', width: '80%', }} inputStyle={{ margin: '0', padding: '20px 0 0 0', }} /> </div> ); } } export default CellTextField;
/** * * CellTextField * */ import React from 'react'; import TextField from 'material-ui/TextField'; import styles from './styles.css'; class CellTextField extends React.Component { // eslint-disable-line react/prefer-stateless-function static defaultProps = { label: 'test', width: '50%', }; static propTypes = { label: React.PropTypes.string, width: React.PropTypes.string, }; checkInput = (e) => { const textValue = Number(e.target.value); console.log(textValue); if (Number.isNaN(textValue)) { this.setState({ label: 'Please input number!', floatingLabelFocusColor: 'red', }); } else { this.setState({ label: this.props.label, floatingLabelFocusColor: 'rgb(0, 188, 212)', }); } }; constructor(props) { super(props); this.state = { label: this.props.label, floatingLabelFocusColor: 'rgb(0, 188, 212)', }; } render() { const { width } = this.props; return ( <div className={styles.cellTextField} style={{ width: width }}> <TextField floatingLabelText={this.state.label} style={{ fontSize: '0.8vw', width: '80%', }} floatingLabelFocusStyle={{ color: this.state.floatingLabelFocusColor }} inputStyle={{ margin: '0', padding: '20px 0 0 0', }} onChange={(e) => this.checkInput(e)} /> </div> ); } } export default CellTextField;
Validate if input is number
Validate if input is number
JavaScript
mit
codermango/BetCalculator,codermango/BetCalculator
--- +++ @@ -18,22 +18,51 @@ static propTypes = { label: React.PropTypes.string, + width: React.PropTypes.string, }; + checkInput = (e) => { + const textValue = Number(e.target.value); + console.log(textValue); + if (Number.isNaN(textValue)) { + this.setState({ + label: 'Please input number!', + floatingLabelFocusColor: 'red', + }); + } else { + this.setState({ + label: this.props.label, + floatingLabelFocusColor: 'rgb(0, 188, 212)', + }); + } + }; + + constructor(props) { + super(props); + this.state = { + label: this.props.label, + floatingLabelFocusColor: 'rgb(0, 188, 212)', + }; + } + render() { - const { width, label } = this.props; + const { width } = this.props; return ( <div className={styles.cellTextField} style={{ width: width }}> <TextField - floatingLabelText={label} + floatingLabelText={this.state.label} style={{ fontSize: '0.8vw', width: '80%', + }} + floatingLabelFocusStyle={{ + color: this.state.floatingLabelFocusColor }} inputStyle={{ margin: '0', padding: '20px 0 0 0', }} + onChange={(e) => this.checkInput(e)} /> </div> );
706abfd07626606a8c901f4643ffcfd0fd1154c5
src/modules/confirm.js
src/modules/confirm.js
(function () { "use strict"; var moduleObj = moduler('confirm', { defaults: { message: 'Are you sure you want to perform this action?', event: 'click' }, init: function (module) { module.$element.on(module.settings.event, module, moduleObj.listen.showConfirm); }, listen: { showConfirm: mo.event(function (module, e) { e.preventDefault(); if (window.confirm(module.settings.message)) { module.$element.trigger('confirm-yes'); } else { module.$element.trigger('confirm-no'); } }) }, destroy: function () { module.$element.off(module.settings.event, moduleObj.listen.showConfirm); } }); })();
(function () { "use strict"; var moduleObj = moduler('confirm', { defaults: { message: 'Are you sure you want to perform this action?', event: 'click' }, init: function (module) { module.$element.on(module.settings.event, module, moduleObj.listen.showConfirm); }, listen: { showConfirm: mo.event(function (module, e) { e.preventDefault(); if (window.confirm(module.settings.message)) { module.$element.trigger('confirm-yes'); } else { module.$element.trigger('confirm-no'); } }) }, destroy: function (module) { module.$element.off(module.settings.event, moduleObj.listen.showConfirm); } }); })();
Fix for destroy method of Confirm
Fix for destroy method of Confirm
JavaScript
mit
simplyio/moduler.js,simplyio/moduler.js
--- +++ @@ -23,7 +23,7 @@ }) }, - destroy: function () { + destroy: function (module) { module.$element.off(module.settings.event, moduleObj.listen.showConfirm); } });
89970c235f4bae57087906c4e5346f188928ce7d
generators/app/index.js
generators/app/index.js
var generators = require('yeoman-generator'); module.exports = generators.Base.extend({ method1: function () { console.log('method 1 just ran'); }, method2: function () { console.log('method 2 just ran'); } });
var generators = require('yeoman-generator'); var inquirer = require("inquirer"); module.exports = generators.Base.extend({ bowerPackages: function() { inquirer.prompt([{ type: "checkbox", message: "Select bower packages to install", name: "Bower packages", choices: [ new inquirer.Separator("Css Framework:"), {name: "Bootstrap"}, {name: "Foundation"}, ] }], function( answers ) { console.log( JSON.stringify(answers, null, " ") ); }); } });
Add prompt to ask for css framework install
Add prompt to ask for css framework install
JavaScript
bsd-3-clause
initios/initios-yeoman,initios/initios-yeoman
--- +++ @@ -1,10 +1,20 @@ var generators = require('yeoman-generator'); +var inquirer = require("inquirer"); module.exports = generators.Base.extend({ - method1: function () { - console.log('method 1 just ran'); - }, - method2: function () { - console.log('method 2 just ran'); - } + bowerPackages: function() { + + inquirer.prompt([{ + type: "checkbox", + message: "Select bower packages to install", + name: "Bower packages", + choices: [ + new inquirer.Separator("Css Framework:"), + {name: "Bootstrap"}, {name: "Foundation"}, + ] + }], function( answers ) { + console.log( JSON.stringify(answers, null, " ") ); + }); + + } });
fd792ad7cdb9881e30fd16595df87b45ebccc78a
src/components/stats/ExternalModuleLink.js
src/components/stats/ExternalModuleLink.js
/* * @flow */ import type {Module} from '../../types/Stats'; import React from 'react'; import {getClassName} from '../Bootstrap/GlyphiconNames'; import {Link} from '../Bootstrap/Button'; type Props = { prefix: ?string, module: Module, }; export default function ExternalModuleLink(props: Props) { // https://phabricator.pinadmin.com/diffusion/P/browse/master/webapp/app/mobile/index.js$20 // https://phabricator.pinadmin.com/diffusion/P/browse/master/ // ../../../../../app/analytics/modules/SelectButtonWrapper/SelectButtonWrapper.js // ../../../../../app/analytics/modules/SelectButtonWrapper/SelectButtonWrapper.js // REACT_APP_FILE_URL_PREFIX=https://phabricator.pinadmin.com/diffusion/P/browse/master/webapp/a/b/c/d/e/ // https://phabricator.pinadmin.com/diffusion/P/browse/master/webapp/a/b/c/d/e/../../../../../app/analytics/modules/SelectButtonWrapper/SelectButtonWrapper.js if (props.prefix) { const file = props.module.name; const href = props.prefix + file; return ( <Link href={href} newtab={true}> <span className={getClassName('new-window')} /> </Link> ); } else { return null; } }
/* * @flow */ import type {Module} from '../../types/Stats'; import React from 'react'; import {getClassName} from '../Bootstrap/GlyphiconNames'; import {Link} from '../Bootstrap/Button'; type Props = { prefix: ?string, module: Module, }; export default function ExternalModuleLink(props: Props) { if (props.prefix) { const file = props.module.name; const href = props.prefix + file; return ( <Link href={href} newtab={true}> <span aria-label="Open in new window" className={getClassName('new-window')} /> </Link> ); } else { return null; } }
Add aria label to external link component
Add aria label to external link component
JavaScript
apache-2.0
pinterest/bonsai,pinterest/bonsai,pinterest/bonsai
--- +++ @@ -14,20 +14,15 @@ }; export default function ExternalModuleLink(props: Props) { - // https://phabricator.pinadmin.com/diffusion/P/browse/master/webapp/app/mobile/index.js$20 - // https://phabricator.pinadmin.com/diffusion/P/browse/master/ - // ../../../../../app/analytics/modules/SelectButtonWrapper/SelectButtonWrapper.js - // ../../../../../app/analytics/modules/SelectButtonWrapper/SelectButtonWrapper.js - - // REACT_APP_FILE_URL_PREFIX=https://phabricator.pinadmin.com/diffusion/P/browse/master/webapp/a/b/c/d/e/ - - // https://phabricator.pinadmin.com/diffusion/P/browse/master/webapp/a/b/c/d/e/../../../../../app/analytics/modules/SelectButtonWrapper/SelectButtonWrapper.js if (props.prefix) { const file = props.module.name; const href = props.prefix + file; return ( <Link href={href} newtab={true}> - <span className={getClassName('new-window')} /> + <span + aria-label="Open in new window" + className={getClassName('new-window')} + /> </Link> ); } else {
b4466bf9068b0d1515a646df091e447f3fa68c96
src/App.js
src/App.js
//@flow import { bindActionCreators } from "redux"; import { connect } from "react-redux"; import * as actionCreators from "./data/actions/actionCreators"; import insertGlobalStyles from "./global/style/globalStyles"; import { Main } from "./scenes/Main"; function mapStateToProps(): {} { return {}; } export function mapDispatchToProps(dispatch: {}) { return bindActionCreators(actionCreators, dispatch); } insertGlobalStyles(); export default connect(mapStateToProps, mapDispatchToProps)(Main);
//@flow import { bindActionCreators } from "redux"; import { connect } from "react-redux"; import * as actionCreators from "./data/actions/actionCreators"; import { Main } from "./scenes/Main"; function mapStateToProps(state: { cards: {}[] }): {} { return { cards: state.cards }; } export function mapDispatchToProps(dispatch: {}) { return bindActionCreators(actionCreators, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(Main);
Remove global styles and add some dummy state (cards)
Remove global styles and add some dummy state (cards)
JavaScript
mit
slightly-askew/portfolio-2017,slightly-askew/portfolio-2017
--- +++ @@ -3,18 +3,15 @@ import { bindActionCreators } from "redux"; import { connect } from "react-redux"; import * as actionCreators from "./data/actions/actionCreators"; -import insertGlobalStyles from "./global/style/globalStyles"; import { Main } from "./scenes/Main"; -function mapStateToProps(): {} { - return {}; +function mapStateToProps(state: { cards: {}[] }): {} { + return { cards: state.cards }; } export function mapDispatchToProps(dispatch: {}) { return bindActionCreators(actionCreators, dispatch); } -insertGlobalStyles(); - export default connect(mapStateToProps, mapDispatchToProps)(Main);
1fe48dd8228d78b124852389dbef4b564a124d37
src/App.js
src/App.js
import React from 'react'; import bukovelAPI from './dataAccess/bukovelApi'; import CardNumberInput from './CardNumberInput'; const TEST_CARD_NUMBER = '01-2167-30-92545'; export default class App extends React.Component { constructor() { super(); this.state = { html: '', cardNumber: TEST_CARD_NUMBER }; this.handleCardNumberChange = this.handleCardNumberChange.bind(this); } handleCardNumberChange(event) { if (event.isValid) { bukovelAPI .getCardBalance(event.text) .then(data => { this.setState({ html: JSON.stringify(data, null, '\t') }); }) } } render() { return ( <div> <CardNumberInput onChange={this.handleCardNumberChange} value={this.state.cardNumber} /> <pre>{this.state.html}</pre> </div> ); } }
import React from 'react'; import bukovelAPI from './dataAccess/bukovelApi'; import CardNumberInput from './CardNumberInput'; const TEST_CARD_NUMBER = '01-2167-30-92545'; export default class App extends React.Component { constructor() { super(); this.state = { html: '', cardNumber: '' }; this.handleCardNumberChange = this.handleCardNumberChange.bind(this); } handleCardNumberChange(event) { if (event.isValid) { bukovelAPI .getCardBalance(event.text) .then(data => { this.setState({ html: JSON.stringify(data, null, '\t') }); }) } } render() { return ( <div> <CardNumberInput onChange={this.handleCardNumberChange} value={this.state.cardNumber} /> <p>{`Test card number: ${TEST_CARD_NUMBER}`}</p> <pre>{this.state.html}</pre> </div> ); } }
Remove auto insertion of test card number.
Remove auto insertion of test card number.
JavaScript
apache-2.0
blobor/skipass.site,blobor/buka,blobor/skipass.site,blobor/buka
--- +++ @@ -10,7 +10,7 @@ this.state = { html: '', - cardNumber: TEST_CARD_NUMBER + cardNumber: '' }; this.handleCardNumberChange = this.handleCardNumberChange.bind(this); } @@ -31,6 +31,7 @@ return ( <div> <CardNumberInput onChange={this.handleCardNumberChange} value={this.state.cardNumber} /> + <p>{`Test card number: ${TEST_CARD_NUMBER}`}</p> <pre>{this.state.html}</pre> </div> );
81daf4cbd5504a15536d56058e2758505222f910
src/App.js
src/App.js
import React from 'react' import styled from 'styled-components' import { Intro, CheckboxTree } from './components' import data from './data/data.json' import github from './assets/github.svg' const Main = styled.main` display: flex; flex-direction: column; width: 80%; max-width: 64rem; height: 100vh; margin: 0 auto; ` const Section = styled.section` display: flex; flex-direction: column; flex: 1; overflow: auto; ` const Footer = styled.footer` align-self: center; margin: 2rem; ` export const App = () => ( <Main> <header> <Intro /> </header> <Section> <article> <CheckboxTree data={data} /> </article> </Section> <Footer> <a href='https://github.com/joelgeorgev/react-checkbox-tree'> <img src={github} alt='GitHub repository' /> </a> </Footer> </Main> )
import React from 'react' import styled from 'styled-components' import { Intro, CheckboxTree } from './components' import data from './data/data.json' import github from './assets/github.svg' const Main = styled.main` display: flex; flex-direction: column; width: 80%; max-width: 64rem; height: 100vh; margin: 0 auto; ` const Section = styled.section` display: flex; flex-direction: column; flex: 1; overflow: auto; ` const Footer = styled.footer` align-self: center; margin: 2rem; ` export const App = () => ( <Main> <header> <Intro /> </header> <Section> <article> <CheckboxTree data={data} /> </article> </Section> <Footer> <a href='https://github.com/joelgeorgev/react-checkbox-tree'> <img src={github} alt='Go to GitHub repository page' /> </a> </Footer> </Main> )
Update GitHub icon alt text
Update GitHub icon alt text
JavaScript
mit
joelgeorgev/react-checkbox-tree,joelgeorgev/react-checkbox-tree
--- +++ @@ -38,7 +38,7 @@ </Section> <Footer> <a href='https://github.com/joelgeorgev/react-checkbox-tree'> - <img src={github} alt='GitHub repository' /> + <img src={github} alt='Go to GitHub repository page' /> </a> </Footer> </Main>
55634a3654b1b25d636caaa548f82ce33f89acb0
src/app.js
src/app.js
/* global fetch */ import React from 'react'; import { render } from 'react-dom'; import { Router, Route, hashHistory } from 'react-router' import Home from './home'; import CaseHandler from './caseHandler'; import Adjudicator from './adjudicator'; class App extends React.Component { render() { return ( <Router history={hashHistory}> <Route path='/' component={Home} /> <Route path='/caseHandler' component={CaseHandler} /> <Route path='/adjudicator' component={Adjudicator} /> </Router> ); } } render(<App/>, document.getElementById('app'));
/* global fetch */ import React from 'react'; import { render } from 'react-dom'; import { Router, Route, hashHistory } from 'react-router' import Home from './home'; import CaseHandler from './caseHandler/caseHandler'; import Adjudicator from './adjudicator/adjudicator'; class App extends React.Component { render() { return ( <Router history={hashHistory}> <Route path='/' component={Home} /> <Route path='/caseHandler' component={CaseHandler} /> <Route path='/adjudicator' component={Adjudicator} /> </Router> ); } } render(<App/>, document.getElementById('app'));
Fix up file references after folder restructure
Fix up file references after folder restructure
JavaScript
mit
dgretho/adjudication,dgretho/adjudication
--- +++ @@ -4,8 +4,8 @@ import { Router, Route, hashHistory } from 'react-router' import Home from './home'; -import CaseHandler from './caseHandler'; -import Adjudicator from './adjudicator'; +import CaseHandler from './caseHandler/caseHandler'; +import Adjudicator from './adjudicator/adjudicator'; class App extends React.Component {
b3522adddaa4415c8afcd3f1f11fefd2b488d358
lib/ferrite/utility.js
lib/ferrite/utility.js
/** * copyObject(object, [recurse]) -- for all JS Objects * * Copies all properties and the prototype to a new object * Optionally set recurse to array containing the properties, on wich this function should be called recursively */ function copyObject(object, recurse) { var new_obj = Object.create(Object.getPrototypeOf(object)); recurse = (recurse) ? recurse : []; for(var prop in object) { new_obj[prop] = object[prop]; if(recurse.indexOf(prop) !== -1) new_obj[prop] = copyObject(object[prop]); } return new_obj; } function repeatString(str, times) { for(var padding = "", i=0; i < times; i++) { padding += str; } return padding; } function isInt(n) { return String(parseInt(n)) === String(n) && parseInt(n) >= 0 && isFinite(n); } function calcLineNo(source, offset) { return source.substr( 0, offset ).split("\n").length; }; function getLineExcerpt(source, offset) { return source.substr( 0, offset ).split("\n").pop() + source.substr( offset, 250 ).split("\n")[0]; }; function getLineCol(source, offset) { return source.substr( 0, offset ).split("\n").pop().length+1 };
/** * copyObject(object, [recurse]) -- for all JS Objects * * Copies all properties and the prototype to a new object * Optionally set recurse to array containing the properties, on wich this function should be called recursively */ function copyObject(object, recurse) { var new_obj = Object.create(Object.getPrototypeOf(object)); recurse = (recurse) ? recurse : []; for(var prop in object) { new_obj[prop] = object[prop]; if(recurse.indexOf(prop) !== -1) new_obj[prop] = copyObject(object[prop]); } return new_obj; } function repeatString(str, times) { for(var padding = "", i=0; i < times; i++) { padding += str; } return padding; } function isInt(n) { return String(parseInt(n)) === String(n) && parseInt(n) >= 0 && isFinite(n); } function calcLineNo(source, offset) { return offset ? source.substr( 0, offset ).split("\n").length : -1; }; function getLineExcerpt(source, offset) { return source.substr( 0, offset ).split("\n").pop() + source.substr( offset, 250 ).split("\n")[0]; }; function getLineCol(source, offset) { return source.substr( 0, offset ).split("\n").pop().length+1 };
Fix calcLineNo for undefined offset
Fix calcLineNo for undefined offset - now returns -1
JavaScript
mit
marcelklehr/magnet
--- +++ @@ -26,7 +26,7 @@ } function calcLineNo(source, offset) { - return source.substr( 0, offset ).split("\n").length; + return offset ? source.substr( 0, offset ).split("\n").length : -1; }; function getLineExcerpt(source, offset) {
8d0750fb6ca50a5e07a54c17813af6d5a724b8c5
lib/jekyll-template.js
lib/jekyll-template.js
var path = require('path'); module.exports = function jekyllTemplate(answers) { return [ '---', 'layout: post', 'date: ' + answers.date, 'duration: ' + answers.duration, 'categories: ' + answers.categories, 'img: ' + path.normalize('./assets/image/speakers/' + answers.imagePath ), 'link: ' + answers.link, '---', '' ]; }
var path = require('path'); module.exports = function jekyllTemplate(answers) { return [ '---', 'layout: post', 'title' + answers.title, 'date: ' + answers.date, 'duration: ' + answers.duration, 'tags: ' + answers.tags, 'img: ' + '/assets/image/speakers/' + answers.imagePath, 'link: ' + answers.link, '---', '' ]; }
Add title and fix tags and image path in Jekyll template
Add title and fix tags and image path in Jekyll template
JavaScript
mit
free-time/freetime-cli,fdaciuk/freetime-cli
--- +++ @@ -3,10 +3,11 @@ return [ '---', 'layout: post', + 'title' + answers.title, 'date: ' + answers.date, 'duration: ' + answers.duration, - 'categories: ' + answers.categories, - 'img: ' + path.normalize('./assets/image/speakers/' + answers.imagePath ), + 'tags: ' + answers.tags, + 'img: ' + '/assets/image/speakers/' + answers.imagePath, 'link: ' + answers.link, '---', ''
1185b3e82cd7c3f6483a604d9348f35f16f294f0
config/index.js
config/index.js
// see http://vuejs-templates.github.io/webpack for documentation. var path = require('path') module.exports = { build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report }, dev: { env: require('./dev.env'), port: 80, autoOpenBrowser: false, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } }
// see http://vuejs-templates.github.io/webpack for documentation. var path = require('path') module.exports = { build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report }, dev: { env: require('./dev.env'), port: 8080, autoOpenBrowser: false, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } }
Revert "reopen port to 80"
Revert "reopen port to 80" This reverts commit 3cfed3456cbed7f6f4a71c114b2645a278b27979.
JavaScript
mit
Cubelrti/kontent,Cubelrti/kontent
--- +++ @@ -23,7 +23,7 @@ }, dev: { env: require('./dev.env'), - port: 80, + port: 8080, autoOpenBrowser: false, assetsSubDirectory: 'static', assetsPublicPath: '/',
ad65439c6f7c21aee73c797f2be02ad861a31e8d
src/utils/constants.js
src/utils/constants.js
const PORT = '6882' const ROOT = location.href.indexOf('localhost') > 0 ? 'http://localhost:' : 'http://192.168.5.102:' export const ROOT_URL = ROOT + PORT + '/' export const ROOT_URL_API = ROOT_URL + 'api' export const YOUTUBE_CONSTS = { YOUTUBE: 'Youtube', URL: 'http://www.youtube.com/embed/', API: 'enablejsapi=1', AUTOPLAY: 'autoplay=1', API_URL: 'http://www.youtube.com/iframe_api' } export const DOWNLOAD_YOUTUBE = '//www.youtubeinmp3.com/fetch/?video=https://www.youtube.com/watch?v=' export const BASE_COLOR1 = '#192d50' export const HEADER_FONT_COLOR = '#dfceba' export const BASE_COLOR2 = '#dfceba' export const BASE_COLOR3 = '#f7f6f7' export const TABLE_HEADER_FONT_COLOR = '#4f6073' export const TABLE_FONT_COLOR = '#030b15' export const googleAutoSuggestURL = `//suggestqueries.google.com/complete/search?client=youtube&ds=yt&q=`
const PORT = '6882' const ROOT = location.href.indexOf('reuvenliran') > 0 ? 'http://reuvenliran.hopto.org:' : location.href export const ROOT_URL = ROOT.indexOf('8080') ? ROOT.replace('8080', PORT) : ROOT + PORT + '/' export const ROOT_URL_API = ROOT_URL + 'api' export const YOUTUBE_CONSTS = { YOUTUBE: 'Youtube', URL: 'http://www.youtube.com/embed/', API: 'enablejsapi=1', AUTOPLAY: 'autoplay=1', API_URL: 'http://www.youtube.com/iframe_api' } export const DOWNLOAD_YOUTUBE = '//www.youtubeinmp3.com/fetch/?video=https://www.youtube.com/watch?v=' export const BASE_COLOR1 = '#192d50' export const HEADER_FONT_COLOR = '#dfceba' export const BASE_COLOR2 = '#dfceba' export const BASE_COLOR3 = '#f7f6f7' export const TABLE_HEADER_FONT_COLOR = '#4f6073' export const TABLE_FONT_COLOR = '#030b15' export const googleAutoSuggestURL = `//suggestqueries.google.com/complete/search?client=youtube&ds=yt&q=`
Fix bug with url refernce to server
Fix bug with url refernce to server
JavaScript
mit
ReuvenLiran/react-musicplayer,ReuvenLiran/react-musicplayer
--- +++ @@ -1,7 +1,7 @@ const PORT = '6882' const ROOT = - location.href.indexOf('localhost') > 0 ? 'http://localhost:' : 'http://192.168.5.102:' -export const ROOT_URL = ROOT + PORT + '/' + location.href.indexOf('reuvenliran') > 0 ? 'http://reuvenliran.hopto.org:' : location.href +export const ROOT_URL = ROOT.indexOf('8080') ? ROOT.replace('8080', PORT) : ROOT + PORT + '/' export const ROOT_URL_API = ROOT_URL + 'api' export const YOUTUBE_CONSTS = { YOUTUBE: 'Youtube',
5be884f967a79f852e2b7d2c5c814ca90df369cd
src/request/stores/request-detail-store.js
src/request/stores/request-detail-store.js
var glimpse = require('glimpse'), requestRepository = require('../repository/request-repository.js'), // TODO: Not sure I need to store the requests _requests = {}, _requestSelectedId = null; function requestsChanged(targetRequests) { glimpse.emit('shell.request.summary.changed', targetRequests); } // Clear Request (function() { function clearRequest() { _requestSelectedId = null; glimpse.emit('shell.request.detail.changed', null); } glimpse.on('shell.request.detail.closed', clearRequest); })(); // Found Data (function() { function dataFound(payload) { // TODO: Really bad hack to get things going atm _requests[payload.newRequest.id] = payload.newRequest; if (payload.newRequest.id === _requestSelectedId) { glimpse.emit('shell.request.detail.changed', payload.newRequest); } } // External data coming in glimpse.on('data.request.detail.found', dataFound); })(); // Trigger Requests (function() { function triggerRequest(payload) { _requestSelectedId = payload.requestId; if (!FAKE_SERVER) { requestRepository.triggerGetDetailsFor(payload.requestId); } } glimpse.on('data.request.detail.requested', triggerRequest); })();
var glimpse = require('glimpse'), requestRepository = require('../repository/request-repository.js'), // TODO: Not sure I need to store the requests _requests = {}, _requestSelectedId = null; function requestChanged(targetRequests) { glimpse.emit('shell.request.detail.changed', targetRequests); } // Clear Request (function() { function clearRequest() { _requestSelectedId = null; requestChanged(null); } glimpse.on('shell.request.detail.closed', clearRequest); })(); // Found Data (function() { function dataFound(payload) { // TODO: Really bad hack to get things going atm _requests[payload.newRequest.id] = payload.newRequest; if (payload.newRequest.id === _requestSelectedId) { requestChanged(payload.newRequest); } } // External data coming in glimpse.on('data.request.detail.found', dataFound); })(); // Trigger Requests (function() { function triggerRequest(payload) { _requestSelectedId = payload.requestId; if (!FAKE_SERVER) { requestRepository.triggerGetDetailsFor(payload.requestId); } } glimpse.on('data.request.detail.requested', triggerRequest); })();
Switch over detail store to call central requestChange event
Switch over detail store to call central requestChange event
JavaScript
unknown
avanderhoorn/Glimpse.Client.Prototype,avanderhoorn/Glimpse.Client.Prototype,Glimpse/Glimpse.Client.Prototype,Glimpse/Glimpse.Client.Prototype,Glimpse/Glimpse.Client.Prototype
--- +++ @@ -4,8 +4,8 @@ _requests = {}, _requestSelectedId = null; -function requestsChanged(targetRequests) { - glimpse.emit('shell.request.summary.changed', targetRequests); +function requestChanged(targetRequests) { + glimpse.emit('shell.request.detail.changed', targetRequests); } // Clear Request @@ -13,7 +13,7 @@ function clearRequest() { _requestSelectedId = null; - glimpse.emit('shell.request.detail.changed', null); + requestChanged(null); } glimpse.on('shell.request.detail.closed', clearRequest); @@ -26,7 +26,7 @@ _requests[payload.newRequest.id] = payload.newRequest; if (payload.newRequest.id === _requestSelectedId) { - glimpse.emit('shell.request.detail.changed', payload.newRequest); + requestChanged(payload.newRequest); } }
5f104201a91614820aa8acdc6fdfe6d9dd027695
components/shared/score.js
components/shared/score.js
import React, { Component } from "react"; import { formatTime } from "../../common/util/date"; export default class extends Component { render() { const { match } = this.props; if (match.fixture) { return match.time && <span>{formatTime(match.date, match.time)}</span>; } if (match.live || match.ended) { return ( <span className={match.live && "live"}> {match.ft && (!match.et || match.ps) && ( <span> {match.ft[0]}&nbsp;-&nbsp;{match.ft[1]} </span> )} {match.et && !match.ps && ( <span> {match.et[0]}&nbsp;-&nbsp;{match.et[1]} aet </span> )} {match.ps && ( <span> {" "} p.{match.ps[0]}-{match.ps[1]} </span> )} </span> ); } if (match.postponed) { return <abbr title="Postponed">PSTP</abbr>; } if (match.suspended) { return <abbr title="Suspended">SUSP</abbr>; } if (match.cancelled) { return <abbr title="Cencelled">CANC</abbr>; } return null; } }
import React, { Component } from "react"; import { formatTime } from "../../common/util/date"; export default class extends Component { render() { const { match } = this.props; if (match.live || match.ended) { return ( <span className={match.live && "live"}> {match.ft && (!match.et || match.ps) && ( <span> {match.ft[0]}&nbsp;-&nbsp;{match.ft[1]} </span> )} {match.et && !match.ps && ( <span> {match.et[0]}&nbsp;-&nbsp;{match.et[1]} aet </span> )} {match.ps && ( <span> {" "} p.{match.ps[0]}-{match.ps[1]} </span> )} </span> ); } if (match.postponed) { return <abbr title="Postponed">PSTP</abbr>; } if (match.suspended) { return <abbr title="Suspended">SUSP</abbr>; } if (match.cancelled) { return <abbr title="Cencelled">CANC</abbr>; } if (match.date && match.time) { return <span>{formatTime(match.date, match.time)}</span>; } return null; } }
Fix match time not showing for fixtures
Fix match time not showing for fixtures
JavaScript
isc
sobstel/golazon,sobstel/golazon,sobstel/golazon
--- +++ @@ -4,10 +4,6 @@ export default class extends Component { render() { const { match } = this.props; - - if (match.fixture) { - return match.time && <span>{formatTime(match.date, match.time)}</span>; - } if (match.live || match.ended) { return ( @@ -44,6 +40,10 @@ return <abbr title="Cencelled">CANC</abbr>; } + if (match.date && match.time) { + return <span>{formatTime(match.date, match.time)}</span>; + } + return null; } }
d77e2510a2bcef6d0713d93fc962604c6340d461
src/components/avatar/AvatarTeam.js
src/components/avatar/AvatarTeam.js
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import theme from './theme.css'; import Box from '../box'; import Icon from '../icon'; import { IconTeamMediumOutline, IconTeamSmallOutline } from '@teamleader/ui-icons'; class AvatarTeam extends PureComponent { render() { const { size } = this.props; return ( <Box alignItems="center" backgroundColor="neutral" backgroundTint="normal" className={cx(theme['avatar'], theme['avatar-team'])} data-teamleader-ui="avatar-team" display="flex" justifyContent="center" > <Icon color="neutral" tint="darkest"> {size === 'tiny' || size === 'small' ? <IconTeamSmallOutline /> : <IconTeamMediumOutline />} </Icon> </Box> ); } } AvatarTeam.propTypes = { /** The size of the avatar. */ size: PropTypes.oneOf(['tiny', 'small', 'medium', 'large', 'hero']), }; export default AvatarTeam;
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import theme from './theme.css'; import Box from '../box'; import Icon from '../icon'; import { IconTeamMediumOutline, IconTeamSmallOutline } from '@teamleader/ui-icons'; class AvatarTeam extends PureComponent { render() { const { size } = this.props; return ( <Box alignItems="center" backgroundColor="neutral" backgroundTint="darkest" className={cx(theme['avatar'], theme['avatar-team'])} data-teamleader-ui="avatar-team" display="flex" justifyContent="center" > <Icon color="neutral" tint="light"> {size === 'tiny' || size === 'small' ? <IconTeamSmallOutline /> : <IconTeamMediumOutline />} </Icon> </Box> ); } } AvatarTeam.propTypes = { /** The size of the avatar. */ size: PropTypes.oneOf(['tiny', 'small', 'medium', 'large', 'hero']), }; export default AvatarTeam;
Use correct background & icon colors according to design
Use correct background & icon colors according to design
JavaScript
mit
teamleadercrm/teamleader-ui
--- +++ @@ -14,13 +14,13 @@ <Box alignItems="center" backgroundColor="neutral" - backgroundTint="normal" + backgroundTint="darkest" className={cx(theme['avatar'], theme['avatar-team'])} data-teamleader-ui="avatar-team" display="flex" justifyContent="center" > - <Icon color="neutral" tint="darkest"> + <Icon color="neutral" tint="light"> {size === 'tiny' || size === 'small' ? <IconTeamSmallOutline /> : <IconTeamMediumOutline />} </Icon> </Box>
a276e5e6324b54a75c2b32695766258920726607
src/subdomain.js
src/subdomain.js
import { routers } from './router'; const detectsubdomain = async function detectsubdomain (ctx, next) { let [subdomain = 'www'] = ctx.request.subdomains; ctx.subdomain = subdomain; if (ctx.request.origin.indexOf(configuration.server.host) > -1) { ctx.response.set('Access-Control-Allow-Origin', ctx.request.origin); ctx.response.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); } await routers(ctx.subdomain).secured.call(ctx, next); await routers(ctx.subdomain).public.call(ctx, next); await next(); }; export default detectsubdomain;
import { routers } from './router'; const detectsubdomain = async function detectsubdomain (ctx, next) { let [subdomain = 'www'] = ctx.request.subdomains; ctx.subdomain = subdomain; let origin = ctx.headers.origin ? ctx.headers.origin : ctx.request.origin; if (origin.indexOf(configuration.server.host) > -1) { ctx.response.set('Access-Control-Allow-Origin', origin); ctx.response.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); } await routers(ctx.subdomain).secured.call(ctx, next); await routers(ctx.subdomain).public.call(ctx, next); await next(); }; export default detectsubdomain;
Access controll allow headers will be correctly detected
fix: Access controll allow headers will be correctly detected
JavaScript
agpl-3.0
gerard2p/koaton
--- +++ @@ -3,8 +3,9 @@ const detectsubdomain = async function detectsubdomain (ctx, next) { let [subdomain = 'www'] = ctx.request.subdomains; ctx.subdomain = subdomain; - if (ctx.request.origin.indexOf(configuration.server.host) > -1) { - ctx.response.set('Access-Control-Allow-Origin', ctx.request.origin); + let origin = ctx.headers.origin ? ctx.headers.origin : ctx.request.origin; + if (origin.indexOf(configuration.server.host) > -1) { + ctx.response.set('Access-Control-Allow-Origin', origin); ctx.response.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); } await routers(ctx.subdomain).secured.call(ctx, next);
55e40c0504b02708f544e1d464715123570b80cd
hosting/src/components/shared/Footer.js
hosting/src/components/shared/Footer.js
import React, { Component } from 'react' import styled from 'styled-components' const FooterWrapper = styled.div` display: flex; justify-content: center; align-items: center; height: 10vh; font-size: 0.85em; background: ${props => props.theme.colors.background}; color: ${props => props.theme.colors.barText}; padding: 0.25em 0.5em; text-align: center; cursor: default; ` const Content = styled.div` ` const Link = styled.a` color: white; ` export default class Footer extends Component { render (){ return ( <FooterWrapper> <Content> Not FDIC Insured <br/> <Link href="https://github.com/csrf-demo/csrf-demo" target="_blank"> Fork on Github </Link> <br/> Nick Breaton &#183; Jeremy Bohannon &#183; Hunter Aeraer </Content> </FooterWrapper> ) } }
import React, { Component } from 'react' import styled from 'styled-components' const FooterWrapper = styled.div` display: flex; justify-content: center; align-items: center; height: 10vh; font-size: 0.85em; background: ${props => props.theme.colors.background}; color: ${props => props.theme.colors.barText}; padding: 0.25em 0.5em; text-align: center; cursor: default; ` const Content = styled.div` ` const Link = styled.a` color: white; ` export default class Footer extends Component { render (){ return ( <FooterWrapper> <Content> Not FDIC Insured <br/> <Link href="https://github.com/csrf-demo/csrf-demo" target="_blank"> Fork on Github </Link> <br/> Nick Breaton &#183; Jeremy Bohannon &#183; Hunter Heavener </Content> </FooterWrapper> ) } }
Fix hunters name (my fault)
Fix hunters name (my fault)
JavaScript
mit
csrf-demo/csrf-demo,csrf-demo/csrf-demo
--- +++ @@ -32,7 +32,7 @@ Fork on Github </Link> <br/> - Nick Breaton &#183; Jeremy Bohannon &#183; Hunter Aeraer + Nick Breaton &#183; Jeremy Bohannon &#183; Hunter Heavener </Content> </FooterWrapper> )
36150a42a04a3ce5cd6de20018d36f55a64f4311
static/js/app.js
static/js/app.js
$(function() { $.get('/tagovi', {csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val()}, function(data) { var options = [] for (var i = 0; i < data.length; i++) { options.push(data[i].fields); } $('#id_tags').selectize({ persist: false, maxItems: 5, selectOnTab: true, valueField: 'name', labelField: 'name', searchField: 'name', options: options, create: function (input) { return { name: input }; } }); }); $("#reload").on("click", function(event) { event.preventDefault(); $.get('/vise-recepata', {page: $("#page").val(), csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val()}, function(data) { $("#toreload").remove(); $("#content").append(data); }); }); });
$(function() { $.get('/tagovi', function(data) { var options = [] for (var i = 0; i < data.length; i++) { options.push(data[i].fields); } $('#id_tags').selectize({ persist: false, maxItems: 5, selectOnTab: true, valueField: 'name', labelField: 'name', searchField: 'name', options: options, create: function (input) { return { name: input }; } }); }); $("#reload").on("click", function(event) { event.preventDefault(); $.get('/vise-recepata', {page: $("#page").val()}, function(data) { $("#toreload").remove(); $("#content").append(data); }); }); });
Fix using tokens in js.
Fix using tokens in js.
JavaScript
mit
MislavMandaric/abs-int,MislavMandaric/abs-int
--- +++ @@ -1,5 +1,5 @@ $(function() { - $.get('/tagovi', {csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val()}, function(data) { + $.get('/tagovi', function(data) { var options = [] for (var i = 0; i < data.length; i++) { options.push(data[i].fields); @@ -22,7 +22,7 @@ $("#reload").on("click", function(event) { event.preventDefault(); - $.get('/vise-recepata', {page: $("#page").val(), csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val()}, function(data) { + $.get('/vise-recepata', {page: $("#page").val()}, function(data) { $("#toreload").remove(); $("#content").append(data); });
b673fdbdac7e5523d16904920315d4ab6c79eaf8
tennu_plugins/blt.js
tennu_plugins/blt.js
var BLTPlugin = { init: function (client, imports) { return { handlers: { '!givemeblt': function (command) { client.act(command.channel, 'gives a juicy BLT to ' + command.nickname); } }, help: { 'givemeblt': [ '!givemeblt', 'Gives the requestor a juicy BLT.' ] }, commands: ['givemeblt'] } } }; module.exports = BLTPlugin;
var BLTPlugin = { init: function (client, imports) { return { handlers: { '!givemeblt': function (command) { client.act(command.channel, 'gives a juicy BLT to ' + command.nickname); } }, help: { 'givemeblt': [ '{{!}}givemeblt', 'Gives the requestor a juicy BLT.' ] }, commands: ['givemeblt'] } } }; module.exports = BLTPlugin;
Use {{!}} instead of ! for help.
Enhancement: Use {{!}} instead of ! for help.
JavaScript
isc
Tennu/BLTBot
--- +++ @@ -9,7 +9,7 @@ help: { 'givemeblt': [ - '!givemeblt', + '{{!}}givemeblt', 'Gives the requestor a juicy BLT.' ] },
600df5d2f48c190a948cbee6c1d668db99498096
src/src.js
src/src.js
console.log("Running!"); var Library = { name: "Timmy", //Library has been called Timmy greet: function(){ alert("Hello from the " + Library.name + " library."); } /* This library is what is known as an object literal. To invoke the greet function, we would write: Library.greet(); */ }
//O. M. J. This actually works. YAY!!! console.log("Running!"); var Library = { name: "John", //Library has been called Timmy greet: function(){ alert("Hello from the " + Library.name + " library."); console.log("User executed Library.greet()!" + "Hi " + name); } stop: function(text){ var alerttext = this.text; alert(alerttext); console.log("You just alerted" + alerttext); } /* This library is what is known as an object literal. To invoke the greet function, we would write: Library.greet(); */ } console.log("All code completed with no errors. \n\n\n Success!")
Clean and ADD ++ (stop)
Clean and ADD ++ (stop) stop == alert
JavaScript
mit
alaskamani15/beginner.js
--- +++ @@ -1,9 +1,17 @@ +//O. M. J. This actually works. YAY!!! + console.log("Running!"); var Library = { - name: "Timmy", //Library has been called Timmy + name: "John", //Library has been called Timmy greet: function(){ alert("Hello from the " + Library.name + " library."); + console.log("User executed Library.greet()!" + "Hi " + name); + } + stop: function(text){ + var alerttext = this.text; + alert(alerttext); + console.log("You just alerted" + alerttext); } /* This library is what is known as an object literal. To invoke the greet function, we would write: @@ -11,3 +19,5 @@ */ } + +console.log("All code completed with no errors. \n\n\n Success!")
b2ed3cdc9c5c12f4d93efea910e0f4f27a02eb0d
src/bar.js
src/bar.js
define(function() { var hr = codebox.require("hr/hr"); var StatusBar = hr.View.extend({ className: "component-statusbar" }); return StatusBar; });
define(function() { var hr = codebox.require("hr/hr"); var _ = codebox.require("hr/utils"); var StatusBar = hr.View.extend({ className: "component-statusbar", // Show loading indicator for a promise // Return the same promise loading: function(p, options) { var that = this; options = _.defaults(options || {}, { // Interval for indicator update (in ms) interval: 300, // Size of indicator size: 7 }); var direction = 1; var position = 0; var interval; var showIndicator = function() { var content = "["; _.each(_.range(options.size), function(i) { if (i == position) { content += "="; } else { content += "-"; } }) content += "]"; that.$el.text(content); position = position + direction; if (position == (options.size -1)) { direction = -direction; } if (position == 0) { direction = -direction; } }; interval = setInterval(showIndicator, options.interval); p.done(function() { clearInterval(interval); that.$el.text(""); }); return p; } }); return StatusBar; });
Add simple api for loading message
Add simple api for loading message
JavaScript
apache-2.0
CodeboxIDE/package-statusbar,etopian/codebox-package-statusbar
--- +++ @@ -1,8 +1,60 @@ define(function() { var hr = codebox.require("hr/hr"); + var _ = codebox.require("hr/utils"); var StatusBar = hr.View.extend({ - className: "component-statusbar" + className: "component-statusbar", + + + + // Show loading indicator for a promise + // Return the same promise + loading: function(p, options) { + var that = this; + options = _.defaults(options || {}, { + // Interval for indicator update (in ms) + interval: 300, + + // Size of indicator + size: 7 + }); + + var direction = 1; + var position = 0; + var interval; + + var showIndicator = function() { + var content = "["; + + _.each(_.range(options.size), function(i) { + if (i == position) { + content += "="; + } else { + content += "-"; + } + }) + + content += "]"; + + that.$el.text(content); + position = position + direction; + if (position == (options.size -1)) { + direction = -direction; + } + if (position == 0) { + direction = -direction; + } + }; + + interval = setInterval(showIndicator, options.interval); + + p.done(function() { + clearInterval(interval); + that.$el.text(""); + }); + + return p; + } }); return StatusBar;
5127fe15793fd2a35af77f7f57a71f905ddaf2a3
test/croonga.test.js
test/croonga.test.js
var http = require('http'); var should = require('should'); var spawn = require('child_process').spawn; function run(options, callback) { var command, commandPath, output; commandPath = __dirname + '/../bin/croonga'; command = spawn(commandPath, options); output = { stdout: '', stderr: '' }; command.stdout.on('data', function(data) { output.stdout += data; }); command.stderr.on('data', function(data) { output.stderr += data; }); callback(null, command, output); } describe('croonga command', function() { it('should output help for --help', function(done) { run(['--help'], function(error, command, output) { command.on('exit', function() { output.stdout.should.include("Usage:"); done(); }); }); }); });
var http = require('http'); var should = require('should'); var spawn = require('child_process').spawn; function run(options, callback) { var command, commandPath, output; commandPath = __dirname + '/../bin/croonga'; command = spawn(commandPath, options); output = { stdout: '', stderr: '' }; command.stdout.on('data', function(data) { output.stdout += data; }); command.stderr.on('data', function(data) { output.stderr += data; }); callback(null, command, output); } describe('croonga command', function() { it('should output help for --help', function(done) { run(['--help'], function(error, command, output) { command.on('exit', function(code) { code.should.equal(0); output.stdout.should.include("Usage:"); done(); }); }); }); });
Check status code returned from croonga command
Check status code returned from croonga command
JavaScript
mit
groonga/gcs,groonga/gcs
--- +++ @@ -22,7 +22,8 @@ describe('croonga command', function() { it('should output help for --help', function(done) { run(['--help'], function(error, command, output) { - command.on('exit', function() { + command.on('exit', function(code) { + code.should.equal(0); output.stdout.should.include("Usage:"); done(); });
5c1fa9ba4e012a25aea47d5f08302bce4a28d473
tests/dummy/app/controllers/application.js
tests/dummy/app/controllers/application.js
import Ember from 'ember'; export default Ember.Controller.extend({ toggleModal: false, actions: { testing() { window.swal("Hello World", "success"); }, toggle() { this.set('toggleModal', true); } } });
import Ember from 'ember'; export default Ember.Controller.extend({ toggleModal: false, actions: { testing() { window.swal({ title: 'Submit email to run ajax request', input: 'email', showCancelButton: true, confirmButtonText: 'Submit', preConfirm: function() { return new Ember.RSVP.Promise(function(resolve) { window.swal.enableLoading(); setTimeout(function() { resolve(); }, 2000); }); }, allowOutsideClick: false }).then(function(email) { if (email) { window.swal({ type: 'success', title: 'Ajax request finished!', html: 'Submitted email: ' + email }); } }); }, toggle() { this.set('toggleModal', true); } } });
Make a bit more complex dummy
Make a bit more complex dummy
JavaScript
mit
Tonkpils/ember-sweetalert,Tonkpils/ember-sweetalert
--- +++ @@ -5,7 +5,29 @@ actions: { testing() { - window.swal("Hello World", "success"); + window.swal({ + title: 'Submit email to run ajax request', + input: 'email', + showCancelButton: true, + confirmButtonText: 'Submit', + preConfirm: function() { + return new Ember.RSVP.Promise(function(resolve) { + window.swal.enableLoading(); + setTimeout(function() { + resolve(); + }, 2000); + }); + }, + allowOutsideClick: false + }).then(function(email) { + if (email) { + window.swal({ + type: 'success', + title: 'Ajax request finished!', + html: 'Submitted email: ' + email + }); + } + }); }, toggle() { this.set('toggleModal', true);
fbec1e1a32bdda21779187391d875d58e6bd80df
lib/plugin/in/googleanalytics.js
lib/plugin/in/googleanalytics.js
var gaAnalytics = require("ga-analytics"), moment = require("moment"); var googleAnalytics = {}; googleAnalytics.load = function(args, next) { var outputs = []; // Setting before a fixed period of time if (args.timeago) { args['startDate'] = args['endDate'] = moment().add(-1 * args.timeago.ago, args.timeago.period).format("YYYY-MM-DD"); } gaAnalytics(args, function(err, res) { if(err) { next(error, "google analytics error."); return; } outputs.push(res.totalsForAllResults[args.metrics]); next(false, outputs); }); }; module.exports = googleAnalytics;
var gaAnalytics = require("ga-analytics"), moment = require("moment"), format = require('string-format'); var googleAnalytics = {}; googleAnalytics.load = function(args, next) { var outputs = []; // Setting before a fixed period of time if (args.timeago) { args['startDate'] = args['endDate'] = moment().add(-1 * args.timeago.ago, args.timeago.period).format("YYYY-MM-DD"); } gaAnalytics(args, function(err, res) { if(err) { next(error, "google analytics error."); return; } if (args.results == "rows") { outputs = res.rows.map(function(val) { var passed = [args.format].concat(val); return format.apply({}, passed); }); if (args.limit) { outputs = outputs.slice(0, args.limit); } } else { outputs.push(res.totalsForAllResults[args.metrics]); } next(false, outputs); }); }; module.exports = googleAnalytics;
Update google analytics input plugin. 複数のカラムの取得対応 (resultsプロパティ追加, filterに渡すフォーマット制御プロパティ追加)
Update google analytics input plugin. 複数のカラムの取得対応 (resultsプロパティ追加, filterに渡すフォーマット制御プロパティ追加)
JavaScript
mit
hideack/evac
--- +++ @@ -1,5 +1,6 @@ var gaAnalytics = require("ga-analytics"), - moment = require("moment"); + moment = require("moment"), + format = require('string-format'); var googleAnalytics = {}; @@ -17,7 +18,20 @@ return; } - outputs.push(res.totalsForAllResults[args.metrics]); + if (args.results == "rows") { + outputs = res.rows.map(function(val) { + var passed = [args.format].concat(val); + return format.apply({}, passed); + }); + + if (args.limit) { + outputs = outputs.slice(0, args.limit); + } + + } else { + outputs.push(res.totalsForAllResults[args.metrics]); + } + next(false, outputs); }); };
b0d31962fc495128093e3a827ec725ecea567dfa
statics.js
statics.js
var express = require('express'); module.exports.init = function(app) { app.use('/js', express.static(__dirname + '/dist/js', {maxAge: 86400000 * 7})); app.use('/css', express.static(__dirname + '/dist/css', {maxAge: 86400000 * 7})); app.use('/img', express.static(__dirname + '/dist/img', {maxAge: 86400000 * 7})); app.use('/font', express.static(__dirname + '/dist/font', {maxAge: 86400000 * 7})); app.use(express.favicon(__dirname + '/dist/favicon.ico', {maxAge: 86400000 * 7})); app.get('/apple-touch-icon-precomposed.png', function(req, res) { res.sendfile(__dirname + '/dist' + req.url, {maxAge: 86400000 * 7}); }); };
var express = require('express'); var oneDay = 86400000; // milliseconds: 60 * 60 * 24 * 1000 var oneWeek = oneDay * 7; module.exports.init = function(app) { app.use('/css', express.static(__dirname + '/dist/css', { maxAge: oneWeek })); app.use('/font', express.static(__dirname + '/dist/font', { maxAge: oneWeek })); app.use('/img', express.static(__dirname + '/dist/img', { maxAge: oneWeek })); app.use('/js', express.static(__dirname + '/dist/js', { maxAge: oneWeek })); app.use(express.favicon(__dirname + '/dist/favicon.ico', { maxAge: oneWeek })); app.get('/apple-touch-icon-precomposed.png', function(req, res) { res.sendfile(__dirname + '/dist' + req.url, { maxAge: oneWeek }); }); };
Use variables for the expires date.
Use variables for the expires date.
JavaScript
mit
caktux/david-www,ecomfe/david-www,ExC0d3/david-www,caktux/david-www,wzrdtales/david-www,80xer/david-www,JoseRoman/david-www,JoseRoman/david-www,alanshaw/david-www,wzrdtales/david-www,ecomfe/david-www,80xer/david-www,ExC0d3/david-www
--- +++ @@ -1,15 +1,18 @@ var express = require('express'); + +var oneDay = 86400000; // milliseconds: 60 * 60 * 24 * 1000 +var oneWeek = oneDay * 7; module.exports.init = function(app) { - app.use('/js', express.static(__dirname + '/dist/js', {maxAge: 86400000 * 7})); - app.use('/css', express.static(__dirname + '/dist/css', {maxAge: 86400000 * 7})); - app.use('/img', express.static(__dirname + '/dist/img', {maxAge: 86400000 * 7})); - app.use('/font', express.static(__dirname + '/dist/font', {maxAge: 86400000 * 7})); + app.use('/css', express.static(__dirname + '/dist/css', { maxAge: oneWeek })); + app.use('/font', express.static(__dirname + '/dist/font', { maxAge: oneWeek })); + app.use('/img', express.static(__dirname + '/dist/img', { maxAge: oneWeek })); + app.use('/js', express.static(__dirname + '/dist/js', { maxAge: oneWeek })); - app.use(express.favicon(__dirname + '/dist/favicon.ico', {maxAge: 86400000 * 7})); + app.use(express.favicon(__dirname + '/dist/favicon.ico', { maxAge: oneWeek })); app.get('/apple-touch-icon-precomposed.png', function(req, res) { - res.sendfile(__dirname + '/dist' + req.url, {maxAge: 86400000 * 7}); + res.sendfile(__dirname + '/dist' + req.url, { maxAge: oneWeek }); }); };
8568eec430b660caf4f1d59f1f67b2350234260a
webpack.config.js
webpack.config.js
/** * This config takes some basic config from conf/webpack/<dev|prod>.js * and builds the appropriate webpack config from there. * * The primary difference is that dev has webpack hot reloading * whereas dev does not. * * The 'loaders' and 'output' need to exist here, because the path needs * to exist at the root (relative to the actual './client/...') */ var settings = require('./settings.js'); var bows = require('bows'); var path = require('path'); var rootDir = path.join(__dirname); module.exports = settings.DEBUG ? require('./conf/webpack/dev.js')(rootDir) : require('./conf/webpack/prod.js')(rootDir);
/** * This config takes some basic config from conf/webpack/<dev|prod>.js * and builds the appropriate webpack config from there. * * The primary difference is that dev has webpack hot reloading * whereas dev does not. * * The 'loaders' and 'output' need to exist here, because the path needs * to exist at the root (relative to the actual './client/...') */ var settings = require('./settings.js'); var bows = require('bows'); var path = require('path'); // this file is required at the root, so pass the rootDir into // sub folders // TODO look into cleaner ways of handling this. var rootDir = path.join(__dirname); if(settings.DEBUG){ var webpack = require('./conf/webpack/dev.js')(rootDir); } else { var webpack = require('./conf/webpack/prod.js')(rootDir); } module.exports = webpack;
Add verbose if else for additional logging, etc.
Add verbose if else for additional logging, etc.
JavaScript
mit
jamie-w/es6-bootstrap,jamie-w/es6-bootstrap
--- +++ @@ -14,8 +14,16 @@ var path = require('path'); +// this file is required at the root, so pass the rootDir into +// sub folders +// TODO look into cleaner ways of handling this. var rootDir = path.join(__dirname); -module.exports = settings.DEBUG ? - require('./conf/webpack/dev.js')(rootDir) : - require('./conf/webpack/prod.js')(rootDir); + +if(settings.DEBUG){ + var webpack = require('./conf/webpack/dev.js')(rootDir); +} else { + var webpack = require('./conf/webpack/prod.js')(rootDir); +} + +module.exports = webpack;
05502c29ab3e5305fb944ed8e5ca7450638c365b
blueprints/ember-cli-bootswatch/index.js
blueprints/ember-cli-bootswatch/index.js
module.exports = { description: 'Add bower dependencies for bootstrap and bootswatch to the project' afterInstall: function(options) { return this.addBowerPackagesToProject([ {name: 'bootstrap', target: '^3.3.1'}, {name: 'bootswatch', target: '^3.3.1'} ]); } };
module.exports = { description: 'Add bower dependencies for bootstrap and bootswatch to the project', normalizeEntityName: function() { // allows us to run ember -g ember-cli-bootswatch and not blow up // because ember cli normally expects the format // ember generate <entitiyName> <blueprint> }, afterInstall: function(options) { return this.addBowerPackagesToProject([ {name: 'bootstrap', target: '^3.3.1'}, {name: 'bootswatch', target: '^3.3.1'} ]); } };
Enable running blueprint without entity name
Enable running blueprint without entity name Missed a comma after description and fix issue running blueprint without an entity name. Fixes #6
JavaScript
mit
Panman8201/ember-cli-bootswatch
--- +++ @@ -1,5 +1,11 @@ module.exports = { - description: 'Add bower dependencies for bootstrap and bootswatch to the project' + description: 'Add bower dependencies for bootstrap and bootswatch to the project', + + normalizeEntityName: function() { + // allows us to run ember -g ember-cli-bootswatch and not blow up + // because ember cli normally expects the format + // ember generate <entitiyName> <blueprint> + }, afterInstall: function(options) { return this.addBowerPackagesToProject([
13ec0b7104aeb85280b1adf8828b926d7cf5daad
blueprints/ember-frontmatter-md/index.js
blueprints/ember-frontmatter-md/index.js
module.exports = { description: 'Creates an initializer to load posts from the meta tag.' // locals: function(options) { // // Return custom template variables here. // return { // foo: options.entity.options.foo // }; // } // afterInstall: function(options) { // // Perform extra work here. // } };
module.exports = { description: 'Creates an initializer to load posts from the meta tag.', // locals: function(options) { // // Return custom template variables here. // return { // foo: options.entity.options.foo // }; // } // afterInstall: function(options) { // // Perform extra work here. // } normalizeEntityName: function() { } };
Add workaroudn to let blueprints work correctly
Add workaroudn to let blueprints work correctly
JavaScript
mit
yaymukund/ember-frontmatter-md,yaymukund/ember-frontmatter-md,yaymukund/ember-frontmatter-md
--- +++ @@ -1,5 +1,5 @@ module.exports = { - description: 'Creates an initializer to load posts from the meta tag.' + description: 'Creates an initializer to load posts from the meta tag.', // locals: function(options) { // // Return custom template variables here. @@ -11,4 +11,5 @@ // afterInstall: function(options) { // // Perform extra work here. // } + normalizeEntityName: function() { } };
5324f5540f3950fc0acc6ade82f6c1bb49683b13
webpack.config.js
webpack.config.js
/*global module, __dirname, require */ /** * @name webpack * @type {Object} * @property NoEmitOnErrorsPlugin */ /** * @name path * @property resolve */ var webpack = require('webpack'), path = require('path'); module.exports = { entry: { bundle: './src/index' }, output: { filename: 'js/[name].js', path: path.resolve(__dirname, './build/js'), publicPath: '../build/' }, module: { loaders: [{ test: /\.js/, exclude: '/node_modules/', loader: 'babel-loader' }, { test: /\.(png|jpg|gif)$/, loader: 'file-loader?name=images/img-[hash:6].[ext]' }] }, plugins: [ new webpack.NoEmitOnErrorsPlugin() ] };
/*global module, __dirname, require */ /** * @name webpack * @type {Object} * @property NoEmitOnErrorsPlugin */ /** * @name path * @property resolve */ var webpack = require('webpack'), path = require('path'); module.exports = { entry: { bundle: './src/index' }, output: { filename: 'js/[name].js', path: path.resolve(__dirname, './build/js'), publicPath: '../build/' }, module: { loaders: [{ test: /\.js/, exclude: '/node_modules/', loader: 'babel-loader' }, { test: /\.(png|jpg|gif)$/, loader: 'file-loader?name=images/img-[hash:6].[ext]' }] }, plugins: [ new webpack.NoEmitOnErrorsPlugin() ], devtool: '#cheap-module-eval-source-map', resolve: { alias: { src: path.resolve(__dirname, 'src'), components: path.resolve(__dirname, 'src/components'), constants: path.resolve(__dirname, 'src/constants'), data: path.resolve(__dirname, 'src/data'), scenes: path.resolve(__dirname, 'src/scenes'), scss: path.resolve(__dirname, 'src/scss'), services: path.resolve(__dirname, 'src/services') } } };
Add alias for core directories, update devtool property
Add alias for core directories, update devtool property
JavaScript
mit
dashukin/react-redux-template,dashukin/react-redux-template
--- +++ @@ -37,5 +37,17 @@ }, plugins: [ new webpack.NoEmitOnErrorsPlugin() - ] + ], + devtool: '#cheap-module-eval-source-map', + resolve: { + alias: { + src: path.resolve(__dirname, 'src'), + components: path.resolve(__dirname, 'src/components'), + constants: path.resolve(__dirname, 'src/constants'), + data: path.resolve(__dirname, 'src/data'), + scenes: path.resolve(__dirname, 'src/scenes'), + scss: path.resolve(__dirname, 'src/scss'), + services: path.resolve(__dirname, 'src/services') + } + } };
a571ce2b1948bdf1e5c6bcb699a323dae3632b9e
webpack.config.js
webpack.config.js
const path = require('path'); const webpack = require('webpack'); module.exports = { entry: { app: path.resolve(__dirname, 'app/Resources/assets/js/app.js') }, output: { path: path.resolve(__dirname, 'web/builds'), filename: 'bundle.js', publicPath: '/builds/' }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: 'babel-loader' }, { test: /\.scss$/, use: [ { loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader" } ] }, { test: /\.woff2?$|\.ttf$|\.eot$|\.svg$/, use: "url-loader" } ] }, plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery", }), ], resolve: { alias: { fonts: path.resolve(__dirname, 'web/fonts'), jquery: path.resolve(__dirname, 'app/Resources/assets/js/jquery-2.1.4.min.js') } } };
const path = require('path'); const webpack = require('webpack'); module.exports = { entry: { app: path.resolve(__dirname, 'app/Resources/assets/js/app.js') }, output: { path: path.resolve(__dirname, 'web/builds'), filename: 'bundle.js', publicPath: '/builds/' }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: 'babel-loader' }, { test: /\.scss$/, use: [ { loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader" } ] }, { test: /\.woff2?$|\.ttf$|\.eot$|\.svg$/, use: "url-loader" } ] }, plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery", }), ], resolve: { alias: { fonts: path.resolve(__dirname, 'web/fonts'), jquery: path.resolve(__dirname, 'app/Resources/assets/js/jquery-2.1.4.min.js'), moment: path.resolve(__dirname, 'app/Resources/assets/js/moment.min.js') } } };
Fix module not found error on moment
Fix module not found error on moment
JavaScript
mit
alOneh/sf-live-2017-symfony-webpack,alOneh/sf-live-2017-symfony-webpack,alOneh/sf-live-2017-symfony-webpack
--- +++ @@ -41,7 +41,8 @@ resolve: { alias: { fonts: path.resolve(__dirname, 'web/fonts'), - jquery: path.resolve(__dirname, 'app/Resources/assets/js/jquery-2.1.4.min.js') + jquery: path.resolve(__dirname, 'app/Resources/assets/js/jquery-2.1.4.min.js'), + moment: path.resolve(__dirname, 'app/Resources/assets/js/moment.min.js') } } };
4266ec9fc365160e2d8fa828cffbd84f759b1f70
mendel/angular/src/app/core/services/auth.service.js
mendel/angular/src/app/core/services/auth.service.js
(function() { 'use strict'; angular .module('static') .factory('AuthService', function ($http, apiHost, Session) { var authService = {}; authService.login = function login(credentials) { return $http .post(apiHost + '/login/', credentials) .then(function (res) { // Create a session (TBD) // Session.create(res.data.session, res.data.id) }); }; authService.isAuthenticated = function isAuthenticated() { return !!Session.userId; }; return authService; }); })();
(function() { 'use strict'; angular .module('static') .factory('AuthService', function ($http, $httpParamSerializerJQLike, $state, $localStorage, apiHost, Session, toastr) { var authService = {}; authService.login = function login(credentials) { return $http({ method: 'POST', url: apiHost + '/login/', data: $httpParamSerializerJQLike(credentials), headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).then(function loginSuccess (data) { // Deserialize the return: var key = data.data.key; var user = data.data.user; // Create Session Session.create(key, user); // Show Success Toast and Redirect toastr.success('Logged In'); $state.go('main'); }, function loginError (error) { toastr.error(JSON.stringify(error)); }); }; authService.logout = function logout(session) { return $http({ method: 'POST', url: apiHost + '/logout/', data: $httpParamSerializerJQLike(session), headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).then(function logoutSuccess (data) { // Destroy Session Session.destroy(); }, function logoutError (error) { toastr.error(JSON.stringify(error)); }); }; authService.getCurrentUser = function getCurrentUser() { // First, check if there's an existing Session if (!!Session.user) { // Yes? Return this user return Session.user; } // If no, check if there's a token to retrieve the user else if (!!$localStorage._mendelToken) { // Set Authorization Header with Token $http.defaults.headers.common['Authorization'] = 'Token ' + $localStorage._mendelToken; // Get User info from endpoint $http({ method: 'GET', url: apiHost + '/user/' }).then(function getCurrentUserSuccess (data) { // Deserialize the return: var user = data.data; // (Creating a Session also requires the token): var key = $localStorage._mendelToken; // Create Session Session.create(key, user); }, function getCurrentUserError (error) { toastr.error(JSON.stringify(error)); }); } else { return null; } }; authService.isAuthenticated = function isAuthenticated() { return !!Session.user; }; return authService; }); })();
Create login/logout/getCurrentUser functions on AuthService
Create login/logout/getCurrentUser functions on AuthService
JavaScript
agpl-3.0
Architizer/mendel,Architizer/mendel,Architizer/mendel,Architizer/mendel
--- +++ @@ -3,22 +3,100 @@ angular .module('static') - .factory('AuthService', function ($http, apiHost, Session) { + .factory('AuthService', function ($http, $httpParamSerializerJQLike, $state, $localStorage, apiHost, Session, toastr) { var authService = {}; authService.login = function login(credentials) { - return $http - .post(apiHost + '/login/', credentials) - .then(function (res) { - // Create a session (TBD) - // Session.create(res.data.session, res.data.id) + + return $http({ + method: 'POST', + url: apiHost + '/login/', + data: $httpParamSerializerJQLike(credentials), + headers: {'Content-Type': 'application/x-www-form-urlencoded'} + }).then(function loginSuccess (data) { + + // Deserialize the return: + var key = data.data.key; + var user = data.data.user; + + // Create Session + Session.create(key, user); + + // Show Success Toast and Redirect + toastr.success('Logged In'); + $state.go('main'); + + }, function loginError (error) { + + toastr.error(JSON.stringify(error)); + }); + }; + + authService.logout = function logout(session) { + + return $http({ + method: 'POST', + url: apiHost + '/logout/', + data: $httpParamSerializerJQLike(session), + headers: {'Content-Type': 'application/x-www-form-urlencoded'} + }).then(function logoutSuccess (data) { + + // Destroy Session + Session.destroy(); + + }, function logoutError (error) { + + toastr.error(JSON.stringify(error)); + }); + }; + + authService.getCurrentUser = function getCurrentUser() { + + // First, check if there's an existing Session + if (!!Session.user) { + + // Yes? Return this user + return Session.user; + } + + // If no, check if there's a token to retrieve the user + else if (!!$localStorage._mendelToken) { + + // Set Authorization Header with Token + $http.defaults.headers.common['Authorization'] = 'Token ' + $localStorage._mendelToken; + + // Get User info from endpoint + $http({ + method: 'GET', + url: apiHost + '/user/' + }).then(function getCurrentUserSuccess (data) { + + // Deserialize the return: + var user = data.data; + + // (Creating a Session also requires the token): + var key = $localStorage._mendelToken; + + // Create Session + Session.create(key, user); + + }, function getCurrentUserError (error) { + + toastr.error(JSON.stringify(error)); }); + } + + else { + + return null; + } }; - + authService.isAuthenticated = function isAuthenticated() { - return !!Session.userId; + + return !!Session.user; }; - + return authService; }); })();
d8245ec2c355b0f3c2189ea26e68bcd690e6de84
generators/app/templates/authentication.js
generators/app/templates/authentication.js
'use strict'; const authentication = require('feathers-authentication'); <% for (var i = 0; i < authentication.length; i++) { %> const <%= S(authentication[i].name).capitalize().s %>Strategy = require('<%= authentication[i].strategy %>').Strategy;<% if (authentication[i].tokenStrategy) { %> const <%= S(authentication[i].name).capitalize().s %>TokenStrategy = require('<%= authentication[i].tokenStrategy %>').Strategy;<% }} %> module.exports = function() { const app = this; let config = app.get('auth'); <% for (var i = 0; i < authentication.length; i++) { %> config.<%= authentication[i].name %>.strategy = <%= S(authentication[i].name).capitalize().s %>Strategy;<% if (authentication[i].tokenStrategy) { %> config.<%= authentication[i].name %>.tokenStrategy = <%= S(authentication[i].name).capitalize().s %>TokenStrategy;<% }} %> app.set('auth', config); app.configure(authentication(config)); }
'use strict'; const authentication = require('feathers-authentication'); <% for (var i = 0; i < authentication.length; i++) { %> const <%= S(authentication[i].name).capitalize().s %>Strategy = require('<%= authentication[i].strategy %>').Strategy;<% if (authentication[i].tokenStrategy) { %> const <%= S(authentication[i].name).capitalize().s %>TokenStrategy = require('<%= authentication[i].tokenStrategy %>');<% }} %> module.exports = function() { const app = this; let config = app.get('auth'); <% for (var i = 0; i < authentication.length; i++) { %> config.<%= authentication[i].name %>.strategy = <%= S(authentication[i].name).capitalize().s %>Strategy;<% if (authentication[i].tokenStrategy) { %> config.<%= authentication[i].name %>.tokenStrategy = <%= S(authentication[i].name).capitalize().s %>TokenStrategy;<% }} %> app.set('auth', config); app.configure(authentication(config)); }
Fix to support token based auth strategies
Fix to support token based auth strategies
JavaScript
mit
feathersjs/generator-feathers,gradealabs/generator-feathers,feathersjs/generator-feathers,feathersjs/generator-feathers
--- +++ @@ -3,7 +3,7 @@ const authentication = require('feathers-authentication'); <% for (var i = 0; i < authentication.length; i++) { %> const <%= S(authentication[i].name).capitalize().s %>Strategy = require('<%= authentication[i].strategy %>').Strategy;<% if (authentication[i].tokenStrategy) { %> -const <%= S(authentication[i].name).capitalize().s %>TokenStrategy = require('<%= authentication[i].tokenStrategy %>').Strategy;<% }} %> +const <%= S(authentication[i].name).capitalize().s %>TokenStrategy = require('<%= authentication[i].tokenStrategy %>');<% }} %> module.exports = function() { const app = this;
fa5739409f1007d73202b0b48b5cea0535a7b3cc
generators/app/templates/webpack.config.js
generators/app/templates/webpack.config.js
const config = require('hjs-webpack')({ in: 'src/index.js', out: 'dist', clearBeforeBuild: true, devServer: { stats: { colors: true, }, }, }) module.exports = config
const config = require('hjs-webpack')({ in: 'src/index.js', out: 'dist', clearBeforeBuild: true, devServer: { stats: { colors: true } } }) config.resolve.modulesDirectories = [ 'web_modules', 'node_modules', 'src', 'src/modules/' ] module.exports = config
Add more directories to be resolved from
Add more directories to be resolved from
JavaScript
mit
127labs/generator-duxedo,127labs/generator-duxedo
--- +++ @@ -4,9 +4,16 @@ clearBeforeBuild: true, devServer: { stats: { - colors: true, - }, - }, + colors: true + } + } }) +config.resolve.modulesDirectories = [ + 'web_modules', + 'node_modules', + 'src', + 'src/modules/' +] + module.exports = config
ee38458c93e43cdeaa4a3a7cb3541dd792755fef
lib/dialects/sqlite/connector-manager.js
lib/dialects/sqlite/connector-manager.js
var Utils = require("../../utils") , sqlite3 = require('sqlite3').verbose() , Query = require("./query") module.exports = (function() { var ConnectorManager = function(sequelize) { this.sequelize = sequelize this.database = new sqlite3.Database(sequelize.options.storage || ':memory:') this.opened = false } Utils._.extend(ConnectorManager.prototype, require("../connector-manager").prototype) ConnectorManager.prototype.query = function(sql, callee, options) { var self = this // Turn on foreign key checking (if the database has any) unless explicitly // disallowed globally. if(!this.opened && this.sequelize.options.foreignKeys !== false) { this.database.serialize(function() { self.database.run("PRAGMA FOREIGN_KEYS = ON") self.opened = true }) } return new Query(this.database, this.sequelize, callee, options).run(sql) } return ConnectorManager })()
var Utils = require("../../utils") , sqlite3 = require('sqlite3').verbose() , Query = require("./query") module.exports = (function() { var ConnectorManager = function(sequelize) { this.sequelize = sequelize this.database = db = new sqlite3.Database(sequelize.options.storage || ':memory:', function(err) { if(!err && sequelize.options.foreignKeys !== false) { // Make it possible to define and use foreign key constraints unelss // explicitly disallowed. It's still opt-in per relation db.run('PRAGMA FOREIGN_KEYS=ON') } }) } Utils._.extend(ConnectorManager.prototype, require("../connector-manager").prototype) ConnectorManager.prototype.query = function(sql, callee, options) { return new Query(this.database, this.sequelize, callee, options).run(sql) } return ConnectorManager })()
Improve pragma handling for sqlite3
Improve pragma handling for sqlite3
JavaScript
mit
IrfanBaqui/sequelize
--- +++ @@ -5,22 +5,17 @@ module.exports = (function() { var ConnectorManager = function(sequelize) { this.sequelize = sequelize - this.database = new sqlite3.Database(sequelize.options.storage || ':memory:') - this.opened = false + this.database = db = new sqlite3.Database(sequelize.options.storage || ':memory:', function(err) { + if(!err && sequelize.options.foreignKeys !== false) { + // Make it possible to define and use foreign key constraints unelss + // explicitly disallowed. It's still opt-in per relation + db.run('PRAGMA FOREIGN_KEYS=ON') + } + }) } Utils._.extend(ConnectorManager.prototype, require("../connector-manager").prototype) ConnectorManager.prototype.query = function(sql, callee, options) { - var self = this - // Turn on foreign key checking (if the database has any) unless explicitly - // disallowed globally. - if(!this.opened && this.sequelize.options.foreignKeys !== false) { - this.database.serialize(function() { - self.database.run("PRAGMA FOREIGN_KEYS = ON") - self.opened = true - }) - } - return new Query(this.database, this.sequelize, callee, options).run(sql) }
9ea03c29ffc1dac7f04f094433c9e47c2ba1c5ad
topcube.js
topcube.js
var spawn = require('child_process').spawn; var path = require('path'); module.exports = function (options) { options = options || {}; options.url = options.url || 'http://nodejs.org'; options.name = options.name || 'nodejs'; var client; switch (process.platform) { case 'win32': client = path.resolve(__dirname + '/cefclient/cefclient'); break; case 'linux': client = path.resolve(__dirname + '/build/default/topcube'); break; default: console.warn(''); return null; break; } var args = []; for (var key in options) args.push('--' + key + '=' + options[key]); var child = spawn(client, args); child.on('exit', function(code) { process.exit(code); }); child.stdout.pipe(process.stdout); child.stderr.pipe(process.stderr); return child; };
var spawn = require('child_process').spawn; var path = require('path'); module.exports = function (options) { options = options || {}; options.url = options.url || 'http://nodejs.org'; options.name = options.name || 'nodejs'; var client; switch (process.platform) { case 'win32': client = path.resolve(__dirname + '/cefclient/cefclient'); break; case 'linux': client = path.resolve(__dirname + '/build/default/topcube'); break; default: console.warn(''); return null; break; } var args = []; for (var key in options) { // Omit keys besides name & url for now until options // parsing bugs are resolved. if (process.platform === 'win32' && (key !== 'name' || key !== 'url')) continue; args.push('--' + key + '=' + options[key]); } var child = spawn(client, args); child.on('exit', function(code) { process.exit(code); }); child.stdout.pipe(process.stdout); child.stderr.pipe(process.stderr); return child; };
Allow only name, url keys for win32.
Allow only name, url keys for win32.
JavaScript
mit
creationix/topcube,creationix/topcube,creationix/topcube
--- +++ @@ -21,7 +21,13 @@ } var args = []; - for (var key in options) args.push('--' + key + '=' + options[key]); + for (var key in options) { + // Omit keys besides name & url for now until options + // parsing bugs are resolved. + if (process.platform === 'win32' && + (key !== 'name' || key !== 'url')) continue; + args.push('--' + key + '=' + options[key]); + } var child = spawn(client, args); child.on('exit', function(code) {
6a4a3647799cfe79363c303054a57cb4e9cbb755
web/app.js
web/app.js
'use strict' const express = require('express') const dotenv = require('dotenv') const result = dotenv.config() if (result.error) dotenv.config({ path: '../.env' }) const app = express() const port = process.env.SITE_PORT app.use(express.static('public')) app.get('/', (req, res) => { res.sendFile('index.html') }) app.listen(port, () => { console.log('listening on port', port) })
'use strict' const express = require('express') const dotenv = require('dotenv') let result = dotenv.config() if (result.error) { result = dotenv.config({ path: '../.env' }) if (result.error) throw result.error } const app = express() const port = read_env_var("SITE_PORT") app.use(express.static('public')) app.get('/', (req, res) => { res.sendFile('index.html') }) app.listen(port, () => { console.log('listening on port', port) }) function read_env_var(envvar) { const val = process.env[envvar] if (!val) throw envvar + " must be specified. \ Did you forget to add it to your .env file?" }
Add error message for undefined envvars
Site: Add error message for undefined envvars
JavaScript
agpl-3.0
SirRade/shootr,SirRade/shootr,SirRade/shootr,SirRade/shootr,SirRade/shootr
--- +++ @@ -3,14 +3,17 @@ const express = require('express') const dotenv = require('dotenv') -const result = dotenv.config() -if (result.error) - dotenv.config({ +let result = dotenv.config() +if (result.error) { + result = dotenv.config({ path: '../.env' }) + if (result.error) + throw result.error +} const app = express() -const port = process.env.SITE_PORT +const port = read_env_var("SITE_PORT") app.use(express.static('public')) @@ -21,3 +24,10 @@ app.listen(port, () => { console.log('listening on port', port) }) + +function read_env_var(envvar) { + const val = process.env[envvar] + if (!val) + throw envvar + " must be specified. \ +Did you forget to add it to your .env file?" +}
9087e7280b21eee2af68653c3b633349098910de
client/src/history.js
client/src/history.js
import createHistory from 'history/createBrowserHistory' import * as qs from 'querystring' import config from './config' const history = createHistory() const navigate = path => { history.push(config.basePath + path) } const getPathname = loc => { let path = '/' + (loc.pathname + loc.hash) path = path.replace(new RegExp(`^${config.basePath}`), '') path = path.replace(/\?.*/, '') return path } const getQuery = loc => { let path = '/' + (loc.pathname + loc.hash) const search = path.replace(/[^?]*\?/, '') return qs.decode(search) } export { history, navigate, getPathname, getQuery, }
import createHistory from 'history/createBrowserHistory' import * as qs from 'querystring' import config from './config' const history = createHistory() const navigate = path => { history.push(config.basePath + path) } const getPathname = loc => { let path = loc.pathname + loc.hash path = path.replace(new RegExp(`^${config.basePath}`), '') if (path[0] !== '/') { path = '/' + path } path = path.replace(/\?.*/, '') return path } const getQuery = loc => { let path = loc.pathname + loc.hash + loc.search const search = path.replace(/[^?]*\?/, '') return qs.decode(search) } export { history, navigate, getPathname, getQuery, }
Fix router not resolving route in some cases
Fix router not resolving route in some cases
JavaScript
mit
daGrevis/msks,daGrevis/msks,daGrevis/msks
--- +++ @@ -10,15 +10,23 @@ } const getPathname = loc => { - let path = '/' + (loc.pathname + loc.hash) + let path = loc.pathname + loc.hash + path = path.replace(new RegExp(`^${config.basePath}`), '') + if (path[0] !== '/') { + path = '/' + path + } + path = path.replace(/\?.*/, '') + return path } const getQuery = loc => { - let path = '/' + (loc.pathname + loc.hash) + let path = loc.pathname + loc.hash + loc.search + const search = path.replace(/[^?]*\?/, '') + return qs.decode(search) }
db7c7ff579eed7683195d4b03754655e9f7246ba
tests/test-helper.js
tests/test-helper.js
/* globals require */ import resolver from './helpers/resolver'; import loadEmberExam from 'ember-exam/test-support/load'; const framework = require.has('ember-qunit') ? 'qunit' : 'mocha'; const oppositeFramework = !require.has('ember-qunit') ? 'qunit' : 'mocha'; Object.keys(require.entries).forEach((entry) => { if (entry.indexOf(oppositeFramework) !== -1) { delete require.entries[entry]; } }); require(`ember-${framework}`).default.setResolver(resolver); loadEmberExam(); // ember-qunit >= v3 support if (framework === 'qunit') { // Use string literal to prevent Babel to transpile this into ES6 import // that would break when tests run with Mocha framework. // In ember-qunit 3.4.0, this new check was added: https://github.com/emberjs/ember-qunit/commit/a7e93c4b4b535dae62fed992b46c00b62bfc83f4 // which adds this Ember.onerror validation test. As this is a test suite for the tests, it's not needed to run ember.OnerrorValidation tests. require(`ember-${framework}`).start({ setupEmberOnerrorValidation: false }); }
/* globals require */ import resolver from './helpers/resolver'; import loadEmberExam from 'ember-exam/test-support/load'; const framework = require.has('ember-qunit') ? 'qunit' : 'mocha'; const oppositeFramework = !require.has('ember-qunit') ? 'qunit' : 'mocha'; Object.keys(require.entries).forEach((entry) => { if (entry.indexOf(oppositeFramework) !== -1) { delete require.entries[entry]; } }); require(`ember-${framework}`).default.setResolver(resolver); loadEmberExam(); // ember-qunit >= v3 support if (framework === 'qunit') { // Use string literal to prevent Babel to transpile this into ES6 import // that would break when tests run with Mocha framework. require(`ember-${framework}`).start(); }
Remove a change in node version to have the change in a seperated pr
Remove a change in node version to have the change in a seperated pr
JavaScript
mit
trentmwillis/ember-exam,trentmwillis/ember-exam,trentmwillis/ember-scatter,trentmwillis/ember-scatter,trentmwillis/ember-exam
--- +++ @@ -19,7 +19,5 @@ if (framework === 'qunit') { // Use string literal to prevent Babel to transpile this into ES6 import // that would break when tests run with Mocha framework. - // In ember-qunit 3.4.0, this new check was added: https://github.com/emberjs/ember-qunit/commit/a7e93c4b4b535dae62fed992b46c00b62bfc83f4 - // which adds this Ember.onerror validation test. As this is a test suite for the tests, it's not needed to run ember.OnerrorValidation tests. - require(`ember-${framework}`).start({ setupEmberOnerrorValidation: false }); + require(`ember-${framework}`).start(); }
e537c60751c717e3963b4a93538b117a29b70a7c
tests/test_client.js
tests/test_client.js
'use strict'; /* TODO: GET client (all/specific/sortBy/pagination/search) POST client (ok/fail) PUT client DELETE client */ exports.get = function(assert, client) { return client.clients.get().then(function(res) { assert(res.data.length === 0, 'Failed to get clients as expected'); }).catch(function() { assert(true, 'Failed to get clients as expected'); }); }; exports.post = function(assert, client) { return client.clients.post().then(function() { assert(false, 'Posted client even though shouldn\'t'); }).catch(function() { assert(true, 'Failed to post client as expected'); }); }; exports.put = function(assert, client) { return client.clients.put().then(function() { assert(false, 'Updated client even though shouldn\'t'); }).catch(function() { assert(true, 'Failed to update client as expected'); }); };
'use strict'; /* TODO: GET client (all/specific/sortBy/pagination/search) POST client (ok/fail) PUT client DELETE client */ exports.get = function(assert, client) { return client.clients.get().then(function(res) { assert(res.data.length === 0, 'Failed to get clients as expected'); }).catch(function() { assert(true, 'Failed to get clients as expected'); }); }; exports.postInvalid = function(assert, client) { return client.clients.post().then(function() { assert(false, 'Posted client even though shouldn\'t'); }).catch(function() { assert(true, 'Failed to post client as expected'); }); }; exports.postValid = function(assert, client) { // TODO: generate a valid client based on schema return client.clients.post({}).then(function() { assert(true, 'Posted client as expected'); }).catch(function(err) { assert(false, 'Failed to post client', err); }); }; exports.put = function(assert, client) { return client.clients.put().then(function() { assert(false, 'Updated client even though shouldn\'t'); }).catch(function() { assert(true, 'Failed to update client as expected'); }); };
Add stub for posting valid client
Add stub for posting valid client
JavaScript
mit
bebraw/react-crm-backend,koodilehto/koodilehto-crm-backend
--- +++ @@ -16,11 +16,20 @@ }); }; -exports.post = function(assert, client) { +exports.postInvalid = function(assert, client) { return client.clients.post().then(function() { assert(false, 'Posted client even though shouldn\'t'); }).catch(function() { assert(true, 'Failed to post client as expected'); + }); +}; + +exports.postValid = function(assert, client) { + // TODO: generate a valid client based on schema + return client.clients.post({}).then(function() { + assert(true, 'Posted client as expected'); + }).catch(function(err) { + assert(false, 'Failed to post client', err); }); };
08f0a1e48c86d2878b6ea548f3b9090b0e17bc8f
truffle.js
truffle.js
module.exports = { migrations_directory: "./migrations", networks: { development: { host: "localhost", port: 8545, network_id: "*" }, live: { host: "localhost", port: 8546, network_id: 1, }, Ropsten: { host: "localhost", port: 8547, network_id: 3, gasprice: 23000000000, // 23 gwei }, Rinkeby: { host: "localhost", port: 8548, network_id: 4, } } }
module.exports = { migrations_directory: "./migrations", networks: { development: { host: "localhost", port: 8545, network_id: "*" }, live: { host: "localhost", port: 8546, network_id: 1, }, Ropsten: { host: "localhost", port: 8547, network_id: 3, gasprice: 23000000000, // 23 gwei }, Kovan: { host: "localhost", port: 8548, network_id: 42, gasprice: 23000000000, // 23 gwei }, Rinkeby: { host: "localhost", port: 8549, network_id: 4, } } }
Deploy to Kovan test network.
Deploy to Kovan test network.
JavaScript
mit
TripleSpeeder/StandingOrderDapp,TripleSpeeder/StandingOrderDapp
--- +++ @@ -17,9 +17,15 @@ network_id: 3, gasprice: 23000000000, // 23 gwei }, + Kovan: { + host: "localhost", + port: 8548, + network_id: 42, + gasprice: 23000000000, // 23 gwei + }, Rinkeby: { host: "localhost", - port: 8548, + port: 8549, network_id: 4, } }
bdcd0f382efcb77415813955bc0ca4e0ece4f8c6
src/Form/FormText.js
src/Form/FormText.js
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; const propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, }; const defaultProps = { className: null, }; function FormText({ children, className }) { const classes = cx('form-text', className); return ( <p className={classes}> {children} </p> ); } FormText.propTypes = propTypes; FormText.defaultProps = defaultProps; export default FormText;
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; const propTypes = { children: PropTypes.node.isRequired, variant: PropTypes.oneOf([ 'black', 'muted', 'primary', 'success', 'info', 'warning', 'danger', 'white', ]), className: PropTypes.string, }; const defaultProps = { variant: 'black', className: null, }; function FormText({ children, variant, className }) { const classes = cx('form-text', className, `text-${variant}`); return ( <p className={classes}> {children} </p> ); } FormText.propTypes = propTypes; FormText.defaultProps = defaultProps; export default FormText;
Add variant prop to form text component
Add variant prop to form text component
JavaScript
mit
ProAI/react-essentials
--- +++ @@ -4,15 +4,26 @@ const propTypes = { children: PropTypes.node.isRequired, + variant: PropTypes.oneOf([ + 'black', + 'muted', + 'primary', + 'success', + 'info', + 'warning', + 'danger', + 'white', + ]), className: PropTypes.string, }; const defaultProps = { + variant: 'black', className: null, }; -function FormText({ children, className }) { - const classes = cx('form-text', className); +function FormText({ children, variant, className }) { + const classes = cx('form-text', className, `text-${variant}`); return ( <p className={classes}>
1d11599d6d881b7cbd4a96d50aa92566e38384d2
sort/insertion_sort.js
sort/insertion_sort.js
var insert = function(array, rightIndex, value) { for(var index = rightIndex; index >= 0 && array[index] > value; index--){ array[index + 1] = array[index]; } array[index + 1] = value; };
Add insert fxn to insertion sort
Add insert fxn to insertion sort
JavaScript
mit
aftaberski/algorithms,aftaberski/algorithms
--- +++ @@ -0,0 +1,8 @@ +var insert = function(array, rightIndex, value) { + for(var index = rightIndex; + index >= 0 && array[index] > value; + index--){ + array[index + 1] = array[index]; + } + array[index + 1] = value; +};
db4c7348e66753a969de4888e6c01608c1e49129
utils/convert.js
utils/convert.js
'use strict'; var _ = require('lodash'); var fs = require('fs'); var path = require('path'); var convert = { moduleToFolder: moduleToFolder, pathToModule: pathToModule }; function pathToModule(dir, entered) { var moduleName = _.camelCase(path.basename(dir)); var moduleFilename = moduleName + '.module.js'; var moduleFilePath = path.resolve(dir, moduleFilename); var prefix; try { fs.accessSync(moduleFilePath, fs.F_OK); prefix = pathToModule(path.resolve(dir, '..'), true); return (prefix) ? prefix + '.' + moduleName : moduleName; } catch (e) { if (entered) { return ''; } else { prefix = pathToModule(path.resolve(dir, '..'), true); return (prefix) ? prefix + '.' + moduleName : moduleName; } } } function moduleToFolder(moduleName) { var moduleParts = moduleName.split('.'); for (var i = 0; i < moduleParts.length; i++) { moduleParts[i] = _.kebabCase(moduleParts[i]); } moduleParts = _.join(moduleParts, '/') + '/'; return moduleParts.replace(/v-24/g, 'v24'); } module.exports = convert;
'use strict'; var _ = require('lodash'); var fs = require('fs'); var path = require('path'); var convert = { moduleToFolder: moduleToFolder, pathToModule: pathToModule }; function pathToModule(dir, entered) { var moduleName = _.camelCase(path.basename(dir)); var moduleFilename = path.basename(dir) + '.module.js'; var moduleFilePath = path.resolve(dir, moduleFilename); var prefix; try { fs.accessSync(moduleFilePath, fs.F_OK); prefix = pathToModule(path.resolve(dir, '..'), true); return (prefix) ? prefix + '.' + moduleName : moduleName; } catch (e) { if (entered) { return ''; } else { prefix = pathToModule(path.resolve(dir, '..'), true); return (prefix) ? prefix + '.' + moduleName : moduleName; } } } function moduleToFolder(moduleName) { var moduleParts = moduleName.split('.'); for (var i = 0; i < moduleParts.length; i++) { moduleParts[i] = _.kebabCase(moduleParts[i]); } moduleParts = _.join(moduleParts, '/') + '/'; return moduleParts.replace(/v-24/g, 'v24'); } module.exports = convert;
Fix passing dashed module paths to generator
Fix passing dashed module paths to generator
JavaScript
mit
sysgarage/generator-sys-angular,sysgarage/generator-sys-angular
--- +++ @@ -10,7 +10,7 @@ function pathToModule(dir, entered) { var moduleName = _.camelCase(path.basename(dir)); - var moduleFilename = moduleName + '.module.js'; + var moduleFilename = path.basename(dir) + '.module.js'; var moduleFilePath = path.resolve(dir, moduleFilename); var prefix; try {
bef736ad7309b7a1e60b8d9935e546aced0c2531
addons/options/src/preview/index.js
addons/options/src/preview/index.js
import addons from '@storybook/addons'; import { EVENT_ID } from '../shared'; // init function will be executed once when the storybook loads for the // first time. This is a good place to add global listeners on channel. export function init() { // NOTE nothing to do here } function regExpStringify(exp) { if (typeof exp === 'string') return exp; if (Object.prototype.toString.call(exp) === '[object RegExp]') return exp.source; return null; } // setOptions function will send Storybook UI options when the channel is // ready. If called before, options will be cached until it can be sent. export function setOptions(newOptions) { const channel = addons.getChannel(); if (!channel) { throw new Error( 'Failed to find addon channel. This may be due to https://github.com/storybooks/storybook/issues/1192.' ); } const options = { ...newOptions, hierarchySeparator: regExpStringify(newOptions.hierarchySeparator), }; channel.emit(EVENT_ID, { options }); }
import addons from '@storybook/addons'; import { EVENT_ID } from '../shared'; // init function will be executed once when the storybook loads for the // first time. This is a good place to add global listeners on channel. export function init() { // NOTE nothing to do here } function regExpStringify(exp) { if (typeof exp === 'string') return exp; if (Object.prototype.toString.call(exp) === '[object RegExp]') return exp.source; return null; } // setOptions function will send Storybook UI options when the channel is // ready. If called before, options will be cached until it can be sent. export function setOptions(newOptions) { const channel = addons.getChannel(); if (!channel) { throw new Error( 'Failed to find addon channel. This may be due to https://github.com/storybooks/storybook/issues/1192.' ); } let options = newOptions; // since 'undefined' and 'null' are the valid values we don't want to // override the hierarchySeparator if the prop is missing if (Object.prototype.hasOwnProperty.call(newOptions, 'hierarchySeparator')) { options = { ...newOptions, hierarchySeparator: regExpStringify(newOptions.hierarchySeparator), }; } channel.emit(EVENT_ID, { options }); }
Check if hierarchySeparator presents in the options object
Check if hierarchySeparator presents in the options object
JavaScript
mit
storybooks/storybook,kadirahq/react-storybook,rhalff/storybook,storybooks/react-storybook,rhalff/storybook,rhalff/storybook,rhalff/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,rhalff/storybook,rhalff/storybook,storybooks/react-storybook
--- +++ @@ -22,10 +22,17 @@ 'Failed to find addon channel. This may be due to https://github.com/storybooks/storybook/issues/1192.' ); } - const options = { - ...newOptions, - hierarchySeparator: regExpStringify(newOptions.hierarchySeparator), - }; + + let options = newOptions; + + // since 'undefined' and 'null' are the valid values we don't want to + // override the hierarchySeparator if the prop is missing + if (Object.prototype.hasOwnProperty.call(newOptions, 'hierarchySeparator')) { + options = { + ...newOptions, + hierarchySeparator: regExpStringify(newOptions.hierarchySeparator), + }; + } channel.emit(EVENT_ID, { options }); }
5184b5963cd48452546d6ff1e0df518cd8473cdf
src/base/baseTool.js
src/base/baseTool.js
export default class { constructor (name) { this.name = name; this.mode = 'disabled'; this.element = undefined; // this.data = {}; this._options = {}; this._configuration = {}; } get configuration () { return this._configuration; } set configuration (configuration) { this._configuration = configuration; } // ToolOptions.js get options () { return this._options; } set options (options) { this._options = options; } clearOptions () { this._options = {}; } }
export default class { constructor (name, strategies, defaultStrategy) { this.name = name; this.mode = 'disabled'; this.element = undefined; // Todo: should this live in baseTool? this.strategies = strategies || {}; this.defaultStrategy = defaultStrategy || Object.keys(this.strategies)[0] || undefined; this.activeStrategy = this.defaultStrategy; // this.data = {}; this._options = {}; this._configuration = {}; } get configuration () { return this._configuration; } set configuration (configuration) { this._configuration = configuration; } // ToolOptions.js get options () { return this._options; } set options (options) { this._options = options; } clearOptions () { this._options = {}; } /** * * * @param {*} evt * @returns Any */ applyActiveStrategy (evt) { return this.strategies[this.activeStrategy](evt); } }
Add a consistent way to set and apply strategies for tools
Add a consistent way to set and apply strategies for tools
JavaScript
mit
chafey/cornerstoneTools,cornerstonejs/cornerstoneTools,cornerstonejs/cornerstoneTools,cornerstonejs/cornerstoneTools
--- +++ @@ -1,8 +1,14 @@ export default class { - constructor (name) { + constructor (name, strategies, defaultStrategy) { this.name = name; this.mode = 'disabled'; this.element = undefined; + + // Todo: should this live in baseTool? + this.strategies = strategies || {}; + this.defaultStrategy = + defaultStrategy || Object.keys(this.strategies)[0] || undefined; + this.activeStrategy = this.defaultStrategy; // this.data = {}; @@ -30,4 +36,14 @@ clearOptions () { this._options = {}; } + + /** + * + * + * @param {*} evt + * @returns Any + */ + applyActiveStrategy (evt) { + return this.strategies[this.activeStrategy](evt); + } }
1b96576cea9138cb95e332a1d12e3a1e1887be56
app/components/students/students.js
app/components/students/students.js
'use strict'; angular.module('myApp.students', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/students', { templateUrl: 'components/students/students.html', controller: 'StudentsCtrl' }); }]) .controller('StudentsCtrl', [function() { // $scope.master = {}; // $scope.update = function(user) { // $scope.master = angular.copy(user); // }; // $scope.reset = function() { // $scope.user = angular.copy($scope.master); // }; // $scope.reset(); }]);
'use strict'; angular.module('myApp.students', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/students', { templateUrl: 'components/students/students.html', controller: 'StudentsCtrl' }); }]) .controller('StudentsCtrl', ['$scope', function($scope) { $scope.master = {}; $scope.update = function(user) { $scope.master = angular.copy(user); }; $scope.reset = function() { $scope.user = angular.copy($scope.master); }; $scope.reset(); }]);
Make the buttons do stuff
Make the buttons do stuff
JavaScript
mit
andrewalexander/hackpsu_registration,andrewalexander/hackpsu_registration,andrewalexander/hackpsu_registration,andrewalexander/hackpsu_registration
--- +++ @@ -9,16 +9,16 @@ }); }]) -.controller('StudentsCtrl', [function() { - // $scope.master = {}; +.controller('StudentsCtrl', ['$scope', function($scope) { + $scope.master = {}; - // $scope.update = function(user) { - // $scope.master = angular.copy(user); - // }; + $scope.update = function(user) { + $scope.master = angular.copy(user); + }; - // $scope.reset = function() { - // $scope.user = angular.copy($scope.master); - // }; + $scope.reset = function() { + $scope.user = angular.copy($scope.master); + }; - // $scope.reset(); + $scope.reset(); }]);
a9ee91d3920d0fa876bd16f5e51a7bad2f29f818
app/native.js
app/native.js
// @flow import CodePush from 'react-native-code-push'; import { AppRegistry, YellowBox } from 'react-native'; import { SingleHotelStandalonePackage, NewHotelsStandAlonePackage, } from '@kiwicom/react-native-app-hotels'; // TODO: please check if it's still needed YellowBox.ignoreWarnings([ // react-native-share warnings. Should be gone with the version 1.1.3 'Class GenericShare was not exported. Did you forget to use RCT_EXPORT_MODULE()', 'Class WhatsAppShare was not exported. Did you forget to use RCT_EXPORT_MODULE()', 'Class GooglePlusShare was not exported. Did you forget to use RCT_EXPORT_MODULE()', 'Class InstagramShare was not exported. Did you forget to use RCT_EXPORT_MODULE()', ]); // Hotels AppRegistry.registerComponent( 'NewKiwiHotels', () => NewHotelsStandAlonePackage, ); AppRegistry.registerComponent( 'SingleHotel', () => SingleHotelStandalonePackage, ); // This file is only used for native integration and we use CodePush there CodePush.sync();
// @flow import CodePush from 'react-native-code-push'; import { AppRegistry, YellowBox } from 'react-native'; import { SingleHotelStandalonePackage, NewHotelsStandAlonePackage, } from '@kiwicom/react-native-app-hotels'; // TODO: please check if it's still needed YellowBox.ignoreWarnings([ // react-native-share warnings. Should be gone with the version 1.1.3 'Class GenericShare was not exported. Did you forget to use RCT_EXPORT_MODULE()', 'Class WhatsAppShare was not exported. Did you forget to use RCT_EXPORT_MODULE()', 'Class GooglePlusShare was not exported. Did you forget to use RCT_EXPORT_MODULE()', 'Class InstagramShare was not exported. Did you forget to use RCT_EXPORT_MODULE()', ]); // Hotels AppRegistry.registerComponent( 'NewKiwiHotels', () => NewHotelsStandAlonePackage, ); AppRegistry.registerComponent( 'SingleHotel', () => SingleHotelStandalonePackage, ); // This file is only used for native integration and we use CodePush there CodePush.sync({ installMode: CodePush.InstallMode.IMMEDIATE, });
Set code push install mode to immediate
Set code push install mode to immediate
JavaScript
mit
mrtnzlml/native,mrtnzlml/native
--- +++ @@ -27,4 +27,6 @@ ); // This file is only used for native integration and we use CodePush there -CodePush.sync(); +CodePush.sync({ + installMode: CodePush.InstallMode.IMMEDIATE, +});
d27ae97ff6e764ac9e40c4b03b91eab8a30d32cc
web/.eslintrc.js
web/.eslintrc.js
// https://eslint.org/docs/user-guide/configuring module.exports = { root: true, parserOptions: { parser: "babel-eslint", sourceType: "module" }, env: { browser: true }, // required to lint *.vue files plugins: ["vue"], extends: ["plugin:vue/recommended", "airbnb-base"], // check if imports actually resolve settings: { "import/resolver": { webpack: { config: "build/webpack.base.conf.js" } } }, // add your custom rules here rules: { // don't require .vue extension when importing "import/extensions": [ "error", "always", { js: "never", vue: "never" } ], // disallow reassignment of function parameters // disallow parameter object manipulation except for specific exclusions "no-param-reassign": [ "error", { props: true, ignorePropertyModificationsFor: [ "state", // for vuex state "acc", // for reduce accumulators "e" // for e.returnvalue ] } ], // allow optionalDependencies "import/no-extraneous-dependencies": [ "error", { optionalDependencies: ["test/unit/index.js"] } ], // allow debugger during development "no-debugger": process.env.NODE_ENV === "production" ? "error" : "off", "linebreak-style": ["error", "windows"] } };
// https://eslint.org/docs/user-guide/configuring module.exports = { root: true, parserOptions: { parser: "babel-eslint", sourceType: "module" }, env: { browser: true }, // required to lint *.vue files plugins: ["vue"], extends: ["plugin:vue/recommended", "airbnb-base"], // check if imports actually resolve settings: { "import/resolver": { webpack: { config: "build/webpack.base.conf.js" } } }, // add your custom rules here rules: { // don't require .vue extension when importing "import/extensions": [ "error", "always", { js: "never", vue: "never" } ], // disallow reassignment of function parameters // disallow parameter object manipulation except for specific exclusions "no-param-reassign": [ "error", { props: true, ignorePropertyModificationsFor: [ "state", // for vuex state "acc", // for reduce accumulators "e" // for e.returnvalue ] } ], "no-plusplus": [ "error", { "allowForLoopAfterthoughts": true } ], // allow optionalDependencies "import/no-extraneous-dependencies": [ "error", { optionalDependencies: ["test/unit/index.js"] } ], // allow debugger during development "no-debugger": process.env.NODE_ENV === "production" ? "error" : "off", "linebreak-style": ["error", "windows"] } };
Disable i++ error in loops
Disable i++ error in loops
JavaScript
mit
homoluden/fukami,homoluden/fukami,homoluden/fukami
--- +++ @@ -44,6 +44,12 @@ ] } ], + "no-plusplus": [ + "error", + { + "allowForLoopAfterthoughts": true + } + ], // allow optionalDependencies "import/no-extraneous-dependencies": [ "error",
dd123262b95f39224b7851ceaaf785399c9de0c0
implementation.js
implementation.js
'use strict'; var bind = require('function-bind'); var ES = require('es-abstract/es7'); var slice = bind.call(Function.call, String.prototype.slice); module.exports = function padLeft(maxLength) { var O = ES.RequireObjectCoercible(this); var S = ES.ToString(O); var stringLength = ES.ToLength(S.length); var fillString; if (arguments.length > 1) { fillString = arguments[1]; } var F = typeof fillString === 'undefined' ? '' : ES.ToString(fillString); if (F === '') { F = ' '; } var intMaxLength = ES.ToLength(maxLength); if (intMaxLength <= stringLength) { return S; } var fillLen = intMaxLength - stringLength; while (F.length < fillLen) { F += F; } var truncatedStringFiller = F.length > fillLen ? slice(F, 0, fillLen) : F; return truncatedStringFiller + S; };
'use strict'; var bind = require('function-bind'); var ES = require('es-abstract/es7'); var slice = bind.call(Function.call, String.prototype.slice); module.exports = function padLeft(maxLength) { var O = ES.RequireObjectCoercible(this); var S = ES.ToString(O); var stringLength = ES.ToLength(S.length); var fillString; if (arguments.length > 1) { fillString = arguments[1]; } var F = typeof fillString === 'undefined' ? '' : ES.ToString(fillString); if (F === '') { F = ' '; } var intMaxLength = ES.ToLength(maxLength); if (intMaxLength <= stringLength) { return S; } var fillLen = intMaxLength - stringLength; while (F.length < fillLen) { var fLen = F.length; var remainingCodeUnits = fillLen - fLen; F += fLen > remainingCodeUnits ? slice(F, 0, remainingCodeUnits) : F; } var truncatedStringFiller = F.length > fillLen ? slice(F, 0, fillLen) : F; return truncatedStringFiller + S; };
Update concatenation algorithm to prevent strings larger than the max length
Update concatenation algorithm to prevent strings larger than the max length From https://github.com/ljharb/proposal-string-pad-left-right/commit/7b6261b9a23cbc00daf0b232c1b40243adcce7d8
JavaScript
mit
ljharb/String.prototype.padLeft,ljharb/String.prototype.padStart,es-shims/String.prototype.padStart,es-shims/String.prototype.padLeft
--- +++ @@ -22,7 +22,9 @@ } var fillLen = intMaxLength - stringLength; while (F.length < fillLen) { - F += F; + var fLen = F.length; + var remainingCodeUnits = fillLen - fLen; + F += fLen > remainingCodeUnits ? slice(F, 0, remainingCodeUnits) : F; } var truncatedStringFiller = F.length > fillLen ? slice(F, 0, fillLen) : F;
2fa060f4dd23a5074b788330c1a8464f79bdadef
routes/edit/screens/App/screens/Project/components/CodeEditor.js
routes/edit/screens/App/screens/Project/components/CodeEditor.js
import React, { Component } from 'react'; import AceEditor from 'react-ace'; import githubTheme from 'brace/theme/github'; import markdownSyntax from 'brace/mode/markdown'; import styles from './CodeEditor.styl'; export default ({ file, onCodeChange, onSave }) => { if (!file) return <div />; const onLoad = (editor) => { editor.commands.addCommand({ name: 'saveChanges', bindKey: {win: 'Ctrl-Enter', mac: 'Ctrl-Enter|Command-Enter'}, exec: onSave }); } return ( <AceEditor mode='markdown' theme='github' name='aceEditor' value={file.content} className={styles.aceEditor} showPrintMargin={false} editorProps={{$blockScrolling: Infinity}} onLoad={onLoad} onChange={onCodeChange} /> ) }
import React, { Component } from 'react'; import AceEditor from 'react-ace'; import githubTheme from 'brace/theme/github'; import markdownSyntax from 'brace/mode/markdown'; import styles from './CodeEditor.styl'; export default ({ file, onCodeChange, onSave }) => { if (!file) return <div />; const onLoad = (editor) => { editor.commands.addCommand({ name: 'saveChanges', bindKey: { win: 'Ctrl-Enter|Ctrl-S', mac: 'Ctrl-Enter|Command-Enter|Command-S' }, exec: onSave }); } return ( <AceEditor mode='markdown' theme='github' name='aceEditor' value={file.content} className={styles.aceEditor} showPrintMargin={false} editorProps={{$blockScrolling: Infinity}} onLoad={onLoad} onChange={onCodeChange} /> ) }
Add support for save on Ctrl/Cmd+S
Add support for save on Ctrl/Cmd+S
JavaScript
mit
Literasee/literasee,Literasee/literasee
--- +++ @@ -11,7 +11,10 @@ const onLoad = (editor) => { editor.commands.addCommand({ name: 'saveChanges', - bindKey: {win: 'Ctrl-Enter', mac: 'Ctrl-Enter|Command-Enter'}, + bindKey: { + win: 'Ctrl-Enter|Ctrl-S', + mac: 'Ctrl-Enter|Command-Enter|Command-S' + }, exec: onSave }); }
ec5f0a6ded1d50773cda52d32f22238bcb019d56
src/app/main/main.controller.js
src/app/main/main.controller.js
(function() { 'use strict'; angular .module('annualTimeBlock') .controller('MainController', MainController); /** @ngInject */ function MainController($timeout, webDevTec, toastr) { var vm = this; vm.awesomeThings = []; vm.classAnimation = ''; vm.creationDate = 1456885185987; vm.showToastr = showToastr; activate(); function activate() { getWebDevTec(); $timeout(function() { vm.classAnimation = 'rubberBand'; }, 4000); } function showToastr() { toastr.info('Fork <a href="https://github.com/Swiip/generator-gulp-angular" target="_blank"><b>generator-gulp-angular</b></a>'); vm.classAnimation = ''; } function getWebDevTec() { vm.awesomeThings = webDevTec.getTec(); angular.forEach(vm.awesomeThings, function(awesomeThing) { awesomeThing.rank = Math.random(); }); } } })();
(function() { 'use strict'; angular .module('annualTimeBlock') .controller('MainController', MainController); /** @ngInject */ function MainController() { var vm = this; } })();
Clear out unneeded MainController stuff
Clear out unneeded MainController stuff
JavaScript
mit
EdwardHinkle/annualTimeBlock,EdwardHinkle/annualTimeBlock
--- +++ @@ -6,34 +6,9 @@ .controller('MainController', MainController); /** @ngInject */ - function MainController($timeout, webDevTec, toastr) { + function MainController() { var vm = this; - vm.awesomeThings = []; - vm.classAnimation = ''; - vm.creationDate = 1456885185987; - vm.showToastr = showToastr; - activate(); - - function activate() { - getWebDevTec(); - $timeout(function() { - vm.classAnimation = 'rubberBand'; - }, 4000); - } - - function showToastr() { - toastr.info('Fork <a href="https://github.com/Swiip/generator-gulp-angular" target="_blank"><b>generator-gulp-angular</b></a>'); - vm.classAnimation = ''; - } - - function getWebDevTec() { - vm.awesomeThings = webDevTec.getTec(); - - angular.forEach(vm.awesomeThings, function(awesomeThing) { - awesomeThing.rank = Math.random(); - }); - } } })();
48c22bda06a7f6ea3592c942db50d7a4236f8605
LesionTracker/client/components/viewerMain/viewerMain.js
LesionTracker/client/components/viewerMain/viewerMain.js
Template.viewerMain.helpers({ 'toolbarOptions': function() { var toolbarOptions = {}; var buttonData = []; buttonData.push({ id: 'resetViewport', title: 'Reset Viewport', classes: 'imageViewerCommand', iconClasses: 'fa fa-undo' }); buttonData.push({ id: 'wwwc', title: 'WW/WC', classes: 'imageViewerTool', iconClasses: 'fa fa-sun-o' }); buttonData.push({ id: 'zoom', title: 'Zoom', classes: 'imageViewerTool', iconClasses: 'fa fa-search' }); buttonData.push({ id: 'pan', title: 'Pan', classes: 'imageViewerTool', iconClasses: 'fa fa-arrows' }); buttonData.push({ id: 'stackScroll', title: 'Stack Scroll', classes: 'imageViewerTool', iconClasses: 'fa fa-bars' }); buttonData.push({ id: 'length', title: 'Length Measurement', classes: 'imageViewerTool', iconClasses: 'fa fa-arrows-v' }); buttonData.push({ id: 'lesion', title: 'Lesion Tool', classes: 'imageViewerTool', iconClasses: 'fa fa-arrows-alt' }); buttonData.push({ id: 'nonTarget', title: 'Non-Target Tool', classes: 'imageViewerTool', iconClasses: 'fa fa-arrows-v' }); toolbarOptions.buttonData = buttonData; toolbarOptions.includePlayClipButton = false; toolbarOptions.includeLayoutButton = false; return toolbarOptions; } });
Template.viewerMain.helpers({ 'toolbarOptions': function() { var toolbarOptions = {}; var buttonData = []; buttonData.push({ id: 'resetViewport', title: 'Reset Viewport', classes: 'imageViewerCommand', iconClasses: 'fa fa-undo' }); buttonData.push({ id: 'wwwc', title: 'WW/WC', classes: 'imageViewerTool', iconClasses: 'fa fa-sun-o' }); buttonData.push({ id: 'zoom', title: 'Zoom', classes: 'imageViewerTool', iconClasses: 'fa fa-search' }); buttonData.push({ id: 'pan', title: 'Pan', classes: 'imageViewerTool', iconClasses: 'fa fa-arrows' }); buttonData.push({ id: 'stackScroll', title: 'Stack Scroll', classes: 'imageViewerTool', iconClasses: 'fa fa-bars' }); buttonData.push({ id: 'lesion', title: 'Target Tool', classes: 'imageViewerTool', iconClasses: 'fa fa-arrows-alt' }); buttonData.push({ id: 'nonTarget', title: 'Non-Target Tool', classes: 'imageViewerTool', iconClasses: 'fa fa-long-arrow-up' }); toolbarOptions.buttonData = buttonData; toolbarOptions.includePlayClipButton = false; toolbarOptions.includeLayoutButton = false; return toolbarOptions; } });
Change icon for non-target tool and remove length tool
Change icon for non-target tool and remove length tool
JavaScript
mit
OHIF/Viewers,HorizonPlatform/Viewers,HorizonPlatform/Viewers,HorizonPlatform/Viewers,OHIF/Viewers,HorizonPlatform/Viewers,OHIF/Viewers
--- +++ @@ -40,15 +40,8 @@ }); buttonData.push({ - id: 'length', - title: 'Length Measurement', - classes: 'imageViewerTool', - iconClasses: 'fa fa-arrows-v' - }); - - buttonData.push({ id: 'lesion', - title: 'Lesion Tool', + title: 'Target Tool', classes: 'imageViewerTool', iconClasses: 'fa fa-arrows-alt' }); @@ -57,7 +50,7 @@ id: 'nonTarget', title: 'Non-Target Tool', classes: 'imageViewerTool', - iconClasses: 'fa fa-arrows-v' + iconClasses: 'fa fa-long-arrow-up' }); toolbarOptions.buttonData = buttonData;
4d472a8c41acd461f1f75b9c0d9d8c65cfd4c4eb
client/tests/end2end/test-custodian-first-login.js
client/tests/end2end/test-custodian-first-login.js
var utils = require('./utils.js'); var temporary_password = "typ0drome@absurd.org"; describe('receiver first login', function() { it('should redirect to /firstlogin upon successful authentication', function() { utils.login_custodian('Custodian1', utils.vars['default_password'], '/#/custodian', true); }); it('should be able to change password from the default one', function() { element(by.model('preferences.old_password')).sendKeys(utils.vars['default_password']); element(by.model('preferences.password')).sendKeys(temporary_password); element(by.model('preferences.check_password')).sendKeys(temporary_password); element(by.css('[data-ng-click="pass_save()"]')).click(); utils.waitForUrl('/custodian/identityaccessrequests'); }); it('should be able to login with the new password', function() { utils.login_custodian('Custodian1', temporary_password, '/#/custodian', false); }); it('should be able to change password accessing the user preferences', function() { element(by.cssContainingText("a", "Password configuration")).click(); element(by.model('preferences.old_password')).sendKeys(temporary_password); element(by.model('preferences.password')).sendKeys(utils.vars['user_password']); element(by.model('preferences.check_password')).sendKeys(utils.vars['user_password']); element(by.css('[data-ng-click="pass_save()"]')).click(); }); });
var utils = require('./utils.js'); var temporary_password = "typ0drome@absurd.org"; describe('receiver first login', function() { it('should redirect to /firstlogin upon successful authentication', function() { utils.login_custodian('Custodian1', utils.vars['default_password'], '/#/custodian', true); }); it('should be able to change password from the default one', function() { element(by.model('preferences.old_password')).sendKeys(utils.vars['default_password']); element(by.model('preferences.password')).sendKeys(temporary_password); element(by.model('preferences.check_password')).sendKeys(temporary_password); element(by.css('[data-ng-click="pass_save()"]')).click(); utils.waitForUrl('/custodian/identityaccessrequests'); }); it('should be able to login with the new password', function() { utils.login_custodian('Custodian1', temporary_password, '/#/custodian', false); }); it('should be able to change password accessing the user preferences', function() { element(by.cssContainingText("a", "Preferences")).click(); element(by.cssContainingText("a", "Password configuration")).click(); element(by.model('preferences.old_password')).sendKeys(temporary_password); element(by.model('preferences.password')).sendKeys(utils.vars['user_password']); element(by.model('preferences.check_password')).sendKeys(utils.vars['user_password']); element(by.css('[data-ng-click="pass_save()"]')).click(); }); });
Fix test of admin/custodian password change
Fix test of admin/custodian password change
JavaScript
agpl-3.0
vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks
--- +++ @@ -20,6 +20,7 @@ }); it('should be able to change password accessing the user preferences', function() { + element(by.cssContainingText("a", "Preferences")).click(); element(by.cssContainingText("a", "Password configuration")).click(); element(by.model('preferences.old_password')).sendKeys(temporary_password); element(by.model('preferences.password')).sendKeys(utils.vars['user_password']);
5684a7a2746bce64504d3ee598c9403315d3211e
js/application.js
js/application.js
$(document).ready(function(){ $(".metronome-parameters").on("submit", function(event){ event.preventDefault(); var tempo = $("#tempo-field").val(); var beatsPerMeasure = $("#beats-field").val(); metronome = new Metronome(tempo, beatsPerMeasure); metronome.start(); }); })
$(document).ready(function(){ $(".metronome-parameters").on("submit", function(event){ event.preventDefault(); if ($('#metronome-button').val() === "Start"){ var tempo = $("#tempo-field").val(); var beatsPerMeasure = $("#beats-field").val(); metronome = new Metronome(tempo, beatsPerMeasure); metronome.start(); } else { metronome.stop(); } }); })
Change submit event listener to start or stop
Change submit event listener to start or stop
JavaScript
mit
dmilburn/beatrice,dmilburn/beatrice
--- +++ @@ -2,9 +2,14 @@ $(".metronome-parameters").on("submit", function(event){ event.preventDefault(); - var tempo = $("#tempo-field").val(); - var beatsPerMeasure = $("#beats-field").val(); - metronome = new Metronome(tempo, beatsPerMeasure); - metronome.start(); + if ($('#metronome-button').val() === "Start"){ + var tempo = $("#tempo-field").val(); + var beatsPerMeasure = $("#beats-field").val(); + metronome = new Metronome(tempo, beatsPerMeasure); + metronome.start(); + } else { + metronome.stop(); + } + }); })
552a0ff648af26ec23415abb24de858bb229e92e
src/components/Auth.js
src/components/Auth.js
import React from "react"; import { connect } from "react-redux"; import { push } from "react-router-redux"; import { parse } from "qs"; import { downloadJournal } from "../actionCreators"; class Auth extends React.Component { componentWillMount() { const accessToken = parse(this.props.location.hash.slice(1)).access_token; // TODO: Convert to action creator this.props.dispatch({ type: "SET_AUTH_TOKEN", token: accessToken }); this.props.dispatch(downloadJournal()); // TODO: Get desired URL from URL or some such thing this.props.dispatch(push("/")); } render() { return null; } } export default connect(null)(Auth);
import React from "react"; import { connect } from "react-redux"; import { push } from "react-router-redux"; import { parse } from "qs"; import { downloadJournal } from "../actionCreators"; const getHash = () => this.props.location.hash.slice(1); const getAccessTokenFromHash = () => parse(getHash()).access_token; class Auth extends React.Component { componentWillMount() { const accessToken = getAccessTokenFromHash(); // TODO: Convert to action creator this.props.dispatch({ type: "SET_AUTH_TOKEN", token: accessToken }); this.props.dispatch(downloadJournal()); // TODO: Get desired URL from URL or some such thing this.props.dispatch(push("/")); } render() { return null; } } export default connect(null)(Auth);
Split out logic to improve readability
Split out logic to improve readability
JavaScript
mit
captbaritone/markdown.today,captbaritone/markdown.today,captbaritone/markdown.today
--- +++ @@ -4,9 +4,12 @@ import { parse } from "qs"; import { downloadJournal } from "../actionCreators"; +const getHash = () => this.props.location.hash.slice(1); +const getAccessTokenFromHash = () => parse(getHash()).access_token; + class Auth extends React.Component { componentWillMount() { - const accessToken = parse(this.props.location.hash.slice(1)).access_token; + const accessToken = getAccessTokenFromHash(); // TODO: Convert to action creator this.props.dispatch({ type: "SET_AUTH_TOKEN", token: accessToken }); this.props.dispatch(downloadJournal());
4dc0b40c4a6f54952cf7bfaa0492872539b88d40
src/controller.spec.js
src/controller.spec.js
import { ControllerProvider } from './controller'; const testModuleName = 'hot-reload-demo'; fdescribe('ControllerProvider', () => { describe('creating a controller through the provider', () => { var ctrl; beforeEach(function() { new ControllerProvider(testModuleName) .register('UnitTestCtrl', class TestCtrl { constructor() { this.testCtrlName = 'UnitTestCtrl'; } }); }); beforeEach(angular.mock.module(testModuleName)); beforeEach(inject(function($controller, $rootScope) { ctrl = $controller('UnitTestCtrl', { $scope: $rootScope.$new() }); })); it('should have been initialized correctly', function() { expect(ctrl).toBeDefined(); expect(ctrl && ctrl.testCtrlName).toBe('UnitTestCtrl'); }); }); });
import { ControllerProvider } from './controller'; const testModuleName = 'hot-reload-demo'; describe('ControllerProvider', () => { describe('creating a controller through the provider', () => { const testCtrlName = 'UnitTestController', someValue = {}; // Some value to provide for the controller var $controller, $rootScope; beforeEach(function() { // Register a simple controller to test new ControllerProvider(testModuleName) .register(testCtrlName, class TestCtrl { constructor() { this.testCtrlName = testCtrlName; } }); // Register a controller with local bindings new ControllerProvider(testModuleName) .register(testCtrlName + 'WithLocalValue', class TestCtrl { constructor(someValue) { this.someValue = someValue; } }); }); beforeEach(angular.mock.module(testModuleName)); beforeEach(inject(function(_$controller_, _$rootScope_) { $controller = _$controller_; $rootScope = _$rootScope_; })); it('should initialize simple controller correctly', function() { var ctrl = $controller(testCtrlName, { $scope: $rootScope.$new(), }); expect(ctrl && ctrl.testCtrlName).toBe(testCtrlName); }); it('should initialize controller with locals correctly', function() { var ctrl = $controller(testCtrlName + 'WithLocalValue', { $scope: $rootScope.$new(), someValue, }); expect(ctrl.someValue).toBe(someValue); }); }); });
Add a failing test for the ControllerProvider
Add a failing test for the ControllerProvider
JavaScript
mit
noppa/ng-hot-reload,noppa/ng-hot-reload,noppa/ng-hot-reload
--- +++ @@ -2,30 +2,51 @@ const testModuleName = 'hot-reload-demo'; -fdescribe('ControllerProvider', () => { +describe('ControllerProvider', () => { describe('creating a controller through the provider', () => { - var ctrl; + const testCtrlName = 'UnitTestController', + someValue = {}; // Some value to provide for the controller + + var $controller, $rootScope; beforeEach(function() { + // Register a simple controller to test new ControllerProvider(testModuleName) - .register('UnitTestCtrl', class TestCtrl { + .register(testCtrlName, class TestCtrl { + constructor() { + this.testCtrlName = testCtrlName; + } + }); - constructor() { - this.testCtrlName = 'UnitTestCtrl'; + // Register a controller with local bindings + new ControllerProvider(testModuleName) + .register(testCtrlName + 'WithLocalValue', class TestCtrl { + constructor(someValue) { + this.someValue = someValue; } - }); }); beforeEach(angular.mock.module(testModuleName)); - beforeEach(inject(function($controller, $rootScope) { - ctrl = $controller('UnitTestCtrl', { $scope: $rootScope.$new() }); + beforeEach(inject(function(_$controller_, _$rootScope_) { + $controller = _$controller_; + $rootScope = _$rootScope_; })); - it('should have been initialized correctly', function() { - expect(ctrl).toBeDefined(); - expect(ctrl && ctrl.testCtrlName).toBe('UnitTestCtrl'); + it('should initialize simple controller correctly', function() { + var ctrl = $controller(testCtrlName, { + $scope: $rootScope.$new(), + }); + expect(ctrl && ctrl.testCtrlName).toBe(testCtrlName); + }); + + it('should initialize controller with locals correctly', function() { + var ctrl = $controller(testCtrlName + 'WithLocalValue', { + $scope: $rootScope.$new(), + someValue, + }); + expect(ctrl.someValue).toBe(someValue); }); }); });
1ec3d3a1c7b8b664c7d5a0455e23e4185eb3bf23
lib/node-expat.js
lib/node-expat.js
var EventEmitter = require('events').EventEmitter; var util = require('util'); var expat = require('../build/default/node-expat'); /** * Simple wrapper because EventEmitter has turned pure-JS as of node * 0.5.x. */ exports.Parser = function(encoding) { this.parser = new expat.Parser(encoding); var that = this; this.parser.emit = function() { that.emit.apply(that, arguments); }; }; util.inherits(exports.Parser, EventEmitter); exports.Parser.prototype.parse = function(buf, isFinal) { return this.parser.parse(buf, isFinal); }; exports.Parser.prototype.setEncoding = function(encoding) { return this.parser.setEncoding(encoding); }; exports.Parser.prototype.getError = function() { return this.parser.getError(); }; exports.Parser.prototype.stop = function() { return this.parser.stop(); }; exports.Parser.prototype.pause = function() { return this.stop(); }; exports.Parser.prototype.resume = function() { return this.parser.resume(); };
var EventEmitter = require('events').EventEmitter; var util = require('util'); var expat = require('../build/Release/node-expat'); /** * Simple wrapper because EventEmitter has turned pure-JS as of node * 0.5.x. */ exports.Parser = function(encoding) { this.parser = new expat.Parser(encoding); var that = this; this.parser.emit = function() { that.emit.apply(that, arguments); }; }; util.inherits(exports.Parser, EventEmitter); exports.Parser.prototype.parse = function(buf, isFinal) { return this.parser.parse(buf, isFinal); }; exports.Parser.prototype.setEncoding = function(encoding) { return this.parser.setEncoding(encoding); }; exports.Parser.prototype.getError = function() { return this.parser.getError(); }; exports.Parser.prototype.stop = function() { return this.parser.stop(); }; exports.Parser.prototype.pause = function() { return this.stop(); }; exports.Parser.prototype.resume = function() { return this.parser.resume(); };
Fix for Node.js 0.6.0: Build seems to be now in Release instead of default
Fix for Node.js 0.6.0: Build seems to be now in Release instead of default
JavaScript
mit
node-xmpp/node-expat,Moharu/node-expat,noahjs/node-expat,Moharu/node-expat,noahjs/node-expat,julianduque/node-expat,noahjs/node-expat,node-xmpp/node-expat,julianduque/node-expat,node-xmpp/node-expat,julianduque/node-expat,Moharu/node-expat
--- +++ @@ -1,6 +1,6 @@ var EventEmitter = require('events').EventEmitter; var util = require('util'); -var expat = require('../build/default/node-expat'); +var expat = require('../build/Release/node-expat'); /** * Simple wrapper because EventEmitter has turned pure-JS as of node
2d5bd5583ed75904284b32b7ba4ff3294267315e
scripts/single-page.js
scripts/single-page.js
$(document).on('ready', function() { $('nav a').on('click', function(event) { event.preventDefault(); var targetURI = event.target.dataset.pagePartial; $.ajax({ cache: false, url: targetURI }).done(function(response) { $('main').html(response); }); }); $('a.blog-link').on('click', function(event) { event.preventDefault(); console.log("I'm a blog link!"); }); });
$(document).on('ready', function() { $('nav a').on('click', function(event) { event.preventDefault(); var targetURI = event.target.dataset.pagePartial; $.ajax({ cache: false, url: targetURI }).done(function(response) { $('main').html(response); }); }); $('a.blog-link').on('click', function(event) { event.preventDefault(); var targetURI = event.target.dataset.pagePartial; console.log("I'm a blog link!", targetURI); $.ajax({ cache: false, url: targetURI }).done(function(response) { console.log('success!', response); }).fail(function(response) { console.log('failure?', response); }); }); });
Update blog link click event to make ajax request
Update blog link click event to make ajax request
JavaScript
mit
RoyTuesday/RoyTuesday.github.io,peternatewood/peternatewood.github.io,peternatewood/peternatewood.github.io,peternatewood/peternatewood.github.io,RoyTuesday/RoyTuesday.github.io
--- +++ @@ -13,7 +13,16 @@ $('a.blog-link').on('click', function(event) { event.preventDefault(); - console.log("I'm a blog link!"); + var targetURI = event.target.dataset.pagePartial; + console.log("I'm a blog link!", targetURI); + $.ajax({ + cache: false, + url: targetURI + }).done(function(response) { + console.log('success!', response); + }).fail(function(response) { + console.log('failure?', response); + }); }); });
fb67dd5793ba6163e66f325fa3adcb12c4fc8038
gulpfile.js
gulpfile.js
var stexDev = require("stex-dev"); var gulp = stexDev.gulp(); var plugins = stexDev.gulpPlugins(); var paths = stexDev.paths; // composite gulp tasks gulp.task('default', ['test']); gulp.task('dist', ['']); gulp.task('test', ['lint', 'mocha']); // gulp.task('db:setup', ['db:ensure-created', 'db:migrate']); // end composite tasks // you can find individual gulp tasks in ./node_modules/stex-dev/lib/gulp.js // // expose the app globals to other tasks // gulp.task('app', function(next) { // var stex = require("./lib/app"); // stex.activate(); // next(); // }); // gulp.task('db:ensure-created', ['app'], function() { // var Knex = require("knex"); // var dbConfig = conf.get("db"); // var dbToCreate = dbConfig.connection.database; // // create a connection to the db without specifying the db // delete dbConfig.connection.database; // var db = Knex.initialize(dbConfig); // return db.raw("CREATE DATABASE IF NOT EXISTS `" + dbToCreate + "`") // .then(function() { /* noop */ }) // .finally(function(){ // db.client.pool.destroy(); // }); // }); // gulp.task('db:migrate', function(next) { // var spawn = require('child_process').spawn; // var proc = spawn("stex", ["db-migrate", "up"], { stdio: 'inherit' }); // proc.on('close', function (code) { // if(code === 0) { // next(); // } else { // next(new Error("Process failed: " + code)); // } // }); // });
var Stex = require("stex"); var stexDev = require("stex-dev"); var gulp = stexDev.gulp(); var plugins = stexDev.gulpPlugins(); var paths = stexDev.paths; paths.root = __dirname; //HACK: can't think of a better way to expose the app root prior to stex init gulp.task('default', ['test']); gulp.task('dist', ['']); gulp.task('test', ['lint', 'mocha']); gulp.task('db:setup', ['db:ensure-created', 'db:migrate']); // you can find individual gulp tasks in ./node_modules/stex-dev/lib/gulp.js
Move app/db tasks into stex-dev
Move app/db tasks into stex-dev
JavaScript
isc
Payshare/stellar-wallet,stellar/stellar-wallet,stellar/stellar-wallet,Payshare/stellar-wallet
--- +++ @@ -1,57 +1,15 @@ +var Stex = require("stex"); var stexDev = require("stex-dev"); var gulp = stexDev.gulp(); var plugins = stexDev.gulpPlugins(); var paths = stexDev.paths; +paths.root = __dirname; //HACK: can't think of a better way to expose the app root prior to stex init -// composite gulp tasks gulp.task('default', ['test']); gulp.task('dist', ['']); gulp.task('test', ['lint', 'mocha']); -// gulp.task('db:setup', ['db:ensure-created', 'db:migrate']); - -// end composite tasks - +gulp.task('db:setup', ['db:ensure-created', 'db:migrate']); // you can find individual gulp tasks in ./node_modules/stex-dev/lib/gulp.js - - -// // expose the app globals to other tasks -// gulp.task('app', function(next) { -// var stex = require("./lib/app"); -// stex.activate(); -// next(); -// }); - -// gulp.task('db:ensure-created', ['app'], function() { -// var Knex = require("knex"); -// var dbConfig = conf.get("db"); -// var dbToCreate = dbConfig.connection.database; - -// // create a connection to the db without specifying the db -// delete dbConfig.connection.database; -// var db = Knex.initialize(dbConfig); - -// return db.raw("CREATE DATABASE IF NOT EXISTS `" + dbToCreate + "`") -// .then(function() { /* noop */ }) -// .finally(function(){ -// db.client.pool.destroy(); -// }); -// }); - - -// gulp.task('db:migrate', function(next) { -// var spawn = require('child_process').spawn; - -// var proc = spawn("stex", ["db-migrate", "up"], { stdio: 'inherit' }); -// proc.on('close', function (code) { -// if(code === 0) { -// next(); -// } else { -// next(new Error("Process failed: " + code)); -// } -// }); -// }); - -
bb913af7a765a1092233c3b73970a800e8fd8dcc
client/app/components/JewelryProducts.js
client/app/components/JewelryProducts.js
import React from 'react'; class JewelryProducts extends React.Component { render() { return ( <h1>Jewelry Products</h1> ); } } export default JewelryProducts;
import React from 'react'; import 'whatwg-fetch'; import h from '../helpers.js'; class JewelryProducts extends React.Component { constructor() { super(); this.state = { pieces: [] }; } componentDidMount() { fetch('/a/pieces') .then(h.checkStatus) .then(h.parseJSON) .then(data => { this.setState({ pieces: data.pieces }); }) .catch(error => { console.log('Error fetching pieces: ', error); // TODO: display sign this.setState({ pieces: null }); }); } render() { return ( <div> <h1>Jewelry Products</h1> <ul> {this.state.pieces.map(piece => { return ( <li> <h5>{piece.description}</h5> <div>${piece.msrp}</div> <div>Qty: {piece.qtyInStock}</div> </li> ); })} </ul> </div> ); } } export default JewelryProducts;
Make an example for data fetching
Make an example for data fetching
JavaScript
mit
jfanderson/KIM,jfanderson/KIM
--- +++ @@ -1,9 +1,48 @@ import React from 'react'; +import 'whatwg-fetch'; + +import h from '../helpers.js'; class JewelryProducts extends React.Component { + constructor() { + super(); + + this.state = { + pieces: [] + }; + } + + componentDidMount() { + fetch('/a/pieces') + .then(h.checkStatus) + .then(h.parseJSON) + .then(data => { + this.setState({ pieces: data.pieces }); + }) + .catch(error => { + console.log('Error fetching pieces: ', error); + + // TODO: display sign + this.setState({ pieces: null }); + }); + } + render() { return ( - <h1>Jewelry Products</h1> + <div> + <h1>Jewelry Products</h1> + <ul> + {this.state.pieces.map(piece => { + return ( + <li> + <h5>{piece.description}</h5> + <div>${piece.msrp}</div> + <div>Qty: {piece.qtyInStock}</div> + </li> + ); + })} + </ul> + </div> ); } }
cdcf48dc3afdb347303cec910a37cf7a34bd03db
client/app/controllers/boltController.js
client/app/controllers/boltController.js
angular.module('bolt.controller', []) .controller('BoltController', function($scope, $location, $window){ $scope.session = $window.localStorage; $scope.startRun = function() { if (document.getElementById("switch_3_left").checked) { $location.path('/run'); } else if (document.getElementById("switch_3_center").checked) { // Eventually replace with friend matching route $location.path('/run'); } else { $location.path('/multiLoad'); } } })
angular.module('bolt.controller', []) .controller('BoltController', function ($scope, $location, $window) { $scope.session = $window.localStorage; $scope.startRun = function () { if (document.getElementById("switch_3_left").checked) { $location.path('/run'); } else if (document.getElementById("switch_3_center").checked) { // Eventually replace with friend matching route $location.path('/run'); } else { $location.path('/multiLoad'); } }; });
Fix and ungodly number of linter errors
Fix and ungodly number of linter errors
JavaScript
mit
thomasRhoffmann/Bolt,elliotaplant/Bolt,gm758/Bolt,elliotaplant/Bolt,boisterousSplash/Bolt,boisterousSplash/Bolt,gm758/Bolt,thomasRhoffmann/Bolt
--- +++ @@ -1,8 +1,8 @@ angular.module('bolt.controller', []) -.controller('BoltController', function($scope, $location, $window){ +.controller('BoltController', function ($scope, $location, $window) { $scope.session = $window.localStorage; - $scope.startRun = function() { + $scope.startRun = function () { if (document.getElementById("switch_3_left").checked) { $location.path('/run'); } else if (document.getElementById("switch_3_center").checked) { @@ -11,5 +11,5 @@ } else { $location.path('/multiLoad'); } - } -}) + }; +});
1ee6d04bf95b1525aed47e964934b271a05f686a
gulpfile.js
gulpfile.js
const del = require('del') const { dest, series, src } = require('gulp') const { init: sourceMapsInit, write: sourceMapsWrite, } = require('gulp-sourcemaps') const { createProject } = require('gulp-typescript') const tsProject = createProject('tsconfig.json', { declaration: true, isolatedModules: false, jsx: 'react', module: 'amd', noEmit: false, resolveJsonModule: false, sourceMap: true, }) const clean = () => del(['dist/**/*']) const compileTS = () => src([ 'src/**/*.ts', 'src/**/*.tsx', '!src/**/*.d.ts', '!src/**/*.stories.tsx', '!src/**/*.test.ts', '!src/setupTests.ts', ]) .pipe(sourceMapsInit()) .pipe(tsProject()) .pipe(sourceMapsWrite()) .pipe(dest('dist')) const copyStyles = () => src(['src/**/*.css', 'src/**/*.scss']).pipe(dest('dist')) exports.default = series(clean, compileTS, copyStyles)
const del = require('del') const { dest, series, src } = require('gulp') const { init: sourceMapsInit, write: sourceMapsWrite, } = require('gulp-sourcemaps') const { createProject } = require('gulp-typescript') const tsProject = createProject('tsconfig.json', { declaration: true, isolatedModules: false, noEmit: false, sourceMap: true, }) const clean = () => del(['dist/**/*']) const compileTS = () => src([ 'src/**/*.ts', 'src/**/*.tsx', '!src/**/*.d.ts', '!src/**/*.stories.tsx', '!src/**/*.test.ts', '!src/setupTests.ts', ]) .pipe(sourceMapsInit()) .pipe(tsProject()) .pipe(sourceMapsWrite()) .pipe(dest('dist')) const copyStyles = () => src(['src/**/*.css', 'src/**/*.scss']).pipe(dest('dist')) exports.default = series(clean, compileTS, copyStyles)
Revert to old compilation format except compile JSX
Revert to old compilation format except compile JSX
JavaScript
mit
IsaacLean/bolt-ui,IsaacLean/bolt-ui
--- +++ @@ -9,10 +9,7 @@ const tsProject = createProject('tsconfig.json', { declaration: true, isolatedModules: false, - jsx: 'react', - module: 'amd', noEmit: false, - resolveJsonModule: false, sourceMap: true, })
d3367ffe1f426b18b88aa0abe11aefbb7131278d
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var elixir = require('laravel-elixir'); var argv = require('yargs').argv; var bin = require('./tasks/bin'); elixir.config.assetsPath = 'source/_assets'; elixir.config.publicPath = 'source'; elixir.config.sourcemaps = false; elixir(function(mix) { var env = argv.e || argv.env || 'local'; var port = argv.p || argv.port || 3000; mix.sass('main.scss') .sass('reset.scss') .exec(bin.path() + ' build ' + env, ['./source/*', './source/**/*', '!./source/_assets/**/*']) .browserSync({ port: port, server: { baseDir: 'build_' + env }, proxy: null, files: [ 'build_' + env + '/**/*' ] }); });
process.env.DISABLE_NOTIFIER = true; var gulp = require('gulp'); var elixir = require('laravel-elixir'); var argv = require('yargs').argv; var bin = require('./tasks/bin'); elixir.config.assetsPath = 'source/_assets'; elixir.config.publicPath = 'source'; elixir.config.sourcemaps = false; elixir(function(mix) { var env = argv.e || argv.env || 'local'; var port = argv.p || argv.port || 3000; mix.sass('main.scss') .sass('reset.scss') .exec(bin.path() + ' build ' + env, ['./source/*', './source/**/*', '!./source/_assets/**/*']) .browserSync({ port: port, server: { baseDir: 'build_' + env }, proxy: null, files: [ 'build_' + env + '/**/*' ], notify: false, open: false, }); });
Disable Elixir and BrowserSync notifications
Disable Elixir and BrowserSync notifications
JavaScript
agpl-3.0
art-institute-of-chicago/gauguin-microsite,art-institute-of-chicago/gauguin-microsite,art-institute-of-chicago/gauguin-microsite
--- +++ @@ -1,3 +1,5 @@ +process.env.DISABLE_NOTIFIER = true; + var gulp = require('gulp'); var elixir = require('laravel-elixir'); var argv = require('yargs').argv; @@ -18,7 +20,9 @@ port: port, server: { baseDir: 'build_' + env }, proxy: null, - files: [ 'build_' + env + '/**/*' ] + files: [ 'build_' + env + '/**/*' ], + notify: false, + open: false, }); });
9a9e537e01b410efbe5aae0429c60a1363f431e3
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var fse = require('fs-extra'); gulp.task('clean', function(done) { fse.removeSync('dist'); fse.mkdirSync('dist'); done(); }); gulp.task('default', ['clean'], function() { return gulp .src('static/*') .pipe(gulp.dest('dist')); });
var gulp = require('gulp'); var fse = require('fs-extra'); gulp.task('clean', function(done) { fse.removeSync('dist'); fse.mkdirSync('dist'); done(); }); gulp.task('default', ['clean'], function() { return gulp .src(['static/*', 'node_modules/localforage/dist/localforage.min.js']) .pipe(gulp.dest('dist')); });
Copy the localForage library in dist/
Copy the localForage library in dist/
JavaScript
apache-2.0
zalun/mercurius,zalun/mercurius,marco-c/mercurius,marco-c/mercurius,marco-c/mercurius
--- +++ @@ -9,6 +9,6 @@ gulp.task('default', ['clean'], function() { return gulp - .src('static/*') + .src(['static/*', 'node_modules/localforage/dist/localforage.min.js']) .pipe(gulp.dest('dist')); });
fe3c32c0361a1b6779b8ee9830df88f13e5653ab
app/components/Tap.js
app/components/Tap.js
import React, { Component, PropTypes } from 'react' import { playAudio } from '../utils/audioplayer' export default class Tap extends Component { static PropTypes = { receivedTaps: PropTypes.object, users: PropTypes.object, } shouldComponentUpdate(nextProps, nextState) { console.log(this.props.receivedTaps) const render = this.props.receivedTaps.length !== 0 && !Object.is(this.props.receivedTaps, nextProps.receivedTaps) return render } render() { const {receivedTaps, users} = this.props const displayName = users && receivedTaps && receivedTaps.length > 0 ? users[receivedTaps[receivedTaps.length - 1].from].displayName : null if (displayName) { const notificationText = `You received a tap from ${displayName}` new Notification(notificationText) playAudio() console.log('ping') } return null } }
import React, { Component, PropTypes } from 'react' import { playAudio } from '../utils/audioplayer' export default class Tap extends Component { static PropTypes = { receivedTaps: PropTypes.object, users: PropTypes.object, } shouldComponentUpdate(nextProps, nextState) { console.log(this.props.receivedTaps) const render = this.props.receivedTaps.length !== 0 && !Object.is(this.props.receivedTaps, nextProps.receivedTaps) return render } render() { const {receivedTaps, users} = this.props const displayName = users && receivedTaps && receivedTaps.length > 0 ? users[receivedTaps[receivedTaps.length - 1].from].displayName : null if (displayName) { const notificationText = `You received a tap from ${displayName}` new Notification(notificationText, {silent: true}) playAudio() console.log('ping') } return null } }
Set system notification sound to silent
Set system notification sound to silent
JavaScript
apache-2.0
hbierlee/digital-shoulder-tap,hbierlee/digital-shoulder-tap
--- +++ @@ -25,7 +25,7 @@ if (displayName) { const notificationText = `You received a tap from ${displayName}` - new Notification(notificationText) + new Notification(notificationText, {silent: true}) playAudio() console.log('ping') }
ce690f942c693ef3e8083b224153f624d58b7913
lib/system_config.js
lib/system_config.js
"format cjs"; var loader = require('@loader'); var isNode = typeof process === "object" && {}.toString.call(process) === "[object process]"; if(isNode) { exports.systemConfig = { meta: { 'jquery': { "format": "global", "exports": "jQuery", "deps": ["can/util/vdom/vdom"] } } }; } else { exports.systemConfig = { map: { "can/util/vdom/vdom": "@empty" } }; }
"format cjs"; var loader = require('@loader'); var isNode = typeof process === "object" && {}.toString.call(process) === "[object process]"; if(isNode) { exports.systemConfig = { map: { "can/util/vdom/vdom": "can/util/vdom/vdom" }, meta: { 'jquery': { "format": "global", "exports": "jQuery", "deps": ["can/util/vdom/vdom"] } } }; } else { exports.systemConfig = { map: { "can/util/vdom/vdom": "@empty" } }; }
Make sure can/util/vdom can load
Make sure can/util/vdom can load The new version of Can now maps can/util/vdom/vdom to @empty by default, so if you are using an env other than server-development or server-production can-ssr can't load. To fix this we need to map can/util/vdom/vdom onto itself so that it definitely does load on the server no matter what env is set.
JavaScript
mit
donejs/done-ssr,donejs/done-ssr
--- +++ @@ -7,6 +7,9 @@ if(isNode) { exports.systemConfig = { + map: { + "can/util/vdom/vdom": "can/util/vdom/vdom" + }, meta: { 'jquery': { "format": "global",
ace61513a0b03b9409ccdceef288f3676a6476ac
lib/tokensManager.js
lib/tokensManager.js
const fs = require("fs"); const objectEquals = require("./objectEquals"); const { DEFAULT_TOKENS_FILENAME } = require("../lib/constants"); const tokensManager = function tokensManager (filename = DEFAULT_TOKENS_FILENAME) { const tokens = (function init () { try { return JSON.parse(fs.readFileSync(filename, { encoding: "utf-8" })); } catch (err) { if (err.code === "ENOENT") return []; else throw err; } })(); const persistTokens = () => fs.writeFileSync(filename, JSON.stringify(tokens, null, 2), { encoding: "utf-8" }); const exists = function exists (token) { return tokens.some(t => objectEquals(t, token)); }; const add = function add (token) { if (!exists(token)) { tokens.push(token); persistTokens(); } }; const clear = function clear () { tokens.splice(0); persistTokens(); }; const remove = function remove (token) { tokens.splice(tokens.indexOf(token), 1); persistTokens(); }; return { add, clear, exists, remove, size: () => tokens.length }; }; module.exports = tokensManager;
const fs = require("fs"); const objectEquals = require("./objectEquals"); const { DEFAULT_TOKENS_FILENAME } = require("../lib/constants"); const tokensManager = function tokensManager (filename = DEFAULT_TOKENS_FILENAME) { const tokens = (function init () { try { return JSON.parse(fs.readFileSync(filename, { encoding: "utf-8" })); } catch (err) { if (err.code === "ENOENT") return []; else throw err; } })(); const persistTokens = () => fs.writeFileSync(filename, JSON.stringify(tokens, null, 2) + "\n", { encoding: "utf-8" }); const exists = function exists (token) { return tokens.some(t => objectEquals(t, token)); }; const add = function add (token) { if (!exists(token)) { tokens.push(token); persistTokens(); } }; const clear = function clear () { tokens.splice(0); persistTokens(); }; const remove = function remove (token) { tokens.splice(tokens.indexOf(token), 1); persistTokens(); }; return { add, clear, exists, remove, size: () => tokens.length }; }; module.exports = tokensManager;
Add EOL to tokens JSON file
Add EOL to tokens JSON file
JavaScript
mit
luispablo/tokenauth
--- +++ @@ -15,7 +15,7 @@ } })(); - const persistTokens = () => fs.writeFileSync(filename, JSON.stringify(tokens, null, 2), { encoding: "utf-8" }); + const persistTokens = () => fs.writeFileSync(filename, JSON.stringify(tokens, null, 2) + "\n", { encoding: "utf-8" }); const exists = function exists (token) { return tokens.some(t => objectEquals(t, token));
df36577dd72440c7e581d304cf86d6edd036bed3
src/utils/detection.js
src/utils/detection.js
/** * Detect platform-specific things. */ goog.provide('onfire.utils.detection'); /** * @type {boolean} */ onfire.utils.detection.IS_NODEJS = (typeof module !== 'undefined' && !!module.exports);
/** * Detect platform-specific things. */ goog.provide('onfire.utils.detection'); /** * @type {boolean} */ onfire.utils.detection.IS_NODEJS = (typeof module !== 'undefined' && module !== this.module && !!module.exports);
Add additional test for Node environment
Add additional test for Node environment module !== this.module in Node, but this can be true in a browser
JavaScript
mit
isabo/onfire
--- +++ @@ -9,4 +9,5 @@ /** * @type {boolean} */ -onfire.utils.detection.IS_NODEJS = (typeof module !== 'undefined' && !!module.exports); +onfire.utils.detection.IS_NODEJS = + (typeof module !== 'undefined' && module !== this.module && !!module.exports);
b38008623b2d0cd3a9912481dcafe4fe37b22d3b
src/submit-button.js
src/submit-button.js
'use strict'; module.exports = function ($interpolate, $parse) { return { require: '^bdSubmit', restrict: 'A', compile: function (element, attributes) { if (!attributes.type) { attributes.$set('type', 'submit'); } return function (scope, element, attributes, controller) { var original = element.text(); scope.submission = controller; function ngDisabled () { return attributes.ngDisabled && !!$parse(attributes.ngDisabled)(scope); } scope.$watch('submission.pending', function (pending) { attributes.$set('disabled', pending || ngDisabled()); element.text($interpolate(pending ? attributes.pending : original)(scope)); }); }; } }; }; module.exports.$inject = ['$interpolate', '$parse'];
'use strict'; module.exports = function ($interpolate, $parse) { return { require: '^bdSubmit', restrict: 'A', compile: function (element, attributes) { if (!attributes.type) { attributes.$set('type', 'submit'); } return function (scope, element, attributes, controller) { var original = element.text(); function ngDisabled () { return attributes.ngDisabled && !!$parse(attributes.ngDisabled)(scope); } scope.$watch(function () { return controller.pending; }, function (pending) { attributes.$set('disabled', pending || ngDisabled()); element.text($interpolate(pending ? attributes.pending : original)(scope)); }); }; } }; }; module.exports.$inject = ['$interpolate', '$parse'];
Use a watch function instead of adding submission to scope
Use a watch function instead of adding submission to scope
JavaScript
mit
bendrucker/angular-form-state
--- +++ @@ -10,11 +10,12 @@ } return function (scope, element, attributes, controller) { var original = element.text(); - scope.submission = controller; function ngDisabled () { return attributes.ngDisabled && !!$parse(attributes.ngDisabled)(scope); } - scope.$watch('submission.pending', function (pending) { + scope.$watch(function () { + return controller.pending; + }, function (pending) { attributes.$set('disabled', pending || ngDisabled()); element.text($interpolate(pending ? attributes.pending : original)(scope)); });
d2adb620304c51e85903f97d9015ac2e6ce340fb
app/controllers/application.js
app/controllers/application.js
import Ember from 'ember'; export default Ember.Controller.extend({ session: Ember.inject.service(), actions: { invalidateSession () { this.get('session').invalidate(); }, login () { const lockOptions = { autoclose: true, icon: 'https://s3-us-west-1.amazonaws.com/barberscore/static/app/bhs_logo.png', closeable: true, focusInput: true, gravatar: false, primaryColor: '#337ab7', rememberLastLogin: true, dict: { title: "Barberscore", email: { headerText: "Enter your email address<br>registered with the BHS.", footerText: "(If you aren't currently registered with the BHS, or can't remember your email, please contact <a href='mailto:support@barberscore.com'>support@barberscore.com</a> for assistance.)" }, emailSent: { success: "We sent an email to <br>{email}<br>with a link to login." }, error: { passwordless: { "bad.connection": "We're sorry, we can't log you in because that email is not registered with the BHS. Try again with a different email address or contact support@barberscore.com for assistance.", } } }, }; this.get('session').authenticate( 'authenticator:auth0-lock-passwordless', 'magiclink', lockOptions ); }, } });
import Ember from 'ember'; export default Ember.Controller.extend({ session: Ember.inject.service(), actions: { invalidateSession () { this.get('session').invalidate(); }, login () { const lockOptions = { autoclose: true, icon: 'https://s3-us-west-1.amazonaws.com/barberscore/static/app/bhs_logo.png', closeable: true, focusInput: true, gravatar: false, primaryColor: '#337ab7', rememberLastLogin: true, dict: { title: "Barberscore", email: { headerText: "Enter your email address<br>registered with the BHS.", footerText: "(If you aren't currently registered with the BHS, or can't remember your email, please contact <a href='mailto:support@barberscore.com'>support@barberscore.com</a> for assistance.)" }, emailSent: { success: "Check your email for the log in link. PLEASE NOTE: It may take up to a minute for the email to be sent, so please be patient." }, error: { passwordless: { "bad.connection": "We're sorry, we can't log you in because that email is not registered with the BHS. Try again with a different email address or contact support@barberscore.com for assistance.", } } }, }; this.get('session').authenticate( 'authenticator:auth0-lock-passwordless', 'magiclink', lockOptions ); }, } });
Update notice for email sent
Update notice for email sent
JavaScript
bsd-2-clause
barberscore/barberscore-web,barberscore/barberscore-web,barberscore/barberscore-web
--- +++ @@ -22,7 +22,7 @@ footerText: "(If you aren't currently registered with the BHS, or can't remember your email, please contact <a href='mailto:support@barberscore.com'>support@barberscore.com</a> for assistance.)" }, emailSent: { - success: "We sent an email to <br>{email}<br>with a link to login." + success: "Check your email for the log in link. PLEASE NOTE: It may take up to a minute for the email to be sent, so please be patient." }, error: { passwordless: {
b2eff2b6ba5ea37838a2111f0dc109c56a6b6d09
app/javascript/components/cloud-tenant-form/create-form.schema.js
app/javascript/components/cloud-tenant-form/create-form.schema.js
/** * @param {Boolean} renderEmsChoices * @param {Object} emsChoices */ function createSchema(renderEmsChoices, emsChoices) { let fields = [{ component: 'text-field', name: 'name', validate: [{ type: 'required-validator', }], label: __('Tenant Name'), maxLength: 128, validateOnMount: true, }]; if (!renderEmsChoices) { fields = [{ component: 'select-field', name: 'ems_id', menuPlacement: 'bottom', label: __('Cloud Provider/Parent Cloud Tenant'), placeholder: `<${__('Choose')}>`, validateOnMount: true, validate: [{ type: 'required-validator', }], options: Object.keys(emsChoices).map(key => ({ value: emsChoices[key], label: key, })), }, ...fields]; } return { fields }; } export default createSchema;
import { componentTypes, validatorTypes } from '@@ddf'; /** * @param {Boolean} renderEmsChoices * @param {Object} emsChoices */ function createSchema(renderEmsChoices, emsChoices) { let fields = [{ component: componentTypes.TEXT_FIELD, name: 'name', validate: [{ type: validatorTypes.REQUIRED, }], label: __('Tenant Name'), maxLength: 128, validateOnMount: true, }]; if (!renderEmsChoices) { fields = [{ component: componentTypes.SELECT, name: 'ems_id', menuPlacement: 'bottom', label: __('Cloud Provider/Parent Cloud Tenant'), placeholder: `<${__('Choose')}>`, validateOnMount: true, validate: [{ type: validatorTypes.REQUIRED, }], options: Object.keys(emsChoices).map(key => ({ value: emsChoices[key], label: key, })), }, ...fields]; } return { fields }; } export default createSchema;
Use constants for component/validator types in cloud tenant form
Use constants for component/validator types in cloud tenant form
JavaScript
apache-2.0
ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic
--- +++ @@ -1,13 +1,15 @@ +import { componentTypes, validatorTypes } from '@@ddf'; + /** * @param {Boolean} renderEmsChoices * @param {Object} emsChoices */ function createSchema(renderEmsChoices, emsChoices) { let fields = [{ - component: 'text-field', + component: componentTypes.TEXT_FIELD, name: 'name', validate: [{ - type: 'required-validator', + type: validatorTypes.REQUIRED, }], label: __('Tenant Name'), maxLength: 128, @@ -15,14 +17,14 @@ }]; if (!renderEmsChoices) { fields = [{ - component: 'select-field', + component: componentTypes.SELECT, name: 'ems_id', menuPlacement: 'bottom', label: __('Cloud Provider/Parent Cloud Tenant'), placeholder: `<${__('Choose')}>`, validateOnMount: true, validate: [{ - type: 'required-validator', + type: validatorTypes.REQUIRED, }], options: Object.keys(emsChoices).map(key => ({ value: emsChoices[key],
cbcc919782649d8bcfd7e86e86a20a82fc4dd109
src/utils/animate.js
src/utils/animate.js
function easing(time) { return 1 - (--time) * time * time * time; }; /** * Given a start/end point of a scroll and time elapsed, calculate the scroll position we should be at * @param {Number} start - the initial value * @param {Number} stop - the final desired value * @param {Number} elapsed - the amount of time elapsed since we started animating * @param {Number} - duration - the duration of the animation * @return {Number} - The value we should use on the next tick */ function getValue(start, end, elapsed, duration) { if (elapsed > duration) return end; return start + (end - start) * easing(elapsed / duration); }; /** * Smoothly animate between two values * @param {Number} fromValue - the initial value * @param {Function} onUpdate - A function that is called on each tick * @param {Function} onComplete - A callback that is fired once the scroll animation ends * @param {Number} duration - the desired duration of the scroll animation */ export default function animate({ fromValue, toValue, onUpdate, onComplete, duration = 600, }) { const startTime = Date.now(); const tick = () => { const elapsed = Date.now() - startTime; window.requestAnimationFrame(() => onUpdate( getValue(fromValue, toValue, elapsed, duration), // Callback elapsed <= duration ? tick : onComplete )); }; tick(); };
function easing(time) { return 1 - (--time) * time * time * time; }; /** * Given a start/end point of a scroll and time elapsed, calculate the scroll position we should be at * @param {Number} start - the initial value * @param {Number} stop - the final desired value * @param {Number} elapsed - the amount of time elapsed since we started animating * @param {Number} - duration - the duration of the animation * @return {Number} - The value we should use on the next tick */ function getValue(start, end, elapsed, duration) { if (elapsed > duration) return end; return start + (end - start) * easing(elapsed / duration); }; /** * Smoothly animate between two values * @param {Number} fromValue - the initial value * @param {Function} onUpdate - A function that is called on each tick * @param {Function} onComplete - A callback that is fired once the scroll animation ends * @param {Number} duration - the desired duration of the scroll animation */ export default function animate({ fromValue, toValue, onUpdate, onComplete, duration = 600, }) { const startTime = performance.now(); const tick = () => { const elapsed = performance.now() - startTime; window.requestAnimationFrame(() => onUpdate( getValue(fromValue, toValue, elapsed, duration), // Callback elapsed <= duration ? tick : onComplete )); }; tick(); };
Use performance.now instead of Date.now
Use performance.now instead of Date.now
JavaScript
mit
clauderic/react-infinite-calendar
--- +++ @@ -29,10 +29,10 @@ onComplete, duration = 600, }) { - const startTime = Date.now(); + const startTime = performance.now(); const tick = () => { - const elapsed = Date.now() - startTime; + const elapsed = performance.now() - startTime; window.requestAnimationFrame(() => onUpdate( getValue(fromValue, toValue, elapsed, duration),
df075c083b7541c32666fc71549465d97ca20c21
jobs/projects/create.js
jobs/projects/create.js
const models = require('../../models'); let Project = models.projects; module.exports = function(connection, done) { connection.createChannel(function(err, ch) { console.log(err); var ex = 'chiepherd.main'; ch.assertExchange(ex, 'topic'); ch.assertQueue('chiepherd.project.create', { exclusive: false }, function(err, q) { ch.bindQueue(q.queue, ex, "chiepherd.project.create") ch.consume(q.queue, function(msg) { // LOG console.log(" [%s]: %s", msg.fields.routingKey, msg.content.toString()); let json = JSON.parse(msg.content.toString()); // Create project Project.create({ name: json.name, label: json.label, description: json.description }).then(function(project) { ch.sendToQueue(msg.properties.replyTo, new Buffer.from(JSON.stringify(project)), { correlationId: msg.properties.correlationId }); ch.ack(msg); }).catch(function(error) { ch.sendToQueue(msg.properties.replyTo, new Buffer.from(JSON.stringify(error)), { correlationId: msg.properties.correlationId }); ch.ack(msg); }); }, { noAck: false }); }); }); done(); }
const models = require('../../models'); let Project = models.projects; module.exports = function(connection, done) { connection.createChannel(function(err, ch) { console.log(err); var ex = 'chiepherd.main'; ch.assertExchange(ex, 'topic'); ch.assertQueue('chiepherd.project.create', { exclusive: false }, function(err, q) { ch.bindQueue(q.queue, ex, "chiepherd.project.create") ch.consume(q.queue, function(msg) { // LOG console.log(" [%s]: %s", msg.fields.routingKey, msg.content.toString()); let json = JSON.parse(msg.content.toString()); // Create project Project.create({ name: json.name, label: json.label, description: json.description }).then(function(project) { ch.sendToQueue(msg.properties.replyTo, new Buffer.from(JSON.stringify(project)), { correlationId: msg.properties.correlationId }); connection.createChannel(function(error, channel) { var ex = 'chiepherd.project.created'; channel.assertExchange(ex, 'fanout', { durable: false }); channel.publish(ex, '', new Buffer.from(JSON.stringify(project))); }); ch.ack(msg); }).catch(function(error) { ch.sendToQueue(msg.properties.replyTo, new Buffer.from(JSON.stringify(error)), { correlationId: msg.properties.correlationId }); ch.ack(msg); }); }, { noAck: false }); }); }); done(); }
Send message to other API
Send message to other API
JavaScript
mit
CHIEPHERD/chiepherd_api,CHIEPHERD/chiepherd_api,CHIEPHERD/chiepherd_api
--- +++ @@ -23,6 +23,11 @@ ch.sendToQueue(msg.properties.replyTo, new Buffer.from(JSON.stringify(project)), { correlationId: msg.properties.correlationId }); + connection.createChannel(function(error, channel) { + var ex = 'chiepherd.project.created'; + channel.assertExchange(ex, 'fanout', { durable: false }); + channel.publish(ex, '', new Buffer.from(JSON.stringify(project))); + }); ch.ack(msg); }).catch(function(error) { ch.sendToQueue(msg.properties.replyTo,
1aca5fcc9668cc9eeec2750acf4ebd1e850a1d1c
packages/react-jsx-highmaps/src/index.js
packages/react-jsx-highmaps/src/index.js
import { withSeriesType } from 'react-jsx-highcharts'; export { Chart, Credits, Debug, Loading, Legend, Series, Subtitle, Title, Tooltip, HighchartsContext, HighchartsChartContext, HighchartsAxisContext, HighchartsSeriesContext, provideHighcharts, provideChart, provideAxis, provideSeries, withHighcharts as withHighmaps, withSeriesType } from 'react-jsx-highcharts'; // Charts export { default as HighchartsMapChart } from './components/HighchartsMapChart'; // Graph Parts export { default as MapNavigation } from './components/MapNavigation'; export { default as XAxis } from './components/XAxis'; export { default as YAxis } from './components/YAxis'; // Series const parentAxisId = { axisId: 'yAxis' }; export const MapBubbleSeries = withSeriesType('MapBubble', parentAxisId); export const MapLineSeries = withSeriesType('MapLine', parentAxisId); export const MapPointSeries = withSeriesType('MapPoint', parentAxisId); export const MapSeries = withSeriesType('Map', parentAxisId);
import { withSeriesType } from 'react-jsx-highcharts'; export { Chart, Credits, Debug, Loading, Legend, Series, Subtitle, Title, Tooltip, HighchartsContext, HighchartsChartContext, HighchartsAxisContext, HighchartsSeriesContext, withHighcharts as withHighmaps, withSeriesType } from 'react-jsx-highcharts'; // Charts export { default as HighchartsMapChart } from './components/HighchartsMapChart'; // Graph Parts export { default as MapNavigation } from './components/MapNavigation'; export { default as XAxis } from './components/XAxis'; export { default as YAxis } from './components/YAxis'; // Series const parentAxisId = { axisId: 'yAxis' }; export const MapBubbleSeries = withSeriesType('MapBubble', parentAxisId); export const MapLineSeries = withSeriesType('MapLine', parentAxisId); export const MapPointSeries = withSeriesType('MapPoint', parentAxisId); export const MapSeries = withSeriesType('Map', parentAxisId);
Remove missing exports from react-jsx-highmaps
Remove missing exports from react-jsx-highmaps
JavaScript
mit
whawker/react-jsx-highcharts,whawker/react-jsx-highcharts
--- +++ @@ -13,10 +13,6 @@ HighchartsChartContext, HighchartsAxisContext, HighchartsSeriesContext, - provideHighcharts, - provideChart, - provideAxis, - provideSeries, withHighcharts as withHighmaps, withSeriesType } from 'react-jsx-highcharts';
0ccd1659f8e5b4999191cf1a8a1cd1960517c46c
client/app/js/core/view-switcher.js
client/app/js/core/view-switcher.js
import Model from '../base/model'; export default class ViewSwitcher { constructor(app, element) { this.app = app; this.element = element; this.currentView = null; } switchView(ViewClass, args) { if (this.currentView instanceof ViewClass) { this.currentView.model.replace(args); return; } if (this.currentView) { this.currentView.unbind(); this.element.removeChild(this.currentView.element); } const model = new Model(args); const view = new ViewClass({app: this.app, model: model}); this.element.appendChild(view.element) view.render(); this.currentView = view; } }
import Model from '../base/model'; export default class ViewSwitcher { constructor(app, element) { this.app = app; this.element = element; this.currentView = null; } switchView(ViewClass, args) { if (this.currentView instanceof ViewClass) { this.currentView.model.replace(args); return; } if (this.currentView) { this.currentView.unbind(); this.element.removeChild(this.currentView.element); } const model = new Model(args); const view = new ViewClass({app: this.app, model: model}); view.render(); this.element.appendChild(view.element); this.currentView = view; } }
Append view's element after rendering
Append view's element after rendering This makes no difference, but seem more logical
JavaScript
mit
despawnerer/theatrics,despawnerer/theatrics,despawnerer/theatrics
--- +++ @@ -22,8 +22,9 @@ const model = new Model(args); const view = new ViewClass({app: this.app, model: model}); - this.element.appendChild(view.element) view.render(); + + this.element.appendChild(view.element); this.currentView = view; }
11a15c61e4e9ad0f4c5efe4c56bc308e37006198
lib/configure_loader.js
lib/configure_loader.js
var pkg = require("../package.json"); global.navigator = global.navigator || { userAgent: "Mozilla/5.0 " + "done-ssr/" + pkg.version }; module.exports = function(loader){ // Ensure the extension loads before the main. var loaderImport = loader.import; loader.import = function(name){ if(name === loader.main) { var args = arguments; // Set up the renderingLoader to be used by plugins to know what root // to attach urls to. if(!loader.renderingLoader) { loader.renderingLoader = loader.clone(); var baseURL = loader.renderingBaseURL || loader.baseURL; if(baseURL.indexOf("file:") === 0) { baseURL = "/"; } loader.renderingLoader.baseURL = baseURL; } return loaderImport.apply(loader, args); } return loaderImport.apply(this, arguments); }; };
var pkg = require("../package.json"); global.navigator = global.navigator || { userAgent: "Mozilla/5.0 " + "done-ssr/" + pkg.version }; module.exports = function(loader){ // Ensure the extension loads before the main. var loaderImport = loader.import; loader.import = function(name){ if(name === loader.main) { var args = arguments; // Set up the renderingLoader to be used by plugins to know what root // to attach urls to. if(!loader.renderingLoader) { loader.renderingLoader = loader.clone(); var baseURL = loader.renderingBaseURL || loader.baseURL; if(baseURL.indexOf("file:") === 0) { baseURL = "/"; } loader.renderingLoader.baseURL = loader.renderingBaseURL = baseURL; } return loaderImport.apply(loader, args); } return loaderImport.apply(this, arguments); }; };
Set renderingBaseURL on the loader
Set renderingBaseURL on the loader
JavaScript
mit
donejs/done-ssr,donejs/done-ssr
--- +++ @@ -19,7 +19,8 @@ if(baseURL.indexOf("file:") === 0) { baseURL = "/"; } - loader.renderingLoader.baseURL = baseURL; + loader.renderingLoader.baseURL = + loader.renderingBaseURL = baseURL; } return loaderImport.apply(loader, args);
e9ff9befd71167f2fe17045e8c370c70ca97b61e
js/store.js
js/store.js
import { createStore, applyMiddleware } from "redux"; import thunk from "redux-thunk"; import { composeWithDevTools } from "redux-devtools-extension"; import reducer from "./reducers"; import mediaMiddleware from "./mediaMiddleware"; import { merge } from "./utils"; import { UPDATE_TIME_ELAPSED, STEP_MARQUEE } from "./actionTypes"; const compose = composeWithDevTools({ actionsBlacklist: [UPDATE_TIME_ELAPSED, STEP_MARQUEE] }); const getStore = ( media, actionEmitter, customMiddlewares = [], stateOverrides ) => { let initialState; if (stateOverrides) { initialState = merge( reducer(undefined, { type: "@@init" }), stateOverrides ); } // eslint-disable-next-line no-unused-vars const emitterMiddleware = store => next => action => { actionEmitter.trigger(action.type); return next(action); }; return createStore( reducer, initialState, compose( applyMiddleware( ...[ thunk, mediaMiddleware(media), emitterMiddleware, ...customMiddlewares ].filter(Boolean) ) ) ); }; export default getStore;
import { createStore, applyMiddleware } from "redux"; import thunk from "redux-thunk"; import { composeWithDevTools } from "redux-devtools-extension"; import reducer from "./reducers"; import mediaMiddleware from "./mediaMiddleware"; import { merge } from "./utils"; import { UPDATE_TIME_ELAPSED, STEP_MARQUEE } from "./actionTypes"; const compose = composeWithDevTools({ actionsBlacklist: [UPDATE_TIME_ELAPSED, STEP_MARQUEE] }); const getStore = ( media, actionEmitter, customMiddlewares = [], stateOverrides ) => { let initialState; if (stateOverrides) { initialState = merge( reducer(undefined, { type: "@@init" }), stateOverrides ); } // eslint-disable-next-line no-unused-vars const emitterMiddleware = store => next => action => { actionEmitter.trigger(action.type, action); return next(action); }; return createStore( reducer, initialState, compose( applyMiddleware( ...[ thunk, mediaMiddleware(media), emitterMiddleware, ...customMiddlewares ].filter(Boolean) ) ) ); }; export default getStore;
Fix webamp.onTrackDidChange, by actually passing the action to the event emitter
Fix webamp.onTrackDidChange, by actually passing the action to the event emitter
JavaScript
mit
captbaritone/winamp2-js,captbaritone/winamp2-js,captbaritone/winamp2-js
--- +++ @@ -26,7 +26,7 @@ // eslint-disable-next-line no-unused-vars const emitterMiddleware = store => next => action => { - actionEmitter.trigger(action.type); + actionEmitter.trigger(action.type, action); return next(action); };
35a42f3873ae041e59952888ce4282a3163debe5
app/main/autoupdater.js
app/main/autoupdater.js
'use strict'; const {app, dialog} = require('electron'); const {autoUpdater} = require('electron-updater'); function appUpdater() { // Log whats happening const log = require('electron-log'); log.transports.file.level = 'info'; autoUpdater.logger = log; autoUpdater.allowPrerelease = false; // Ask the user if update is available // eslint-disable-next-line no-unused-vars autoUpdater.on('update-downloaded', (event, info) => { // Ask user to update the app dialog.showMessageBox({ type: 'question', buttons: ['Install and Relaunch', 'Later'], defaultId: 0, message: 'A new version of ' + app.getName() + ' has been downloaded', detail: 'It will be installed the next time you restart the application' }, response => { if (response === 0) { setTimeout(() => autoUpdater.quitAndInstall(), 1); } }); }); // Init for updates autoUpdater.checkForUpdates(); } module.exports = { appUpdater };
'use strict'; const {app, dialog} = require('electron'); const {autoUpdater} = require('electron-updater'); const ConfigUtil = require('./../renderer/js/utils/config-util.js'); function appUpdater() { // Log whats happening const log = require('electron-log'); log.transports.file.level = 'info'; autoUpdater.logger = log; autoUpdater.allowPrerelease = ConfigUtil.getConfigItem('BetaUpdate'); // Ask the user if update is available // eslint-disable-next-line no-unused-vars autoUpdater.on('update-downloaded', (event, info) => { // Ask user to update the app dialog.showMessageBox({ type: 'question', buttons: ['Install and Relaunch', 'Later'], defaultId: 0, message: 'A new version of ' + app.getName() + ' has been downloaded', detail: 'It will be installed the next time you restart the application' }, response => { if (response === 0) { setTimeout(() => autoUpdater.quitAndInstall(), 1); } }); }); // Init for updates autoUpdater.checkForUpdates(); } module.exports = { appUpdater };
Allow auto update for prerelease based on betaupdates setting
Allow auto update for prerelease based on betaupdates setting
JavaScript
apache-2.0
zulip/zulip-electron,zulip/zulip-desktop,zulip/zulip-desktop,zulip/zulip-desktop,zulip/zulip-electron,zulip/zulip-desktop,zulip/zulip-electron
--- +++ @@ -1,13 +1,15 @@ 'use strict'; const {app, dialog} = require('electron'); const {autoUpdater} = require('electron-updater'); + +const ConfigUtil = require('./../renderer/js/utils/config-util.js'); function appUpdater() { // Log whats happening const log = require('electron-log'); log.transports.file.level = 'info'; autoUpdater.logger = log; - autoUpdater.allowPrerelease = false; + autoUpdater.allowPrerelease = ConfigUtil.getConfigItem('BetaUpdate'); // Ask the user if update is available // eslint-disable-next-line no-unused-vars
3b81a97838b7c176ad0ae1c3c0e4323780446a39
components/loadingBar/LoadingBar.js
components/loadingBar/LoadingBar.js
import React, { PureComponent } from 'react'; class LoadingBar extends PureComponent { render() { return null; } } export default LoadingBar;
import React, { PureComponent } from 'react'; class LoadingBar extends PureComponent { render() { return ( <svg version="1.1" xmlns="http://www.w3.org/2000/svg"> <rect /> </svg> ); } } export default LoadingBar;
Create SVG containing a rectangle as SVG is performance wise the best option for animation
Create SVG containing a rectangle as SVG is performance wise the best option for animation
JavaScript
mit
teamleadercrm/teamleader-ui
--- +++ @@ -2,7 +2,11 @@ class LoadingBar extends PureComponent { render() { - return null; + return ( + <svg version="1.1" xmlns="http://www.w3.org/2000/svg"> + <rect /> + </svg> + ); } }
f6b974940964241d0980b15efb3f030452c70c82
ext/open_ZIP.js
ext/open_ZIP.js
define(function() { 'use strict'; function open(item) { console.log(item); } return open; });
define(['msdos/util'], function(dosUtil) { 'use strict'; function open() { this.addExplorer(function(expedition) { var pos = 0; function onLocalFileHeader(bytes) { var localFile = new LocalFileHeaderView(bytes.buffer, bytes.byteOffset, bytes.byteLength); if (!localFile.hasValidSignature) { return expedition.abandon('invalid Local File Header signature'); } } this.byteSource.slice(pos, pos + 0x1d).then(onLocalFileHeader); }); } function LocalFileHeaderView(buffer, byteOffset, byteLength) { this.dataView = new DataView(buffer, byteOffset, byteLength); this.bytes = new Uint8Array(buffer, byteOffset, byteLength); } LocalFileHeaderView.prototype = { get hasValidSignature() { return String.fromCharCode.apply(null, this.bytes.subarray(0, 4)) === 'PK\3\4'; }, get version() { return this.getUint16(4, true) / 10; }, get flags() { return this.getUint16(6, true) / 10; }, get isEncrypted() { return !!(this.flags & (1 << 0)); }, get usesCompressionOption1() { return !!(this.flags & (1 << 1)); }, get usesCompressionOption2() { return !!(this.flags & (1 << 2)); }, get hasDataDescriptor() { return !!(this.flags & (1 << 3)); }, get hasEnhancedDeflation() { return !!(this.flags & (1 << 4)); }, get hasCompressedPatchedData() { return !!(this.flags & (1 << 5)); }, get hasStrongEncryption() { return !!(this.flags & (1 << 6)); }, get hasLanguageEncoding() { return !!(this.flags & (1 << 11)); }, get hasMaskHeaderValues() { return !!(this.flags & (1 << 13)); }, }; return open; });
Add some fields to local file header
Add some fields to local file header
JavaScript
mit
radishengine/drowsy,radishengine/drowsy
--- +++ @@ -1,10 +1,63 @@ -define(function() { +define(['msdos/util'], function(dosUtil) { 'use strict'; - function open(item) { - console.log(item); + function open() { + this.addExplorer(function(expedition) { + var pos = 0; + function onLocalFileHeader(bytes) { + var localFile = new LocalFileHeaderView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + if (!localFile.hasValidSignature) { + return expedition.abandon('invalid Local File Header signature'); + } + + } + this.byteSource.slice(pos, pos + 0x1d).then(onLocalFileHeader); + }); } + + function LocalFileHeaderView(buffer, byteOffset, byteLength) { + this.dataView = new DataView(buffer, byteOffset, byteLength); + this.bytes = new Uint8Array(buffer, byteOffset, byteLength); + } + LocalFileHeaderView.prototype = { + get hasValidSignature() { + return String.fromCharCode.apply(null, this.bytes.subarray(0, 4)) === 'PK\3\4'; + }, + get version() { + return this.getUint16(4, true) / 10; + }, + get flags() { + return this.getUint16(6, true) / 10; + }, + get isEncrypted() { + return !!(this.flags & (1 << 0)); + }, + get usesCompressionOption1() { + return !!(this.flags & (1 << 1)); + }, + get usesCompressionOption2() { + return !!(this.flags & (1 << 2)); + }, + get hasDataDescriptor() { + return !!(this.flags & (1 << 3)); + }, + get hasEnhancedDeflation() { + return !!(this.flags & (1 << 4)); + }, + get hasCompressedPatchedData() { + return !!(this.flags & (1 << 5)); + }, + get hasStrongEncryption() { + return !!(this.flags & (1 << 6)); + }, + get hasLanguageEncoding() { + return !!(this.flags & (1 << 11)); + }, + get hasMaskHeaderValues() { + return !!(this.flags & (1 << 13)); + }, + }; return open;
710f79a9aba647161fca92d79af554d412fa25e8
snippets/action-search/search-action.js
snippets/action-search/search-action.js
var page = tabris.create("Page", { title: "Actions", topLevel: true }); var proposals = ["baseball", "batman", "battleship", "bangkok", "bangladesh", "banana"]; var textView = tabris.create("TextView", { layoutData: {centerX: 0, centerY: 0} }).appendTo(page); var action = tabris.create("SearchAction", { title: "Search", image: "images/search.png" }).on("select", function() { this.set("text", ""); }).on("input", function(widget, query) { updateProposals(query); }).on("accept", function(widget, query) { textView.set("text", "Selected '" + query + "'"); }); updateProposals(""); tabris.create("Button", { text: "Open Search", layoutData: {centerX: 0, centerY: 0} }).on("select", function() { action.open(); }).appendTo(page); page.open(); function updateProposals(query) { action.set("proposals", proposals.filter(function(proposal) { return proposal.indexOf(query.toLowerCase()) !== -1; })); }
var page = tabris.create("Page", { title: "Actions", topLevel: true }); var proposals = ["baseball", "batman", "battleship", "bangkok", "bangladesh", "banana"]; var searchBox = tabris.create("Composite", { layoutData: {centerX: 0, centerY: 0} }).appendTo(page); var textView = tabris.create("TextView").appendTo(searchBox); var action = tabris.create("SearchAction", { title: "Search", image: "images/search.png" }).on("select", function() { this.set("text", ""); }).on("input", function(widget, query) { updateProposals(query); }).on("accept", function(widget, query) { textView.set("text", "Selected '" + query + "'"); }); updateProposals(""); tabris.create("Button", { text: "Open Search", centerX: 0, top: "prev() 10" }).on("select", function() { action.open(); }).appendTo(searchBox); page.open(); function updateProposals(query) { action.set("proposals", proposals.filter(function(proposal) { return proposal.indexOf(query.toLowerCase()) !== -1; })); }
Fix search action snippet layout
Fix search action snippet layout "Selected '...'" text was behind the button as both were centered horizontally and vertically on the screen. Wrap them in a centered container instead. Change-Id: I71ee80f5b7ba00cdb3cbf279c8fd1a413746ef28
JavaScript
bsd-3-clause
eclipsesource/tabris-js,eclipsesource/tabris-js,eclipsesource/tabris-js
--- +++ @@ -5,9 +5,11 @@ var proposals = ["baseball", "batman", "battleship", "bangkok", "bangladesh", "banana"]; -var textView = tabris.create("TextView", { +var searchBox = tabris.create("Composite", { layoutData: {centerX: 0, centerY: 0} }).appendTo(page); + +var textView = tabris.create("TextView").appendTo(searchBox); var action = tabris.create("SearchAction", { title: "Search", @@ -24,10 +26,11 @@ tabris.create("Button", { text: "Open Search", - layoutData: {centerX: 0, centerY: 0} + centerX: 0, + top: "prev() 10" }).on("select", function() { action.open(); -}).appendTo(page); +}).appendTo(searchBox); page.open();
72b64f7e83fdfb1a20311b86e271359529dc4abf
sencha-workspace/SlateAdmin/app/view/progress/interims/Manager.js
sencha-workspace/SlateAdmin/app/view/progress/interims/Manager.js
Ext.define('SlateAdmin.view.progress.interims.Manager', { extend: 'Ext.Container', xtype: 'progress-interims-manager', requires: [ 'SlateAdmin.view.progress.interims.SectionsGrid', 'SlateAdmin.view.progress.interims.StudentsGrid', 'SlateAdmin.view.progress.interims.EditorForm' ], layout: 'border', componentCls: 'progress-interims-manager', items: [ { region: 'west', weight: 100, split: true, xtype: 'progress-interims-sectionsgrid' }, { region: 'center', xtype: 'progress-interims-studentsgrid', disabled: true }, { region: 'east', split: true, weight: 100, flex: 1, xtype: 'progress-interims-editorform', disabled: true } ] });
Ext.define('SlateAdmin.view.progress.interims.Manager', { extend: 'Ext.Container', xtype: 'progress-interims-manager', requires: [ 'SlateAdmin.view.progress.interims.SectionsGrid', 'SlateAdmin.view.progress.interims.StudentsGrid', 'SlateAdmin.view.progress.interims.EditorForm', 'SlateAdmin.view.progress.SectionNotesForm' ], layout: 'border', componentCls: 'progress-interims-manager', items: [ { region: 'west', weight: 100, split: true, xtype: 'progress-interims-sectionsgrid' }, { region: 'center', xtype: 'progress-interims-studentsgrid', disabled: true }, { region: 'east', split: true, weight: 100, flex: 1, xtype: 'progress-interims-editorform', disabled: true }, { region: 'south', split: true, xtype: 'progress-sectionnotesform', fieldName: 'InterimReportNotes', collapsible: true, collapsed: true, titleCollapse: true, stateful: true, stateId: 'progress-interims-sectionnotesform', disabled: true } ] });
Add section notes form to interims manager
Add section notes form to interims manager
JavaScript
mit
SlateFoundation/slate-admin,SlateFoundation/slate,SlateFoundation/slate,SlateFoundation/slate-admin,SlateFoundation/slate-admin,SlateFoundation/slate,SlateFoundation/slate-admin,SlateFoundation/slate,SlateFoundation/slate-admin,SlateFoundation/slate
--- +++ @@ -4,7 +4,8 @@ requires: [ 'SlateAdmin.view.progress.interims.SectionsGrid', 'SlateAdmin.view.progress.interims.StudentsGrid', - 'SlateAdmin.view.progress.interims.EditorForm' + 'SlateAdmin.view.progress.interims.EditorForm', + 'SlateAdmin.view.progress.SectionNotesForm' ], @@ -32,6 +33,19 @@ xtype: 'progress-interims-editorform', disabled: true + }, + { + region: 'south', + split: true, + + xtype: 'progress-sectionnotesform', + fieldName: 'InterimReportNotes', + collapsible: true, + collapsed: true, + titleCollapse: true, + stateful: true, + stateId: 'progress-interims-sectionnotesform', + disabled: true } ] });
df3a6e16525e2764ea018a48bc178ff75c0bb467
test/spec/element/value.spec.js
test/spec/element/value.spec.js
describe("value", function() { "use strict"; var div, input; beforeEach(function() { div = DOM.create("div>a+a"); input = DOM.create("input[value=foo]"); }); it("should replace child element(s) from node with provided element", function() { expect(div[0].childNodes.length).toBe(2); expect(div.value(DOM.create("b"))).toBe(div); expect(div[0].childNodes.length).toBe(1); expect(div.child(0)).toHaveTag("b"); }); it("should return innerHTML string from node when called with no args", function() { expect(div.value()).toBe("<a></a><a></a>"); }); it("should set value of text input to provided string value", function () { expect(input.value("bar")).toBe(input); expect(input[0].value).toBe("bar"); }); });
describe("value", function() { "use strict"; var div, input; beforeEach(function() { div = DOM.create("div>a+a"); input = DOM.create("input[value=foo]"); }); it("should replace child element(s) from node with provided element", function() { expect(div[0].childNodes.length).toBe(2); expect(div.value(DOM.create("b"))).toBe(div); expect(div[0].childNodes.length).toBe(1); expect(div.child(0)).toHaveTag("b"); }); it("should return innerHTML string from node when called with no args", function() { expect(div.value()).toBe("<a></a><a></a>"); }); it("should set value of text input to provided string value", function () { expect(input.value("bar")).toBe(input); expect(input[0].value).toBe("bar"); }); it("should set value of text input to string value of provided element", function () { expect(input.value(DOM.create("div"))).toBe(input); expect(input[0].value).toBe("<div>"); expect(input[0].childNodes.length).toBe(0); }); });
Add failing test case regarding input.value($Element)
Add failing test case regarding input.value($Element)
JavaScript
mit
suenot/better-dom,suenot/better-dom,chemerisuk/better-dom,chemerisuk/better-dom
--- +++ @@ -24,5 +24,11 @@ expect(input[0].value).toBe("bar"); }); + it("should set value of text input to string value of provided element", function () { + expect(input.value(DOM.create("div"))).toBe(input); + expect(input[0].value).toBe("<div>"); + expect(input[0].childNodes.length).toBe(0); + }); + });
5206759e482853b788126022ef4682958dccec30
lib/fs/copy.js
lib/fs/copy.js
// Copy file // Credit: Isaac Schlueter // http://groups.google.com/group/nodejs/msg/ef4de0b516f7d5b8 'use strict'; var util = require('util') , fs = require('fs'); module.exports = function (source, dest, cb) { fs.lstat(source, function (err, stats) { var read; if (err) { cb(err); return; } try { util.pump(fs.createReadStream(source), fs.createWriteStream(dest, { mode: stats.mode }), cb); } catch (e) { cb(e); } }); };
// Copy file // Credit: Isaac Schlueter // http://groups.google.com/group/nodejs/msg/ef4de0b516f7d5b8 'use strict'; var util = require('util') , fs = require('fs') , stat = fs.stat, createReadStream = fs.createReadStream , createWriteStream = fs.createWriteStream module.exports = function (source, dest, cb) { stat(source, function (err, stats) { var stream; if (err) { cb(err); return; } try { stream = createReadStream(source); stream.on('error', cb) stream.pipe(createWriteStream(dest, { mode: stats.mode })); stream.on('end', cb); } catch (e) { cb(e); } }); };
Use pipe instead util.pump for file streaming
Use pipe instead util.pump for file streaming
JavaScript
mit
medikoo/node-ext
--- +++ @@ -5,18 +5,23 @@ 'use strict'; var util = require('util') - , fs = require('fs'); + , fs = require('fs') + + , stat = fs.stat, createReadStream = fs.createReadStream + , createWriteStream = fs.createWriteStream module.exports = function (source, dest, cb) { - fs.lstat(source, function (err, stats) { - var read; + stat(source, function (err, stats) { + var stream; if (err) { cb(err); return; } try { - util.pump(fs.createReadStream(source), - fs.createWriteStream(dest, { mode: stats.mode }), cb); + stream = createReadStream(source); + stream.on('error', cb) + stream.pipe(createWriteStream(dest, { mode: stats.mode })); + stream.on('end', cb); } catch (e) { cb(e); }
449e510f861f56ed673613d8102f6b1a3e680ced
lib/default-encoding.js
lib/default-encoding.js
var defaultEncoding /* istanbul ignore next */ if (process.browser) { defaultEncoding = 'utf-8' } else if (process.version) { var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' } else { defaultEncoding = 'utf-8' } module.exports = defaultEncoding
var defaultEncoding /* istanbul ignore next */ if (global.process && global.process.browser) { defaultEncoding = 'utf-8' } else if (global.process && global.process.version) { var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' } else { defaultEncoding = 'utf-8' } module.exports = defaultEncoding
Check for process before accessing
Check for process before accessing
JavaScript
mit
crypto-browserify/pbkdf2,crypto-browserify/pbkdf2
--- +++ @@ -1,8 +1,8 @@ var defaultEncoding /* istanbul ignore next */ -if (process.browser) { +if (global.process && global.process.browser) { defaultEncoding = 'utf-8' -} else if (process.version) { +} else if (global.process && global.process.version) { var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'
283cce3b70e3a71279bbc805c973fd5d6e8b0aa2
test/support/config.js
test/support/config.js
var _ = require('underscore'); module.exports = function(opts) { var config = { redis_pool: { max: 10, idleTimeoutMillis: 1, reapIntervalMillis: 1, port: 6336 } } _.extend(config, opts || {}); return config; }();
var _ = require('underscore'); module.exports = function(opts) { var config = { redis_pool: { max: 10, idleTimeoutMillis: 1, reapIntervalMillis: 1, port: 6337 } } _.extend(config, opts || {}); return config; }();
Use port 6337 for the test redis server
Use port 6337 for the test redis server
JavaScript
bsd-3-clause
CartoDB/node-redis-mpool
--- +++ @@ -7,7 +7,7 @@ max: 10, idleTimeoutMillis: 1, reapIntervalMillis: 1, - port: 6336 + port: 6337 } }
40f242103e201c0c8c2cb94d3b0b74d259ec52ef
examples/jsx-seconds-elapsed/src/main.js
examples/jsx-seconds-elapsed/src/main.js
/** @jsx hJSX */ import {run, Rx} from '@cycle/core'; import {makeDOMDriver, hJSX} from '@cycle/dom'; function main(drivers) { let secondsElapsed$ = Rx.Observable.interval(1000) .map(i => i + 1) .startWith(0); let vtree$ = secondsElapsed$.map(secondsElapsed => <div>{`Seconds elapsed ${secondsElapsed}`}</div> ); return {DOM: vtree$}; } let drivers = { DOM: makeDOMDriver('#main-container') }; run(main, drivers);
/** @jsx hJSX */ import {run, Rx} from '@cycle/core'; import {makeDOMDriver, hJSX} from '@cycle/dom'; function main(drivers) { let secondsElapsed$ = Rx.Observable.interval(1000) .map(i => i + 1) .startWith(0); let vtree$ = secondsElapsed$.map(secondsElapsed => <div>Seconds elapsed {secondsElapsed}</div> ); return {DOM: vtree$}; } let drivers = { DOM: makeDOMDriver('#main-container') }; run(main, drivers);
Improve code style in jsx-seconds-elapsed example
Improve code style in jsx-seconds-elapsed example
JavaScript
mit
cyclejs/cyclejs,usm4n/cyclejs,maskinoshita/cyclejs,ntilwalli/cyclejs,feliciousx-open-source/cyclejs,usm4n/cyclejs,ntilwalli/cyclejs,staltz/cycle,ntilwalli/cyclejs,maskinoshita/cyclejs,usm4n/cyclejs,cyclejs/cyclejs,feliciousx-open-source/cyclejs,maskinoshita/cyclejs,cyclejs/cycle-core,maskinoshita/cyclejs,cyclejs/cyclejs,ntilwalli/cyclejs,staltz/cycle,feliciousx-open-source/cyclejs,feliciousx-open-source/cyclejs,cyclejs/cycle-core,usm4n/cyclejs,cyclejs/cyclejs
--- +++ @@ -7,7 +7,7 @@ .map(i => i + 1) .startWith(0); let vtree$ = secondsElapsed$.map(secondsElapsed => - <div>{`Seconds elapsed ${secondsElapsed}`}</div> + <div>Seconds elapsed {secondsElapsed}</div> ); return {DOM: vtree$}; }
40403c636b6ca29e01dff10b0e761389c8f07468
app/scripts/app.js
app/scripts/app.js
/*global angular */ /*jslint browser: true */ (function () { 'use strict'; var app; app = angular.module('thin.gsApp', ['ngRoute', 'ngSanitize', 'alerts', 'auth']) .config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl' }) .otherwise({ redirectTo: '/' }); $locationProvider.html5Mode(true); $locationProvider.hashPrefix('!'); }]); app.run(function ($rootScope, Facebook, alert) { $rootScope.Facebook = Facebook; }); }());
/*global angular */ /*jslint browser: true */ (function () { 'use strict'; var app; app = angular.module('thin.gsApp', ['ngRoute', 'ngSanitize', 'alerts', 'auth']) .config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl' }) .otherwise({ redirectTo: '/' }); $locationProvider.html5Mode(true); $locationProvider.hashPrefix('!'); }]); app.run(function ($rootScope, userService, alert) { $rootScope.userService = userService; }); }());
Rename the Facebook service to userService
Rename the Facebook service to userService Signed-off-by: Henrique Vicente <d390f26e2f50ad5716a9c69c58de1f5df9730e3b@gmail.com>
JavaScript
mit
henvic/thin.gs
--- +++ @@ -21,8 +21,8 @@ $locationProvider.hashPrefix('!'); }]); - app.run(function ($rootScope, Facebook, alert) { - $rootScope.Facebook = Facebook; + app.run(function ($rootScope, userService, alert) { + $rootScope.userService = userService; }); }());
c270660572ec7a79c110b65622c4d14aad0c117b
meteor/server/server.js
meteor/server/server.js
//TODO setup deploySettings.json Meteor.startup(function () { var githubServiceSetup = Accounts.loginServiceConfiguration.find({service: "github"}).count() === 1; if (githubServiceSetup) { //setup authentication Provider Accounts.loginServiceConfiguration.remove({ service: "github" }); Accounts.loginServiceConfiguration.insert({ service: "github", clientId: Meteor.settings["GITHUB_CLIENTID"], secret: Meteor.settings["GITHUB_SECRET"] }); } });
Meteor.startup(function () { var githubServiceSetup = Accounts.loginServiceConfiguration.find({service: "github"}).count() === 1; if (!githubServiceSetup) { //setup authentication Provider Accounts.loginServiceConfiguration.remove({ service: "github" }); Accounts.loginServiceConfiguration.insert({ service: "github", clientId: Meteor.settings["GITHUB_CLIENTID"], secret: Meteor.settings["GITHUB_SECRET"] }); } });
Fix mistake where not adding github info when needed
Fix mistake where not adding github info when needed
JavaScript
agpl-3.0
codebounty/codebounty
--- +++ @@ -1,7 +1,6 @@ -//TODO setup deploySettings.json Meteor.startup(function () { var githubServiceSetup = Accounts.loginServiceConfiguration.find({service: "github"}).count() === 1; - if (githubServiceSetup) { + if (!githubServiceSetup) { //setup authentication Provider Accounts.loginServiceConfiguration.remove({ service: "github"
c3d2b30dc74391b221665849f2a32fb4c6f0ad30
proxy/server.js
proxy/server.js
var proxy = require('redbird')({port: 8080}); proxy.register('localhost/event/api/user', "http://localhost:3001/user");
var proxy = require('redbird')({port: 8080}); proxy.register('localhost/event', 'http://localhost:3000'); proxy.register('localhost/event/api/user', 'http://localhost:3001/user'); proxy.register('localhost/event/api/session', 'http://localhost:3002/session'); proxy.register('localhost/event/api/file', 'http://localhost:3003/file');
Add API and frontend routes
Add API and frontend routes
JavaScript
mit
haimich/event,haimich/event,haimich/event
--- +++ @@ -1,3 +1,6 @@ var proxy = require('redbird')({port: 8080}); -proxy.register('localhost/event/api/user', "http://localhost:3001/user"); +proxy.register('localhost/event', 'http://localhost:3000'); +proxy.register('localhost/event/api/user', 'http://localhost:3001/user'); +proxy.register('localhost/event/api/session', 'http://localhost:3002/session'); +proxy.register('localhost/event/api/file', 'http://localhost:3003/file');
cbacc31ddebbd2b7c8d3a809d55739ccfca962a6
tools/tool-env/install-babel.js
tools/tool-env/install-babel.js
// This file exists because it is the file in the tool that is not automatically // transpiled by Babel "use strict"; function babelRegister() { const meteorBabel = require("meteor-babel"); const path = require("path"); const toolsPath = path.dirname(__dirname); const meteorPath = path.dirname(toolsPath); const cacheDir = path.join(meteorPath, ".babel-cache"); const babelOptions = meteorBabel.getDefaultOptions({ nodeMajorVersion: parseInt(process.versions.node) }); meteorBabel.setCacheDir(cacheDir); require('meteor-babel/register') .allowDirectory(toolsPath) .setSourceMapRootPath(meteorPath) .setBabelOptions(babelOptions); } babelRegister(); // #RemoveInProd this line is removed in isopack.js require("./install-runtime.js");
// This file exists because it is the file in the tool that is not automatically // transpiled by Babel "use strict"; function babelRegister() { const meteorBabel = require("meteor-babel"); const path = require("path"); const toolsPath = path.dirname(__dirname); const meteorPath = path.dirname(toolsPath); const cacheDir = path.join(meteorPath, ".babel-cache"); const babelOptions = meteorBabel.getDefaultOptions({ nodeMajorVersion: parseInt(process.versions.node) }); // Make sure that source maps are included in the generated code for // meteor/tools modules. babelOptions.sourceMap = "inline"; meteorBabel.setCacheDir(cacheDir); require('meteor-babel/register') .allowDirectory(toolsPath) .setSourceMapRootPath(meteorPath) .setBabelOptions(babelOptions); } babelRegister(); // #RemoveInProd this line is removed in isopack.js require("./install-runtime.js");
Fix inline source maps in meteor/tools code.
Fix inline source maps in meteor/tools code.
JavaScript
mit
Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor
--- +++ @@ -13,6 +13,10 @@ nodeMajorVersion: parseInt(process.versions.node) }); + // Make sure that source maps are included in the generated code for + // meteor/tools modules. + babelOptions.sourceMap = "inline"; + meteorBabel.setCacheDir(cacheDir); require('meteor-babel/register')
754071878da574b3912710d7ea2a681bcc2a74bb
src/components/MenuScreen/MenuScreen.js
src/components/MenuScreen/MenuScreen.js
import React from "react"; import Container from "./Container.js"; import Button from "./../Shared/Button.js"; import setCurrentScreenAction from "../../actions/ScreenActions.js"; import { GAME_SCREEN } from "../../actions/ScreenActions.js"; const screenTitle = "Tic Tac Toe React"; const MenuScreen = React.createClass({ PropTypes: { dispatch: React.PropTypes.func.isRequired }, headerStyle: { textAlign: "center", color: "white" }, render () { return ( <Container> <h1 style={this.headerStyle}> {screenTitle} </h1> <Button onClick={() => this.props.dispatch( setCurrentScreenAction(GAME_SCREEN) )} text="Play with Human" useWrapper /> <h2 style={this.headerStyle}> {"Play with computer"} </h2> <Button buttonClickHandler={()=>1} text="EASY" useWrapper /> <Button buttonClickHandler={()=>1} text="MEDIUM" useWrapper /> <Button buttonClickHandler={()=>1} text="HARD" useWrapper /> </Container> ); } }); export default MenuScreen;
import React from "react"; import Container from "./Container.js"; import Button from "./../Shared/Button.js"; import setCurrentScreenAction from "../../actions/ScreenActions.js"; import { GAME_SCREEN } from "../../actions/ScreenActions.js"; import {setGameModeAction} from "../../actions/GameActions.js"; import {VS_HUMAN, EASY, MEDIUM, HARD} from "../../reducers/Game.js"; const screenTitle = "Tic Tac Toe React"; const MenuScreen = React.createClass({ PropTypes: { dispatch: React.PropTypes.func.isRequired }, headerStyle: { textAlign: "center", color: "white" }, render () { return ( <Container> <h1 style={this.headerStyle}> {screenTitle} </h1> <Button onClick={() => { this.props.dispatch(setCurrentScreenAction(GAME_SCREEN)) this.props.dispatch(setGameModeAction(VS_HUMAN)); } } text="Play with Human" useWrapper /> <h2 style={this.headerStyle}> {"Play with computer"} </h2> <Button onClick={() => { this.props.dispatch(setCurrentScreenAction(GAME_SCREEN)) this.props.dispatch(setGameModeAction(EASY)); } } text="EASY" useWrapper /> <Button onClick={() => { this.props.dispatch(setCurrentScreenAction(GAME_SCREEN)) this.props.dispatch(setGameModeAction(MEDIUM)); } } text="MEDIUM" useWrapper /> <Button onClick={() => { this.props.dispatch(setCurrentScreenAction(GAME_SCREEN)) this.props.dispatch(setGameModeAction(HARD)); } } text="HARD" useWrapper /> </Container> ); } }); export default MenuScreen;
Add actions to start vs computer
Add actions to start vs computer Change onClick action handlers for buttons
JavaScript
mit
Lingvokot/Tic-Tac-Toe-React,Lingvokot/Tic-Tac-Toe-React,Lingvokot/Tic-Tac-Toe-React
--- +++ @@ -5,6 +5,9 @@ import setCurrentScreenAction from "../../actions/ScreenActions.js"; import { GAME_SCREEN } from "../../actions/ScreenActions.js"; + +import {setGameModeAction} from "../../actions/GameActions.js"; +import {VS_HUMAN, EASY, MEDIUM, HARD} from "../../reducers/Game.js"; const screenTitle = "Tic Tac Toe React"; @@ -24,24 +27,38 @@ <h1 style={this.headerStyle}> {screenTitle} </h1> - <Button onClick={() => this.props.dispatch( - setCurrentScreenAction(GAME_SCREEN) - )} + <Button onClick={() => { + this.props.dispatch(setCurrentScreenAction(GAME_SCREEN)) + this.props.dispatch(setGameModeAction(VS_HUMAN)); + } + } text="Play with Human" useWrapper /> <h2 style={this.headerStyle}> {"Play with computer"} </h2> - <Button buttonClickHandler={()=>1} + <Button onClick={() => { + this.props.dispatch(setCurrentScreenAction(GAME_SCREEN)) + this.props.dispatch(setGameModeAction(EASY)); + } + } text="EASY" useWrapper /> - <Button buttonClickHandler={()=>1} + <Button onClick={() => { + this.props.dispatch(setCurrentScreenAction(GAME_SCREEN)) + this.props.dispatch(setGameModeAction(MEDIUM)); + } + } text="MEDIUM" useWrapper /> - <Button buttonClickHandler={()=>1} + <Button onClick={() => { + this.props.dispatch(setCurrentScreenAction(GAME_SCREEN)) + this.props.dispatch(setGameModeAction(HARD)); + } + } text="HARD" useWrapper />
4446bd48ebd8ced9f5001b202b8d0fa2b8b36a74
server/src/connectors/carriots.module.js
server/src/connectors/carriots.module.js
"use strict"; let https = require('https'); let keys = require("./secretKeys.js"); exports.init = function (mainCallback) { let options = { host: "api.carriots.com", path: "/streams/?max=1&order=-1", port: 443, method: "GET", headers: { "Accept": "application/json", "carriots.apiKey": keys.CARRIOTS_APIKEY, "Connection": "keep-alive", "Content-Type": "application/json", "Host": "api.carriots.com" } }; setInterval(function () { let req = https.request(options, (res) => { res.on('data', (chunk) => { let body = []; body.push(chunk); let msg = JSON.parse(body.toString()); if (undefined !== msg && undefined !== msg.result) { let data = msg.result[0].data; mainCallback(data.sender, data.quantity, "Carriots"); } }); }); req.on('error', (e) => { console.error(e); }); req.end(); }, 10000); };
"use strict"; let https = require('https'); let keys = require("./secretKeys.js"); exports.init = function (mainCallback) { let options = { host: "api.carriots.com", path: "/streams/?max=1&order=-1", port: 443, method: "GET", headers: { "Accept": "application/json", "carriots.apiKey": keys.CARRIOTS_APIKEY, "Connection": "keep-alive", "Content-Type": "application/json", "Host": "api.carriots.com" } }; setInterval(function () { let req = https.request(options, (res) => { res.on('data', (chunk) => { let body = []; body.push(chunk); let msg = JSON.parse(body.toString()); if (undefined !== msg && undefined !== msg.result) { let data = msg.result[0].data; mainCallback(data.sender, data.quantity, "Carriots"); } }); }); req.on('error', (e) => { console.error(e); }); req.end(); }, 5000); };
Set interval to 5 seconds instead of 10
Set interval to 5 seconds instead of 10
JavaScript
mit
Zenika/bottleopener_iot,Zenika/bottleopener_iot,Zenika/bottleopener_iot,Zenika/bottleopener_iot
--- +++ @@ -39,6 +39,6 @@ }); req.end(); - }, 10000); + }, 5000); };
5e1316ee48816cab9c2d8eec9c31b5054d0d801a
app/core/services/ledger-nano.js
app/core/services/ledger-nano.js
/* global angular, require */ import 'ionic-sdk/release/js/ionic.bundle'; import platformInfo from './platform-info.js'; angular.module('app.service.ledger-nano', []) .factory('LedgerNano', function ($q) { 'use strict'; let StellarLedger; if (platformInfo.isElectron) { const electron = require('electron'); StellarLedger = electron.remote.require('stellar-ledger-api'); } const bip32Path = (index) => `44'/148'/${index}'`; const wrapper = (func, field) => $q((resolve, reject) => { StellarLedger.comm.create_async() .then(comm => { const api = new StellarLedger.Api(comm); func(api) .then(result => resolve(result[field])) .catch(err => reject(err)) .done(() => comm.close_async()); }) .catch(err => reject(err)); }); const getPublicKey = (index) => { const func = api => api.getPublicKey_async(bip32Path(index)) return wrapper(func, 'publicKey'); }; const signTxHash = (index, txHash) => { const func = api => api.signTxHash_async(bip32Path(index), txHash); return wrapper(func, 'signature'); }; // No Device // Invalid status 6d00 wrong app return { getPublicKey: getPublicKey, signTxHash: signTxHash }; });
/* global require */ import platformInfo from './platform-info.js'; let StellarLedger; if (platformInfo.isElectron) { const electron = require('electron'); StellarLedger = electron.remote.require('stellar-ledger-api'); } const bip32Path = (index) => `44'/148'/${index}'`; const wrapper = (func, field) => new Promise((resolve, reject) => { StellarLedger.comm.create_async() .then(comm => { const api = new StellarLedger.Api(comm); func(api) .then(result => resolve(result[field])) .catch(err => reject(err)) .done(() => comm.close_async()); }) .catch(err => reject(err)); }); const getPublicKey = (index) => { const func = api => api.getPublicKey_async(bip32Path(index)); return wrapper(func, 'publicKey'); }; const signTxHash = (index, txHash) => { const func = api => api.signTxHash_async(bip32Path(index), txHash); return wrapper(func, 'signature'); }; // No Device // Invalid status 6d00 wrong app export default { getPublicKey: getPublicKey, signTxHash: signTxHash };
Use native Promise instead of $q
Use native Promise instead of $q
JavaScript
agpl-3.0
johansten/stargazer,johansten/stargazer,johansten/stargazer
--- +++ @@ -1,47 +1,41 @@ -/* global angular, require */ +/* global require */ -import 'ionic-sdk/release/js/ionic.bundle'; import platformInfo from './platform-info.js'; -angular.module('app.service.ledger-nano', []) -.factory('LedgerNano', function ($q) { - 'use strict'; +let StellarLedger; +if (platformInfo.isElectron) { + const electron = require('electron'); + StellarLedger = electron.remote.require('stellar-ledger-api'); +} - let StellarLedger; - if (platformInfo.isElectron) { - const electron = require('electron'); - StellarLedger = electron.remote.require('stellar-ledger-api'); - } +const bip32Path = (index) => `44'/148'/${index}'`; - const bip32Path = (index) => `44'/148'/${index}'`; +const wrapper = (func, field) => new Promise((resolve, reject) => { + StellarLedger.comm.create_async() + .then(comm => { + const api = new StellarLedger.Api(comm); + func(api) + .then(result => resolve(result[field])) + .catch(err => reject(err)) + .done(() => comm.close_async()); + }) + .catch(err => reject(err)); +}); - const wrapper = (func, field) => $q((resolve, reject) => { - StellarLedger.comm.create_async() - .then(comm => { - const api = new StellarLedger.Api(comm); - func(api) - .then(result => resolve(result[field])) - .catch(err => reject(err)) - .done(() => comm.close_async()); - }) - .catch(err => reject(err)); - }); +const getPublicKey = (index) => { + const func = api => api.getPublicKey_async(bip32Path(index)); + return wrapper(func, 'publicKey'); +}; - const getPublicKey = (index) => { - const func = api => api.getPublicKey_async(bip32Path(index)) - return wrapper(func, 'publicKey'); - }; +const signTxHash = (index, txHash) => { + const func = api => api.signTxHash_async(bip32Path(index), txHash); + return wrapper(func, 'signature'); +}; - const signTxHash = (index, txHash) => { - const func = api => api.signTxHash_async(bip32Path(index), txHash); - return wrapper(func, 'signature'); - }; +// No Device +// Invalid status 6d00 wrong app - // No Device - // Invalid status 6d00 wrong app - - return { - getPublicKey: getPublicKey, - signTxHash: signTxHash - }; -}); +export default { + getPublicKey: getPublicKey, + signTxHash: signTxHash +};
ee805b8617ecbc03cef0c421124bb799890b9ef8
app/utils/service-colors.js
app/utils/service-colors.js
export default { 'CORE - METRORAIL': 'red', 'CORE - METRORAPID': '#f24d6e', 'CORE - LIMITED': '#649dce', 'CORE - RADIAL': '#5190c8', 'CORE - FEEDER': '#3d84c2', 'CORE - EXPRESS/FLYERS': '#3777ae', 'CORE - CROSSTOWN': '#77a9d4', 'SPECIAL - REVERSE COMMUTE': '#6c9452', 'SPECIAL - RAIL CONNECTORS': '#4b874b', 'SPECIAL - EBUS': '#42775b', 'SPECIAL - NIGHT OWLS': '#7ec87e', 'SPECIAL - SENIOR': '#70b18e', 'UT - CIRCULATORS': '#ffbb4f', 'UT - RADIALS': '#af823c' }
export default { 'CORE - METRORAIL': 'red', 'CORE - METRORAPID': '#f24d6e', 'CORE - LIMITED': '#1D86A4', 'CORE - RADIAL': '#053862', 'CORE - FEEDER': '#72C6DE', 'CORE - EXPRESS/FLYERS': '#42A7C3', 'CORE - CROSSTOWN': '#105FA0', 'SPECIAL - REVERSE COMMUTE': '#6c9452', 'SPECIAL - RAIL CONNECTORS': '#4b874b', 'SPECIAL - EBUS': '#42775b', 'SPECIAL - NIGHT OWLS': '#7ec87e', 'SPECIAL - SENIOR': '#70b18e', 'UT - CIRCULATORS': '#ffbb4f', 'UT - RADIALS': '#af823c' }
Increase contrast and color variation.
Increase contrast and color variation.
JavaScript
mit
jga/capmetrics-web,jga/capmetrics-web
--- +++ @@ -1,11 +1,11 @@ export default { 'CORE - METRORAIL': 'red', 'CORE - METRORAPID': '#f24d6e', - 'CORE - LIMITED': '#649dce', - 'CORE - RADIAL': '#5190c8', - 'CORE - FEEDER': '#3d84c2', - 'CORE - EXPRESS/FLYERS': '#3777ae', - 'CORE - CROSSTOWN': '#77a9d4', + 'CORE - LIMITED': '#1D86A4', + 'CORE - RADIAL': '#053862', + 'CORE - FEEDER': '#72C6DE', + 'CORE - EXPRESS/FLYERS': '#42A7C3', + 'CORE - CROSSTOWN': '#105FA0', 'SPECIAL - REVERSE COMMUTE': '#6c9452', 'SPECIAL - RAIL CONNECTORS': '#4b874b', 'SPECIAL - EBUS': '#42775b',
fd1fcc6f35f2e36290fe1143edcea2334e079267
app/assets/javascripts/_analytics.js
app/assets/javascripts/_analytics.js
(function() { "use strict"; GOVUK.Tracker.load(); var cookieDomain = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : document.domain; var property = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? 'UA-49258698-1' : 'UA-49258698-3'; GOVUK.analytics = new GOVUK.Analytics({ universalId: property, cookieDomain: cookieDomain }); GOVUK.analytics.trackPageview(); })();
(function() { "use strict"; GOVUK.Analytics.load(); var cookieDomain = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : document.domain; var property = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? 'UA-49258698-1' : 'UA-49258698-3'; // wrapper function for calls to window.ga, used by all Google Analytics trackers function sendToGa() { if (typeof window.ga === "function") { ga.apply(window, arguments); } } // Rewritten universal tracker to allow setting of the autoLinker property var DMGoogleAnalyticsUniversalTracker = function(id, cookieDomain) { configureProfile(id, cookieDomain); anonymizeIp(); function configureProfile(id, cookieDomain) { sendToGa('create', id, {'cookieDomain': cookieDomain, 'allowLinker': true }); } function anonymizeIp() { // https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#anonymizeip sendToGa('set', 'anonymizeIp', true); } }; DMGoogleAnalyticsUniversalTracker.prototype = GOVUK.GoogleAnalyticsUniversalTracker.prototype; GOVUK.GoogleAnalyticsUniversalTracker = DMGoogleAnalyticsUniversalTracker; GOVUK.analytics = new GOVUK.Analytics({ universalId: property, cookieDomain: cookieDomain }); GOVUK.analytics.trackPageview(); GOVUK.analytics.addLinkedTrackerDomain(property, 'link', 'digitalservicesstore.service.gov.uk'); })();
Patch GOVUK.Analytics to add 'allowLinker' option
Patch GOVUK.Analytics to add 'allowLinker' option The GOVUK.Analytics interface doesn't set the 'allowLinker' option when creating a ga tracker. In order to preserve a vendor-agnostic interface it also doesn't allow this to be sent through when creating a new GOVUK.Analytics instance. This commit patches GOVUK.GoogleAnalyticsUniversalTracker to include 'autoLinker' as a default option for all ga trackers.
JavaScript
mit
alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend
--- +++ @@ -1,11 +1,35 @@ (function() { "use strict"; - GOVUK.Tracker.load(); + GOVUK.Analytics.load(); var cookieDomain = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : document.domain; var property = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? 'UA-49258698-1' : 'UA-49258698-3'; + + // wrapper function for calls to window.ga, used by all Google Analytics trackers + function sendToGa() { + if (typeof window.ga === "function") { + ga.apply(window, arguments); + } + } + // Rewritten universal tracker to allow setting of the autoLinker property + var DMGoogleAnalyticsUniversalTracker = function(id, cookieDomain) { + configureProfile(id, cookieDomain); + anonymizeIp(); + + function configureProfile(id, cookieDomain) { + sendToGa('create', id, {'cookieDomain': cookieDomain, 'allowLinker': true }); + } + + function anonymizeIp() { + // https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#anonymizeip + sendToGa('set', 'anonymizeIp', true); + } + }; + DMGoogleAnalyticsUniversalTracker.prototype = GOVUK.GoogleAnalyticsUniversalTracker.prototype; + GOVUK.GoogleAnalyticsUniversalTracker = DMGoogleAnalyticsUniversalTracker; GOVUK.analytics = new GOVUK.Analytics({ universalId: property, cookieDomain: cookieDomain }); GOVUK.analytics.trackPageview(); + GOVUK.analytics.addLinkedTrackerDomain(property, 'link', 'digitalservicesstore.service.gov.uk'); })();