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
e5fb18d4a59e707f075d76310af2ec919ca5716c
src/modules/getPrice/index.js
src/modules/getPrice/index.js
import module from '../../module' import command from '../../components/command' import loader from '../../components/loader' import axios from 'axios' import humanize from '../../utils/humanize' export default module( loader(() => { console.log('test') }), command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => { try { const {data: itemData} = await axios.get( `https://esi.tech.ccp.is/latest/search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}` ); const itemid = itemData.inventorytype[0]; const {data: priceData} = await axios.get( `http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142` ); const sellFivePercent = humanize(priceData[0].sell.fivePercent); const buyFivePercent = humanize(priceData[0].buy.fivePercent); message.channel.sendMessage( `__Price of **${args}** (or nearest match) in Jita__:\n` + `**Sell**: ${sellFivePercent} ISK\n` + `**Buy**: ${buyFivePercent} ISK` ) } catch(e) { console.error(e); throw e } }) )
import module from '../../module' import command from '../../components/command' import loader from '../../components/loader' import axios from 'axios' import humanize from '../../utils/humanize' export default module( loader(() => { console.log('test') }), command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => { try { const esiURL = 'https://esi.tech.ccp.is/latest/'; const {data: itemData} = await axios.get( `${esiURL}search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}` ); const itemid = itemData.inventorytype[0]; const {data: priceData} = await axios.get( `http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142` ); const sellFivePercent = humanize(priceData[0].sell.fivePercent); const buyFivePercent = humanize(priceData[0].buy.fivePercent); message.channel.sendMessage( `__Price of **${args}** (or nearest match) in Jita__:\n` + `**Sell**: ${sellFivePercent} ISK\n` + `**Buy**: ${buyFivePercent} ISK` ) } catch(e) { console.error(e); throw e } }) )
Move ESI url prefix to variable
Move ESI url prefix to variable
JavaScript
mit
emensch/thonk9k
--- +++ @@ -10,8 +10,10 @@ }), command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => { try { + const esiURL = 'https://esi.tech.ccp.is/latest/'; + const {data: itemData} = await axios.get( - `https://esi.tech.ccp.is/latest/search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}` + `${esiURL}search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}` ); const itemid = itemData.inventorytype[0];
6801d288ec728671330a6881306753abd30e0a8f
app/student.front.js
app/student.front.js
const $answer = $('.answer') const {makeRichText} = require('./rich-text-editor') const save = ($elem, async = true) => $.post({ url: '/save', data: {text: $elem.html(), answerId: $elem.attr('id')}, async }) function saveScreenshot(questionId) { return ({data, type}) => { return $.post({ type: 'POST', url: `/saveImg?answerId=${questionId}`, data: data, processData: false, contentType: type }).then(res => { return res.url }) } } const richTextOptions = id => ({ screenshot: { saver: data => saveScreenshot(id)(data), limit: 10 } }) $answer.each((i, answer) => { makeRichText(answer, richTextOptions(answer.id)) $.get(`/load?answerId=${answer.id}`, data => data && $(answer).html(data.html)) }).on('keypress', e => { if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') { e.preventDefault() save($(e.target)) } }) $('#answer1').focus()
const $answer = $('.answer') const {makeRichText} = require('./rich-text-editor') const save = ($elem, async = true) => $.post({ url: '/save', data: {text: $elem.html(), answerId: $elem.attr('id')}, async }) function saveScreenshot(questionId) { return ({data, type}) => { return $.post({ type: 'POST', url: `/saveImg?answerId=${questionId}`, data: data, processData: false, contentType: type }).then(res => { return res.url }) } } const richTextOptions = id => ({ screenshot: { saver: data => saveScreenshot(id)(data), limit: 10 } }) $answer.each((i, answer) => { $.get(`/load?answerId=${answer.id}`, data => { data && $(answer).html(data.html) makeRichText(answer, richTextOptions(answer.id), onValueChange) }) }).on('keypress', e => { if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') { e.preventDefault() save($(e.target)) } }) $('#answer1').focus() function onValueChange() { }
Update answer content before initializing rich text
Update answer content before initializing rich text
JavaScript
mit
digabi/math-editor,digabi/rich-text-editor,digabi/rich-text-editor,digabi/rich-text-editor,digabi/math-editor
--- +++ @@ -28,8 +28,10 @@ }) $answer.each((i, answer) => { - makeRichText(answer, richTextOptions(answer.id)) - $.get(`/load?answerId=${answer.id}`, data => data && $(answer).html(data.html)) + $.get(`/load?answerId=${answer.id}`, data => { + data && $(answer).html(data.html) + makeRichText(answer, richTextOptions(answer.id), onValueChange) + }) }).on('keypress', e => { if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') { e.preventDefault() @@ -37,3 +39,7 @@ } }) $('#answer1').focus() + +function onValueChange() { + +}
d02ef235fb382ff749a41561518c18c7ebd81f2f
src/JokeMeUpBoy.js
src/JokeMeUpBoy.js
/** * Prints a random programmer joke. * @author Vitor Cortez <vitoracortez+github@gmail.com> */ var jokeMeUpBoy = function() { const jokes = getListOfJokes(); let rand = Math.floor(Math.random() * jokes.length); console.log(jokes[rand]); }; /** * Holds a list of classic programmer jokes. * Feel free to add a new joke each day. * @private */ function getListOfJokes() { var arr = []; arr.push('Q: How do you tell an introverted computer scientist from an extroverted computer scientist?\nA: An extroverted computer scientist looks at your shoes when he talks to you.'); return arr; } anything.prototype.JokeMeUpBoy = jokeMeUpBoy;
/** * Prints a random programmer joke. * @author Vitor Cortez <vitoracortez+github@gmail.com> */ var jokeMeUpBoy = function() { const jokes = getListOfJokes(); let rand = Math.floor(Math.random() * jokes.length); console.log(jokes[rand]); }; /** * Holds a list of classic programmer jokes. * Feel free to add a new joke each day. * @private */ function getListOfJokes() { var arr = []; arr.push('Q: How do you tell an introverted computer scientist from an extroverted computer scientist?\nA: An extroverted computer scientist looks at your shoes when he talks to you.'); arr.push('Q: Why do programmers always mix up Halloween and Christmas?\nA: Because Oct 31 == Dec 25!'); return arr; } anything.prototype.JokeMeUpBoy = jokeMeUpBoy;
Add a new dank joke
Add a new dank joke Dem jokes
JavaScript
mit
Rabrennie/anything.js,Sha-Grisha/anything.js,Rabrennie/anything.js,Rabrennie/anything.js,Rabrennie/anything.js,Sha-Grisha/anything.js,Sha-Grisha/anything.js,Sha-Grisha/anything.js
--- +++ @@ -16,6 +16,7 @@ function getListOfJokes() { var arr = []; arr.push('Q: How do you tell an introverted computer scientist from an extroverted computer scientist?\nA: An extroverted computer scientist looks at your shoes when he talks to you.'); + arr.push('Q: Why do programmers always mix up Halloween and Christmas?\nA: Because Oct 31 == Dec 25!'); return arr; }
86cef9310543200502e822cbfbc39066e3f91967
public/app/user-account/user-login/user-login-controller.js
public/app/user-account/user-login/user-login-controller.js
define(function() { var LoginController = function($location, AuthenticationService) { // reset login status AuthenticationService.clearCredentials(); this.login = function() { this.dataLoading = true; var self = this AuthenticationService.login(this.username, this.password) .success(function(userProfile, status) { AuthenticationService.setCredentials(self.username, self.password); $location.path('/'); }) .error(function(error, status) { self.error = error.message; self.dataLoading = false; }); }; } LoginController.$inject = ['$location', 'UserAuthenticationService'] return LoginController })
define(function() { var LoginController = function($location, $mdDialog, AuthenticationService) { // reset login status AuthenticationService.clearCredentials() this.login = function() { this.dataLoading = true var self = this AuthenticationService.login(this.username, this.password) .success(function(userProfile, status) { AuthenticationService.setCredentials(self.username, self.password) $location.path('/') }) .error(function(error, status) { self.dataLoading = false var alert = $mdDialog.alert({ title: 'We couldn\'t sign you in!', content: error.message, ok: 'Try again' }) $mdDialog.show(alert) }) } } LoginController.$inject = ['$location', '$mdDialog', 'UserAuthenticationService'] return LoginController })
Update login controller to display dialog on error
Update login controller to display dialog on error
JavaScript
mit
tenevdev/idiot,tenevdev/idiot
--- +++ @@ -1,27 +1,34 @@ define(function() { - var LoginController = function($location, AuthenticationService) { + var LoginController = function($location, $mdDialog, AuthenticationService) { - // reset login status - AuthenticationService.clearCredentials(); + // reset login status + AuthenticationService.clearCredentials() - this.login = function() { - this.dataLoading = true; + this.login = function() { + this.dataLoading = true - var self = this + var self = this - AuthenticationService.login(this.username, this.password) - .success(function(userProfile, status) { - AuthenticationService.setCredentials(self.username, self.password); - $location.path('/'); + AuthenticationService.login(this.username, this.password) + .success(function(userProfile, status) { + AuthenticationService.setCredentials(self.username, self.password) + $location.path('/') + }) + .error(function(error, status) { + self.dataLoading = false + + var alert = $mdDialog.alert({ + title: 'We couldn\'t sign you in!', + content: error.message, + ok: 'Try again' }) - .error(function(error, status) { - self.error = error.message; - self.dataLoading = false; - }); - }; + + $mdDialog.show(alert) + }) } + } - LoginController.$inject = ['$location', 'UserAuthenticationService'] + LoginController.$inject = ['$location', '$mdDialog', 'UserAuthenticationService'] return LoginController })
297c942ffefae923501d5988c36ef6930b5888b7
examples/http-random-user/src/main.js
examples/http-random-user/src/main.js
import Cycle from '@cycle/core'; import {div, button, h1, h4, a, makeDOMDriver} from '@cycle/dom'; import {makeHTTPDriver} from '@cycle/http'; function main(sources) { const getRandomUser$ = sources.DOM.select('.get-random').events('click') .map(() => { const randomNum = Math.round(Math.random() * 9) + 1; return { url: 'http://jsonplaceholder.typicode.com/users/' + String(randomNum), key: 'users', method: 'GET' }; }); const user$ = sources.HTTP .filter(res$ => res$.request.key === 'users') .mergeAll() .map(res => res.body) .startWith(null); const vtree$ = user$.map(user => div('.users', [ button('.get-random', 'Get random user'), user === null ? null : div('.user-details', [ h1('.user-name', user.name), h4('.user-email', user.email), a('.user-website', {href: user.website}, user.website) ]) ]) ); return { DOM: vtree$, HTTP: getRandomUser$ }; } Cycle.run(main, { DOM: makeDOMDriver('#main-container'), HTTP: makeHTTPDriver() });
import Cycle from '@cycle/core'; import {div, button, h1, h4, a, makeDOMDriver} from '@cycle/dom'; import {makeHTTPDriver} from '@cycle/http'; function main(sources) { const getRandomUser$ = sources.DOM.select('.get-random').events('click') .map(() => { const randomNum = Math.round(Math.random() * 9) + 1; return { url: 'http://jsonplaceholder.typicode.com/users/' + String(randomNum), category: 'users', method: 'GET' }; }); const user$ = sources.HTTP .filter(res$ => res$.request.category === 'users') .mergeAll() .map(res => res.body) .startWith(null); const vtree$ = user$.map(user => div('.users', [ button('.get-random', 'Get random user'), user === null ? null : div('.user-details', [ h1('.user-name', user.name), h4('.user-email', user.email), a('.user-website', {href: user.website}, user.website) ]) ]) ); return { DOM: vtree$, HTTP: getRandomUser$ }; } Cycle.run(main, { DOM: makeDOMDriver('#main-container'), HTTP: makeHTTPDriver() });
Rename http-random-user key to category
Rename http-random-user key to category
JavaScript
mit
cyclejs/cyclejs,cyclejs/cyclejs,feliciousx-open-source/cyclejs,cyclejs/cyclejs,usm4n/cyclejs,maskinoshita/cyclejs,cyclejs/cycle-core,staltz/cycle,ntilwalli/cyclejs,ntilwalli/cyclejs,feliciousx-open-source/cyclejs,usm4n/cyclejs,usm4n/cyclejs,maskinoshita/cyclejs,maskinoshita/cyclejs,ntilwalli/cyclejs,feliciousx-open-source/cyclejs,feliciousx-open-source/cyclejs,cyclejs/cycle-core,ntilwalli/cyclejs,staltz/cycle,usm4n/cyclejs,cyclejs/cyclejs,maskinoshita/cyclejs
--- +++ @@ -8,13 +8,13 @@ const randomNum = Math.round(Math.random() * 9) + 1; return { url: 'http://jsonplaceholder.typicode.com/users/' + String(randomNum), - key: 'users', + category: 'users', method: 'GET' }; }); const user$ = sources.HTTP - .filter(res$ => res$.request.key === 'users') + .filter(res$ => res$.request.category === 'users') .mergeAll() .map(res => res.body) .startWith(null);
73e99f993882ddd754fefd112f2c95ce62e5dad2
app/components/OverFlowMenu.js
app/components/OverFlowMenu.js
import React, { Component, PropTypes, cloneElement } from 'react'; import styles from './OverFlowMenu.module.scss'; export class OverflowItem extends Component { onClick(e) { this.props.onClick(e); this.props.onClicked(); } render() { return ( <div className={styles.item} {...this.props} onClick={this.onClick.bind(this)}> { this.props.children } </div> ); } } export default class OverFlowMenu extends Component { constructor(props) { super(props); this.state = {open: false}; } toggle() { this.setState({open: !this.state.open}); } onItemClicked() { this.toggle(); } onMouseLeave() { this.toggle(); } render() { const cn = [this.state.open ? styles.overflowMenuOpen : styles.overflowMenu, this.props.className].join(' '); return ( <div className={ cn }> <button className={styles.btn} onClick={this.toggle.bind(this)}> <i className="fa small fa-ellipsis-v"/> </button> <div className="items" onMouseLeave={this.onMouseLeave.bind(this)}> { React.Children.map(this.props.children, (child) => { return cloneElement(child, { onClicked: this.onItemClicked.bind(this) }); })} </div> </div> ); } }
import React, { Component, PropTypes, cloneElement } from 'react'; import styles from './OverFlowMenu.module.scss'; export class OverflowItem extends Component { onClick(e) { this.props.onClick(e); this.props.onClicked(); } render() { return ( <div className={styles.item} {...this.props} onClick={this.onClick.bind(this)}> { this.props.children } </div> ); } } export default class OverFlowMenu extends Component { constructor(props) { super(props); this.state = {open: false}; } toggle() { this.setOpen(!this.isOpen()); } isOpen() { return this.state.open; } setOpen(openOrClosed) { this.setState({open: openOrClosed}); } onItemClicked() { this.toggle(); } onMouseLeave() { this.setOpen(false); } render() { const cn = [this.state.open ? styles.overflowMenuOpen : styles.overflowMenu, this.props.className].join(' '); return ( <div className={ cn }> <button className={styles.btn} onClick={this.toggle.bind(this)}> <i className="fa small fa-ellipsis-v"/> </button> <div className="items" onMouseLeave={this.onMouseLeave.bind(this)}> { React.Children.map(this.props.children, (child) => { return cloneElement(child, { onClicked: this.onItemClicked.bind(this) }); })} </div> </div> ); } }
Fix overflow menu reopening immediately after selecting an item
Fix overflow menu reopening immediately after selecting an item Was caused by mouseout toggling, instead of closing
JavaScript
mpl-2.0
pascalw/gettable,pascalw/gettable
--- +++ @@ -23,7 +23,15 @@ } toggle() { - this.setState({open: !this.state.open}); + this.setOpen(!this.isOpen()); + } + + isOpen() { + return this.state.open; + } + + setOpen(openOrClosed) { + this.setState({open: openOrClosed}); } onItemClicked() { @@ -31,7 +39,7 @@ } onMouseLeave() { - this.toggle(); + this.setOpen(false); } render() {
5e850fc85216fed6848878eaf66841c8dc25fc1b
src/selectors/cashRegister.js
src/selectors/cashRegister.js
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import { createSelector } from 'reselect'; import { pageStateSelector } from './pageSelectors'; import currency from '../localization/currency'; /** * Derives current balance from cash register transactions. * @return {Number} */ export const selectTransactions = createSelector([pageStateSelector], pageState => pageState.data); export const selectReceipts = createSelector([selectTransactions], transactions => transactions.filter(({ type }) => type === 'receipt') ); export const selectPayments = createSelector([selectTransactions], transactions => transactions.filter(({ type }) => type === 'payment') ); export const selectReceiptsTotal = createSelector([selectReceipts], receipts => receipts.reduce((acc, { total }) => acc + total, 0) ); export const selectPaymentsTotal = createSelector([selectPayments], payments => payments.reduce((acc, { total }) => acc + total, 0) ); export const selectBalance = createSelector( [selectReceiptsTotal, selectPaymentsTotal], (receiptsTotal, paymentsTotal) => currency(receiptsTotal - paymentsTotal).format(false) );
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import { createSelector } from 'reselect'; import { pageStateSelector } from './pageSelectors'; import currency from '../localization/currency'; /** * Derives current balance from cash register transactions. * @return {Number} */ export const selectTransactions = createSelector([pageStateSelector], pageState => pageState.data); export const selectReceipts = createSelector([selectTransactions], transactions => transactions.filter(({ type }) => type === 'receipt') ); export const selectPayments = createSelector([selectTransactions], transactions => transactions.filter(({ type }) => type === 'payment') ); export const selectReceiptsTotal = createSelector([selectReceipts], receipts => receipts.reduce((acc, { total }) => acc.add(total), currency(0)) ); export const selectPaymentsTotal = createSelector([selectPayments], payments => payments.reduce((acc, { total }) => acc.add(total), currency(0)) ); export const selectBalance = createSelector( [selectReceiptsTotal, selectPaymentsTotal], (receiptsTotal, paymentsTotal) => receiptsTotal.subtract(paymentsTotal).format() );
Add currency to cash register selectors
Add currency to cash register selectors
JavaScript
mit
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
--- +++ @@ -23,14 +23,14 @@ ); export const selectReceiptsTotal = createSelector([selectReceipts], receipts => - receipts.reduce((acc, { total }) => acc + total, 0) + receipts.reduce((acc, { total }) => acc.add(total), currency(0)) ); export const selectPaymentsTotal = createSelector([selectPayments], payments => - payments.reduce((acc, { total }) => acc + total, 0) + payments.reduce((acc, { total }) => acc.add(total), currency(0)) ); export const selectBalance = createSelector( [selectReceiptsTotal, selectPaymentsTotal], - (receiptsTotal, paymentsTotal) => currency(receiptsTotal - paymentsTotal).format(false) + (receiptsTotal, paymentsTotal) => receiptsTotal.subtract(paymentsTotal).format() );
39c4271933e1392d20483aa3e1c6e7287fb3d820
src/api/githubAPI.js
src/api/githubAPI.js
let Octokat = require('octokat'); let octo = new Octokat({}); class GithubApi { constructor(){ this.octo = new Octokat({}); } static newOctokatNoToken(){ this.octo = new Octokat({}); } static newOctokatWithToken(token){ this.octo = new Octokat({ token: token }); } static testOctokat(){ return new Promise((resolve) => { resolve(octo.repos('compumike08', 'GitHub_Status_API_GUI').fetch()); }); } } export default GithubApi;
let Octokat = require('octokat'); let octo = new Octokat({}); class GithubApi { static testOctokat(){ return new Promise((resolve) => { resolve(octo.repos('compumike08', 'GitHub_Status_API_GUI').fetch()); }); } } export default GithubApi;
Revert "Modify GithubApi to be able to set an OAuth token when instantiating"
Revert "Modify GithubApi to be able to set an OAuth token when instantiating" This reverts commit 2197aa8a6246348070b9c26693ec08fc44f02031.
JavaScript
mit
compumike08/GitHub_Status_API_GUI,compumike08/GitHub_Status_API_GUI
--- +++ @@ -2,20 +2,6 @@ let octo = new Octokat({}); class GithubApi { - constructor(){ - this.octo = new Octokat({}); - } - - static newOctokatNoToken(){ - this.octo = new Octokat({}); - } - - static newOctokatWithToken(token){ - this.octo = new Octokat({ - token: token - }); - } - static testOctokat(){ return new Promise((resolve) => { resolve(octo.repos('compumike08', 'GitHub_Status_API_GUI').fetch());
60f02a26c5857e28e268cbfdd242644089c6626c
react.js
react.js
module.exports = { extends: ["./index.js", "plugin:react/recommended"], env: { browser: true }, plugins: [ "react" ], parserOptions: { sourceType: 'module', ecmaVersion: 6, ecmaFeatures: { "jsx": true } } };
module.exports = { extends: ["./index.js", "plugin:react/recommended"], env: { browser: true }, plugins: [ "react" ], parserOptions: { sourceType: 'module', ecmaVersion: 6, ecmaFeatures: { "jsx": true } }, rules: { "react/display-name": 0, "react/no-danger": 0 } };
Add common React rules to preset
Add common React rules to preset
JavaScript
mit
netconomy/eslint-config-netconomy
--- +++ @@ -12,5 +12,9 @@ ecmaFeatures: { "jsx": true } + }, + rules: { + "react/display-name": 0, + "react/no-danger": 0 } };
30d5c4942db0ccdb2f5ee4de0d4405d456ff3ed9
webpack.conf.js
webpack.conf.js
import webpack from "webpack"; import path from "path"; export default { module: { rules: [ { test: /\.((png)|(eot)|(woff)|(woff2)|(ttf)|(svg)|(gif))(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader?name=/[hash].[ext]" }, {test: /\.json$/, loader: "json-loader"}, { loader: "babel-loader", test: /\.js?$/, exclude: /node_modules/, query: {cacheDirectory: true} } ] }, plugins: [ new webpack.ProvidePlugin({ "fetch": "imports-loader?this=>global!exports?global.fetch!whatwg-fetch" }) ], context: path.join(__dirname, "src"), entry: { app: ["./js/app"] }, output: { path: path.join(__dirname, "dist"), publicPath: "/", filename: "[name].js" }, externals: [/^vendor\/.+\.js$/] };
import webpack from "webpack"; import path from "path"; export default { module: { rules: [ { test: /\.((png)|(eot)|(woff)|(woff2)|(ttf)|(svg)|(gif))(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader?name=/[hash].[ext]" }, {test: /\.json$/, loader: "json-loader"}, { loader: "babel-loader", test: /\.js?$/, exclude: /node_modules/, query: {cacheDirectory: true} } ] }, plugins: [ new webpack.ProvidePlugin({ "fetch": "imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch" }) ], context: path.join(__dirname, "src"), entry: { app: ["./js/app"] }, output: { path: path.join(__dirname, "dist"), publicPath: "/", filename: "[name].js" }, externals: [/^vendor\/.+\.js$/] };
Update exports loader to Webpack 3 syntax
Update exports loader to Webpack 3 syntax Closes #67.
JavaScript
mit
doudigit/doudigit.github.io,BeitouSafeHome/btsh,netlify-templates/one-click-hugo-cms,netlify-templates/one-click-hugo-cms,emiaj/blog,chromicant/blog,doudigit/doudigit.github.io,jcrincon/jcrincon.github.io,chromicant/blog,BeitouSafeHome/btsh,emiaj/blog,jcrincon/jcrincon.github.io,emiaj/blog
--- +++ @@ -20,7 +20,7 @@ plugins: [ new webpack.ProvidePlugin({ - "fetch": "imports-loader?this=>global!exports?global.fetch!whatwg-fetch" + "fetch": "imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch" }) ],
55e44ff76a4baae8214cd89c498868b661d99049
spawnAsync.js
spawnAsync.js
'use strict'; let spawn = require('cross-spawn'); module.exports = function spawnAsync() { let args = Array.prototype.slice.call(arguments, 0); let child; let promise = new Promise((fulfill, reject) => { child = spawn.apply(spawn, args); let stdout = ''; let stderr = ''; if (child.stdout) { child.stdout.on('data', data => { stdout += data; }); } if (child.stderr) { child.stderr.on('data', data => { stderr += data; }); } child.on('close', (code, signal) => { child.removeAllListeners(); let result = { pid: child.pid, output: [stdout, stderr], stdout, stderr, status: code, signal, }; if (code) { let error = new Error(`Process exited with non-zero code: ${code}`); Object.assign(error, result); reject(error); } else { fulfill(result); } }); child.on('error', error => { child.removeAllListeners(); error.pid = child.pid; error.output = [stdout, stderr]; error.stdout = stdout; error.stderr = stderr; error.status = null; reject(error); }); }); promise.child = child; return promise; };
'use strict'; let spawn = require('cross-spawn'); module.exports = function spawnAsync(...args) { let child; let promise = new Promise((fulfill, reject) => { child = spawn.apply(spawn, args); let stdout = ''; let stderr = ''; if (child.stdout) { child.stdout.on('data', data => { stdout += data; }); } if (child.stderr) { child.stderr.on('data', data => { stderr += data; }); } child.on('close', (code, signal) => { child.removeAllListeners(); let result = { pid: child.pid, output: [stdout, stderr], stdout, stderr, status: code, signal, }; if (code) { let error = new Error(`Process exited with non-zero code: ${code}`); Object.assign(error, result); reject(error); } else { fulfill(result); } }); child.on('error', error => { child.removeAllListeners(); error.pid = child.pid; error.output = [stdout, stderr]; error.stdout = stdout; error.stderr = stderr; error.status = null; reject(error); }); }); promise.child = child; return promise; };
Use rest param instead of slice
Use rest param instead of slice
JavaScript
mit
exponentjs/spawn-async,650Industries/spawn-async
--- +++ @@ -2,8 +2,7 @@ let spawn = require('cross-spawn'); -module.exports = function spawnAsync() { - let args = Array.prototype.slice.call(arguments, 0); +module.exports = function spawnAsync(...args) { let child; let promise = new Promise((fulfill, reject) => { child = spawn.apply(spawn, args);
9017acd8ec8e0aaf9cf95d0b64385fb18fff0dcc
lib/config.js
lib/config.js
// Load configurations file var config = require('../configs/config.json'); // Validate settings if (!config.mpd || !config.mpd.host || !config.mpd.port) { throw new Error("You must specify MPD host and port"); } if (!config.radioStations || (typeof config.radioStations !== 'object')) { throw new Error('"radioStations" field must be an object'); } var isRadioStationsEmpty = true; for(var index in config.radioStations) { if (config.radioStations.hasOwnProperty(index)) { isRadioStationsEmpty = false; config.defaultRadioStation = config.defaultRadioStation || index; } } if (isRadioStationsEmpty) { throw new Error("You must specify at least one radio station"); } module.exports = config;
// Load configurations file var config = require('../configs/config.json'); // Validate settings if (!config.mpd || !config.mpd.host || !config.mpd.port) { throw new Error("You must specify MPD host and port"); } if (!config.radioStations || (typeof config.radioStations !== 'object')) { throw new Error('"radioStations" field must be an object'); } var isRadioStationsEmpty = true; for(var index in config.radioStations) { if (config.radioStations.hasOwnProperty(index)) { isRadioStationsEmpty = false; config.defaultRadioStation = config.defaultRadioStation || index; } } if (isRadioStationsEmpty) { throw new Error("You must specify at least one radio station"); } // Make sure the application port is set config.server.port = config.server.port || 8000; module.exports = config;
Make use server port is set
Make use server port is set
JavaScript
apache-2.0
JustBlackBird/bluethroat,JustBlackBird/bluethroat,JustBlackBird/bluethroat
--- +++ @@ -22,4 +22,7 @@ throw new Error("You must specify at least one radio station"); } +// Make sure the application port is set +config.server.port = config.server.port || 8000; + module.exports = config;
ee5a87db22b7e527d7d0102072bba5de91ac38fb
lib/errors.js
lib/errors.js
/** AuthGW Custom Errors @author tylerFowler **/ /** @name InvalidRoleError @desc Thrown when a role is given that is not in the list of roles @param { String } invalidRole **/ function InvalidRoleError(invalidRole) { this.name = 'InvalidRoleError'; this.message = `${invalidRole} is not a valid role`; this.stack = (new Error()).stack; } InvalidRoleError.prototype = Object.create(Error.prototype); InvalidRoleError.prototype.constructor = InvalidRoleError; exports.InvalidRoleError = InvalidRoleError;
/** AuthGW Custom Errors @author tylerFowler **/ /** @class InvalidRoleError @extends Error @desc Thrown when a role is given that is not in the list of roles @param { String } invalidRole **/ class InvalidRoleError extends Error { constructor(invalidRole) { this.name = 'InvalidRoleError'; this.message = `${invalidRole} is not a valid role`; } } exports.InvalidRoleError = InvalidRoleError;
Use class syntax for creating error
Use class syntax for creating error
JavaScript
mit
tylerFowler/authgw
--- +++ @@ -4,15 +4,14 @@ **/ /** - @name InvalidRoleError + @class InvalidRoleError @extends Error @desc Thrown when a role is given that is not in the list of roles @param { String } invalidRole **/ -function InvalidRoleError(invalidRole) { - this.name = 'InvalidRoleError'; - this.message = `${invalidRole} is not a valid role`; - this.stack = (new Error()).stack; +class InvalidRoleError extends Error { + constructor(invalidRole) { + this.name = 'InvalidRoleError'; + this.message = `${invalidRole} is not a valid role`; + } } -InvalidRoleError.prototype = Object.create(Error.prototype); -InvalidRoleError.prototype.constructor = InvalidRoleError; exports.InvalidRoleError = InvalidRoleError;
48ef57b90e8567574199dddb5b6cee78b6b039b0
src/config.js
src/config.js
export const TZ = 'Europe/Prague' export const SIRIUS_PROXY_PATH = process.env.SIRIUS_PROXY_PATH
export const TZ = 'Europe/Prague' export const SIRIUS_PROXY_PATH = global.SIRIUS_PROXY_PATH || process.env.SIRIUS_PROXY_PATH
Allow SIRIUS_PROXY_PATH override by global var
Allow SIRIUS_PROXY_PATH override by global var
JavaScript
mit
cvut/fittable-widget,cvut/fittable,cvut/fittable-widget,cvut/fittable-widget,cvut/fittable,cvut/fittable
--- +++ @@ -1,3 +1,3 @@ export const TZ = 'Europe/Prague' -export const SIRIUS_PROXY_PATH = process.env.SIRIUS_PROXY_PATH +export const SIRIUS_PROXY_PATH = global.SIRIUS_PROXY_PATH || process.env.SIRIUS_PROXY_PATH
57789e5d40c448ab1138dad987f7d8f9595966ee
.storybook/config.js
.storybook/config.js
import { configure } from '@storybook/vue'; // automatically import all files ending in *.stories.js const req = require.context('../stories', true, /\.stories\.js$/); function loadStories() { req.keys().forEach(filename => req(filename)); } configure(loadStories, module);
import { configure, addParameters } from '@storybook/vue'; // Option defaults: addParameters({ options: { name: 'Vue Visual', panelPosition: 'right', } }) // automatically import all files ending in *.stories.js const req = require.context('../stories', true, /\.stories\.js$/); function loadStories() { req.keys().forEach(filename => req(filename)); } configure(loadStories, module);
Put package name in the storybook
Put package name in the storybook
JavaScript
mit
BKWLD/vue-visual
--- +++ @@ -1,4 +1,12 @@ -import { configure } from '@storybook/vue'; +import { configure, addParameters } from '@storybook/vue'; + +// Option defaults: +addParameters({ + options: { + name: 'Vue Visual', + panelPosition: 'right', + } +}) // automatically import all files ending in *.stories.js const req = require.context('../stories', true, /\.stories\.js$/);
2de18a5628f1acf45a5884c93bd985d4f6f367a3
lib/server.js
lib/server.js
var acquires = {}; var Responder = require('cote').Responder; var autoReleaseTimeout = 30000; var counts = { acquires: 0, releases: 0 }; function acquire(req, cb) { console.log('acquire', req.id); counts.acquires++; cb.autoRelease = setTimeout(function() { console.log('auto release', req.id); release(req); }, autoReleaseTimeout); if (acquires[req.id]) return acquires[req.id].push(cb); acquires[req.id] = []; cb(); } function release(req) { console.log('release', req.id); counts.releases++; if (!(req.id in acquires)) return; if (!acquires[req.id].length) return delete acquires[req.id]; var cb = acquires[req.id].shift(); cb && cb(); clearTimeout(cb.autoRelease); } function init() { var server = new Responder({ name: 'semaver server', key: 'semaver', respondsTo: ['acquire', 'release'] }); server.on('acquire', acquire); server.on('release', release); setInterval(function() { console.log('counts', counts); if (Object.keys(acquires).length) console.log(acquires); }, 1000); } module.exports = { init: init };
var acquires = {}; var Responder = require('cote').Responder; var autoReleaseTimeout = 30000; var counts = { acquires: 0, releases: 0 }; function acquire(req, cb) { console.log('acquire', req.id); counts.acquires++; if (acquires[req.id]) { cb.autoRelease = setTimeout(function() { console.log('auto release', req.id); release(req); }, autoReleaseTimeout); return acquires[req.id].push(cb); } acquires[req.id] = []; cb(); } function release(req) { console.log('release', req.id); counts.releases++; if (!(req.id in acquires)) return; if (!acquires[req.id].length) return delete acquires[req.id]; var cb = acquires[req.id].shift(); cb && cb(); clearTimeout(cb.autoRelease); } function init() { var server = new Responder({ name: 'semaver server', key: 'semaver', respondsTo: ['acquire', 'release'] }); server.on('acquire', acquire); server.on('release', release); setInterval(function() { console.log('counts', counts); if (Object.keys(acquires).length) console.log(acquires); }, 1000); } module.exports = { init: init };
Move auto release timeout to if check in acquire.
Move auto release timeout to if check in acquire.
JavaScript
apache-2.0
tart/semaver
--- +++ @@ -11,13 +11,13 @@ console.log('acquire', req.id); counts.acquires++; - cb.autoRelease = setTimeout(function() { - console.log('auto release', req.id); - release(req); - }, autoReleaseTimeout); - - if (acquires[req.id]) + if (acquires[req.id]) { + cb.autoRelease = setTimeout(function() { + console.log('auto release', req.id); + release(req); + }, autoReleaseTimeout); return acquires[req.id].push(cb); + } acquires[req.id] = []; cb();
f5774e3fb24ca403de481e446c3bf68fa78b2c47
spec/fixtures/api/quit-app/main.js
spec/fixtures/api/quit-app/main.js
var app = require('electron').app app.on('ready', function () { app.exit(123) }) process.on('exit', function (code) { console.log('Exit event with code: ' + code) })
var app = require('electron').app app.on('ready', function () { // This setImmediate call gets the spec passing on Linux setImmediate(function () { app.exit(123) }) }) process.on('exit', function (code) { console.log('Exit event with code: ' + code) })
Exit from a setImmediate callback
Exit from a setImmediate callback
JavaScript
mit
seanchas116/electron,felixrieseberg/electron,pombredanne/electron,bpasero/electron,wan-qy/electron,leftstick/electron,the-ress/electron,jaanus/electron,deed02392/electron,thomsonreuters/electron,brave/muon,tonyganch/electron,tinydew4/electron,thomsonreuters/electron,gerhardberger/electron,roadev/electron,simongregory/electron,the-ress/electron,rreimann/electron,shiftkey/electron,thomsonreuters/electron,kcrt/electron,preco21/electron,aichingm/electron,ankitaggarwal011/electron,Floato/electron,Gerhut/electron,voidbridge/electron,leftstick/electron,seanchas116/electron,thingsinjars/electron,aliib/electron,jhen0409/electron,MaxWhere/electron,roadev/electron,bpasero/electron,lzpfmh/electron,joaomoreno/atom-shell,lzpfmh/electron,kokdemo/electron,rajatsingla28/electron,Floato/electron,dongjoon-hyun/electron,renaesop/electron,brenca/electron,etiktin/electron,posix4e/electron,astoilkov/electron,brenca/electron,Floato/electron,ankitaggarwal011/electron,thompsonemerson/electron,lzpfmh/electron,miniak/electron,dongjoon-hyun/electron,gabriel/electron,posix4e/electron,minggo/electron,deed02392/electron,leftstick/electron,thompsonemerson/electron,shiftkey/electron,astoilkov/electron,voidbridge/electron,miniak/electron,felixrieseberg/electron,rreimann/electron,lzpfmh/electron,simongregory/electron,pombredanne/electron,stevekinney/electron,roadev/electron,stevekinney/electron,gerhardberger/electron,jaanus/electron,minggo/electron,Floato/electron,the-ress/electron,tinydew4/electron,bbondy/electron,wan-qy/electron,gabriel/electron,the-ress/electron,tinydew4/electron,aliib/electron,biblerule/UMCTelnetHub,leethomas/electron,bbondy/electron,biblerule/UMCTelnetHub,brave/muon,miniak/electron,renaesop/electron,noikiy/electron,stevekinney/electron,lzpfmh/electron,ankitaggarwal011/electron,thingsinjars/electron,thompsonemerson/electron,noikiy/electron,minggo/electron,kokdemo/electron,joaomoreno/atom-shell,etiktin/electron,thomsonreuters/electron,tonyganch/electron,stevekinney/electron,kcrt/electron,leethomas/electron,bbondy/electron,voidbridge/electron,stevekinney/electron,kcrt/electron,rajatsingla28/electron,Floato/electron,felixrieseberg/electron,Gerhut/electron,felixrieseberg/electron,voidbridge/electron,evgenyzinoviev/electron,brave/electron,electron/electron,dongjoon-hyun/electron,simongregory/electron,voidbridge/electron,gabriel/electron,rajatsingla28/electron,gabriel/electron,electron/electron,thomsonreuters/electron,kokdemo/electron,tonyganch/electron,gerhardberger/electron,aichingm/electron,twolfson/electron,electron/electron,simongregory/electron,leftstick/electron,simongregory/electron,aichingm/electron,tonyganch/electron,aliib/electron,brave/electron,leethomas/electron,seanchas116/electron,tylergibson/electron,aichingm/electron,rajatsingla28/electron,roadev/electron,tylergibson/electron,twolfson/electron,bbondy/electron,shiftkey/electron,tinydew4/electron,astoilkov/electron,dongjoon-hyun/electron,evgenyzinoviev/electron,electron/electron,aliib/electron,brave/muon,rajatsingla28/electron,thingsinjars/electron,twolfson/electron,voidbridge/electron,joaomoreno/atom-shell,kcrt/electron,evgenyzinoviev/electron,renaesop/electron,tinydew4/electron,thompsonemerson/electron,leftstick/electron,leftstick/electron,MaxWhere/electron,brave/electron,bpasero/electron,renaesop/electron,brave/electron,seanchas116/electron,shiftkey/electron,brave/muon,wan-qy/electron,minggo/electron,thingsinjars/electron,noikiy/electron,etiktin/electron,brave/muon,tonyganch/electron,kcrt/electron,rreimann/electron,deed02392/electron,astoilkov/electron,Gerhut/electron,jaanus/electron,aichingm/electron,bpasero/electron,biblerule/UMCTelnetHub,minggo/electron,pombredanne/electron,rreimann/electron,deed02392/electron,kokdemo/electron,the-ress/electron,biblerule/UMCTelnetHub,rreimann/electron,brenca/electron,wan-qy/electron,thompsonemerson/electron,thingsinjars/electron,leethomas/electron,renaesop/electron,minggo/electron,jhen0409/electron,posix4e/electron,leethomas/electron,aichingm/electron,preco21/electron,Evercoder/electron,brave/electron,preco21/electron,seanchas116/electron,shiftkey/electron,tylergibson/electron,Evercoder/electron,miniak/electron,Evercoder/electron,gerhardberger/electron,dongjoon-hyun/electron,Gerhut/electron,posix4e/electron,evgenyzinoviev/electron,tylergibson/electron,Evercoder/electron,MaxWhere/electron,brenca/electron,jhen0409/electron,electron/electron,preco21/electron,bpasero/electron,noikiy/electron,jhen0409/electron,felixrieseberg/electron,tylergibson/electron,astoilkov/electron,kokdemo/electron,seanchas116/electron,astoilkov/electron,wan-qy/electron,dongjoon-hyun/electron,jaanus/electron,preco21/electron,gerhardberger/electron,brenca/electron,simongregory/electron,leethomas/electron,roadev/electron,noikiy/electron,posix4e/electron,kcrt/electron,electron/electron,gerhardberger/electron,deed02392/electron,preco21/electron,Evercoder/electron,twolfson/electron,joaomoreno/atom-shell,felixrieseberg/electron,gabriel/electron,jaanus/electron,tonyganch/electron,evgenyzinoviev/electron,thompsonemerson/electron,brave/electron,twolfson/electron,gerhardberger/electron,ankitaggarwal011/electron,twolfson/electron,bpasero/electron,pombredanne/electron,renaesop/electron,jaanus/electron,thingsinjars/electron,etiktin/electron,shiftkey/electron,bbondy/electron,MaxWhere/electron,bpasero/electron,ankitaggarwal011/electron,MaxWhere/electron,Gerhut/electron,joaomoreno/atom-shell,pombredanne/electron,the-ress/electron,tylergibson/electron,jhen0409/electron,jhen0409/electron,brave/muon,gabriel/electron,rajatsingla28/electron,tinydew4/electron,posix4e/electron,lzpfmh/electron,joaomoreno/atom-shell,biblerule/UMCTelnetHub,electron/electron,ankitaggarwal011/electron,aliib/electron,biblerule/UMCTelnetHub,miniak/electron,wan-qy/electron,miniak/electron,bbondy/electron,Evercoder/electron,etiktin/electron,noikiy/electron,roadev/electron,kokdemo/electron,brenca/electron,pombredanne/electron,aliib/electron,MaxWhere/electron,rreimann/electron,the-ress/electron,thomsonreuters/electron,Gerhut/electron,Floato/electron,deed02392/electron,etiktin/electron,evgenyzinoviev/electron,stevekinney/electron
--- +++ @@ -1,7 +1,10 @@ var app = require('electron').app app.on('ready', function () { - app.exit(123) + // This setImmediate call gets the spec passing on Linux + setImmediate(function () { + app.exit(123) + }) }) process.on('exit', function (code) {
ad16587294c3186a89e84105fb2e390b36f26ca0
lib/switch.js
lib/switch.js
const gpio = require('raspi-gpio') module.exports = class Switch { constructor (pinId) { this.nInput = new gpio.DigitalInput(pinId, gpio.PULL_UP) } on (changeListener) { this.nInput.on('change', (value) => { changeListener(value) }) } }
const gpio = require('raspi-gpio') module.exports = class Switch { constructor (pinId) { this.nInput = new gpio.DigitalInput({ pin: pinId, pullResistor: gpio.PULL_UP}) } on (changeListener) { this.nInput.on('change', (value) => { changeListener(value) }) } }
Fix pin pull resistor config
Fix pin pull resistor config
JavaScript
mit
DanStough/josl
--- +++ @@ -2,7 +2,9 @@ module.exports = class Switch { constructor (pinId) { - this.nInput = new gpio.DigitalInput(pinId, gpio.PULL_UP) + this.nInput = new gpio.DigitalInput({ + pin: pinId, + pullResistor: gpio.PULL_UP}) } on (changeListener) {
b9e214312ec055e7e6d64fcc6a75b108c6176657
js/index.js
js/index.js
// Pullquotes document.addEventListener("DOMContentLoaded", function(event) { function pullQuote(el){ var parentParagraph = el.parentNode; parentParagraph.style.position = 'relative'; var clone = el.cloneNode(true); clone.setAttribute('class','semantic-pull-quote--pulled'); // Hey y’all, watch this! parentParagraph.parentNode.parentNode.insertBefore(clone, parentParagraph.parentNode); if(!clone.getAttribute('data-content')){ clone.setAttribute('data-content', clone.innerHTML ); clone.innerHTML = null; } }; var pullQuotes = document.getElementsByClassName('semantic-pull-quote'); for(var i = 0; i < pullQuotes.length; i++) { pullQuote(pullQuotes[i]); } });
// Semantic Pullquotes document.addEventListener("DOMContentLoaded", function(event) { function pullQuote(el){ var parentParagraph = el.parentNode; parentParagraph.style.position = 'relative'; var clone = el.cloneNode(true); clone.setAttribute('class','semantic-pull-quote--pulled'); // Hey y’all, watch this! parentParagraph.parentNode.parentNode.insertBefore(clone, parentParagraph.parentNode); if(!clone.getAttribute('data-content')){ clone.setAttribute('data-content', clone.innerHTML ); clone.innerHTML = null; } }; var pullQuotes = document.getElementsByClassName('semantic-pull-quote'); for(var i = 0; i < pullQuotes.length; i++) { pullQuote(pullQuotes[i]); } });
Rename Pullquotes --> Semantic Pullquotes
Rename Pullquotes --> Semantic Pullquotes
JavaScript
mit
curiositry/sassisfy,curiositry/sassisfy
--- +++ @@ -1,4 +1,4 @@ -// Pullquotes +// Semantic Pullquotes document.addEventListener("DOMContentLoaded", function(event) { function pullQuote(el){ var parentParagraph = el.parentNode;
234138b3a81e6db0439851c131448eb3f030f146
app/send-native.js
app/send-native.js
'use strict'; const application = 'io.github.deathcap.nodeachrome'; function decodeResponse(response, cb) { console.log('decodeResponse',response); if (typeof cb !== 'function') { console.error('??? decodeResponse non-string callback',cb); cb = () => {}; } if (!response) return cb(chrome.runtime.lastError); if (response.error) return cb(new Error(response.error.message)); return cb(null, response.result); } // Send message using Google Chrome Native Messaging API to a native code host function sendNative(method, params, cb) { console.log('sendNative',method,params); const msg = {method: method, params: params}; chrome.runtime.sendNativeMessage(application, msg, (response) => decodeResponse(response, cb)); } module.exports = sendNative;
'use strict'; const application = 'io.github.deathcap.nodeachrome'; let callbacks = new Map(); let nextID = 1; let port = null; function decodeResponse(response, cb) { console.log('decodeResponse',response); if (typeof cb !== 'function') { console.error('??? decodeResponse non-string callback',cb); cb = () => {}; } if (!response) return cb(chrome.runtime.lastError); if (response.error) return cb(new Error(response.error.message)); return cb(null, response.result); } function recvIncoming(msg) { const cb = callbacks.get(msg.id); if (!cb) { throw new Error(`received native host message with unexpected id: ${msg.id} in ${JSON.stringify(msg)}`); } cb(msg); callbacks.delete(msg.id); } function disconnected(e) { console.log('unexpected native host disconnect:',e); throw new Error('unexpected native host disconnect:'+e); // TODO: reconnect? if it crashes } function connectPort() { port = chrome.runtime.connectNative(application); port.onMessage.addListener(recvIncoming); port.onDisconnect.addListener(disconnected); return port; } // Send message using Google Chrome Native Messaging API to a native code host function sendNative(method, params, cb) { console.log('sendNative',method,params); const id = nextID; nextID += 1; const msg = {method: method, params: params, id: id}; if (!port) { port = connectPort(); } callbacks.set(id, (response) => decodeResponse(response, cb)); port.postMessage(msg); // the one-off sendNativeMessage call is convenient in that it accepts a response callback, // but it launches the host app every time, so it doesn't preserve open filehandles (for e.g. fs.open/fs.write) //chrome.runtime.sendNativeMessage(application, msg, (response) => decodeResponse(response, cb)); } module.exports = sendNative;
Change native messaging to keep the host running persistently, maintaining an open port
Change native messaging to keep the host running persistently, maintaining an open port
JavaScript
mit
deathcap/nodeachrome,deathcap/nodeachrome,deathcap/nodeachrome
--- +++ @@ -1,6 +1,10 @@ 'use strict'; const application = 'io.github.deathcap.nodeachrome'; + +let callbacks = new Map(); +let nextID = 1; +let port = null; function decodeResponse(response, cb) { console.log('decodeResponse',response); @@ -10,11 +14,49 @@ return cb(null, response.result); } +function recvIncoming(msg) { + const cb = callbacks.get(msg.id); + if (!cb) { + throw new Error(`received native host message with unexpected id: ${msg.id} in ${JSON.stringify(msg)}`); + } + + cb(msg); + + callbacks.delete(msg.id); +} + +function disconnected(e) { + console.log('unexpected native host disconnect:',e); + throw new Error('unexpected native host disconnect:'+e); + // TODO: reconnect? if it crashes +} + +function connectPort() { + port = chrome.runtime.connectNative(application); + port.onMessage.addListener(recvIncoming); + port.onDisconnect.addListener(disconnected); + + return port; +} + // Send message using Google Chrome Native Messaging API to a native code host function sendNative(method, params, cb) { console.log('sendNative',method,params); - const msg = {method: method, params: params}; - chrome.runtime.sendNativeMessage(application, msg, (response) => decodeResponse(response, cb)); + const id = nextID; + nextID += 1; + const msg = {method: method, params: params, id: id}; + + if (!port) { + port = connectPort(); + } + + callbacks.set(id, (response) => decodeResponse(response, cb)); + + port.postMessage(msg); + + // the one-off sendNativeMessage call is convenient in that it accepts a response callback, + // but it launches the host app every time, so it doesn't preserve open filehandles (for e.g. fs.open/fs.write) + //chrome.runtime.sendNativeMessage(application, msg, (response) => decodeResponse(response, cb)); } module.exports = sendNative;
a6a42353b20a9282bdb83cf45c0111954b9d6888
ember-cli-build.js
ember-cli-build.js
/* eslint-env node */ const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); module.exports = function(defaults) { var app = new EmberAddon(defaults, { // Add options here }); /* This build file specifies the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree(); };
/* eslint-env node */ const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); module.exports = function(defaults) { var app = new EmberAddon(defaults, { 'ember-cli-babel': { includePolyfill: true }, }); /* This build file specifies the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree(); };
Include ember-cli-babel polyfil to fix tests
Include ember-cli-babel polyfil to fix tests
JavaScript
mit
amiel/ember-data-url-templates,amiel/ember-data-url-templates
--- +++ @@ -3,7 +3,9 @@ module.exports = function(defaults) { var app = new EmberAddon(defaults, { - // Add options here + 'ember-cli-babel': { + includePolyfill: true + }, }); /*
1db74f03479538911f1c9336df233aea3c7cc622
karma.conf.js
karma.conf.js
var webpackConfig = require('./webpack.config'); module.exports = function (config) { config.set({ basePath: '', frameworks: ['mocha', 'chai'], files: [ 'test/**/*.ts' ], exclude: [ ], preprocessors: { 'src/**/!(defaults)/*.js': ['coverage'], 'test/**/*.ts': ['webpack'] }, webpack: { module: webpackConfig.module, resolve: webpackConfig.resolve }, reporters: ['progress', 'coverage'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['ChromeES6'], singleRun: true, concurrency: Infinity, coverageReporter: { includeAllSources: true, reporters: [ // generates ./coverage/lcov.info { type: 'lcovonly', subdir: '.' }, // generates ./coverage/coverage-final.json { type: 'json', subdir: '.' }, // generates HTML reports { type: 'html', dir: 'coverage/' } ] }, customLaunchers: { ChromeES6: { base: 'Chrome', flags: ['--javascript-harmony', '--no-sandbox'] } } }) }
var webpackConfig = require('./webpack.config'); module.exports = function (config) { config.set({ basePath: '', frameworks: ['mocha', 'chai'], files: [ 'test/**/*.ts' ], mime: { 'text/x-typescript': ['ts', 'tsx'] }, exclude: [ ], preprocessors: { 'src/**/!(defaults)/*.js': ['coverage'], 'test/**/*.ts': ['webpack'] }, webpack: { module: webpackConfig.module, resolve: webpackConfig.resolve }, reporters: ['progress', 'coverage'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['ChromeES6'], singleRun: true, concurrency: Infinity, coverageReporter: { includeAllSources: true, reporters: [ // generates ./coverage/lcov.info { type: 'lcovonly', subdir: '.' }, // generates ./coverage/coverage-final.json { type: 'json', subdir: '.' }, // generates HTML reports { type: 'html', dir: 'coverage/' } ] }, customLaunchers: { ChromeES6: { base: 'Chrome', flags: ['--javascript-harmony', '--no-sandbox'] } } }) }
Add mime type option in karma file!
Add mime type option in karma file!
JavaScript
apache-2.0
proteus-h2020/proteic,proteus-h2020/proteic,proteus-h2020/proteus-charts,proteus-h2020/proteic
--- +++ @@ -7,6 +7,11 @@ files: [ 'test/**/*.ts' ], + + mime: { + 'text/x-typescript': ['ts', 'tsx'] + }, + exclude: [ ], preprocessors: {
a551c502c03f0e324aa0765d36799f3c8305b2f2
app/utils/index.js
app/utils/index.js
const moment = require('moment'); export const dateFormat = (utcDate) => { return moment(utcDate, 'YYYY-MM-DD hh:mm:ss z').format('LLL'); };
const moment = require('moment'); export const dateFormat = (utcDate) => { return moment.utc(new Date(utcDate)).format('LLL'); };
Use Date function to help parse timezone.
Use Date function to help parse timezone.
JavaScript
mit
FuBoTeam/fubo-flea-market,FuBoTeam/fubo-flea-market
--- +++ @@ -1,5 +1,5 @@ const moment = require('moment'); export const dateFormat = (utcDate) => { - return moment(utcDate, 'YYYY-MM-DD hh:mm:ss z').format('LLL'); + return moment.utc(new Date(utcDate)).format('LLL'); };
ec5401d64467628fa318a96363dcd4ae85ff1d98
get_languages.js
get_languages.js
var request = require('request'); var yaml = require('js-yaml'); module.exports = function (callback) { var languagesURL = 'https://raw.githubusercontent.com/github/linguist/master/lib/linguist/languages.yml'; request(languagesURL, function (error, response, body) { var languages = yaml.safeLoad(body); Object.keys(languages).forEach(function (languageName) { languages[languageName] = languages[languageName].color; }); if (!error && response.statusCode === 200) { callback(languages); } else { callback(undefined); } }); };
var request = require('request'); var yaml = require('js-yaml'); module.exports = function (callback) { var languagesURL = 'https://raw.githubusercontent.com/github/linguist/master/lib/linguist/languages.yml'; request(languagesURL, function (error, response, body) { var languages = yaml.safeLoad(body); Object.keys(languages).forEach(function (languageName) { if (languages[languageName]) { languages[languageName] = languages[languageName].color; } else { delete languages[languageName]; } }); if (!error && response.statusCode === 200) { callback(languages); } else { callback(undefined); } }); };
Remove languages that don't have colors
Remove languages that don't have colors
JavaScript
mit
nicolasmccurdy/language-colors,nicolasmccurdy/language-colors
--- +++ @@ -8,7 +8,11 @@ var languages = yaml.safeLoad(body); Object.keys(languages).forEach(function (languageName) { - languages[languageName] = languages[languageName].color; + if (languages[languageName]) { + languages[languageName] = languages[languageName].color; + } else { + delete languages[languageName]; + } }); if (!error && response.statusCode === 200) {
e24f9da2e1b107767453a8693be90cfb97ebe76c
lib/index.js
lib/index.js
/** * isUndefined * Checks if a value is undefined or not. * * @name isUndefined * @function * @param {Anything} input The input value. * @returns {Boolean} `true`, if the input is `undefined`, `false` otherwise. */ module.exports = function isUndefined(input) { return typeof input === 'undefined'; };
"use strict"; /** * isUndefined * Checks if a value is undefined or not. * * @name isUndefined * @function * @param {Anything} input The input value. * @returns {Boolean} `true`, if the input is `undefined`, `false` otherwise. */ let u = void 0; module.exports = input => input === u;
Use void 0 to get the undefined value.
Use void 0 to get the undefined value.
JavaScript
mit
IonicaBizau/is-undefined
--- +++ @@ -1,3 +1,5 @@ +"use strict"; + /** * isUndefined * Checks if a value is undefined or not. @@ -7,6 +9,5 @@ * @param {Anything} input The input value. * @returns {Boolean} `true`, if the input is `undefined`, `false` otherwise. */ -module.exports = function isUndefined(input) { - return typeof input === 'undefined'; -}; +let u = void 0; +module.exports = input => input === u;
5aff66da9b38b94fe0e6b453ecb2678e0f743d8a
example/i18n/fr.js
example/i18n/fr.js
export const messages = { post: { name: 'Article', all: 'Articles', list: { search: 'Recherche', title: 'Titre', published_at: 'Publié le', commentable: 'Commentable', views: 'Vues', }, form: { title: 'Titre', published_at: 'Publié le', teaser: 'Description', body: 'Contenu', average_note: 'Note moyenne', allow_comments: 'Accepte les commentaires ?', password: 'Mot de passe (si protégé)', summary: 'Résumé', miscellaneous: 'Extra', nb_view: 'Nb de vues ?', comments: 'Commentaires', created_at: 'Créer le', }, }, comment: { name: 'Commentaire', all: 'Commentaires', form: { body: 'Contenu', created_at: 'Créer le', author_name: 'Nom de l\'auteur', }, }, author: { name: 'Auteur', list: { name: 'Nom', }, }, }; export default messages;
export const messages = { post: { name: 'Article', all: 'Articles', list: { search: 'Recherche', title: 'Titre', published_at: 'Publié le', commentable: 'Commentable', views: 'Vues', }, form: { title: 'Titre', published_at: 'Publié le', teaser: 'Description', body: 'Contenu', average_note: 'Note moyenne', allow_comments: 'Accepte les commentaires ?', password: 'Mot de passe (si protégé)', summary: 'Résumé', miscellaneous: 'Extra', nb_view: 'Nb de vues', comments: 'Commentaires', created_at: 'Créé le', }, }, comment: { name: 'Commentaire', all: 'Commentaires', form: { body: 'Contenu', created_at: 'Créé le', author_name: 'Nom de l\'auteur', }, }, author: { name: 'Auteur', list: { name: 'Nom', }, }, resources: { comments: 'Commentaire |||| Commentaires' } }; export default messages;
Fix typos in French translation of the example
Fix typos in French translation of the example
JavaScript
mit
matteolc/admin-on-rest,matteolc/admin-on-rest,marmelab/admin-on-rest,marmelab/admin-on-rest
--- +++ @@ -19,9 +19,9 @@ password: 'Mot de passe (si protégé)', summary: 'Résumé', miscellaneous: 'Extra', - nb_view: 'Nb de vues ?', + nb_view: 'Nb de vues', comments: 'Commentaires', - created_at: 'Créer le', + created_at: 'Créé le', }, }, comment: { @@ -29,7 +29,7 @@ all: 'Commentaires', form: { body: 'Contenu', - created_at: 'Créer le', + created_at: 'Créé le', author_name: 'Nom de l\'auteur', }, }, @@ -39,6 +39,9 @@ name: 'Nom', }, }, + resources: { + comments: 'Commentaire |||| Commentaires' + } }; export default messages;
cbfb5044b5d16a826f98104f52c8588fffbfb6c0
src/deploy.spec.js
src/deploy.spec.js
import {describe, it} from 'mocha'; import { assertThat, equalTo, } from 'hamjest'; const toSrcDestPairs = (files, {sourcePath, destinationPath}) => files.map(file => ({ sourceFileName: file, destinationFilename: file.replace(sourcePath, destinationPath) })) ; describe('Build src-dest pairs from file names', () => { const sourcePath = '/src/path'; const destinationPath = '/dest/path'; const deps = {sourcePath, destinationPath}; const buildPairs = (files) => toSrcDestPairs(files, deps) ; it('WHEN no file names given return empty pairs', () => { const noFiles = []; assertThat(buildPairs(noFiles), equalTo([])); }); it('WHEN one file given, replace src path with dest path', () => { const oneSrcFile = [`${sourcePath}/file.js`]; const onePair = [{ sourceFileName: `${sourcePath}/file.js`, destinationFilename: `${destinationPath}/file.js` }]; assertThat(buildPairs(oneSrcFile), equalTo(onePair)); }); });
import {describe, it} from 'mocha'; import { assertThat, equalTo, } from 'hamjest'; const toSrcDestPairs = (files, {sourcePath, destinationPath}) => files.map(file => ({ sourceFileName: file, destinationFilename: file.replace(sourcePath, destinationPath) })) ; describe('Build src-dest pairs from file names', () => { const sourcePath = '/src/path'; const destinationPath = '/dest/path'; const deps = {sourcePath, destinationPath}; const buildPairs = (files) => toSrcDestPairs(files, deps) ; it('WHEN no file names given return empty pairs', () => { const noFiles = []; assertThat(buildPairs(noFiles), equalTo([])); }); it('WHEN one file given, replace src path with dest path', () => { const oneSrcFile = [`${sourcePath}/file.js`]; const onePair = [{ sourceFileName: `${sourcePath}/file.js`, destinationFilename: `${destinationPath}/file.js` }]; assertThat(buildPairs(oneSrcFile), equalTo(onePair)); }); it('WHEN many files given, replace src path with dest path', () => { const manyFile = [ `${sourcePath}/file.js`, `${sourcePath}/any/depth/file.js`, ]; const manyPairs = [ {sourceFileName: `${sourcePath}/file.js`, destinationFilename: `${destinationPath}/file.js`}, {sourceFileName: `${sourcePath}/any/depth/file.js`, destinationFilename: `${destinationPath}/any/depth/file.js`}, ]; assertThat(buildPairs(manyFile), equalTo(manyPairs)); }); });
Write a (documenting) test that describes the "lots-case".
Write a (documenting) test that describes the "lots-case".
JavaScript
mit
tddbin/katas,tddbin/katas,tddbin/katas
--- +++ @@ -30,4 +30,15 @@ }]; assertThat(buildPairs(oneSrcFile), equalTo(onePair)); }); + it('WHEN many files given, replace src path with dest path', () => { + const manyFile = [ + `${sourcePath}/file.js`, + `${sourcePath}/any/depth/file.js`, + ]; + const manyPairs = [ + {sourceFileName: `${sourcePath}/file.js`, destinationFilename: `${destinationPath}/file.js`}, + {sourceFileName: `${sourcePath}/any/depth/file.js`, destinationFilename: `${destinationPath}/any/depth/file.js`}, + ]; + assertThat(buildPairs(manyFile), equalTo(manyPairs)); + }); });
e082e386adc50466d4c30a24dea8ce6a93b265b4
routes/admin/authenticated/sidebar/templates-list/page.connected.js
routes/admin/authenticated/sidebar/templates-list/page.connected.js
import { provideHooks } from 'redial' import { connect } from 'react-redux' import * as MobilizationActions from '~mobilizations/action-creators' import * as MobilizationSelectors from '~mobilizations/selectors' import * as TemplateActions from '~mobilizations/templates/action-creators' import * as TemplateSelectors from '~mobilizations/templates/selectors' import Page from './page' const redial = { fetch: ({ dispatch, getState, params }) => { const state = getState() const promises = [] !TemplateSelectors.isLoaded(state) && promises.push( dispatch(TemplateActions.asyncFetch()) ) promises.push(dispatch(MobilizationActions.toggleMenu(undefined))) return Promise.all(promises) } } const mapStateToProps = state => ({ loading: TemplateSelectors.isLoading(state), menuActiveIndex: MobilizationSelectors.getMenuActiveIndex(state), mobilizationTemplates: TemplateSelectors.getCustomTemplates(state) }) const mapActionCreatorsToProps = { asyncDestroyTemplate: TemplateActions.asyncDestroyTemplate, toggleMenu: MobilizationActions.toggleMenu } export default provideHooks(redial)( connect(mapStateToProps, mapActionCreatorsToProps)(Page) )
import { provideHooks } from 'redial' import { connect } from 'react-redux' import MobSelectors from '~client/mobrender/redux/selectors' import { toggleMobilizationMenu } from '~client/mobrender/redux/action-creators' import * as TemplateActions from '~mobilizations/templates/action-creators' import * as TemplateSelectors from '~mobilizations/templates/selectors' import Page from './page' const redial = { fetch: ({ dispatch, getState, params }) => { const state = getState() const promises = [] !TemplateSelectors.isLoaded(state) && promises.push( dispatch(TemplateActions.asyncFetch()) ) promises.push(dispatch(toggleMobilizationMenu(undefined))) return Promise.all(promises) } } const mapStateToProps = state => ({ loading: TemplateSelectors.isLoading(state), menuActiveIndex: MobSelectors(state).getMobilizationMenuActive(), mobilizationTemplates: TemplateSelectors.getCustomTemplates(state) }) const mapActionCreatorsToProps = { asyncDestroyTemplate: TemplateActions.asyncDestroyTemplate, toggleMenu: toggleMobilizationMenu } export default provideHooks(redial)( connect(mapStateToProps, mapActionCreatorsToProps)(Page) )
Fix menu in template list
Fix menu in template list
JavaScript
agpl-3.0
nossas/bonde-client,nossas/bonde-client,nossas/bonde-client
--- +++ @@ -1,8 +1,8 @@ import { provideHooks } from 'redial' import { connect } from 'react-redux' -import * as MobilizationActions from '~mobilizations/action-creators' -import * as MobilizationSelectors from '~mobilizations/selectors' +import MobSelectors from '~client/mobrender/redux/selectors' +import { toggleMobilizationMenu } from '~client/mobrender/redux/action-creators' import * as TemplateActions from '~mobilizations/templates/action-creators' import * as TemplateSelectors from '~mobilizations/templates/selectors' @@ -16,20 +16,20 @@ !TemplateSelectors.isLoaded(state) && promises.push( dispatch(TemplateActions.asyncFetch()) ) - promises.push(dispatch(MobilizationActions.toggleMenu(undefined))) + promises.push(dispatch(toggleMobilizationMenu(undefined))) return Promise.all(promises) } } const mapStateToProps = state => ({ loading: TemplateSelectors.isLoading(state), - menuActiveIndex: MobilizationSelectors.getMenuActiveIndex(state), + menuActiveIndex: MobSelectors(state).getMobilizationMenuActive(), mobilizationTemplates: TemplateSelectors.getCustomTemplates(state) }) const mapActionCreatorsToProps = { asyncDestroyTemplate: TemplateActions.asyncDestroyTemplate, - toggleMenu: MobilizationActions.toggleMenu + toggleMenu: toggleMobilizationMenu } export default provideHooks(redial)(
26325efdf4836d0eb44a4f987830c38562222cda
public/javascripts/app.js
public/javascripts/app.js
var app = angular.module("blogApp", []); var posts = []; app.config(function($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/home.html', controller: 'BlogCtrl' }) .when('/post/:postId', { templateUrl: 'views/post.html', controller: 'PostCtrl' }) .otherwise({ redirectTo: '/' }); }); var socket = io.connect(window.location.origin); socket.on('message', function(data) { switch(data.type) { default: break; } });
var app = angular.module("blogApp", []); var posts = []; app.config(function($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/home.html', controller: 'BlogCtrl' }) .when('/post/:postId', { templateUrl: 'views/post.html', controller: 'PostCtrl' }) .otherwise({ redirectTo: '/' }); }); var host = location.origin.replace(/^http/, 'ws'); var socket = io.connect(host); socket.on('message', function(data) { switch(data.type) { default: break; } });
Change for socket connection on Heroku
Change for socket connection on Heroku
JavaScript
mit
Somojojojo/blog
--- +++ @@ -17,7 +17,8 @@ }); }); -var socket = io.connect(window.location.origin); +var host = location.origin.replace(/^http/, 'ws'); +var socket = io.connect(host); socket.on('message', function(data) { switch(data.type)
6621c6e7cc5fb3d62d8a5fabb08cf870b72ed5fe
lib/dropbox/index.js
lib/dropbox/index.js
'use strict'; var cp = require('child_process'); var child = cp.fork(__dirname + '/child.js'); var passport = require('passport'); var DropboxOAuth2Strategy = require('passport-dropbox-oauth2').Strategy; var active = false; module.exports = function (options) { child.send({ options: options.dropbox }); return { initialize: function () { active = true; passport.use(new DropboxOAuth2Strategy({ clientID: options.dropbox.id, clientSecret: options.dropbox.secret, callbackURL: 'https://jsbin.dev/auth/dropbox/callback' }, function (accessToken, refreshToken, profile, done) { done(null, profile); } )); } }; }; module.exports.saveBin = function (file, fileName, user) { if (!active) { return; } child.send({ file: file, fileName: fileName, user: user }); };
'use strict'; var cp = require('child_process'); var child = cp.fork(__dirname + '/child.js'); var passport = require('passport'); var DropboxOAuth2Strategy = require('passport-dropbox-oauth2').Strategy; var active = false; module.exports = function (options) { child.send({ options: options.dropbox }); return { initialize: function () { active = true; passport.use(new DropboxOAuth2Strategy({ clientID: options.dropbox.id, clientSecret: options.dropbox.secret, callbackURL: 'https://jsbin.dev/auth/dropbox/callback' }, function (accessToken, refreshToken, profile, done) { profile.access_token = accessToken; done(null, profile); } )); } }; }; module.exports.saveBin = function (file, fileName, user) { if (!active) { return; } child.send({ file: file, fileName: fileName, user: user }); };
Add accessToken to profile before done
Add accessToken to profile before done
JavaScript
mit
svacha/jsbin,filamentgroup/jsbin,eggheadio/jsbin,late-warrior/jsbin,thsunmy/jsbin,pandoraui/jsbin,ilyes14/jsbin,digideskio/jsbin,saikota/jsbin,AverageMarcus/jsbin,fgrillo21/NPA-Exam,late-warrior/jsbin,peterblazejewicz/jsbin,juliankrispel/jsbin,francoisp/jsbin,ctide/jsbin,juliankrispel/jsbin,KenPowers/jsbin,mdo/jsbin,mingzeke/jsbin,dedalik/jsbin,jsbin/jsbin,IvanSanchez/jsbin,Freeformers/jsbin,jwdallas/jsbin,ilyes14/jsbin,vipulnsward/jsbin,arcseldon/jsbin,HeroicEric/jsbin,mingzeke/jsbin,digideskio/jsbin,jasonsanjose/jsbin-app,jamez14/jsbin,IvanSanchez/jsbin,yohanboniface/jsbin,saikota/jsbin,dennishu001/jsbin,jsbin/jsbin,ctide/jsbin,carolineartz/jsbin,arcseldon/jsbin,HeroicEric/jsbin,yize/jsbin,Hamcha/jsbin,johnmichel/jsbin,y3sh/jsbin-fork,pandoraui/jsbin,nitaku/jervis,fgrillo21/NPA-Exam,kentcdodds/jsbin,johnmichel/jsbin,peterblazejewicz/jsbin,knpwrs/jsbin,dennishu001/jsbin,filamentgroup/jsbin,vipulnsward/jsbin,kirjs/jsbin,eggheadio/jsbin,Hamcha/jsbin,KenPowers/jsbin,simonThiele/jsbin,francoisp/jsbin,mlucool/jsbin,dedalik/jsbin,roman01la/jsbin,yohanboniface/jsbin,blesh/jsbin,jwdallas/jsbin,jamez14/jsbin,kentcdodds/jsbin,jasonsanjose/jsbin-app,simonThiele/jsbin,thsunmy/jsbin,dhval/jsbin,IveWong/jsbin,mcanthony/jsbin,IveWong/jsbin,martinvd/jsbin,minwe/jsbin,yize/jsbin,fend-classroom/jsbin,dhval/jsbin,Freeformers/jsbin,roman01la/jsbin,AverageMarcus/jsbin,knpwrs/jsbin,y3sh/jsbin-fork,carolineartz/jsbin,mcanthony/jsbin,kirjs/jsbin,minwe/jsbin,KenPowers/jsbin,svacha/jsbin,martinvd/jsbin,mlucool/jsbin,knpwrs/jsbin,fend-classroom/jsbin,remotty/jsbin
--- +++ @@ -17,6 +17,7 @@ clientSecret: options.dropbox.secret, callbackURL: 'https://jsbin.dev/auth/dropbox/callback' }, function (accessToken, refreshToken, profile, done) { + profile.access_token = accessToken; done(null, profile); } ));
bb9858b1edbc7f8fe7a2abd70110adb50055ff8c
lib/main.js
lib/main.js
import "es6-symbol"; import "weakmap"; import svgLoader from "./loader.js"; import Icon from "./components/Icon.js"; import Sprite from "./components/Sprite.js"; import Theme from "./components/Theme.js"; var callback = function callback() { }; const icons = Icon; const initLoader = svgLoader; // loads an external SVG file as sprite. function load(loader, onFulfilled, onRejected) { if (!onRejected) { onRejected = callback; } if (typeof loader === "string") { loader = svgLoader(loader); } else if (!loader || !loader.request) { onRejected(new TypeError("Invalid Request")); } loader.onSuccess = function(svg) { make(svg, onFulfilled, onRejected); }; loader.onFailure = function(e) { onRejected(new TypeError(e)); }; loader.send(); } function make(svg, onFulfilled, onRejected) { var theme; var autorun = false; if (!onFulfilled) { onFulfilled = callback; autorun = true; } if (!onRejected) { onRejected = callback; } try { var sprite = new Sprite(svg); theme = new Theme(sprite); onFulfilled(theme); if (autorun) { theme.render(); } } catch (e) { onRejected(e); } } export { icons, initLoader, load, make };
import "es6-symbol"; import "weakmap"; import svgLoader from "./loader.js"; import Icon from "./components/Icon.js"; import Sprite from "./components/Sprite.js"; import Theme from "./components/Theme.js"; var callback = function callback() { }; const icons = Icon; const initLoader = svgLoader; // loads an external SVG file as sprite. function load(loader, onFulfilled, onRejected) { if (!onRejected) { onRejected = callback; } if (typeof loader === "string") { loader = svgLoader(loader); } else if (!loader || !loader.request) { onRejected(new TypeError("Invalid Request")); } loader.onSuccess = function onSuccess(svg) { make(svg, onFulfilled, onRejected); }; loader.onFailure = function onFailure(e) { onRejected(new TypeError(e)); }; loader.send(); } function make(svg, onFulfilled, onRejected) { var theme; var autorun = false; if (!onFulfilled) { onFulfilled = callback; autorun = true; } if (!onRejected) { onRejected = callback; } try { var sprite = new Sprite(svg); theme = new Theme(sprite); onFulfilled(theme); if (autorun) { theme.render(); } } catch (e) { onRejected(e); } } export { icons, initLoader, load, make };
Update name of callback functions
Update name of callback functions
JavaScript
mit
vuzonp/uxon
--- +++ @@ -22,11 +22,11 @@ onRejected(new TypeError("Invalid Request")); } - loader.onSuccess = function(svg) { + loader.onSuccess = function onSuccess(svg) { make(svg, onFulfilled, onRejected); }; - loader.onFailure = function(e) { + loader.onFailure = function onFailure(e) { onRejected(new TypeError(e)); };
19e3dc49302a635f51bcd552fb70b434c0968520
tests/cross-context-instance.js
tests/cross-context-instance.js
let ivm = require('isolated-vm'); let isolate = new ivm.Isolate; function makeContext() { let context = isolate.createContextSync(); let global = context.globalReference(); global.setSync('ivm', ivm); isolate.compileScriptSync(` function makeReference(ref) { return new ivm.Reference(ref); } function isReference(ref) { return ref instanceof ivm.Reference; } `).runSync(context); return { makeReference: global.getSync('makeReference'), isReference: global.getSync('isReference'), }; } let context1 = makeContext(); let context2 = makeContext(); [ context1, context2 ].forEach(context => { if (!context1.isReference.applySync(null, [ new ivm.Reference({}) ])) { console.log('fail1'); } if (!context1.isReference.applySync(null, [ context1.makeReference.applySync(null, [ 1 ]) ])) { console.log('fail2'); } }); if (context1.isReference.applySync(null, [ context2.makeReference.applySync(null, [ 1 ]).derefInto() ])) { console.log('fail3'); } console.log('pass');
let ivm = require('isolated-vm'); let isolate = new ivm.Isolate; function makeContext() { let context = isolate.createContextSync(); let global = context.globalReference(); global.setSync('ivm', ivm); isolate.compileScriptSync(` function makeReference(ref) { return new ivm.Reference(ref); } function isReference(ref) { return ref instanceof ivm.Reference; } `).runSync(context); return { makeReference: global.getSync('makeReference'), isReference: global.getSync('isReference'), }; } let context1 = makeContext(); let context2 = makeContext(); [ context1, context2 ].forEach(context => { if (!context.isReference.applySync(null, [ new ivm.Reference({}) ])) { console.log('fail1'); } if (!context.isReference.applySync(null, [ context.makeReference.applySync(null, [ 1 ]) ])) { console.log('fail2'); } }); if (context1.isReference.applySync(null, [ context2.makeReference.applySync(null, [ 1 ]).derefInto() ])) { console.log('fail3'); } console.log('pass');
Fix test wasn't actually testing
Fix test wasn't actually testing
JavaScript
isc
laverdet/isolated-vm,laverdet/isolated-vm,laverdet/isolated-vm,laverdet/isolated-vm
--- +++ @@ -22,10 +22,10 @@ let context1 = makeContext(); let context2 = makeContext(); [ context1, context2 ].forEach(context => { - if (!context1.isReference.applySync(null, [ new ivm.Reference({}) ])) { + if (!context.isReference.applySync(null, [ new ivm.Reference({}) ])) { console.log('fail1'); } - if (!context1.isReference.applySync(null, [ context1.makeReference.applySync(null, [ 1 ]) ])) { + if (!context.isReference.applySync(null, [ context.makeReference.applySync(null, [ 1 ]) ])) { console.log('fail2'); } });
0c44942fa439737c8adf26a2e196bbd700e18e66
R7.University.Employee/js/module.js
R7.University.Employee/js/module.js
$(function () { // paint tables with dnnGrid classes var table = ".employeeDetails #employeeDisciplines table"; $(table).addClass ("dnnGrid").css ("border-collapse", "collapse"); // use parent () to get rows with matched cell types $(table + " tr:nth-child(even) td").parent ().addClass ("dnnGridItem"); $(table + " tr:nth-child(odd) td").parent ().addClass ("dnnGridAltItem"); // paint headers $(table + " tr th").parent ().addClass ("dnnGridHeader").attr ("align", "left"); });
$(function () { // paint tables with dnnGrid classes var table = ".employeeDetails #employeeDisciplines table"; $(table).addClass ("dnnGrid").css ("border-collapse", "collapse"); // use parent () to get rows with matched cell types $(table + " tr:nth-child(even) td").parent ().addClass ("dnnGridItem") .next ().addClass ("dnnGridAltItem"); // paint headers $(table + " tr th").parent ().addClass ("dnnGridHeader").attr ("align", "left"); });
Optimize & fix table painting script
Optimize & fix table painting script
JavaScript
agpl-3.0
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
--- +++ @@ -3,8 +3,8 @@ var table = ".employeeDetails #employeeDisciplines table"; $(table).addClass ("dnnGrid").css ("border-collapse", "collapse"); // use parent () to get rows with matched cell types - $(table + " tr:nth-child(even) td").parent ().addClass ("dnnGridItem"); - $(table + " tr:nth-child(odd) td").parent ().addClass ("dnnGridAltItem"); + $(table + " tr:nth-child(even) td").parent ().addClass ("dnnGridItem") + .next ().addClass ("dnnGridAltItem"); // paint headers $(table + " tr th").parent ().addClass ("dnnGridHeader").attr ("align", "left"); });
ef259591d22d303c351b419f130b13061e28771a
app/native/src/types/Navigation.js
app/native/src/types/Navigation.js
// @flow export type Navigation = { navigate: (screen: string, parameters?: Object) => void, state: { params: Object, }, };
// @flow type NavigationStateParameters = Object; /** * @see https://reactnavigation.org/docs/navigators/navigation-prop */ export type Navigation = { navigate: (routeName: string, parameters?: NavigationStateParameters) => void, state: { params: NavigationStateParameters, }, setParams: (newParameters: NavigationStateParameters) => void, goBack: () => void, };
Improve Flow type of the navigation
Improve Flow type of the navigation
JavaScript
mit
mrtnzlml/native,mrtnzlml/native
--- +++ @@ -1,8 +1,15 @@ // @flow +type NavigationStateParameters = Object; + +/** + * @see https://reactnavigation.org/docs/navigators/navigation-prop + */ export type Navigation = { - navigate: (screen: string, parameters?: Object) => void, + navigate: (routeName: string, parameters?: NavigationStateParameters) => void, state: { - params: Object, + params: NavigationStateParameters, }, + setParams: (newParameters: NavigationStateParameters) => void, + goBack: () => void, };
1b6904a33c0f83eddf6c759ebe4243d54eb1f54f
app/services/resizeable-columns.js
app/services/resizeable-columns.js
import Ember from "ember"; const { $, inject, run } = Ember; export default Ember.Service.extend({ fastboot: inject.service(), init() { this._super(...arguments); if (!this.get('fastboot.isFastBoot')) { this.setupMouseEventsFromIframe(); } }, setupMouseEventsFromIframe() { window.addEventListener('message', (m) => { run(() => { if(typeof m.data==='object' && 'mousemove' in m.data) { let event = $.Event("mousemove", { pageX: m.data.mousemove.pageX + $("#dummy-content-iframe").offset().left, pageY: m.data.mousemove.pageY + $("#dummy-content-iframe").offset().top }); $(window).trigger(event); } if(typeof m.data==='object' && 'mouseup' in m.data) { let event = $.Event("mouseup", { pageX: m.data.mouseup.pageX + $("#dummy-content-iframe").offset().left, pageY: m.data.mouseup.pageY + $("#dummy-content-iframe").offset().top }); $(window).trigger(event); } }); }); } });
import Ember from "ember"; const { $, inject, run } = Ember; export default Ember.Service.extend({ fastboot: inject.service(), init() { this._super(...arguments); if (!this.get('fastboot.isFastBoot')) { this.setupMouseEventsFromIframe(); } }, handleMouseEvents(m, mouseEvent) { const event = $.Event(mouseEvent, { pageX: m.pageX + $("#dummy-content-iframe").offset().left, pageY: m.pageY + $("#dummy-content-iframe").offset().top }); $(window).trigger(event); }, setupMouseEventsFromIframe() { window.addEventListener('message', (m) => { run(() => { if(typeof m.data==='object' && 'mousemove' in m.data) { this.handleMouseEvents(m.data.mousemove, 'mousemove'); } if(typeof m.data==='object' && 'mouseup' in m.data) { this.handleMouseEvents(m.data.mouseup, 'mousemove'); } }); }); } });
Refactor mouse events in resizeable columns
Refactor mouse events in resizeable columns
JavaScript
mit
ember-cli/ember-twiddle,ember-cli/ember-twiddle,Gaurav0/ember-twiddle,Gaurav0/ember-twiddle,knownasilya/ember-twiddle,knownasilya/ember-twiddle,knownasilya/ember-twiddle,ember-cli/ember-twiddle,Gaurav0/ember-twiddle
--- +++ @@ -12,22 +12,23 @@ } }, + handleMouseEvents(m, mouseEvent) { + const event = $.Event(mouseEvent, { + pageX: m.pageX + $("#dummy-content-iframe").offset().left, + pageY: m.pageY + $("#dummy-content-iframe").offset().top + }); + $(window).trigger(event); + }, + setupMouseEventsFromIframe() { window.addEventListener('message', (m) => { run(() => { if(typeof m.data==='object' && 'mousemove' in m.data) { - let event = $.Event("mousemove", { - pageX: m.data.mousemove.pageX + $("#dummy-content-iframe").offset().left, - pageY: m.data.mousemove.pageY + $("#dummy-content-iframe").offset().top - }); - $(window).trigger(event); + this.handleMouseEvents(m.data.mousemove, 'mousemove'); } + if(typeof m.data==='object' && 'mouseup' in m.data) { - let event = $.Event("mouseup", { - pageX: m.data.mouseup.pageX + $("#dummy-content-iframe").offset().left, - pageY: m.data.mouseup.pageY + $("#dummy-content-iframe").offset().top - }); - $(window).trigger(event); + this.handleMouseEvents(m.data.mouseup, 'mousemove'); } }); });
78874dcdad510e76c2ee6d47c6b0ac72073b3e7c
lib/loaders/index.js
lib/loaders/index.js
import loadersWithAuthentication from "./loaders_with_authentication" import loadersWithoutAuthentication from "./loaders_without_authentication" export default (accessToken, userID) => { const loaders = loadersWithoutAuthentication() if (accessToken) { return Object.assign({}, loaders, loadersWithAuthentication(accessToken, userID)) } return loaders }
import loadersWithAuthentication from "./loaders_with_authentication" import loadersWithoutAuthentication from "./loaders_without_authentication" /** * Creates a new set of data loaders for all routes. These should be created for each GraphQL query and passed to the * `graphql` query execution function. * * Only if credentials are provided will the set include authenticated loaders, so before using an authenticated loader * it would be wise to check if the loader is not in fact `undefined`. */ export default (accessToken, userID) => { const loaders = loadersWithoutAuthentication() if (accessToken) { return Object.assign({}, loaders, loadersWithAuthentication(accessToken, userID)) } return loaders }
Add documentation for a bunch of functions.
[loaders] Add documentation for a bunch of functions.
JavaScript
mit
craigspaeth/metaphysics,mzikherman/metaphysics-1,artsy/metaphysics,artsy/metaphysics,craigspaeth/metaphysics,mzikherman/metaphysics-1,artsy/metaphysics,mzikherman/metaphysics-1,mzikherman/metaphysics-1
--- +++ @@ -1,6 +1,13 @@ import loadersWithAuthentication from "./loaders_with_authentication" import loadersWithoutAuthentication from "./loaders_without_authentication" +/** + * Creates a new set of data loaders for all routes. These should be created for each GraphQL query and passed to the + * `graphql` query execution function. + * + * Only if credentials are provided will the set include authenticated loaders, so before using an authenticated loader + * it would be wise to check if the loader is not in fact `undefined`. + */ export default (accessToken, userID) => { const loaders = loadersWithoutAuthentication() if (accessToken) {
da8027163e556a84e60d0c41bd61ea4b8a42ef05
src/renderer/scr.dom.js
src/renderer/scr.dom.js
var DOM = (function(){ var entityMap = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': '&quot;', "'": '&#39;', "/": '&#x2F;' }; var entityRegex = /[&<>"'\/]/g; return { /* * Returns a child element by its ID. Parent defaults to the entire document. */ id: function(id, parent){ return (parent || document).getElementById(id); }, /* * Returns an array of all child elements containing the specified class. Parent defaults to the entire document. */ cls: function(cls, parent){ return Array.prototype.slice.call((parent || document).getElementsByClassName(cls)); }, /* * Returns an array of all child elements that have the specified tag. Parent defaults to the entire document. */ tag: function(tag, parent){ return Array.prototype.slice.call((parent || document).getElementsByTagName(tag)); }, /* * Creates an element, adds it to the DOM, and returns it. */ createElement: function(tag, parent){ var ele = document.createElement(tag); parent.appendChild(ele); return ele; }, /* * Removes an element from the DOM. */ removeElement: function(ele){ ele.parentNode.removeChild(ele); }, /* * Converts characters to their HTML entity form. */ escapeHTML: function(html){ return html.replace(entityRegex, s => entityMap[s]); } }; })();
var DOM = (function(){ var entityMap = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': '&quot;', "'": '&#39;', "/": '&#x2F;' }; var entityRegex = /[&<>"'\/]/g; return { /* * Returns a child element by its ID. Parent defaults to the entire document. */ id: function(id, parent){ return (parent || document).getElementById(id); }, /* * Returns an array of all child elements containing the specified class. Parent defaults to the entire document. */ cls: function(cls, parent){ return Array.prototype.slice.call((parent || document).getElementsByClassName(cls)); }, /* * Returns an array of all child elements that have the specified tag. Parent defaults to the entire document. */ tag: function(tag, parent){ return Array.prototype.slice.call((parent || document).getElementsByTagName(tag)); }, /* * Creates an element, adds it to the DOM, and returns it. */ createElement: function(tag, parent){ var ele = document.createElement(tag); parent.appendChild(ele); return ele; }, /* * Removes an element from the DOM. */ removeElement: function(ele){ ele.parentNode.removeChild(ele); }, /* * Converts characters to their HTML entity form. */ escapeHTML: function(html){ return String(html).replace(entityRegex, s => entityMap[s]); } }; })();
Fix HTML escaping in renderer crashing on non-string values
Fix HTML escaping in renderer crashing on non-string values
JavaScript
mit
chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker
--- +++ @@ -52,7 +52,7 @@ * Converts characters to their HTML entity form. */ escapeHTML: function(html){ - return html.replace(entityRegex, s => entityMap[s]); + return String(html).replace(entityRegex, s => entityMap[s]); } }; })();
9520ab1f9e7020879c8e3c2e8f6faad31fd572ef
Kwc/Shop/Box/Cart/Component.defer.js
Kwc/Shop/Box/Cart/Component.defer.js
var onReady = require('kwf/on-ready'); var $ = require('jQuery'); var getKwcRenderUrl = require('kwf/get-kwc-render-url'); onReady.onRender('.kwcClass',function(el) { var url = getKwcRenderUrl(); $.each($('.kwfUp-addToCardForm .kwfUp-formContainer'), $.proxy(function(index, form) { $(form).on('kwfUp-form-submitSuccess', $.proxy(function(event) { $.ajax({ url: url, data: { componentId: el.data('component-id') }, success: function(response) { el.html(response); onReady.callOnContentReady(el, {newRender: true}); } }); }, el)); }, el)); }, { priority: 0 }); //call after Kwc.Form.Component
var onReady = require('kwf/on-ready'); var $ = require('jQuery'); var getKwcRenderUrl = require('kwf/get-kwc-render-url'); onReady.onRender('.kwcClass',function(el) { var url = getKwcRenderUrl(); $.each($('.kwfUp-addToCardForm .kwfUp-formContainer'), $.proxy(function(index, form) { $(form).on('kwfUp-form-submitSuccess', $.proxy(function(event) { $.ajax({ url: url, data: { componentId: el.data('component-id') }, success: function(response) { $('.kwcClass').html(response); onReady.callOnContentReady(el, {newRender: true}); } }); }, el)); }, el)); }, { priority: 0 }); //call after Kwc.Form.Component
Fix wrong exchange of cartbox-domelement
Fix wrong exchange of cartbox-domelement
JavaScript
bsd-2-clause
koala-framework/koala-framework,koala-framework/koala-framework
--- +++ @@ -11,7 +11,7 @@ url: url, data: { componentId: el.data('component-id') }, success: function(response) { - el.html(response); + $('.kwcClass').html(response); onReady.callOnContentReady(el, {newRender: true}); } });
b4dfceadd3a541cb13d5a69a4ef799dce1dc2037
web/src/js/components/Dashboard/DashboardContainer.js
web/src/js/components/Dashboard/DashboardContainer.js
import graphql from 'babel-plugin-relay/macro' import { createFragmentContainer } from 'react-relay' import Dashboard from 'js/components/Dashboard/DashboardComponent' export default createFragmentContainer(Dashboard, { app: graphql` fragment DashboardContainer_app on App { campaign { isLive } ...UserMenuContainer_app } `, user: graphql` fragment DashboardContainer_user on User { id experimentActions { referralNotification searchIntro } joined searches tabs ...WidgetsContainer_user ...UserBackgroundImageContainer_user ...UserMenuContainer_user ...LogTabContainer_user ...LogRevenueContainer_user ...LogConsentDataContainer_user ...LogAccountCreationContainer_user ...NewUserTourContainer_user ...AssignExperimentGroupsContainer_user } `, })
import graphql from 'babel-plugin-relay/macro' import { createFragmentContainer } from 'react-relay' import Dashboard from 'js/components/Dashboard/DashboardComponent' export default createFragmentContainer(Dashboard, { app: graphql` fragment DashboardContainer_app on App { campaign { isLive numNewUsers # TODO: remove later. For testing Redis. } ...UserMenuContainer_app } `, user: graphql` fragment DashboardContainer_user on User { id experimentActions { referralNotification searchIntro } joined searches tabs ...WidgetsContainer_user ...UserBackgroundImageContainer_user ...UserMenuContainer_user ...LogTabContainer_user ...LogRevenueContainer_user ...LogConsentDataContainer_user ...LogAccountCreationContainer_user ...NewUserTourContainer_user ...AssignExperimentGroupsContainer_user } `, })
Add data fetching for testing out Redis
Add data fetching for testing out Redis
JavaScript
mpl-2.0
gladly-team/tab,gladly-team/tab,gladly-team/tab
--- +++ @@ -8,6 +8,7 @@ fragment DashboardContainer_app on App { campaign { isLive + numNewUsers # TODO: remove later. For testing Redis. } ...UserMenuContainer_app }
25376ac4975c5d5021b40438f8954a6faa24e21d
lib/config.js
lib/config.js
var Fs = require('fs'); var config = module.exports = {}; // Configuring TLS config.tls = { key: Fs.readFileSync('./lib/certs/key.key'), cert: Fs.readFileSync('./lib/certs/cert.crt'), // Only necessary if using the client certificate authentication. requestCert: true, // Only necessary only if client is using the self-signed certificate. ca: [] }; config.crumb = { cookieOptions: { isSecure: true }, autoGenerate: true }; config.monitor = { opsInterval: 1000, reporters: [{ reporter: require('good-console'), events: { log: '*', response: '*' } }, { reporter: require('good-file'), events: { ops: '*' }, config: './test/fixtures/monitor_log' }, { reporter: 'good-http', events: { ops: '*', log: '*', response: '*' }, config: { endpoint: 'http://localhost:3000', wreck: { headers: { 'x-api-key': 12345 } } } }] };
var Fs = require('fs'); var config = module.exports = {}; // Configuring TLS config.tls = { key: Fs.readFileSync('./lib/certs/key.key'), cert: Fs.readFileSync('./lib/certs/cert.crt'), // Only necessary if using the client certificate authentication. requestCert: true, // Only necessary only if client is using the self-signed certificate. ca: [] }; config.crumb = { cookieOptions: { isSecure: true }, autoGenerate: true }; config.monitor = { opsInterval: 1000, reporters: [{ reporter: require('good-console'), events: { log: '*', response: '*' } }, { reporter: require('good-file'), events: { ops: '*' }, config: './test/fixtures/monitor_log' }] }; // @Example of logging to a remote server. // config.monitor = { // opsInterval: 1000, // reporters: [{ // reporter: require('good-console'), // events: { log: '*', response: '*' } // }, { // reporter: require('good-file'), // events: { ops: '*' }, // config: './test/fixtures/monitor_log' // }, { // reporter: 'good-http', // events: { ops: '*', log: '*', response: '*' }, // config: { // endpoint: 'http://localhost:3000', // wreck: { // headers: { 'x-api-key': 12345 } // } // } // }] // };
Refactor good stop sending logs to remote server
Refactor good stop sending logs to remote server Comments in lib/config.js still show how to send logs to remote server. But, it is not used.
JavaScript
bsd-3-clause
jd73/university,jd73/university
--- +++ @@ -19,7 +19,6 @@ autoGenerate: true }; - config.monitor = { opsInterval: 1000, reporters: [{ @@ -29,15 +28,27 @@ reporter: require('good-file'), events: { ops: '*' }, config: './test/fixtures/monitor_log' - }, { - reporter: 'good-http', - events: { ops: '*', log: '*', response: '*' }, - config: { - endpoint: 'http://localhost:3000', - wreck: { - headers: { 'x-api-key': 12345 } - } - } }] }; +// @Example of logging to a remote server. +// config.monitor = { +// opsInterval: 1000, +// reporters: [{ +// reporter: require('good-console'), +// events: { log: '*', response: '*' } +// }, { +// reporter: require('good-file'), +// events: { ops: '*' }, +// config: './test/fixtures/monitor_log' +// }, { +// reporter: 'good-http', +// events: { ops: '*', log: '*', response: '*' }, +// config: { +// endpoint: 'http://localhost:3000', +// wreck: { +// headers: { 'x-api-key': 12345 } +// } +// } +// }] +// };
fa1c80fabddcf07bc6a81f581b36a3a26578fc02
src/js/app/main.js
src/js/app/main.js
/** * Load all the Views. */ require([ 'models/user', 'controllers/home', 'outer' ], function (User, Home, Router) { var users = [new User('Barney'), new User('Cartman'), new User('Sheldon')]; localStorage.users = JSON.stringify(users); Home.start(); Router.startRouting(); });
/** * Load all the Views. */ require([ 'models/user', 'controllers/home', 'router' ], function (User, Home, Router) { var users = [new User('Barney'), new User('Cartman'), new User('Sheldon')]; localStorage.users = JSON.stringify(users); Home.start(); Router.startRouting(); });
Rename router file part iii.
Rename router file part iii.
JavaScript
mit
quantumtom/rainbow-dash,quantumtom/rainbow-dash,quantumtom/ash,quantumtom/ash
--- +++ @@ -5,7 +5,7 @@ require([ 'models/user', 'controllers/home', - 'outer' + 'router' ], function (User, Home, Router) { var users = [new User('Barney'),
2b261f89e9820a4697e0a812defaec05385fad51
test/spec/controllers/main.js
test/spec/controllers/main.js
'use strict'; describe('Controller: MainCtrl', function () { // load the controller's module beforeEach(module('quakeStatsApp')); var MainCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
'use strict'; describe('Controller: MainCtrl', function () { // load the controller's module beforeEach(module('quakeStatsApp')); var MainCtrl, scope, mockStats = { gamesStats: [] }; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope, Constants: {}, stats: mockStats }); })); it('should attach a list of games to the scope', function () { expect(scope.games).toBeDefined(); }); });
Make the first dummy test pass
Tests: Make the first dummy test pass
JavaScript
mit
mbarzeev/quake-stats,mbarzeev/quake-stats
--- +++ @@ -6,17 +6,22 @@ beforeEach(module('quakeStatsApp')); var MainCtrl, - scope; + scope, + mockStats = { + gamesStats: [] + }; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { - $scope: scope + $scope: scope, + Constants: {}, + stats: mockStats }); })); - it('should attach a list of awesomeThings to the scope', function () { - expect(scope.awesomeThings.length).toBe(3); + it('should attach a list of games to the scope', function () { + expect(scope.games).toBeDefined(); }); });
d111e99ba98e357e1f13eb8b8e83da5e188b9d0a
lib/readTemplate.js
lib/readTemplate.js
'use strict'; const fs = require('fs'); const Promise = require('bluebird'); const readFile = Promise.promisify(fs.readFile, { context: fs }); const cache = require('./cache'); module.exports = readTemplate; function readTemplate(path, callback) { const cacheKey = `template.${path}`; if (process.env.NODE_ENV === 'production') { return cache.get(cacheKey) .catch((err) => { return readFile(path) .then((buf) => buf.toString()) .then((value) => cache.put(cacheKey, value, { ttl: 0 })); }) .asCallback(callback); } else { return readFile(path) .then((buf) => buf.toString()) .asCallback(callback); } };
'use strict'; const fs = require('fs'); const Promise = require('bluebird'); const readFile = Promise.promisify(fs.readFile, { context: fs }); const cache = require('./cache'); module.exports = readTemplate; function readTemplate(path, callback) { const cacheKey = `template.${path}`; return cache.get(cacheKey) .catch((err) => { return readFile(path) .then((buf) => buf.toString()) .then((value) => cache.put(cacheKey, value, { ttl: 0 })); }) .asCallback(callback); };
Revert "only cache templates in production"
Revert "only cache templates in production" This reverts commit 4e2bf7d48d60bba8b4d4497786e4db0ab8f81bef.
JavaScript
apache-2.0
carsdotcom/windshieldjs,carsdotcom/windshieldjs
--- +++ @@ -8,18 +8,11 @@ function readTemplate(path, callback) { const cacheKey = `template.${path}`; - - if (process.env.NODE_ENV === 'production') { - return cache.get(cacheKey) - .catch((err) => { - return readFile(path) - .then((buf) => buf.toString()) - .then((value) => cache.put(cacheKey, value, { ttl: 0 })); - }) - .asCallback(callback); - } else { - return readFile(path) - .then((buf) => buf.toString()) - .asCallback(callback); - } + return cache.get(cacheKey) + .catch((err) => { + return readFile(path) + .then((buf) => buf.toString()) + .then((value) => cache.put(cacheKey, value, { ttl: 0 })); + }) + .asCallback(callback); };
62624f36608eb495e18050fdff395b39bd69fd22
app/assets/javascripts/spree/checkout/payment/adyen_encrypted_credit_card.js
app/assets/javascripts/spree/checkout/payment/adyen_encrypted_credit_card.js
Spree.createEncryptedAdyenForm = function(paymentMethodId) {  document.addEventListener("DOMContentLoaded", function() { var checkout_form = document.getElementById("checkout_form_payment") // See adyen.encrypt.simple.html for details on the options to use var options = { name: "payment_source[" + paymentMethodId + "][encrypted_credit_card_data]", enableValidations : true, // If there's other payment methods, they need to be able to submit submitButtonAlwaysEnabled: true, disabledValidClass: true }; // Create the form. // Note that the method is on the Adyen object, not the adyen.encrypt object. return adyen.createEncryptedForm(checkout_form, options); }); }
Spree.createEncryptedAdyenForm = function(paymentMethodId) {  document.addEventListener("DOMContentLoaded", function() { var checkout_form = document.getElementById("checkout_form_payment") // See adyen.encrypt.simple.html for details on the options to use var options = { name: "payment_source[" + paymentMethodId + "][encrypted_credit_card_data]", enableValidations : true, // If there's other payment methods, they need to be able to submit submitButtonAlwaysEnabled: false, disabledValidClass: true }; // Create the form. // Note that the method is on the Adyen object, not the adyen.encrypt object. return adyen.createEncryptedForm(checkout_form, options); }); }
Enable validations on CC form
Enable validations on CC form
JavaScript
mit
freerunningtech/solidus-adyen,StemboltHQ/solidus-adyen,freerunningtech/solidus-adyen,StemboltHQ/solidus-adyen,StemboltHQ/solidus-adyen,freerunningtech/solidus-adyen,StemboltHQ/solidus-adyen,freerunningtech/solidus-adyen
--- +++ @@ -6,7 +6,7 @@ name: "payment_source[" + paymentMethodId + "][encrypted_credit_card_data]", enableValidations : true, // If there's other payment methods, they need to be able to submit - submitButtonAlwaysEnabled: true, + submitButtonAlwaysEnabled: false, disabledValidClass: true }; // Create the form.
25ecb5e4f4bfeac33198913ec49bdb8b2412f462
MovieFinder/src/main/webapp/public/src/controllers/nav-controller.js
MovieFinder/src/main/webapp/public/src/controllers/nav-controller.js
// // nav-controller.js // Contains the controller for the nav-bar. // (function () { 'use strict'; angular.module('movieFinder.controllers') .controller('NavCtrl', function ($scope, $modal, user) { var _this = this; var signInModal; this.error = { signIn: '' }; this.showSignInModal = function () { signInModal = $modal({ scope: $scope, template: 'partials/modals/sign-in.html', container: 'body' }); }; this.login = function (username, password) { user.login(username, password).success(function(){ signInModal.$promise.then(signInModal.hide); }).error(function(){ _this.error.signIn = 'Some error message'; }); }; this.logout = function() { user.logout(); }; }); })();
// // nav-controller.js // Contains the controller for the nav-bar. // (function () { 'use strict'; angular.module('movieFinder.controllers') .controller('NavCtrl', function ($scope, $modal, user) { var _this = this; var signInModal; this.error = { signIn: '' }; this.showSignInModal = function () { this.error.signIn = ''; signInModal = $modal({ scope: $scope, template: 'partials/modals/sign-in.html', container: 'body' }); }; this.login = function (username, password) { user.login(username, password).success(function(){ signInModal.$promise.then(signInModal.hide); }).error(function(){ _this.error.signIn = 'Some error message'; }); }; this.logout = function() { user.logout(); }; }); })();
Reset error message when dialog re-opened.
Reset error message when dialog re-opened.
JavaScript
mit
we4sz/DAT076,we4sz/DAT076
--- +++ @@ -17,6 +17,8 @@ }; this.showSignInModal = function () { + this.error.signIn = ''; + signInModal = $modal({ scope: $scope, template: 'partials/modals/sign-in.html',
633dd358d078e50503406f15f8b46b8ba9fce951
src/modules/sound.js
src/modules/sound.js
let lastPachiIndex = -1 let lastCaptureIndex = -1 let captureSounds = Object.keys(new Int8Array(5)).map(x => new Audio(`./data/capture${x}.mp3`)) let pachiSounds = Object.keys(new Int8Array(5)).map(x => new Audio(`./data/${x}.mp3`)) let newGameSound = new Audio('./data/newgame.mp3') let passSound = new Audio('./data/pass.mp3') exports.playPachi = function(delay = 0) { let index = lastPachiIndex while (index === lastPachiIndex) { index = Math.floor(Math.random() * pachiSounds.length) } lastPachiIndex = index setTimeout(() => pachiSounds[index].play(), delay) } exports.playCapture = function(delay = 0) { let index = lastCaptureIndex while (index === lastCaptureIndex) { index = Math.floor(Math.random() * captureSounds.length) } lastCaptureIndex = index setTimeout(() => captureSounds[index].play(), delay) } exports.playPass = function(delay = 0) { setTimeout(() => passSound.play(), delay) } exports.playNewGame = function(delay = 0) { setTimeout(() => newGameSound.play(), delay) }
const helper = require('./helper') let lastPachiIndex = -1 let lastCaptureIndex = -1 let captureSounds = [...Array(5)].map((_, i) => new Audio(`./data/capture${i}.mp3`)) let pachiSounds = [...Array(5)].map((_, i) => new Audio(`./data/${i}.mp3`)) let newGameSound = new Audio('./data/newgame.mp3') let passSound = new Audio('./data/pass.mp3') exports.playPachi = function(delay = 0) { let index = lastPachiIndex while (index === lastPachiIndex) { index = Math.floor(Math.random() * pachiSounds.length) } lastPachiIndex = index setTimeout(() => pachiSounds[index].play().catch(helper.noop), delay) } exports.playCapture = function(delay = 0) { let index = lastCaptureIndex while (index === lastCaptureIndex) { index = Math.floor(Math.random() * captureSounds.length) } lastCaptureIndex = index setTimeout(() => captureSounds[index].play().catch(helper.noop), delay) } exports.playPass = function(delay = 0) { setTimeout(() => passSound.play().catch(helper.noop), delay) } exports.playNewGame = function(delay = 0) { setTimeout(() => newGameSound.play().catch(helper.noop), delay) }
Fix weird error messages about play() and pause()
Fix weird error messages about play() and pause()
JavaScript
mit
yishn/Sabaki,yishn/Goban,yishn/Goban,yishn/Sabaki
--- +++ @@ -1,8 +1,10 @@ +const helper = require('./helper') + let lastPachiIndex = -1 let lastCaptureIndex = -1 -let captureSounds = Object.keys(new Int8Array(5)).map(x => new Audio(`./data/capture${x}.mp3`)) -let pachiSounds = Object.keys(new Int8Array(5)).map(x => new Audio(`./data/${x}.mp3`)) +let captureSounds = [...Array(5)].map((_, i) => new Audio(`./data/capture${i}.mp3`)) +let pachiSounds = [...Array(5)].map((_, i) => new Audio(`./data/${i}.mp3`)) let newGameSound = new Audio('./data/newgame.mp3') let passSound = new Audio('./data/pass.mp3') @@ -16,7 +18,7 @@ lastPachiIndex = index - setTimeout(() => pachiSounds[index].play(), delay) + setTimeout(() => pachiSounds[index].play().catch(helper.noop), delay) } exports.playCapture = function(delay = 0) { @@ -28,13 +30,13 @@ lastCaptureIndex = index - setTimeout(() => captureSounds[index].play(), delay) + setTimeout(() => captureSounds[index].play().catch(helper.noop), delay) } exports.playPass = function(delay = 0) { - setTimeout(() => passSound.play(), delay) + setTimeout(() => passSound.play().catch(helper.noop), delay) } exports.playNewGame = function(delay = 0) { - setTimeout(() => newGameSound.play(), delay) + setTimeout(() => newGameSound.play().catch(helper.noop), delay) }
c1a1f8f3ddf1485016c3d70c2ceca66be42608f3
src/server.js
src/server.js
var express = require('express'); var app = express(); app.use('/game', express.static(__dirname + '/public')); var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('Node app is up and running to serve static HTML content.'); });
var express = require('express'); var app = express(); app.use('/app', express.static(__dirname + '/public')); var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('Node app is up and running to serve static HTML content.'); });
Fix that URL--we just have to update Kibana.
Fix that URL--we just have to update Kibana.
JavaScript
apache-2.0
gameontext/gameon-webapp,gameontext/gameon-webapp,gameontext/gameon-webapp
--- +++ @@ -1,7 +1,7 @@ var express = require('express'); var app = express(); -app.use('/game', express.static(__dirname + '/public')); +app.use('/app', express.static(__dirname + '/public')); var server = app.listen(3000, function () { var host = server.address().address;
87407f3dbd25b823d05f2f5b03475a7ecc391438
lib/geoloc.js
lib/geoloc.js
var geoip = require('geoip'); function Point(latitude, longitude) { this.latitude = latitude; this.longitude = longitude; } module.exports = { /* * Returns geoloc Point from the requester's ip adress * @throws Exception */ getPointfromIp: function(ip, geoliteConfig) { var latitude, longitude; var city = new geoip.City(geoliteConfig.geolitepath); var geo = city.lookupSync(ip); if (!geo) { return null; } longitude = geo.longitude; latitude = geo.latitude; return new Point(latitude, longitude); }, getCityFromIp : function (ip, geoliteConfig) { var city = new geoip.City(geoliteConfig.geolitepath); return city.lookupSync(ip); } };
var geoip = require('geoip'); function Point(latitude, longitude) { this.latitude = latitude; this.longitude = longitude; } module.exports = { /* * Returns geoloc Point from the requester's ip adress * @throws Exception */ getPointfromIp: function(ip, geolitePath) { var latitude, longitude; var city = new geoip.City(geolitePath); var geo = city.lookupSync(ip); if (!geo) { return null; } longitude = geo.longitude; latitude = geo.latitude; return new Point(latitude, longitude); }, getCityFromIp : function (ip, geolitePath) { var city = new geoip.City(geolitePath); return city.lookupSync(ip); } };
Change getPointFromIp & getCityFromIp methods signature
Change getPointFromIp & getCityFromIp methods signature
JavaScript
mit
Jumplead/GeonamesServer,Jumplead/GeonamesServer,xjewer/GeonamesServer,xjewer/GeonamesServer,xjewer/GeonamesServer,Jumplead/GeonamesServer,Jumplead/GeonamesServer
--- +++ @@ -10,10 +10,10 @@ * Returns geoloc Point from the requester's ip adress * @throws Exception */ - getPointfromIp: function(ip, geoliteConfig) { + getPointfromIp: function(ip, geolitePath) { var latitude, longitude; - var city = new geoip.City(geoliteConfig.geolitepath); + var city = new geoip.City(geolitePath); var geo = city.lookupSync(ip); if (!geo) { @@ -25,8 +25,8 @@ return new Point(latitude, longitude); }, - getCityFromIp : function (ip, geoliteConfig) { - var city = new geoip.City(geoliteConfig.geolitepath); + getCityFromIp : function (ip, geolitePath) { + var city = new geoip.City(geolitePath); return city.lookupSync(ip); }
152c0faec45c4b754b3496a37de0884df11eb5bb
isProduction.js
isProduction.js
if (process && process.env && process.env.NODE_ENV === 'production') { console.warn([ 'You are running Mimic in production mode,', 'in most cases you only want to run Mimic in development environments.\r\n', 'For more information on how to load Mimic in development environments only please see:', 'https://github.com/500tech/mimic#loading-mimic-only-in-development-environments' ].join(' ')); }
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'production') { console.warn([ 'You are running Mimic in production mode,', 'in most cases you only want to run Mimic in development environments.\r\n', 'For more information on how to load Mimic in development environments only please see:', 'https://github.com/500tech/mimic#loading-mimic-only-in-development-environments' ].join(' ')); }
Fix a bug where checking process.env.NODE_ENV was not safe enough
fix(bootstrapping): Fix a bug where checking process.env.NODE_ENV was not safe enough the check for process variable existence threw an error in some build systems which do not take care of the process global variable such as angular cli.
JavaScript
mit
500tech/bdsm,500tech/mimic,500tech/mimic,500tech/bdsm
--- +++ @@ -1,4 +1,4 @@ -if (process && process.env && process.env.NODE_ENV === 'production') { +if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'production') { console.warn([ 'You are running Mimic in production mode,', 'in most cases you only want to run Mimic in development environments.\r\n',
7a2e50e7634ead72e8301fb99da246f20e92c961
libs/connections.js
libs/connections.js
//Get required modules var Connection = require( 'ssh2' ); var domain = require( 'domain' ); //Add my libs var handlers = require( './handlers.js' ); //Auxiliary function to initialize/re-initialize ssh connection function initializeConnection() { //Initialize the ssh connection connection = new Connection(), handler = domain.create(); //Handling "error" event inside domain handler. handler.add(connection); //Add global connection handlers handlers.setGlobalConnectionHandlers(); //Start connection connection.connect(OptionsForSFTP); } function resetConnection() { //Mark inactive connection active_connection = false; //Start connection connection.connect(OptionsForSFTP); } //Expose handlers public API module.exports = { initializeConnection: initializeConnection, resetConnection: resetConnection };
//Get required modules var Connection = require( 'ssh2' ); var domain = require( 'domain' ); //Auxiliary function to initialize/re-initialize ssh connection function initializeConnection() { //Add my libs var handlers = require( './handlers.js' ); //Initialize the ssh connection connection = new Connection(), handler = domain.create(); //Handling "error" event inside domain handler. handler.add(connection); //Add global connection handlers handlers.setGlobalConnectionHandlers(); //Start connection connection.connect(OptionsForSFTP); } function resetConnection() { //Mark inactive connection active_connection = false; //Start connection connection.connect(OptionsForSFTP); } //Expose handlers public API module.exports = { resetConnection: resetConnection, initializeConnection: initializeConnection };
Fix module require chicken-egg problem
Fix module require chicken-egg problem
JavaScript
mit
ctimoteo/syncmaster
--- +++ @@ -2,11 +2,11 @@ var Connection = require( 'ssh2' ); var domain = require( 'domain' ); -//Add my libs -var handlers = require( './handlers.js' ); - //Auxiliary function to initialize/re-initialize ssh connection function initializeConnection() { + //Add my libs + var handlers = require( './handlers.js' ); + //Initialize the ssh connection connection = new Connection(), handler = domain.create(); @@ -27,6 +27,6 @@ //Expose handlers public API module.exports = { - initializeConnection: initializeConnection, - resetConnection: resetConnection + resetConnection: resetConnection, + initializeConnection: initializeConnection };
9bbcea12f0db82cf583d9fcc42998b2b79ef4372
lib/parser.js
lib/parser.js
'use babel'; export default class Parser { source: null editor: null parse(source, editor) { this.source = source; this.editor = editor; return this.scan(); } scan() { let result = [], count = 0; // Find 'describes', set indexs, find 'it' this.findInstanceOf('describe(\'', result, 0, this.source.length); this.getEndIndex(result); result.map((obj) => obj.children = []); result.map((obj) => this.findInstanceOf('it(\'', obj.children, obj.index, obj.endIndex)); return result; } findInstanceOf(word, result, startIndex, endIndex) { let index = startIndex, wordLength = word.length, name, position; while (index != -1 && index < endIndex) { index++; index = this.source.indexOf(word, index); if (index == -1 || index > endIndex) break; name = this.source.substring(index + wordLength, this.source.indexOf('\'', index + wordLength + 1)); position = this.editor.buffer.positionForCharacterIndex(index); result.push({index, name, position}); } } getEndIndex(arr){ arr.map((obj, index, arr) => { if (arr[index + 1]) { obj.endIndex = arr[index + 1]['index']; } else { obj.endIndex = this.source.length; } }); } }
'use babel'; export default class Parser { source: null editor: null parse(source, editor) { this.source = source; this.editor = editor; return this.scan(); } scan() { let result = [], count = 0; // Find 'describes', set indexs, find 'it' this.findInstanceOf('describe(\'', result, 0, this.source.length); this.getEndIndex(result); result.map((obj) => obj.children = []); result.map((obj) => this.findInstanceOf('it(\'', obj.children, obj.index, obj.endIndex)); return result; } findInstanceOf(word, result, startIndex, endIndex) { let index = startIndex, wordLength = word.length, name, position; while (index != -1 && index < endIndex) { index++; index = this.source.indexOf(word, index); if (index == -1 || index > endIndex) break; name = this.source.substring(index + wordLength, this.source.indexOf('\'', index + wordLength + 1)); position = this.editor.buffer.positionForCharacterIndex(index); result.push({index, name, position, expanded: true,}); } } getEndIndex(arr){ arr.map((obj, index, arr) => { if (arr[index + 1]) { obj.endIndex = arr[index + 1]['index']; } else { obj.endIndex = this.source.length; } }); } }
Expand the tree view by defualt
Expand the tree view by defualt
JavaScript
mit
chiragchoudhary66/test-list-maker
--- +++ @@ -31,7 +31,7 @@ if (index == -1 || index > endIndex) break; name = this.source.substring(index + wordLength, this.source.indexOf('\'', index + wordLength + 1)); position = this.editor.buffer.positionForCharacterIndex(index); - result.push({index, name, position}); + result.push({index, name, position, expanded: true,}); } }
9413f0cb3b4bd6545d29e79e9b656469b209a417
jquery.linkem.js
jquery.linkem.js
// jquery.linkem.js // Copyright Michael Hanson // https://github.com/mybuddymichael/jquery-linkem (function( $ ) { $.fn.linkem = function() { var linked = this; this.on( "keydown keyup mousedown mouseup", function() { linked.text( $(this).val() ); }); }; return this; })( jQuery );
// jquery.linkem.js // Copyright Michael Hanson // https://github.com/mybuddymichael/jquery-linkem (function( $ ) { $.fn.linkem = function() { var linked = this; this.on( "input change", function() { linked.text( $(this).val() ); }); }; return this; })( jQuery );
Change events to "input" and "change"
Change events to "input" and "change"
JavaScript
mit
mybuddymichael/jquery-linkem
--- +++ @@ -6,7 +6,7 @@ $.fn.linkem = function() { var linked = this; - this.on( "keydown keyup mousedown mouseup", function() { + this.on( "input change", function() { linked.text( $(this).val() ); }); };
47b311db68aa5343f66e3f5a5fd77602bd3e2e9e
server/models/products.js
server/models/products.js
// npm dependencies const mongoose = require('mongoose'); // defines Product model // contains 3 fields (title, description, and price) let Product = mongoose.model('Product', { title: { type: String, required: true, minlength: 5, trim: true }, description: { type: String, required: true, minlength: 10, trim: true }, price: { type: Number, default: null } }); module.exports = { Product }
// npm dependencies const mongoose = require('mongoose'); // defines Product model // contains 3 fields (title, description, and price) let Product = mongoose.model('Product', { title: { type: String, required: true, minlength: 5, trim: true }, description: { type: String, minlength: 10, trim: true }, price: { type: Number, default: null } }); module.exports = { Product }
Remove 'required' validation from 'description' field
Remove 'required' validation from 'description' field
JavaScript
mit
dshaps10/full-stack-demo-site,dshaps10/full-stack-demo-site
--- +++ @@ -12,7 +12,6 @@ }, description: { type: String, - required: true, minlength: 10, trim: true },
8e54f1bd3f215ada478b6fb41644bcb777b29ab2
js/app/viewer.js
js/app/viewer.js
/*jslint browser: true, white: true, plusplus: true */ /*global angular, console, alert*/ (function () { 'use strict'; var app = angular.module('status', ['ui.bootstrap', 'chieffancypants.loadingBar', 'tableSort']); app.controller("StatusController", function($scope, $http) { $scope.serverName = app.serverName; var request = app.api + "search/tickets?unresolved=1"; $http.get( request ) .success(function(data, status, header, config) { $scope.apiLoaded = true; $scope.ticketsCount = data.length; if ($scope.ticketsCount > 0) { $scope.tickets = data; } }) .error(function(data, status, header, config) { $scope.apiLoaded = false; console.log("Error while retrieving tickets, API request failed: " + app.api + "search/tickets?closedBy=0"); }); }); }());
/*jslint browser: true, white: true, plusplus: true */ /*global angular, console, alert*/ (function () { 'use strict'; var app = angular.module('status', ['ui.bootstrap', 'chieffancypants.loadingBar', 'tableSort']); app.controller("StatusController", function($scope, $http) { $scope.serverName = app.serverName; var request = app.api + "search/tickets?unresolved=1"; $http.get( request ) .success(function(data, status, header, config) { $scope.apiLoaded = true; $scope.ticketsCount = data.length; if ($scope.ticketsCount > 0) { $scope.tickets = data; } }) .error(function(data, status, header, config) { $scope.apiLoaded = false; console.log("Error while retrieving tickets, API request failed: " + app.api + "search/tickets?unresolved=1"); }); }); }());
Update console log error text
Update console log error text
JavaScript
agpl-3.0
ShinDarth/TC-Ticket-Web-Viewer,ShinDarth/TC-Ticket-Web-Viewer
--- +++ @@ -23,7 +23,7 @@ }) .error(function(data, status, header, config) { $scope.apiLoaded = false; - console.log("Error while retrieving tickets, API request failed: " + app.api + "search/tickets?closedBy=0"); + console.log("Error while retrieving tickets, API request failed: " + app.api + "search/tickets?unresolved=1"); }); });
e8b81efc0799f24d099ac7073da35a4ece27d615
desktop/webpack.main.config.js
desktop/webpack.main.config.js
const plugins = require('./webpack.plugins') const webpack = require('webpack') module.exports = { /** * This is the main entry point for your application, it's the first file * that runs in the main process. */ entry: './src/index.ts', plugins: [ ...plugins, new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify( process.env.NODE_ENV ?? 'development' ), 'process.env.SENTRY_DSN': JSON.stringify(process.env.SENTRY_DSN), 'process.type': '"browser"', }), ], module: { rules: [ // Add support for native node modules // TODO: Investigate. Seems to cause issues, and things seem to work without this loader // { // test: /\.node$/, // use: 'node-loader', // }, { test: /\.(m?js|node)$/, parser: { amd: false }, use: { loader: '@marshallofsound/webpack-asset-relocator-loader', options: { outputAssetBase: 'native_modules', debugLog: true, }, }, }, { test: /\.tsx?$/, exclude: /(node_modules|\.webpack)/, use: { loader: 'ts-loader', options: { configFile: 'tsconfig.main.json', transpileOnly: true, }, }, }, ], }, resolve: { extensions: ['.js', '.mjs', '.ts', '.json'], }, }
const plugins = require('./webpack.plugins') const webpack = require('webpack') module.exports = { /** * This is the main entry point for your application, it's the first file * that runs in the main process. */ entry: './src/index.ts', plugins: [ ...plugins, new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify( process.env.NODE_ENV ?? 'development' ), 'process.env.SENTRY_DSN': JSON.stringify(process.env.SENTRY_DSN), 'process.type': '"browser"', }), ], module: { rules: [ // Add support for native node modules { test: /native_modules\/.+\.node$/, use: 'node-loader', }, { test: /\.(m?js|node)$/, parser: { amd: false }, use: { loader: '@marshallofsound/webpack-asset-relocator-loader', options: { outputAssetBase: 'native_modules', debugLog: true, }, }, }, { test: /\.tsx?$/, exclude: /(node_modules|\.webpack)/, use: { loader: 'ts-loader', options: { configFile: 'tsconfig.main.json', transpileOnly: true, }, }, }, ], }, resolve: { extensions: ['.js', '.mjs', '.ts', '.json'], }, }
Fix resolution of native Node modules
chore(Desktop): Fix resolution of native Node modules See https://github.com/electron-userland/electron-forge/pull/2449
JavaScript
apache-2.0
stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila
--- +++ @@ -20,11 +20,10 @@ module: { rules: [ // Add support for native node modules - // TODO: Investigate. Seems to cause issues, and things seem to work without this loader - // { - // test: /\.node$/, - // use: 'node-loader', - // }, + { + test: /native_modules\/.+\.node$/, + use: 'node-loader', + }, { test: /\.(m?js|node)$/, parser: { amd: false },
a966513e6677626454f550bd81cd50efce79c86f
src/unix_stream.js
src/unix_stream.js
var util = require('util'); var Socket = require('net').Socket; /* Make sure we choose the correct build directory */ var directory = process.config.default_configuration === 'Debug' ? 'Debug' : 'Release'; var bindings = require(__dirname + '/../build/' + directory + '/unix_stream.node'); var SOCK_STREAM = bindings.SOCK_STREAM; var AF_UNIX = bindings.AF_UNIX; var bind = bindings.bind; var socket = bindings.socket; function errnoException(errorno, syscall) { var e = new Error(syscall + ' ' + errorno); e.errno = e.code = errorno; e.syscall = syscall; return e; } exports.createSocket = function(local_path) { var fd; if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) === -1) throw errnoException(errno, 'socket'); var s = new Socket(fd); if (local_path) { if (bind(fd, local_path) == -1) { process.nextTick(function() { s.emit('error', errnoException(errno, 'bind')); }); } s.local_path = local_path; } return s; };
var util = require('util'); var Socket = require('net').Socket; /* Make sure we choose the correct build directory */ var directory = process.config.target_defaults.default_configuration === 'Debug' ? 'Debug' : 'Release'; var bindings = require(__dirname + '/../build/' + directory + '/unix_stream.node'); var SOCK_STREAM = bindings.SOCK_STREAM; var AF_UNIX = bindings.AF_UNIX; var bind = bindings.bind; var socket = bindings.socket; function errnoException(errorno, syscall) { var e = new Error(syscall + ' ' + errorno); e.errno = e.code = errorno; e.syscall = syscall; return e; } exports.createSocket = function(local_path) { var fd; if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) === -1) throw errnoException(errno, 'socket'); var s = new Socket(fd); if (local_path) { if (bind(fd, local_path) == -1) { process.nextTick(function() { s.emit('error', errnoException(errno, 'bind')); }); } s.local_path = local_path; } return s; };
Use the correct process.config variable
Use the correct process.config variable
JavaScript
isc
santigimeno/node-unix-stream,santigimeno/node-unix-stream,santigimeno/node-unix-stream
--- +++ @@ -2,7 +2,7 @@ var Socket = require('net').Socket; /* Make sure we choose the correct build directory */ -var directory = process.config.default_configuration === 'Debug' ? 'Debug' : 'Release'; +var directory = process.config.target_defaults.default_configuration === 'Debug' ? 'Debug' : 'Release'; var bindings = require(__dirname + '/../build/' + directory + '/unix_stream.node'); var SOCK_STREAM = bindings.SOCK_STREAM;
74386ac41257a7ea865aefd09631ff87815c23a5
src/components/App/index.js
src/components/App/index.js
import React, { Component } from 'react'; /* global styles for app */ import './styles/app.scss'; /* application components */ import { Header } from '../../components/Header'; import { Footer } from '../../components/Footer'; export class App extends Component { static propTypes = { children: React.PropTypes.any, }; render() { return ( <section> <Header /> <main className="container"> {this.props.children} </main> <Footer /> </section> ); } }
import React, { Component } from 'react'; /* global styles for app */ import './styles/app.scss'; /* application components */ import { Header } from '../../components/Header'; import { Footer } from '../../components/Footer'; export class App extends Component { static propTypes = { children: React.PropTypes.any, }; render() { return ( <section> <Header /> <main> <div className="container"> {this.props.children} </div> </main> <Footer /> </section> ); } }
Change markup so that main el is outside of container, can take a full width bg color
Change markup so that main el is outside of container, can take a full width bg color
JavaScript
mit
dramich/Chatson,badT/twitchBot,badT/Chatson,badT/twitchBot,dramich/Chatson,dramich/twitchBot,TerryCapan/twitchBot,TerryCapan/twitchBot,dramich/twitchBot,badT/Chatson
--- +++ @@ -16,8 +16,10 @@ return ( <section> <Header /> - <main className="container"> - {this.props.children} + <main> + <div className="container"> + {this.props.children} + </div> </main> <Footer /> </section>
ada006bbcee7e855f9ee44acbd777928a0c58d1b
addon/initializers/mutation-observer.js
addon/initializers/mutation-observer.js
/** * Simple initializer that implements the mutationObserverMixin * in all the Components. It uses a flag defined in the app * environment for it. */ import Ember from 'ember'; import mutationObserver from '../mixins/mutation-observer'; export function initialize(app) { const config = app.lookupFactory ? app.lookupFactory('config:environment') : app.__container__.lookupFactory('config:environment'); if (!config || !config.mutationObserverInjection) {return;} Ember.Component.reopen(mutationObserver); } export default { name: 'mutation-observer', initialize: initialize };
/** * Simple initializer that implements the mutationObserverMixin * in all the Components. It uses a flag defined in the app * environment for it. */ import Ember from 'ember'; import mutationObserver from '../mixins/mutation-observer'; export function initialize(app) { let config; try { // Ember 2.15+ config = app.resolveRegistration('config:environment'); } catch (e) { // Older Ember approach config = app.lookupFactory ? app.lookupFactory('config:environment') : app.__container__.lookupFactory('config:environment'); } if (!config || !config.mutationObserverInjection) {return;} Ember.Component.reopen(mutationObserver); } export default { name: 'mutation-observer', initialize: initialize };
Fix initializer for Ember 2.15+
Fix initializer for Ember 2.15+
JavaScript
mit
zzarcon/ember-cli-Mutation-Observer,zzarcon/ember-cli-Mutation-Observer
--- +++ @@ -8,10 +8,17 @@ import mutationObserver from '../mixins/mutation-observer'; export function initialize(app) { - const config = app.lookupFactory ? - app.lookupFactory('config:environment') : - app.__container__.lookupFactory('config:environment'); - + let config; + try { + // Ember 2.15+ + config = app.resolveRegistration('config:environment'); + } catch (e) { + // Older Ember approach + config = app.lookupFactory ? + app.lookupFactory('config:environment') : + app.__container__.lookupFactory('config:environment'); + } + if (!config || !config.mutationObserverInjection) {return;} Ember.Component.reopen(mutationObserver);
1f13a1254fbf5303a58bf75b14b160e11d7dd30e
src/components/Lotteries.js
src/components/Lotteries.js
/** * Created by mgab on 14/05/2017. */ import React,{ Component } from 'react' import Title from './common/styled-components/Title' import Lottery from './Lottery' export default class Lotteries extends Component { render() { const lotteries = [] this.props.lotteriesData.forEach((entry) => { lotteries.push(<Lottery name={entry.id} jackpot={entry.jackpots[0].jackpot} drawingDate={entry.drawingDate} key={entry.id} />) }) return ( <div> <Title>Lotteries</Title> <div> {lotteries} </div> </div> ) } }
/** * Created by mgab on 14/05/2017. */ import React,{ Component } from 'react' import Title from './common/styled-components/Title' import Lottery from './Lottery' export default class Lotteries extends Component { render() { const lotteries = [] if (this.props.lotteriesData) { this.props.lotteriesData.forEach((entry) => { lotteries.push(<Lottery name={entry.id} jackpot={entry.jackpots[0].jackpot} drawingDate={entry.drawingDate} key={entry.id} />) }) } return ( <div> <Title>Lotteries</Title> <div> {lotteries} </div> </div> ) } }
Check for lotteries data before trying to process them.
Check for lotteries data before trying to process them.
JavaScript
mit
mihailgaberov/lottoland-react-demo,mihailgaberov/lottoland-react-demo
--- +++ @@ -13,12 +13,15 @@ const lotteries = [] - this.props.lotteriesData.forEach((entry) => { - lotteries.push(<Lottery name={entry.id} - jackpot={entry.jackpots[0].jackpot} - drawingDate={entry.drawingDate} - key={entry.id} />) - }) + if (this.props.lotteriesData) { + this.props.lotteriesData.forEach((entry) => { + lotteries.push(<Lottery name={entry.id} + jackpot={entry.jackpots[0].jackpot} + drawingDate={entry.drawingDate} + key={entry.id} />) + }) + } + return ( <div>
28c89588650841686f1c0c515360686a5ac0afd8
src/middleware/authenticate.js
src/middleware/authenticate.js
import handleAdapter from '../handleAdapter' export default (config) => { if ( ! config.enabled) return (req, res, next) => { next() } var verifyHeader = ( !! config.header) var header = (config.header || 'Authorization').toLowerCase() var tokenLength = 32 var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`) return (req, res, next) => { var err req.auth = {} if (verifyHeader) { var value = req.auth.header = req.headers[header] if ( ! value) { err = new Error(`Missing ${config.header} header.`) err.statusCode = 401 return next(err) } if (config.byToken !== false) { var token = value.replace(tokenRegExp, '$1') if (token.length !== tokenLength) { err = new Error('Invalid token.') err.statusCode = 401 return next(err) } req.auth.token = token } } handleAdapter(req, config, next, (err, user) => { if (err) { err = new Error(err) err.statusCode = 401 return next(err) } req.user = user next() }) } }
import handleAdapter from '../handleAdapter' export default (config) => { if ( ! config.enabled) return (req, res, next) => { next() } var header = (config.header || 'Authorization').toLowerCase() var tokenLength = 32 var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`) return (req, res, next) => { var err req.auth = {} if (header) { var value = req.auth.header = req.headers[header] if ( ! value) { err = new Error(`Missing ${config.header} header.`) err.statusCode = 401 return next(err) } if (config.byToken !== false) { var token = value.replace(tokenRegExp, '$1') if (token.length !== tokenLength) { err = new Error('Invalid token.') err.statusCode = 401 return next(err) } req.auth.token = token } } handleAdapter(req, config, next, (err, user) => { if (err) { err = new Error(err) err.statusCode = 401 return next(err) } req.user = user next() }) } }
Fix header not being validated if 'auth.header' option is not given.
Fix header not being validated if 'auth.header' option is not given. In authenticate middleware.
JavaScript
mit
kukua/concava
--- +++ @@ -3,7 +3,6 @@ export default (config) => { if ( ! config.enabled) return (req, res, next) => { next() } - var verifyHeader = ( !! config.header) var header = (config.header || 'Authorization').toLowerCase() var tokenLength = 32 var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`) @@ -13,7 +12,7 @@ req.auth = {} - if (verifyHeader) { + if (header) { var value = req.auth.header = req.headers[header] if ( ! value) {
fc9bdc4a183ea90c596603bdc5cdc62e2902c1ce
lib/Subheader.js
lib/Subheader.js
import { getColor } from './helpers'; import { StyleSheet, View, Text } from 'react-native'; import { TYPO, THEME_NAME } from './config'; import React, { Component, PropTypes } from 'react'; const styles = StyleSheet.create({ container: { padding: 16 }, text: TYPO.paperFontBody1 }); export default class Subheader extends Component { static propTypes = { text: PropTypes.string.isRequired, color: PropTypes.string, inset: PropTypes.bool, theme: PropTypes.oneOf(THEME_NAME), lines: PropTypes.number }; static defaultProps = { color: 'rgba(0,0,0,.54)', inset: false, theme: 'light', lines: 1 }; render() { const { text, color, inset, lines } = this.props; return ( <View style={[styles.container, { paddingLeft: inset ? 72 : 16 }]} > <Text numberOfLines={lines} style={[styles.text, { color: getColor(color), fontWeight: '500' }]} > {text} </Text> </View> ); } }
import { getColor } from './helpers'; import { StyleSheet, View, Text } from 'react-native'; import { TYPO, THEME_NAME } from './config'; import React, { Component, PropTypes } from 'react'; const styles = StyleSheet.create({ container: { padding: 16 }, text: TYPO.paperFontBody1 }); export default class Subheader extends Component { static propTypes = { text: PropTypes.string.isRequired, color: PropTypes.string, inset: PropTypes.bool, theme: PropTypes.oneOf(THEME_NAME), lines: PropTypes.number, style: PropTypes.object, }; static defaultProps = { color: 'rgba(0,0,0,.54)', inset: false, theme: 'light', lines: 1 }; render() { const { text, color, inset, lines, style } = this.props; return ( <View style={[styles.container, { paddingLeft: inset ? 72 : 16 }, style]} > <Text numberOfLines={lines} style={[styles.text, { color: getColor(color), fontWeight: '500' }]} > {text} </Text> </View> ); } }
Add ability to set state of subheader
Add ability to set state of subheader
JavaScript
mit
xotahal/react-native-material-ui,mobileDevNativeCross/react-native-material-ui,xvonabur/react-native-material-ui,blovato/sca-mobile-components,ajaxangular/react-native-material-ui,kenma9123/react-native-material-ui
--- +++ @@ -17,7 +17,8 @@ color: PropTypes.string, inset: PropTypes.bool, theme: PropTypes.oneOf(THEME_NAME), - lines: PropTypes.number + lines: PropTypes.number, + style: PropTypes.object, }; static defaultProps = { @@ -28,13 +29,13 @@ }; render() { - const { text, color, inset, lines } = this.props; + const { text, color, inset, lines, style } = this.props; return ( <View style={[styles.container, { paddingLeft: inset ? 72 : 16 - }]} + }, style]} > <Text numberOfLines={lines}
edbcdb75813fdd8149c147f0c7dc5138e06307e6
test/unit/history/setLimit.test.js
test/unit/history/setLimit.test.js
import History from '../../../src/history' describe('History::setLimit', function() { const action = n => n it('sets the correct size given Infinity', function() { const history = new History() history.setLimit(Infinity) expect(history.limit).toEqual(Infinity) }) it('sets the correct size given an integer', function() { const history = new History() history.setLimit(10) expect(history.limit).toEqual(10) }) it('sets the limit to 0 given a negative integer', function() { const history = new History() history.setLimit(-10) expect(history.limit).toEqual(0) }) })
import History from '../../../src/history' describe('History::setLimit', function() { it('sets the correct size given Infinity', function() { const history = new History() history.setLimit(Infinity) expect(history.limit).toEqual(Infinity) }) it('sets the correct size given an integer', function() { const history = new History() history.setLimit(10) expect(history.limit).toEqual(10) }) it('sets the limit to 0 given a negative integer', function() { const history = new History() history.setLimit(-10) expect(history.limit).toEqual(0) }) })
Remove unused variable that caused linter warning
Remove unused variable that caused linter warning
JavaScript
mit
vigetlabs/microcosm,vigetlabs/microcosm,vigetlabs/microcosm
--- +++ @@ -1,8 +1,6 @@ import History from '../../../src/history' describe('History::setLimit', function() { - const action = n => n - it('sets the correct size given Infinity', function() { const history = new History() history.setLimit(Infinity)
2990ed3071a0969145e0a76beae6ad057e6e14f9
subsystem/click.js
subsystem/click.js
phoxy._ClickHook = { _: {}, }; phoxy._ClickHook._.click = { InitClickHook: function() { document.querySelector('body').addEventListener('click', function(event) { var target = event.target; while (true) { if (target === null) return; if (target.nodeName === 'A') break; // only click on A is triggered target = target.parentElement; } var url = target.getAttribute('href'); if (url === undefined || target.hasAttribute('not-phoxy')) return; if (phoxy._.click.OnClick(url, false)) return; event.preventDefault() }, true); window.onpopstate = phoxy._.click.OnPopState; } , OnClick: function (url, not_push) { if (url.indexOf('#') !== -1) return true; if (url[0] === '/') url = url.substring(1); phoxy.MenuCall(url); return false; } , OnPopState: function(e) { var path = e.target.location.pathname; var hash = e.target.location.hash; phoxy._.click.OnClick(path, true); } };
phoxy._ClickHook = { _: {}, }; phoxy._ClickHook._.click = { InitClickHook: function() { document.querySelector('body').addEventListener('click', function(event) { var target = event.target; while (true) { if (target === null) return; if (target.nodeName === 'A') break; // only click on A is triggered target = target.parentElement; } var url = target.getAttribute('href'); if (url === undefined || target.hasAttribute('not-phoxy')) return; if (phoxy._.click.OnClick(url, false)) return; event.preventDefault() }, true); window.onpopstate = phoxy._.click.OnPopState; } , OnClick: function (url, not_push) { if (url.indexOf('#') !== -1) return true; if (url[0] === '/') url = url.substring(1); if (not_push) phoxy.ApiRequest(url); else phoxy.MenuCall(url); return false; } , OnPopState: function(e) { var path = e.target.location.pathname; var hash = e.target.location.hash; phoxy._.click.OnClick(path, true); } };
Fix empty history issue, when we never could go back
Fix empty history issue, when we never could go back
JavaScript
apache-2.0
phoxy/phoxy,phoxy/phoxy
--- +++ @@ -41,7 +41,10 @@ if (url[0] === '/') url = url.substring(1); - phoxy.MenuCall(url); + if (not_push) + phoxy.ApiRequest(url); + else + phoxy.MenuCall(url); return false; } ,
675134d0bb49567fade2501538dc088b21cdab64
StructureMaintainer.js
StructureMaintainer.js
module.exports = function() { console.log("Maintaining Structures... " + Game.getUsedCpu()); var newCandidates = [], links = [], spawns = []; Object.keys(Game.structures).forEach(function(structureId) { structure = Game.structures[structureId]; if(structure.hits < (structure.hitsMax / 2)) { newCandidates.push(structure); } if(structure.structureType === STRUCTURE_LINK) { links.push(structure.id); } }); Memory.repairList.forEach(function (id) { var structure = Game.getObjectById(id); if(!structure || structure.hits >= structure.hitsMax*0.75) { Memory.repairList.splice(Memory.repairList.indexOf(id), 1); } }); Memory.linkList = links; Memory.spawnList = Game.spawns; newCandidates.forEach(function (structure) { if(Memory.repairList.indexOf(structure.id) === -1) { Memory.repairList.push(structure.id); } }); console.log("Finished " + Game.getUsedCpu()); };
module.exports = function() { console.log("Maintaining Structures... " + Game.getUsedCpu()); var structures = Object.keys(Game.rooms).forEach(function (roomName) { Game.rooms[roomName].find(FIND_STRUCTURES, { filter: function (structure) { return (structure.my === true || structure.structureType === "STRUCTURE_ROAD"); } }); }); var newCandidates = [], links = [], spawns = []; structures.forEach(function(structure) { if(structure.hits < (structure.hitsMax / 2)) { newCandidates.push(structure); } if(structure.structureType === STRUCTURE_LINK) { links.push(structure.id); } }); Memory.repairList.forEach(function (id) { var structure = Game.getObjectById(id); if(!structure || structure.hits >= structure.hitsMax*0.75) { Memory.repairList.splice(Memory.repairList.indexOf(id), 1); } }); Memory.linkList = links; Memory.spawnList = Game.spawns; newCandidates.forEach(function (structure) { if(Memory.repairList.indexOf(structure.id) === -1) { Memory.repairList.push(structure.id); } }); console.log("Finished " + Game.getUsedCpu()); };
Make it so that the Structure Maintainer includes roads as well.
Make it so that the Structure Maintainer includes roads as well.
JavaScript
mit
pmaidens/screeps,pmaidens/screeps
--- +++ @@ -1,10 +1,18 @@ module.exports = function() { console.log("Maintaining Structures... " + Game.getUsedCpu()); + + var structures = Object.keys(Game.rooms).forEach(function (roomName) { + Game.rooms[roomName].find(FIND_STRUCTURES, { + filter: function (structure) { + return (structure.my === true || structure.structureType === "STRUCTURE_ROAD"); + } + }); + }); + var newCandidates = [], links = [], spawns = []; - Object.keys(Game.structures).forEach(function(structureId) { - structure = Game.structures[structureId]; + structures.forEach(function(structure) { if(structure.hits < (structure.hitsMax / 2)) { newCandidates.push(structure); }
e29974b1adcb91af1a65ac474fcb36d7a0e24098
test/17_image/definitions.js
test/17_image/definitions.js
define(function () { return [ { "default": { name: "TestForm", label: "TestForm", _elements: [ { "default": { name: "Name", type: "text", label: "Name" } }, { "default": { name: "Photo", type: "file", label: "Photo", accept: "image/*" } }, { "default": { name: "Photo1", type: "file", label: "Photo1", accept: "image/*" } }, { "default": { name: "Photo2", type: "file", label: "Photo2", accept: "image/*" } }, { 'default': { name: 'location', label: 'Location', type: 'location' } }, { 'default': { name: 'draw', label: 'Sign', type: 'draw', size: 'signature' } }, { "default": { name: "Rank", type: "number", label: "Rank" } }, { "default": { name: "Details", type: "text", label: "Details" } } ] } } ]; });
define(function () { return [ { "default": { name: "TestForm", label: "TestForm", _elements: [ { "default": { name: "Name", type: "text", label: "Name" } }, { "default": { name: "Photo", type: "file", label: "Photo", accept: "image/*", capture: true } }, { "default": { name: "Photo1", type: "file", label: "Photo1", accept: "image/*", capture: false } }, { "default": { name: "Photo2", type: "file", label: "Photo2", accept: "image/*", capture: true } }, { 'default': { name: 'location', label: 'Location', type: 'location' } }, { 'default': { name: 'draw', label: 'Sign', type: 'draw', size: 'signature' } }, { "default": { name: "Rank", type: "number", label: "Rank" } }, { "default": { name: "Details", type: "text", label: "Details" } } ] } } ]; });
Update form definition in tests to demonstrate functionality
Update form definition in tests to demonstrate functionality
JavaScript
bsd-3-clause
blinkmobile/forms,blinkmobile/forms
--- +++ @@ -17,7 +17,8 @@ name: "Photo", type: "file", label: "Photo", - accept: "image/*" + accept: "image/*", + capture: true } }, { @@ -25,7 +26,8 @@ name: "Photo1", type: "file", label: "Photo1", - accept: "image/*" + accept: "image/*", + capture: false } }, { @@ -33,7 +35,8 @@ name: "Photo2", type: "file", label: "Photo2", - accept: "image/*" + accept: "image/*", + capture: true } }, {
7bfa2357a3764c9979d078a459759bcfd94f8e46
blueprints/telling-stories/index.js
blueprints/telling-stories/index.js
/*jshint node:true*/ var existsSync = require('exists-sync'); module.exports = { description: 'Install telling-stories dependencies', normalizeEntityName: function() {}, afterInstall: function() { // Register shutdown animation to the end of every acceptance test if (existsSync('tests/helpers/module-for-acceptance.js')) { this.insertIntoFile('tests/helpers/module-for-acceptance.js', " afterEach = window.require('telling-stories').shutdown(afterEach);", { after: "let afterEach = options.afterEach && options.afterEach.apply(this, arguments);\n" }); } return this.addAddonsToProject({ packages: [ { name: 'ember-cli-page-object', version: '^1.6.0' }, { name: 'telling-stories-dashboard', version: '1.0.0-alpha.2' } ] }); } };
/*jshint node:true*/ var existsSync = require('exists-sync'); module.exports = { description: 'Install telling-stories dependencies', normalizeEntityName: function() {}, afterInstall: function() { // Register shutdown animation to the end of every acceptance test if (existsSync('tests/helpers/module-for-acceptance.js')) { this.insertIntoFile('tests/helpers/module-for-acceptance.js', " afterEach = window.require('telling-stories').shutdown(afterEach);", { after: "let afterEach = options.afterEach && options.afterEach.apply(this, arguments);\n" }); } return this.addAddonsToProject({ packages: [ { name: 'ember-cli-page-object', version: '^1.6.0' }, { name: 'telling-stories-dashboard', version: '1.0.0-alpha.3' } ] }); } };
Update bluprint to install latest telling-stories-dashboard
Update bluprint to install latest telling-stories-dashboard
JavaScript
mit
mvdwg/telling-stories,mvdwg/telling-stories
--- +++ @@ -18,7 +18,7 @@ return this.addAddonsToProject({ packages: [ { name: 'ember-cli-page-object', version: '^1.6.0' }, - { name: 'telling-stories-dashboard', version: '1.0.0-alpha.2' } + { name: 'telling-stories-dashboard', version: '1.0.0-alpha.3' } ] }); }
819345213938c7b6df4eaeb2dac2c39b2078e1d0
public/javascripts/app/views/gameController.js
public/javascripts/app/views/gameController.js
define([ 'Backbone', //Collection 'app/collections/games' ], function( Backbone, Games ){ var GameController = Backbone.View.extend({ events: { 'keyup .js-create-game' : 'create' }, initialize: function(){ this.collection = new Games(this.options.projectId); this.collection.bind('add', this.addGame, this); this.collection.bind('reset', this.render, this).fetch(); }, create: function(event){ if(event.keyCode === 13){ this.collection.create({ name: event.currentTarget.value, projectId: this.options.projectId }); } }, addGame: function(){ console.log(this.collection); }, render: function(){ console.log(this.collection); } }); return GameController; });
define([ 'Backbone', //Collection 'app/collections/games', //Template 'text!templates/project-page/gameTemplate.html', ], function( Backbone, //Collection Games, //Template gameTemplate ){ var GameController = Backbone.View.extend({ template: _.template(gameTemplate), events: { 'keyup .js-create-game' : 'create' }, initialize: function(){ this.collection = new Games(this.options.projectId); this.collection.bind('add', this.addGame, this); this.collection.bind('reset', this.render, this); }, guid: function(){ var S4 = function (){ return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); }, create: function(event){ if(event.keyCode === 13){ this.collection.create({ _id: this.guid(), name: event.currentTarget.value, projectId: this.options.projectId }); event.currentTarget.value=''; } }, addGame: function(newModel){ var newGame = newModel.toJSON(); this.$el.append(this.template(newGame)); }, render: function(){ var template = this.template; var $list = this.$el; _.each(this.collection.models, function(model){ var game = template(model.toJSON()); $list.append(game); }); } }); return GameController; });
Add game logic on game controller
front-end: Add game logic on game controller
JavaScript
mit
tangosource/pokerestimate,tangosource/pokerestimate
--- +++ @@ -3,17 +3,24 @@ 'Backbone', //Collection - 'app/collections/games' + 'app/collections/games', + //Template + 'text!templates/project-page/gameTemplate.html', ], function( Backbone, - Games + //Collection + Games, + //Template + gameTemplate ){ var GameController = Backbone.View.extend({ + + template: _.template(gameTemplate), events: { 'keyup .js-create-game' : 'create' @@ -22,24 +29,39 @@ initialize: function(){ this.collection = new Games(this.options.projectId); this.collection.bind('add', this.addGame, this); - this.collection.bind('reset', this.render, this).fetch(); + this.collection.bind('reset', this.render, this); + }, + + guid: function(){ + var S4 = function (){ return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; + return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); }, create: function(event){ if(event.keyCode === 13){ this.collection.create({ + _id: this.guid(), name: event.currentTarget.value, projectId: this.options.projectId }); + + event.currentTarget.value=''; } }, - addGame: function(){ - console.log(this.collection); + addGame: function(newModel){ + var newGame = newModel.toJSON(); + this.$el.append(this.template(newGame)); }, render: function(){ - console.log(this.collection); + var template = this.template; + var $list = this.$el; + + _.each(this.collection.models, function(model){ + var game = template(model.toJSON()); + $list.append(game); + }); } });
56c2e6b543e51ec44a5bcb133ef9511c50d0f4ff
ui/src/shared/middleware/errors.js
ui/src/shared/middleware/errors.js
// import {replace} from 'react-router-redux' import {authExpired} from 'shared/actions/auth' import {publishNotification as notify} from 'shared/actions/notifications' import {HTTP_FORBIDDEN} from 'shared/constants' const notificationsBlackoutDuration = 5000 let allowNotifications = true // eslint-disable-line const errorsMiddleware = store => next => action => { if (action.type === 'ERROR_THROWN') { const {error, error: {status, auth}, altText} = action console.error(error) if (status === HTTP_FORBIDDEN) { const {auth: {me}} = store.getState() const wasSessionTimeout = me !== null next(authExpired(auth)) if (wasSessionTimeout) { store.dispatch(notify('error', 'Session timed out. Please login again.')) allowNotifications = false setTimeout(() => { allowNotifications = true }, notificationsBlackoutDuration) } else { store.dispatch(notify('error', 'Please login to use Chronograf.')) } } else if (altText) { store.dispatch(notify('error', altText)) } else { store.dispatch(notify('error', 'Cannot communicate with server.')) } } next(action) } export default errorsMiddleware
import {authExpired} from 'shared/actions/auth' import {publishNotification as notify} from 'shared/actions/notifications' import {HTTP_FORBIDDEN} from 'shared/constants' const actionsAllowedDuringBlackout = ['@@', 'AUTH_', 'ME_', 'NOTIFICATION_', 'ERROR_'] const notificationsBlackoutDuration = 5000 let allowNotifications = true // eslint-disable-line const errorsMiddleware = store => next => action => { const {auth: {me}} = store.getState() if (action.type === 'ERROR_THROWN') { const {error: {status, auth}, altText} = action if (status === HTTP_FORBIDDEN) { const wasSessionTimeout = me !== null store.dispatch(authExpired(auth)) if (wasSessionTimeout) { store.dispatch(notify('error', 'Session timed out. Please login again.')) allowNotifications = false setTimeout(() => { allowNotifications = true }, notificationsBlackoutDuration) } else { store.dispatch(notify('error', 'Please login to use Chronograf.')) } } else if (altText) { store.dispatch(notify('error', altText)) } else { store.dispatch(notify('error', 'Cannot communicate with server.')) } } // if auth has expired, do not execute any further actions or redux state // changes in order to prevent changing notification that indiciates why // logout occurred and any attempts to change redux state by actions that may // have triggered AJAX requests prior to auth expiration and whose response // returns after logout if (me === null && !(actionsAllowedDuringBlackout.some((allowedAction) => action.type.includes(allowedAction)))) { return } next(action) } export default errorsMiddleware
Refactor error middleware to suppress redux actions after auth expires and always show correct logout reason error notification
Refactor error middleware to suppress redux actions after auth expires and always show correct logout reason error notification
JavaScript
mit
mark-rushakoff/influxdb,influxdb/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,influxdb/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb
--- +++ @@ -1,23 +1,22 @@ -// import {replace} from 'react-router-redux' import {authExpired} from 'shared/actions/auth' import {publishNotification as notify} from 'shared/actions/notifications' import {HTTP_FORBIDDEN} from 'shared/constants' +const actionsAllowedDuringBlackout = ['@@', 'AUTH_', 'ME_', 'NOTIFICATION_', 'ERROR_'] const notificationsBlackoutDuration = 5000 let allowNotifications = true // eslint-disable-line const errorsMiddleware = store => next => action => { + const {auth: {me}} = store.getState() + if (action.type === 'ERROR_THROWN') { - const {error, error: {status, auth}, altText} = action - - console.error(error) + const {error: {status, auth}, altText} = action if (status === HTTP_FORBIDDEN) { - const {auth: {me}} = store.getState() const wasSessionTimeout = me !== null - next(authExpired(auth)) + store.dispatch(authExpired(auth)) if (wasSessionTimeout) { store.dispatch(notify('error', 'Session timed out. Please login again.')) @@ -36,6 +35,14 @@ } } + // if auth has expired, do not execute any further actions or redux state + // changes in order to prevent changing notification that indiciates why + // logout occurred and any attempts to change redux state by actions that may + // have triggered AJAX requests prior to auth expiration and whose response + // returns after logout + if (me === null && !(actionsAllowedDuringBlackout.some((allowedAction) => action.type.includes(allowedAction)))) { + return + } next(action) }
2825711cff4a32829bfa94afb00ec5168f524382
webapp/src/ui/view/sidenav-view.js
webapp/src/ui/view/sidenav-view.js
const Backbone = require('backbone'); require('backbone.marionette'); const Repository = require('../../domain/repository'); const TeamItemViewTemplate = require('../template/team-item-view-template.hbs'); const Template = require('../template/sidenav-view-template.hbs'); const TeamItemView = Backbone.Marionette.View.extend({ template: TeamItemViewTemplate, tagName: 'li' }); const TeamListView = Backbone.Marionette.CollectionView.extend({ childView: TeamItemView }); module.exports = Backbone.Marionette.View.extend({ template: Template, ui: { addTeamButton: '.btn.add-team' }, events: { 'click @ui.addTeamButton': 'addTeam' }, regions: { teams: '.teams' }, onRender: function() { Repository.getTeams() .then(teams => { this.showChildView('teams', new TeamListView({collection: teams})); }); }, onDomRefresh: function() { this.$('.sidenav-button').sideNav(); }, addTeam: function() { Repository.addTeam(); } });
const Backbone = require('backbone'); require('backbone.marionette'); const Repository = require('../../domain/repository'); const TeamItemViewTemplate = require('../template/team-item-view-template.hbs'); const Template = require('../template/sidenav-view-template.hbs'); const TeamItemView = Backbone.Marionette.View.extend({ template: TeamItemViewTemplate, tagName: 'li' }); const TeamListView = Backbone.Marionette.CollectionView.extend({ childView: TeamItemView }); module.exports = Backbone.Marionette.View.extend({ template: Template, ui: { addTeamButton: '.btn.add-team' }, events: { 'click @ui.addTeamButton': 'addTeam', 'click .teams': 'closeSidenav' }, regions: { teams: '.teams' }, onRender: function() { Repository.getTeams() .then(teams => { this.showChildView('teams', new TeamListView({collection: teams})); }); }, onDomRefresh: function() { this.$('.sidenav-button').sideNav(); }, addTeam: function() { Repository.addTeam(); }, closeSidenav: function() { this.$('.sidenav-button').sideNav('hide'); } });
Hide sidenav when selecting team
Hide sidenav when selecting team
JavaScript
mit
hagifoo/gae-pomodoro,hagifoo/gae-pomodoro,hagifoo/gae-pomodoro
--- +++ @@ -19,7 +19,8 @@ addTeamButton: '.btn.add-team' }, events: { - 'click @ui.addTeamButton': 'addTeam' + 'click @ui.addTeamButton': 'addTeam', + 'click .teams': 'closeSidenav' }, regions: { teams: '.teams' @@ -38,5 +39,9 @@ addTeam: function() { Repository.addTeam(); + }, + + closeSidenav: function() { + this.$('.sidenav-button').sideNav('hide'); } });
00e9721fef7c4438a6fae92ace89fbd59397912d
public/app/services/searchService.js
public/app/services/searchService.js
(function () { 'use strict'; define( [ 'lodash', 'jquery' ], function (_, $) { return function (baseUrl, ajaxOptions, noCache, logErrors) { var queryString; queryString = function (parameters) { return '(' + _.map(parameters.children, function (child) { return child.hasOwnProperty('children') ? queryString(child) : '(' + child.key + ':' + child.value + ')'; }) .join(' ' + parameters.operator + ' ') + ')'; }; return function (parameters, callback) { $.ajax(_.merge({}, ajaxOptions, { url: baseUrl + '?q=' + queryString(parameters || {}) + (noCache ? '&noCache=1' : ''), success: function (result) { if (!result.ok) { return callback(new Error('Invalid response received from server')); } delete result.ok; callback(undefined, _.values(result)); }, error: function (jqXHR, textStatus, err) { if (logErrors && console && typeof console.error === 'function') { console.error(jqXHR, textStatus, err); } callback(err || 'An unknown error occurred'); } })); }; }; } ); }());
(function () { 'use strict'; define( [ 'lodash', 'jquery' ], function (_, $) { return function (baseUrl, ajaxOptions, noCache, logErrors) { var queryString; queryString = function (parameters) { return _.map(parameters.children, function (child) { return child.hasOwnProperty('children') ? '(' + queryString(child) + ')' : '(' + child.key + ':' + child.value + ')'; }) .join(' ' + parameters.operator + ' '); }; return function (parameters, callback) { $.ajax(_.merge({}, ajaxOptions, { url: baseUrl + '?q=' + queryString(parameters || {}) + (noCache ? '&noCache=1' : ''), success: function (result) { if (!result.ok) { return callback(new Error('Invalid response received from server')); } delete result.ok; callback(undefined, _.values(result)); }, error: function (jqXHR, textStatus, err) { if (logErrors && console && typeof console.error === 'function') { console.error(jqXHR, textStatus, err); } callback(err || 'An unknown error occurred'); } })); }; }; } ); }());
Fix issue with brackets in generated queries.
Fix issue with brackets in generated queries.
JavaScript
mit
rwahs/research-frontend,rwahs/research-frontend
--- +++ @@ -11,12 +11,12 @@ var queryString; queryString = function (parameters) { - return '(' + _.map(parameters.children, function (child) { + return _.map(parameters.children, function (child) { return child.hasOwnProperty('children') ? - queryString(child) : + '(' + queryString(child) + ')' : '(' + child.key + ':' + child.value + ')'; }) - .join(' ' + parameters.operator + ' ') + ')'; + .join(' ' + parameters.operator + ' '); }; return function (parameters, callback) {
82344afed3636343877719fa3aa03377ec6c4159
app/assets/javascripts/student_signup.js
app/assets/javascripts/student_signup.js
var studentSignUp = function(timeslot_id){ var data = {}; data.subject = $("#subject-input").val(); $("#modal_remote").modal('hide'); $.ajax({ data: data, type: "PATCH", url: "/api/timeslots/" + timeslot_id, beforeSend: customBlockUi(this) }).done(function(){ swal({ title: "Great!", text: "You have scheduled a tutoring session!", confirmButtonColor: "#66BB6A", type: "success" }); $('#tutor-cal').fullCalendar('refetchEvents'); }).fail(function() { swal({ title: "Oops...", text: "Something went wrong!", confirmButtonColor: "#EF5350", type: "error" }); }); }
var studentSignUp = function(timeslot_id){ var data = {}; data.subject = $("#subject-input").val(); $("#modal_remote").modal('hide'); $.ajax({ data: data, type: "PATCH", url: "/api/timeslots/" + timeslot_id, beforeSend: customBlockUi(this) }).done(function(){ swal({ title: "Great!", text: "You have scheduled a tutoring session!", confirmButtonColor: "#FFFFFF", showConfirmButton: false, allowOutsideClick: true, timer: 1500, type: "success" }); $('#tutor-cal').fullCalendar('refetchEvents'); }).fail(function() { swal({ title: "Oops...", text: "Something went wrong!", confirmButtonColor: "#EF5350", type: "error" }); }); }
Add timer and remove confirm buttonk, overall cleanup for better ux
Add timer and remove confirm buttonk, overall cleanup for better ux
JavaScript
mit
theresaboard/theres-a-board,theresaboard/theres-a-board,theresaboard/theres-a-board
--- +++ @@ -11,7 +11,10 @@ swal({ title: "Great!", text: "You have scheduled a tutoring session!", - confirmButtonColor: "#66BB6A", + confirmButtonColor: "#FFFFFF", + showConfirmButton: false, + allowOutsideClick: true, + timer: 1500, type: "success" }); $('#tutor-cal').fullCalendar('refetchEvents');
49dfd4fea21ee7868a741c770db551c6e3bcdf5b
commonjs/frontend-core.js
commonjs/frontend-core.js
var _ = require('underscore'); _.extend(Array.prototype, { //deprecated! -> forEach (ist auch ein JS-Standard!) each: function(fn, scope) { _.each(this, fn, scope); }, //to use array.forEach directly forEach: function(fn, scope) { _.forEach(this, fn, scope); } }); if (typeof Array.prototype.add != 'function') { //add is alias for push Array.prototype.add = function () { this.push.apply(this, arguments); }; } if (typeof Array.prototype.shuffle != 'function') { //+ Jonas Raoni Soares Silva //@ http://jsfromhell.com/array/shuffle [rev. #1] Array.prototype.shuffle = function () { for (var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x); return this; }; } //source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== 'function') { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () { }, fBound = function () { return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; if (this.prototype) { // native functions don't have a prototype fNOP.prototype = this.prototype; } fBound.prototype = new fNOP(); return fBound; }; }
var _ = require('underscore'); if (typeof Array.prototype.forEach != 'function') { Array.prototype.forEach = function (fn, scope) { _.forEach(this, fn, scope); }; } //source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== 'function') { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () { }, fBound = function () { return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; if (this.prototype) { // native functions don't have a prototype fNOP.prototype = this.prototype; } fBound.prototype = new fNOP(); return fBound; }; }
Revert "Revert "set only forEach globally for Array.prototyp if not exists (ie8 fallback)""
Revert "Revert "set only forEach globally for Array.prototyp if not exists (ie8 fallback)"" This reverts commit 86586d27805750e77dd598669d12336be35c4d51.
JavaScript
bsd-2-clause
kaufmo/koala-framework,kaufmo/koala-framework,koala-framework/koala-framework,kaufmo/koala-framework,koala-framework/koala-framework
--- +++ @@ -1,30 +1,8 @@ var _ = require('underscore'); -_.extend(Array.prototype, { - //deprecated! -> forEach (ist auch ein JS-Standard!) - each: function(fn, scope) { - _.each(this, fn, scope); - }, - - //to use array.forEach directly - forEach: function(fn, scope) { +if (typeof Array.prototype.forEach != 'function') { + Array.prototype.forEach = function (fn, scope) { _.forEach(this, fn, scope); - } -}); - -if (typeof Array.prototype.add != 'function') { - //add is alias for push - Array.prototype.add = function () { - this.push.apply(this, arguments); - }; -} - -if (typeof Array.prototype.shuffle != 'function') { - //+ Jonas Raoni Soares Silva - //@ http://jsfromhell.com/array/shuffle [rev. #1] - Array.prototype.shuffle = function () { - for (var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x); - return this; }; }
dfd8429c117fa2bf0af2a336807d40296b68ab84
frontend/src/shogi/pieces/nullPiece.js
frontend/src/shogi/pieces/nullPiece.js
import Base from './base'; import * as CONST from '../constants/pieceTypes'; export default class NullPiece extends Base { constructor({ type, x, y, movable = false, isPlaced = false }) { super({ type, x, y, movable, isPlaced }); this.type = CONST.USI_NULL_TYPE; return this; } promote() { return this; } unpromote() { return this; } isPromoted() { return true; } moveDef() { } }
import Base from './base'; import * as CONST from '../constants/pieceTypes'; export default class NullPiece extends Base { constructor({ type, x, y, movable = false, isPlaced = false }) { super({ type, x, y, movable, isPlaced }); this.type = CONST.USI_NULL_TYPE; return this; } promote() { return this; } unpromote() { return this; } isPromoted() { return true; } toOpponentPiece() { } moveDef() { } }
Add `toOpponentPiece` method for NullPiece
Add `toOpponentPiece` method for NullPiece * return undefined. because NullPiece can't captured.
JavaScript
mit
mgi166/usi-front,mgi166/usi-front
--- +++ @@ -20,6 +20,9 @@ return true; } + toOpponentPiece() { + } + moveDef() { } }
eb05d0a5b3b2fd16b1056d23118f1bfc093cb00f
GruntFile.js
GruntFile.js
module.exports = function(grunt) { grunt.config.init({ pkg: grunt.file.readJSON('package.json') }); grunt.loadNpmTasks('grunt-eslint'); grunt.config('eslint', { dist: { options: { configFile: '.eslintrc', }, src: ['touchtap-event.js'] } }); grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.config('jasmine', { test: { src: 'touchtap-event.js', options: { specs: 'test/*-spec.js' } } }); grunt.registerTask('test', [ 'jasmine:test', ]); grunt.registerTask('default', [ 'eslint', 'test' ]); };
module.exports = function(grunt) { grunt.config.init({ pkg: grunt.file.readJSON('package.json') }); grunt.loadNpmTasks('grunt-eslint'); grunt.config('eslint', { dist: { options: { configFile: '.eslintrc', }, src: ['touchtap-event.js'] } }); grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.config('jasmine', { test: { src: 'touchtap-event.js', options: { specs: 'test/*-spec.js' } } }); grunt.registerTask('test', [ 'eslint', 'jasmine:test', ]); grunt.registerTask('default', [ 'test' ]); };
Move eslint in to test grunt task
Move eslint in to test grunt task
JavaScript
mit
Tyriar/touchtap-event,Tyriar/touchtap-event
--- +++ @@ -25,11 +25,11 @@ }); grunt.registerTask('test', [ + 'eslint', 'jasmine:test', ]); grunt.registerTask('default', [ - 'eslint', 'test' ]); };
66deb115264bfccba20ce5daac9ee252febd245d
test/index.js
test/index.js
var PI = require("../lib"); // Two decimals console.log(PI(3)); console.log(PI(16)); // 100 decimals console.log(PI(100));
var PI = require("../lib"); // Two decimals console.log("3." + PI(3)); console.log("3." + PI(16)); // 100 decimals console.log("3." + PI(1000));
Prepend "3." since the function returns the decimals.
Prepend "3." since the function returns the decimals.
JavaScript
mit
IonicaBizau/pi-number
--- +++ @@ -1,8 +1,8 @@ var PI = require("../lib"); // Two decimals -console.log(PI(3)); -console.log(PI(16)); +console.log("3." + PI(3)); +console.log("3." + PI(16)); // 100 decimals -console.log(PI(100)); +console.log("3." + PI(1000));
5af9b4617fd2f0fc3e613d6695ec876814deb793
test/setup.js
test/setup.js
/*! * React Native Autolink * * Copyright 2016-2019 Josh Swan * Released under the MIT license * https://github.com/joshswan/react-native-autolink/blob/master/LICENSE */ import Adapter from 'enzyme-adapter-react-16'; import Enzyme from 'enzyme'; Enzyme.configure({ adapter: new Adapter() }); require('react-native-mock-render/mock');
/*! * React Native Autolink * * Copyright 2016-2019 Josh Swan * Released under the MIT license * https://github.com/joshswan/react-native-autolink/blob/master/LICENSE */ import Adapter from 'enzyme-adapter-react-16'; import Enzyme from 'enzyme'; Enzyme.configure({ adapter: new Adapter() }); require('react-native-mock-render/mock'); require('@babel/register')({ only: [ 'src/**/*.js', 'test/**/*.js', 'node_modules/autolinker/dist/es2015/**/*.js', ], });
Fix transpiling issue in tests
Fix transpiling issue in tests
JavaScript
mit
joshswan/react-native-autolink,joshswan/react-native-autolink
--- +++ @@ -12,3 +12,10 @@ Enzyme.configure({ adapter: new Adapter() }); require('react-native-mock-render/mock'); +require('@babel/register')({ + only: [ + 'src/**/*.js', + 'test/**/*.js', + 'node_modules/autolinker/dist/es2015/**/*.js', + ], +});
5f328870bf71aecd4f6621263474b3feda9c0729
src/hooks/usePageReducer.js
src/hooks/usePageReducer.js
import { useReducer, useCallback } from 'react'; import getReducer from '../pages/dataTableUtilities/reducer/getReducer'; import getColumns from '../pages/dataTableUtilities/columns'; import { debounce } from '../utilities/index'; /** * useReducer wrapper for pages within the app. Creaates a * composed reducer through getReducer for a paraticular * page as well as fetching the required columns and inserting * them into the initial state of the component. * * Returns the current state as well as three dispatchers for * actions to the reducer - a regular dispatch and two debounced * dispatchers - which group sequential calls within the timeout * period, call either the last invocation or the first within * the timeout period. * @param {String} page routeName for the current page. * @param {Object} initialState Initial state of the reducer * @param {Number} debounceTimeout Timeout period for a regular debounce * @param {Number} instantDebounceTimeout Timeout period for an instant debounce */ const usePageReducer = ( page, initialState, debounceTimeout = 250, instantDebounceTimeout = 250 ) => { const columns = getColumns(page); const [state, dispatch] = useReducer(getReducer(page), { ...initialState, columns }); const debouncedDispatch = useCallback(debounce(dispatch, debounceTimeout), []); const instantDebouncedDispatch = useCallback( debounce(dispatch, instantDebounceTimeout, true), [] ); return [state, dispatch, instantDebouncedDispatch, debouncedDispatch]; }; export default usePageReducer;
import { useReducer, useCallback } from 'react'; import getReducer from '../pages/dataTableUtilities/reducer/getReducer'; import getColumns from '../pages/dataTableUtilities/columns'; import { debounce } from '../utilities/index'; /** * useReducer wrapper for pages within the app. Creates a * composed reducer through getReducer for a paraticular * page as well as fetching the required columns and inserting * them into the initial state of the component. * * Returns the current state as well as three dispatchers for * actions to the reducer - a regular dispatch and two debounced * dispatchers - which group sequential calls within the timeout * period, call either the last invocation or the first within * the timeout period. * @param {String} page routeName for the current page. * @param {Object} initialState Initial state of the reducer * @param {Number} debounceTimeout Timeout period for a regular debounce * @param {Number} instantDebounceTimeout Timeout period for an instant debounce */ const usePageReducer = ( page, initialState, debounceTimeout = 250, instantDebounceTimeout = 250 ) => { const columns = getColumns(page); const [state, dispatch] = useReducer(getReducer(page), { ...initialState, columns }); const debouncedDispatch = useCallback(debounce(dispatch, debounceTimeout), []); const instantDebouncedDispatch = useCallback( debounce(dispatch, instantDebounceTimeout, true), [] ); return [state, dispatch, instantDebouncedDispatch, debouncedDispatch]; }; export default usePageReducer;
Add update to useReducer comments
Add update to useReducer comments Co-Authored-By: Chris Petty <637933a5c948ed3d23257417b9455449bf8cfd77@gmail.com>
JavaScript
mit
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
--- +++ @@ -4,7 +4,7 @@ import { debounce } from '../utilities/index'; /** - * useReducer wrapper for pages within the app. Creaates a + * useReducer wrapper for pages within the app. Creates a * composed reducer through getReducer for a paraticular * page as well as fetching the required columns and inserting * them into the initial state of the component.
66768e0aae1eeb622d0a901ee376d3f4d108f765
test/karma.config.js
test/karma.config.js
const serverEndpoints = require('./server') module.exports = function(config) { config.set({ basePath: '..', frameworks: ['detectBrowsers', 'mocha', 'chai'], detectBrowsers: { preferHeadless: true, usePhantomJS: false }, client: { mocha: { ui: 'tdd' } }, files: [ 'node_modules/promise-polyfill/promise.js', 'node_modules/abortcontroller-polyfill/dist/abortcontroller-polyfill-only.js', 'node_modules/url-search-params/build/url-search-params.max.js', 'dist/fetch.umd.js', 'test/test.js' ], reporters: process.env.CI ? ['dots'] : ['progress'], port: 9876, colors: true, logLevel: process.env.CI ? config.LOG_WARN : config.LOG_INFO, autoWatch: false, singleRun: true, concurrency: Infinity, beforeMiddleware: ['custom'], plugins: [ 'karma-*', { 'middleware:custom': ['value', serverEndpoints] } ] }) }
const serverEndpoints = require('./server') module.exports = function(config) { config.set({ basePath: '..', frameworks: ['detectBrowsers', 'mocha', 'chai'], detectBrowsers: { preferHeadless: true, usePhantomJS: false, postDetection: availableBrowsers => availableBrowsers.map(browser => (browser.startsWith('Chrom') ? `${browser}NoSandbox` : browser)) }, client: { mocha: { ui: 'tdd' } }, files: [ 'node_modules/promise-polyfill/promise.js', 'node_modules/abortcontroller-polyfill/dist/abortcontroller-polyfill-only.js', 'node_modules/url-search-params/build/url-search-params.max.js', 'dist/fetch.umd.js', 'test/test.js' ], reporters: process.env.CI ? ['dots'] : ['progress'], port: 9876, colors: true, logLevel: process.env.CI ? config.LOG_WARN : config.LOG_INFO, autoWatch: false, singleRun: true, concurrency: Infinity, customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox'] }, ChromiumHeadlessNoSandbox: { base: 'ChromiumHeadless', flags: ['--no-sandbox'] } }, beforeMiddleware: ['custom'], plugins: [ 'karma-*', { 'middleware:custom': ['value', serverEndpoints] } ] }) }
Bring back `--no-sandbox` for Travis CI compatibility
Bring back `--no-sandbox` for Travis CI compatibility
JavaScript
mit
github/fetch,aleclarson/fetch
--- +++ @@ -6,7 +6,9 @@ frameworks: ['detectBrowsers', 'mocha', 'chai'], detectBrowsers: { preferHeadless: true, - usePhantomJS: false + usePhantomJS: false, + postDetection: availableBrowsers => + availableBrowsers.map(browser => (browser.startsWith('Chrom') ? `${browser}NoSandbox` : browser)) }, client: { mocha: { @@ -27,6 +29,16 @@ autoWatch: false, singleRun: true, concurrency: Infinity, + customLaunchers: { + ChromeHeadlessNoSandbox: { + base: 'ChromeHeadless', + flags: ['--no-sandbox'] + }, + ChromiumHeadlessNoSandbox: { + base: 'ChromiumHeadless', + flags: ['--no-sandbox'] + } + }, beforeMiddleware: ['custom'], plugins: [ 'karma-*',
386fbab3484a3bec5c2dcb538825c17979c0233e
lib/assets/javascripts/drop.js
lib/assets/javascripts/drop.js
//= require ./core //= require ./config //= require_self //= require_tree ./routers //= require_tree ./views //= require_tree ./models (function () { var Drop = window.Drop; _.extend(Drop, Marbles.Events, { Models: {}, Collections: {}, Routers: {}, Helpers: { fullPath: function (path) { prefix = Drop.config.PATH_PREFIX || '/'; return (prefix + '/').replace(/\/+$/, '') + path; } }, run: function (options) { if (!Marbles.history || Marbles.history.started) { return; } if (!options) { options = {}; } if (!this.config.container) { this.config.container = { el: document.getElementById('main') }; } Marbles.history.start(_.extend({ root: (this.config.PATH_PREFIX || '') + '/' }, options.history || {})); this.ready = true; this.trigger('ready'); } }); if (Drop.config_ready) { Drop.trigger('config:ready'); } })();
//= require ./core //= require ./config //= require_self //= require_tree ./routers //= require_tree ./views //= require_tree ./models (function () { var Drop = window.Drop; _.extend(Drop, Marbles.Events, { Views: {}, Models: {}, Collections: {}, Routers: {}, Helpers: { fullPath: function (path) { prefix = Drop.config.PATH_PREFIX || '/'; return (prefix + '/').replace(/\/+$/, '') + path; } }, run: function (options) { if (!Marbles.history || Marbles.history.started) { return; } if (!options) { options = {}; } if (!this.config.container) { this.config.container = { el: document.getElementById('main') }; } Marbles.history.start(_.extend({ root: (this.config.PATH_PREFIX || '') + '/' }, options.history || {})); this.ready = true; this.trigger('ready'); } }); if (Drop.config_ready) { Drop.trigger('config:ready'); } })();
Add Drop.Views object to hold React components
Add Drop.Views object to hold React components
JavaScript
bsd-3-clause
cupcake/files-web,cupcake/files-web
--- +++ @@ -10,6 +10,7 @@ var Drop = window.Drop; _.extend(Drop, Marbles.Events, { + Views: {}, Models: {}, Collections: {}, Routers: {},
74c191b2f5058ecff0755b44eb55f79953e13808
blueprints/ember-sweetalert/index.js
blueprints/ember-sweetalert/index.js
module.exports = { normalizeEntityName: function() {}, afterInstall: function() {} };
module.exports = { normalizeEntityName: function() {}, afterInstall: function() { return this.addBowerPackageToProject('sweetalert2', '^6.1.0'); } };
Add bower package to project
Add bower package to project Believe this will fix issue #3, plus is desired behaviour anyway because you need the installing Ember project to have sweetalert2 installed via bower.
JavaScript
mit
Tonkpils/ember-sweetalert,Tonkpils/ember-sweetalert
--- +++ @@ -1,5 +1,7 @@ module.exports = { normalizeEntityName: function() {}, - afterInstall: function() {} + afterInstall: function() { + return this.addBowerPackageToProject('sweetalert2', '^6.1.0'); + } };
484d74160b829a5e75011c62224cbb149f0b236e
src/color/GradientStop.js
src/color/GradientStop.js
var GradientStop = Base.extend({ beans: true, // TODO: support midPoint? (initial tests didn't look nice) initialize: function(color, rampPoint) { this.color = Color.read([color]); this.rampPoint = rampPoint !== null ? rampPoint : 0; }, getRampPoint: function() { return this._rampPoint; }, setRampPoint: function(rampPoint) { this._rampPoint = rampPoint; }, getColor: function() { return this._color; }, setColor: function() { this._color = Color.read(arguments); } });
var GradientStop = Base.extend({ beans: true, // TODO: support midPoint? (initial tests didn't look nice) initialize: function(color, rampPoint) { this._color = Color.read([color]); this._rampPoint = rampPoint !== null ? rampPoint : 0; }, getRampPoint: function() { return this._rampPoint; }, setRampPoint: function(rampPoint) { this._rampPoint = rampPoint; }, getColor: function() { return this._color; }, setColor: function() { this._color = Color.read(arguments); } });
Set private properties directly in initialize(), no need to call setters.
Set private properties directly in initialize(), no need to call setters.
JavaScript
mit
EskenderDev/paper.js,baiyanghese/paper.js,li0t/paper.js,nancymark/paper.js,luisbrito/paper.js,iconexperience/paper.js,luisbrito/paper.js,fredoche/paper.js,JunaidPaul/paper.js,superjudge/paper.js,lehni/paper.js,ClaireRutkoske/paper.js,baiyanghese/paper.js,0/paper.js,ClaireRutkoske/paper.js,legendvijay/paper.js,superjudge/paper.js,superjudge/paper.js,proofme/paper.js,luisbrito/paper.js,JunaidPaul/paper.js,Olegas/paper.js,byte-foundry/paper.js,baiyanghese/paper.js,li0t/paper.js,mcanthony/paper.js,EskenderDev/paper.js,mcanthony/paper.js,nancymark/paper.js,lehni/paper.js,legendvijay/paper.js,byte-foundry/paper.js,NHQ/paper,lehni/paper.js,fredoche/paper.js,mcanthony/paper.js,nancymark/paper.js,legendvijay/paper.js,rgordeev/paper.js,NHQ/paper,proofme/paper.js,iconexperience/paper.js,ClaireRutkoske/paper.js,0/paper.js,byte-foundry/paper.js,proofme/paper.js,rgordeev/paper.js,EskenderDev/paper.js,li0t/paper.js,Olegas/paper.js,chad-autry/paper.js,fredoche/paper.js,iconexperience/paper.js,JunaidPaul/paper.js,Olegas/paper.js,rgordeev/paper.js
--- +++ @@ -3,8 +3,8 @@ // TODO: support midPoint? (initial tests didn't look nice) initialize: function(color, rampPoint) { - this.color = Color.read([color]); - this.rampPoint = rampPoint !== null ? rampPoint : 0; + this._color = Color.read([color]); + this._rampPoint = rampPoint !== null ? rampPoint : 0; }, getRampPoint: function() {
1a55b57d10c44c0e036cf1a5d0ee35ab3b79a90e
lib/Helper/EventHandlerHelper.js
lib/Helper/EventHandlerHelper.js
"use babel"; import { Emitter } from 'atom' export default class EventHandlerHelper { constructor() { this.emitter = new Emitter(); } onClose(callback) { this.emitter.on("maperwiki-wordcount-close",callback); } close() { this.emitter.emit("maperwiki-wordcount-close"); } onViewWordcountFrame(callback) { this.emitter.on("maperwiki-wordcount-visibility",callback); } viewWordcountFrame(visible) { this.emitter.emit("maperwiki-wordcount-visibility",visible); } onCloseExportPanel(callback) { this.emitter.on("maperwiki-export-panel-close",callback); } closeExportPanel(visible) { this.emitter.emit("maperwiki-export-panel-close",visible); } onClear(callback) { this.emitter.on("clear-control",callback); } clear() { this.emitter.emit("clear-control"); } destroy() { this.emitter.clear(); this.emitter.dispose(); } dispose() { this.destroy(); } }
"use babel"; import { Emitter } from 'atom' export default class EventHandlerHelper { constructor() { this.emitter = new Emitter(); } onClose(callback) { return this.emitter.on("maperwiki-wordcount-close",callback); } close() { this.emitter.emit("maperwiki-wordcount-close"); } onViewWordcountFrame(callback) { return this.emitter.on("maperwiki-wordcount-visibility",callback); } viewWordcountFrame(visible) { this.emitter.emit("maperwiki-wordcount-visibility",visible); } onCloseExportPanel(callback) { return this.emitter.on("maperwiki-export-panel-close",callback); } closeExportPanel(visible) { this.emitter.emit("maperwiki-export-panel-close",visible); } onClear(callback) { return this.emitter.on("clear-control",callback); } clear() { this.emitter.emit("clear-control"); } destroy() { this.emitter.clear(); this.emitter.dispose(); } }
Patch for Event handler (second try) :)
Patch for Event handler (second try) :) Real patch for event handler...
JavaScript
mit
rkaradas/MaPerWiki,rkaradas/MaPerWiki
--- +++ @@ -10,7 +10,7 @@ onClose(callback) { - this.emitter.on("maperwiki-wordcount-close",callback); + return this.emitter.on("maperwiki-wordcount-close",callback); } close() { @@ -19,7 +19,7 @@ onViewWordcountFrame(callback) { - this.emitter.on("maperwiki-wordcount-visibility",callback); + return this.emitter.on("maperwiki-wordcount-visibility",callback); } viewWordcountFrame(visible) @@ -29,7 +29,7 @@ onCloseExportPanel(callback) { - this.emitter.on("maperwiki-export-panel-close",callback); + return this.emitter.on("maperwiki-export-panel-close",callback); } closeExportPanel(visible) @@ -39,7 +39,7 @@ onClear(callback) { - this.emitter.on("clear-control",callback); + return this.emitter.on("clear-control",callback); } clear() { @@ -51,8 +51,4 @@ this.emitter.clear(); this.emitter.dispose(); } - dispose() - { - this.destroy(); - } }
48acd862586847ef3d9310c5be4467aa3481744f
docs/src/pages/Home/counterCode.js
docs/src/pages/Home/counterCode.js
export default `import { h, app } from "hyperapp" app({ init: 0, view: state => h("div", {}, [ h("h1", {}, state), h("button", { onclick: state => state - 1 }, "subtract"), h("button", { onclick: state => state + 1 }, "add") ]), node: document.getElementById("app") })`
export default `import { h, app } from "hyperapp" app({ init: 0, view: state => h("div", {}, [ h("h1", {}, state), h("button", { onclick: state => state - 1 }, "substract"), h("button", { onclick: state => state + 1 }, "add") ]), node: document.getElementById("app") })`
Fix typo in counter app
Fix typo in counter app
JavaScript
mit
jbucaran/hyperapp,hyperapp/hyperapp,hyperapp/hyperapp
--- +++ @@ -5,7 +5,7 @@ view: state => h("div", {}, [ h("h1", {}, state), - h("button", { onclick: state => state - 1 }, "subtract"), + h("button", { onclick: state => state - 1 }, "substract"), h("button", { onclick: state => state + 1 }, "add") ]), node: document.getElementById("app")
dd2b6eb07efe252559f82dde5eb5a6e084f0d859
src/main/javascript/list.js
src/main/javascript/list.js
var Vue = require('vue'); var CommentService = require('./services/comment-service.js'); var template = require('./list.html'); new Vue({ el: '#platon-comment-thread', render: template.render, staticRenderFns: template.staticRenderFns, data: { loading: true, comments: [] }, components: { 'platon-comment': require('./components/comment'), 'platon-comment-form': require('./components/comment-form') }, methods: { addComment: function(newComment) { this.comments.push(newComment); } }, created: function () { var vm = this; CommentService.getComments(window.location.href) .then(function updateModel(comments) { vm.comments = comments; vm.loading = false; }) .catch(function displayError(reason) { alert(reason); }); } });
var Vue = require('vue'); var CommentService = require('./services/comment-service.js'); var template = require('./list.html'); new Vue({ el: '#platon-comment-thread', render: template.render, staticRenderFns: template.staticRenderFns, data: { loading: true, comments: [] }, components: { 'platon-comment': require('./components/comment'), 'platon-comment-form': require('./components/comment-form') }, methods: { addComment: function(newComment) { this.comments.push(newComment); } }, created: function () { var vm = this; CommentService.getComments(window.location.pathname) .then(function updateModel(comments) { vm.comments = comments; vm.loading = false; }) .catch(function displayError(reason) { alert(reason); }); } });
Use url path instead of full url for threads
Use url path instead of full url for threads
JavaScript
apache-2.0
pvorb/platon,pvorb/platon,pvorb/platon
--- +++ @@ -27,7 +27,7 @@ created: function () { var vm = this; - CommentService.getComments(window.location.href) + CommentService.getComments(window.location.pathname) .then(function updateModel(comments) { vm.comments = comments; vm.loading = false;
1c97af1dba133a014295c692135c2c194b500435
example/src/app.js
example/src/app.js
var App = Ember.Application.create(); App.Boards = ['common', 'intermediate', 'advanced']; App.Host = "http://localhost:5984";
var App = Ember.Application.create(); App.Boards = ['common', 'intermediate', 'advanced']; App.Host = "http://ember-couchdb-kit.roundscope.pw:15984";
Revert "reverted change of couchdb host"
Revert "reverted change of couchdb host" This reverts commit 6d60341ba077ef645c1f2f6dbf8a4030e07b2812.
JavaScript
mit
Zatvobor/ember-couchdb-kit,ValidUSA/ember-couch,Zatvobor/ember-couchdb-kit,ValidUSA/ember-couch
--- +++ @@ -3,4 +3,4 @@ App.Boards = ['common', 'intermediate', 'advanced']; -App.Host = "http://localhost:5984"; +App.Host = "http://ember-couchdb-kit.roundscope.pw:15984";
48992018fc9bb6fa38bac553fe2132ce84a50a8a
server/Media/FileScanner/getFiles.js
server/Media/FileScanner/getFiles.js
const debug = require('debug') const log = debug('app:media:fileScanner:getFiles') const { promisify } = require('util') const { resolve } = require('path') const fs = require('fs') const readdir = promisify(fs.readdir) const stat = promisify(fs.stat) async function getFiles (dir, extra) { let list = [] try { list = await readdir(dir) } catch (err) { log(err) } const files = await Promise.all(list.map(async (item) => { const file = resolve(dir, item) return (await stat(file)).isDirectory() ? getFiles(file, extra) : { file, ...extra } })) return files.reduce((a, f) => a.concat(f), []) } module.exports = getFiles
const { promisify } = require('util') const { resolve } = require('path') const fs = require('fs') const readdir = promisify(fs.readdir) const stat = promisify(fs.stat) async function getFiles (dir, extra) { const list = await readdir(dir) const files = await Promise.all(list.map(async (item) => { const file = resolve(dir, item) return (await stat(file)).isDirectory() ? getFiles(file, extra) : { file, ...extra } })) return files.reduce((a, f) => a.concat(f), []) } module.exports = getFiles
Fix path offline detection (don't catch readdir() errors)
Fix path offline detection (don't catch readdir() errors)
JavaScript
isc
bhj/karaoke-forever,bhj/karaoke-forever
--- +++ @@ -1,5 +1,3 @@ -const debug = require('debug') -const log = debug('app:media:fileScanner:getFiles') const { promisify } = require('util') const { resolve } = require('path') const fs = require('fs') @@ -7,13 +5,7 @@ const stat = promisify(fs.stat) async function getFiles (dir, extra) { - let list = [] - - try { - list = await readdir(dir) - } catch (err) { - log(err) - } + const list = await readdir(dir) const files = await Promise.all(list.map(async (item) => { const file = resolve(dir, item)
0ef64c70248efaf7cd051d7d3d4db619cdae5589
ember_debug/models/profile_node.js
ember_debug/models/profile_node.js
/** A tree structure for assembling a list of render calls so they can be grouped and displayed nicely afterwards. @class ProfileNode **/ var ProfileNode = function(start, payload, parent) { this.start = start; this.timestamp = Date.now(); if (payload) { if (payload.template) { this.name = payload.template; } if (payload.object) { this.name = payload.object.toString(); var match = this.name.match(/:(ember\d+)>$/); if (match && match.length > 1) { this.viewGuid = match[1]; } } } else { this.name = "unknown view"; } if (parent) { this.parent = parent; } this.children = []; }; ProfileNode.prototype = { finish: function(timestamp) { this.time = (timestamp - this.start); this.calcDuration(); // Once we attach to our parent, we remove that reference // to avoid a graph cycle when serializing: if (this.parent) { this.parent.children.push(this); this.parent = null; } }, calcDuration: function() { this.duration = Math.round(this.time * 100) / 100; } }; export default ProfileNode;
/** A tree structure for assembling a list of render calls so they can be grouped and displayed nicely afterwards. @class ProfileNode **/ var ProfileNode = function(start, payload, parent) { this.start = start; this.timestamp = Date.now(); if (payload) { if (payload.template) { this.name = payload.template; } if (payload.object) { var name = payload.object.toString(); var match = name.match(/:(ember\d+)>$/); this.name = name.replace(/:?:ember\d+>$/, '').replace(/^</, ''); if (match && match.length > 1) { this.viewGuid = match[1]; } } } else { this.name = "unknown view"; } if (parent) { this.parent = parent; } this.children = []; }; ProfileNode.prototype = { finish: function(timestamp) { this.time = (timestamp - this.start); this.calcDuration(); // Once we attach to our parent, we remove that reference // to avoid a graph cycle when serializing: if (this.parent) { this.parent.children.push(this); this.parent = null; } }, calcDuration: function() { this.duration = Math.round(this.time * 100) / 100; } }; export default ProfileNode;
Clean up view name in render performance tree
Clean up view name in render performance tree
JavaScript
mit
karthiick/ember-inspector,Patsy-issa/ember-inspector,jryans/ember-inspector,knownasilya/ember-inspector,chrisgame/ember-inspector,chrisgame/ember-inspector,jayphelps/ember-inspector,Patsy-issa/ember-inspector,jayphelps/ember-inspector,sly7-7/ember-inspector,teddyzeenny/ember-inspector,pete-the-pete/ember-inspector,emberjs/ember-inspector,karthiick/ember-inspector,NikkiDreams/ember-inspector,pete-the-pete/ember-inspector,maheshsenni/ember-inspector,vvscode/js--ember-inspector,teddyzeenny/ember-extension,emberjs/ember-inspector,knownasilya/ember-inspector,sivakumar-kailasam/ember-inspector,teddyzeenny/ember-inspector,teddyzeenny/ember-extension,NikkiDreams/ember-inspector,aceofspades/ember-inspector,cibernox/ember-inspector,dsturley/ember-inspector,sly7-7/ember-inspector,maheshsenni/ember-inspector,sivakumar-kailasam/ember-inspector,dsturley/ember-inspector,cibernox/ember-inspector,vvscode/js--ember-inspector,aceofspades/ember-inspector,rwjblue/ember-inspector,jryans/ember-inspector
--- +++ @@ -9,8 +9,9 @@ if (payload) { if (payload.template) { this.name = payload.template; } if (payload.object) { - this.name = payload.object.toString(); - var match = this.name.match(/:(ember\d+)>$/); + var name = payload.object.toString(); + var match = name.match(/:(ember\d+)>$/); + this.name = name.replace(/:?:ember\d+>$/, '').replace(/^</, ''); if (match && match.length > 1) { this.viewGuid = match[1]; }
99c293ce2bd0f0e5ac297d62b1b158a9b4208d5d
slurp/src/main/webapp/scripts/init-firebase.js
slurp/src/main/webapp/scripts/init-firebase.js
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Initialize Firebase and its related product we use using the provided // Firebase project configuation. var firebaseConfig = { apiKey: "AIzaSyAAJgRhJY_rRn_q_On1HdA3hx15YHSkEJg", authDomain: "step53-2020.firebaseapp.com", databaseURL: "https://step53-2020.firebaseio.com", projectId: "step53-2020", storageBucket: "step53-2020.appspot.com", messagingSenderId: "905834221913", appId: "1:905834221913:web:25e711f1132b2c0537fc48", measurementId: "G-PLVY991DHW" }; firebase.initializeApp(firebaseConfig);
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Initialize Firebase and its related product we use using the provided // Firebase project configuation. var firebaseConfig = { apiKey: "AIzaSyAAJgRhJY_rRn_q_On1HdA3hx15YHSkEJg", authDomain: "step53-2020.firebaseapp.com", databaseURL: "https://step53-2020.firebaseio.com", projectId: "step53-2020", storageBucket: "step53-2020.appspot.com", messagingSenderId: "905834221913", appId: "1:905834221913:web:25e711f1132b2c0537fc48", measurementId: "G-PLVY991DHW" }; firebase.initializeApp(firebaseConfig); const db = firebase.firestore();
Add initializaton of Cloud Firestore instance for use accross all scripts.
Add initializaton of Cloud Firestore instance for use accross all scripts.
JavaScript
apache-2.0
googleinterns/SLURP,googleinterns/SLURP,googleinterns/SLURP
--- +++ @@ -27,3 +27,4 @@ }; firebase.initializeApp(firebaseConfig); +const db = firebase.firestore();
1029d50240901af797ee62816b02afaafb9b5ec2
src/editor/deposittool.js
src/editor/deposittool.js
import * as PIXI from 'pixi.js'; import PlaceTool from './placetool'; import {createLogDepositGraphics} from '../game/logdeposit'; export default class DepositTool extends PlaceTool { constructor(stage, level) { super(stage, level); var pointerGraphics = createLogDepositGraphics(); this.pointerContainer.addChild(pointerGraphics); this.minDistanceFromRoad = 70; this.maxDistanceFromRoad = 50; this.type = -1; } activate() { super.activate(); } mouseMove(mouseInput) { super.mouseMove(mouseInput); } mouseDown(mouseInput) { } mouseUp(mouseInput) { super.mouseUp(mouseInput); } placeItem(position, angle) { this.level.addDeposit(position, angle, this.type) } setType(type) { this.type = type; } keyDown(event) {} keyUp(event) {} deactivate() { super.deactivate(); } }
import * as PIXI from 'pixi.js'; import PlaceTool from './placetool'; import {createLogDepositGraphics} from '../game/logdeposit'; export default class DepositTool extends PlaceTool { constructor(stage, level) { super(stage, level); var pointerGraphics = createLogDepositGraphics(); this.pointerContainer.addChild(pointerGraphics); this.minDistanceFromRoad = 70; this.maxDistanceFromRoad = 50; this.type = undefined; } activate() { super.activate(); } mouseMove(mouseInput) { super.mouseMove(mouseInput); } mouseDown(mouseInput) { } mouseUp(mouseInput) { super.mouseUp(mouseInput); } placeItem(position, angle) { this.level.addDeposit(position, angle, this.type) } setType(type) { this.type = type; } keyDown(event) {} keyUp(event) {} deactivate() { super.deactivate(); } }
Fix editor crashing when adding log deposit
Fix editor crashing when adding log deposit
JavaScript
mit
gaviarctica/forestry-game-frontend,gaviarctica/forestry-game-frontend
--- +++ @@ -12,7 +12,7 @@ this.minDistanceFromRoad = 70; this.maxDistanceFromRoad = 50; - this.type = -1; + this.type = undefined; } activate() {
056be57007a61135c167b4474bca96b015e8b34b
cfg/.vim/templates/react-native/fire.js
cfg/.vim/templates/react-native/fire.js
'use strict'; import React, { PropTypes, Component } from 'react'; import { InteractionManager } from 'react-native'; import SkeletonNameHOC from './skeleton-name.hoc.js'; export default class FierySkeletonName extends Component { constructor(props) { super(props); } static propTypes = { db: PropTypes.object, } static defaultProps = { db: {}, } render() { return ( <SkeletonNameHOC {...this.props} /> ); } }
'use strict'; import React, { PropTypes, Component } from 'react'; import { InteractionManager } from 'react-native'; import SkeletonNameHOC from './skeleton-name.hoc.js'; export default class FierySkeletonName extends Component { constructor(props) { super(props); } static propTypes = {} render() { return ( <SkeletonNameHOC {...this.props} /> ); } }
Remove db from props in template
Remove db from props in template Now that I have a React Native project where I take db and friends from context, I find that the automatic db in propTypes is a hassle to delete, so I've removed it for now.
JavaScript
mit
igemnace/vim-config,igemnace/my-vim-config,igemnace/vim-config,igemnace/vim-config
--- +++ @@ -9,13 +9,7 @@ super(props); } - static propTypes = { - db: PropTypes.object, - } - - static defaultProps = { - db: {}, - } + static propTypes = {} render() { return (
1e9c3b9c669c78e42fa9b6636ae72f5499b2175e
tests/directivesSpec.js
tests/directivesSpec.js
(function () { 'use strict'; describe('directives module', function () { var $compile, $rootScope, DropletMock; beforeEach(module('directives')); beforeEach(inject(function ($injector) { $compile = $injector.get('$compile'); $rootScope = $injector.get('$rootScope'); DropletMock = { 'status': 'active', 'memory': '512' }; })); describe('status', function () { var $scope, element; beforeEach(function () { $scope = $rootScope.$new(); $scope.droplet = DropletMock; element = $compile('<status></status>')($scope); $rootScope.$digest(); }); it('should contains the "Status: active" string in a child node', function () { expect(element[0].innerText).toBe('Status: active'); }); }); describe('memory', function () { var $scope, element; beforeEach(function () { $scope = $rootScope.$new(); $scope.droplet = DropletMock; element = $compile('<memory></memory>')($scope); $rootScope.$digest(); }); it('should contains the "Memory: 512MB" string in a child node', function () { expect(element[0].innerText).toBe('Memory: 512 MB'); }); }); }); })();
(function () { 'use strict'; describe('directives module', function () { var $compile, $rootScope, DropletMock; beforeEach(module('directives')); beforeEach(inject(function ($injector) { $compile = $injector.get('$compile'); $rootScope = $injector.get('$rootScope'); DropletMock = { 'status': 'active', 'memory': '512', 'vcpus': 1 }; })); describe('status', function () { var $scope, element; beforeEach(function () { $scope = $rootScope.$new(); $scope.droplet = DropletMock; element = $compile('<status></status>')($scope); $rootScope.$digest(); }); it('should contains the "Status: active" string in a child node', function () { expect(element[0].innerText).toBe('Status: active'); }); }); describe('memory', function () { var $scope, element; beforeEach(function () { $scope = $rootScope.$new(); $scope.droplet = DropletMock; element = $compile('<memory></memory>')($scope); $rootScope.$digest(); }); it('should contains the "Memory: 512MB" string in a child node', function () { expect(element[0].innerText).toBe('Memory: 512 MB'); }); }); describe('cpus', function () { var $scope, element; beforeEach(function () { $scope = $rootScope.$new(); $scope.droplet = DropletMock; element = $compile('<cpus></cpus>')($scope); $rootScope.$digest(); }); it('should contains the "CPUs: 1" string in a child node', function () { expect(element[0].innerText).toBe("CPUs: 1"); }); }); }); })();
Add cpus directive unit test
Add cpus directive unit test
JavaScript
mit
DojoGeekRA/DigitalOcean,DojoGeekRA/DigitalOcean
--- +++ @@ -10,7 +10,8 @@ $rootScope = $injector.get('$rootScope'); DropletMock = { 'status': 'active', - 'memory': '512' + 'memory': '512', + 'vcpus': 1 }; })); describe('status', function () { @@ -39,5 +40,18 @@ expect(element[0].innerText).toBe('Memory: 512 MB'); }); }); + describe('cpus', function () { + var $scope, + element; + beforeEach(function () { + $scope = $rootScope.$new(); + $scope.droplet = DropletMock; + element = $compile('<cpus></cpus>')($scope); + $rootScope.$digest(); + }); + it('should contains the "CPUs: 1" string in a child node', function () { + expect(element[0].innerText).toBe("CPUs: 1"); + }); + }); }); })();
756929079aaf1dbef8b869d917e0fc8a0f4f3a10
examples/vue-apollo/nuxt.config.js
examples/vue-apollo/nuxt.config.js
module.exports = { build: { vendor: ['vue-apollo', 'apollo-client'] }, router: { middleware: 'apollo' }, plugins: [ // Will inject the plugin in the $root app and also in the context as `i18n` { src: '~plugins/apollo.js', injectAs: 'apolloProvider' } ] }
module.exports = { build: { vendor: ['vue-apollo', 'apollo-client'] }, router: { middleware: 'apollo' }, plugins: [ // Will inject the plugin in the $root app and also in the context as `apolloProvider` { src: '~plugins/apollo.js', injectAs: 'apolloProvider' } ] }
Fix copy paste typo in the comments
Fix copy paste typo in the comments
JavaScript
mit
jfroffice/nuxt.js,mgesmundo/nuxt.js,mgesmundo/nuxt.js,jfroffice/nuxt.js
--- +++ @@ -6,7 +6,7 @@ middleware: 'apollo' }, plugins: [ - // Will inject the plugin in the $root app and also in the context as `i18n` + // Will inject the plugin in the $root app and also in the context as `apolloProvider` { src: '~plugins/apollo.js', injectAs: 'apolloProvider' } ] }
239bc0fe0eeae2c309902e2b56dafbd2298cb3aa
app/services/logger.js
app/services/logger.js
import Ember from "ember"; import config from "../config/environment"; export default Ember.Service.extend({ session: Ember.inject.service(), rollbar: Ember.inject.service(), getReason(reason) { return reason instanceof Error || typeof reason !== "object" ? reason : JSON.stringify(reason); }, error: function(reason) { if (reason.status === 0) { return; } console.info(reason); if (config.environment === "production" || config.staging) { var userName = this.get("session.currentUser.fullName"); var currentUser = this.get("session.currentUser"); var userId = this.get("session.currentUser.id"); var error = this.getReason(reason); var environment = config.staging ? "staging" : config.environment; var version = `${config.APP.SHA} (shared ${config.APP.SHARED_SHA})`; var airbrake = new airbrakeJs.Client({ projectId: config.APP.AIRBRAKE_PROJECT_ID, projectKey: config.APP.AIRBRAKE_PROJECT_KEY }); airbrake.setHost(config.APP.AIRBRAKE_HOST); airbrake.notify({ error, context: { userId, userName, environment, version } }); this.set('rollbar.currentUser', currentUser); this.get('rollbar').error(error, data = { id: userId, username: userName, environment: environment}); } } });
import Ember from "ember"; import config from "../config/environment"; export default Ember.Service.extend({ session: Ember.inject.service(), rollbar: Ember.inject.service(), getReason(reason) { return reason instanceof Error || typeof reason !== "object" ? reason : JSON.stringify(reason); }, error: function(reason) { if (reason.status === 0) { return; } console.info(reason); if (config.environment === "production" || config.staging) { var currentUser = this.get("session.currentUser"); var userName = currentUser.get("fullName"); var userId = currentUser.get("id"); var error = this.getReason(reason); var environment = config.staging ? "staging" : config.environment; var version = `${config.APP.SHA} (shared ${config.APP.SHARED_SHA})`; var airbrake = new airbrakeJs.Client({ projectId: config.APP.AIRBRAKE_PROJECT_ID, projectKey: config.APP.AIRBRAKE_PROJECT_KEY }); airbrake.setHost(config.APP.AIRBRAKE_HOST); airbrake.notify({ error, context: { userId, userName, environment, version } }); this.set('rollbar.currentUser', currentUser); this.get('rollbar').error(error, data = { id: userId, username: userName, environment: environment}); } } });
Use currenUser instead of getting it from session
Use currenUser instead of getting it from session
JavaScript
mit
crossroads/shared.goodcity,crossroads/shared.goodcity
--- +++ @@ -16,9 +16,9 @@ } console.info(reason); if (config.environment === "production" || config.staging) { - var userName = this.get("session.currentUser.fullName"); var currentUser = this.get("session.currentUser"); - var userId = this.get("session.currentUser.id"); + var userName = currentUser.get("fullName"); + var userId = currentUser.get("id"); var error = this.getReason(reason); var environment = config.staging ? "staging" : config.environment; var version = `${config.APP.SHA} (shared ${config.APP.SHARED_SHA})`;
3689be16a26bd3f95eda6c57a4232952f6a87eca
ghost/admin/utils/codemirror-mobile.js
ghost/admin/utils/codemirror-mobile.js
/*global CodeMirror*/ import mobileUtils from 'ghost/utils/mobile-utils'; import createTouchEditor from 'ghost/assets/lib/touch-editor'; var setupMobileCodeMirror, TouchEditor, init; setupMobileCodeMirror = function setupMobileCodeMirror() { var noop = function () {}, key; for (key in CodeMirror) { if (CodeMirror.hasOwnProperty(key)) { CodeMirror[key] = noop; } } CodeMirror.fromTextArea = function (el, options) { return new TouchEditor(el, options); }; CodeMirror.keyMap = { basic: {} }; }; init = function init() { if (mobileUtils.hasTouchScreen()) { $('body').addClass('touch-editor'); // make editor tabs touch-to-toggle in portrait mode $('.floatingheader').on('touchstart', function () { $('.entry-markdown').toggleClass('active'); $('.entry-preview').toggleClass('active'); }); Ember.touchEditor = true; mobileUtils.initFastClick(); TouchEditor = createTouchEditor(); setupMobileCodeMirror(); } }; export default { createIfMobile: init };
/*global CodeMirror, device*/ import mobileUtils from 'ghost/utils/mobile-utils'; import createTouchEditor from 'ghost/assets/lib/touch-editor'; var setupMobileCodeMirror, TouchEditor, init; setupMobileCodeMirror = function setupMobileCodeMirror() { var noop = function () {}, key; for (key in CodeMirror) { if (CodeMirror.hasOwnProperty(key)) { CodeMirror[key] = noop; } } CodeMirror.fromTextArea = function (el, options) { return new TouchEditor(el, options); }; CodeMirror.keyMap = { basic: {} }; }; init = function init() { //Codemirror does not function on mobile devices, // nor on any iDevice. if (device.mobile() || (device.tablet() && device.ios())) { $('body').addClass('touch-editor'); // make editor tabs touch-to-toggle in portrait mode $('.floatingheader').on('touchstart', function () { $('.entry-markdown').toggleClass('active'); $('.entry-preview').toggleClass('active'); }); Ember.touchEditor = true; mobileUtils.initFastClick(); TouchEditor = createTouchEditor(); setupMobileCodeMirror(); } }; export default { createIfMobile: init };
Use Device.js to determine mobile editor use
Use Device.js to determine mobile editor use Ref #2570 - Adds new library, device.js to determine if the user is on an ios mobile or tablet.
JavaScript
mit
TryGhost/Ghost,TryGhost/Ghost,TryGhost/Ghost
--- +++ @@ -1,4 +1,4 @@ -/*global CodeMirror*/ +/*global CodeMirror, device*/ import mobileUtils from 'ghost/utils/mobile-utils'; import createTouchEditor from 'ghost/assets/lib/touch-editor'; @@ -24,7 +24,9 @@ }; init = function init() { - if (mobileUtils.hasTouchScreen()) { + //Codemirror does not function on mobile devices, + // nor on any iDevice. + if (device.mobile() || (device.tablet() && device.ios())) { $('body').addClass('touch-editor'); // make editor tabs touch-to-toggle in portrait mode
b7491beeae4340a1d73d484c0b7671bb2f682edd
src/services/helpers/scopePermissions/ScopeMembersService.js
src/services/helpers/scopePermissions/ScopeMembersService.js
const auth = require('@feathersjs/authentication'); const globalHooks = require('../../../hooks'); const { ScopeService } = require('./ScopeService'); const { lookupScope, checkScopePermissions } = require('./hooks'); /** * Implements retrieving a list of all users who are associated with a scope. * @class ScopeMembersService * @extends {ScopeService} */ class ScopeMembersService extends ScopeService { /** * Custom set of hooks. * @static * @returns Object<FeathersHooksCollection> * @override ScopeService#hooks * @memberof ScopeMembersService */ static hooks() { return { before: { all: [ globalHooks.ifNotLocal(auth.hooks.authenticate('jwt')), lookupScope, checkScopePermissions(['SCOPE_PERMISSIONS_VIEW']), ], }, }; } /** * Implements the route * @param {Object} params Feathers request params * @returns {Array<ObjectId>} a list of userIds * @memberof ScopeMembersService */ async find(params) { const members = await this.handler.apply(this, [params]) || []; return members; } } module.exports = { ScopeMembersService, };
const auth = require('@feathersjs/authentication'); const globalHooks = require('../../../hooks'); const { ScopeService } = require('./ScopeService'); const { lookupScope, checkScopePermissions } = require('./hooks'); /** * Implements retrieving a list of all users who are associated with a scope. * @class ScopeMembersService * @extends {ScopeService} */ class ScopeMembersService extends ScopeService { /** * Custom set of hooks. * @static * @returns Object<FeathersHooksCollection> * @override ScopeService#hooks * @memberof ScopeMembersService */ static hooks() { return { before: { all: [ globalHooks.ifNotLocal(auth.hooks.authenticate('jwt')), lookupScope, globalHooks.ifNotLocal(checkScopePermissions(['SCOPE_PERMISSIONS_VIEW'])), ], }, }; } /** * Implements the route * @param {Object} params Feathers request params * @returns {Array<ObjectId>} a list of userIds * @memberof ScopeMembersService */ async find(params) { const members = await this.handler.apply(this, [params]) || []; return members; } } module.exports = { ScopeMembersService, };
Check for permission only in external calls
Check for permission only in external calls
JavaScript
agpl-3.0
schul-cloud/schulcloud-server,schul-cloud/schulcloud-server,schul-cloud/schulcloud-server
--- +++ @@ -22,7 +22,7 @@ all: [ globalHooks.ifNotLocal(auth.hooks.authenticate('jwt')), lookupScope, - checkScopePermissions(['SCOPE_PERMISSIONS_VIEW']), + globalHooks.ifNotLocal(checkScopePermissions(['SCOPE_PERMISSIONS_VIEW'])), ], }, };
63b38bdb6b304d495ed17ae2defa1f7512491c5c
aritgeo/src/aritgeo.js
aritgeo/src/aritgeo.js
'use strict' module.exports = { aritGeo: function(numlist) { if (!Array.isArray(numlist)) { return null; } if (numlist.length === 0) { return 0; } if (numlist.length === 1 || numlist.length === 2) { return -1; } } }
'use strict' module.exports = { aritGeo: function(numlist) { if (!Array.isArray(numlist)) { return null; } if (numlist.length === 0) { return 0; } if (numlist.length === 1 || numlist.length === 2) { return -1; } if (module.compute.isArithmetic(numlist.slice(1), numlist[1] - numlist[0])) { return 'Arithmetic'; } } } module.compute = { isArithmetic: function(numlist, diff) { if (numlist[1] - numlist[0] === diff) { if (numlist.length === 2) { return true; } else return true && this.isArithmetic(numlist.slice(1), numlist[1] - numlist[0]); } else return false; } }
Implement case for arithmetic sequences
Implement case for arithmetic sequences
JavaScript
mit
princess-essien/andela-bootcamp-slc
--- +++ @@ -13,5 +13,19 @@ if (numlist.length === 1 || numlist.length === 2) { return -1; } + + if (module.compute.isArithmetic(numlist.slice(1), numlist[1] - numlist[0])) { + return 'Arithmetic'; + } } } + +module.compute = { + isArithmetic: function(numlist, diff) { + if (numlist[1] - numlist[0] === diff) { + if (numlist.length === 2) { + return true; + } else return true && this.isArithmetic(numlist.slice(1), numlist[1] - numlist[0]); + } else return false; + } +}
4471d6844864cb28e5ddd883781b690a48490089
public/app.js
public/app.js
/* jslint node: true */ 'use strict'; var AUTHORIZED_URLS = [ '/index.html' ]; var HOST = '0.0.0.0'; var PORT = 9917; function handleIo(socket) { socket.on('slide-update', function(msg) { socket.broadcast.emit("slide-update", msg); }); } function handleHTTP(req, res) { var path = url.parse(req.url).pathname; switch(path) { case '/': res.writeHeader(200, {'Content-Type': 'text/html'}); res.end('Hello'); break; case '/index.html': fs.readFile(__dirname + path, function(error, data) { if (error) { res.writeHeader(404); res.end('foo oops, this doesn\'t exist - 404'); } else { res.writeHeader(200, {'Content-Type': 'text/html'}); res.end(data, 'utf8'); } }); break; default: res.writeHeader(404); res.end('oops, this doesn\'t exist - 404'); break; } } var http = require('http'); var url = require('url'); var fs = require('fs'); var server = http.createServer(handleHTTP); server.listen(PORT, HOST); var io = require('socket.io')(server); io.on('connection', handleIo);
/* jslint node: true */ 'use strict'; var AUTHORIZED_URLS = [ '/index.html' ]; var HOST = '0.0.0.0'; var PORT = 9917; function handleIo(socket) { socket.on('slide-update', function(msg) { socket.broadcast.emit("slide-update", msg); }); } function handleHTTP(req, res) { var path = url.parse(req.url).pathname; switch(path) { case '/': fs.readFile(__dirname + '/index.html', function(error, data) { if (error) { res.writeHeader(404); res.end('foo oops, this doesn\'t exist - 404'); } else { res.writeHeader(200, {'Content-Type': 'text/html'}); res.end(data, 'utf8'); } }); break; default: res.writeHeader(404); res.end('oops, this doesn\'t exist - 404'); break; } } var http = require('http'); var url = require('url'); var fs = require('fs'); var server = http.createServer(handleHTTP); server.listen(PORT, HOST); var io = require('socket.io')(server); io.on('connection', handleIo);
Update router to default to slide control
Update router to default to slide control
JavaScript
mit
mbasanta/bespoke-remote-server,mbasanta/bespoke-remote-server
--- +++ @@ -18,11 +18,7 @@ switch(path) { case '/': - res.writeHeader(200, {'Content-Type': 'text/html'}); - res.end('Hello'); - break; - case '/index.html': - fs.readFile(__dirname + path, function(error, data) { + fs.readFile(__dirname + '/index.html', function(error, data) { if (error) { res.writeHeader(404); res.end('foo oops, this doesn\'t exist - 404');
295add674f07390b71c89ad59229c6d17fec879f
src/js/components/User.js
src/js/components/User.js
import React, { PropTypes, Component } from 'react'; import { IMAGES_ROOT } from '../constants/Constants'; import shouldPureComponentUpdate from 'react-pure-render/function'; import selectn from 'selectn'; export default class User extends Component { static propTypes = { user: PropTypes.object.isRequired }; shouldComponentUpdate = shouldPureComponentUpdate; render() { const { user, profile } = this.props; let imgSrc = user.picture ? `${IMAGES_ROOT}media/cache/user_avatar_180x180/user/images/${user.picture}` : `${IMAGES_ROOT}media/cache/user_avatar_180x180/bundles/qnoowweb/images/user-no-img.jpg`; return ( <div className="User"> <div className="content-block user-block"> <div className="user-image"> <img src={imgSrc} /> </div> <div className="user-data"> <div className="user-username title"> {user.username} </div> <div className="user-location"> {/** TODO: For some reason, profile is different for different renders. This is a temporal fix */} <span className="icon-marker"></span> {selectn('Location', profile) || selectn('location.locality', profile) || ''} </div> </div> </div> </div> ); } }
import React, { PropTypes, Component } from 'react'; import { IMAGES_ROOT } from '../constants/Constants'; import shouldPureComponentUpdate from 'react-pure-render/function'; import selectn from 'selectn'; export default class User extends Component { static propTypes = { user: PropTypes.object.isRequired }; shouldComponentUpdate = shouldPureComponentUpdate; render() { const { user, profile } = this.props; let imgSrc = user.picture ? `${IMAGES_ROOT}media/cache/user_avatar_180x180/user/images/${user.picture}` : `${IMAGES_ROOT}media/cache/user_avatar_180x180/bundles/qnoowweb/images/user-no-img.jpg`; return ( <div className="User"> <div className="content-block user-block"> <div className="user-image"> <img src={imgSrc} /> </div> <div className="user-data"> <div className="user-username title"> {user.username} </div> <div className="user-location"> {/** TODO: For some reason, profile is different for different renders. This is a temporal fix */} <span className="icon-marker"></span> {selectn('Location', profile) || selectn('location.locality', profile) || selectn('location.address', profile) || ''} </div> </div> </div> </div> ); } }
Use address when there is no location
Use address when there is no location
JavaScript
agpl-3.0
nekuno/client,nekuno/client
--- +++ @@ -25,7 +25,7 @@ </div> <div className="user-location"> {/** TODO: For some reason, profile is different for different renders. This is a temporal fix */} - <span className="icon-marker"></span> {selectn('Location', profile) || selectn('location.locality', profile) || ''} + <span className="icon-marker"></span> {selectn('Location', profile) || selectn('location.locality', profile) || selectn('location.address', profile) || ''} </div> </div> </div>
a8e892e298630309646cd9f6f3862d17c680f80d
app/scripts/utils.js
app/scripts/utils.js
'use strict'; (function() { angular.module('ncsaas') .factory('ncUtilsFlash', ['Flash', ncUtilsFlash]); function ncUtilsFlash(Flash) { return { success: function(message) { this.flashMessage('success', message); }, error: function(message) { this.flashMessage('danger', message); }, info: function(message) { this.flashMessage('info', message); }, warning: function(message) { this.flashMessage('warning', message); }, flashMessage: function(type, message) { Flash.create(type, message); } }; } angular.module('ncsaas') .factory('ncUtils', ['$rootScope', 'blockUI', ncUtils]); function ncUtils($rootScope, blockUI) { return { deregisterEvent: function(eventName) { $rootScope.$$listeners[eventName] = []; }, updateIntercom: function() { window.Intercom('update'); }, blockElement: function(element, promise) { var block = blockUI.instances.get(element); block.start(); promise.finally(function() { block.stop(); }); } } } })();
'use strict'; (function() { angular.module('ncsaas') .factory('ncUtilsFlash', ['Flash', ncUtilsFlash]); function ncUtilsFlash(Flash) { return { success: function(message) { this.flashMessage('success', message); }, error: function(message) { this.flashMessage('danger', message); }, info: function(message) { this.flashMessage('info', message); }, warning: function(message) { this.flashMessage('warning', message); }, flashMessage: function(type, message) { if (message) { Flash.create(type, message); } } }; } angular.module('ncsaas') .factory('ncUtils', ['$rootScope', 'blockUI', ncUtils]); function ncUtils($rootScope, blockUI) { return { deregisterEvent: function(eventName) { $rootScope.$$listeners[eventName] = []; }, updateIntercom: function() { window.Intercom('update'); }, blockElement: function(element, promise) { var block = blockUI.instances.get(element); block.start(); promise.finally(function() { block.stop(); }); } } } })();
Add check for message exist in ncUtilsFlash.flashMessage (SAAS-822)
Add check for message exist in ncUtilsFlash.flashMessage (SAAS-822) Added condition for ncUtilsFlash.flashMessage function.
JavaScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -20,7 +20,9 @@ this.flashMessage('warning', message); }, flashMessage: function(type, message) { - Flash.create(type, message); + if (message) { + Flash.create(type, message); + } } }; }
80dbd6b199ab4a8a014150731303d31e7f7ba529
lib/factory-boy.js
lib/factory-boy.js
FactoryBoy = {}; FactoryBoy._factories = []; Factory = function (name, collection, attributes) { this.name = name; this.collection = collection; this.attributes = attributes; }; FactoryBoy.define = function (name, collection, attributes) { var factory = new Factory(name, collection, attributes); FactoryBoy._factories.push(factory); }; FactoryBoy._getFactory = function (name) { return _.findWhere(FactoryBoy._factories, {name: name}); }; FactoryBoy.create = function (name, newAttr) { var factory = this._getFactory(name); var collection = factory.collection; var deepExtend = Npm.require('deep-extend'); // Allow to overwrite the attribute definitions var attr = deepExtend(factory.attributes, newAttr); var docId = collection.insert(attr); var doc = collection.findOne(docId); return doc; }; FactoryBoy.build = function (name, collection, attrOverwrite) { var factory = this._getFactory(name); return factory.attributes; };
FactoryBoy = {}; FactoryBoy._factories = []; Factory = function (name, collection, attributes) { this.name = name; this.collection = collection; this.attributes = attributes; }; FactoryBoy.define = function (name, collection, attributes) { var factory = new Factory(name, collection, attributes); FactoryBoy._factories.push(factory); }; FactoryBoy._getFactory = function (name) { var factory = _.findWhere(FactoryBoy._factories, {name: name}); if (! factory) { throw new Error('Could not find the factory by that name'); } return factory; }; FactoryBoy.create = function (name, newAttr) { var factory = this._getFactory(name); var collection = factory.collection; var deepExtend = Npm.require('deep-extend'); // Allow to overwrite the attribute definitions var attr = deepExtend(factory.attributes, newAttr); var docId = collection.insert(attr); var doc = collection.findOne(docId); return doc; }; FactoryBoy.build = function (name, collection, attrOverwrite) { var factory = this._getFactory(name); return factory.attributes; };
Throw error if factory is not found
Throw error if factory is not found
JavaScript
mit
sungwoncho/factory-boy
--- +++ @@ -14,7 +14,13 @@ }; FactoryBoy._getFactory = function (name) { - return _.findWhere(FactoryBoy._factories, {name: name}); + var factory = _.findWhere(FactoryBoy._factories, {name: name}); + + if (! factory) { + throw new Error('Could not find the factory by that name'); + } + + return factory; }; FactoryBoy.create = function (name, newAttr) {