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
cbcd01ba33d3d8b4408d97ddbe3aa80eb22984dc
src/inject/inject.js
src/inject/inject.js
chrome.extension.sendMessage({}, function(response) { var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); var labels = document.getElementsByClassName('label'); Array.prototype.filter.call(labels, function(label) { return label.textContent.indexOf('blocked') === 0; }).forEach(function(label) { label.style.color = 'rgb(199, 37, 67)'; }); } }, 4000); });
chrome.extension.sendMessage({}, function(response) { var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); var colorMapping = { 'blocked': 'rgb(199, 37, 67)', 'needs ': 'rgb(199, 37, 67)' }; function colorLabelNodes(labels) { Object.keys(colorMapping).forEach(function(labelKeyword) { Array.prototype.filter.call(labels, function(label) { return label.textContent.indexOf(labelKeyword) === 0 }).forEach(function(label) { label.style.color = colorMapping[labelKeyword]; }); }); } var observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { Array.prototype.forEach.call(mutation.addedNodes, function(addedNode) { if (typeof addedNode.getElementsByClassName !== 'undefined') { var labels = addedNode.getElementsByClassName('label'); colorLabelNodes(labels); } }); }); }); // configuration of the observer: var config = { childList: true, subtree: true }; observer.observe(document, config); } }, 10); });
Set color on all newly-added labels
Set color on all newly-added labels
JavaScript
isc
oliverswitzer/wwltw-for-pivotal-tracker,mkenyon/red-labels-for-pivotal-tracker,oliverswitzer/wwltw-for-pivotal-tracker
--- +++ @@ -1,14 +1,38 @@ chrome.extension.sendMessage({}, function(response) { - var readyStateCheckInterval = setInterval(function() { - if (document.readyState === "complete") { - clearInterval(readyStateCheckInterval); + var readyStateCheckInterval = setInterval(function() { + if (document.readyState === "complete") { + clearInterval(readyStateCheckInterval); - var labels = document.getElementsByClassName('label'); - Array.prototype.filter.call(labels, function(label) { - return label.textContent.indexOf('blocked') === 0; - }).forEach(function(label) { - label.style.color = 'rgb(199, 37, 67)'; - }); - } - }, 4000); + var colorMapping = { + 'blocked': 'rgb(199, 37, 67)', + 'needs ': 'rgb(199, 37, 67)' + }; + + function colorLabelNodes(labels) { + Object.keys(colorMapping).forEach(function(labelKeyword) { + Array.prototype.filter.call(labels, function(label) { + return label.textContent.indexOf(labelKeyword) === 0 + }).forEach(function(label) { + label.style.color = colorMapping[labelKeyword]; + }); + }); + } + + var observer = new MutationObserver(function (mutations) { + mutations.forEach(function (mutation) { + Array.prototype.forEach.call(mutation.addedNodes, function(addedNode) { + if (typeof addedNode.getElementsByClassName !== 'undefined') { + var labels = addedNode.getElementsByClassName('label'); + colorLabelNodes(labels); + } + }); + }); + }); + + // configuration of the observer: + var config = { childList: true, subtree: true }; + + observer.observe(document, config); + } + }, 10); });
46962ed201abf4e701fb069c02ab1a1751464857
information.js
information.js
'use strict'; var hosts = { 'bbc.co.uk': 'bbc', 'm.bbc.co.uk': 'bbc', 'reddit.com': 'reddit', 'www.reddit.com': 'reddit', 'condenast.co.uk': 'condenast' }; var organisations = { 'bbc': { 'owner': null, 'info': 'British Broadcasting Corporation' }, 'reddit': { 'owner': 'condenast', 'info': 'Reddit' }, 'condenast': { 'owner': 'advancepublications', 'info': 'Condé Nast' }, 'advancepublications': { 'owner': null, 'info': 'Advance Publications' } }; function getInfoString (organisationKey) { var infoString = ''; for (;;) { var organisation = organisations[organisationKey]; console.log(organisation); if (!organisation) { return infoString; } if (infoString.length) { infoString += " -> "; } infoString += organisation.info; organisationKey = organisation.owner; } }; module.exports = { getInfo: function (host) { console.log(host); var siteKey = hosts[host]; return getInfoString(siteKey); } };
'use strict'; var hosts = { 'bbc.co.uk': 'bbc', 'm.bbc.co.uk': 'bbc', 'reddit.com': 'reddit', 'www.reddit.com': 'reddit', 'condenast.co.uk': 'condenast' 'tumblr.com' : 'tumblr' }; var organisations = { 'bbc': { 'owner': null, 'info': 'British Broadcasting Corporation' }, 'reddit': { 'owner': 'condenast', 'info': 'Reddit' }, 'condenast': { 'owner': 'advancepublications', 'info': 'Condé Nast' }, 'advancepublications': { 'owner': null, 'info': 'Advance Publications' }, 'tumblr': { 'owner': 'yahoo', 'info': 'Tumblr' }, 'yahoo': { 'owner': null, 'info': 'Yahoo' } }; function getInfoString (organisationKey) { var infoString = ''; for (;;) { var organisation = organisations[organisationKey]; console.log(organisation); if (!organisation) { return infoString; } if (infoString.length) { infoString += " -> "; } infoString += organisation.info; organisationKey = organisation.owner; } }; module.exports = { getInfo: function (host) { console.log(host); var siteKey = hosts[host]; return getInfoString(siteKey); } };
Add tumblr->yahoo info for server
Add tumblr->yahoo info for server
JavaScript
mit
magicmark/Transparification-Server
--- +++ @@ -6,6 +6,7 @@ 'reddit.com': 'reddit', 'www.reddit.com': 'reddit', 'condenast.co.uk': 'condenast' + 'tumblr.com' : 'tumblr' }; var organisations = { @@ -24,6 +25,14 @@ 'advancepublications': { 'owner': null, 'info': 'Advance Publications' + }, + 'tumblr': { + 'owner': 'yahoo', + 'info': 'Tumblr' + }, + 'yahoo': { + 'owner': null, + 'info': 'Yahoo' } };
144eba59227a600aec09ab549c0be840698d191a
src/js/utils/_base-view.js
src/js/utils/_base-view.js
import * as _ from 'underscore'; import * as Backbone from 'backbone'; class BaseView extends Backbone.View { constructor(options = {}) { super(options); this._subviews = null; } registerSubView(view) { this._subviews = this._subviews || []; this._subviews.push(view); } remove() { _.invoke(this._subviews, 'remove'); Backbone.View.prototype.remove.call(this); } } export default BaseView;
import * as _ from 'underscore'; import * as Backbone from 'backbone'; class BaseView extends Backbone.View { constructor(options = {}) { super(options); this._subviews = null; } assign(view, selector) { view.setElement(this.$(selector)).render(); } registerSubView(view) { this._subviews = this._subviews || []; this._subviews.push(view); } remove() { _.invoke(this._subviews, 'remove'); Backbone.View.prototype.remove.call(this); } } export default BaseView;
Update base view w/convenience function for rendering subviews
Update base view w/convenience function for rendering subviews See: http://ianstormtaylor.com/rendering-views-in-backbonejs-isnt-always-simp le/
JavaScript
mit
trevormunoz/katherine-anne,trevormunoz/katherine-anne,trevormunoz/katherine-anne
--- +++ @@ -6,6 +6,10 @@ constructor(options = {}) { super(options); this._subviews = null; + } + + assign(view, selector) { + view.setElement(this.$(selector)).render(); } registerSubView(view) {
6dd03089f29ae7cd357f45a929bed8f7e7d6440b
src/input/storageHandler.js
src/input/storageHandler.js
'use strict' // Code thanks to MDN export function storageAvailable (type) { try { let storage = window[type] let x = '__storage_test__' storage.setItem(x, x) storage.removeItem(x) return true } catch (e) { let storage = window[type] return e instanceof DOMException && ( // everything except Firefox e.code === 22 || // Firefox e.code === 1014 || // test name field too, because code might not be present // everything except Firefox e.name === 'QuotaExceededError' || // Firefox e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && // acknowledge QuotaExceededError only if there's something already stored storage.length !== 0 } } export function storagePopulated () { if (window.localStorage.length !== 0) { console.log('populated') return true } } export function populateStorage () { window.localStorage.setItem('pomodoroTime', document.getElementById('pomodoroInput').value) window.localStorage.setItem('shortBreakTime', document.getElementById('shortBreakInput').value) window.localStorage.setItem('longBreakTime', document.getElementById('longBreakInput').value) }
'use strict' // Code thanks to MDN export function storageAvailable (type) { try { let storage = window[type] let x = '__storage_test__' storage.setItem(x, x) storage.removeItem(x) return true } catch (e) { let storage = window[type] return e instanceof DOMException && ( // everything except Firefox e.code === 22 || // Firefox e.code === 1014 || // test name field too, because code might not be present // everything except Firefox e.name === 'QuotaExceededError' || // Firefox e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && // acknowledge QuotaExceededError only if there's something already stored storage.length !== 0 } } export function storagePopulated () { if (window.localStorage.length !== 0) { console.log('populated') return true } } export function populateStorage () { window.localStorage.setItem('pomodoroTime', document.getElementById('pomodoroInput').value) window.localStorage.setItem('shortBreakTime', document.getElementById('shortBreakInput').value) window.localStorage.setItem('longBreakTime', document.getElementById('longBreakInput').value) window.localStorage.setItem('alarmDropdown', document.getElementById('alarmDropdown').value) window.localStorage.setItem('ticking', document.getElementById('tickToggle').checked) window.localStorage.setItem('storageToggle', document.getElementById('storageToggle').checked) }
Add all settings to populateStorage
Add all settings to populateStorage
JavaScript
mit
CrowsVeldt/FreeCodeCamp-Pomodoro-Timer
--- +++ @@ -36,4 +36,7 @@ window.localStorage.setItem('pomodoroTime', document.getElementById('pomodoroInput').value) window.localStorage.setItem('shortBreakTime', document.getElementById('shortBreakInput').value) window.localStorage.setItem('longBreakTime', document.getElementById('longBreakInput').value) + window.localStorage.setItem('alarmDropdown', document.getElementById('alarmDropdown').value) + window.localStorage.setItem('ticking', document.getElementById('tickToggle').checked) + window.localStorage.setItem('storageToggle', document.getElementById('storageToggle').checked) }
ccce0d08bd0a43ba10a5b18470095b0c19bfe18c
webpack.client.babel.js
webpack.client.babel.js
import base from './webpack.base.babel.js'; import path from 'path'; import webpack from 'webpack'; const {WDS_PORT, PORT, APP_WEB_BASE_PATH} = process.env; export default { ...base, entry: "./src/app/_client.js", output: { path: path.join(__dirname, 'dist', 'static'), filename: "app.js", publicPath: `${APP_WEB_BASE_PATH}/` }, plugins: base.plugins .concat(process.env.NODE_ENV==="production" ? [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }) ] : [] ), devServer: { publicPath: `${APP_WEB_BASE_PATH}/static`, contentBase: `http://localhost:${PORT}/static`, historyApiFallback: true, progress: false, stats: 'errors-only', compress: true, port: WDS_PORT, proxy: { "*": `http://localhost:${PORT}` } } };
import base from './webpack.base.babel.js'; import path from 'path'; import webpack from 'webpack'; const {WDS_PORT, PORT, APP_WEB_BASE_PATH} = process.env; export default { ...base, entry: "./src/app/_client.js", output: { path: path.join(__dirname, 'dist', 'static'), filename: "app.js", publicPath: `${APP_WEB_BASE_PATH}/` }, plugins: base.plugins .concat(process.env.NODE_ENV==="production" ? [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }) ] : [] ), devServer: { publicPath: '/static/', contentBase: `http://localhost:${PORT}/static`, historyApiFallback: true, progress: false, stats: 'errors-only', compress: true, port: WDS_PORT, proxy: { "**": `http://localhost:${PORT}` } } };
Fix dev server redirection bug
Fix dev server redirection bug When running `npm run dev` and opening the browser, newer version of WDS would redirect to the proxied server instead of proxying. Changed proxy syntax to match `**` instead of `*`
JavaScript
mit
mdjasper/React-Reading-List,tuxsudo/react-starter
--- +++ @@ -28,7 +28,7 @@ ), devServer: { - publicPath: `${APP_WEB_BASE_PATH}/static`, + publicPath: '/static/', contentBase: `http://localhost:${PORT}/static`, historyApiFallback: true, progress: false, @@ -36,7 +36,7 @@ compress: true, port: WDS_PORT, proxy: { - "*": `http://localhost:${PORT}` + "**": `http://localhost:${PORT}` } }
dc731a64f204251143021cdc663ddaea195f3908
lib/web/scripts/IdleView.js
lib/web/scripts/IdleView.js
const Marionette = require('backbone.marionette'); const moment = require('moment'); module.exports = class IdleView extends Marionette.View { template = Templates['idle']; className() { return 'idle-content'; } events() { return {'click': 'hide'}; } onRender() { this.timeRefresh = setInterval(this.render.bind(this), 10000); } serializeData() { const now = moment(); return { time: now.format('h:mm'), ampm: now.format('a'), day: now.format('dddd'), date: now.format('MMM Do, Y') }; } hide() { this.trigger('hide'); } onDestroy() { clearInterval(this.timeRefresh); } }
const Marionette = require('backbone.marionette'); const moment = require('moment'); module.exports = class IdleView extends Marionette.View { template = Templates['idle']; className() { return 'idle-content'; } events() { return {'click': 'hide'}; } initialize() { this.timeRefresh = setInterval(this.render.bind(this), 10000); } serializeData() { const now = moment(); return { time: now.format('h:mm'), ampm: now.format('a'), day: now.format('dddd'), date: now.format('MMM Do, Y') }; } hide() { this.trigger('hide'); } onDestroy() { clearInterval(this.timeRefresh); } }
Fix extremely stupid bug in idle display!
Fix extremely stupid bug in idle display!
JavaScript
mit
monitron/jarvis-ha,monitron/jarvis-ha
--- +++ @@ -11,7 +11,7 @@ return {'click': 'hide'}; } - onRender() { + initialize() { this.timeRefresh = setInterval(this.render.bind(this), 10000); }
ba816550e509def9d0d4f3f6d500b80402b0a5c2
routes/index.js
routes/index.js
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'VoteAnon' }); }); router.route('/create') .get(function(req, res) { res.render('create', { title: 'VoteAnon: create poll' }); }) .post(function(req, res) { res.render('confirm_create', { title: 'VoteAnon: poll created' }); }); module.exports = router;
var express = require('express'); var redis = require('redis'); var router = express.Router(); var client = redis.createClient(); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'VoteAnon' }); }); router.route('/create') .get(function(req, res) { res.render('create', { title: 'VoteAnon: create poll' }); }) .post(function(req, res) { res.render('confirm_create', { title: 'VoteAnon: poll created' }); }); module.exports = router;
Connect to redis on route
Connect to redis on route
JavaScript
mit
Pringley/voteanon
--- +++ @@ -1,5 +1,8 @@ var express = require('express'); +var redis = require('redis'); + var router = express.Router(); +var client = redis.createClient(); /* GET home page. */ router.get('/', function(req, res) {
8a12e4a209c262d5ad446d99a81cd8936a353ab4
make-event.js
make-event.js
'use strict'; let fs = require('fs'); let moment = require('moment'); let parseDate = require('./parse-date'); function maybeParse(value) { if(value[0] === '@') { return moment(parseDate(value.slice(1))).format('YYYY-MM-DD HH-mm-ss'); } try { return JSON.parse(value); } catch(error) { if(value.indexOf(',') !== -1) { return value.split(',').map(maybeParse); } else { return value; } } } module.exports = function(args) { let dateTime = moment().format('YYYY-MM-DD HH-mm-ss'); let event = {}; event.type = args[0]; args.slice(1).forEach(function(arg) { var keyValue = /^([^:]+):(.+)$/.exec(arg); if(keyValue) { event[keyValue[1]] = maybeParse(keyValue[2]); } else { event.positionals = event.positionals || []; event.positionals.push(maybeParse(arg)); } }); fs.writeFileSync(dateTime + '.json', JSON.stringify(event, null, 4)); };
'use strict'; let fs = require('fs'); let moment = require('moment'); let parseDate = require('./parse-date'); function maybeParse(value) { if(value[0] === '@') { return moment(parseDate(value.slice(1))).format('YYYY-MM-DD HH-mm-ss'); } try { return JSON.parse(value); } catch(error) { if(value.indexOf(',') !== -1) { return value.split(',').map(maybeParse); } else { return value; } } } module.exports = function(args) { let event = {}; event.type = args.shift(); let dateTime = (function() { let dateTime = parseDate(args[0]); if(dateTime) { dateTime = moment(dateTime); args.shift(); } else { dateTime = moment(); } return dateTime; })(); args.forEach(function(arg) { var keyValue = /^([^:]+):(.+)$/.exec(arg); if(keyValue) { event[keyValue[1]] = maybeParse(keyValue[2]); } else { event.positionals = event.positionals || []; event.positionals.push(maybeParse(arg)); } }); fs.writeFileSync( dateTime.format('YYYY-MM-DD HH-mm-ss') + '.json', JSON.stringify(event, null, 4) ); };
Allow event date to be overridden.
Allow event date to be overridden.
JavaScript
agpl-3.0
n2liquid/ev
--- +++ @@ -23,12 +23,25 @@ } module.exports = function(args) { - let dateTime = moment().format('YYYY-MM-DD HH-mm-ss'); let event = {}; - event.type = args[0]; + event.type = args.shift(); - args.slice(1).forEach(function(arg) { + let dateTime = (function() { + let dateTime = parseDate(args[0]); + + if(dateTime) { + dateTime = moment(dateTime); + args.shift(); + } + else { + dateTime = moment(); + } + + return dateTime; + })(); + + args.forEach(function(arg) { var keyValue = /^([^:]+):(.+)$/.exec(arg); if(keyValue) { @@ -40,5 +53,8 @@ } }); - fs.writeFileSync(dateTime + '.json', JSON.stringify(event, null, 4)); + fs.writeFileSync( + dateTime.format('YYYY-MM-DD HH-mm-ss') + '.json', + JSON.stringify(event, null, 4) + ); };
baa2562e6410e491b9e094ff6b0900fe5ea23d7d
ember/tests/acceptance/page-not-found-test.js
ember/tests/acceptance/page-not-found-test.js
import { module, test } from 'qunit'; import { setupApplicationTest } from 'ember-qunit'; import { visit, currentURL } from '@ember/test-helpers'; import { setupPretender } from 'skylines/tests/helpers/setup-pretender'; module('Acceptance | page-not-found', function(hooks) { setupApplicationTest(hooks); setupPretender(hooks); hooks.beforeEach(async function() { await visit('/foobar'); }); test('will keep the URL at /foobar', function(assert) { assert.equal(currentURL(), '/foobar'); }); test('will show "Page not found" error message', function(assert) { assert.dom('.page-header').containsText('Page not found'); }); });
import { module, test } from 'qunit'; import { setupApplicationTest } from 'ember-qunit'; import { visit, currentURL } from '@ember/test-helpers'; import { setupPolly } from 'skylines/tests/helpers/setup-polly'; module('Acceptance | page-not-found', function(hooks) { setupApplicationTest(hooks); setupPolly(hooks, { recordIfMissing: false }); hooks.beforeEach(async function() { await visit('/foobar'); }); test('will keep the URL at /foobar', function(assert) { assert.equal(currentURL(), '/foobar'); }); test('will show "Page not found" error message', function(assert) { assert.dom('.page-header').containsText('Page not found'); }); });
Use Polly.js instead of Pretender
tests/page-not-found: Use Polly.js instead of Pretender
JavaScript
agpl-3.0
RBE-Avionik/skylines,Turbo87/skylines,RBE-Avionik/skylines,Harry-R/skylines,RBE-Avionik/skylines,skylines-project/skylines,Harry-R/skylines,Harry-R/skylines,RBE-Avionik/skylines,Turbo87/skylines,Turbo87/skylines,skylines-project/skylines,skylines-project/skylines,skylines-project/skylines,Harry-R/skylines,Turbo87/skylines
--- +++ @@ -2,11 +2,11 @@ import { setupApplicationTest } from 'ember-qunit'; import { visit, currentURL } from '@ember/test-helpers'; -import { setupPretender } from 'skylines/tests/helpers/setup-pretender'; +import { setupPolly } from 'skylines/tests/helpers/setup-polly'; module('Acceptance | page-not-found', function(hooks) { setupApplicationTest(hooks); - setupPretender(hooks); + setupPolly(hooks, { recordIfMissing: false }); hooks.beforeEach(async function() { await visit('/foobar');
430d0dd3530c83907f9867454fdd3781b05835c9
webpack_config/server/webpack.prod.babel.js
webpack_config/server/webpack.prod.babel.js
import webpack from 'webpack' import baseWebpackConfig from './webpack.base' import UglifyJSPlugin from 'uglifyjs-webpack-plugin' import {BundleAnalyzerPlugin} from 'webpack-bundle-analyzer' import {Plugin as ShakePlugin} from 'webpack-common-shake' import OptimizeJsPlugin from 'optimize-js-plugin' const plugins = [ new webpack.ProgressPlugin(), new webpack.optimize.ModuleConcatenationPlugin(), new ShakePlugin(), // NOTE: you can use BabiliPlugin as an alternative to UglifyJSPlugin // new BabiliPlugin(), new UglifyJSPlugin({ sourceMap: true, compress: { warnings: false, unused: true, dead_code: true // This option removes console.log in production // drop_console: true }, output: { comments: false } }), new OptimizeJsPlugin({ sourceMap: true }) ] // Do you want to use bundle analyzer? if (process.env.ANALYZE_BUNDLE) { plugins.push(new BundleAnalyzerPlugin({analyzerMode: 'static'})) } export default Object.assign({}, baseWebpackConfig, { plugins: baseWebpackConfig.plugins.concat(plugins) })
import webpack from 'webpack' import baseWebpackConfig from './webpack.base' import UglifyJSPlugin from 'uglifyjs-webpack-plugin' import {BundleAnalyzerPlugin} from 'webpack-bundle-analyzer' import {Plugin as ShakePlugin} from 'webpack-common-shake' import OptimizeJsPlugin from 'optimize-js-plugin' const analyzePlugins = process.env.ANALYZE_BUNDLE ? [new BundleAnalyzerPlugin({analyzerMode: 'static'})] : [] const plugins = [ new webpack.ProgressPlugin(), new webpack.optimize.ModuleConcatenationPlugin(), new ShakePlugin(), // NOTE: you can use BabiliPlugin as an alternative to UglifyJSPlugin // new BabiliPlugin(), new UglifyJSPlugin({ sourceMap: true, compress: { warnings: false, unused: true, dead_code: true // This option removes console.log in production // drop_console: true }, output: { comments: false } }), new OptimizeJsPlugin({ sourceMap: true }), ...analyzePlugins ] export default Object.assign({}, baseWebpackConfig, { plugins: baseWebpackConfig.plugins.concat(plugins) })
Revert "Revert "style(webpack_config/server): rewrite prod conf in functional style""
Revert "Revert "style(webpack_config/server): rewrite prod conf in functional style"" This reverts commit e9de3d6da5e3cfc03b6d5e39fe92ede9c110d712.
JavaScript
apache-2.0
Metnew/react-semantic.ui-starter
--- +++ @@ -5,6 +5,9 @@ import {Plugin as ShakePlugin} from 'webpack-common-shake' import OptimizeJsPlugin from 'optimize-js-plugin' +const analyzePlugins = process.env.ANALYZE_BUNDLE + ? [new BundleAnalyzerPlugin({analyzerMode: 'static'})] + : [] const plugins = [ new webpack.ProgressPlugin(), new webpack.optimize.ModuleConcatenationPlugin(), @@ -26,13 +29,9 @@ }), new OptimizeJsPlugin({ sourceMap: true - }) + }), + ...analyzePlugins ] - -// Do you want to use bundle analyzer? -if (process.env.ANALYZE_BUNDLE) { - plugins.push(new BundleAnalyzerPlugin({analyzerMode: 'static'})) -} export default Object.assign({}, baseWebpackConfig, { plugins: baseWebpackConfig.plugins.concat(plugins)
003259602f03821ff6049914d66ecb77692badc2
tests/mocks/streams/mock-hot-collections.js
tests/mocks/streams/mock-hot-collections.js
define([ 'inherits', 'streamhub-hot-collections/streams/hot-collections', 'streamhub-hot-collections-tests/mocks/clients/mock-hot-collections-client'], function (inherits, HotCollections, MockHotCollectionsClient) { var MockHotCollections = function (opts) { opts = opts || {}; opts.client = opts.client || new MockHotCollectionsClient(); HotCollections.call(this, opts); }; inherits(MockHotCollections, HotCollections); return MockHotCollections; });
define([ 'inherits', 'streamhub-hot-collections/streams/hot-collections', 'streamhub-hot-collections-tests/mocks/clients/mock-hot-collections-client', 'streamhub-sdk-tests/mocks/mock-stream'], function (inherits, HotCollections, MockHotCollectionsClient, MockStream) { var MockHotCollections = function (opts) { opts = opts || {}; opts.client = opts.client || new MockHotCollectionsClient(); HotCollections.call(this, opts); }; inherits(MockHotCollections, HotCollections); MockHotCollections.prototype.push = function (a) { if (a !== null) { var collections = Array.prototype.slice.call(arguments); for (var i=0; i < collections.length; i++) { collections[i].createUpdater = function () { return new MockStream.LivefyreContent(); } } } HotCollections.prototype.push.apply(this, arguments) }; return MockHotCollections; });
Add mockstream to mock hot collection
Add mockstream to mock hot collection
JavaScript
mit
gobengo/streamhub-hot-collections
--- +++ @@ -1,8 +1,9 @@ define([ 'inherits', 'streamhub-hot-collections/streams/hot-collections', - 'streamhub-hot-collections-tests/mocks/clients/mock-hot-collections-client'], -function (inherits, HotCollections, MockHotCollectionsClient) { + 'streamhub-hot-collections-tests/mocks/clients/mock-hot-collections-client', + 'streamhub-sdk-tests/mocks/mock-stream'], +function (inherits, HotCollections, MockHotCollectionsClient, MockStream) { var MockHotCollections = function (opts) { opts = opts || {}; @@ -12,5 +13,18 @@ inherits(MockHotCollections, HotCollections); + MockHotCollections.prototype.push = function (a) { + if (a !== null) { + var collections = Array.prototype.slice.call(arguments); + for (var i=0; i < collections.length; i++) { + collections[i].createUpdater = function () { + return new MockStream.LivefyreContent(); + } + } + } + + HotCollections.prototype.push.apply(this, arguments) + }; + return MockHotCollections; });
b60d3d0b975cd077e2f1beeba07a8a4f53ad2512
js/debugLog.js
js/debugLog.js
/* * vim: ts=4:sw=4:expandtab */ (function () { 'use strict'; var MAX_MESSAGES = 1000; var PHONE_REGEX = /\+\d{7,12}(\d{3})/g; var debugLog = []; if (window.console) { console._log = console.log; console.log = function(thing){ console._log(thing); if (debugLog.length > MAX_MESSAGES) { debugLog.shift(); } var str = ('' + thing).replace(PHONE_REGEX, "+[REDACTED]$1"); debugLog.push(str); }; console.get = function() { return debugLog.join('\n'); }; console.post = function(log) { if (log === undefined) { log = console.get(); } return new Promise(function(resolve) { $.post('https://api.github.com/gists', textsecure.utils.jsonThing({ "public": true, "files": { "debugLog.txt": { "content": log } } })).then(function(response) { console._log('Posted debug log to ', response.html_url); resolve(response.html_url); }).fail(resolve); }); }; } })();
/* * vim: ts=4:sw=4:expandtab */ (function () { 'use strict'; var MAX_MESSAGES = 1000; var PHONE_REGEX = /\+\d{7,12}(\d{3})/g; var debugLog = []; if (window.console) { console._log = console.log; console.log = function(){ console._log.apply(this, arguments); if (debugLog.length > MAX_MESSAGES) { debugLog.shift(); } var args = Array.prototype.slice.call(arguments); var str = args.join(' ').replace(PHONE_REGEX, "+[REDACTED]$1"); debugLog.push(str); }; console.get = function() { return debugLog.join('\n'); }; console.post = function(log) { if (log === undefined) { log = console.get(); } return new Promise(function(resolve) { $.post('https://api.github.com/gists', textsecure.utils.jsonThing({ "public": true, "files": { "debugLog.txt": { "content": log } } })).then(function(response) { console._log('Posted debug log to ', response.html_url); resolve(response.html_url); }).fail(resolve); }); }; } })();
Make debug log handle multiple arguments
Make debug log handle multiple arguments Ex: console.log('delivery receipt', phone_number, timestamp) // FREEBIE
JavaScript
agpl-3.0
nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop
--- +++ @@ -8,12 +8,13 @@ var debugLog = []; if (window.console) { console._log = console.log; - console.log = function(thing){ - console._log(thing); + console.log = function(){ + console._log.apply(this, arguments); if (debugLog.length > MAX_MESSAGES) { debugLog.shift(); } - var str = ('' + thing).replace(PHONE_REGEX, "+[REDACTED]$1"); + var args = Array.prototype.slice.call(arguments); + var str = args.join(' ').replace(PHONE_REGEX, "+[REDACTED]$1"); debugLog.push(str); }; console.get = function() {
1829b94752a3cf01773d7d360adb2c18e528fcc8
src/renderer/mixins/global/readMagnet.js
src/renderer/mixins/global/readMagnet.js
export default { mounted () { document.addEventListener('paste', this.handlePaste) }, beforeDestroy () { document.removeEventListener('paste', this.handlePaste) }, computed: { isClientPage () { return this.$route.path === '/torrenting' } }, methods: { handlePaste (e) { const text = e.clipboardData.getData('text') if (/magnet:\?/.test(text)) { if (!this.isClientPage) { e.preventDefault() this.$store.dispatch('streaming/play', { link: text, isTorrent: true, name: null, neighbours: null }) } } } } }
export default { mounted () { document.addEventListener('paste', this.handlePaste) }, beforeDestroy () { document.removeEventListener('paste', this.handlePaste) }, computed: { isClientPage () { return this.$route.path === '/torrenting' } }, methods: { /** * @param {ClipboardEvent} e */ handlePaste (e) { const text = e.clipboardData.getData('text') if (e.target.tagName.toUpperCase() === 'INPUT') return if (/magnet:\?/.test(text)) { if (!this.isClientPage) { e.preventDefault() this.$store.dispatch('streaming/play', { link: text, isTorrent: true, name: null, neighbours: null }) } } } } }
Fix wrong handling of paste event that would result in streaming from a magnet if pasting into input for download for eg
Fix wrong handling of paste event that would result in streaming from a magnet if pasting into input for download for eg
JavaScript
mit
Kylart/KawAnime,Kylart/KawAnime,Kylart/KawAnime
--- +++ @@ -14,8 +14,13 @@ }, methods: { + /** + * @param {ClipboardEvent} e + */ handlePaste (e) { const text = e.clipboardData.getData('text') + + if (e.target.tagName.toUpperCase() === 'INPUT') return if (/magnet:\?/.test(text)) { if (!this.isClientPage) {
e268600106b19b02a8bcfd72f3aa9c59396f8d3d
js/src/core.js
js/src/core.js
// Export a global module. window.tangelo = {}; (function (tangelo) { "use strict"; // Tangelo version number. tangelo.version = function () { var version = "0.9.0-dev"; return version; }; // A namespace for plugins. tangelo.plugin = {}; // Standard way to access a plugin namespace. tangelo.getPlugin = function (plugin) { if (tangelo.plugin[plugin] === undefined) { tangelo.plugin[plugin] = {}; } return tangelo.plugin[plugin]; }; }(window.tangelo));
// Export a global module. window.tangelo = {}; (function (tangelo) { "use strict"; // Tangelo version number. tangelo.version = function () { var version = "0.9.0-dev"; return version; }; // A namespace for plugins. tangelo.plugin = {}; // Create a plugin namespace if it does not exist; otherwise, do nothing. tangelo.ensurePlugin = function (plugin) { if (tangelo.plugin[plugin] === undefined) { tangelo.plugin[plugin] = {}; } }; // Standard way to access a plugin namespace. tangelo.getPlugin = function (plugin) { if (tangelo.plugin[plugin] === undefined) { tangelo.plugin[plugin] = {}; } return tangelo.plugin[plugin]; }; }(window.tangelo));
Add tangelo.ensurePlugin() function, to replace tangelo.getPlugin() (which is deprecated)
Add tangelo.ensurePlugin() function, to replace tangelo.getPlugin() (which is deprecated)
JavaScript
apache-2.0
Kitware/tangelo,Kitware/tangelo,Kitware/tangelo
--- +++ @@ -13,6 +13,13 @@ // A namespace for plugins. tangelo.plugin = {}; + // Create a plugin namespace if it does not exist; otherwise, do nothing. + tangelo.ensurePlugin = function (plugin) { + if (tangelo.plugin[plugin] === undefined) { + tangelo.plugin[plugin] = {}; + } + }; + // Standard way to access a plugin namespace. tangelo.getPlugin = function (plugin) { if (tangelo.plugin[plugin] === undefined) {
2f9e7e2af6539395656c7a1ae0b375f178b1c156
packages/vega-view/src/initialize-handler.js
packages/vega-view/src/initialize-handler.js
import {offset} from './render-size'; export default function(view, prevHandler, el, constructor) { var handler = new constructor(view.loader(), view.tooltip()) .scene(view.scenegraph().root) .initialize(el, offset(view), view); if (prevHandler) { prevHandler.handlers().forEach(function(h) { handler.on(h.type, h.handler); }); } return handler; }
import {offset} from './render-size'; export default function(view, prevHandler, el, constructor) { var handler = new constructor(view.loader(), tooltip(view)) .scene(view.scenegraph().root) .initialize(el, offset(view), view); if (prevHandler) { prevHandler.handlers().forEach(function(h) { handler.on(h.type, h.handler); }); } return handler; } // wrap tooltip handler to trap errors function tooltip(view) { var handler = view.tooltip(), tooltip = null; if (handler) { tooltip = function() { try { handler.apply(this, arguments); } catch (error) { view.error(error); } }; } return tooltip; }
Add error trap for tooltip handler.
Add error trap for tooltip handler.
JavaScript
bsd-3-clause
vega/vega,vega/vega,lgrammel/vega,vega/vega,vega/vega
--- +++ @@ -1,7 +1,7 @@ import {offset} from './render-size'; export default function(view, prevHandler, el, constructor) { - var handler = new constructor(view.loader(), view.tooltip()) + var handler = new constructor(view.loader(), tooltip(view)) .scene(view.scenegraph().root) .initialize(el, offset(view), view); @@ -13,3 +13,21 @@ return handler; } + +// wrap tooltip handler to trap errors +function tooltip(view) { + var handler = view.tooltip(), + tooltip = null; + + if (handler) { + tooltip = function() { + try { + handler.apply(this, arguments); + } catch (error) { + view.error(error); + } + }; + } + + return tooltip; +}
346fa351b6c0c17c486dad3dbd85f974f48fb4aa
src/services/file.js
src/services/file.js
const { FileService } = require('./file/file.service') const { BadScriptPermission } = require('./file/bad-script-permission.error') const { ScriptNotExist } = require('./file/script-not-exist.error') module.exports = exports = { FileService, BadScriptPermission, ScriptNotExist }
const { FileService } = require('./file/file.service') const { BadScriptPermission } = require('./file/bad-script-permission.error') const { ScriptNotExist } = require('./file/script-not-exist.error') const { TargetFileAlreadyExist } = require('./file/target-file-already-exist.error') module.exports = exports = { FileService, BadScriptPermission, ScriptNotExist, TargetFileAlreadyExist }
Declare TargetFileAlreadyExist in service index
Declare TargetFileAlreadyExist in service index
JavaScript
apache-2.0
Mindsers/configfile
--- +++ @@ -1,9 +1,11 @@ const { FileService } = require('./file/file.service') const { BadScriptPermission } = require('./file/bad-script-permission.error') const { ScriptNotExist } = require('./file/script-not-exist.error') +const { TargetFileAlreadyExist } = require('./file/target-file-already-exist.error') module.exports = exports = { FileService, BadScriptPermission, - ScriptNotExist + ScriptNotExist, + TargetFileAlreadyExist }
1e7dd2c0d1a471092fc1ef6888543d2a4626e237
www/script.js
www/script.js
HandlebarsIntl.registerWith(Handlebars); $(function() { window.state = {}; var source = $("#stats-template").html(); var template = Handlebars.compile(source); refreshStats(template); setInterval(function() { refreshStats(template); }, 5000) }); function refreshStats(template) { $.getJSON("/stats", function(stats) { $("#alert").addClass('hide'); // Sort miners by ID if (stats.miners) { stats.miners = stats.miners.sort(compare) } var epochOffset = (30000 - (stats.height % 30000)) * 1000 * 17 stats.nextEpoch = stats.now + epochOffset // Repaint stats var html = template(stats); $('#stats').html(html); }).fail(function() { $("#alert").removeClass('hide'); }); } function compare(a, b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; }
HandlebarsIntl.registerWith(Handlebars); $(function() { window.state = {}; var source = $("#stats-template").html(); var template = Handlebars.compile(source); refreshStats(template); setInterval(function() { refreshStats(template); }, 5000) }); function refreshStats(template) { $.getJSON("/stats", function(stats) { $("#alert").addClass('hide'); // Sort miners by ID if (stats.miners) { stats.miners = stats.miners.sort(compare) } var epochOffset = (30000 - (stats.height % 30000)) * 1000 * 15 stats.nextEpoch = stats.now + epochOffset // Repaint stats var html = template(stats); $('#stats').html(html); }).fail(function() { $("#alert").removeClass('hide'); }); } function compare(a, b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; }
Adjust epoch estimation time for Homestead
Adjust epoch estimation time for Homestead
JavaScript
mit
sammy007/ether-proxy,sammy007/ether-proxy,sammy007/ether-proxy,sammy007/ether-proxy
--- +++ @@ -20,7 +20,7 @@ stats.miners = stats.miners.sort(compare) } - var epochOffset = (30000 - (stats.height % 30000)) * 1000 * 17 + var epochOffset = (30000 - (stats.height % 30000)) * 1000 * 15 stats.nextEpoch = stats.now + epochOffset // Repaint stats
030c68973913fcf45f259a2f0cdd334955d33dac
src/util/weak-map.js
src/util/weak-map.js
export default window.WeakMap || (function () { let index = 0; function Wm () { this.key = `____weak_map_${index++}`; } Wm.prototype = { delete (obj) { if (obj) { delete obj[this.key]; } }, get (obj) { return obj ? obj[this.key] : null; }, has (obj) { return obj ? typeof obj[this.key] !== 'undefined' : false; }, set (obj, val) { return obj ? obj[this.key] = val : null; } }; return Wm; }());
export default window.WeakMap || (function () { let index = 0; function Wm () { this.key = `____weak_map_${index++}`; } Wm.prototype = { delete (obj) { if (obj) { delete obj[this.key]; } }, get (obj) { return obj ? obj[this.key] : null; }, has (obj) { return obj ? typeof obj[this.key] !== 'undefined' : false; }, set (obj, val) { if (obj) { const key = this.key; if (typeof obj[key] === 'undefined') { Object.defineProperty(obj, key, { configurable: true, enumerable: false, value: val }); } else { obj[key] = val; } } } }; return Wm; }());
Make weak map props non-enumerable preventing circular references when traversing props.
Make weak map props non-enumerable preventing circular references when traversing props.
JavaScript
mit
skatejs/named-slots
--- +++ @@ -16,7 +16,18 @@ return obj ? typeof obj[this.key] !== 'undefined' : false; }, set (obj, val) { - return obj ? obj[this.key] = val : null; + if (obj) { + const key = this.key; + if (typeof obj[key] === 'undefined') { + Object.defineProperty(obj, key, { + configurable: true, + enumerable: false, + value: val + }); + } else { + obj[key] = val; + } + } } }; return Wm;
40c5111ee6fe0b7c670dc28d66d475be2ff030fc
null-prune.js
null-prune.js
(function (name, definition) { // AMD if (typeof define === 'function') { define(definition); } // Node.js else if (typeof module !== 'undefined' && module.exports) { module.exports = definition(); } // Browser else { window[name] = definition(); } })('nullPrune', function () { function hasOwnProperty(obj, property) { return Object.prototype.hasOwnProperty.call(obj, property) } function isObject (input) { return input && (typeof input === 'object') } function keys (obj) { const ownKeys = [] for (let key in obj) { if (hasOwnProperty(obj, key)) { ownKeys.push(key) } } return ownKeys } function nullPrune (inputObject, { objectKey, parentObject }) { keys(inputObject).forEach(function(key) { let node = inputObject[key] if (isObject(node)) { nullPrune(node, { objectKey: key, parentObject: inputObject }) } else if (node == null) { delete inputObject[key] } }) if (keys(inputObject).length === 0) { delete parentObject[objectKey] } } return function(inputObject) { if (!isObject(inputObject)) { return inputObject } nullPrune(inputObject, {}) return inputObject } })
(function (name, definition) { if (typeof define === 'function') { // AMD define(definition); } else if (typeof module !== 'undefined' && module.exports) { // Node.js module.exports = definition(); } else { // Browser window[name] = definition(); } })('nullPrune', function () { function hasOwnProperty(obj, property) { return Object.prototype.hasOwnProperty.call(obj, property) } function isObject (input) { return input && (typeof input === 'object') } function keys (obj) { const ownKeys = [] for (let key in obj) { if (hasOwnProperty(obj, key)) { ownKeys.push(key) } } return ownKeys } function nullPrune (inputObject, { objectKey, parentObject }) { keys(inputObject).forEach(function(key) { let node = inputObject[key] if (isObject(node)) { nullPrune(node, { objectKey: key, parentObject: inputObject }) } else if (node == null) { delete inputObject[key] } }) if (keys(inputObject).length === 0) { delete parentObject[objectKey] } } return function(inputObject) { if (!isObject(inputObject)) { return inputObject } nullPrune(inputObject, {}) return inputObject } })
Tidy up indentation of UMD loader
Tidy up indentation of UMD loader
JavaScript
apache-2.0
cskeppstedt/null-prune
--- +++ @@ -1,19 +1,14 @@ (function (name, definition) { - + if (typeof define === 'function') { // AMD - if (typeof define === 'function') { - define(definition); - } - + define(definition); + } else if (typeof module !== 'undefined' && module.exports) { // Node.js - else if (typeof module !== 'undefined' && module.exports) { - module.exports = definition(); - } - + module.exports = definition(); + } else { // Browser - else { - window[name] = definition(); - } + window[name] = definition(); + } })('nullPrune', function () { function hasOwnProperty(obj, property) { return Object.prototype.hasOwnProperty.call(obj, property)
940163051b33e111370fbb292666e4668c519a27
test/integration/test-bad-credentials.js
test/integration/test-bad-credentials.js
var common = require('../common'); var connection = common.createConnection({password: 'INVALID PASSWORD'}); var assert = require('assert'); var err; connection.connect(function(_err) { assert.equal(err, undefined); err = _err; }); process.on('exit', function() { assert.ok(/access denied/i.test(err.message)); assert.equal(err.code, 'ER_ACCESS_DENIED_ERROR'); });
var common = require('../common'); var connection = common.createConnection({password: 'INVALID PASSWORD'}); var assert = require('assert'); var err; connection.connect(function(_err) { assert.equal(err, undefined); err = _err; }); process.on('exit', function() { assert.equal(err.code, 'ER_ACCESS_DENIED_ERROR'); assert.ok(/access denied/i.test(err.message)); });
Make test error more useful
Make test error more useful
JavaScript
mit
saisai/node-mysql,wxkdesky/node-mysql,1602/node-mysql,bbito/node-mysql,l371559739/node-mysql,yanninho/node-mysql,linalu1/node-mysql,felixge/node-mysql,tempbottle/node-mysql,shipci/node-mysql,apathyjade/node-mysql,yulongge/node-mysql,XiaoLongW/node-mysql,grooverdan/node-mysql,zhhb/node-mysql,chinazhaghai/node-mysql,Jimbly/node-mysql,lukw00/node-mysql,ashwinks/node-mysql,AndersonGitHub/node-mysql,seangarner/node-mysql,yourcaptain/node-mysql,theblackperl/node-mysql,AshWilliams/node-mysql,mysqljs/mysql,mhasan3/node-mysql,acorbi/node-mysql,NikosEfthias/node-mysql,WY08271/node-mysql,yan5845hao/node-mysql-1,danidomi/node-mysql,cgvarela/node-mysql,teng2015/node-mysql,bORm/node-mysql
--- +++ @@ -9,7 +9,7 @@ }); process.on('exit', function() { + assert.equal(err.code, 'ER_ACCESS_DENIED_ERROR'); assert.ok(/access denied/i.test(err.message)); - assert.equal(err.code, 'ER_ACCESS_DENIED_ERROR'); });
fa7831b3ab4331c1e617809b520d82deb5711931
shared/api_client/ChainConfig.js
shared/api_client/ChainConfig.js
import { ecc_config, hash } from "../ecc" ecc_config.address_prefix = "GLS"; let chain_id = "" for(let i = 0; i < 32; i++) chain_id += "00" module.exports = { address_prefix: "GLS", expire_in_secs: 15, chain_id }
import { ecc_config, hash } from "../ecc" ecc_config.address_prefix = "STM"; let chain_id = "" for(let i = 0; i < 32; i++) chain_id += "00" module.exports = { address_prefix: "STM", expire_in_secs: 15, chain_id }
Use STM instead GLS as ecc_config.address_prefix
Use STM instead GLS as ecc_config.address_prefix
JavaScript
mit
GolosChain/tolstoy,GolosChain/tolstoy,GolosChain/tolstoy
--- +++ @@ -1,12 +1,12 @@ import { ecc_config, hash } from "../ecc" -ecc_config.address_prefix = "GLS"; +ecc_config.address_prefix = "STM"; let chain_id = "" for(let i = 0; i < 32; i++) chain_id += "00" module.exports = { - address_prefix: "GLS", + address_prefix: "STM", expire_in_secs: 15, chain_id }
520f37fad8789c5e43e59918b84848b1dea3bf06
test/when-adapter.js
test/when-adapter.js
(function() { 'use strict'; if(typeof exports === 'object') { var when = require('../when'); exports.fulfilled = when.resolve; exports.rejected = when.reject; exports.pending = function () { var deferred = when.defer(); return { promise: deferred.promise, fulfill: deferred.resolve, reject: deferred.reject }; }; } })();
(function() { 'use strict'; if(typeof exports === 'object') { var when = require('../when'); exports.fulfilled = when.resolve; exports.rejected = when.reject; exports.pending = function () { var pending = {}; pending.promise = when.promise(function(resolve, reject) { pending.fulfill = resolve; pending.reject = reject; }); return pending; }; } })();
Update aplus test adapter to use when.promise
Update aplus test adapter to use when.promise
JavaScript
mit
caporta/when,caporta/when,ning-github/when,SourcePointUSA/when,stevage/when,frank-weindel/when,tkirda/when,ning-github/when,mlennon3/when,stevage/when,anthonyvia/when,tkirda/when,petkaantonov/when,SourcePointUSA/when,frank-weindel/when,anthonyvia/when,mlennon3/when,DJDNS/when.js
--- +++ @@ -9,13 +9,14 @@ exports.rejected = when.reject; exports.pending = function () { - var deferred = when.defer(); + var pending = {}; - return { - promise: deferred.promise, - fulfill: deferred.resolve, - reject: deferred.reject - }; + pending.promise = when.promise(function(resolve, reject) { + pending.fulfill = resolve; + pending.reject = reject; + }); + + return pending; }; } })();
5b15efa2a01ccdb6ed4c92128df362e585bbd868
string/startswith.js
string/startswith.js
module.exports = function (str, query, position) { return str.substr(position, query.length) === query; };
/** Does a string start with another string? @module string/startsWith @param {string} str The string to search through. @param {string} query The string to find in `str`. @param {number} [position=0] The index to start the search. Defaults to the beginning of the string. @returns {bool} Does the string start with another string? @example var startsWith = require('lildash/string/startswith'); startsWith('food', 'foo'); // => true startsWith('cake', 'foo'); // => false startsWith('cake', 'k'); // => false startsWith('cake', 'k', 2); // => true */ module.exports = function (str, query, position) { return str.substr(position, query.length) === query; };
Add JSDoc documentation to string/startsWith
Add JSDoc documentation to string/startsWith
JavaScript
mit
EvanHahn/lildash
--- +++ @@ -1,3 +1,18 @@ +/** +Does a string start with another string? + +@module string/startsWith +@param {string} str The string to search through. +@param {string} query The string to find in `str`. +@param {number} [position=0] The index to start the search. Defaults to the beginning of the string. +@returns {bool} Does the string start with another string? +@example +var startsWith = require('lildash/string/startswith'); +startsWith('food', 'foo'); // => true +startsWith('cake', 'foo'); // => false +startsWith('cake', 'k'); // => false +startsWith('cake', 'k', 2); // => true +*/ module.exports = function (str, query, position) { return str.substr(position, query.length) === query; };
e825b025f3e7e2c96cf73ae669e70161bb1e6b7e
app/assets/javascripts/umlaut/ajax_windows.js
app/assets/javascripts/umlaut/ajax_windows.js
/* ajax_windows.js. Support for modal popup windows in Umlaut items. */ jQuery(document).ready(function($) { var populate_modal = function(data, textStatus, jqXHR) { data = $(data); var heading = data.find("h1, h2, h3, h4, h5, h6").eq(0).remove(); $("#modal .modal-header h3").text(heading.text()); var submit = data.find("form input[type=submit]").eq(0).remove(); $("#modal .modal-body").html(data.html()); if (submit) $("#modal .modal-footer").html(submit.wrap('<div>').parent().html()); $("#modal").modal("show"); } var display_modal = function(event) { event.preventDefault(); $.get(this.href, "", populate_modal, "html"); return false; } var ajax_form_catch = function(event) { event.preventDefault(); var form = $("#modal form"); $.post(form.attr("action"), form.serialize(), populate_modal, "html"); return false; }; $("a.ajax_window").live("click", display_modal); $("#modal .modal-footer input[type=submit]").live("click", ajax_form_catch); $("#modal form").live("submit", ajax_form_catch); });
/* ajax_windows.js. Support for modal popup windows in Umlaut items. */ jQuery(document).ready(function($) { var populate_modal = function(data, textStatus, jqXHR) { data = $(data); var heading = data.find("h1, h2, h3, h4, h5, h6").eq(0).remove(); $("#modal .modal-header h3").text(heading.text()); var submit = data.find("form input[type=submit]").eq(0).remove(); $("#modal .modal-body").html(data.html()); footer = $("#modal .modal-footer") var old_submit = footer.find("#modal .modal-footer input[type=submit]").eq(0).remove(); if (submit) { footer.prepend(submit); } $("#modal").modal("show"); } var display_modal = function(event) { event.preventDefault(); $.get(this.href, "", populate_modal, "html"); return false; } var ajax_form_catch = function(event) { event.preventDefault(); var form = $("#modal form"); $.post(form.attr("action"), form.serialize(), populate_modal, "html"); return false; }; $("a.ajax_window").live("click", display_modal); $("#modal .modal-footer input[type=submit]").live("click", ajax_form_catch); $("#modal form").live("submit", ajax_form_catch); });
Update to handle modal window submits.
Update to handle modal window submits.
JavaScript
mit
team-umlaut/umlaut,team-umlaut/umlaut,team-umlaut/umlaut
--- +++ @@ -6,7 +6,11 @@ $("#modal .modal-header h3").text(heading.text()); var submit = data.find("form input[type=submit]").eq(0).remove(); $("#modal .modal-body").html(data.html()); - if (submit) $("#modal .modal-footer").html(submit.wrap('<div>').parent().html()); + footer = $("#modal .modal-footer") + var old_submit = footer.find("#modal .modal-footer input[type=submit]").eq(0).remove(); + if (submit) { + footer.prepend(submit); + } $("#modal").modal("show"); } var display_modal = function(event) {
6cdc555485a9fba147558341eed8a11b2a63efd7
lib/CordovaPluginAdapter.js
lib/CordovaPluginAdapter.js
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter'); var ReactNative = require('react-native'); function CordovaPluginAdapter() { this.nativeInterface = ReactNative.NativeModules.CordovaPluginAdapter; this._callbackCount = Math.random(); this._callbacks = {}; this.initCallbackChannel(); }; CordovaPluginAdapter.prototype.exec = function(success, fail, service, action, args) { var callbackId = [service, action, this._callbackCount].join(':'); this._callbacks[callbackId] = { success: success, fail: fail }; this.nativeInterface.exec(service, action, callbackId, JSON.stringify(args)); this._callbackCount++; }; CordovaPluginAdapter.prototype.initCallbackChannel = function() { RCTDeviceEventEmitter.addListener('CordovaWebViewProxy', this.onChannelCallback, this); }; CordovaPluginAdapter.prototype.onChannelCallback = function(params) { if (typeof this._callbacks[params.callbackId] === 'object') { var result = params.message; try { if (params.status === 1) { this._callbacks[params.callbackId].success(result); } else if (params.status === 1) { this._callbacks[params.callbackId].fail(result); } } finally { if (!params.keepCallback) { delete this._callbacks[params.callbackId]; } } } }; module.exports = CordovaPluginAdapter;
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter'); var ReactNative = require('react-native'); function CordovaPluginAdapter() { this.nativeInterface = ReactNative.NativeModules.CordovaPluginAdapter; this._callbackCount = Math.random(); this._callbacks = {}; this.initCallbackChannel(); }; CordovaPluginAdapter.prototype.exec = function(success, fail, service, action, args) { var callbackId = [service, action, this._callbackCount].join(':'); this._callbacks[callbackId] = { success: success, fail: fail }; this.nativeInterface.exec(service, action, callbackId, JSON.stringify(args)); this._callbackCount++; }; CordovaPluginAdapter.prototype.initCallbackChannel = function() { RCTDeviceEventEmitter.addListener('CordovaWebViewProxy', this.onChannelCallback, this); }; CordovaPluginAdapter.prototype.onChannelCallback = function(params) { if (typeof this._callbacks[params.callbackId] === 'object') { var result = JSON.parse(params.message); try { if (params.status === 1) { this._callbacks[params.callbackId].success(result); } else if (params.status === 1) { this._callbacks[params.callbackId].fail(result); } } finally { if (!params.keepCallback) { delete this._callbacks[params.callbackId]; } } } }; module.exports = CordovaPluginAdapter;
Return object, not string from Cordova plugin calls
Return object, not string from Cordova plugin calls
JavaScript
isc
axemclion/react-native-cordova-plugin,axemclion/react-native-cordova-plugin
--- +++ @@ -25,7 +25,7 @@ CordovaPluginAdapter.prototype.onChannelCallback = function(params) { if (typeof this._callbacks[params.callbackId] === 'object') { - var result = params.message; + var result = JSON.parse(params.message); try { if (params.status === 1) { this._callbacks[params.callbackId].success(result);
82dc2f6053b9f55e380daa43d288128f9788f739
.wdio/ci.conf.js
.wdio/ci.conf.js
exports.config = { specs: [ './test/**/*.js' ], exclude: [ ], sync: true, logLevel: 'silent', coloredLogs: true, bail: 0, screenshotPath: 'screenshots', baseUrl: 'http://localhost:3000', framework: 'mocha', mochaOpts: { ui: 'bdd', }, reporters: [ 'spec' ], waitforTimeout: 10000, connectionRetryTimeout: 90000, connectionRetryCount: 3, services: [ 'browserstack' ], maxInstances: 1, capabilities: [ { browserName: 'chrome', project: 'telepathy-web', 'browserstack.local': true, }, { browserName: 'safari', project: 'telepathy-web', 'browserstack.local': true, }, { browserName: 'firefox', project: 'telepathy-web', 'browserstack.local': true, }, ], browserstackLocal: true, user: process.env.BROWSERSTACK_USER, key: process.env.BROWSERSTACK_PASS, };
exports.config = { specs: [ './test/**/*.js' ], exclude: [ ], sync: true, logLevel: 'silent', coloredLogs: true, bail: 0, screenshotPath: 'screenshots', baseUrl: 'http://localhost:3000', framework: 'mocha', mochaOpts: { ui: 'bdd', }, reporters: [ 'spec' ], waitforTimeout: 30000, connectionRetryTimeout: 90000, connectionRetryCount: 3, services: [ 'browserstack' ], maxInstances: 1, capabilities: [ { browserName: 'chrome', project: 'telepathy-web', 'browserstack.local': true, }, { browserName: 'safari', project: 'telepathy-web', 'browserstack.local': true, }, { browserName: 'firefox', project: 'telepathy-web', 'browserstack.local': true, }, ], browserstackLocal: true, user: process.env.BROWSERSTACK_USER, key: process.env.BROWSERSTACK_PASS, };
Increase waitforTimeout to 30 seconds
Increase waitforTimeout to 30 seconds
JavaScript
mpl-2.0
chameleoid/telepathy-web,chameleoid/telepathy-web,chameleoid/telepathy-web
--- +++ @@ -18,7 +18,7 @@ reporters: [ 'spec' ], - waitforTimeout: 10000, + waitforTimeout: 30000, connectionRetryTimeout: 90000, connectionRetryCount: 3,
476629c71af2137a81c276d93abaa87946e6ccbc
vendor/ember-intercom-io.js
vendor/ember-intercom-io.js
(function() { /* globals define, Intercom */ function generateModule(name, values) { define(name, [], function() { 'use strict'; return values; }); } function setupIntercom(config) { var ic = window.Intercom || null; if (typeof ic === 'function') { ic('reattach_activator'); ic('update', {}); } else { var d = document; var i = function() { i.c(arguments); }; i.q = []; i.c = function(args) { i.q.push(args); }; window.Intercom = i; var s = d.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = `https://widget.intercom.io/widget/${Ember.get(config, 'intercom.appId')}`; var [x] = d.getElementsByTagName('script'); x.parentNode.insertBefore(s, x); } } generateModule('ember-intercom-io', { 'setupIntercom': setupIntercom }); })();
(function() { /* globals define, Intercom */ function generateModule(name, values) { define(name, [], function() { 'use strict'; return values; }); } function setupIntercom(config) { var ic = window.Intercom || null; if (typeof ic === 'function') { ic('reattach_activator'); ic('update', {}); } else { var d = window.document; var i = function() { i.c(arguments); }; i.q = []; i.c = function(args) { i.q.push(args); }; window.Intercom = i; var s = d.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = 'https://widget.intercom.io/widget/' + Ember.get(config, 'intercom.appId'); var x = d.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); } } generateModule('ember-intercom-io', { 'setupIntercom': setupIntercom }); })();
Use es5 for node.js code, to make phantom happy
Use es5 for node.js code, to make phantom happy
JavaScript
mit
levanto-financial/ember-intercom-io,seawatts/ember-intercom-io,mike-north/ember-intercom-io,levanto-financial/ember-intercom-io,mike-north/ember-intercom-io,seawatts/ember-intercom-io
--- +++ @@ -15,7 +15,7 @@ ic('reattach_activator'); ic('update', {}); } else { - var d = document; + var d = window.document; var i = function() { i.c(arguments); }; @@ -28,8 +28,8 @@ var s = d.createElement('script'); s.type = 'text/javascript'; s.async = true; - s.src = `https://widget.intercom.io/widget/${Ember.get(config, 'intercom.appId')}`; - var [x] = d.getElementsByTagName('script'); + s.src = 'https://widget.intercom.io/widget/' + Ember.get(config, 'intercom.appId'); + var x = d.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); } }
2cef9ebfa7c747e96db3a8d8e2a3dce9a3e74c82
test/stub/ns.tmpl.js
test/stub/ns.tmpl.js
beforeEach(function() { function genViewHTML(id, view) { var html = ''; var clazz = 'ns-view-' + id; if (view.async) { clazz += ' ns-async'; } if (view.collection) { clazz += ' ns-view-container-desc'; } if (view.placeholder) { clazz += ' ns-view-placeholder'; } html += '<div class="' + clazz + '" data-key="' + view.key + '">'; // don't create child views in async state if (!view.async) { html += genHTML(view.views); } html += '</div>'; return html; } function genHTML(views) { var html = ''; for (var id in views) { var view = views[id]; // collection if (Array.isArray(view)) { view.forEach(function(collectionItem) { html += genViewHTML(id, collectionItem); }); } else { html += genViewHTML(id, view); } } return html; } sinon.stub(ns, 'tmpl', function(json) { return ns.html2node('<div class="root">' + genHTML(json.views) + '</div>'); }); }); afterEach(function() { ns.tmpl.restore(); });
beforeEach(function() { function genViewHTML(id, view) { var html = ''; var clazz = 'ns-view-' + id; if (view.async) { clazz += ' ns-async'; } if (view.collection) { clazz += ' ns-view-container-desc'; } if (view.placeholder) { clazz += ' ns-view-placeholder'; } html += '<div class="' + clazz + '" data-key="' + view.key + '" data-random="' + Math.random() + '">'; // don't create child views in async state if (!view.async) { html += genHTML(view.views); } html += '</div>'; return html; } function genHTML(views) { var html = ''; for (var id in views) { var view = views[id]; // collection if (Array.isArray(view)) { view.forEach(function(collectionItem) { html += genViewHTML(id, collectionItem); }); } else { html += genViewHTML(id, view); } } return html; } sinon.stub(ns, 'tmpl', function(json) { return ns.html2node('<div class="root">' + genHTML(json.views) + '</div>'); }); }); afterEach(function() { ns.tmpl.restore(); });
Add random key to generated nodes to simple get same it or not
Add random key to generated nodes to simple get same it or not
JavaScript
mit
yandex-ui/noscript,Rebulus/noscript,mishk0/noscript
--- +++ @@ -13,7 +13,7 @@ if (view.placeholder) { clazz += ' ns-view-placeholder'; } - html += '<div class="' + clazz + '" data-key="' + view.key + '">'; + html += '<div class="' + clazz + '" data-key="' + view.key + '" data-random="' + Math.random() + '">'; // don't create child views in async state if (!view.async) { html += genHTML(view.views);
7eeebd090769ed1bcf8013b6f0306b5531ba3e86
test/util/localrq.js
test/util/localrq.js
var request = require('request'); var localRoot = 'http://localhost:' + process.env.PORT || 3000; var assert = require('assert'); exports.get = function localGet(url, cb) { return request({url: localRoot + url, encoding: 'utf8', method: 'GET'}, assertServerSuccess(cb)); }; exports.post = function localPost(url, body, cb) { return request({url: localRoot + url, encoding: 'utf8', method: 'POST', body: body}, assertServerSuccess(cb)); }; function assertServerSuccess(cb) { return function(err, res, body) { if (res.statusCode >= 500) { assert.fail(res.statusCode, 500, body, '<'); } else cb && cb(err,res,body); }; }
var request = require('request'); var localRoot = 'http://localhost:' + process.env.PORT || 3000; var assert = require('assert'); exports.get = function localGet(url, cb) { return request({url: localRoot + url, encoding: 'utf8', method: 'GET'}, assertServerSuccess(cb)); }; exports.post = function localPost(url, body, cb) { return request({url: localRoot + url, encoding: 'utf8', method: 'POST', body: body}, assertServerSuccess(cb)); }; function assertServerSuccess(cb) { return function(err, res, body) { if (!err && res.statusCode >= 500) { assert.fail(res.statusCode, 500, body, '<'); } else cb && cb(err,res,body); }; }
Handle errs when asserting server success
Handle errs when asserting server success
JavaScript
mit
chatphrase/caress
--- +++ @@ -14,7 +14,7 @@ function assertServerSuccess(cb) { return function(err, res, body) { - if (res.statusCode >= 500) { + if (!err && res.statusCode >= 500) { assert.fail(res.statusCode, 500, body, '<'); } else cb && cb(err,res,body); };
99abf608ea6e19c83a3f4e564ea31f7749fc48be
.babelrc.js
.babelrc.js
const {join} = require("path") module.exports = { plugins: [ ["module-resolver", { cwd: __dirname, root: ["src"], alias: { "package.json": join(__dirname, "package.json") } }], "@babel/transform-runtime", ["@babel/proposal-decorators", { legacy: true }], ["@babel/proposal-class-properties", { loose: true }], "@babel/plugin-proposal-partial-application", "@babel/proposal-nullish-coalescing-operator", "@babel/proposal-optional-catch-binding", "@babel/proposal-optional-chaining", "@babel/proposal-export-namespace-from", "@babel/proposal-export-default-from", "@babel/proposal-do-expressions", ["@babel/proposal-pipeline-operator", { proposal: "minimal" }], ["@babel/transform-modules-commonjs", { mjsStrictNamespace: false }], ] }
const {join} = require("path") module.exports = { plugins: [ ["module-resolver", { cwd: __dirname, root: ["src"], alias: { "package.json": join(__dirname, "package.json") } }], "@babel/transform-runtime", ["@babel/proposal-decorators", { legacy: true }], ["@babel/proposal-class-properties", { loose: true }], "@babel/proposal-partial-application", "@babel/proposal-nullish-coalescing-operator", "@babel/proposal-optional-catch-binding", "@babel/proposal-optional-chaining", "@babel/proposal-export-namespace-from", "@babel/proposal-export-default-from", "@babel/proposal-do-expressions", ["@babel/proposal-pipeline-operator", { proposal: "minimal" }], ["@babel/transform-modules-commonjs", { mjsStrictNamespace: false }], ] }
Add partial application plugin for babel.
Add partial application plugin for babel.
JavaScript
mit
octet-stream/ponyfiction-js,octet-stream/ponyfiction-js
--- +++ @@ -16,7 +16,7 @@ ["@babel/proposal-class-properties", { loose: true }], - "@babel/plugin-proposal-partial-application", + "@babel/proposal-partial-application", "@babel/proposal-nullish-coalescing-operator", "@babel/proposal-optional-catch-binding", "@babel/proposal-optional-chaining",
c7ff1ef3550c46c3ee97740c97ca1d47a3914217
src/components/encrypt/EncryptKeyListItem.js
src/components/encrypt/EncryptKeyListItem.js
'use strict'; import React, { Component } from 'react'; import ReactCSS from 'reactcss'; class EncryptKeyListItem extends Component { classes() { return { 'default': { }, }; } render() { return <div></div>; } } export default ReactCSS(EncryptKeyListItem);
'use strict'; import React, { Component } from 'react'; import ReactCSS from 'reactcss'; import { User } from '../common/index'; import colors from '../../styles/variables/colors'; import { spacing, sizing } from '../../styles/variables/utils'; class EncryptKeyListItem extends Component { classes() { return { 'default': { user: { padding: `${spacing.m}px ${spacing.m}px ${spacing.m}px`, display: 'flex', }, spaceLine: { borderBottom: `solid 1px ${colors.offBgLight}`, margin: `0px ${spacing.m}px 0px ${spacing.m + sizing.avatar + spacing.s}px`, item: 1, }, }, }; } render() { return <div></div>; } } export default ReactCSS(EncryptKeyListItem);
Add encrypt key list item styles
Add encrypt key list item styles
JavaScript
mit
henryboldi/felony,tobycyanide/felony,henryboldi/felony,tobycyanide/felony
--- +++ @@ -3,11 +3,24 @@ import React, { Component } from 'react'; import ReactCSS from 'reactcss'; +import { User } from '../common/index'; + +import colors from '../../styles/variables/colors'; +import { spacing, sizing } from '../../styles/variables/utils'; + class EncryptKeyListItem extends Component { classes() { return { 'default': { - + user: { + padding: `${spacing.m}px ${spacing.m}px ${spacing.m}px`, + display: 'flex', + }, + spaceLine: { + borderBottom: `solid 1px ${colors.offBgLight}`, + margin: `0px ${spacing.m}px 0px ${spacing.m + sizing.avatar + spacing.s}px`, + item: 1, + }, }, }; }
9fcd1742f83e9759d0b8d7fd4338cd6149a19a07
PageTool/Analytics/Include/Analytics.tool.js
PageTool/Analytics/Include/Analytics.tool.js
var _gaq = _gaq || []; _gaq.push(['_setAccount', '{ANALYTICS_CODE}']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js', '__gaTracker'); __gaTracker('create', '{ANALYTICS_CODE}', 'teawars.com'); __gaTracker('send', 'pageview');
Update to use Universal Tracking
Update to use Universal Tracking
JavaScript
mit
phpgt/webengine
--- +++ @@ -1,15 +1,8 @@ -var _gaq = _gaq || []; -_gaq.push(['_setAccount', '{ANALYTICS_CODE}']); -_gaq.push(['_trackPageview']); +(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ +(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), +m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) +})(window,document,'script','//www.google-analytics.com/analytics.js', +'__gaTracker'); -(function() { - var ga = document.createElement('script'); - ga.type = 'text/javascript'; - ga.async = true; - ga.src = ('https:' == document.location.protocol - ? 'https://' - : 'http://') - + 'stats.g.doubleclick.net/dc.js'; - var s = document.getElementsByTagName('script')[0]; - s.parentNode.insertBefore(ga, s); -})(); +__gaTracker('create', '{ANALYTICS_CODE}', 'teawars.com'); +__gaTracker('send', 'pageview');
07927b0770d543f49028de8a4f1ebb5ead627e94
client/javascript/services/getAssessments.js
client/javascript/services/getAssessments.js
import debugModule from 'debug'; import Joi from 'joi'; import xhr from 'xhr'; const debug = debugModule('csra'); const schema = Joi.array().items( Joi.object({ id: Joi.number(), nomisId: Joi.string().optional(), forename: Joi.string(), surname: Joi.string(), dateOfBirth: Joi.string(), riskAssessmentCompleted: Joi.boolean(), healthAssessmentCompleted: Joi.boolean(), outcome: Joi.string().optional(), }), ); const validate = (assessment) => { const isValid = Joi.validate(assessment, schema, { abortEarly: false, presence: 'required', }); debug('Validation of get assessments return %j', isValid.error); return isValid.error === null; }; const getAssessments = (callback) => { const target = '/api/assessments'; debug('get assessments'); const options = { timeout: 3500, }; xhr.get(target, options, (error, resp, body) => { debug('get assessments returned %j', error || body); if (error) { callback(null); } else { callback(validate(body) ? body : null); } }); }; export default getAssessments;
import debugModule from 'debug'; import Joi from 'joi'; import xhr from 'xhr'; const debug = debugModule('csra'); const schema = Joi.array().items( Joi.object({ id: Joi.number(), nomisId: Joi.string().optional(), forename: Joi.string(), surname: Joi.string(), dateOfBirth: Joi.string(), riskAssessmentCompleted: Joi.boolean(), healthAssessmentCompleted: Joi.boolean(), outcome: Joi.string().optional(), }), ); const validate = (assessment) => { const isValid = Joi.validate(assessment, schema, { abortEarly: false, presence: 'required', }); debug('Validation of get assessments return %j', isValid.error); return isValid.error === null; }; const getAssessments = (callback) => { const target = '/api/assessments'; debug('get assessments'); const options = { timeout: 3500, json: true, }; xhr.get(target, options, (error, resp, body) => { debug('get assessments returned %j', error || body); if (error) { callback(null); } else { callback(validate(body) ? body : null); } }); }; export default getAssessments;
Add JSON option to automatically parse to JSON from request
CSRA-547: Add JSON option to automatically parse to JSON from request
JavaScript
mit
noms-digital-studio/csra-app,noms-digital-studio/csra-app,noms-digital-studio/csra-app
--- +++ @@ -35,6 +35,7 @@ const options = { timeout: 3500, + json: true, }; xhr.get(target, options, (error, resp, body) => {
2d0d320d058b08703a1c4ce746c6cd5e0c976acb
webui/src/app/core/providers.resource.js
webui/src/app/core/providers.resource.js
'use strict'; var angular = require('angular'); var traefikCoreProvider = 'traefik.core.provider'; module.exports = traefikCoreProvider; angular .module(traefikCoreProvider, ['ngResource']) .factory('Providers', Providers); /** @ngInject */ function Providers($resource, $q) { const resourceProvider = $resource('../api/providers'); return { get: function () { return $q((resolve, reject) => { resourceProvider.get() .$promise .then((rawProviders) => { for (let providerName in rawProviders) { if (rawProviders.hasOwnProperty(providerName)) { if (!providerName.startsWith('$')) { // BackEnds mapping let bckends = rawProviders[providerName].backends || {}; rawProviders[providerName].backends = Object.keys(bckends) .map(key => { const goodBackend = bckends[key]; goodBackend.backendId = key; return goodBackend; }); // FrontEnds mapping let frtends = rawProviders[providerName].frontends || {}; rawProviders[providerName].frontends = Object.keys(frtends) .map(key => { const goodFrontend = frtends[key]; goodFrontend.frontendId = key; return goodFrontend; }); } } } resolve(rawProviders); }) .catch(reject); }); } }; }
'use strict'; var angular = require('angular'); var traefikCoreProvider = 'traefik.core.provider'; module.exports = traefikCoreProvider; angular .module(traefikCoreProvider, ['ngResource']) .factory('Providers', Providers); /** @ngInject */ function Providers($resource, $q) { const resourceProvider = $resource('../api/providers'); return { get: function () { return $q((resolve, reject) => { resourceProvider.get() .$promise .then((rawProviders) => { delete rawProviders.acme; delete rawProviders.ACME; for (let providerName in rawProviders) { if (rawProviders.hasOwnProperty(providerName)) { if (!providerName.startsWith('$')) { // BackEnds mapping let bckends = rawProviders[providerName].backends || {}; rawProviders[providerName].backends = Object.keys(bckends) .map(key => { const goodBackend = bckends[key]; goodBackend.backendId = key; return goodBackend; }); // FrontEnds mapping let frtends = rawProviders[providerName].frontends || {}; rawProviders[providerName].frontends = Object.keys(frtends) .map(key => { const goodFrontend = frtends[key]; goodFrontend.frontendId = key; return goodFrontend; }); } } } resolve(rawProviders); }) .catch(reject); }); } }; }
Remove useless ACME tab from UI.
Remove useless ACME tab from UI.
JavaScript
mit
containous/traefik,aantono/traefik,vdemeester/traefik,FriggaHel/traefik,aantono/traefik,ldez/traefik,vdemeester/traefik,containous/traefik,aantono/traefik,dtomcej/traefik,mmatur/traefik,FriggaHel/traefik,aantono/traefik,ldez/traefik,mmatur/traefik,mmatur/traefik,dtomcej/traefik,vdemeester/traefik,mmatur/traefik,SantoDE/traefik,SantoDE/traefik,ldez/traefik,dtomcej/traefik,aantono/traefik,ldez/traefik,FriggaHel/traefik,SantoDE/traefik,dtomcej/traefik,containous/traefik,FriggaHel/traefik,vdemeester/traefik,containous/traefik,SantoDE/traefik
--- +++ @@ -17,6 +17,9 @@ resourceProvider.get() .$promise .then((rawProviders) => { + delete rawProviders.acme; + delete rawProviders.ACME; + for (let providerName in rawProviders) { if (rawProviders.hasOwnProperty(providerName)) { if (!providerName.startsWith('$')) {
f5cdb43607f9894f915e266b634a88e3577cbe05
bin/gh.js
bin/gh.js
#!/usr/bin/env node /* * Copyright 2013-2015, All Rights Reserved. * * Code licensed under the BSD License: * https://github.com/node-gh/gh/blob/master/LICENSE.md * * @author Eduardo Lundgren <edu@rdo.io> */ 'use strict'; var path = require('path'), fs = require('fs'), logger = require('../lib/logger'), pkg = require('../package.json'), semver = require('semver'), tracker = require('../lib/tracker'), configs = require('../lib/configs'); // Check node version if (!isCompatibleNodeVersion()) { logger.error('Please update your NodeJS version: http://nodejs.org/download'); } if (!fs.existsSync(configs.getUserHomePath())) { configs.createGlobalConfig(); } // If configs.PLUGINS_PATH_KEY is undefined, try to cache it before proceeding. if (configs.getConfig()[configs.PLUGINS_PATH_KEY] === undefined) { configs.getNodeModulesGlobalPath(); } // -- Env ------------------------------------------------------------------------------------------ try { process.env.GH_PATH = path.join(__dirname, '../'); require('../lib/cmd.js').run(); } catch (e) { tracker.track('error'); throw e; } function isCompatibleNodeVersion() { return semver.satisfies(process.version, pkg.engines.node); }
#!/usr/bin/env node /* * Copyright 2013-2015, All Rights Reserved. * * Code licensed under the BSD License: * https://github.com/node-gh/gh/blob/master/LICENSE.md * * @author Eduardo Lundgren <edu@rdo.io> */ 'use strict'; var path = require('path'), fs = require('fs'), logger = require('../lib/logger'), pkg = require('../package.json'), semver = require('semver'), tracker = require('../lib/tracker'), configs = require('../lib/configs'); // Check node version function isCompatibleNodeVersion() { return semver.satisfies(process.version, pkg.engines.node); } if (!isCompatibleNodeVersion()) { logger.error('Please update your NodeJS version: http://nodejs.org/download'); } if (!fs.existsSync(configs.getUserHomePath())) { configs.createGlobalConfig(); } // If configs.PLUGINS_PATH_KEY is undefined, try to cache it before proceeding. if (configs.getConfig()[configs.PLUGINS_PATH_KEY] === undefined) { configs.getNodeModulesGlobalPath(); } // -- Env ------------------------------------------------------------------------------------------ try { process.env.GH_PATH = path.join(__dirname, '../'); require('../lib/cmd.js').run(); } catch (e) { tracker.track('error'); throw e; }
Fix linting issue. Source formatting.
Fix linting issue. Source formatting.
JavaScript
bsd-3-clause
oouyang/gh,tomzx/gh,henvic/gh,modulexcite/gh,TomzxForks/gh,tomzx/gh,dustinryerson/gh,oouyang/gh,henvic/gh,modulexcite/gh,TomzxForks/gh,dustinryerson/gh
--- +++ @@ -20,6 +20,10 @@ configs = require('../lib/configs'); // Check node version +function isCompatibleNodeVersion() { + return semver.satisfies(process.version, pkg.engines.node); +} + if (!isCompatibleNodeVersion()) { logger.error('Please update your NodeJS version: http://nodejs.org/download'); } @@ -42,7 +46,3 @@ tracker.track('error'); throw e; } - -function isCompatibleNodeVersion() { - return semver.satisfies(process.version, pkg.engines.node); -}
7df460bdc5be6aadb2a0d20bddf6c2648652639c
modules/ext.pageTriage.util/ext.pageTriage.viewUtil.js
modules/ext.pageTriage.util/ext.pageTriage.viewUtil.js
$( function() { if ( !mw.pageTriage ) { mw.pageTriage = {}; } mw.pageTriage.viewUtil = { // fetch and compile a template, then return it. // args: view, template template: function( arg ) { apiRequest = { 'action': 'pagetriagetemplate', 'view': arg.view, 'format': 'json' }; var templateText; if( arg.template instanceof Array ) { apiRequest.template = arg.template.join('|'); } else { apiRequest.template = arg.template; } $.ajax( { type: 'post', url: mw.util.wikiScript( 'api' ), data: apiRequest, dataType: 'json', async: false, success: function( result ) { if( result.pagetriagetemplate.result == 'success' ) { templateText = result.pagetriagetemplate.template; } } } ); return _.template( templateText ); } }; } );
$( function() { if ( !mw.pageTriage ) { mw.pageTriage = {}; } mw.pageTriage.viewUtil = { // fetch and compile a template, then return it. // args: view, template template: function( arg ) { apiRequest = { 'action': 'pagetriagetemplate', 'view': arg.view, 'format': 'json' }; var templateText; if( arg.template instanceof Array ) { apiRequest.template = arg.template.join('|'); } else { apiRequest.template = arg.template; } $.ajax( { type: 'post', url: mw.util.wikiScript( 'api' ), data: apiRequest, dataType: 'json', async: false, success: function( result ) { if ( result.pagetriagetemplate !== undefined && result.pagetriagetemplate.result === 'success' ) { templateText = result.pagetriagetemplate.template; } } } ); return _.template( templateText ); } }; } );
Make sure some results were returned to avoid error.
Make sure some results were returned to avoid error. Change-Id: Ic788bd1be6711e8c9475909562514d66c6a26d4c
JavaScript
mit
wikimedia/mediawiki-extensions-PageTriage,wikimedia/mediawiki-extensions-PageTriage,wikimedia/mediawiki-extensions-PageTriage
--- +++ @@ -27,9 +27,9 @@ dataType: 'json', async: false, success: function( result ) { - if( result.pagetriagetemplate.result == 'success' ) { + if ( result.pagetriagetemplate !== undefined && result.pagetriagetemplate.result === 'success' ) { templateText = result.pagetriagetemplate.template; - } + } } } );
f1f97709aaed83b7cc3bac30d795650519d417aa
app/assets/javascripts/controller/router.js
app/assets/javascripts/controller/router.js
var AppRouter = Backbone.Router.extend({ routes: { 'topics/:topicId': 'showResults', '*actions': 'defaultAction' }, showResults: function(topicId) { if ($('#topics-container').length === 0) { this.defaultAction(); } var resultsView = new ResultsView(); resultsView.render(); var topicCharts = new TopicCharts([], { topicId: topicId }); topicCharts.fetch({ success: function(response) { var topicChartsView = new TopicChartsView({ collection: response.models }); topicChartsView.render(); // Ensure that the correct option is displayed as 'selected' in the dropdown. $('option:nth-child(' + (parseInt(topicId)+1) + ')').attr('selected', true); } }); }, defaultAction: function() { var homeView = new HomeView(); homeView.render(); } });
var AppRouter = Backbone.Router.extend({ routes: { 'topics/:topicId': 'showResults', '*actions': 'defaultAction' }, showResults: function(topicId) { if ($('#topics-container').length === 0) { this.defaultAction(); } var resultsView = new ResultsView(); resultsView.render(); var topicCharts = new TopicCharts([], { topicId: topicId }); topicCharts.fetch({ success: function(response) { $('option:nth-child(' + (parseInt(topicId)+1) + ')').attr('selected', true); var topicChartsView = new TopicChartsView({ collection: response.models }); topicChartsView.render(); // Ensure that the correct option is displayed as 'selected' in the dropdown. } }); }, defaultAction: function() { var homeView = new HomeView(); homeView.render(); } });
Fix refresh bug by ensuring the correct dropdown choice is selected
Fix refresh bug by ensuring the correct dropdown choice is selected
JavaScript
mit
Jasmine-Feldmann/pollarity,Jasmine-Feldmann/pollarity,zebogen/pollarity,Jasmine-Feldmann/pollarity,zebogen/pollarity,zebogen/pollarity,zebogen/pollarity,Jasmine-Feldmann/pollarity
--- +++ @@ -15,10 +15,10 @@ var topicCharts = new TopicCharts([], { topicId: topicId }); topicCharts.fetch({ success: function(response) { + $('option:nth-child(' + (parseInt(topicId)+1) + ')').attr('selected', true); var topicChartsView = new TopicChartsView({ collection: response.models }); topicChartsView.render(); // Ensure that the correct option is displayed as 'selected' in the dropdown. - $('option:nth-child(' + (parseInt(topicId)+1) + ')').attr('selected', true); } }); },
d28e387391f8ea3aa46932e6ec0ae75f28f2f4ae
app/assets/javascripts/spending_averages.js
app/assets/javascripts/spending_averages.js
$(function () { $('#spending-averages').highcharts({ chart: { type: 'bar' }, title: { text: 'Historic World Population by Region' }, subtitle: { text: 'Source: <a href="https://en.wikipedia.org/wiki/World_population">Wikipedia.org</a>' }, yAxis: { categories: ['Housing', 'Transportation', 'Food', 'Phone', 'Misc'], title: { text: null } }, xAxis: { min: 0, title: { text: 'Population (millions)', align: 'high' }, labels: { overflow: 'justify' } }, tooltip: { valueSuffix: ' millions' }, plotOptions: { bar: { dataLabels: { enabled: true } } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -40, y: 80, floating: true, borderWidth: 1, backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'), shadow: true }, credits: { enabled: false }, series: [{ name: 'Your spending', data: [107, 31, 635, 203, 2] }, { name: 'Average Spending', data: [133, 156, 947, 408, 6] }] }); });
$(function () { $('#spending-averages').highcharts({ chart: { type: 'bar' }, title: { text: 'Historic World Population by Region' }, subtitle: { text: 'Source: <a href="https://en.wikipedia.org/wiki/World_population">Wikipedia.org</a>' }, yAxis: { categories: ['Housing', 'Transportation', 'Food', 'Phone', 'Misc'], title: { text: null } }, xAxis: { min: 0, title: { text: 'Population (millions)', align: 'high' }, labels: { overflow: 'justify' } }, tooltip: { valueSuffix: ' millions' }, plotOptions: { bar: { dataLabels: { enabled: true } } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -40, y: 80, floating: true, borderWidth: 1, backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'), shadow: true }, credits: { enabled: false }, series: [{ name: 'Your spending', data: [107, 31, 635, 203, 5] }, { name: 'Average Spending', data: [35, 15, 7, 3, 30, 10] }] }); });
Add data for national avrages
Add data for national avrages
JavaScript
mit
nyc-cicadas-2015/Can-I-Afford-This,nyc-cicadas-2015/Can-I-Afford-This,nyc-cicadas-2015/Can-I-Afford-This
--- +++ @@ -51,10 +51,10 @@ }, series: [{ name: 'Your spending', - data: [107, 31, 635, 203, 2] + data: [107, 31, 635, 203, 5] }, { name: 'Average Spending', - data: [133, 156, 947, 408, 6] + data: [35, 15, 7, 3, 30, 10] }] }); });
83fed674f7b436cb4c1ba2d91346d15a2b05ad7a
lib/helpers.js
lib/helpers.js
/** * Helper functions that are used in the other modules to reduce the number of times * that code for common tasks is rewritten * * (c) 2013, Greg Malysa <gmalysa@stanford.edu> * Permission to use granted under the terms of the MIT License. See LICENSE for details. */ /** * Retrieves the name for a function, using fn.name to determine what it is, or if no * name is given (i.e. an anonymous function), returns altname. If altname is ALSO not * given, returns (anonymous), as a final default value. * @param fn Function whose name we want to find * @param altname Optional string, name to use if the function was anonymous * @return String name of the function */ module.exports.fname = function(fn, altname) { if (fn.name) return fn.name; if (altname) return altname; return '(anonymous)'; } /** * Checks if a function name should be hidden from the call graph because it is an * internal function. This is a small hack, but it helps remove internals from the * call graph, which simplifies the view for the end user working with his code, all * of which exists outsie the library. * @param name The function name to test * @return bool True if this function name should not be pushed */ module.exports.hide_function = function(name) { if (name == '__after_glue' || name == '__chain_inner') return true; return false; }
/** * Helper functions that are used in the other modules to reduce the number of times * that code for common tasks is rewritten * * (c) 2013, Greg Malysa <gmalysa@stanford.edu> * Permission to use granted under the terms of the MIT License. See LICENSE for details. */ /** * Retrieves the name for a function, using fn.name to determine what it is, or if no * name is given (i.e. an anonymous function), returns altname. If altname is ALSO not * given, returns (anonymous), as a final default value. * @param fn Function whose name we want to find * @param altname Optional string, name to use if the function was anonymous * @return String name of the function */ module.exports.fname = function(fn, altname) { if (fn.name) return fn.name; if (altname) return altname; return '<anonymous>'; } /** * Checks if a function name should be hidden from the call graph because it is an * internal function. This is a small hack, but it helps remove internals from the * call graph, which simplifies the view for the end user working with his code, all * of which exists outsie the library. * @param name The function name to test * @return bool True if this function name should not be pushed */ module.exports.hide_function = function(name) { if (name == '__after_glue' || name == '__chain_inner') return true; return false; }
Rename anonymous to make the styling more like others
Rename anonymous to make the styling more like others
JavaScript
mit
gmalysa/flux-link
--- +++ @@ -19,7 +19,7 @@ return fn.name; if (altname) return altname; - return '(anonymous)'; + return '<anonymous>'; } /**
292eab2125b76d48c175559e8cbd1198ef53510c
app/polymer/src/server/config/babel.prod.js
app/polymer/src/server/config/babel.prod.js
module.exports = { // Don't try to find .babelrc because we want to force this configuration. babelrc: false, presets: [ [ require.resolve('babel-preset-env'), { targets: { browsers: ['last 2 versions', 'safari >= 7'], }, modules: false, }, ], require.resolve('babel-preset-stage-0'), require.resolve('babel-preset-react'), require.resolve('babel-preset-minify'), ], plugins: [ require.resolve('babel-plugin-transform-regenerator'), [ require.resolve('babel-plugin-transform-runtime'), { helpers: true, polyfill: true, regenerator: true, }, ], ], };
module.exports = { // Don't try to find .babelrc because we want to force this configuration. babelrc: false, presets: [ [ require.resolve('babel-preset-env'), { targets: { browsers: ['last 2 versions', 'safari >= 7'], }, modules: false, }, ], require.resolve('babel-preset-stage-0'), require.resolve('babel-preset-react'), [ require.resolve('babel-preset-minify'), { mangle: false, }, ], ], plugins: [ require.resolve('babel-plugin-transform-regenerator'), [ require.resolve('babel-plugin-transform-runtime'), { helpers: true, polyfill: true, regenerator: true, }, ], ], };
Set mangle to false in babel-preset-minify for polymer to fix static build
Set mangle to false in babel-preset-minify for polymer to fix static build
JavaScript
mit
storybooks/storybook,rhalff/storybook,kadirahq/react-storybook,rhalff/storybook,storybooks/storybook,storybooks/react-storybook,rhalff/storybook,storybooks/storybook,rhalff/storybook,rhalff/storybook,storybooks/storybook,storybooks/storybook,rhalff/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook
--- +++ @@ -13,7 +13,12 @@ ], require.resolve('babel-preset-stage-0'), require.resolve('babel-preset-react'), - require.resolve('babel-preset-minify'), + [ + require.resolve('babel-preset-minify'), + { + mangle: false, + }, + ], ], plugins: [ require.resolve('babel-plugin-transform-regenerator'),
42500591eb8048396af67dac18e155e28ba6de03
_attachments/script/paste.js
_attachments/script/paste.js
jQuery(function($) { /* tab insertion handling */ $('#code').keydown(function(e) { if (e.keyCode == 9 && !e.ctrlKey && !e.altKey) { if (this.setSelectionRange) { var start = this.selectionStart; var end = this.selectionEnd; var top = this.scrollTop; this.value = this.value.slice(0, start) + '\t' + this.value.slice(end); this.setSelectionRange(start + 1, start + 1); this.scrollTop = top; e.preventDefault(); } else if (document.selection.createRange) { this.selection = document.selection.createRange(); this.selection.text = '\t'; e.returnValue = false; } } }) $('#paste').click(function(e) { var doc = {}; doc.title = $('#title').val().trim(); doc.content = $('#code').val().trim(); var tags = $('#tags').val().split(','); doc.tags = tags.map(function(t) {return t.trim()}); $Couch.create(doc, './ddoc/_update/create').done(function (data) { window.location.pathname += data._id; }) return false; //e.preventDefault(); }) })
jQuery(function($) { /* tab handling - gemo style */ $('#code').keydown(function(e) { if (e.keyCode == 9 && !e.ctrlKey && !e.altKey) { if (this.setSelectionRange) { var start = this.selectionStart; var end = this.selectionEnd; var top = this.scrollTop; var selected = this.value.slice(start, end); if (e.shiftKey) { // deindent var replacement = selected.replace(/^\t/gm, ''); } else { // indent var replacement = selected.replace(/^/gm, '\t'); } this.value = this.value.slice(0, start) + replacement + this.value.slice(end); this.setSelectionRange(start, end + replacement.length - selected.length ); this.scrollTop = top; e.preventDefault(); } else if (document.selection.createRange) { this.selection = document.selection.createRange(); this.selection.text = '\t'; e.returnValue = false; } } }) $('#paste').click(function(e) { var doc = {}; doc.title = $('#title').val().trim(); doc.content = $('#code').val().trim(); var tags = $('#tags').val().split(','); doc.tags = tags.map(function(t) {return t.trim()}); $Couch.create(doc, './ddoc/_update/create').done(function (data) { window.location.pathname += data._id; }) return false; //e.preventDefault(); }) })
Indent and deindent selected block of text - gemo style
Indent and deindent selected block of text - gemo style
JavaScript
mit
gdamjan/paste-couchapp
--- +++ @@ -1,14 +1,22 @@ jQuery(function($) { - /* tab insertion handling */ + /* tab handling - gemo style */ $('#code').keydown(function(e) { if (e.keyCode == 9 && !e.ctrlKey && !e.altKey) { if (this.setSelectionRange) { var start = this.selectionStart; var end = this.selectionEnd; var top = this.scrollTop; - this.value = this.value.slice(0, start) + '\t' + this.value.slice(end); - this.setSelectionRange(start + 1, start + 1); + var selected = this.value.slice(start, end); + if (e.shiftKey) { + // deindent + var replacement = selected.replace(/^\t/gm, ''); + } else { + // indent + var replacement = selected.replace(/^/gm, '\t'); + } + this.value = this.value.slice(0, start) + replacement + this.value.slice(end); + this.setSelectionRange(start, end + replacement.length - selected.length ); this.scrollTop = top; e.preventDefault(); }
2569ab19ab1ae516451a8018b8911fd82c72e100
array/common-elements-two-arrays.js
array/common-elements-two-arrays.js
// Program that identifies common element(s) that exist within both two arrays function intersection(firstArray, secondArray) { var hashMap = {}; var commonElements = []; // create hashmap with elements of first array as keys arrOne.forEach(function(element) { hashMap[element] = 1; }) }
// Program that identifies common element(s) that exist within both two arrays function intersection(firstArray, secondArray) { var hashMap = {}; var commonElements = []; // create hashmap with elements of first array as keys arrOne.forEach(function(element) { hashMap[element] = 1; }) // use hashmap's O(1) look up time to check if an element in second array exists in the hash (i.e. first array) secondArray.forEach(function(element) { // iterate through entire second array if (hashMap[element] === 1) { // if element in second array exists in hashmap commonElements.push(element); // add matching element into output array } }); }
Use hashmap's O(1) look up time to check if an element in second array exists in the hash (i.e. first array), iterating through entire second array
Use hashmap's O(1) look up time to check if an element in second array exists in the hash (i.e. first array), iterating through entire second array
JavaScript
mit
derekmpham/interview-prep,derekmpham/interview-prep
--- +++ @@ -8,6 +8,13 @@ arrOne.forEach(function(element) { hashMap[element] = 1; }) + + // use hashmap's O(1) look up time to check if an element in second array exists in the hash (i.e. first array) + secondArray.forEach(function(element) { // iterate through entire second array + if (hashMap[element] === 1) { // if element in second array exists in hashmap + commonElements.push(element); // add matching element into output array + } + }); }
79019f506fe1fef40d1edb4e79ab4ca732403d1a
webpack-cfg/alias.js
webpack-cfg/alias.js
module.exports = { resolve: { alias: { // Use non-compiled version of the following libraries 'reselect': 'reselect/src/index.js', // Use non-compiled version of the following react libraries 'react-icon-base': 'react-icon-base/index.js', 'react-collapse': 'react-collapse/src/index.js', 'react-height': 'react-height/src/index.js', 'react-i18next': 'react-i18next/src/index.js', 'react-sortable-hoc': 'react-sortable-hoc/dist/es6' } } }
module.exports = { resolve: { alias: { // Use non-compiled version of the following libraries 'reselect': 'reselect/src/index.js', 'react-redux-firebase': 'react-redux-firebase/es' } } }
Use ES module of react-redux-firebase
Use ES module of react-redux-firebase
JavaScript
mit
jsse-2017-ph23/web-frontend,jsse-2017-ph23/web-frontend,jsse-2017-ph23/web-frontend
--- +++ @@ -3,13 +3,7 @@ alias: { // Use non-compiled version of the following libraries 'reselect': 'reselect/src/index.js', - - // Use non-compiled version of the following react libraries - 'react-icon-base': 'react-icon-base/index.js', - 'react-collapse': 'react-collapse/src/index.js', - 'react-height': 'react-height/src/index.js', - 'react-i18next': 'react-i18next/src/index.js', - 'react-sortable-hoc': 'react-sortable-hoc/dist/es6' + 'react-redux-firebase': 'react-redux-firebase/es' } } }
13893fdda355e822af305b3863c07ceeba88a13a
init.js
init.js
requirejs.config({ paths: { 'jquery': './lib/components/jquery/dist/jquery.min' } }); require( [ 'src/graph' ] , function( Graph ) { var functions = [ function( domGraph, domSource ) { var g1 = new Graph( domGraph ); var serie = g1.newSerie("serieTest") .setLabel( "My serie" ) .autoAxis() .setData( [ [1, 2], [2, 5], [3, 10] ] ) .showMarkers( true ) .setMarkerType( 1 ); var serie = g1.newSerie("serieTest") .setLabel( "My serie 2" ) .autoAxis() .setData( [ [2, 4], [3, 1], [5, 20] ] ) .setLineColor('red'); var legend = g1.makeLegend({ frame: true, frameWidth: 1, frameColor: "green", backgroundColor: "blue" }); g1.redraw( ); g1.drawSeries(); } ] for( var i = 0, l = functions.length ; i < l ; i ++ ) { functions[ i ]("example-1-graph"); $("#example-1-source").html( functions[ i ].toString() ); } } );
requirejs.config({ paths: { 'jquery': './lib/components/jquery/dist/jquery.min' } }); require( [ 'src/graph' ] , function( Graph ) { var functions = [ function( domGraph ) { var graph = new Graph( domGraph ); graph.newSerie("serieTest") .setLabel( "My serie" ) .autoAxis() .setData( [ [1, 2], [2, 5], [3, 10] ] ) .showMarkers( true ) .setMarkerType( 1 ); graph.newSerie("serieTest") .setLabel( "My serie 2" ) .autoAxis() .setData( [ [2, 4], [3, 1], [5, 20] ] ) .setLineColor('red'); graph.makeLegend({ frame: true, frameWidth: 1, frameColor: "green", backgroundColor: "blue" }); graph.redraw( ); graph.drawSeries(); } ] for( var i = 0, l = functions.length ; i < l ; i ++ ) { functions[ i ]("example-1-graph"); $("#example-1-source").html( functions[ i ].toString() ); } } );
Update script for the beauty of it
Update script for the beauty of it
JavaScript
mit
NPellet/jsGraph,andcastillo/graph,NPellet/jsGraph,andcastillo/graph
--- +++ @@ -9,34 +9,36 @@ var functions = [ -function( domGraph, domSource ) { +function( domGraph ) { - var g1 = new Graph( domGraph ); + var graph = new Graph( domGraph ); - var serie = g1.newSerie("serieTest") - .setLabel( "My serie" ) - .autoAxis() - .setData( [ [1, 2], [2, 5], [3, 10] ] ) - .showMarkers( true ) - .setMarkerType( 1 ); + graph.newSerie("serieTest") + .setLabel( "My serie" ) + .autoAxis() + .setData( [ [1, 2], [2, 5], [3, 10] ] ) + .showMarkers( true ) + .setMarkerType( 1 ); - var serie = g1.newSerie("serieTest") - .setLabel( "My serie 2" ) - .autoAxis() - .setData( [ [2, 4], [3, 1], [5, 20] ] ) - .setLineColor('red'); + graph.newSerie("serieTest") + .setLabel( "My serie 2" ) + .autoAxis() + .setData( [ [2, 4], [3, 1], [5, 20] ] ) + .setLineColor('red'); - var legend = g1.makeLegend({ + graph.makeLegend({ frame: true, frameWidth: 1, frameColor: "green", backgroundColor: "blue" }); - g1.redraw( ); - g1.drawSeries(); + graph.redraw( ); + graph.drawSeries(); } + + ]
5cfea2ffb89d3f81e20bb36dd5341b281fa78ada
app/assets/javascripts/scripts.js
app/assets/javascripts/scripts.js
$(function(){ $(".tablesorter").tablesorter(); $("tr[data-link]").click(function() { window.location = $(this).data("link") }); console.log('Scripts loaded.'); });
var tablesort = function() { $(".tablesorter").tablesorter(); console.log('Tablesorter loaded.'); }; $(document).on('turbolinks:load', tablesort);
Load js on turbolink refresh
Load js on turbolink refresh
JavaScript
mit
greenvault/wahlbezirke,greenvault/wahlbezirke,greenvault/wahlbezirke
--- +++ @@ -1,7 +1,6 @@ -$(function(){ +var tablesort = function() { $(".tablesorter").tablesorter(); - $("tr[data-link]").click(function() { - window.location = $(this).data("link") - }); - console.log('Scripts loaded.'); -}); + console.log('Tablesorter loaded.'); +}; + +$(document).on('turbolinks:load', tablesort);
324b5aba5334b203ce1a622471b41427d0b0afa6
addon/models/file-version.js
addon/models/file-version.js
import DS from 'ember-data'; import OsfModel from './osf-model'; /** * @module ember-osf * @submodule models */ /** * Model for OSF APIv2 file versions. Primarily used in relationship fields. * This model is used for basic file version metadata. To interact with file contents directly, see the `file-manager` service. * For field and usage information, see: * * https://api.osf.io/v2/docs/#!/v2/File_Versions_List_GET * * https://api.osf.io/v2/docs/#!/v2/File_Version_Detail_GET * @class FileVersion */ export default OsfModel.extend({ size: DS.attr('number'), contentType: DS.attr('fixstring') });
import DS from 'ember-data'; import OsfModel from './osf-model'; /** * @module ember-osf * @submodule models */ /** * Model for OSF APIv2 file versions. Primarily used in relationship fields. * This model is used for basic file version metadata. To interact with file contents directly, see the `file-manager` service. * For field and usage information, see: * * https://api.osf.io/v2/docs/#!/v2/File_Versions_List_GET * * https://api.osf.io/v2/docs/#!/v2/File_Version_Detail_GET * @class FileVersion */ export default OsfModel.extend({ size: DS.attr('number'), dateCreated: DS.attr('date'), contentType: DS.attr('fixstring') });
Add dateCreated to file version model
Add dateCreated to file version model
JavaScript
apache-2.0
jamescdavis/ember-osf,binoculars/ember-osf,crcresearch/ember-osf,baylee-d/ember-osf,CenterForOpenScience/ember-osf,binoculars/ember-osf,jamescdavis/ember-osf,chrisseto/ember-osf,baylee-d/ember-osf,chrisseto/ember-osf,CenterForOpenScience/ember-osf,crcresearch/ember-osf
--- +++ @@ -17,5 +17,6 @@ */ export default OsfModel.extend({ size: DS.attr('number'), + dateCreated: DS.attr('date'), contentType: DS.attr('fixstring') });
870d438d162750d7b3b0586702ec551352200c10
client/app/scripts/services/meta-machine.js
client/app/scripts/services/meta-machine.js
angular .module('app') .factory('MetaMachine', function($rootScope) { var MetaMachine = { title: function(pageTitle, baseTitle) { baseTitle = typeof baseTitle != 'undefined' ? baseTitle : "Rootstrikers"; $rootScope.title = typeof pageTitle != 'undefined' ? pageTitle + " | " + baseTitle : baseTitle; }, description: function(description) { $rootScope.metaDescription = description || "We fight the corrupting influence of money in politics"; } }; return MetaMachine; });
angular .module('app') .factory('MetaMachine', function($rootScope) { var metaDefaults = { metaTitle: "Home | Rootstrikers", metaDescription: "We fight the corrupting influence of money in politics", metaImage: "http://facultycreative.com/img/icons/facultyicon114.png", metaUrl: "http://rs002dev.herokuapp.com/" }; (function setDefaults() { _.each(metaDefaults, function(val, key) { $rootScope[key] = val; }); })(); var MetaMachine = { title: function(pageTitle, baseTitle) { baseTitle = typeof baseTitle != 'undefined' ? baseTitle : "Rootstrikers"; $rootScope.metaTitle = typeof pageTitle != 'undefined' ? pageTitle + " | " + baseTitle : baseTitle; }, description: function(description) { $rootScope.metaDescription = description || "We fight the corrupting influence of money in politics"; }, image: function(url) { $rootScope.metaImage = url || "http://facultycreative.com/img/icons/facultyicon114.png"; }, url: function(url) { $rootScope.metaUrl = url || "http://rs002dev.herokuapp.com/"; } }; return MetaMachine; });
Update MetaMachine directive to add a metaImage tag and metaUrl tag (OG tags for Facebook). Directive now also sets page defaults.
Update MetaMachine directive to add a metaImage tag and metaUrl tag (OG tags for Facebook). Directive now also sets page defaults.
JavaScript
mit
brettshollenberger/rootstrikers,brettshollenberger/rootstrikers
--- +++ @@ -1,13 +1,31 @@ angular .module('app') .factory('MetaMachine', function($rootScope) { + + var metaDefaults = { + metaTitle: "Home | Rootstrikers", + metaDescription: "We fight the corrupting influence of money in politics", + metaImage: "http://facultycreative.com/img/icons/facultyicon114.png", + metaUrl: "http://rs002dev.herokuapp.com/" + }; + + (function setDefaults() { + _.each(metaDefaults, function(val, key) { $rootScope[key] = val; }); + })(); + var MetaMachine = { title: function(pageTitle, baseTitle) { baseTitle = typeof baseTitle != 'undefined' ? baseTitle : "Rootstrikers"; - $rootScope.title = typeof pageTitle != 'undefined' ? pageTitle + " | " + baseTitle : baseTitle; + $rootScope.metaTitle = typeof pageTitle != 'undefined' ? pageTitle + " | " + baseTitle : baseTitle; }, description: function(description) { $rootScope.metaDescription = description || "We fight the corrupting influence of money in politics"; + }, + image: function(url) { + $rootScope.metaImage = url || "http://facultycreative.com/img/icons/facultyicon114.png"; + }, + url: function(url) { + $rootScope.metaUrl = url || "http://rs002dev.herokuapp.com/"; } }; return MetaMachine;
7afc12f3526dd6ff2dcfc6d57b2838d59c557994
common/components/stores/NavigationStore.js
common/components/stores/NavigationStore.js
// @flow import type { SectionType } from "../enums/Section.js"; import { ReduceStore } from "flux/utils"; import UniversalDispatcher from "./UniversalDispatcher.js"; import { Record } from "immutable"; import Section from "../enums/Section.js"; import url from "../utils/url.js"; export type NavigationActionType = { type: "SET_SECTION", section: SectionType, url: string, fromUrl: ?boolean, }; // TODO: Remove showsplash argument const DEFAULT_STATE = { section: Section.FindProjects, url: url.section(Section.FindProjects, { showSplash: 1 }), }; class State extends Record(DEFAULT_STATE) { section: SectionType; url: string; } class NavigationStore extends ReduceStore<State> { constructor(): void { super(UniversalDispatcher); } getInitialState(): State { const state = new State(); return state; } reduce(state: State, action: NavigationActionType): State { switch (action.type) { case "SET_SECTION": if (action.fromUrl) { history.replaceState({}, "", action.url); } else { history.pushState({}, "", action.url); } return state.set("section", action.section); default: (action: empty); return state; } } getSection(): SectionType { return this.getState().section; } } export default new NavigationStore();
// @flow import type { SectionType } from "../enums/Section.js"; import { ReduceStore } from "flux/utils"; import UniversalDispatcher from "./UniversalDispatcher.js"; import { Record } from "immutable"; import Section from "../enums/Section.js"; import url from "../utils/url.js"; export type NavigationActionType = { type: "SET_SECTION", section: SectionType, url: string, fromUrl: ?boolean, }; // TODO: Remove showsplash argument const DEFAULT_STATE = { section: Section.Home, url: url.section(Section.Home), }; class State extends Record(DEFAULT_STATE) { section: SectionType; url: string; } class NavigationStore extends ReduceStore<State> { constructor(): void { super(UniversalDispatcher); } getInitialState(): State { const state = new State(); return state; } reduce(state: State, action: NavigationActionType): State { switch (action.type) { case "SET_SECTION": if (action.fromUrl) { history.replaceState({}, "", action.url); } else { history.pushState({}, "", action.url); } return state.set("section", action.section); default: (action: empty); return state; } } getSection(): SectionType { return this.getState().section; } } export default new NavigationStore();
Change default section to Home
Change default section to Home
JavaScript
mit
DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange
--- +++ @@ -16,8 +16,8 @@ }; // TODO: Remove showsplash argument const DEFAULT_STATE = { - section: Section.FindProjects, - url: url.section(Section.FindProjects, { showSplash: 1 }), + section: Section.Home, + url: url.section(Section.Home), }; class State extends Record(DEFAULT_STATE) {
083e928a4b8260b92646fe2ce14a34b6e67c8bb4
app/initializers/clock-service.js
app/initializers/clock-service.js
// Based on "Continous Redrawing of Objects" // http://emberjs.com/guides/cookbook/working_with_objects/continuous_redrawing_of_views/ // // #pulse is updated every ~15-seconds // var ClockService = Ember.Object.extend({ pulse: Ember.computed.oneWay('_minutes').readOnly(), tick: function () { var clock = this; Ember.run.later(function () { var minutes = clock.get('_minutes'); if (typeof minutes === 'number') { clock.set('_minutes', minutes + (1/4)); } }, 15000); }.observes('_minutes').on('init'), _minutes: 0 }); var ClockServiceInitializer = { name: "clock-service", initialize: function(container, application) { container.register('clock:service', ClockService, { singleton: true }); application.inject('view', 'clock', 'clock:service'); } }; export default ClockServiceInitializer;
// Based on "Continous Redrawing of Objects" // http://emberjs.com/guides/cookbook/working_with_objects/continuous_redrawing_of_views/ // // #pulse is updated every ~15-seconds // var ClockService = Ember.Object.extend({ pulse: Ember.computed.oneWay('_minutes').readOnly(), tick: function () { var clock = this; // This should be the idiomatic `Ember.run.later` but that // blocks acceptance tests. This is a workaround from // https://github.com/emberjs/ember.js/issues/3008 setTimeout(function() { Em.run(function() { var minutes = clock.get('_minutes'); if (typeof minutes === 'number') { clock.set('_minutes', minutes + (1/4)); } }) }, 15000); }.observes('_minutes').on('init'), _minutes: 0 }); var ClockServiceInitializer = { name: "clock-service", initialize: function(container, application) { container.register('clock:service', ClockService, { singleton: true }); application.inject('view', 'clock', 'clock:service'); } }; export default ClockServiceInitializer;
Fix for stalling acceptance tests.
Fix for stalling acceptance tests.
JavaScript
mit
substantial/substantial-dash-client
--- +++ @@ -7,11 +7,16 @@ pulse: Ember.computed.oneWay('_minutes').readOnly(), tick: function () { var clock = this; - Ember.run.later(function () { - var minutes = clock.get('_minutes'); - if (typeof minutes === 'number') { - clock.set('_minutes', minutes + (1/4)); - } + // This should be the idiomatic `Ember.run.later` but that + // blocks acceptance tests. This is a workaround from + // https://github.com/emberjs/ember.js/issues/3008 + setTimeout(function() { + Em.run(function() { + var minutes = clock.get('_minutes'); + if (typeof minutes === 'number') { + clock.set('_minutes', minutes + (1/4)); + } + }) }, 15000); }.observes('_minutes').on('init'), _minutes: 0
6eed7ab4ff7ec2b9834153874d3b8813d0eda54f
src/lib/addCustomMediaQueries.js
src/lib/addCustomMediaQueries.js
import _ from 'lodash' import postcss from 'postcss' function buildMediaQuery(breakpoint) { if (_.isString(breakpoint)) { breakpoint = {min: breakpoint} } return _(breakpoint).map((value, feature) => { feature = _.get( { min: 'min-width', max: 'max-width', }, feature, feature ) return `(${feature}: ${value})` }).join(' and ') } export default function(options) { let breakpoints = options.breakpoints return function(css) { Object.keys(breakpoints).forEach(breakpoint => { const variableName = `--breakpoint-${breakpoint}` const mediaQuery = buildMediaQuery(breakpoints[breakpoint]) const rule = postcss.atRule({ name: 'custom-media', params: `${variableName} ${mediaQuery}`, }) css.prepend(rule) }) } }
import _ from 'lodash' import postcss from 'postcss' function buildMediaQuery(breakpoints) { if (_.isString(breakpoints)) { breakpoints = {min: breakpoints} } if (!_.isArray(breakpoints)) { breakpoints = [breakpoints] } return _(breakpoints).map((breakpoint) => { return _(breakpoint).map((value, feature) => { feature = _.get( { min: 'min-width', max: 'max-width', }, feature, feature ) return `(${feature}: ${value})` }).join(' and ') }).join(', ') } export default function(options) { let breakpoints = options.breakpoints return function(css) { Object.keys(breakpoints).forEach(breakpoint => { const variableName = `--breakpoint-${breakpoint}` const mediaQuery = buildMediaQuery(breakpoints[breakpoint]) const rule = postcss.atRule({ name: 'custom-media', params: `${variableName} ${mediaQuery}`, }) css.prepend(rule) }) } }
Add ability to define more complex breakpoints.
Add ability to define more complex breakpoints.
JavaScript
mit
tailwindlabs/tailwindcss,tailwindlabs/tailwindcss,tailwindcss/tailwindcss,tailwindlabs/tailwindcss
--- +++ @@ -1,21 +1,26 @@ import _ from 'lodash' import postcss from 'postcss' -function buildMediaQuery(breakpoint) { - if (_.isString(breakpoint)) { - breakpoint = {min: breakpoint} +function buildMediaQuery(breakpoints) { + if (_.isString(breakpoints)) { + breakpoints = {min: breakpoints} } - return _(breakpoint).map((value, feature) => { - feature = _.get( - { - min: 'min-width', - max: 'max-width', - }, - feature, - feature - ) - return `(${feature}: ${value})` - }).join(' and ') + if (!_.isArray(breakpoints)) { + breakpoints = [breakpoints] + } + return _(breakpoints).map((breakpoint) => { + return _(breakpoint).map((value, feature) => { + feature = _.get( + { + min: 'min-width', + max: 'max-width', + }, + feature, + feature + ) + return `(${feature}: ${value})` + }).join(' and ') + }).join(', ') } export default function(options) {
9ee00c1b2b9bb79e664d5f7ce0b9ce78478d7c1d
src/hooks/useDatePicker.js
src/hooks/useDatePicker.js
/* eslint-disable import/prefer-default-export */ import React from 'react'; /** * Hook to simplify the use of the native date picker component by unwrapping * the callback event and firing the callback only when the date is changing, * providing a value to conditionally render the native picker and a callback * to set the render value. * * Pass an onChange callback which will be called when a new date is selected * from the datepicker and not when cancelled or dismissed, with a JS date object * rather than a nativeEvent. * * @param {Func} callback callback * @return {Array} [ * datePickerIsOpen: boolean indicator whether the date picker is open. * openDatePicker: Callback function to set the datePickerIsOpen to true. * datePickerCallback: Wrapped callback, triggered on changing the date in the picker, * returning a JS date object. * ] */ export const useDatePicker = onChangeCallback => { const [datePickerIsOpen, setDatePickerIsOpen] = React.useState(false); const datePickerCallback = React.useCallback( event => { setDatePickerIsOpen(false); const { type, nativeEvent } = event; if (type === 'set' && onChangeCallback) { const { timestamp } = nativeEvent; onChangeCallback(new Date(timestamp)); } }, [onChangeCallback] ); const openDatePicker = React.useCallback(() => { setDatePickerIsOpen(true); }, []); return [datePickerIsOpen, openDatePicker, datePickerCallback]; };
/* eslint-disable import/prefer-default-export */ import React from 'react'; /** * Hook to simplify the use of the native date picker component by unwrapping * the callback event and firing the callback only when the date is changing, * providing a value to conditionally render the native picker and a callback * to set the render value. * * Pass an onChange callback which will be called when a new date is selected * from the datepicker and not when cancelled or dismissed, with a JS date object * rather than a nativeEvent. * * @param {Func} callback callback * @return {Array} [ * datePickerIsOpen: boolean indicator whether the date picker is open. * openDatePicker: Callback function to set the datePickerIsOpen to true. * datePickerCallback: Wrapped callback, triggered on changing the date in the picker, * returning a JS date object. * ] */ export const useDatePicker = onChangeCallback => { const [datePickerIsOpen, setDatePickerIsOpen] = React.useState(false); const datePickerCallback = React.useCallback( event => { setDatePickerIsOpen(false); const { type, nativeEvent } = event; if (type === 'set' && onChangeCallback) { const { timestamp } = nativeEvent; onChangeCallback(timestamp); } }, [onChangeCallback] ); const openDatePicker = React.useCallback(() => { setDatePickerIsOpen(true); }, []); return [datePickerIsOpen, openDatePicker, datePickerCallback]; };
Add pass timestamp rather than date object
Add pass timestamp rather than date object
JavaScript
mit
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
--- +++ @@ -28,7 +28,8 @@ const { type, nativeEvent } = event; if (type === 'set' && onChangeCallback) { const { timestamp } = nativeEvent; - onChangeCallback(new Date(timestamp)); + + onChangeCallback(timestamp); } }, [onChangeCallback]
e186fce706c2b219bc3c5451ee8910baaf98400c
src/data/teams/selectors.js
src/data/teams/selectors.js
import { createSelector } from 'reselect'; import { denormalize } from 'normalizr'; import mapValues from 'lodash/mapValues'; import teamSchema from './schema'; const selectPlayers = state => state.data.players; export const selectTeam = (state, props) => state.data.teams.byId[props.teamId]; export const selectTeams = state => state.data.teams; export const selectTeamPlayerItems = (state, props) => state.data.teams.byId[props.teamId].players; export const selectDenormalizedTeams = createSelector( [selectTeams, selectPlayers], (teams, players) => { const data = { teams, players }; return denormalize( Object.keys(teams.byId), [teamSchema], { ...mapValues(data, value => value.byId) }, ); }, );
import { createSelector } from 'reselect'; import { denormalize } from 'normalizr'; import mapValues from 'lodash/mapValues'; import teamSchema from './schema'; const selectPlayers = state => state.data.players; export const selectTeam = (state, props) => state.data.teams.byId[props.teamId]; export const selectTeams = state => state.data.teams; export const selectTeamPlayerItems = (state, props) => { const team = selectTeam(state, props); return team ? team.players : []; }; export const selectDenormalizedTeams = createSelector( [selectTeams, selectPlayers], (teams, players) => { const data = { teams, players }; return denormalize( Object.keys(teams.byId), [teamSchema], { ...mapValues(data, value => value.byId) }, ); }, );
Reset response errors when a new tactic is created
Reset response errors when a new tactic is created
JavaScript
mit
m-mik/tactic-editor,m-mik/tactic-editor
--- +++ @@ -8,7 +8,11 @@ export const selectTeam = (state, props) => state.data.teams.byId[props.teamId]; export const selectTeams = state => state.data.teams; -export const selectTeamPlayerItems = (state, props) => state.data.teams.byId[props.teamId].players; + +export const selectTeamPlayerItems = (state, props) => { + const team = selectTeam(state, props); + return team ? team.players : []; +}; export const selectDenormalizedTeams = createSelector( [selectTeams, selectPlayers],
f1ae689d7dcffb5187b61f78dbed65d54322cbfe
quickstart/node/autopilot/query-task/query_task.3.x.js
quickstart/node/autopilot/query-task/query_task.3.x.js
// Download the helper library from https://www.twilio.com/docs/python/install // Your Account Sid and Auth Token from twilio.com/console const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const authToken = 'your_auth_token'; const client = require('twilio')(accountSid, authToken); // Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list query = client.preview.understand.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .queries .create({ language: 'en-US', query: 'Tell me a joke', }) .then(query => console.log(query.results.task)) .done();
// Download the helper library https://www.twilio.com/docs/libraries/node#install // Your Account Sid and Auth Token from twilio.com/console const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const authToken = 'your_auth_token'; const client = require('twilio')(accountSid, authToken); // Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list query = client.preview.understand.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .queries .create({ language: 'en-US', query: 'Tell me a joke', }) .then(query => console.log(query.results.task)) .done();
Update comment to point to node library install
Update comment to point to node library install
JavaScript
mit
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets
--- +++ @@ -1,4 +1,4 @@ -// Download the helper library from https://www.twilio.com/docs/python/install +// Download the helper library https://www.twilio.com/docs/libraries/node#install // Your Account Sid and Auth Token from twilio.com/console const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
cd03e20f518ade3d7875a32c040dd47cedbef360
rikitrakiws.js
rikitrakiws.js
var log4js = require('log4js'); var logger = log4js.getLogger(); var express = require('express'); var favicon = require('serve-favicon'); var bodyParser = require('body-parser'); var port = process.env.OPENSHIFT_NODEJS_PORT || 3000; var ipaddress = process.env.OPENSHIFT_NODEJS_IP; var loglevel = process.env.LOGLEVEL || 'DEBUG'; var app = express(); app.use(favicon(__dirname + '/public/favicon.ico')); logger.setLevel(loglevel); app.use(express.static('public')); app.use(log4js.connectLogger(log4js.getLogger('http'), { level: 'auto' })); app.use(bodyParser.json({limit: '5mb'})); app.use(bodyParser.raw({limit: '10mb', type: 'image/jpeg'})); app.use('/api/', require('./routes/').router); /* app.use(function(error, req, res, next) { if (error) { logger.error('InvalidInput', error.message); res.status(error.status).send({error: 'InvalidInput', description: error.message}); } else { next(); } }); */ app.listen(port, ipaddress, function () { logger.info('starting rikitrakiws', this.address()); });
var log4js = require('log4js'); var logger = log4js.getLogger(); var express = require('express'); var favicon = require('serve-favicon'); var bodyParser = require('body-parser'); var port = process.env.OPENSHIFT_NODEJS_PORT || 3000; var ipaddress = process.env.OPENSHIFT_NODEJS_IP; var loglevel = process.env.LOGLEVEL || 'DEBUG'; var app = express(); app.use(favicon(__dirname + '/public/favicon.ico')); logger.setLevel(loglevel); app.use(express.static('public')); app.use(log4js.connectLogger(log4js.getLogger('http'), { level: 'auto' })); app.use(bodyParser.json({limit: '5mb'})); app.use(bodyParser.raw({limit: '10mb', type: 'image/jpeg'})); app.use('/api/', require('./routes/').router); app.use(function (req, res, next) { res.removeHeader("WWW-Authenticate"); next(); }); /* app.use(function(error, req, res, next) { if (error) { logger.error('InvalidInput', error.message); res.status(error.status).send({error: 'InvalidInput', description: error.message}); } else { next(); } }); */ app.listen(port, ipaddress, function () { logger.info('starting rikitrakiws', this.address()); });
Drop header to avoid auth browser popup
Drop header to avoid auth browser popup
JavaScript
mit
jimmyangel/rikitrakiws,jimmyangel/rikitrakiws
--- +++ @@ -20,6 +20,11 @@ app.use('/api/', require('./routes/').router); +app.use(function (req, res, next) { + res.removeHeader("WWW-Authenticate"); + next(); +}); + /* app.use(function(error, req, res, next) { if (error) { logger.error('InvalidInput', error.message);
eb13bf4ff0d9b2f74e1de34418f0d7250fd537cc
rules/style.js
rules/style.js
module.exports = { rules: { // require trailing comma in multilines 'comma-dangle': [2, 'always-multiline'], // require function expressions to have a name 'func-names': 0, // require or disallow use of semicolons instead of ASI 'semi': [2, 'never'], // require or disallow space before function opening parenthesis 'space-before-function-paren': [2, 'never'], // require or disallow Yoda conditions 'yoda': [2, 'never'] } }
module.exports = { rules: { // disallow trailing commas in object literals 'comma-dangle': [2, 'never'], // require function expressions to have a name 'func-names': 0, // require or disallow use of semicolons instead of ASI 'semi': [2, 'never'], // require or disallow space before function opening parenthesis 'space-before-function-paren': [2, 'never'], // require or disallow Yoda conditions 'yoda': [2, 'never'] } }
Revert "[WV][000000] Allow trailing comma"
Revert "[WV][000000] Allow trailing comma"
JavaScript
mit
rentpath/eslint-config-rentpath
--- +++ @@ -1,7 +1,7 @@ module.exports = { rules: { - // require trailing comma in multilines - 'comma-dangle': [2, 'always-multiline'], + // disallow trailing commas in object literals + 'comma-dangle': [2, 'never'], // require function expressions to have a name 'func-names': 0, // require or disallow use of semicolons instead of ASI
cc8f8d2f523a0c440bbd819610d860f86ba9d383
src/modules/findBestIcon.js
src/modules/findBestIcon.js
function sortIconsBySize(icons) { return icons.sort((a, b) => { if (a.data.size < b.data.size) { return 1; } else { return -1; } }); } function findBestIcon(icons) { return sortIconsBySize(icons)[0]; } module.exports = findBestIcon;
function sortIconsBySize(icons) { return icons.sort((a, b) => { if (a.size < b.size) { return 1; } else { return -1; } }); } function findBestIcon(icons) { return sortIconsBySize(icons)[0]; } module.exports = findBestIcon;
Fix bug where icons are not sorted properly
Fix bug where icons are not sorted properly
JavaScript
mit
jiahaog/page-icon
--- +++ @@ -1,6 +1,6 @@ function sortIconsBySize(icons) { return icons.sort((a, b) => { - if (a.data.size < b.data.size) { + if (a.size < b.size) { return 1; } else { return -1;
f4f275c057152f37855e6eb23945d07509cb2af0
res/loader.js
res/loader.js
browser.storage.local.get( [ 'bgcolor', 'textcolor', 'messages' ] ).then( function ( r ) { var m = r.messages.split( '\n' ); m = m[ Math.floor( Math.random() * m.length ) ]; document.querySelector( 'h1' ).textContent = m; document.body.style.backgroundColor = r.bgcolor; document.body.style.color = r.textcolor; console.log( r ); } );
browser.storage.local.get( [ 'bgcolor', 'textcolor', 'messages' ] ).then( function ( r ) { var m = r.messages || 'Breathe'; m = m.split( '\n' ); m = m[ Math.floor( Math.random() * m.length ) ]; document.querySelector( 'h1' ).textContent = m; document.body.style.backgroundColor = r.bgcolor || '#fff'; document.body.style.color = r.textcolor || '#b3b3b3'; console.log( r ); } );
Load sane settings if there are none
Load sane settings if there are none
JavaScript
mit
prtksxna/breathe,prtksxna/breathe
--- +++ @@ -1,9 +1,11 @@ browser.storage.local.get( [ 'bgcolor', 'textcolor', 'messages' ] ).then( function ( r ) { - var m = r.messages.split( '\n' ); + var m = r.messages || 'Breathe'; + + m = m.split( '\n' ); m = m[ Math.floor( Math.random() * m.length ) ]; document.querySelector( 'h1' ).textContent = m; - document.body.style.backgroundColor = r.bgcolor; - document.body.style.color = r.textcolor; + document.body.style.backgroundColor = r.bgcolor || '#fff'; + document.body.style.color = r.textcolor || '#b3b3b3'; console.log( r ); } );
6f3cd5a14d32b86bec9c0892a75d367e89420a05
native/components/list-loading-indicator.react.js
native/components/list-loading-indicator.react.js
// @flow import { connect } from 'lib/utils/redux-utils'; import * as React from 'react'; import { ActivityIndicator } from 'react-native'; import type { AppState } from '../redux/redux-setup'; import type { Colors } from '../themes/colors'; import { colorsSelector, styleSelector } from '../themes/colors'; type Props = {| // Redux state colors: Colors, styles: typeof styles, |}; function ListLoadingIndicator(props: Props) { const { listBackgroundLabel } = props.colors; return ( <ActivityIndicator color={listBackgroundLabel} size="large" style={props.styles.loadingIndicator} /> ); } const styles = { loadingIndicator: { backgroundColor: 'listBackground', flex: 1, padding: 10, }, }; const stylesSelector = styleSelector(styles); export default connect((state: AppState) => ({ colors: colorsSelector(state), styles: stylesSelector(state), }))(ListLoadingIndicator);
// @flow import * as React from 'react'; import { ActivityIndicator } from 'react-native'; import { useStyles, useColors } from '../themes/colors'; function ListLoadingIndicator() { const styles = useStyles(unboundStyles); const colors = useColors(); const { listBackgroundLabel } = colors; return ( <ActivityIndicator color={listBackgroundLabel} size="large" style={styles.loadingIndicator} /> ); } const unboundStyles = { loadingIndicator: { backgroundColor: 'listBackground', flex: 1, padding: 10, }, }; export default ListLoadingIndicator;
Use hook instead of connect functions and HOC in ListLoadingIndicator
[native] Use hook instead of connect functions and HOC in ListLoadingIndicator Test Plan: Flow Reviewers: ashoat, palys-swm Reviewed By: ashoat Subscribers: zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D483
JavaScript
bsd-3-clause
Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal
--- +++ @@ -1,39 +1,29 @@ // @flow -import { connect } from 'lib/utils/redux-utils'; import * as React from 'react'; import { ActivityIndicator } from 'react-native'; -import type { AppState } from '../redux/redux-setup'; -import type { Colors } from '../themes/colors'; -import { colorsSelector, styleSelector } from '../themes/colors'; +import { useStyles, useColors } from '../themes/colors'; -type Props = {| - // Redux state - colors: Colors, - styles: typeof styles, -|}; -function ListLoadingIndicator(props: Props) { - const { listBackgroundLabel } = props.colors; +function ListLoadingIndicator() { + const styles = useStyles(unboundStyles); + const colors = useColors(); + const { listBackgroundLabel } = colors; return ( <ActivityIndicator color={listBackgroundLabel} size="large" - style={props.styles.loadingIndicator} + style={styles.loadingIndicator} /> ); } -const styles = { +const unboundStyles = { loadingIndicator: { backgroundColor: 'listBackground', flex: 1, padding: 10, }, }; -const stylesSelector = styleSelector(styles); -export default connect((state: AppState) => ({ - colors: colorsSelector(state), - styles: stylesSelector(state), -}))(ListLoadingIndicator); +export default ListLoadingIndicator;
b9fa1633356d88a60e39b7e29f612d6f0a2901b0
js/population.js
js/population.js
function Population(size) { var agents = new Array(size); var genomes = new Array(size); for (i = 0; i < size; i++) { var prob = Math.random(); if (prob <= 0.33) { genomes[i] = new Genome(1,0,0); } elseif (prob > 0.33 && prob <= 0.67) { genomes[i] = new Genome(0,1,0); } else genomes[i] = new Genome(0,0,1); agents[i] = new Agent(genomes[i]); } this.pop = agents; } // "T" for tournament, "R" for roulette wheel var parentmethod = "T"; Population.prototype.parentselection = function() { // Get all fitness functions from parents if (parentmethod == "T") { // Choose parents // return parents } else if (parentmethod == "R") { } }
function Population(size) { var agents = new Array(size); var genomes = new Array(size); for (i = 0; i < size; i++) { var prob = Math.random(); if (prob < 0.33) { genomes[i] = new Genome(1,0,0); } else if (prob >= 0.33 && prob < 0.67) { genomes[i] = new Genome(0,1,0); } else genomes[i] = new Genome(0,0,1); agents[i] = new Agent(genomes[i]); } this.pop = agents; } // "T" for tournament, "R" for roulette wheel var parentmethod = "T"; Population.prototype.parentselection = function() { // Get all fitness functions from parents var fitness = new Array(this.pop.length); for (i = 0; i < this.pop.length; i++) { fitness[i] = this.pop[i].getFitness(); } // Tournament selection if (parentmethod == "T") { // Choose k individuals from population at random for (p = 0; p < 4; p++) { var k = 3; var parents = new Array(k); for (i = 0; i < tournament; i ++) { parents[i] = Math.round(Math.random() * this.pop.length); } } // return parents } // Roulette wheel selection else if (parentmethod == "R") { } } Population.prototype.update = function() { }
Edit parent selection, update gamemanager to Senna's version
Edit parent selection, update gamemanager to Senna's version
JavaScript
mit
Moorkopsoesje/natural-computing,Moorkopsoesje/natural-computing,Moorkopsoesje/natural-computing
--- +++ @@ -3,10 +3,10 @@ var genomes = new Array(size); for (i = 0; i < size; i++) { var prob = Math.random(); - if (prob <= 0.33) { + if (prob < 0.33) { genomes[i] = new Genome(1,0,0); } - elseif (prob > 0.33 && prob <= 0.67) { + else if (prob >= 0.33 && prob < 0.67) { genomes[i] = new Genome(0,1,0); } else genomes[i] = new Genome(0,0,1); @@ -20,14 +20,31 @@ Population.prototype.parentselection = function() { // Get all fitness functions from parents + var fitness = new Array(this.pop.length); + for (i = 0; i < this.pop.length; i++) { + fitness[i] = this.pop[i].getFitness(); + } + // Tournament selection if (parentmethod == "T") { + // Choose k individuals from population at random + for (p = 0; p < 4; p++) { + var k = 3; + var parents = new Array(k); + for (i = 0; i < tournament; i ++) { + parents[i] = Math.round(Math.random() * this.pop.length); + } + + } + // return parents + } - // Choose parents + // Roulette wheel selection + else if (parentmethod == "R") { + + } +} - // return parents - } - else if (parentmethod == "R") { - - } +Population.prototype.update = function() { + }
3989a97b750c34da3963f8edb0154167fe99f2bc
addon/components/jqui-datepicker/component.js
addon/components/jqui-datepicker/component.js
import Ember from 'ember'; import jquiWidget from 'ember-cli-jquery-ui/mixins/jqui-widget'; export default Ember.TextField.extend(jquiWidget, { uiType: 'datepicker', uiOptions: ["altField", "altFormat", "appendText", "autoSize", "beforeShow", "beforeShowDay", "buttonImage", "buttonImageOnly", "buttonText", "calculateWeek", "changeMonth", "changeYear", "closeText", "constrainInput", "currentText", "dateFormat", "dayNames", "dayNamesMin", "dayNamesShort", "defaultDate", "duration", "firstDay", "gotoCurrent", "hideIfNoPrevNext", "isRTL", "maxDate", "minDate", "monthNames", "monthNamesShort", "navigationAsDateFormat", "nextText", "numberOfMonths", "onChangeMonthYear", "onClose", "onSelect", "prevText", "selectOtherMonths", "shortYearCutoff", "showAnim", "showButtonPanel", "showCurrentAtPos", "showMonthAfterYear", "showOn", "showOptions", "showOtherMonths", "showWeek", "stepMonths", "weekHeader", "yearRange", "yearSuffix"], uiEvents: ['onChangeMonthYear', 'onClose', 'onSelect'] });
import Ember from 'ember'; import jquiWidget from 'ember-cli-jquery-ui/mixins/jqui-widget'; export default Ember.TextField.extend(jquiWidget, { uiType: 'datepicker', uiOptions: ["altField", "altFormat", "appendText", "autoSize", "beforeShow", "beforeShowDay", "buttonImage", "buttonImageOnly", "buttonText", "calculateWeek", "changeMonth", "changeYear", "closeText", "constrainInput", "currentText", "dateFormat", "dayNames", "dayNamesMin", "dayNamesShort", "defaultDate", "duration", "firstDay", "gotoCurrent", "hideIfNoPrevNext", "isRTL", "maxDate", "minDate", "monthNames", "monthNamesShort", "navigationAsDateFormat", "nextText", "numberOfMonths", "onChangeMonthYear", "onClose", "onSelect", "prevText", "selectOtherMonths", "shortYearCutoff", "showAnim", "showButtonPanel", "showCurrentAtPos", "showMonthAfterYear", "showOn", "showOptions", "showOtherMonths", "showWeek", "stepMonths", "weekHeader", "yearRange", "yearSuffix"] });
Remove useless events that don't exist
Remove useless events that don't exist
JavaScript
mit
Gaurav0/ember-cli-jquery-ui,Gaurav0/ember-cli-jquery-ui
--- +++ @@ -14,6 +14,5 @@ "selectOtherMonths", "shortYearCutoff", "showAnim", "showButtonPanel", "showCurrentAtPos", "showMonthAfterYear", "showOn", "showOptions", "showOtherMonths", "showWeek", "stepMonths", "weekHeader", "yearRange", - "yearSuffix"], - uiEvents: ['onChangeMonthYear', 'onClose', 'onSelect'] + "yearSuffix"] });
ff6e324be00554374a57e068519e40d62b9664dd
lib/router.js
lib/router.js
Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound', waitOn: function() { return Meteor.subscribe('notifications'); } }); Router.route('/posts/:_id', { name: 'postPage', waitOn: function() { return Meteor.subscribe('comments', this.params._id); }, data: function() { return Posts.findOne(this.params._id); } }); Router.route('posts/:_id/edit', { name: 'postEdit', data: function() { return Posts.findOne(this.params._id); } }); Router.route('/submit', { name: 'postSubmit' }); Router.route('/:postsLimit?', { name: 'postsList', waitOn: function() { var limit = parseInt(this.params.postsLimit) || 5; return Meteor.subscribe('posts', { sort: { submitted: -1 }, limit: limit }); } }); var requireLogin = function() { if (!Meteor.user()) { if (Meteor.loggingIn()) { this.render(this.loadingTemplate); } else { this.render('accessDenied'); } } else { this.next(); } } Router.onBeforeAction('dataNotFound', { only: 'postPage' }); Router.onBeforeAction(requireLogin, { only: 'postSubmit' });
Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound', waitOn: function() { return Meteor.subscribe('notifications'); } }); Router.route('/posts/:_id', { name: 'postPage', waitOn: function() { return Meteor.subscribe('comments', this.params._id); }, data: function() { return Posts.findOne(this.params._id); } }); Router.route('posts/:_id/edit', { name: 'postEdit', data: function() { return Posts.findOne(this.params._id); } }); Router.route('/submit', { name: 'postSubmit' }); Router.route('/:postsLimit?', { name: 'postsList', waitOn: function() { var limit = parseInt(this.params.postsLimit) || 5; return Meteor.subscribe('posts', { sort: { submitted: -1 }, limit: limit }); }, data: function() { var limit = parseInt(this.params.postsLimit) || 5; return { posts: Posts.find({}, { sort: { submitted: -1 }, limit: limit }); } } }); var requireLogin = function() { if (!Meteor.user()) { if (Meteor.loggingIn()) { this.render(this.loadingTemplate); } else { this.render('accessDenied'); } } else { this.next(); } } Router.onBeforeAction('dataNotFound', { only: 'postPage' }); Router.onBeforeAction(requireLogin, { only: 'postSubmit' });
Add dataContext to postsLimit route
Add dataContext to postsLimit route
JavaScript
mit
Bennyz/microscope,Bennyz/microscope
--- +++ @@ -33,6 +33,13 @@ waitOn: function() { var limit = parseInt(this.params.postsLimit) || 5; return Meteor.subscribe('posts', { sort: { submitted: -1 }, limit: limit }); + }, + data: function() { + var limit = parseInt(this.params.postsLimit) || 5; + + return { + posts: Posts.find({}, { sort: { submitted: -1 }, limit: limit }); + } } });
126873a8d5c90810789387c8e8ec90fe4ad1f3d8
lib/router.js
lib/router.js
var subscriptions = new SubsManager(); Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound' }); Router.route('/', { name: 'home', waitOn: function() { return [subscriptions.subscribe('lastGames'), subscriptions.subscribe('allUsers')]; }, fastRender: true }); Router.route('/ranking', { name: 'rankingWrapper', /*waitOn: function() { return subscriptions.subscribe(''); },*/ fastRender: true }); Router.route('/championship', { name: 'ChampionshipWrapper', /*waitOn: function() { return subscriptions.subscribe(''); },*/ fastRender: true }); Router.route('/search', { name: 'search', /*waitOn: function() { return subscriptions.subscribe(''); },*/ fastRender: true }); Router.route('/account', { name: 'accountWrapper', fastRender: true });
var subscriptions = new SubsManager(); Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound' }); Router.route('/', { name: 'home', waitOn: function() { return [subscriptions.subscribe('lastGames'), subscriptions.subscribe('allUsers')]; }, fastRender: true }); Router.route('/ranking', { name: 'rankingWrapper', waitOn: function() { return subscriptions.subscribe('allUsers'); }, data: function() { return Meteor.users.find({}, { fields: { 'profile.firstName': 1, 'profile.lastName': 1, 'profile.points': 1 } }); }, fastRender: true }); Router.route('/championship', { name: 'ChampionshipWrapper', /*waitOn: function() { return subscriptions.subscribe(''); },*/ fastRender: true }); Router.route('/search', { name: 'search', /*waitOn: function() { return subscriptions.subscribe(''); },*/ fastRender: true }); Router.route('/account', { name: 'accountWrapper', fastRender: true });
Add data for ranking route
Add data for ranking route
JavaScript
mit
dexterneo/ping_pong_wars,dexterneo/ping_pong_wars
--- +++ @@ -16,9 +16,18 @@ Router.route('/ranking', { name: 'rankingWrapper', - /*waitOn: function() { - return subscriptions.subscribe(''); - },*/ + waitOn: function() { + return subscriptions.subscribe('allUsers'); + }, + data: function() { + return Meteor.users.find({}, { + fields: { + 'profile.firstName': 1, + 'profile.lastName': 1, + 'profile.points': 1 + } + }); + }, fastRender: true });
f905f4080d45f0db635b178b2931daf93b51706e
test/server/webhookSpec.js
test/server/webhookSpec.js
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const chai = require('chai') const expect = chai.expect describe('webhook', () => { const webhook = require('../../lib/webhook') const challenge = { key: 'key', name: 'name' } describe('notify', () => { it('fails when no webhook URL is provided via environment variable', () => { expect(() => webhook.notify(challenge)).to.throw('options.uri is a required argument') }) it('fails when supplied webhook is not a valid URL', () => { expect(() => webhook.notify(challenge, 'localhorst')).to.throw('Invalid URI "localhorst"') }) it('submits POST with payload to existing URL', () => { expect(() => webhook.notify(challenge, 'https://webhook.site/46beb3e9-df8f-495b-98b9-abf0d4ae38a0')).to.not.throw() }) }) })
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const chai = require('chai') const expect = chai.expect describe('webhook', () => { const webhook = require('../../lib/webhook') const challenge = { key: 'key', name: 'name' } describe('notify', () => { it('fails when no webhook URL is provided via environment variable', () => { expect(() => webhook.notify(challenge)).to.throw('options.uri is a required argument') }) it('fails when supplied webhook is not a valid URL', () => { expect(() => webhook.notify(challenge, 'localhorst')).to.throw('Invalid URI "localhorst"') }) it('submits POST with payload to existing URL', () => { expect(() => webhook.notify(challenge, 'https://webhook.site/#!/e3b07c99-fd53-4799-aa18-984f71009f8c')).to.not.throw() }) }) })
Update to new (unburned) webhook.site URL
Update to new (unburned) webhook.site URL
JavaScript
mit
bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop
--- +++ @@ -24,7 +24,7 @@ }) it('submits POST with payload to existing URL', () => { - expect(() => webhook.notify(challenge, 'https://webhook.site/46beb3e9-df8f-495b-98b9-abf0d4ae38a0')).to.not.throw() + expect(() => webhook.notify(challenge, 'https://webhook.site/#!/e3b07c99-fd53-4799-aa18-984f71009f8c')).to.not.throw() }) }) })
e7ae935573dfc193d2e7548b8eac6abec475a849
test/spec/leafbird.spec.js
test/spec/leafbird.spec.js
/* Copyright 2015 Leafbird Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ describe('configure', function() { it('Confugure changes on original config.', function() { var leafbrd = Leafbird({}); leafbrd.configure({}); expect(leafbrd.config).toEqual(undefined); }); it('verify if a leafbird global object has defined', function(){ expect(leafbird).toBeDefined(); }); });
/* Copyright 2015 Leafbird Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ describe('configure', function() { it('Confugure changes on original config.', function() { var leafbrd = Leafbird({}); leafbrd.configure({}); expect(leafbrd.config).toEqual(undefined); }); it('verify if a leafbird global object has defined', function() { expect(leafbird).toBeDefined(); }); it('verify if leafbird global variable has a Leafbird object instance', function() { if(!(leafbird instanceof Leafbird)) { fail('leafbird global variable is not a Leafbird instance.'); } }); });
Verify if leafbird global variable has a Leafbird object instance.
Verify if leafbird global variable has a Leafbird object instance.
JavaScript
apache-2.0
bscherer/leafbird,leafbirdjs/leafbird,leafbirdjs/leafbird,lucasb/leafbird,bscherer/leafbird,lucasb/leafbird
--- +++ @@ -21,7 +21,14 @@ expect(leafbrd.config).toEqual(undefined); }); - it('verify if a leafbird global object has defined', function(){ + it('verify if a leafbird global object has defined', function() { expect(leafbird).toBeDefined(); }); + + it('verify if leafbird global variable has a Leafbird object instance', + function() { + if(!(leafbird instanceof Leafbird)) { + fail('leafbird global variable is not a Leafbird instance.'); + } + }); });
8458ca15bf929710cdfc5f0667690a22fe1ce40b
test/specs/effects.spec.js
test/specs/effects.spec.js
import * as effects from 'src/effects' /** * @jest-environment jsdom */ jest.useFakeTimers() describe('Effects', () => { let element beforeEach(() => { element = document.createElement('div') document.body.appendChild(element) }) afterEach(() => { document.body.innerHTML = '' }) test('Fade in', () => { element.style.opacity = 1 effects.fadeIn(element, 100) expect(Number(element.style.opacity)).toBeGreaterThanOrEqual(0) jest.runAllTimers() expect(Number(element.style.opacity)).toBeGreaterThanOrEqual(1) }) test('RAF fade in', () => { window.requestAnimationFrame = jest.fn(fn => setTimeout(fn, 1)) effects.fadeIn(element, 1) jest.runAllTimers() expect(window.requestAnimationFrame).toBeCalled() effects.fadeIn(element) jest.runAllTimers() expect(window.requestAnimationFrame).toBeCalled() delete window.requestAnimationFrame }) test('Fade out', () => { element.style.opacity = 0 effects.fadeOut(element, 100) expect(Number(element.style.opacity)).toBeLessThanOrEqual(1) jest.runAllTimers() expect(Number(element.style.opacity)).toBeLessThanOrEqual(0) }) test('Hide', () => { effects.hide(element) expect(element.style.display).toBe('none') }) test('Show', () => { effects.show(element) expect(element.style.display).toBe('') }) })
import * as effects from 'src/effects' /** * @jest-environment jsdom */ jest.useFakeTimers() describe('Effects', () => { let element beforeEach(() => { element = document.createElement('div') document.body.appendChild(element) }) afterEach(() => { document.body.innerHTML = '' }) test('Fade in', () => { element.style.opacity = 1 effects.fadeIn(element, 100) expect(Number(element.style.opacity)).toBeGreaterThanOrEqual(0) jest.runAllTimers() expect(Number(element.style.opacity)).toBeGreaterThanOrEqual(1) }) test('RAF fade in', () => { global.requestAnimationFrame = jest.fn() effects.fadeIn(element, 1) jest.runAllTimers() expect(global.requestAnimationFrame).toBeCalled() effects.fadeIn(element) jest.runAllTimers() expect(global.requestAnimationFrame).toBeCalled() delete global.requestAnimationFrame }) test('Fade out', () => { element.style.opacity = 0 effects.fadeOut(element, 100) expect(Number(element.style.opacity)).toBeLessThanOrEqual(1) jest.runAllTimers() expect(Number(element.style.opacity)).toBeLessThanOrEqual(0) }) test('Hide', () => { effects.hide(element) expect(element.style.display).toBe('none') }) test('Show', () => { effects.show(element) expect(element.style.display).toBe('') }) })
Fix fade test with RAF
test(Effects): Fix fade test with RAF Because of wrong mock implementation
JavaScript
mit
lucaperret/gaspard
--- +++ @@ -21,14 +21,14 @@ expect(Number(element.style.opacity)).toBeGreaterThanOrEqual(1) }) test('RAF fade in', () => { - window.requestAnimationFrame = jest.fn(fn => setTimeout(fn, 1)) + global.requestAnimationFrame = jest.fn() effects.fadeIn(element, 1) jest.runAllTimers() - expect(window.requestAnimationFrame).toBeCalled() + expect(global.requestAnimationFrame).toBeCalled() effects.fadeIn(element) jest.runAllTimers() - expect(window.requestAnimationFrame).toBeCalled() - delete window.requestAnimationFrame + expect(global.requestAnimationFrame).toBeCalled() + delete global.requestAnimationFrame }) test('Fade out', () => { element.style.opacity = 0
5e0df55f9306d7e6eecd71881c59788a35925aec
parse-comments/lib/utils.js
parse-comments/lib/utils.js
/*! * parse-comments <https://github.com/jonschlinkert/parse-comments> * * Copyright (c) 2014-2015, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; var utils = module.exports = {}; utils.trimRight = function(str) { return str.replace(/\s+$/, ''); }; utils.stripStars = function (line) { var re = /^(?:\s*[\*]{1,2}\s)/; return utils.trimRight(line.replace(re, '')); };
let utils = module.exports = {}; utils.trimRight = function(str) { return str.replace(/\s+$/, ''); }; utils.stripStars = function (line) { let re = /^(?:\s*[\*]{1,2}\s)/; return utils.trimRight(line.replace(re, '')); };
Clean up parse-comments utilis file
Clean up parse-comments utilis file
JavaScript
apache-2.0
weepower/wee-core
--- +++ @@ -1,19 +1,10 @@ -/*! - * parse-comments <https://github.com/jonschlinkert/parse-comments> - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ - -'use strict'; - -var utils = module.exports = {}; +let utils = module.exports = {}; utils.trimRight = function(str) { return str.replace(/\s+$/, ''); }; utils.stripStars = function (line) { - var re = /^(?:\s*[\*]{1,2}\s)/; + let re = /^(?:\s*[\*]{1,2}\s)/; return utils.trimRight(line.replace(re, '')); };
bd2ee45b9fad33587764f03dbeb6f39c86299ea6
js/main.js
js/main.js
var questions = [ Q1 = { question: "What do HTML means?", answer: "HyperText Markup Language" }, Q2 = { question: "What do CSS means?", answer: "Cascading Style Sheet" } ]; var question = document.getElementById('question'); var questionNum = 0; function createNum() { questionNum = Math.floor(Math.random() * 2); } createNum(); question.innerHTML = questions[questionNum].question;
var questions = [ Q1 = { question: "What does HTML means?", answer: "HyperText Markup Language" }, Q2 = { question: "What does CSS means?", answer: "Cascading Style Sheet" }, Q3 = { question: "Why the \"C\" in CSS, is called Cascading?", answer: "When CSS rules are duplicated, the rule to be use is chosen by <em>cascading</em> down from more general rules to the specific rule required" } ]; var question = document.getElementById('question'); var questionNum = 0; function createNum() { questionNum = Math.floor(Math.random() * 3); } createNum(); question.innerHTML = questions[questionNum].question;
Modify and add another question
Modify and add another question
JavaScript
mit
vinescarlan/FlashCards,vinescarlan/FlashCards
--- +++ @@ -1,11 +1,15 @@ var questions = [ Q1 = { - question: "What do HTML means?", + question: "What does HTML means?", answer: "HyperText Markup Language" }, Q2 = { - question: "What do CSS means?", + question: "What does CSS means?", answer: "Cascading Style Sheet" + }, + Q3 = { + question: "Why the \"C\" in CSS, is called Cascading?", + answer: "When CSS rules are duplicated, the rule to be use is chosen by <em>cascading</em> down from more general rules to the specific rule required" } ]; @@ -14,7 +18,7 @@ var questionNum = 0; function createNum() { - questionNum = Math.floor(Math.random() * 2); + questionNum = Math.floor(Math.random() * 3); } createNum();
265769d571df9e80462bb339c0476d8b1f4e3516
initialize.js
initialize.js
var i = (function() { 'use strict'; return { c: function(obj, args) { if (arguments.length > 0) { var newObj = Object.create(arguments[0]); if ('init' in newObj) { if (arguments.length > 1) { var args = []; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]); } newObj.init.apply(newObj, args); } } return newObj; } } }; })();
var i = (function() { 'use strict'; return { c: function(obj, args) { if (arguments.length > 0) { var newObj = Object.create(arguments[0]); if ('init' in newObj && typeof newObj.init === 'function') { if (arguments.length > 1) { var args = []; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]); } newObj.init.apply(newObj, args); } } return newObj; } } }; })();
Check that init is a function
Check that init is a function
JavaScript
mit
delta-nry/Initialize.js,delta-nry/Initialize.js
--- +++ @@ -4,7 +4,7 @@ c: function(obj, args) { if (arguments.length > 0) { var newObj = Object.create(arguments[0]); - if ('init' in newObj) { + if ('init' in newObj && typeof newObj.init === 'function') { if (arguments.length > 1) { var args = []; for (var i = 1; i < arguments.length; i++) {
a8bc763ab377f872355bef930bf5ad1735c25e19
app/models/UserDevice.js
app/models/UserDevice.js
module.exports = function(sequelize, DataTypes) { var UserDevice = sequelize.define('UserDevice', { type: { type: DataTypes.ENUM('IOS', 'ANDROID'), defaultValue: 'IOS' }, token: { type: DataTypes.STRING, allowNull: false } }, { classMethods: { addDevice: function(deviceInfo) { UserDevice.find({where: deviceInfo}) .success(function(device) { if(device) { } else { UserDevice.create(deviceInfo); } }); } }, associate: function(models){ UserDevice.belongsTo(models.User); } } ); return UserDevice; };
module.exports = function(sequelize, DataTypes) { var UserDevice = sequelize.define('UserDevice', { type: { type: DataTypes.ENUM('IOS', 'ANDROID'), defaultValue: 'IOS' }, token: { type: DataTypes.STRING, allowNull: false } }, { classMethods: { addDevice: function(deviceInfo) { var search = { type: deviceInfo.type, token: deviceInfo.token, }; UserDevice.find({where: search}) .success(function(device) { if(device) { device.destroy(); } UserDevice.create(deviceInfo); }); } }, associate: function(models){ UserDevice.belongsTo(models.User); } } ); return UserDevice; };
Remove duplicated device token for multiple users
Remove duplicated device token for multiple users
JavaScript
mit
barak-shirali/PDS,barak-shirali/PDS,barak-shirali/PDS,barak-shirali/PDS
--- +++ @@ -15,14 +15,16 @@ { classMethods: { addDevice: function(deviceInfo) { - UserDevice.find({where: deviceInfo}) + var search = { + type: deviceInfo.type, + token: deviceInfo.token, + }; + UserDevice.find({where: search}) .success(function(device) { if(device) { - + device.destroy(); } - else { - UserDevice.create(deviceInfo); - } + UserDevice.create(deviceInfo); }); } },
dffde72e5e73cd23d2531198a0f61435ca30efb0
lib/ArgVerifier.js
lib/ArgVerifier.js
var ArgumentError = require('./ArgumentError'); var topiarist = require('topiarist'); function verifierMethod(verifier, methodName) { return function() { if(!this.skipVerification) { if(this.argValue === undefined) throw new ArgumentError(this.argName + ' argument must be provided.'); verifier[methodName].apply(this, arguments); } if(this.argsVerifier.argIndex < this.argsVerifier.arguments.length) { this.argsVerifier.constructor.pendingVerifier = this.argsVerifier; } return this.argsVerifier; }; } function ArgVerifier(argsVerifier, argName, argValue) { this.argsVerifier = argsVerifier; this.argName = argName; this.argValue = argValue; } ArgVerifier.addVerifier = function(verifier) { for(var methodName in verifier) { ArgVerifier.prototype[methodName] = verifierMethod(verifier, methodName); } }; Object.defineProperty(ArgVerifier.prototype, 'optionally', { get: function optionally() { if((this.argValue === undefined) || (this.argValue === null)) { this.skipVerification = true; } return this; } }); module.exports = ArgVerifier;
var ArgumentError = require('./ArgumentError'); var topiarist = require('topiarist'); function verifierMethod(verifierMethod) { return function(arg) { if(!this.skipVerification) { if(this.argValue === undefined) throw new ArgumentError(this.argName + ' argument must be provided.'); verifierMethod.call(this, arg); } if(this.argsVerifier.argIndex < this.argsVerifier.arguments.length) { this.argsVerifier.constructor.pendingVerifier = this.argsVerifier; } return this.argsVerifier; }; } function ArgVerifier(argsVerifier, argName, argValue) { this.argsVerifier = argsVerifier; this.argName = argName; this.argValue = argValue; } ArgVerifier.addVerifier = function(verifier) { for(var methodName in verifier) { ArgVerifier.prototype[methodName] = verifierMethod(verifier[methodName]); } }; Object.defineProperty(ArgVerifier.prototype, 'optionally', { get: function optionally() { if((this.argValue === undefined) || (this.argValue === null)) { this.skipVerification = true; } return this; } }); module.exports = ArgVerifier;
Use call() rather than apply() to improve performance.
Use call() rather than apply() to improve performance.
JavaScript
apache-2.0
dchambers/typester
--- +++ @@ -1,12 +1,12 @@ var ArgumentError = require('./ArgumentError'); var topiarist = require('topiarist'); -function verifierMethod(verifier, methodName) { - return function() { +function verifierMethod(verifierMethod) { + return function(arg) { if(!this.skipVerification) { if(this.argValue === undefined) throw new ArgumentError(this.argName + ' argument must be provided.'); - verifier[methodName].apply(this, arguments); + verifierMethod.call(this, arg); } if(this.argsVerifier.argIndex < this.argsVerifier.arguments.length) { @@ -25,7 +25,7 @@ ArgVerifier.addVerifier = function(verifier) { for(var methodName in verifier) { - ArgVerifier.prototype[methodName] = verifierMethod(verifier, methodName); + ArgVerifier.prototype[methodName] = verifierMethod(verifier[methodName]); } };
c532fbe1246fcf2032b09a417b27a932f0bce774
server/services/ads.spec.js
server/services/ads.spec.js
/* global describe, beforeEach, afterEach, it */ const knex_config = require('../../knexfile'); const knex = require('knex')(knex_config['test']); const chai = require('chai'); const should = chai.should(); describe('Handle ads', function() { beforeEach(function(done) { knex.migrate.rollback() .then(function() { knex.migrate.latest() .then(function() { return knex.seed.run() .then(function() { done(); }); }); }); }); afterEach(function(done) { knex.migrate.rollback() .then(function() { done(); }); }); it('should list ads in order', (done) => { done(); }) });
/* global describe, beforeEach, afterEach, it */ const chai = require('chai'); const should = chai.should(); const knex_config = require('../../knexfile'); const knex = require('knex')(knex_config['test']); const util = require('../util')({ knex }); const service = require('./ads')({ knex, util }); describe('Handle ads', function() { beforeEach(function(done) { knex.migrate.rollback() .then(function() { knex.migrate.latest() .then(function() { return knex.seed.run() .then(function() { done(); }); }); }); }); afterEach(function(done) { knex.migrate.rollback() .then(function() { done(); }); }); it('should list ads in order', (done) => { service.listAds(false).then((ads) => { ads.map(ad => ad.id).should.eql([2, 3, 1]); done(); }) }) });
Test that ads appear in date order latest first
Test that ads appear in date order latest first
JavaScript
agpl-3.0
Tradenomiliitto/tradenomiitti,Tradenomiliitto/tradenomiitti,Tradenomiliitto/tradenomiitti
--- +++ @@ -1,9 +1,13 @@ /* global describe, beforeEach, afterEach, it */ + +const chai = require('chai'); +const should = chai.should(); + const knex_config = require('../../knexfile'); const knex = require('knex')(knex_config['test']); -const chai = require('chai'); -const should = chai.should(); +const util = require('../util')({ knex }); +const service = require('./ads')({ knex, util }); describe('Handle ads', function() { @@ -29,6 +33,9 @@ it('should list ads in order', (done) => { - done(); + service.listAds(false).then((ads) => { + ads.map(ad => ad.id).should.eql([2, 3, 1]); + done(); + }) }) });
9e246962370dcd7f96732b56eaa2c09d1c757626
util/transitionToParams.js
util/transitionToParams.js
import queryString from 'query-string'; function transitionToParams(params) { const location = this.props.location; let query = location.query; if (query === undefined) query = queryString.parse(location.search); const allParams = Object.assign({}, query, params); const keys = Object.keys(allParams); let url = location.pathname; if (keys.length) { url += `?${keys.map(key => `${key}=${encodeURIComponent(allParams[key])}`).join('&')}`; } this.props.history.push(url); } export default transitionToParams;
import queryString from 'query-string'; function transitionToParams(params) { const location = this.props.location; let query = location.query; if (query === undefined) query = queryString.parse(location.search); const allParams = Object.assign({}, query, params); const keys = Object.keys(allParams); let url = location.pathname; if (keys.length) { url += `?${queryString.stringify(allParams)}`; } this.props.history.push(url); } export default transitionToParams;
Use queryString.stringify instead of by-hand gluing
Use queryString.stringify instead of by-hand gluing Fixes STCOM-112
JavaScript
apache-2.0
folio-org/stripes-components,folio-org/stripes-components
--- +++ @@ -11,7 +11,7 @@ let url = location.pathname; if (keys.length) { - url += `?${keys.map(key => `${key}=${encodeURIComponent(allParams[key])}`).join('&')}`; + url += `?${queryString.stringify(allParams)}`; } this.props.history.push(url);
4c3c91c9b38ab6bde4a748c33e177f1f53036d6c
js/scripts.js
js/scripts.js
var pingPong = function(userNumber) { if ((userNumber % 3 === 0) || (userNumber % 5 === 0)) { return true; } else { return false; } }
var pingPong = function(userNumber) { if ((userNumber % 3 === 0) || (userNumber % 5 === 0)) { return true; } else { return false; } };
Remove superfluous and redundant code
Remove superfluous and redundant code
JavaScript
mit
kcmdouglas/pingpong,kcmdouglas/pingpong
--- +++ @@ -4,4 +4,4 @@ } else { return false; } -} +};
09605e33cb1693d1a1cc88ee38b08d275bc9119c
views/components/addApp.js
views/components/addApp.js
import { h, Component } from 'preact' import { bind } from './util' export default class extends Component { constructor() { super() this.state.show = false } linkState(key) { return e => this.setState({ [key]: e.target.value }) } @bind toggleShow() { this.setState({ show: !this.state.show }) } clearState() { this.setState({ appName: '', username: '', password: '', show: false }) } @bind handleSubmit(e) { e.preventDefault() this.props.add(this.state.appName, this.state.username, this.state.password) this.clearState() } render(_, { show, appName, username, password }) { return ( <section> <div style={{display: show ? 'block' : 'none'}}> <form onSubmit={this.handleSubmit}> <input name='appName' placeholder='Enter app name' value={appName} onInput={this.linkState('appName')} /> <input name='username' placeholder='Enter app username' value={username} onInput={this.linkState('username')} /> <input name='password' placeholder='Enter app password' value={password} onInput={this.linkState('password')} /> <button type='submit'>Save</button> </form> </div> <button onClick={this.toggleShow}>Add new app</button> </section> ) } }
import { h, Component } from 'preact' import { bind } from './util' export default class extends Component { constructor() { super() this.state.show = false } linkState(key) { return e => this.setState({ [key]: e.target.value }) } @bind toggleShow() { this.setState({ show: !this.state.show }) } clearState() { this.setState({ appName: '', username: '', password: '', show: false }) } @bind handleSubmit(e) { const { appName, username, password } = this.state e.preventDefault() this.props.add(appName, username, password) this.clearState() } render(_, { show, appName, username, password }) { return ( <section> <div style={{display: show ? 'block' : 'none'}}> <form onSubmit={this.handleSubmit}> <input name='appName' placeholder='Enter app name' value={appName} onInput={this.linkState('appName')} /> <input name='username' placeholder='Enter app username' value={username} onInput={this.linkState('username')} /> <input name='password' placeholder='Enter app password' value={password} onInput={this.linkState('password')} /> <button type='submit'>Save</button> </form> </div> <button onClick={this.toggleShow}>Add new app</button> </section> ) } }
Use destructuring to remove noise
Use destructuring to remove noise
JavaScript
mit
zeusdeux/password-manager,zeusdeux/password-manager
--- +++ @@ -27,9 +27,10 @@ } @bind handleSubmit(e) { + const { appName, username, password } = this.state + e.preventDefault() - - this.props.add(this.state.appName, this.state.username, this.state.password) + this.props.add(appName, username, password) this.clearState() } render(_, { show, appName, username, password }) {
1dc06e37aa07f60780d1f3e74d2f58fa896d913e
src/Loading.js
src/Loading.js
import React, { Component } from 'react'; import './Loading.css'; class Loading extends Component { render() { return <p>Loading timetable data.</p>; } } export default Loading;
import React, { Component } from 'react'; import './Loading.css'; class Loading extends Component { render() { return ( <div className='loading'> <h1>Loading</h1> <h2>{this.props.name}</h2> <p>{this.props.message}</p> </div> ); } } Loading.defaultProps = { name: 'Loading name', message: 'Loading something. This is the default message. Blame the lazy developer for not giving you any more info and copy-pasting this text from Error screen.' }; Loading.propTypes = { name: React.PropTypes.string, message: React.PropTypes.string }; export default Loading;
Add error style message and name.
Add error style message and name.
JavaScript
mit
kangasta/timetablescreen,kangasta/timetablescreen
--- +++ @@ -3,8 +3,24 @@ class Loading extends Component { render() { - return <p>Loading timetable data.</p>; + return ( + <div className='loading'> + <h1>Loading</h1> + <h2>{this.props.name}</h2> + <p>{this.props.message}</p> + </div> + ); } } +Loading.defaultProps = { + name: 'Loading name', + message: 'Loading something. This is the default message. Blame the lazy developer for not giving you any more info and copy-pasting this text from Error screen.' +}; + +Loading.propTypes = { + name: React.PropTypes.string, + message: React.PropTypes.string +}; + export default Loading;
90ad2381efbe614ebec6516ffaa7a2df628ac259
src/Weather.js
src/Weather.js
import React from 'react'; import Temperature from './Temperature.js'; class Weather extends React.Component { render = () => { // FIXME: After rendering, send stats to Google Analytics // FIXME: Add the actual temperatures return ( <Temperature degreesCelsius={25} hour={12}></Temperature> ); } } export default Weather;
import React from 'react'; import Temperature from './Temperature.js'; class Weather extends React.Component { renderTemperatures = (renderUs) => { // FIXME: Add the actual temperatures console.log(renderUs); return ( <Temperature degreesCelsius={25} hour={1} /> ); } getForecastsToRender = () => { const renderUs = []; const now_ms = (new Date()).getTime(); const start = new Date(now_ms + 0.75 * 3600 * 1000); const end = new Date(now_ms + 11.75 * 3600 * 1000); // eslint-disable-next-line for (const [timestamp_ms, forecast] of Object.entries(this.props.forecast)) { const timestamp_date = new Date(timestamp_ms); if (timestamp_date < start) { continue; } if (timestamp_date > end) { continue; } renderUs.push(forecast); } console.log(renderUs); return renderUs; } render = () => { // FIXME: After rendering, send stats to Google Analytics const renderUs = this.getForecastsToRender() return ( <React.Fragment> {this.renderTemperatures(renderUs)} </React.Fragment> ); } } export default Weather;
Add logic for choosing which forecasts to show
Add logic for choosing which forecasts to show
JavaScript
mit
walles/weatherclock,walles/weatherclock,walles/weatherclock,walles/weatherclock
--- +++ @@ -3,12 +3,50 @@ import Temperature from './Temperature.js'; class Weather extends React.Component { + renderTemperatures = (renderUs) => { + // FIXME: Add the actual temperatures + + console.log(renderUs); + + return ( + <Temperature degreesCelsius={25} hour={1} /> + ); + } + + getForecastsToRender = () => { + const renderUs = []; + + const now_ms = (new Date()).getTime(); + const start = new Date(now_ms + 0.75 * 3600 * 1000); + const end = new Date(now_ms + 11.75 * 3600 * 1000); + + // eslint-disable-next-line + for (const [timestamp_ms, forecast] of Object.entries(this.props.forecast)) { + const timestamp_date = new Date(timestamp_ms); + + if (timestamp_date < start) { + continue; + } + + if (timestamp_date > end) { + continue; + } + + renderUs.push(forecast); + } + + console.log(renderUs); + return renderUs; + } + render = () => { // FIXME: After rendering, send stats to Google Analytics - // FIXME: Add the actual temperatures + const renderUs = this.getForecastsToRender() return ( - <Temperature degreesCelsius={25} hour={12}></Temperature> + <React.Fragment> + {this.renderTemperatures(renderUs)} + </React.Fragment> ); } }
3cb2c725d0571d44d43c1265966e0de8df47b725
lib/common.js
lib/common.js
/** * Find indices of all occurance of elem in arr. Uses 'indexOf'. * @param {array} arr - Array-like element (works with strings too!). * @param {array_element} elem - Element to search for in arr. * @return {array} indices - Array of indices where elem occurs in arr. */ var findAllIndices = function(arr, elem) { var indices = []; var i = arr.indexOf(elem); while (i != -1) { indices.push(i); i = arr.indexOf(elem, i + 1); } return indices; }; /** * Find indices of all matches of Regex pattern in str. * @param {string} str - string to find Regex patterns in. * @param {RegExp} re - Regex patterns * @return {array} Array of indices where Regex pattern occurs in str. */ var findAllIndicesRegex = function(str, re) { var indices = []; var m = re.exec(str); while (m) { indices.push(m.index); m = re.exec(str); } return indices; }; module.exports.findAllIndices = findAllIndices; module.exports.findAllIndicesRegex = findAllIndicesRegex;
/** * Find indices of all occurance of elem in arr. Uses 'indexOf'. * @param {array} arr - Array-like element (works with strings too!). * @param {array_element} elem - Element to search for in arr. * @return {array} indices - Array of indices where elem occurs in arr. */ var findAllIndices = function(arr, elem) { var indices = []; var i = arr.indexOf(elem); while (i != -1) { indices.push(i); i = arr.indexOf(elem, i + 1); } return indices; }; /** * Find indices of all matches of Regex pattern in str. * @param {string} str - string to find Regex patterns in. * @param {RegExp} re - Regex patterns * @return {array} Array of indices where Regex pattern occurs in str. */ var findAllIndicesRegex = function(str, re) { var indices = []; var m = re.exec(str); while (m) { indices.push(m.index); m = re.exec(str); } return indices; }; var nullOutChars = function(str, start, end, nullChar) { return str.slice(0, start) + nullChar.repeat(end - start) + str.slice(end); } module.exports.findAllIndices = findAllIndices; module.exports.findAllIndicesRegex = findAllIndicesRegex; module.exports.nullOutChars = nullOutChars;
Add new fxn to null out chars in str range
Add new fxn to null out chars in str range
JavaScript
mit
nhatbui/libhrc,nhatbui/libhrc
--- +++ @@ -30,5 +30,10 @@ return indices; }; +var nullOutChars = function(str, start, end, nullChar) { + return str.slice(0, start) + nullChar.repeat(end - start) + str.slice(end); +} + module.exports.findAllIndices = findAllIndices; module.exports.findAllIndicesRegex = findAllIndicesRegex; +module.exports.nullOutChars = nullOutChars;
5fd4d39b04efac1d58fc2106f8184a1bc43a220b
lib/common.js
lib/common.js
'use strict'; var extendPrototypeWithThese = function (prototype, extendThese) { /* Helper method to implement a simple inheritance model for object prototypes. */ var outp = prototype; if (extendThese) { for (var i = extendThese.length - 1; i >= 0; i--) { // I need to create the object in order to copy the prototype functions var tmpObj = new extendThese[i](); for (var key in tmpObj) { if (key == '_implements') { // Implements should be extended with later coming before earlier // TODO: Filer so we remove duplicates from existing list (order makes difference) outp.prototype._implements = tmpObj._implements.concat(outp.prototype._implements); } else { // All others added and lower indexes override higher outp.prototype[key] = tmpObj[key]; } } } } return outp; } module.exports.extendPrototypeWithThese = extendPrototypeWithThese; var addMembers = function (outp, params) { /* Helper method to add each item in params dictionary to the prototype of outp. */ for (var key in params) { if (params.hasOwnProperty(key)) { outp.prototype[key] = params[key]; } } return outp; } module.exports.addMembers = addMembers;
'use strict'; var extendPrototypeWithThese = function (prototype, extendThese) { /* Helper method to implement a simple inheritance model for object prototypes. */ var outp = prototype; if (extendThese) { for (var i = extendThese.length - 1; i >= 0; i--) { // I need to create the object in order to copy the prototype functions var tmpObj = extendThese[i].prototype; for (var key in tmpObj) { if (key == '_implements') { // Implements should be extended with later coming before earlier // TODO: Filer so we remove duplicates from existing list (order makes difference) outp.prototype._implements = tmpObj._implements.concat(outp.prototype._implements); } else { // All others added and lower indexes override higher outp.prototype[key] = tmpObj[key]; } } } } return outp; } module.exports.extendPrototypeWithThese = extendPrototypeWithThese; var addMembers = function (outp, params) { /* Helper method to add each item in params dictionary to the prototype of outp. */ for (var key in params) { if (params.hasOwnProperty(key)) { outp.prototype[key] = params[key]; } } return outp; } module.exports.addMembers = addMembers;
Copy prototype memebers on extend
Copy prototype memebers on extend
JavaScript
mit
jhsware/component-registry,jhsware/SimpleJSRegistry
--- +++ @@ -11,7 +11,7 @@ for (var i = extendThese.length - 1; i >= 0; i--) { // I need to create the object in order to copy the prototype functions - var tmpObj = new extendThese[i](); + var tmpObj = extendThese[i].prototype; for (var key in tmpObj) { if (key == '_implements') { // Implements should be extended with later coming before earlier
09fddd7a0bf9a3c53e46f371f04701ef56a42811
test/algorithms/sorting/testInsertionSort.js
test/algorithms/sorting/testInsertionSort.js
/* eslint-env mocha */ const InsertionSort = require('../../../src').Algorithms.Sorting.InsertionSort; const assert = require('assert'); describe('Insertion Sort', () => { it('should have no data when empty initialization', () => { const inst = new InsertionSort(); assert.equal(inst.size, 0); assert.deepEqual(inst.unsortedList, []); assert.deepEqual(inst.sortedList, []); }); });
/* eslint-env mocha */ const InsertionSort = require('../../../src').Algorithms.Sorting.InsertionSort; const assert = require('assert'); describe('Insertion Sort', () => { it('should have no data when empty initialization', () => { const inst = new InsertionSort(); assert.equal(inst.size, 0); assert.deepEqual(inst.unsortedList, []); assert.deepEqual(inst.sortedList, []); }); it('should sort the array', () => { const inst = new InsertionSort([2, 1, 3, 4]); assert.equal(inst.size, 4); assert.deepEqual(inst.unsortedList, [2, 1, 3, 4]); assert.deepEqual(inst.sortedList, [1, 2, 3, 4]); assert.equal(inst.toString(), '1, 2, 3, 4'); }); });
Test Insertion Sort: Test for sorting the array
Test Insertion Sort: Test for sorting the array
JavaScript
mit
ManrajGrover/algorithms-js
--- +++ @@ -9,4 +9,14 @@ assert.deepEqual(inst.unsortedList, []); assert.deepEqual(inst.sortedList, []); }); + + it('should sort the array', () => { + const inst = new InsertionSort([2, 1, 3, 4]); + assert.equal(inst.size, 4); + + assert.deepEqual(inst.unsortedList, [2, 1, 3, 4]); + assert.deepEqual(inst.sortedList, [1, 2, 3, 4]); + assert.equal(inst.toString(), '1, 2, 3, 4'); + }); + });
28838615005e5da47a15e78596f9e0f2513b9df7
addon/mixins/lazy-route.js
addon/mixins/lazy-route.js
/** * ES6 not supported here */ import Ember from "ember"; import config from 'ember-get-config'; export default Ember.Mixin.create({ bundleLoader: Ember.inject.service("bundle-loader"), findBundleNameByRoute: function(routeName){ //Find bundle for route var foundBundleName = Object.keys(config.bundles) .find((name)=> { let bundle = config.bundles[name]; return bundle.routes.indexOf(routeName)>-1; }); return foundBundleName; }, beforeModel: function(transition, queryParams){ this._super(transition,queryParams); let service = this.get("bundleLoader"); let bundleName = this.findBundleNameByRoute(transition.targetName); return service.loadBundle(bundleName); } });
/** * ES6 not supported here */ import Ember from "ember"; import config from 'ember-get-config'; export default Ember.Mixin.create({ bundleLoader: Ember.inject.service("bundle-loader"), findBundleNameByRoute: function(routeName){ //Find bundle for route var bundleName = null; var bundleNames = Object.keys(config.bundles); bundleNames.forEach(function(name) { var bundle = config.bundles[name]; if(bundle.routes.indexOf(routeName) >= 0) { bundleName = name; } }); return bundleName; }, beforeModel: function(transition, queryParams){ this._super(transition,queryParams); let service = this.get("bundleLoader"); let bundleName = this.findBundleNameByRoute(transition.targetName); return service.loadBundle(bundleName); } });
Fix tests by switching to es5 syntax in finding bundles
Fix tests by switching to es5 syntax in finding bundles
JavaScript
mit
duizendnegen/ember-cli-lazy-load,duizendnegen/ember-cli-lazy-load
--- +++ @@ -5,17 +5,20 @@ import config from 'ember-get-config'; export default Ember.Mixin.create({ - bundleLoader: Ember.inject.service("bundle-loader"), findBundleNameByRoute: function(routeName){ //Find bundle for route - var foundBundleName = Object.keys(config.bundles) - .find((name)=> { - let bundle = config.bundles[name]; - return bundle.routes.indexOf(routeName)>-1; - }); - return foundBundleName; + var bundleName = null; + var bundleNames = Object.keys(config.bundles); + bundleNames.forEach(function(name) { + var bundle = config.bundles[name]; + if(bundle.routes.indexOf(routeName) >= 0) { + bundleName = name; + } + }); + + return bundleName; }, beforeModel: function(transition, queryParams){
be9b946dfe51b075c002c1d2e2abb7cb0fad7559
src/zoomingExits/zoomOutUp.js
src/zoomingExits/zoomOutUp.js
/*! Animate.js | The MIT License (MIT) | Copyright (c) 2017 GibboK */ ; (function (animate) { 'use strict'; animate.zoomOutUp = function (selector, options) { var keyframeset = [ { opacity: 1, transform: 'none', transformOrigin: 'left center', offset: 0 }, { opacity: 1, transform: 'scale3d(.475, .475, .475) translate3d(0, 60px, 0)', animationTimingFunction: 'cubic-bezier(0.550, 0.055, 0.675, 0.190)', offset: 0.4 }, { opacity: 0, transform: 'scale3d(.1, .1, .1) translate3d(0, -2000px, 0)', transformOrigin: 'center bottom', animationTimingFunction: 'cubic-bezier(0.175, 0.885, 0.320, 1)', offset: 1 } ]; return animate._animate(selector, keyframeset, options); } })(window.animate = window.animate || {});
/*! Animate.js | The MIT License (MIT) | Copyright (c) 2017 GibboK */ ; (function (animate) { 'use strict'; animate.zoomOutUp = function (selector, options) { var keyframeset = [ { opacity: 1, transform: 'none', transformOrigin: 'center bottom', offset: 0 }, { opacity: 1, transform: 'scale3d(.475, .475, .475) translate3d(0, 60px, 0)', animationTimingFunction: 'cubic-bezier(0.550, 0.055, 0.675, 0.190)', offset: 0.4 }, { opacity: 0, transform: 'scale3d(.1, .1, .1) translate3d(0, -2000px, 0)', transformOrigin: 'center bottom', animationTimingFunction: 'cubic-bezier(0.175, 0.885, 0.320, 1)', offset: 1 } ]; return animate._animate(selector, keyframeset, options); } })(window.animate = window.animate || {});
Add fix bug in animation
Add fix bug in animation
JavaScript
mit
gibbok/animate.js,gibbok/animate.js,gibbok/animatelo,gibbok/animatelo
--- +++ @@ -6,7 +6,7 @@ { opacity: 1, transform: 'none', - transformOrigin: 'left center', + transformOrigin: 'center bottom', offset: 0 }, {
007c630953c76a27b74b46b48b20dcb8b3d79cae
js/respec-w3c-extensions.js
js/respec-w3c-extensions.js
// extend the bibliographic entries var localBibliography = { "HYDRA-CORE": { authors: [ "Markus Lanthaler" ], href: "http://www.hydra-cg.com/spec/latest/core/", title: "Hydra Core Vocabulary", status: "unofficial", publisher: "W3C" }, "PAV": "Paolo Ciccarese, Stian Soiland-Reyes, Khalid Belhajjame, Alasdair JG Gray, Carole Goble, Tim Clark (2013): <cite><a href=\"http://purl.org/pav/\">PAV ontology: provenance, authoring and versioning</a>.</cite> Journal of biomedical semantics 4:37. doi:<a href=\"http://dx.doi.org/10.1186/2041-1480-4-37\">10.1186/2041-1480-4-37</a>" };
// extend the bibliographic entries var localBibliography = { "HYDRA-CORE": { authors: [ "Markus Lanthaler" ], href: "http://www.hydra-cg.com/spec/latest/core/", title: "Hydra Core Vocabulary", status: "Unofficial Draft", publisher: "W3C" }, "PAV": { authors: [ "Paolo Ciccarese", "Stian Soiland-Reyes", "Khalid Belhajjame", "Alasdair JG Gray", "Carole Goble", "Tim Clark" ], href: "http://purl.org/pav/", title: "PAV ontology: provenance, authoring and versioning", publisher: "Journal of biomedical semantics", status: "Published" } };
Set up localBiblio according to ReSpec's documentation:
Set up localBiblio according to ReSpec's documentation: http://www.w3.org/respec/ref.html#localbiblio
JavaScript
mit
pentandra/spec,pentandra/spec
--- +++ @@ -4,8 +4,21 @@ authors: [ "Markus Lanthaler" ], href: "http://www.hydra-cg.com/spec/latest/core/", title: "Hydra Core Vocabulary", - status: "unofficial", + status: "Unofficial Draft", publisher: "W3C" }, - "PAV": "Paolo Ciccarese, Stian Soiland-Reyes, Khalid Belhajjame, Alasdair JG Gray, Carole Goble, Tim Clark (2013): <cite><a href=\"http://purl.org/pav/\">PAV ontology: provenance, authoring and versioning</a>.</cite> Journal of biomedical semantics 4:37. doi:<a href=\"http://dx.doi.org/10.1186/2041-1480-4-37\">10.1186/2041-1480-4-37</a>" + "PAV": { + authors: [ + "Paolo Ciccarese", + "Stian Soiland-Reyes", + "Khalid Belhajjame", + "Alasdair JG Gray", + "Carole Goble", + "Tim Clark" + ], + href: "http://purl.org/pav/", + title: "PAV ontology: provenance, authoring and versioning", + publisher: "Journal of biomedical semantics", + status: "Published" + } };
f617ae5418d6c1223887a6685cd9714526fc95d2
src/components/LoginForm.js
src/components/LoginForm.js
import React, {Component} from 'react'; import {Button, Card, CardSection, Input} from './common'; class LoginForm extends Component { constructor(props) { super(props); this.state = {email: "", password: ''}; } render() { return <Card> <CardSection> <Input label="Email" placeholder="user@gmail.com" onChangeText={email => this.setState({email})} value={this.state.email}/> </CardSection> <CardSection> <Input secureTextEntry label="Password" placeholder = "password" onChangeText={password => this.setState({password})} value = {this.state.password} /> </CardSection> <CardSection> <Button> Log in </Button> </CardSection> </Card> } } export default LoginForm;
import React, {Component} from 'react'; import {Button, Card, CardSection, Input} from './common'; import firebase from 'firebase'; import {Text} from 'react-native'; class LoginForm extends Component { constructor(props) { super(props); this.state = {email: '', password: '', error: ''}; } async onButtonPress() { const {email, password} = this.state; this.setState({error: ''}); try { await firebase.auth().signInWithEmailAndPassword(email, password); } catch (err) { try { await firebase.auth().createUserWithEmailAndPassword(email, password); } catch (err) { console.log("error", err); this.setState({error: "Login Failed"}); } } } render() { return <Card> <CardSection> <Input label="Email" placeholder="user@gmail.com" onChangeText={email => this.setState({email})} value={this.state.email}/> </CardSection> <CardSection> <Input secureTextEntry label="Password" placeholder="password" onChangeText={password => this.setState({password})} value={this.state.password} /> </CardSection> <Text style={styles.errorTextStyle}> {this.state.error} </Text> <CardSection> <Button onPress={()=>this.onButtonPress()}> Log in </Button> </CardSection> </Card> } } const styles = { errorTextStyle: { fontSize: 20, alignSelf: 'center', color: 'red' } }; export default LoginForm;
Use firebase to authenticate users
Use firebase to authenticate users
JavaScript
apache-2.0
ChenLi0830/RN-Auth,ChenLi0830/RN-Auth,ChenLi0830/RN-Auth
--- +++ @@ -1,10 +1,29 @@ import React, {Component} from 'react'; import {Button, Card, CardSection, Input} from './common'; +import firebase from 'firebase'; +import {Text} from 'react-native'; class LoginForm extends Component { constructor(props) { super(props); - this.state = {email: "", password: ''}; + this.state = {email: '', password: '', error: ''}; + } + + async onButtonPress() { + const {email, password} = this.state; + this.setState({error: ''}); + try { + await firebase.auth().signInWithEmailAndPassword(email, password); + } + catch (err) { + try { + await firebase.auth().createUserWithEmailAndPassword(email, password); + } + catch (err) { + console.log("error", err); + this.setState({error: "Login Failed"}); + } + } } render() { @@ -19,14 +38,19 @@ <CardSection> <Input secureTextEntry label="Password" - placeholder = "password" + placeholder="password" onChangeText={password => this.setState({password})} - value = {this.state.password} + value={this.state.password} /> </CardSection> + + <Text style={styles.errorTextStyle}> + {this.state.error} + </Text> + <CardSection> - <Button> + <Button onPress={()=>this.onButtonPress()}> Log in </Button> </CardSection> @@ -34,4 +58,12 @@ } } +const styles = { + errorTextStyle: { + fontSize: 20, + alignSelf: 'center', + color: 'red' + } +}; + export default LoginForm;
a9bcc1388143c86f8ac6d5afcfe0b8cb376b8de7
src/main/webapp/resources/dev/js/singleUser.js
src/main/webapp/resources/dev/js/singleUser.js
/** * Author: Josh Adam <josh.adam@phac-aspc.gc.ca> * Date: 2013-04-17 * Time: 9:41 AM */ var username = $('#username').text(); function Project (data) { "use strict"; this.name = data.name; } function UserViewModel () { "use strict"; self.projects = ko.observableArray([]); function getUserProjects () { "use strict"; $.getJSON('/users/' + username + '/projects', function (allData) { var mappedProjects = $.map(allData.projectList, function (item) { return new Project(item) }); self.projects(mappedProjects); }); } getUserProjects(); } $.ajaxSetup({ cache: false }); ko.applyBindings(new UserViewModel());
/** * Author: Josh Adam <josh.adam@phac-aspc.gc.ca> * Date: 2013-04-17 * Time: 9:41 AM */ var username = $('#username').text(); function Project (data) { "use strict"; this.name = data.name; } function UserViewModel () { "use strict"; self.projects = ko.observableArray([]); function getUserProjects () { "use strict"; $.getJSON('/users/' + username + '/projects', function (allData) { var mappedProjects = $.map(allData.projectResources.projects, function (item) { return new Project(item) }); self.projects(mappedProjects); }); } getUserProjects(); } $.ajaxSetup({ cache: false }); ko.applyBindings(new UserViewModel());
Change the expected JSON format for user projects.
Change the expected JSON format for user projects.
JavaScript
apache-2.0
phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida
--- +++ @@ -19,7 +19,7 @@ "use strict"; $.getJSON('/users/' + username + '/projects', function (allData) { - var mappedProjects = $.map(allData.projectList, function (item) { + var mappedProjects = $.map(allData.projectResources.projects, function (item) { return new Project(item) }); self.projects(mappedProjects);
c68b6772d435d76bfe290e40e0ae0539c1ba5d76
src/js/model/Contacts.js
src/js/model/Contacts.js
var ContactView = require('../view/Contact'); /** * Creates a new Contact * @constructor * @arg {Object} options - Object hash used to populate instance * @arg {string} options.firstName - First name of the contact * @arg {string} options.firstName - Last name of the contact * @arg {string} options.tel - name of the contact */ var Contact = function(options) { if (typeof options !== 'object') { throw console.error('`options` is not properly defined'); } this.init(options); }; Contact.prototype = { firstName: '', lastName: '', tel: '', /** * @description Creates a new instance of Contact */ init: function(options) { var opts = Object.keys(options); opts.forEach(function(currentValue){ this[currentValue] = options[currentValue]; }, this); console.log(this); this.save(); }, save: function() { var key = localStorage.length; var contact = { firstName: this.firstName, lastName: this.lastName, tel: this.tel }; localStorage.setItem(key, JSON.stringify(contact)); var contactView = new ContactView(key, contact); } }; Contact.remove = function(id) { localStorage.removeItem(id); }; module.exports = Contact;
var ContactView = require('../view/Contact'); /** * Creates a new Contact. * @constructor * @arg {Object} options - Object hash used to populate instance. * @arg {string} options.firstName - First name of the contact. * @arg {string} options.firstName - Last name of the contact. * @arg {string} options.tel - Telephone number of the contact. */ var Contact = function(options) { if (typeof options !== 'object') { throw console.error('`options` is not properly defined'); } this.init(options); }; Contact.prototype = { firstName: '', lastName: '', tel: '', /** * @description Creates a new instance of Contact. */ init: function(options) { var opts = Object.keys(options); opts.forEach(function(currentValue){ this[currentValue] = options[currentValue]; }, this); console.log(this); this.save(); }, save: function() { var key = localStorage.length; var contact = { firstName: this.firstName, lastName: this.lastName, tel: this.tel }; localStorage.setItem(key, JSON.stringify(contact)); var contactView = new ContactView(key, contact); } }; Contact.remove = function(id) { localStorage.removeItem(id); }; module.exports = Contact;
Use periods on senteces in docs
Use periods on senteces in docs
JavaScript
isc
bitfyre/contacts
--- +++ @@ -1,12 +1,12 @@ var ContactView = require('../view/Contact'); /** - * Creates a new Contact + * Creates a new Contact. * @constructor - * @arg {Object} options - Object hash used to populate instance - * @arg {string} options.firstName - First name of the contact - * @arg {string} options.firstName - Last name of the contact - * @arg {string} options.tel - name of the contact + * @arg {Object} options - Object hash used to populate instance. + * @arg {string} options.firstName - First name of the contact. + * @arg {string} options.firstName - Last name of the contact. + * @arg {string} options.tel - Telephone number of the contact. */ var Contact = function(options) { if (typeof options !== 'object') { @@ -21,7 +21,7 @@ tel: '', /** - * @description Creates a new instance of Contact + * @description Creates a new instance of Contact. */ init: function(options) { var opts = Object.keys(options);
061563eb253e72812e45aa454455288d194f3cc5
app/scripts/components/player-reaction.js
app/scripts/components/player-reaction.js
import m from 'mithril'; import classNames from '../classnames.js'; class PlayerReactionComponent { oninit({ attrs: { session, player } }) { this.player = player; session.on('send-reaction', ({ reactingPlayer, reaction }) => { if (reactingPlayer.color === this.player.color) { // Immediately update the reaction if another reaction was sent before // the current reaction disappears clearTimeout(this.player.reaction ? this.player.reaction.timer : null); this.player.reaction = reaction; // The reaction should disappear after the specified duration this.player.reaction.timer = setTimeout(() => { this.player.reaction.timer = null; m.redraw(); }, PlayerReactionComponent.reactionDuration); m.redraw(); } }); } // The oninit() call (and therefore the send-reaction listener) only runs once // for the lifetime of this component instance, however the player object may // change during that time, so we need to ensure the above listener has an // dynamic reference to the freshest instance of the player onupdate({ attrs: { player } }) { this.player = player; } view({ attrs: { player } }) { return m('div.player-reaction', m('div.player-reaction-symbol', { class: classNames({ 'show': player.reaction && player.reaction.timer }) }, player.reaction ? player.reaction.symbol : null)); } } // The duration a reaction is shown before disappearing PlayerReactionComponent.reactionDuration = 1500; export default PlayerReactionComponent;
import m from 'mithril'; import classNames from '../classnames.js'; class PlayerReactionComponent { oninit({ attrs: { session, player } }) { this.player = player; session.on('send-reaction', ({ reactingPlayer, reaction }) => { if (reactingPlayer.color === this.player.color) { // Immediately update the reaction if another reaction was sent before // the current reaction disappears clearTimeout(this.player.reaction ? this.player.reaction.timer : null); this.player.reaction = reaction; // The reaction should disappear after the specified duration this.player.reaction.timer = setTimeout(() => { if (this.player.reaction) { this.player.reaction.timer = null; } m.redraw(); }, PlayerReactionComponent.reactionDuration); m.redraw(); } }); } // The oninit() call (and therefore the send-reaction listener) only runs once // for the lifetime of this component instance, however the player object may // change during that time, so we need to ensure the above listener has an // dynamic reference to the freshest instance of the player onupdate({ attrs: { player } }) { this.player = player; } view({ attrs: { player } }) { return m('div.player-reaction', m('div.player-reaction-symbol', { class: classNames({ 'show': player.reaction && player.reaction.timer }) }, player.reaction ? player.reaction.symbol : null)); } } // The duration a reaction is shown before disappearing PlayerReactionComponent.reactionDuration = 1500; export default PlayerReactionComponent;
Fix race condition when setTimeout callback is run
Fix race condition when setTimeout callback is run The player object may change by the time the callback is run, and therefore this.player.reactions may not exist at that point.
JavaScript
mit
caleb531/connect-four
--- +++ @@ -13,7 +13,9 @@ this.player.reaction = reaction; // The reaction should disappear after the specified duration this.player.reaction.timer = setTimeout(() => { - this.player.reaction.timer = null; + if (this.player.reaction) { + this.player.reaction.timer = null; + } m.redraw(); }, PlayerReactionComponent.reactionDuration); m.redraw();
547cb0360680e20025e086895f1926ea93c3a205
lib/generators/loaders/ESNextReactLoader.js
lib/generators/loaders/ESNextReactLoader.js
module.exports = { test: /\.es6\.js$|\.js$|\.jsx$/, exclude: /node_modules/, loader: 'babel', query: { presets: [ 'es2015-native-modules', 'stage-2', 'react', ], plugins: [ 'transform-class-properties', 'transform-react-constant-elements', 'transform-react-inline-elements', 'lodash', // fixes the babel budnling issue ], } };
module.exports = { test: /\.es6\.js$|\.js$|\.jsx$/, exclude: /node_modules/, loader: 'babel', query: { presets: [ 'es2015-native-modules', 'stage-2', 'react', ].map(function(p) { return require.resolve('babel-preset-' + p) }), plugins: [ 'transform-class-properties', 'transform-react-constant-elements', 'transform-react-inline-elements', 'lodash', // fixes the babel budnling issue ].map(function(p) { return require.resolve('babel-plugin-' + p) }), } };
Revert "Revert "Fix module resolution for npm-link'd packages""
Revert "Revert "Fix module resolution for npm-link'd packages"" This reverts commit 8dc3d9b82be05fe3077e2cc82963a229858930b5.
JavaScript
mit
reddit/node-build
--- +++ @@ -7,12 +7,12 @@ 'es2015-native-modules', 'stage-2', 'react', - ], + ].map(function(p) { return require.resolve('babel-preset-' + p) }), plugins: [ 'transform-class-properties', 'transform-react-constant-elements', 'transform-react-inline-elements', 'lodash', // fixes the babel budnling issue - ], + ].map(function(p) { return require.resolve('babel-plugin-' + p) }), } };
2bf558768d4fc3bf4d1505c5a948c9962ca89b9e
lib/bumper.js
lib/bumper.js
function Bumper(coords, context, color) { this.minX = coords.minX; this.maxX = coords.maxX; this.minY = coords.minY; this.maxY = coords.maxY; this.context = context; this.type = coords.type; this.color = coords.color || "white" }; Bumper.prototype.draw = function() { if (this.type == "bumper") { this.context.fillStyle = this.color; } else { var image = new Image(); image.src = "../images/sand2.png" var pattern = this.context.createPattern(image, "repeat") this.context.fillStyle = pattern; } this.context.fillRect(this.minX, this.minY, this.maxX - this.minX, this.maxY - this.minY); return this; }; module.exports = Bumper;
function Bumper(coords, context, color) { this.minX = coords.minX; this.maxX = coords.maxX; this.minY = coords.minY; this.maxY = coords.maxY; this.context = context; this.type = coords.type; this.color = coords.color || "white" }; Bumper.prototype.draw = function() { if (this.type == "bumper") { this.context.fillStyle = this.color; } else { var image = new Image(); image.src = "./images/sand2.png" var pattern = this.context.createPattern(image, "repeat") this.context.fillStyle = pattern; } this.context.fillRect(this.minX, this.minY, this.maxX - this.minX, this.maxY - this.minY); return this; }; module.exports = Bumper;
Change relative path for sand image
Change relative path for sand image
JavaScript
mit
brennanholtzclaw/game_time,brennanholtzclaw/game_time
--- +++ @@ -14,7 +14,7 @@ } else { var image = new Image(); - image.src = "../images/sand2.png" + image.src = "./images/sand2.png" var pattern = this.context.createPattern(image, "repeat") this.context.fillStyle = pattern; }
816f68b9722ebdeaaf2fc9df1915e6d647b8ba79
test/e2e/dataExportSpec.js
test/e2e/dataExportSpec.js
const config = require('config') describe('/#/privacy-security/data-export', () => { describe('challenge "dataExportChallenge"', () => { beforeEach(() => { browser.get('/#/register') element(by.id('emailControl')).sendKeys('admun@' + config.get('application.domain')) element(by.id('passwordControl')).sendKeys('admun123') element(by.id('repeatPasswordControl')).sendKeys('admun123') element(by.name('securityQuestion')).click() element.all(by.cssContainingText('mat-option', 'Your eldest siblings middle name?')).click() element(by.id('securityAnswerControl')).sendKeys('admun') element(by.id('registerButton')).click() }) protractor.beforeEach.login({ email: 'admun@' + config.get('application.domain'), password: 'admun123' }) it('should be possible to steal admin user data by causing email clash during export', () => { browser.get('/#/privacy-security/data-export') element(by.id('formatControl')).all(by.tagName('mat-radio-button')).get(0).click() element(by.id('submitButton')).click() }) protractor.expect.challengeSolved({ challenge: 'GDPR Compliance Tier 2' }) }) })
const config = require('config') describe('/#/privacy-security/data-export', () => { xdescribe('challenge "dataExportChallenge"', () => { beforeEach(() => { browser.get('/#/register') element(by.id('emailControl')).sendKeys('admun@' + config.get('application.domain')) element(by.id('passwordControl')).sendKeys('admun123') element(by.id('repeatPasswordControl')).sendKeys('admun123') element(by.name('securityQuestion')).click() element.all(by.cssContainingText('mat-option', 'Your eldest siblings middle name?')).click() element(by.id('securityAnswerControl')).sendKeys('admun') element(by.id('registerButton')).click() }) protractor.beforeEach.login({ email: 'admun@' + config.get('application.domain'), password: 'admun123' }) it('should be possible to steal admin user data by causing email clash during export', () => { browser.get('/#/privacy-security/data-export') element(by.id('formatControl')).all(by.tagName('mat-radio-button')).get(0).click() element(by.id('submitButton')).click() }) protractor.expect.challengeSolved({ challenge: 'GDPR Compliance Tier 2' }) }) })
Disable flaky dataExport e2e test
Disable flaky dataExport e2e test
JavaScript
mit
bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop
--- +++ @@ -1,7 +1,7 @@ const config = require('config') describe('/#/privacy-security/data-export', () => { - describe('challenge "dataExportChallenge"', () => { + xdescribe('challenge "dataExportChallenge"', () => { beforeEach(() => { browser.get('/#/register') element(by.id('emailControl')).sendKeys('admun@' + config.get('application.domain'))
17b597513cb8c7aab777cd1ea5fe7228cd15c166
pogo-protos.js
pogo-protos.js
const fs = require('fs'), protobuf = require('protobufjs'); const builder = protobuf.newBuilder(), protoDir = __dirname + '/proto'; fs.readdirSync(protoDir) .filter(filename => filename.match(/\.proto$/)) .forEach(filename => protobuf.loadProtoFile(protoDir + '/' + filename, builder)); module.exports = builder.build("POGOProtos");
const fs = require('fs'), protobuf = require('protobufjs'); const builder = protobuf.newBuilder(), protoDir = __dirname + '/proto'; fs.readdirSync(protoDir) .filter(filename => filename.match(/\.proto$/)) .forEach(filename => protobuf.loadProtoFile(protoDir + '/' + filename, builder)); // Recursively add the packed=true to all packable repeated fields. // Repeated fields are packed by default in proto3 but protobuf.js incorrectly does not set the option. // See also: https://github.com/dcodeIO/protobuf.js/issues/432 function addPackedOption(ns) { if (ns instanceof protobuf.Reflect.Message) { ns.getChildren(protobuf.Reflect.Field).forEach(field => { if (field.repeated && protobuf.PACKABLE_WIRE_TYPES.indexOf(field.type.wireType) != -1) { field.options.packed = true; } }); } else if (ns instanceof protobuf.Reflect.Namespace) { ns.children.forEach(addPackedOption); } } addPackedOption(builder.lookup('POGOProtos')); module.exports = builder.build("POGOProtos");
Set packed=true for all repeated packable types
Set packed=true for all repeated packable types Workaround for https://github.com/dcodeIO/protobuf.js/issues/432
JavaScript
mit
cyraxx/node-pogo-protos,cyraxx/node-pogo-protos
--- +++ @@ -8,4 +8,20 @@ .filter(filename => filename.match(/\.proto$/)) .forEach(filename => protobuf.loadProtoFile(protoDir + '/' + filename, builder)); +// Recursively add the packed=true to all packable repeated fields. +// Repeated fields are packed by default in proto3 but protobuf.js incorrectly does not set the option. +// See also: https://github.com/dcodeIO/protobuf.js/issues/432 +function addPackedOption(ns) { + if (ns instanceof protobuf.Reflect.Message) { + ns.getChildren(protobuf.Reflect.Field).forEach(field => { + if (field.repeated && protobuf.PACKABLE_WIRE_TYPES.indexOf(field.type.wireType) != -1) { + field.options.packed = true; + } + }); + } else if (ns instanceof protobuf.Reflect.Namespace) { + ns.children.forEach(addPackedOption); + } +} +addPackedOption(builder.lookup('POGOProtos')); + module.exports = builder.build("POGOProtos");
f677fef8a3474eacd62a22ddedc25a3c91ec9c3f
src/js/components/interests/CardContentList.js
src/js/components/interests/CardContentList.js
import React, { PropTypes, Component } from 'react'; import CardContent from '../ui/CardContent'; export default class CardContentList extends Component { static propTypes = { contents : PropTypes.array.isRequired, userId : PropTypes.number.isRequired, otherUserId : PropTypes.number, onReport : PropTypes.func, }; constructor(props) { super(props); this.onReport = this.onReport.bind(this); } onReport(contentId, reason) { if (this.props.onReport) { this.props.onReport(contentId, reason); } } render() { const {contents, userId, otherUserId, onClickHandler} = this.props; return ( <div className="content-list"> {contents.map((content, index) => <CardContent key={index} hideLikeButton={false} {...content} loggedUserId={userId} otherUserId={otherUserId} embed_id={content.embed ? content.embed.id : null} embed_type={content.embed ? content.embed.type : null} fixedHeight={true} onReport={this.onReport}/>)} </div> ); } }
import React, { PropTypes, Component } from 'react'; import CardContent from '../ui/CardContent'; export default class CardContentList extends Component { static propTypes = { contents : PropTypes.array.isRequired, userId : PropTypes.number.isRequired, otherUserId : PropTypes.number, onReport : PropTypes.func, }; constructor(props) { super(props); this.onReport = this.onReport.bind(this); } onReport(contentId, reason) { this.props.onReport(contentId, reason); } render() { const {contents, userId, otherUserId} = this.props; return ( <div className="content-list"> {contents.map((content, index) => <CardContent key={index} hideLikeButton={false} {...content} loggedUserId={userId} otherUserId={otherUserId} embed_id={content.embed ? content.embed.id : null} embed_type={content.embed ? content.embed.type : null} fixedHeight={true} onReport={this.props.onReport ? this.onReport : null}/>)} </div> ); } }
Make report optional in CardContent
QS-1341: Make report optional in CardContent
JavaScript
agpl-3.0
nekuno/client,nekuno/client
--- +++ @@ -16,19 +16,17 @@ } onReport(contentId, reason) { - if (this.props.onReport) { - this.props.onReport(contentId, reason); - } + this.props.onReport(contentId, reason); } render() { - const {contents, userId, otherUserId, onClickHandler} = this.props; + const {contents, userId, otherUserId} = this.props; return ( <div className="content-list"> {contents.map((content, index) => <CardContent key={index} hideLikeButton={false} {...content} loggedUserId={userId} otherUserId={otherUserId} embed_id={content.embed ? content.embed.id : null} embed_type={content.embed ? content.embed.type : null} fixedHeight={true} - onReport={this.onReport}/>)} + onReport={this.props.onReport ? this.onReport : null}/>)} </div> ); }
65a3be9065227ba11ab0680f85c109d99b860bb4
tools/cli/default-npm-deps.js
tools/cli/default-npm-deps.js
import buildmessage from "../utils/buildmessage.js"; import { pathJoin, statOrNull, writeFile, unlink, } from "../fs/files"; const INSTALL_JOB_MESSAGE = "installing npm dependencies"; export function install(appDir, options) { const packageJsonPath = pathJoin(appDir, "package.json"); const needTempPackageJson = ! statOrNull(packageJsonPath); if (needTempPackageJson) { const { dependencies } = require("../static-assets/skel-minimal/package.json"); // Write a minimial package.json with the same dependencies as the // default new-app package.json file. writeFile( packageJsonPath, JSON.stringify({ dependencies }, null, 2) + "\n", "utf8", ); } const ok = buildmessage.enterJob(INSTALL_JOB_MESSAGE, function () { const npmCommand = ["install"]; if (options && options.includeDevDependencies) { npmCommand.push("--production=false"); } const { runNpmCommand } = require("../isobuild/meteor-npm.js"); const installResult = runNpmCommand(npmCommand, appDir); if (! installResult.success) { buildmessage.error( "Could not install npm dependencies for test-packages: " + installResult.error); return false; } return true; }); if (needTempPackageJson) { // Clean up the temporary package.json file created above. unlink(packageJsonPath); } return ok; }
import buildmessage from "../utils/buildmessage.js"; import { pathJoin, statOrNull, writeFile, unlink, } from "../fs/files"; const INSTALL_JOB_MESSAGE = "installing npm dependencies"; export function install(appDir, options) { const packageJsonPath = pathJoin(appDir, "package.json"); const needTempPackageJson = ! statOrNull(packageJsonPath); if (needTempPackageJson) { // NOTE we need skel-minimal to pull in jQuery which right now is required for Blaze const { dependencies } = require("../static-assets/skel-blaze/package.json"); // Write a minimial package.json with the same dependencies as the // default new-app package.json file. writeFile( packageJsonPath, JSON.stringify({ dependencies }, null, 2) + "\n", "utf8", ); } const ok = buildmessage.enterJob(INSTALL_JOB_MESSAGE, function () { const npmCommand = ["install"]; if (options && options.includeDevDependencies) { npmCommand.push("--production=false"); } const { runNpmCommand } = require("../isobuild/meteor-npm.js"); const installResult = runNpmCommand(npmCommand, appDir); if (! installResult.success) { buildmessage.error( "Could not install npm dependencies for test-packages: " + installResult.error); return false; } return true; }); if (needTempPackageJson) { // Clean up the temporary package.json file created above. unlink(packageJsonPath); } return ok; }
Fix test-packages in browser testing
Fix test-packages in browser testing
JavaScript
mit
Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor
--- +++ @@ -13,7 +13,8 @@ const needTempPackageJson = ! statOrNull(packageJsonPath); if (needTempPackageJson) { - const { dependencies } = require("../static-assets/skel-minimal/package.json"); + // NOTE we need skel-minimal to pull in jQuery which right now is required for Blaze + const { dependencies } = require("../static-assets/skel-blaze/package.json"); // Write a minimial package.json with the same dependencies as the // default new-app package.json file.
57617e3f76abbb7e0c4c421c0a6fbb1872a9ac87
app/templates/Gruntfile.js
app/templates/Gruntfile.js
'use strict'; module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { scss: { files: ['app/styles/**/*.scss'], tasks: ['scss'] } }, sass: { dist: { files: [{ expand: true, cwd: 'app/styles', src: ['*.scss'], dest: 'app/styles', ext: '.css' }] } } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['sass']); };
'use strict'; module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { scss: { files: ['app/styles/**/*.scss'], tasks: ['sass'] } }, sass: { dist: { files: [{ expand: true, cwd: 'app/styles', src: ['*.scss'], dest: 'app/styles', ext: '.css' }] } } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['sass']); };
Fix watch was referring to subtask with typo
Fix watch was referring to subtask with typo
JavaScript
bsd-3-clause
doberman/generator-doberman,doberman/generator-doberman
--- +++ @@ -7,7 +7,7 @@ watch: { scss: { files: ['app/styles/**/*.scss'], - tasks: ['scss'] + tasks: ['sass'] } },
4313cae1c10e687123c18625126537004ceb5131
lib/util/request-browser.js
lib/util/request-browser.js
/*! @license ©2013 Ruben Verborgh - Multimedia Lab / iMinds / Ghent University */ /** Browser replacement for the request module using jQuery. */ var EventEmitter = require('events').EventEmitter, SingleIterator = require('../../lib/iterators/Iterator').SingleIterator; require('setimmediate'); // Requests the given resource as an iterator function createRequest(settings) { var request = new EventEmitter(); // Delegate the request to jQuery's AJAX module var jqXHR = jQuery.ajax({ url: settings.url, timeout: settings.timeout, type: settings.method, headers: { accept: settings.headers && settings.headers.accept || '*/*' }, }) // Emit the result as a readable response iterator .success(function () { var response = new SingleIterator(jqXHR.responseText || ''); response.statusCode = jqXHR.status; response.headers = { 'content-type': jqXHR.getResponseHeader('content-type') }; request.emit('response', response); }); request.abort = function () { jqXHR.abort(); }; return request; } module.exports = createRequest;
/*! @license ©2013 Ruben Verborgh - Multimedia Lab / iMinds / Ghent University */ /** Browser replacement for the request module using jQuery. */ var EventEmitter = require('events').EventEmitter, SingleIterator = require('../../lib/iterators/Iterator').SingleIterator; require('setimmediate'); // Requests the given resource as an iterator function createRequest(settings) { var request = new EventEmitter(); // Delegate the request to jQuery's AJAX module var jqXHR = jQuery.ajax({ url: settings.url, timeout: settings.timeout, type: settings.method, headers: { accept: settings.headers && settings.headers.accept || '*/*' }, }) // Emit the result as a readable response iterator .success(function () { var response = new SingleIterator(jqXHR.responseText || ''); response.statusCode = jqXHR.status; response.headers = { 'content-type': jqXHR.getResponseHeader('content-type') }; request.emit('response', response); }) // Emit an error if the request fails .fail(function () { request.emit('error', new Error('Error requesting ' + settings.url)); }); // Aborts the request request.abort = function () { jqXHR.abort(); }; return request; } module.exports = createRequest;
Add error handling to browser requests.
Add error handling to browser requests.
JavaScript
mit
infitude/Client.js
--- +++ @@ -23,7 +23,12 @@ response.statusCode = jqXHR.status; response.headers = { 'content-type': jqXHR.getResponseHeader('content-type') }; request.emit('response', response); + }) + // Emit an error if the request fails + .fail(function () { + request.emit('error', new Error('Error requesting ' + settings.url)); }); + // Aborts the request request.abort = function () { jqXHR.abort(); }; return request;
c848a715cb5423085cb76c3bd958a1141ec2defd
public/app.js
public/app.js
$(document).ready(function() { var options = { chart: { renderTo: 'chart', type: 'spline', }, title: { text: 'Recent Water Values' }, xAxis: { type: 'datetime', title: { text: 'Date' } }, yAxis: { labels: { formatter: function() { return this.value == 1 ? 'Wet' : 'Dry'; } }, min: 0, max: 1, tickInterval: 1, title: { text: null } }, legend: { enabled: false }, series: [{}] }; $.getJSON('data.json', function(data) { var series = []; // Store some stats while parsing through var lastStatus; var lastWet; var lastDry; $.each(data, function(key, value) { series.push([Date.parse(key), value]); lastStatus = value; if (value == 1) { lastWet = key; } if (value == 0) { lastDry = key; } }); $('#current').text(lastStatus ? 'Wet' : 'Dry'); $('#lastWet').text(lastWet); $('#lastDry').text(lastDry); options.series[0].data = series; options.series[0].color = '#449944'; options.series[0].name = 'Water Value'; var chart = new Highcharts.Chart(options); }); });
$(document).ready(function() { var options = { chart: { renderTo: 'chart', type: 'spline', }, title: { text: 'Recent Water Values' }, xAxis: { type: 'datetime', title: { text: 'Date' } }, yAxis: { labels: { formatter: function() { return this.value == 1 ? 'Wet' : 'Dry'; } }, min: 0, max: 1, tickInterval: 1, title: { text: null } }, legend: { enabled: false }, series: [{}] }; // Don't cache the json :) $.ajaxSetup({ cache:false }); $.getJSON('data.json', function(data) { var series = []; // Store some stats while parsing through var lastStatus; var lastWet; var lastDry; $.each(data, function(key, value) { series.push([Date.parse(key), value]); lastStatus = value; if (value == 1) { lastWet = key; } if (value == 0) { lastDry = key; } }); $('#current').text(lastStatus ? 'Wet' : 'Dry'); $('#lastWet').text(lastWet); $('#lastDry').text(lastDry); options.series[0].data = series; options.series[0].color = '#449944'; options.series[0].name = 'Water Value'; var chart = new Highcharts.Chart(options); }); });
Remove cacheing of the json
Remove cacheing of the json
JavaScript
mit
amcolash/WaterPi,amcolash/WaterPi,amcolash/WaterPi,amcolash/WaterIoT,amcolash/WaterIoT,amcolash/WaterPi,amcolash/WaterIoT,amcolash/WaterIoT
--- +++ @@ -32,6 +32,11 @@ series: [{}] }; + // Don't cache the json :) + $.ajaxSetup({ + cache:false + }); + $.getJSON('data.json', function(data) { var series = [];
ba68dfed99a9616724512b11c9a7189552e71161
node-tests/unit/utils/rasterize-list-test.js
node-tests/unit/utils/rasterize-list-test.js
'use strict'; const expect = require('../../helpers/expect'); const fs = require('fs'); const sizeOf = require('image-size'); const RasterizeList = require('../../../src/utils/rasterize-list'); describe('RasterizeList', function() { // Hitting the file system is slow this.timeout(0); context('when src and toRasterize', () => { const src = 'node-tests/fixtures/icon.svg'; const toRasterize = [ { size: 60, name: 'icon-60', path: 'tmp/icon-60.png' } ]; afterEach(() => { toRasterize.forEach((rasterize) => { fs.unlinkSync(rasterize.path); }); }); it('returns a promise that resolves to an array', (done) => { expect( RasterizeList({src: src, toRasterize: toRasterize}) ).to.eventually.be.a('array').notify(done); }); it('writes the files to rasterize at the right size', (done) => { RasterizeList({src: src, toRasterize: toRasterize}).then(() => { toRasterize.forEach((rasterize) => { expect(fs.existsSync(rasterize.path)).to.equal(true); expect(sizeOf(rasterize.path).width).to.equal(rasterize.size); expect(sizeOf(rasterize.path).height).to.equal(rasterize.size); }); done(); }); }); }); });
'use strict'; const expect = require('../../helpers/expect'); const fs = require('fs'); const sizeOf = require('image-size'); const RasterizeList = require('../../../src/utils/rasterize-list'); describe('RasterizeList', function() { // Hitting the file system is slow this.timeout(0); context('when src and toRasterize', () => { const src = 'node-tests/fixtures/icon.svg'; const toRasterize = [ { size: 60, name: 'icon-60', path: 'tmp/icon-60.png' } ]; let subject; before(() => { subject = RasterizeList({src: src, toRasterize: toRasterize}); }); after(() => { toRasterize.forEach((rasterize) => { fs.unlinkSync(rasterize.path); }); }); it('returns a promise that resolves to an array', (done) => { expect(subject).to.eventually.be.a('array').notify(done); }); it('writes the files to rasterize at the right size', (done) => { subject.then(() => { toRasterize.forEach((rasterize) => { expect(fs.existsSync(rasterize.path)).to.equal(true); expect(sizeOf(rasterize.path).width).to.equal(rasterize.size); expect(sizeOf(rasterize.path).height).to.equal(rasterize.size); }); done(); }); }); }); });
Update test to improve speed by only writing and unlinking files once
refactor(rasterize-list): Update test to improve speed by only writing and unlinking files once
JavaScript
mit
isleofcode/splicon
--- +++ @@ -19,21 +19,24 @@ path: 'tmp/icon-60.png' } ]; + let subject; - afterEach(() => { + before(() => { + subject = RasterizeList({src: src, toRasterize: toRasterize}); + }); + + after(() => { toRasterize.forEach((rasterize) => { fs.unlinkSync(rasterize.path); }); }); it('returns a promise that resolves to an array', (done) => { - expect( - RasterizeList({src: src, toRasterize: toRasterize}) - ).to.eventually.be.a('array').notify(done); + expect(subject).to.eventually.be.a('array').notify(done); }); it('writes the files to rasterize at the right size', (done) => { - RasterizeList({src: src, toRasterize: toRasterize}).then(() => { + subject.then(() => { toRasterize.forEach((rasterize) => { expect(fs.existsSync(rasterize.path)).to.equal(true); expect(sizeOf(rasterize.path).width).to.equal(rasterize.size);
b5994cb13469f3d48f589a2a7910149ef46b0516
build/npm/stop-server.js
build/npm/stop-server.js
/* * Copyright (C) 2017 Steven Soloff * * This software is licensed under the terms of the GNU Affero General Public * License version 3 or later (https://www.gnu.org/licenses/). */ import config from './config' import del from 'del' import fs from 'fs' import kill from 'tree-kill' const serverPid = fs.readFileSync(config.paths.serverPid, { encoding: config.encodings.serverPid }) del(config.paths.serverPid) kill(serverPid)
/* * Copyright (C) 2017 Steven Soloff * * This software is licensed under the terms of the GNU Affero General Public * License version 3 or later (https://www.gnu.org/licenses/). */ import config from './config' import fs from 'fs' import kill from 'tree-kill' const serverPid = fs.readFileSync(config.paths.serverPid, { encoding: config.encodings.serverPid }) fs.unlinkSync(config.paths.serverPid) kill(serverPid)
Use fs.unlinkSync() to delete files
Use fs.unlinkSync() to delete files
JavaScript
agpl-3.0
ssoloff/hazelslack-server-core
--- +++ @@ -6,13 +6,12 @@ */ import config from './config' -import del from 'del' import fs from 'fs' import kill from 'tree-kill' const serverPid = fs.readFileSync(config.paths.serverPid, { encoding: config.encodings.serverPid }) -del(config.paths.serverPid) +fs.unlinkSync(config.paths.serverPid) kill(serverPid)
91fabd5f82b18a1b1e2acae87160be3488efc044
tests/helpers/start-app.js
tests/helpers/start-app.js
import Ember from 'ember'; import Application from '../../app'; import config from '../../config/environment'; export default function startApp(attrs) { let application; // use defaults, but you can override let attributes = Ember.assign({}, config.APP, attrs); Ember.run(() => { application = Application.create(attributes); application.setupForTesting(); application.injectTestHelpers(); }); return application; }
import Ember from 'ember'; import Application from '../../app'; import config from '../../config/environment'; export default function startApp(attrs) { let application; let assign = Ember.assign || Ember.merge // use defaults, but you can override let attributes = assign({}, config.APP, attrs); Ember.run(() => { application = Application.create(attributes); application.setupForTesting(); application.injectTestHelpers(); }); return application; }
Fix tests for ember v2.4.x
Fix tests for ember v2.4.x
JavaScript
mit
josemarluedke/ember-cli-numeral,jayphelps/ember-cli-numeral,josemarluedke/ember-cli-numeral
--- +++ @@ -4,9 +4,10 @@ export default function startApp(attrs) { let application; + let assign = Ember.assign || Ember.merge // use defaults, but you can override - let attributes = Ember.assign({}, config.APP, attrs); + let attributes = assign({}, config.APP, attrs); Ember.run(() => { application = Application.create(attributes);
8963d5f14cf34b4771a5dbcdad7181680aef7881
example/src/screens/types/Drawer.js
example/src/screens/types/Drawer.js
import React from 'react'; import {StyleSheet, View, Text} from 'react-native'; class MyClass extends React.Component { render() { return ( <View style={styles.container}> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, width: 300, alignItems: 'center', justifyContent: 'center', backgroundColor: '#ffffff', }, }); export default MyClass;
import React from 'react'; import {StyleSheet, View, Button} from 'react-native'; class MyClass extends React.Component { onShowModal = () => { this.props.navigator.toggleDrawer({ side: 'left' }); this.props.navigator.showModal({ screen: 'example.Types.Modal', title: `Modal` }); }; render() { return ( <View style={styles.container}> <View style={styles.button}> <Button onPress={this.onShowModal} title="Show Modal"/> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, width: 300, alignItems: 'center', justifyContent: 'center', backgroundColor: '#ffffff', }, button: { marginTop: 16 } }); export default MyClass;
Add show modal button to SideMenu
Add show modal button to SideMenu
JavaScript
mit
junedomingo/react-native-navigation,junedomingo/react-native-navigation,junedomingo/react-native-navigation,junedomingo/react-native-navigation
--- +++ @@ -1,12 +1,26 @@ import React from 'react'; -import {StyleSheet, View, Text} from 'react-native'; +import {StyleSheet, View, Button} from 'react-native'; class MyClass extends React.Component { + + onShowModal = () => { + this.props.navigator.toggleDrawer({ + side: 'left' + }); + this.props.navigator.showModal({ + screen: 'example.Types.Modal', + title: `Modal` + }); + }; render() { return ( <View style={styles.container}> - + <View style={styles.button}> + <Button + onPress={this.onShowModal} + title="Show Modal"/> + </View> </View> ); } @@ -20,6 +34,9 @@ justifyContent: 'center', backgroundColor: '#ffffff', }, + button: { + marginTop: 16 + } }); export default MyClass;
c120257c591597d8bf291396180e18f40bb3b1fa
common/components/utils/ghostApi.js
common/components/utils/ghostApi.js
// @flow import GhostContentAPI from "@tryghost/content-api"; const ghostContentAPI = window.GHOST_URL && window.GHOST_CONTENT_API_KEY && new GhostContentAPI({ url: window.GHOST_URL, key: window.GHOST_CONTENT_API_KEY, version: "v3", }); export type GhostPost = {| title: string, url: string, excerpt: ?string, custom_excerpt: ?string, feature_image: string, |}; class ghostApiHelper { static browse( tag: string, successCallback: ($ReadOnlyArray<GhostPost>) => void, errCallback: string => void ) { ghostContentAPI.posts .browse({ filter: "tag:" + tag, fields: "title, url, excerpt, custom_excerpt, feature_image", }) .then(postsResponse => { successCallback ? successCallback(postsResponse) : console.log(JSON.stringify(postsResponse)); }) .catch(err => { errCallback ? errCallback(err) : console.error(err); }); } static isConfigured(): boolean { return !!ghostContentAPI; } } export default ghostApiHelper;
// @flow import GhostContentAPI from "@tryghost/content-api"; const ghostContentAPI = window.GHOST_URL && window.GHOST_CONTENT_API_KEY && new GhostContentAPI({ url: window.GHOST_URL, key: window.GHOST_CONTENT_API_KEY, version: "v3", }); export type GhostPost = {| title: string, url: string, slug: string, excerpt: ?string, custom_excerpt: ?string, feature_image: string, |}; class ghostApiHelper { static browse( tag: string, successCallback: ($ReadOnlyArray<GhostPost>) => void, errCallback: string => void ) { ghostContentAPI.posts .browse({ filter: "tag:" + tag, fields: "title, url, slug, excerpt, custom_excerpt, feature_image", }) .then(postsResponse => { successCallback ? successCallback(postsResponse) : console.log(JSON.stringify(postsResponse)); }) .catch(err => { errCallback ? errCallback(err) : console.error(err); }); } static isConfigured(): boolean { return !!ghostContentAPI; } } export default ghostApiHelper;
Include slugs in ghost response
Include slugs in ghost response
JavaScript
mit
DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange
--- +++ @@ -13,6 +13,7 @@ export type GhostPost = {| title: string, url: string, + slug: string, excerpt: ?string, custom_excerpt: ?string, feature_image: string, @@ -27,7 +28,7 @@ ghostContentAPI.posts .browse({ filter: "tag:" + tag, - fields: "title, url, excerpt, custom_excerpt, feature_image", + fields: "title, url, slug, excerpt, custom_excerpt, feature_image", }) .then(postsResponse => { successCallback