commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
14d808a9e369fc38fff1975ea0e6225b788b12d9
client/app/serializers/cabin.js
client/app/serializers/cabin.js
import DS from 'ember-data'; import ApplicationSerializer from '../serializers/application'; export default ApplicationSerializer.extend({ normalize: function (modelClass, resourceHash, prop) { var normalizedHash = resourceHash; var normalizedFasiliteter = []; // Maps `fasiliteter` object to an array of objects with the key as `type` and value as `kommentar` if (resourceHash.fasiliteter) { for (var key in resourceHash.fasiliteter) { normalizedFasiliteter.push({type: key, kommentar: resourceHash.fasiliteter[key]}); } normalizedHash.fasiliteter = normalizedFasiliteter; } return this._super(modelClass, normalizedHash, prop); }, serialize: function(snapshot, options) { var json = this._super(snapshot, options); // Maps `fasiliteter` array back to object if (json.fasiliteter && json.fasiliteter.length) { var serializedFasiliteter = {}; for (var i = 0; i < json.fasiliteter.length; i++) { serializedFasiliteter[json.fasiliteter[i]['type']] = json.fasiliteter[i]['kommentar'] || ''; } json.fasiliteter = serializedFasiliteter; } return json; } });
import DS from 'ember-data'; import ApplicationSerializer from '../serializers/application'; export default ApplicationSerializer.extend({ normalize: function (modelClass, resourceHash, prop) { var normalizedHash = resourceHash; var normalizedFasiliteter = []; // Maps `fasiliteter` object to an array of objects with the key as `type` and value as `kommentar` if (resourceHash.fasiliteter) { for (var key in resourceHash.fasiliteter) { normalizedFasiliteter.push({type: key, kommentar: resourceHash.fasiliteter[key]}); } normalizedHash.fasiliteter = normalizedFasiliteter; } return this._super(modelClass, normalizedHash, prop); }, serialize: function(snapshot, options) { var json = this._super(snapshot, options); // Maps `fasiliteter` array back to object if (json.fasiliteter && json.fasiliteter.length) { var serializedFasiliteter = {}; for (var i = 0; i < json.fasiliteter.length; i++) { serializedFasiliteter[json.fasiliteter[i]['type']] = json.fasiliteter[i]['kommentar'] || ''; } json.fasiliteter = serializedFasiliteter; } // Update `tilrettelagt_for` with types from `tilrettelegginger` if (json.tilrettelegginger && json.tilrettelegginger.length) { json.tilrettelagt_for = json.tilrettelegginger.mapBy('type'); } return json; } });
Update tilrettelagt_for array with types from tilrettelegginger on save
Update tilrettelagt_for array with types from tilrettelegginger on save
JavaScript
mit
Turistforeningen/Hytteadmin,Turistforeningen/Hytteadmin
d88b60ddc0bbea880011b48a4d5e9a1374b7b67a
babel-defaults.js
babel-defaults.js
/* eslint-disable object-shorthand */ module.exports = { // We need to make sure that the transpiler hit the linoleum source since we are // not building to npm or simliar. ignore: function(filename) { return ((/node_modules/.test(filename)) && !(/linoleum(-[^/]*)?\/electron/.test(filename)) && !(/linoleum(-[^/]*)?\/src/.test(filename)) && !(/linoleum(-[^/]*)?\/tasks/.test(filename))) || (/\$.*\$/.test(filename)); }, sourceMap: 'inline', auxiliaryCommentBefore: 'istanbul ignore start', auxiliaryCommentAfter: 'istanbul ignore end', presets: [ require.resolve('babel-preset-react'), require.resolve('babel-preset-es2015'), require.resolve('babel-preset-stage-0') ] };
/* eslint-disable object-shorthand */ module.exports = { // We need to make sure that the transpiler hit the linoleum source since we are // not building to npm or simliar. ignore: function(filename) { return ((/node_modules/.test(filename)) && !(/linoleum(-[^/]*)?\/(electron|src|tasks|Gulpfile)/.test(filename))) || (/\$.*\$/.test(filename)); }, sourceMap: 'inline', auxiliaryCommentBefore: 'istanbul ignore start', auxiliaryCommentAfter: 'istanbul ignore end', presets: [ require.resolve('babel-preset-react'), require.resolve('babel-preset-es2015'), require.resolve('babel-preset-stage-0') ] };
Simplify bable includes and add Gulpfiles
Simplify bable includes and add Gulpfiles
JavaScript
mit
kpdecker/linoleum
b8ebb9207195e23afa6c0ce3f943c6908abee740
rollup.config.js
rollup.config.js
import buble from '@rollup/plugin-buble' export default { input: 'src/commands.js', output: { dir: 'dist', format: 'cjs', sourcemap: true }, plugins: [buble()], external(id) { return !/^[\.\/]/.test(id) } }
import buble from '@rollup/plugin-buble' export default { input: './src/commands.js', output: { dir: 'dist', format: 'cjs', sourcemap: true }, plugins: [buble()], external(id) { return !/^[\.\/]/.test(id) } }
Add missing ./ prefix in rollup input
Add missing ./ prefix in rollup input
JavaScript
mit
ProseMirror/prosemirror-commands
1f2587a913a987fa0eae03bfa4b4dd1cffb8a5e1
controllers/users/collection.js
controllers/users/collection.js
module.exports = (function(){ // GET /users/:id/media?lat=<LAT>&lng=<LNG>&time=<TIME> return function* collection(id) { // Twitter Requests var twitterDef = require('q').defer() var TwitterManager = require('../media/twitter'); var twitterGranuals = twitterDef.promise.then(TwitterManager.search); // var twitterDef = require('q').defer() // var instagramDef = require('q').defer() var InstagramManager = require('../media/instagram'); // var instagramGranuals = instagramDef.promise.then(InstagramManager.search); var instagramGranuals = InstagramManager.search(this.request.url); // Flickr Requests // var FlickrManager = require('../media/flickr'); // var flickrGranuals = yield FlickrManager.search(this.request.url); // Creating a universal capsul object var capsul = { "user_id": id, "latitude": require('../../helpers').paramsForUrl(this.request.url).lat, "longitude": require('../../helpers').paramsForUrl(this.request.url).lng, "timestamp": require('../../helpers').paramsForUrl(this.request.url).time, "data": [] } // def.resolve(this.request.url) // var instaGranuals = def.promise.then(InstagramManager.search); // capsul.data.push(instagramGranuals) twitterDef.resolve(this.request.url) // instagramDef.resolve(this.request.url) capsul.data.push(twitterGranuals); capsul.data.push(instagramGranuals) this.body = yield capsul; } })();
module.exports = (function(){ // GET /users/:id/media?lat=<LAT>&lng=<LNG>&time=<TIME> return function* collection(id) { var Q = require('q'); var TwitterManager = require('../media/twitter'); var InstagramManager = require('../media/instagram'); // Twitter Requests var twitterDef = Q.defer(); var twitterGranuals = twitterDef.promise .then(TwitterManager.search); // Instagram Requests var instagramDef = Q.defer(); var instagramGranuals = instagramDef.promise .then(InstagramManager.search); // Flickr Requests // var FlickrManager = require('../media/flickr'); // var flickrGranuals = yield FlickrManager.search(this.request.url); // Creating a universal capsul object var capsul = { "user_id": id, "latitude": require('../../helpers').paramsForUrl(this.request.url).lat, "longitude": require('../../helpers').paramsForUrl(this.request.url).lng, "timestamp": require('../../helpers').paramsForUrl(this.request.url).time, "data": [] } twitterDef.resolve(this.request.url) instagramDef.resolve(this.request.url) capsul.data.push(twitterGranuals); capsul.data.push(instagramGranuals); this.body = yield capsul; } })();
Refactor to use promises for social media service responses.
Refactor to use promises for social media service responses.
JavaScript
mit
capsul/capsul-api
4e35bbcc85351ff97aeacd3674d16612c94e78be
routes/routes.js
routes/routes.js
var artistController = require('../controllers/artist-controller'); var genreController = require('../controllers/genre-controller'); module.exports = function(app, passport) { app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' })); app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect : '/' }), function(req, res) { return res.status(200).send(req.user); }); app.get('/profile', function(req, res) { return res.send(200); }); app.post('/api/artist/:id/like', artistController.likeArtist); app.get('/api/artist/recommendation', artistController.getArtistRecommendations); app.get('/api/genre', genreController.getGenres); app.get('/api/genre/artists', genreController.getArtistsByGenre); app.get('*', function(req, res) { return res.render('index.html'); }); };
var artistController = require('../controllers/artist-controller'); var genreController = require('../controllers/genre-controller'); module.exports = function(app, passport) { app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' })); app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect : '/', successRedirect : '/' })); app.get('/profile', function(req, res) { return res.send(200); }); app.post('/api/artist/:id/like', artistController.likeArtist); app.get('/api/artist/recommendation', artistController.getArtistRecommendations); app.get('/api/genre', genreController.getGenres); app.get('/api/genre/artists', genreController.getArtistsByGenre); app.get('*', function(req, res) { return res.render('index.html'); }); };
Change route file to be used later
Change route file to be used later
JavaScript
mit
kurtbradd/facebook-music-recommender,kurtbradd/facebook-music-recommender,kurtbradd/facebook-music-recommender,kurtbradd/facebook-music-recommender
d7c0f286914c260f545b5c9c095a19daed918ff1
cms/static/cms/js/user/index.js
cms/static/cms/js/user/index.js
$.extend( true, $.fn.dataTable.defaults, { "autoWidth": false, "columnDefs": [ { width: '10%', targets: 0 }, { width: '15%', targets: 1 }, { width: '10%', targets: 2 }, { width: '10%', targets: 3 }, { width: '25%', targets: 4 }, { width: '10%', targets: 5 }, { width: '10%', targets: 6 }, ], "order": [[ 0, "asc" ]] } ); $(document).ready(function() { $('#items').DataTable(); // Breadcum $('#breadcrumb-home').append(en.cms.breadcrumb.home); $('#breadcrumb-user').append(en.cms.breadcrumb.user); // Table headers $('#header-username').append(en.cms.header.username); $('#header-email').append(en.cms.header.email); $('#header-firstname').append(en.cms.header.firstname); $('#header-lastname').append(en.cms.header.lastname); $('#header-lastlogin').append(en.cms.header.lastlogin); $('#header-isstaff').append(en.cms.header.isstaff); $('#header-isactive').append(en.cms.header.isactive); $('#main-title').append(en.cms.breadcrumb.user); $('#add').append(en.cms.action.add_user); } );
$.extend( true, $.fn.dataTable.defaults, { "autoWidth": false, "columnDefs": [ { width: '10%', targets: 0 }, { width: '10%', targets: 1 }, { width: '10%', targets: 2 }, { width: '10%', targets: 3 }, { width: '20%', targets: 4 }, { width: '10%', targets: 5 }, { width: '10%', targets: 6 }, { width: '20%', targets: 7 }, ], "order": [[ 0, "asc" ]] } ); $(document).ready(function() { $('#items').DataTable(); // Breadcum $('#breadcrumb-home').append(en.cms.breadcrumb.home); $('#breadcrumb-user').append(en.cms.breadcrumb.user); // Table headers $('#header-username').append(en.cms.header.username); $('#header-email').append(en.cms.header.email); $('#header-firstname').append(en.cms.header.firstname); $('#header-lastname').append(en.cms.header.lastname); $('#header-lastlogin').append(en.cms.header.lastlogin); $('#header-isstaff').append(en.cms.header.isstaff); $('#header-isactive').append(en.cms.header.isactive); $('#main-title').append(en.cms.breadcrumb.user); $('#add').append(en.cms.action.add_user); } );
Fix DataTable in User page
[Release_0.0.1] Fix DataTable in User page
JavaScript
apache-2.0
deka108/mathqa-server,deka108/mathqa-server,deka108/mathqa-server,deka108/mathqa-server,deka108/meas_deka,deka108/meas_deka,deka108/meas_deka,deka108/meas_deka
745633dabd3e695a30edc5fbd1625bb7f09aa26d
server/config.js
server/config.js
const productionConfig = { apiBase: 'http://api.storypalette.net/v1/', socketBase: 'http://api.storypalette.net/', environment: 'production', port: 8882, }; const developmentConfig = { apiBase: 'http://localhost:8880/v1/', socketBase: 'http://localhost:8880/', environment: 'local', port: 8882, } const config = (process.env.NODE_ENV === 'development') ? developmentConfig : productionConfig; module.exports = config;
const productionConfig = { //apiBase: 'http://api.storypalette.net/v1/', //socketBase: 'http://api.storypalette.net/', apiBase: 'http://storypalette-server.herokuapp.com/v1/', socketBase: 'http://storypalette-server.herokuapp.com/', environment: 'production', port: 8882, }; const developmentConfig = { apiBase: 'http://localhost:8880/v1/', socketBase: 'http://localhost:8880/', environment: 'local', port: 8882, } const config = (process.env.NODE_ENV === 'development') ? developmentConfig : productionConfig; module.exports = config;
Use heroku api base for now
Use heroku api base for now
JavaScript
isc
storypalette/storypalette-performer-touch,storypalette/storypalette-performer-touch
10290106b9a075685852699cb8bbaf5bb3a012ca
tutorials/customProjectors/customProjectors.js
tutorials/customProjectors/customProjectors.js
window.onload = function() { var xScale = new Plottable.LinearScale(); var yScale = new Plottable.LinearScale(); var xAxis = new Plottable.XAxis(xScale, "bottom"); var yAxis = new Plottable.YAxis(yScale, "left"); // A DataSource is a Plottable object that maintains data and metadata, and updates dependents when it changes // In the previous example, we implicitly created a DataSource by putting the data directly into the Renderer constructor var gitDataSource = new Plottable.DataSource(gitData); var renderer = new Plottable.LineRenderer(gitDataSource, xScale, yScale); // We define an accessor function that the renderer will use to access a "Perspective" into the DataSource function dayAccessor(d) { return d.day; } // By calling renderer.project, we tell the renderer to set the "x" attribute using the dayAccessor function // and to project it through the xScale. This creates a binding between the data and the scale, so that the // scale automatically sets its domain, and will update its domain if the data changes renderer.project("x", dayAccessor, xScale); // If Plottable gets a string as an accessor argument, it will automatically turn it into a key function, as follows: // project(attr, "total_commits", scale) == project(attr, function(d) {return d.total_commits}, scale) renderer.project("y", "total_commits", yScale); // This accessor is somewhat more sophisticated - it performs some data aggregation on-the-fly for renderering function linesAddedAccessor(d) { var total = 0; d.changes.forEach(function(c) { total += c.additions; }); return total; } // Make a LogScale. Since the range doesn't correspond to the layout bounds of a renderer, we need to set the range ourselves. var radiusScale = new Plottable.LogScale().range([1, 10]); renderer.project("r", linesAddedAccessor, radiusScale) var chart = new Plottable.Table([ [yAxis, renderer], [null, xAxis ] ]); chart.renderTo("#chart"); }
window.onload = function() { var xScale = new Plottable.LinearScale(); var yScale = new Plottable.LinearScale(); var xAxis = new Plottable.XAxis(xScale, "bottom"); var yAxis = new Plottable.YAxis(yScale, "left"); var renderer = new Plottable.LineRenderer(gitData, xScale, yScale); function getXDataValue(d) { return d.day; } renderer.project("x", getXDataValue, xScale); function getYDataValue(d) { return d.total_commits; } renderer.project("y", getYDataValue, yScale); var chart = new Plottable.Table([ [yAxis, renderer], [null, xAxis ] ]); chart.renderTo("#chart"); }
Revert "Update customProjector example to use a scale. Doesn't work yet (pending merge to gh-pages)"
Revert "Update customProjector example to use a scale. Doesn't work yet (pending merge to gh-pages)" This reverts commit df014cfaed10a0eba602ebb0355ef83452faf133. Modified example instead of copying.
JavaScript
mit
RobertoMalatesta/plottable,jacqt/plottable,NextTuesday/plottable,NextTuesday/plottable,gdseller/plottable,jacqt/plottable,palantir/plottable,NextTuesday/plottable,alyssaq/plottable,iobeam/plottable,alyssaq/plottable,jacqt/plottable,palantir/plottable,RobertoMalatesta/plottable,palantir/plottable,danmane/plottable,danmane/plottable,softwords/plottable,softwords/plottable,onaio/plottable,danmane/plottable,gdseller/plottable,iobeam/plottable,alyssaq/plottable,onaio/plottable,onaio/plottable,palantir/plottable,iobeam/plottable,softwords/plottable,gdseller/plottable,RobertoMalatesta/plottable
04cc01275c74084ad1d01180ae6a7cf4f3438875
shared/shared.js
shared/shared.js
import { $assign, $fetch, $replaceAll } from 'domose'; /* Dispatch an Custom Event with a detail /* ========================================================================== */ function $dispatch(target, type, detail) { // an event const event = document.createEvent('CustomEvent'); event.initCustomEvent(type, true, true, detail); target.dispatchEvent(event); } export { $assign, $dispatch, $fetch, $replaceAll };
import { $assign, $fetch, $replaceAll } from 'domose'; /* Dispatch an Custom Event with a detail /* ========================================================================== */ function $dispatch(target, type, detail) { // an event const event = document.createEvent('CustomEvent'); event.initCustomEvent(type, true, true, detail); target.dispatchEvent(event); } function $enableFocusRing(target) { // retooled from https://github.com/jonathantneal/js-focus-ring let keyboardThrottleTimeoutID; const activeElements = []; target.addEventListener('blur', () => { activeElements.forEach((activeElement) => { activeElement.removeAttribute('js-focus'); activeElement.removeAttribute('js-focus-ring'); }); }, true); target.addEventListener('focus', () => { const activeElement = document.activeElement; if (activeElement instanceof Element) { activeElement.setAttribute('js-focus', ''); if (keyboardThrottleTimeoutID) { activeElement.setAttribute('js-focus-ring', ''); } activeElements.push(activeElement); } }, true); target.addEventListener('keydown', () => { keyboardThrottleTimeoutID = clearTimeout(keyboardThrottleTimeoutID) || setTimeout(() => { keyboardThrottleTimeoutID = 0; }, 100); }, true); } export { $assign, $dispatch, $enableFocusRing, $fetch, $replaceAll };
Add method to selectively enable focus ring
Add method to selectively enable focus ring
JavaScript
apache-2.0
gschnall/global-nav,gschnall/global-nav
e8dac4b099ea892d8953eedcb035cd802414600b
js/lib/externs.js
js/lib/externs.js
/* * externs.js - define externs for the google closure compiler * * Copyright © 2012-2015, JEDLSoft * * 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. */ // !dependencies: false function console(str){}; function JSON(str){}; console.log = function (str){}; var PalmSystem, process, require, module, environment, exports, global, Intl, Qt;
/* * externs.js - define externs for the google closure compiler * * Copyright © 2012-2015, JEDLSoft * * 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. */ // !dependencies: false function console(str){}; function JSON(str){}; console.log = function (str){}; var PalmSystem, require, module, environment, exports, global, Intl, Qt; var process = {env: {LANG: "", LANGUAGE: "", LC_ALL:""}};
Fix closure compiler warnings for process.env.*
Fix closure compiler warnings for process.env.* git-svn-id: 9171c9e75a46cbc9e9e8eb6adca0da07872ad553@1885 5ac057f5-ce63-4fb3-acd1-ab13b794ca36
JavaScript
apache-2.0
iLib-js/iLib,iLib-js/iLib,iLib-js/iLib,iLib-js/iLib,iLib-js/iLib
c38995393eb051f0430d6241725c673aa40db704
tests/integration/components/pulse-settings/component-test.js
tests/integration/components/pulse-settings/component-test.js
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('pulse-settings', 'Integration | Component | pulse settings', { integration: true }); test('it renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{pulse-settings}}`); assert.equal(this.$().text().trim(), ''); // Template block usage: this.render(hbs` {{#pulse-settings}} template block text {{/pulse-settings}} `); assert.equal(this.$().text().trim(), 'template block text'); });
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('pulse-settings', 'Integration | Component | pulse settings', { integration: true }); test('it renders', function(assert) { this.render(hbs`{{pulse-settings}}`); assert.ok(/Set Up/.test(this.$().text())); });
Fix tests for pulse-settings component
Fix tests for pulse-settings component
JavaScript
apache-2.0
usecanvas/web-v2,usecanvas/web-v2,usecanvas/web-v2
9772f857d22a68912b96d113f7953b89e733e33c
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-bower-concat'); var taskConfig = { pkg: grunt.file.readJSON('package.json'), bower_concat: { all: { dest: 'build/_bower.js', cssDest: 'build/_bower.css', include: [ 'underscore', 'jquery-mousewheel', 'jquery', 'bootstrap' ], dependencies: { 'underscore': 'jquery', 'jquery-mousewheel': 'jquery', 'bootstrap': 'jquery' }, bowerOptions: { relative: false } } } } grunt.initConfig(grunt.util._.extend(taskConfig)); };
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-bower-concat'); var taskConfig = { pkg: grunt.file.readJSON('package.json'), bower_concat: { all: { dest: 'build/_bower.js', cssDest: 'build/_bower.css', include: [ 'underscore', 'jquery-mousewheel', 'jquery', 'bootstrap' ], mainFiles: { bootstrap: ['dist/css/bootstrap.css','dist/js/bootstrap.js'] }, dependencies: { 'underscore': 'jquery', 'jquery-mousewheel': 'jquery', 'bootstrap': 'jquery' }, bowerOptions: { relative: false } } } } grunt.initConfig(grunt.util._.extend(taskConfig)); };
Add Bootstrap CSS file reference in grunt task
Add Bootstrap CSS file reference in grunt task
JavaScript
mit
pra85/grunt-bower-concat-example
7f79b3c28a91e28548fb93ffdf63164707f60a1f
app/index-load-script.js
app/index-load-script.js
var baseHref = `http://localhost: ${process.env.npm_package_config_port}` var appEntry = `${baseHref} /gen/app.entry.js` var baseNode = document.createElement('base') baseNode.href = baseHref document.getElementsByTagName('head')[0].appendChild(baseNode) const createScript = function (scriptPath) { return new Promise((resolve, reject) => { var script = document.createElement('script') script.type = 'text/javascript' script.src = scriptPath script.async = true script.onload = resolve script.onerror = reject document.body.appendChild(script) }) } document.querySelector('#webpackLoading').style.display = 'block' createScript(appEntry).catch(() => { document.querySelector('#webpackLoading').style.display = 'none' document.querySelector('#setupError').style.display = 'block' })
var baseHref = 'http://localhost:' + process.env.npm_package_config_port var appEntry = baseHref + '/gen/app.entry.js' var baseNode = document.createElement('base') baseNode.href = baseHref document.getElementsByTagName('head')[0].appendChild(baseNode) const createScript = function (scriptPath) { return new Promise(function (resolve, reject) { var script = document.createElement('script') script.type = 'text/javascript' script.src = scriptPath script.async = true script.onload = resolve script.onerror = reject document.body.appendChild(script) }) } document.querySelector('#webpackLoading').style.display = 'block' createScript(appEntry).catch(function () { document.querySelector('#webpackLoading').style.display = 'none' document.querySelector('#setupError').style.display = 'block' })
Fix loading bug with last merge
Fix loading bug with last merge
JavaScript
mpl-2.0
jonathansampson/browser-laptop,jonathansampson/browser-laptop,MKuenzi/browser-laptop,dcposch/browser-laptop,Sh1d0w/browser-laptop,luixxiul/browser-laptop,diasdavid/browser-laptop,willy-b/browser-laptop,diasdavid/browser-laptop,dcposch/browser-laptop,darkdh/browser-laptop,willy-b/browser-laptop,manninglucas/browser-laptop,Sh1d0w/browser-laptop,darkdh/browser-laptop,MKuenzi/browser-laptop,Sh1d0w/browser-laptop,MKuenzi/browser-laptop,jonathansampson/browser-laptop,luixxiul/browser-laptop,darkdh/browser-laptop,MKuenzi/browser-laptop,manninglucas/browser-laptop,pmkary/braver,manninglucas/browser-laptop,timborden/browser-laptop,Sh1d0w/browser-laptop,timborden/browser-laptop,timborden/browser-laptop,dcposch/browser-laptop,darkdh/browser-laptop,pmkary/braver,dcposch/browser-laptop,jonathansampson/browser-laptop,luixxiul/browser-laptop,diasdavid/browser-laptop,timborden/browser-laptop,willy-b/browser-laptop,luixxiul/browser-laptop,pmkary/braver,pmkary/braver,diasdavid/browser-laptop,manninglucas/browser-laptop,willy-b/browser-laptop
20d13a2f21c00968cd9c749dc1527c0ed43a3a34
wp-content/themes/template/src/scripts/main.js
wp-content/themes/template/src/scripts/main.js
$(document).ready(function () { $('#primaryPostForm').validate() // Image preview in upload input $('.form__input--upload').on('change', function () { var label = $(this).data('label'); var image = (window.URL ? URL : webkitURL).createObjectURL(this.files[0]); $(label).css('background-image', 'url(' + image + ')'); $('.remover').css('display', 'block'); }) $('.remover').on('click', function () { var input = $(this).data('for'); var label = $(input).data('label'); $(input).wrap('<form>').closest('form').get(0).reset(); $(input).unwrap(); $(label).css('background-image', 'none'); $('.remover').css('display', 'none'); }) $('.color-switcher-button').on('click', function() { $('body').fadeOut('fast').siblings('head').find('link#stylesheet').attr('href', $(this).data('stylesheet')).closest('head').siblings('body').fadeIn('fast'); }) });
$(document).ready(function () { $('#primaryPostForm').validate() // Image preview in upload input $('.form__input--upload').on('change', function () { var label = $(this).data('label'); var image = (window.URL ? URL : webkitURL).createObjectURL(this.files[0]); $(label).css('background-image', 'url(' + image + ')'); $('.remover').css('display', 'block'); }) $('.remover').on('click', function () { var input = $(this).data('for'); var label = $(input).data('label'); $(input).wrap('<form>').closest('form').get(0).reset(); $(input).unwrap(); $(label).css('background-image', 'none'); $('.remover').css('display', 'none'); }) $('.color-switcher-button').on('click', function() { $('link#stylesheet').attr('href', $(this).data('stylesheet')); }) });
Remove color switcher fade effect
Remove color switcher fade effect
JavaScript
mit
DNepovim/kraj-praha,DNepovim/kraj-praha,DNepovim/kraj-praha
cc1a92e941a68df9f0f606c1b399e83a013a9aca
aura-components/src/main/components/auradocs/search/searchController.js
aura-components/src/main/components/auradocs/search/searchController.js
/* * Copyright (C) 2012 salesforce.com, inc. * * 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. */ { handleSearch : function(cmp,event){ var searchTerm = event.getParam('searchTerm') || (event.getSource() && event.getSource().getElement().value); if (searchTerm.length > 0) { var results_location = "#help?topic=searchResults&searchTerm=" + escape(searchTerm); window.location = results_location; } } }
/* * Copyright (C) 2012 salesforce.com, inc. * * 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. */ { handleSearch : function(cmp,event){ var searchTerm = event.getParam('searchTerm') || event.getSource().getElement().value; if (searchTerm.length > 0) { var results_location = "#help?topic=searchResults&searchTerm=" + escape(searchTerm); window.location = results_location; } } }
Revert "Fix for possible deref of cleaned up source component"
Revert "Fix for possible deref of cleaned up source component" This reverts commit 2b35e47816edb0f655fca21d108d651a6a218b2c.
JavaScript
apache-2.0
madmax983/aura,badlogicmanpreet/aura,lcnbala/aura,badlogicmanpreet/aura,madmax983/aura,forcedotcom/aura,SalesforceSFDC/aura,forcedotcom/aura,DebalinaDey/AuraDevelopDeb,madmax983/aura,DebalinaDey/AuraDevelopDeb,navyliu/aura,forcedotcom/aura,SalesforceSFDC/aura,madmax983/aura,igor-sfdc/aura,lhong375/aura,navyliu/aura,forcedotcom/aura,igor-sfdc/aura,lcnbala/aura,DebalinaDey/AuraDevelopDeb,badlogicmanpreet/aura,lhong375/aura,lcnbala/aura,navyliu/aura,TribeMedia/aura,navyliu/aura,TribeMedia/aura,TribeMedia/aura,lcnbala/aura,SalesforceSFDC/aura,TribeMedia/aura,igor-sfdc/aura,madmax983/aura,lhong375/aura,badlogicmanpreet/aura,DebalinaDey/AuraDevelopDeb,lhong375/aura,SalesforceSFDC/aura,navyliu/aura,madmax983/aura,lcnbala/aura,navyliu/aura,SalesforceSFDC/aura,badlogicmanpreet/aura,DebalinaDey/AuraDevelopDeb,badlogicmanpreet/aura,igor-sfdc/aura,SalesforceSFDC/aura,forcedotcom/aura,DebalinaDey/AuraDevelopDeb,TribeMedia/aura,igor-sfdc/aura,lcnbala/aura,TribeMedia/aura
d12eeb4944e9414b1f0543fda462fff3656b9970
application/bar/index.js
application/bar/index.js
var builder = require('focus').component.builder; var React = require('react'); var applicationStore = require('focus').application.builtInStore(); var barMixin = { getDefaultProps: function getCartridgeDefaultProps(){ return { appName: "", style: {} }; }, /** @inheriteddoc */ getInitialState: function getCartridgeInitialState() { return this._getStateFromStore(); }, /** @inheriteddoc */ componentWillMount: function cartridgeWillMount() { applicationStore.addSummaryComponentChangeListener(this._handleComponentChange); }, /** @inheriteddoc */ componentWillUnMount: function cartridgeWillUnMount(){ applicationStore.removeSummaryComponentChangeListener(this._onComponentChange); }, _getStateFromStore: function getCartridgeStateFromStore(){ return {summaryComponent: applicationStore.getSummaryComponent() || {component: 'div', props: {}}}; }, _handleComponentChange: function _handleComponentChangeBarSummary(){ this.setState(this._getStateFromStore()); }, /** @inheriteddoc */ render: function renderBar() { var className = `bar ${this.props.style.className}`; return ( <div className={className} data-focus='bar'> <div className='applicationName'>{this.props.appName}</div> <this.state.summaryComponent.component {...this.state.summaryComponent.props}/> </div> ); } }; module.exports = builder(barMixin);
Add summary inside the bar.
[bar] Add summary inside the bar.
JavaScript
mit
KleeGroup/focus-components,Bernardstanislas/focus-components,anisgh/focus-components,Bernardstanislas/focus-components,KleeGroup/focus-components,asimsir/focus-components,JabX/focus-components,sebez/focus-components,Ephrame/focus-components,JabX/focus-components,sebez/focus-components,anisgh/focus-components,Ephrame/focus-components,Jerom138/focus-components,Jerom138/focus-components,anisgh/focus-components,Bernardstanislas/focus-components,Jerom138/focus-components,JRLK/focus-components,get-focus/focus-components,Ephrame/focus-components,JRLK/focus-components,asimsir/focus-components,JRLK/focus-components
a8836a562b1a7d1f0d4a4f59f9c30c3b46ca7318
grid-packages/ag-grid-docs/src/javascript-charts-axis/axis-tick-count/main.js
grid-packages/ag-grid-docs/src/javascript-charts-axis/axis-tick-count/main.js
var options = { container: document.getElementById('myChart'), data: generateSpiralData(), series: [{ type: 'line', xKey: 'x', yKey: 'y', marker: { enabled: false } }], axes: [ { type: 'number', position: 'bottom', tick: { count: 10, }, }, { type: 'number', position: 'left', tick: { count: 10, }, } ], legend: { enabled: false } }; var chart = agCharts.AgChart.create(options); function setTickCountTo5() { chart.axes[0].tick.count = 5; chart.axes[1].tick.count = 5; chart.performLayout(); } function setTickCountTo10() { chart.axes[0].tick.count = 10; chart.axes[1].tick.count = 10; chart.performLayout(); } function generateSpiralData() { var a = 1; var b = 1; var data = []; var step = 0.1; for (var th = 1; th < 50; th += step) { var r = a + b * th; var datum = { x: r * Math.cos(th), y: r * Math.sin(th) }; data.push(datum); } return data; }
var options = { container: document.getElementById('myChart'), data: generateSpiralData(), series: [{ type: 'line', xKey: 'x', yKey: 'y', marker: { enabled: false } }], axes: [ { type: 'number', position: 'bottom', tick: { count: 10, }, }, { type: 'number', position: 'left', tick: { count: 10, }, } ], legend: { enabled: false } }; var chart = agCharts.AgChart.create(options); function setTickCountTo5() { options.axes[0].tick.count = 5; options.axes[1].tick.count = 5; agCharts.AgChart.update(chart, options); } function setTickCountTo10() { options.axes[0].tick.count = 10; options.axes[1].tick.count = 10; agCharts.AgChart.update(chart, options); } function generateSpiralData() { var a = 1; var b = 1; var data = []; var step = 0.1; for (var th = 1; th < 50; th += step) { var r = a + b * th; var datum = { x: r * Math.cos(th), y: r * Math.sin(th) }; data.push(datum); } return data; }
Fix "Axis Tick Styling" example.
Fix "Axis Tick Styling" example.
JavaScript
mit
ceolter/ag-grid,ceolter/ag-grid,ceolter/angular-grid,ceolter/angular-grid
87888fd4f68dc0c34fb84e3b13cdc420befe7b9a
app/assets/javascripts/express_admin/utility.js
app/assets/javascripts/express_admin/utility.js
$(function() { // toggle on/off switch $(document).on('click', '[data-toggle]', function() { targetHide = $(this).data('toggle-hide') targetShow = $(this).data('toggle-show') $('[data-toggle-name="' + targetHide + '"]').addClass('hide') $('[data-toggle-name="' + targetShow + '"]').removeClass('hide') .find('input:text, textarea').first().focus() }); // AJAX request utility AJAXRequest = function(url, method, data, success, error) { return $.ajax({ url : url, type : method, data : data, dataType : 'JSON', cache : false, success : function(json) { success(json) }, error : function() { error() } }); } });
$(function() { // toggle on/off switch $(document).on('click', '[data-toggle]', function() { targetHide = $(this).data('toggle-hide') targetShow = $(this).data('toggle-show') $('[data-toggle-name="' + targetHide + '"]').addClass('hide') $('[data-toggle-name="' + targetShow + '"]').removeClass('hide') }); // AJAX request utility AJAXRequest = function(url, method, data, success, error) { return $.ajax({ url : url, type : method, data : data, dataType : 'JSON', cache : false, success : function(json) { success(json) }, error : function() { error() } }); } });
Remove the auto focus on element toggle feature
Remove the auto focus on element toggle feature
JavaScript
mit
aelogica/express_admin,aelogica/express_admin,aelogica/express_admin,aelogica/express_admin
071ac08d6ef28b1dd39224a4bf4df24140203056
backend/app/assets/javascripts/spree/backend/product_picker.js
backend/app/assets/javascripts/spree/backend/product_picker.js
$.fn.productAutocomplete = function (options) { 'use strict' // Default options options = options || {} var multiple = typeof (options.multiple) !== 'undefined' ? options.multiple : true function formatProduct (product) { return Select2.util.escapeMarkup(product.name) } function formatProductList(products) { var formatted_data = $.map(products, function (obj) { var item = { id: obj.id, text: obj.name } return item }); return formatted_data } this.select2({ multiple: true, minimumInputLength: 3, ajax: { url: Spree.routes.products_api, dataType: 'json', data: function (params) { var query = { q: { name_or_master_sku_cont: params.term }, m: 'OR', token: Spree.api_key } return query; }, processResults: function(data) { var products = data.products ? data.products : [] var results = formatProductList(products) return { results: results } } }, templateSelection: function(data, container) { return data.text } }) } $(document).ready(function () { $('.product_picker').productAutocomplete() })
$.fn.productAutocomplete = function (options) { 'use strict' // Default options options = options || {} var multiple = typeof (options.multiple) !== 'undefined' ? options.multiple : true function formatProduct (product) { return Select2.util.escapeMarkup(product.name) } function formatProductList(products) { var formatted_data = $.map(products, function (obj) { var item = { id: obj.id, text: obj.name } return item }); return formatted_data } this.select2({ multiple: true, minimumInputLength: 3, ajax: { url: Spree.routes.products_api, dataType: 'json', data: function (params) { return { q: { name_or_master_sku_cont: params.term }, m: 'OR', token: Spree.api_key } }, processResults: function(data) { var products = data.products ? data.products : [] var results = formatProductList(products) return { results: results } } }, templateSelection: function(data, container) { return data.text } }).on("select2:unselect", function (e) { if($(this).select2('data').length == 0) { $('<input>').attr({ type: 'hidden', name: this.name, value: '', id: this.id }).appendTo('form.edit_promotion') } }).on('select2:select', function(e) { $('input#'+this.id).remove() }) } $(document).ready(function () { $('.product_picker').productAutocomplete() })
Fix remove last element from select box
Fix remove last element from select box
JavaScript
bsd-3-clause
imella/spree,imella/spree,imella/spree
f0ecaecbe12972301e5c8044d9613f1b46b8a4ec
src/components/navigation/Navbar.js
src/components/navigation/Navbar.js
import React from 'react' import { Link } from 'react-router' import { ElloMark } from '../iconography/ElloIcons' class Navbar extends React.Component { render() { return ( <nav className="Navbar" role="navigation"> <Link to="/"> <ElloMark /> </Link> <div className="NavbarLinks"> <Link to="/discover">Discover</Link> <Link to="/search">Search</Link> <Link to="/onboarding/channels">Onboarding</Link> </div> </nav> ) } } export default Navbar
import React from 'react' import Mousetrap from 'mousetrap' import { Link } from 'react-router' import { ElloMark } from '../iconography/ElloIcons' import { SHORTCUT_KEYS } from '../../constants/action_types' const shortcuts = { [SHORTCUT_KEYS.SEARCH]: '/search', [SHORTCUT_KEYS.DISCOVER]: '/discover', [SHORTCUT_KEYS.ONBOARDING]: '/onboarding/channels', } class Navbar extends React.Component { componentDidMount() { Mousetrap.bind(Object.keys(shortcuts), (event, shortcut) => { const { router } = this.context router.transitionTo(shortcuts[shortcut]) }) } componentWillUnmount() { Mousetrap.unbind(Object.keys(shortcuts)) } render() { return ( <nav className="Navbar" role="navigation"> <Link to="/"> <ElloMark /> </Link> <div className="NavbarLinks"> <Link to="/discover">Discover</Link> <Link to="/search">Search</Link> <Link to="/onboarding/channels">Onboarding</Link> </div> </nav> ) } } Navbar.contextTypes = { router: React.PropTypes.object.isRequired, } export default Navbar
Add shortcut keys for the main navigation
Add shortcut keys for the main navigation
JavaScript
mit
ello/webapp,ello/webapp,ello/webapp
1af5312c5a4f8e3561e052525480d6ce6cde07b9
src/platforms/electron/startSandbox.js
src/platforms/electron/startSandbox.js
import express from 'express'; import unpackByOutpoint from './unpackByOutpoint'; // Polyfills and `lbry-redux` global.fetch = require('node-fetch'); global.window = global; if (typeof global.fetch === 'object') { global.fetch = global.fetch.default; } const { Lbry } = require('lbry-redux'); delete global.window; export default async function startSandbox() { const port = 5278; const sandbox = express(); sandbox.get('/set/:outpoint', async (req, res) => { const { outpoint } = req.params; const resolvedPath = await unpackByOutpoint(Lbry, outpoint); sandbox.use(`/sandbox/${outpoint}/`, express.static(resolvedPath)); res.send(`/sandbox/${outpoint}/`); }); sandbox .listen(port, 'localhost', () => console.log(`Sandbox listening on port ${port}.`)) .on('error', err => { if (err.code === 'EADDRINUSE') { console.log( 'Server already listening at localhost://5278: This is probably another LBRY app running. If not, games in the app will not work.' ); } }); }
import express from 'express'; import unpackByOutpoint from './unpackByOutpoint'; // Polyfills and `lbry-redux` global.fetch = require('node-fetch'); global.window = global; if (typeof global.fetch === 'object') { global.fetch = global.fetch.default; } const { Lbry } = require('lbry-redux'); delete global.window; export default async function startSandbox() { const port = 5278; const sandbox = express(); sandbox.get('/set/:outpoint', async (req, res) => { const { outpoint } = req.params; const resolvedPath = await unpackByOutpoint(Lbry, outpoint); sandbox.use(`/sandbox/${outpoint}/`, express.static(resolvedPath)); res.send(`/sandbox/${outpoint}/`); }); sandbox .listen(port, 'localhost', () => console.log(`Sandbox listening on port ${port}.`)) .on('error', err => { if (err.code === 'EADDRINUSE') { console.log( `Server already listening at localhost:${port}. This is probably another LBRY app running. If not, games in the app will not work.` ); } }); }
Use port from variable instead of hard coding
Use port from variable instead of hard coding ### Changes 1. Edited error description to add port's value from variable instead of hard coding. Also removed redundant `//` between localhost and port.
JavaScript
mit
lbryio/lbry-app,lbryio/lbry-electron,lbryio/lbry-electron,lbryio/lbry-app,lbryio/lbry-electron
8527c947f131b9c430041943b3596b46d65b54ec
src/controllers/post-controller.js
src/controllers/post-controller.js
import BlogPost from '../database/models/blog-post'; import log from '../log'; const PUBLIC_API_ATTRIBUTES = [ 'id', 'title', 'link', 'description', 'date_updated', 'date_published', 'author_id' ]; const DEFAULT_ORDER = [ ['date_published', 'DESC'] ]; export function getAll() { return new Promise((resolve, reject) => { BlogPost.findAll({ attributes: PUBLIC_API_ATTRIBUTES, order: DEFAULT_ORDER, raw: true }) .then(resolve) .catch(error => { log.error({ error }, 'Error getting list of all posts'); reject(error); }); }); } export function getById(id) { return new Promise((resolve, reject) => { BlogPost.findOne({ attributes: PUBLIC_API_ATTRIBUTES, where: { id }, raw: true }) .then(resolve) .catch(error => { log.error({ error }, 'Error getting blog post by id'); reject(error); }); }); } export function getPage(pageNumber, pageSize) { return new Promise((resolve, reject) => { BlogPost.findAll({ attributes: PUBLIC_API_ATTRIBUTES, order: DEFAULT_ORDER, offset: pageNumber * pageSize, limit: pageSize, raw: true }) .then(resolve) .catch(error => { log.error({ error }, 'Error getting page of posts'); reject(error); }); }); }
import BlogPost from '../database/models/blog-post'; import log from '../log'; const PUBLIC_API_ATTRIBUTES = [ 'id', 'title', 'link', 'image_uri', 'description', 'date_updated', 'date_published', 'author_id' ]; const DEFAULT_ORDER = [ ['date_published', 'DESC'] ]; export function getAll() { return new Promise((resolve, reject) => { BlogPost.findAll({ attributes: PUBLIC_API_ATTRIBUTES, order: DEFAULT_ORDER, raw: true }) .then(resolve) .catch(error => { log.error({ error }, 'Error getting list of all posts'); reject(error); }); }); } export function getById(id) { return new Promise((resolve, reject) => { BlogPost.findOne({ attributes: PUBLIC_API_ATTRIBUTES, where: { id }, raw: true }) .then(resolve) .catch(error => { log.error({ error }, 'Error getting blog post by id'); reject(error); }); }); } export function getPage(pageNumber, pageSize) { return new Promise((resolve, reject) => { BlogPost.findAll({ attributes: PUBLIC_API_ATTRIBUTES, order: DEFAULT_ORDER, offset: pageNumber * pageSize, limit: pageSize, raw: true }) .then(resolve) .catch(error => { log.error({ error }, 'Error getting page of posts'); reject(error); }); }); }
Allow image_uri to be part of the public API
Allow image_uri to be part of the public API
JavaScript
mit
csblogs/api-server,csblogs/api-server
ad6916c838d96bc3b2a29678aca4b60dc098d9a7
client/app/components/graph/graph.controller.js
client/app/components/graph/graph.controller.js
import _ from 'lodash' class GraphController { constructor() { this.prepareData(); } prepareData() { // I am assuming the reference object is always sent // at position 0 so I will not be figuring that out let series = []; let labels = []; this.demodata.map(function (item) { let indexes = item.variables.indexes; labels = _.keys(indexes); series.push(_.values(indexes)); }); this.series = series; this.labels = labels; } } export default GraphController;
import _ from 'lodash' class GraphController { constructor() { this.prepareData(); } capitalize(string) { return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); }); } prepareData() { // I am assuming the reference object is always sent // at position 0 so I will not be figuring that out let series = []; let labels = []; this.demodata.map(function (item) { let indexes = item.variables.indexes; labels = _.keys(indexes); series.push(_.values(indexes)); }); this.series = series; this.labels = this.prettyLabels(labels); } prettyLabels(labels) { return labels.map((label) => { return this.capitalize(label.replace('_', ' ')); }) } } export default GraphController;
Make the graph labels nicer
Make the graph labels nicer
JavaScript
apache-2.0
wojtekgalaj/webpack-interview-exercise,wojtekgalaj/webpack-interview-exercise
2be8ae444d43d27c5e7e8eaadc6fb0998cde65a8
src/components/navbar/SearchMixin.js
src/components/navbar/SearchMixin.js
/* By default the search is hidden. When you add a component on the page that wants to use the search, * then add this as a mixin. It will use CSS to activate the search while the component is shown. * * WARNING: this assumes that it is called within a <keep-alive> tag, therefore it listens * at activated/deactivated lifecycle hooks. */ export default { data () { return { searchTerm: '' } }, activated: function () { this.eventbus.$emit('search.visible', true) }, deactivated: function () { this.eventbus.$emit('search.visible', false) }, created () { this.eventbus.$on('search.term', this.searchEventReceived) this.eventbus.$emit('search.init') }, beforeDestroy: function () { this.eventbus.$off('search.term', this.searchEventReceived) }, methods: { searchEventReceived (term) { this.searchTerm = term } } }
/* By default the search is hidden. When you add a component on the page that wants to use the search, * then add this as a mixin. It will use CSS to activate the search while the component is shown. * * WARNING: this assumes that it is called within a <keep-alive> tag, therefore it listens * at activated/deactivated lifecycle hooks. */ export default { data () { return { searchTerm: '' } }, activated: function () { this.eventbus.$emit('search.reset') this.eventbus.$emit('search.visible', true) }, deactivated: function () { this.eventbus.$emit('search.visible', false) }, created () { this.eventbus.$on('search.term', this.searchEventReceived) this.eventbus.$emit('search.init') }, beforeDestroy: function () { this.eventbus.$off('search.term', this.searchEventReceived) }, methods: { searchEventReceived (term) { this.searchTerm = term } } }
Reset search on page change
Reset search on page change
JavaScript
mit
dukecon/dukecon_pwa,dukecon/dukecon_pwa,dukecon/dukecon_pwa
8091c80faced7df102973a726179662a7fd3f2c9
src/zeit/content/cp/browser/resources/area.js
src/zeit/content/cp/browser/resources/area.js
(function ($) { var FIELDS = { 'centerpage': 'referenced_cp', 'channel': 'query', 'query': 'raw_query' }; var show_matching_field = function(container, current_type) { $(['referenced_cp', 'query', 'raw_query']).each(function(i, field) { var method = field == FIELDS[current_type] ? 'show' : 'hide'; var target = $('.fieldname-' + field, container).closest('fieldset'); target[method](); }); }; $(document).bind('fragment-ready', function(event) { var type_select = $('.fieldname-automatic_type select', event.__target); show_matching_field(event.__target, type_select.val()); type_select.on( 'change', function() { show_matching_field(event.__target, $(this).val()); }); }); }(jQuery));
(function ($) { var FIELDS = { 'centerpage': 'referenced_cp', 'channel': 'query', 'query': 'raw_query' }; var show_matching_field = function(container, current_type) { $(['referenced_cp', 'query', 'raw_query']).each(function(i, field) { var method = field == FIELDS[current_type] ? 'show' : 'hide'; var target = $('.fieldname-' + field, container).closest('fieldset'); target[method](); }); }; $(document).bind('fragment-ready', function(event) { var type_select = $('.fieldname-automatic_type select', event.__target); if (! type_select.length) { return; } show_matching_field(event.__target, type_select.val()); type_select.on( 'change', function() { show_matching_field(event.__target, $(this).val()); }); }); }(jQuery));
Exit fragment-ready event handler when it's from a non-applicable fragment
Exit fragment-ready event handler when it's from a non-applicable fragment
JavaScript
bsd-3-clause
ZeitOnline/zeit.content.cp,ZeitOnline/zeit.content.cp
0442b430be43b04580abcdcc7cdbbbaed5540c44
src/lights/DirectionalLightShadow.js
src/lights/DirectionalLightShadow.js
import { LightShadow } from './LightShadow.js'; import { OrthographicCamera } from '../cameras/OrthographicCamera.js'; /** * @author mrdoob / http://mrdoob.com/ */ function DirectionalLightShadow( ) { LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); } DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { constructor: DirectionalLightShadow } ); export { DirectionalLightShadow };
import { LightShadow } from './LightShadow.js'; import { OrthographicCamera } from '../cameras/OrthographicCamera.js'; /** * @author mrdoob / http://mrdoob.com/ */ function DirectionalLightShadow() { LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); } DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { constructor: DirectionalLightShadow, isDirectionalLightShadow: true, updateMatrices: function ( light, viewCamera, viewportIndex ) { var camera = this.camera, lightPositionWorld = this._lightPositionWorld, lookTarget = this._lookTarget; lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); camera.position.copy( lightPositionWorld ); lookTarget.setFromMatrixPosition( light.target.matrixWorld ); camera.lookAt( lookTarget ); camera.updateMatrixWorld(); LightShadow.prototype.updateMatrices.call( this, light, viewCamera, viewportIndex ); } } ); export { DirectionalLightShadow };
Add matrix calcs to direction shadow class
Add matrix calcs to direction shadow class
JavaScript
mit
Liuer/three.js,greggman/three.js,TristanVALCKE/three.js,zhoushijie163/three.js,Samsy/three.js,donmccurdy/three.js,jpweeks/three.js,mrdoob/three.js,SpinVR/three.js,greggman/three.js,stanford-gfx/three.js,TristanVALCKE/three.js,looeee/three.js,Itee/three.js,Samsy/three.js,aardgoose/three.js,TristanVALCKE/three.js,looeee/three.js,donmccurdy/three.js,fraguada/three.js,Samsy/three.js,TristanVALCKE/three.js,fraguada/three.js,fraguada/three.js,TristanVALCKE/three.js,Itee/three.js,WestLangley/three.js,Liuer/three.js,fraguada/three.js,makc/three.js.fork,mrdoob/three.js,Samsy/three.js,kaisalmen/three.js,WestLangley/three.js,jpweeks/three.js,Samsy/three.js,gero3/three.js,TristanVALCKE/three.js,fraguada/three.js,06wj/three.js,zhoushijie163/three.js,SpinVR/three.js,aardgoose/three.js,fyoudine/three.js,gero3/three.js,QingchaoHu/three.js,QingchaoHu/three.js,fraguada/three.js,makc/three.js.fork,fyoudine/three.js,stanford-gfx/three.js,Samsy/three.js,06wj/three.js,kaisalmen/three.js
5c4cae3e2e64e35e41dd3a210592846f130f3171
chrome/background.js
chrome/background.js
// this idea borrowed from // https://www.planbox.com/blog/development/coding/bypassing-githubs-content-security-policy-chrome-extension.html chrome.webRequest.onHeadersReceived.addListener(function(details) { for (i = 0; i < details.responseHeaders.length; i++) { if (isCSPHeader(details.responseHeaders[i].name.toUpperCase())) { var csp = details.responseHeaders[i].value; csp = csp.replace("media-src 'none'", "media-src 'self' blob:"); details.responseHeaders[i].value = csp; } } return { // Return the new HTTP header responseHeaders: details.responseHeaders }; }, { urls: ["*://github.com/*"], types: ["main_frame"] }, ["blocking", "responseHeaders"]); function isCSPHeader(headerName) { return (headerName == 'CONTENT-SECURITY-POLICY') || (headerName == 'X-WEBKIT-CSP'); }
// this idea borrowed from // https://www.planbox.com/blog/development/coding/bypassing-githubs-content-security-policy-chrome-extension.html chrome.webRequest.onHeadersReceived.addListener(function(details) { for (i = 0; i < details.responseHeaders.length; i++) { if (isCSPHeader(details.responseHeaders[i].name.toUpperCase())) { var csp = details.responseHeaders[i].value; csp = csp.replace("media-src 'none'", "media-src 'self' blob:"); csp = csp.replace("connect-src 'self' uploads.github.com status.github.com api.github.com www.google-analytics.com github-cloud.s3.amazonaws.com wss://live.github.com", "connect-src 'self' uploads.github.com status.github.com api.github.com www.google-analytics.com github-cloud.s3.amazonaws.com wss://live.github.com api.imgur.com"); details.responseHeaders[i].value = csp; } } return { // Return the new HTTP header responseHeaders: details.responseHeaders }; }, { urls: ["*://github.com/*"], types: ["main_frame"] }, ["blocking", "responseHeaders"]); function isCSPHeader(headerName) { return (headerName == 'CONTENT-SECURITY-POLICY') || (headerName == 'X-WEBKIT-CSP'); }
Handle GitHub's updated Content Security Policy
Handle GitHub's updated Content Security Policy It looks like GitHub changed their CSP recently. This extension didn't work for me until I added this code.
JavaScript
mit
thieman/github-selfies,thieman/github-selfies
9f143c518269d8a14b9c40964dda586aa27a6d37
client/src/app.js
client/src/app.js
import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import MonthDetail from './components/pages/History/MonthDetail'; import HomePage from './components/pages/Home'; import SignupPage from './components/pages/Signup'; import LoginPage from './components/pages/Login'; import StopWatchPage from './components/pages/StopWatch'; import HistoryPage from './components/pages/History'; import PrivateRoute from './components/PrivateRoute'; import NotFoundPage from './components/NotFoundPage'; import NavBar from './components/NavBar'; import './styles.css'; class App extends Component { render () { return ( <Router> <div> <NavBar /> <Switch> <Route exact path="/" component={HomePage} /> <Route path="/signup" component={SignupPage} /> <Route path="/login" component={LoginPage} /> <Route path="/stopwatch" component={StopWatchPage} /> <PrivateRoute exact path="/history" component={HistoryPage} /> <PrivateRoute path="/history/:month" component={MonthDetail} /> <Route component={NotFoundPage} /> </Switch> </div> </Router> ); } } export default App;
import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import MonthDetail from './components/pages/History/MonthDetail'; import HomePage from './components/pages/Home'; import SignupPage from './components/pages/Signup'; import LoginPage from './components/pages/Login'; import StopWatchPage from './components/pages/StopWatch'; import HistoryPage from './components/pages/History'; import PrivateRoute from './components/PrivateRoute'; import NotFoundPage from './components/NotFoundPage'; import NavBar from './components/NavBar'; import './styles.css'; class App extends Component { render () { return ( <Router> <div> <NavBar /> <Switch> <Route exact path="/" component={HomePage} /> <Route path="/signup" component={SignupPage} /> <Route path="/login" component={LoginPage} /> <PrivateRoute path="/stopwatch" component={StopWatchPage} /> <PrivateRoute exact path="/history" component={HistoryPage} /> <PrivateRoute path="/history/:month" component={MonthDetail} /> <Route component={NotFoundPage} /> </Switch> </div> </Router> ); } } export default App;
Add stopwatch as auth protected route
Add stopwatch as auth protected route
JavaScript
mit
mbchoa/presence,mbchoa/presence
26f51f95a8547f8a6e7067856b432183ef9908ef
draft-js-image-plugin/src/modifiers/addImage.js
draft-js-image-plugin/src/modifiers/addImage.js
import { EditorState, AtomicBlockUtils, } from 'draft-js'; export default (editorState, url, extraData) => { const urlType = 'image'; const contentState = editorState.getCurrentContent(); const contentStateWithEntity = contentState.createEntity(urlType, 'IMMUTABLE', { ...extraData, src: url }); const entityKey = contentStateWithEntity.getLastCreatedEntityKey(); const newEditorState = AtomicBlockUtils.insertAtomicBlock( editorState, entityKey, ' ' ); return EditorState.forceSelection( newEditorState, editorState.getCurrentContent().getSelectionAfter() ); };
import { EditorState, AtomicBlockUtils, } from 'draft-js'; export default (editorState, url, extraData) => { const urlType = 'image'; const contentState = editorState.getCurrentContent(); const contentStateWithEntity = contentState.createEntity(urlType, 'IMMUTABLE', { ...extraData, src: url }); const entityKey = contentStateWithEntity.getLastCreatedEntityKey(); const newEditorState = AtomicBlockUtils.insertAtomicBlock( editorState, entityKey, ' ' ); return EditorState.forceSelection( newEditorState, newEditorState.getCurrentContent().getSelectionAfter() ); };
Move cursor after image when inserting
Move cursor after image when inserting
JavaScript
mit
nikgraf/draft-js-plugin-editor,draft-js-plugins/draft-js-plugins,nikgraf/draft-js-plugin-editor,nikgraf/draft-js-plugin-editor,draft-js-plugins/draft-js-plugins,draft-js-plugins/draft-js-plugins,draft-js-plugins/draft-js-plugins
7f80989cb19f31de01fffcc2976939bf095b0c0d
apps/jsdoc/actions.js
apps/jsdoc/actions.js
include('helma/webapp/response'); include('helma/engine'); include('helma/jsdoc'); require('core/array'); exports.index = function index(req, module) { var repo = new ScriptRepository(getRepositories()[1]); if (module && module != "/") { var jsdoc = []; res = repo.getScriptResource(module); var currentDoc; parseScriptResource(res, function(node) { if (node.jsDoc) { currentDoc = extractTags(node.jsDoc) print(currentDoc[0][1]); jsdoc.push(currentDoc); } else { print(getTypeName(node) + " // " + getName(node)); if (isName(node) && getName(node) != "exports" && currentDoc && !currentDoc.name) { Object.defineProperty(currentDoc, 'name', {value: getName(node)}); } } return true; }); return new SkinnedResponse(getResource('./skins/module.html'), { title: "Module " + res.moduleName, jsdoc: jsdoc }); } else { var modules = repo.getScriptResources(true).sort(function(a, b) {return a.relativePath > b.relativePath}); return new SkinnedResponse(getResource('./skins/index.html'), { title: "API Documentation", modules: modules }); } }
include('helma/webapp/response'); include('helma/engine'); include('helma/jsdoc'); require('core/array'); exports.index = function index(req, module) { var repo = new ScriptRepository(getRepositories()[1]); if (module && module != "/") { var jsdoc = []; var res = repo.getScriptResource(module); var currentDoc; parseScriptResource(res, function(node) { if (node.jsDoc) { currentDoc = extractTags(node.jsDoc) // print(currentDoc[0][1]); jsdoc.push(currentDoc); } else { // print(getTypeName(node) + " // " + getName(node)); if (isName(node) && getName(node) != "exports" && currentDoc && !currentDoc.name) { Object.defineProperty(currentDoc, 'name', {value: getName(node)}); } } return true; }); return new SkinnedResponse(getResource('./skins/module.html'), { title: "Module " + res.moduleName, jsdoc: jsdoc }); } else { var modules = repo.getScriptResources(true).sort(function(a, b) {return a.relativePath > b.relativePath}); return new SkinnedResponse(getResource('./skins/index.html'), { title: "API Documentation", modules: modules }); } }
Disable debug output, add missing var
Disable debug output, add missing var
JavaScript
apache-2.0
ringo/ringojs,ashwinrayaprolu1984/ringojs,ringo/ringojs,ashwinrayaprolu1984/ringojs,oberhamsi/ringojs,ashwinrayaprolu1984/ringojs,Transcordia/ringojs,Transcordia/ringojs,oberhamsi/ringojs,ashwinrayaprolu1984/ringojs,ringo/ringojs,oberhamsi/ringojs,Transcordia/ringojs,ringo/ringojs,Transcordia/ringojs
ca2c3bf7d57284eaaf8e9be69c6c15746fcd5bde
src/components/ComponentizeContent.js
src/components/ComponentizeContent.js
import { node, object, oneOfType, string } from 'prop-types' import Bit from './Bit' import Code from './Code' import HTML from 'html-parse-stringify' import React from 'react' import reactify from '../util/reactify' import Image from './Image' import Rule from './Rule' import Paragraph from './Paragraph' const DEFAULT_MAPPINGS = { // TODO: Add stemcell components and add API endpoint for end-user mappings code: Code, hr: Rule, img: Image, p: Paragraph } // TODO: Move this to optional package? const ComponentizeContent = ({ children, ...props }) => { if (!children || typeof children !== 'string') { return children } const ast = HTML.parse(`<div>${children}</div>`) const reparsedAst = reactify(ast, { mappings: DEFAULT_MAPPINGS }) return ( <Bit {...props}> {reparsedAst} </Bit> ) } ComponentizeContent.propTypes = { children: node, className: oneOfType([object, string]) } export default ComponentizeContent
import { node, object, oneOfType, string } from 'prop-types' import Bit from './Bit' import Code from './Code' import HTML from 'html-parse-stringify' import React from 'react' import reactify from '../util/reactify' import Image from './Image' import Rule from './Rule' import Paragraph from './Paragraph' const DEFAULT_MAPPINGS = { // TODO: Add stemcell components and add API endpoint for end-user mappings code: Code, hr: Rule, img: Image, p: Paragraph } // TODO: Move this to optional package? const ComponentizeContent = ({ children, ...props }) => { if (!children) { return null } if (typeof children !== 'string') { return children } const ast = HTML.parse(`<div>${children}</div>`) const reparsedAst = reactify(ast, { mappings: DEFAULT_MAPPINGS }) return ( <Bit {...props}> {reparsedAst} </Bit> ) } ComponentizeContent.propTypes = { children: node, className: oneOfType([object, string]) } export default ComponentizeContent
Add better fix for handling invalid markdown inputs
Add better fix for handling invalid markdown inputs
JavaScript
mit
dlindahl/stemcell,dlindahl/stemcell
ce3ee6f2131314d395734ef0e69b89a5f62cf51d
gulp/continuous-integration.js
gulp/continuous-integration.js
'use strict'; var gulp = require('gulp'); gulp.task( 'ci', ['coding-standards', 'test', 'protractor', 'protractor:dist'] );
'use strict'; var gulp = require('gulp'); gulp.task( 'ci', ['coding-standards', 'test', 'protractor'] );
Remove protractor:dist from the ci task (gulp).
Remove protractor:dist from the ci task (gulp).
JavaScript
mit
algotech/angular-boilerplate,OroianRares/stock-prices,OroianRares/BrowserChatApp,OroianRares/angular-boilerplate,OroianRares/stock-prices,OroianRares/BrowserChatApp,algotech/angular-boilerplate,OroianRares/angular-boilerplate
86abbdef8290ab8dda9553e1981f92382321a602
EdityMcEditface/wwwroot/edity/layouts/editComponents/source.js
EdityMcEditface/wwwroot/edity/layouts/editComponents/source.js
"use strict"; jsns.run([ "htmlrest.domquery", "htmlrest.storage", "htmlrest.rest", "htmlrest.controller", "htmlrest.widgets.navmenu", "edity.pageSourceSync" ], function (exports, module, domQuery, storage, rest, controller, navmenu, sourceSync) { function EditSourceController(bindings) { var editSourceDialog = bindings.getToggle('dialog'); var codemirrorElement = domQuery.first('#editSourceTextarea'); var cm = CodeMirror.fromTextArea(codemirrorElement, { lineNumbers: true, mode: "htmlmixed", theme: "edity" }); function apply(evt) { evt.preventDefault(); editSourceDialog.off(); sourceSync.setHtml(cm.getValue()); } this.apply = apply; function NavItemController() { function edit() { editSourceDialog.on(); cm.setValue(sourceSync.getHtml()); setTimeout(function () { cm.refresh(); }, 500); } this.edit = edit; } var editMenu = navmenu.getNavMenu("edit-nav-menu-items"); editMenu.add("EditSourceNavItem", NavItemController); } controller.create("editSource", EditSourceController); });
"use strict"; jsns.run([ "htmlrest.domquery", "htmlrest.storage", "htmlrest.rest", "htmlrest.controller", "htmlrest.widgets.navmenu", "edity.pageSourceSync" ], function (exports, module, domQuery, storage, rest, controller, navmenu, sourceSync) { function EditSourceController(bindings) { var editSourceDialog = bindings.getToggle('dialog'); var codemirrorElement = domQuery.first('#editSourceTextarea'); var cm = CodeMirror.fromTextArea(codemirrorElement, { lineNumbers: true, mode: "htmlmixed", theme: "edity" }); function apply(evt) { evt.preventDefault(); editSourceDialog.off(); sourceSync.setHtml(cm.getValue()); } this.apply = apply; function NavItemController() { function edit() { editSourceDialog.on(); cm.setSize(null, window.innerHeight - 250); cm.setValue(sourceSync.getHtml()); setTimeout(function () { cm.refresh(); }, 500); } this.edit = edit; } var editMenu = navmenu.getNavMenu("edit-nav-menu-items"); editMenu.add("EditSourceNavItem", NavItemController); } controller.create("editSource", EditSourceController); });
Set codemirror size when opening modal.
Set codemirror size when opening modal.
JavaScript
mit
threax/EdityMcEditface,threax/EdityMcEditface,threax/EdityMcEditface
8110d5ddc810886ca3bb7c72ac2908d05ec6176b
troposphere/static/js/controllers/projects.js
troposphere/static/js/controllers/projects.js
define(['react', 'collections/projects', 'models/project', 'rsvp'], function(React, Collection, Model, RSVP) { var projects = new Collection(); var getProjects = function() { return new RSVP.Promise(function(resolve, reject) { projects.fetch({ success: resolve, error: reject }); }); }; var createProject = function(name, description) { console.log(name, description); return new RSVP.Promise(function(resolve, reject) { var model = new Model(); model.save({name: name, description: description}, { success: function(model) { resolve(model); }, error: function(model, response) { reject(response); } }); }); }; return { create: createProject, get: getProjects }; });
define(['react', 'collections/projects', 'models/project', 'rsvp', 'controllers/notifications'], function(React, Collection, Model, RSVP, Notifications) { var projects = new Collection(); var getProjects = function() { return new RSVP.Promise(function(resolve, reject) { projects.fetch({ success: resolve, error: reject }); }); }; var createProject = function(name, description) { console.log(name, description); return new RSVP.Promise(function(resolve, reject) { var model = new Model(); model.save({name: name, description: description}, { success: function(model) { Notifications.success('Success', 'Created new project "' + model.get('name') + '"'); resolve(model); }, error: function(model, response) { reject(response); } }); }); }; return { create: createProject, get: getProjects }; });
Add success notifcation for project creation
Add success notifcation for project creation
JavaScript
apache-2.0
CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend
86e6616397397d0cdcda5aa0d89ee872429769b6
src/shared/components/login/login.js
src/shared/components/login/login.js
import React, { Component } from 'react'; import Modal from 'shared/components/modal/modal'; import Form from 'shared/components/form/form'; import FormEmail from 'shared/components/form/formEmail/formEmail'; import FormPassword from 'shared/components/form/formPassword/formPassword'; class Login extends Component { render() { return ( <div> <Modal> <Form> <FormEmail displayName="Username" /> <FormPassword displayName="Password" /> </Form> </Modal> </div> ); } } export default Login;
import React, { Component } from 'react'; import Modal from 'shared/components/modal/modal'; import Form from 'shared/components/form/form'; import { Redirect } from 'react-router-dom'; import axios from 'axios'; import config from 'config/environment'; import _ from 'lodash'; import FormEmail from 'shared/components/form/formEmail/formEmail'; import FormPassword from 'shared/components/form/formPassword/formPassword'; import FormButton from 'shared/components/form/formButton/formButton'; class Login extends Component { state = { email: '', emailValid: false, password: '', passwordValid: false, authenticated: false, error: '' } onEmailChange = (value, valid) => { this.setState({ email: value, emailValid: valid }); } onPasswordChange = (value, valid) => { this.setState({ password: value, passwordValid: valid }); } isFormValid = () => this.state.emailValid && this.state.passwordValid handleOnClick = (e) => { e.preventDefault = true; if (this.isFormValid()) { axios.post(`${config.backendUrl}/sessions`, { user: { email: this.state.email, password: this.state.password } }).then(({ data }) => { document.cookie = `token=${data.token}`; this.setState({ authenticated: true }); }).catch((response) => { const error = _.get(response, 'response.data.error'); this.setState({ error }); }); } } render() { const { error } = this.state; return ( <div> <Modal> <Form autoComplete> <FormEmail displayName="Email" label="Email" onChange={this.onEmailChange} /> <FormPassword displayName="Password" label="Password" onChange={this.onPasswordChange} /> {error && <h2>{error}</h2>} <FormButton className="Login-btn" text="login" onClick={this.handleOnClick} /> </Form> </Modal> {this.state.authenticated && <Redirect to="/mentor-request" />} </div> ); } } export default Login;
Handle user signing and redirect
Handle user signing and redirect
JavaScript
mit
hollomancer/operationcode_frontend,miaket/operationcode_frontend,NestorSegura/operationcode_frontend,sethbergman/operationcode_frontend,tskuse/operationcode_frontend,NestorSegura/operationcode_frontend,alexspence/operationcode_frontend,OperationCode/operationcode_frontend,tskuse/operationcode_frontend,sethbergman/operationcode_frontend,OperationCode/operationcode_frontend,hollomancer/operationcode_frontend,miaket/operationcode_frontend,hollomancer/operationcode_frontend,miaket/operationcode_frontend,tskuse/operationcode_frontend,tal87/operationcode_frontend,tal87/operationcode_frontend,NestorSegura/operationcode_frontend,alexspence/operationcode_frontend,alexspence/operationcode_frontend,tal87/operationcode_frontend,sethbergman/operationcode_frontend,OperationCode/operationcode_frontend
b74e5d8d697f113d43f6c0793dc669168220632c
lib/axiom_pnacl/executables.js
lib/axiom_pnacl/executables.js
// Copyright (c) 2014 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import AxiomError from 'axiom/core/error'; import environment from 'axiom_shell/environment'; import VimCommand from 'axiom_pnacl/vim'; // @note ExecuteContext from 'axiom/bindings/fs/execute_context' export var executables = function(sourceUrl) { return { 'vim()': function() { var vimCommand = new VimCommand(sourceUrl); return vimCommand.run.bind(vimCommand); }() }; }; export default executables;
// Copyright (c) 2014 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import AxiomError from 'axiom/core/error'; import environment from 'axiom_shell/environment'; import VimCommand from 'axiom_pnacl/vim'; // @note ExecuteContext from 'axiom/bindings/fs/execute_context' export var executables = function(sourceUrl) { return { 'vim(@)': function() { var vimCommand = new VimCommand(sourceUrl); return vimCommand.run.bind(vimCommand); }() }; }; export default executables;
Allow 'vim' command to accept an array of arguments.
Allow 'vim' command to accept an array of arguments.
JavaScript
apache-2.0
rpaquay/axiom,chromium/axiom,umop/axiom_old_private,ussuri/axiom,mcanthony/axiom
7c5ddc02666adb0bd8f011e908fb1d0e11a01244
util.js
util.js
function quote(s) { return "\"" + s.replace(/([\\\"])/, "\\$1") + "\""; } function maybe_quote(s) { if (/[\\\"]/.test(s)) return quote(s); else return s; } function repr(x, max_depth) { if (max_depth == undefined) max_depth = 1; if (x === null) { return "null"; } if (typeof x == "object") { if ("hashCode" in x) // Guess that it's a Java object. return String(x); if (max_depth <= 0) return "{...}"; var elems = []; for (var k in x) elems.push(maybe_quote(k) + ": " + repr(x[k], max_depth - 1)); return "{ " + elems.join(", ") + " }"; } else if (typeof x == "string") { return quote(x); } else { return String(x); } }
function quote(s) { return "\"" + s.replace(/([\\\"])/, "\\$1") + "\""; } function maybe_quote(s) { if (/[\\\"]/.test(s)) return quote(s); else return s; } function repr(x, max_depth) { if (max_depth == undefined) max_depth = 1; if (x === null) { return "null"; } else if (x instanceof java.lang.Iterable) { var elems = []; var i = x.iterator(); while (i.hasNext()) elems.push(repr(i.next())); return x["class"] + ":[ " + elems.join(", ") + " ]"; } else if (typeof x == "object") { if ("hashCode" in x) // Guess that it's a Java object. return String(x); if (max_depth <= 0) return "{...}"; var elems = []; for (var k in x) elems.push(maybe_quote(k) + ": " + repr(x[k], max_depth - 1)); return "{ " + elems.join(", ") + " }"; } else if (typeof x == "string") { return quote(x); } else { return String(x); } }
Allow repr to show java.lang.Iterables.
Allow repr to show java.lang.Iterables.
JavaScript
mit
arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy
a7fb7e9a16e45bbc29603be46d082910c06b30b7
app.js
app.js
function Actor(other) { other = other || {}; this.name = other.name || ""; this.init = other.init || 0; this.hp = other.hp || 0; }; var sort = function(left, right) { return left.init==right.init ? 0 : (left.init > right.init ? -1 : 1); }; function Encounter() { this.actors = []; }; var ViewModel = function() { self = this; self.formActor = ko.observable(new Actor()); self.actors = ko.observableArray([]); self.addActor = function() { self.actors.push(new Actor(self.formActor())); self.formActor(new Actor()); }; self.sortActors = function() { self.actors.sort(sort); }; self.endTurn = function() { self.actors.remove(this); self.actors.push(this); }; }; ko.applyBindings(new ViewModel());
function Actor(other) { other = other || {}; this.name = other.name || ""; this.init = other.init || 0; this.hp = other.hp || 1; }; var sort = function(left, right) { return left.init==right.init ? 0 : (left.init > right.init ? -1 : 1); }; function Encounter() { this.actors = []; }; var ViewModel = function() { self = this; self.formActor = ko.observable(new Actor()); self.actors = ko.observableArray([]); self.addActor = function() { self.actors.push(new Actor(self.formActor())); self.formActor(new Actor()); }; self.sortActors = function() { self.actors.sort(sort); }; self.endTurn = function() { self.actors.remove(this); self.actors.push(this); }; }; ko.applyBindings(new ViewModel());
Change default health to 1.
Change default health to 1.
JavaScript
mit
madigan/ncounter,madigan/ncounter
c15fc1bae4bd27839a0d78e220d02eb94bd4bdae
test/helpers/supportsWorker.js
test/helpers/supportsWorker.js
module.exports = function supportsWorker() { try { // eslint-disable-next-line node/no-unsupported-features/node-builtins return require("worker_threads") !== undefined; } catch (e) { return false; } };
const nodeVersion = process.versions.node.split(".").map(Number); module.exports = function supportsWorker() { // Verify that in the current node version new Worker() accepts URL as the first parameter: // https://nodejs.org/api/worker_threads.html#worker_threads_new_worker_filename_options if (nodeVersion[0] >= 14) { return true; } else if (nodeVersion[0] === 13 && nodeVersion[1] >= 12) { return true; } else if (nodeVersion[0] === 12 && nodeVersion[1] >= 17) { return true; } return false; };
Fix new Worker() compatibility check in unit tests for older node versions
Fix new Worker() compatibility check in unit tests for older node versions
JavaScript
mit
SimenB/webpack,webpack/webpack,webpack/webpack,webpack/webpack,webpack/webpack,SimenB/webpack,SimenB/webpack,SimenB/webpack
d78824b2be952e65117258d3ec701304425fe304
frontend/src/containers/TeamPage/TeamPage.js
frontend/src/containers/TeamPage/TeamPage.js
import React, { Component } from 'react' import Helmet from 'react-helmet' import { NavBar } from '../../components' const styles = { iframe: { width: '100%', } } class TeamPage extends Component { componentDidMount() { var iframe = this.refs.iframe iframe.addEventListener('load', () => { var iframeScrollHeight = iframe.contentWindow.document.body.scrollHeight + 'px' iframe.height = iframeScrollHeight }) } render() { return( <div> <Helmet title="Team" /> <NavBar /> <iframe ref="iframe" style={styles.iframe} src="/staticPage/team"/> </div> ) } } export default TeamPage
import React, { Component } from 'react' import Helmet from 'react-helmet' import { NavBar } from '../../components' const styles = { iframe: { width: '100%', } } class TeamPage extends Component { componentDidMount() { var iframe = this.refs.iframe iframe.addEventListener('load', () => { var iframeScrollHeight = iframe.contentWindow.document.body.scrollHeight + 'px' iframe.height = iframeScrollHeight }) } render() { return( <div> <Helmet title="Team" /> <NavBar /> <iframe ref="iframe" style={styles.iframe} src="/staticPage/team/index.html" /> </div> ) } } export default TeamPage
Fix issue where team page is not found
Fix issue where team page is not found
JavaScript
mit
hackclub/api,hackclub/api,hackclub/api
6c19c79f596ae6872c7b5b2fe2b31ff4f5c8cb51
test/mjsunit/asm/math-clz32.js
test/mjsunit/asm/math-clz32.js
// Copyright 2015 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Flags: --allow-natives-syntax var stdlib = { Math: Math }; var f = (function Module(stdlib) { "use asm"; var clz32 = stdlib.Math.clz32; function f(a) { a = a >>> 0; return clz32(a)|0; } return f; })(stdlib); assertEquals(32, f(0)); assertEquals(32, f(NaN)); assertEquals(32, f(undefined)); for (var i = 0; i < 32; ++i) { assertEquals(i, f((-1) >>> i)); } for (var i = -2147483648; i < 2147483648; i += 3999773) { assertEquals(%MathClz32(i), f(i)); assertEquals(%_MathClz32(i), f(i)); }
// Copyright 2015 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Flags: --allow-natives-syntax var stdlib = { Math: Math }; var f = (function Module(stdlib) { "use asm"; var clz32 = stdlib.Math.clz32; function f(a) { a = a >>> 0; return clz32(a)|0; } return f; })(stdlib); assertEquals(32, f(0)); assertEquals(32, f(NaN)); assertEquals(32, f(undefined)); for (var i = 0; i < 32; ++i) { assertEquals(i, f((-1) >>> i)); } for (var i = -2147483648; i < 2147483648; i += 3999773) { assertEquals(%MathClz32(i), f(i)); assertEquals(%MathClz32(i), %_MathClz32(i >>> 0)); }
Fix test of %_MathClz32 intrinsic.
[turbofan] Fix test of %_MathClz32 intrinsic. This test will fail once we optimize top-level code, because the aforementioned intrinsic doesn't perform a NumberToUint32 conversion. R=titzer@chromium.org TEST=mjsunit/asm/math-clz32 Review URL: https://codereview.chromium.org/1041173002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#27524}
JavaScript
mit
UniversalFuture/moosh,UniversalFuture/moosh,UniversalFuture/moosh,UniversalFuture/moosh
2747aa2c950deb95a99ef937c23c8d7db17d5f86
src/main/resources/com/semperos/screwdriver/js/extension/process-rjs.js
src/main/resources/com/semperos/screwdriver/js/extension/process-rjs.js
//Create a runner that will run a separate build for each item //in the configs array. Thanks to @jwhitley for this cleverness for (var i = 0; i < __Screwdriver.rjs.moduleConfigs.length; i++) { requirejs.optimize(__Screwdriver.rjs.moduleConfigs[i], function(x) { print("Screwdriver RequireJS Optimizer (r.js)"); print(x); print("Screwdriver RequireJS optimization complete for file: " + __Screwdriver.rjs.moduleConfigs[i].out) print("===============================>SCREWDRIVER<====================================="); }) }
//Create a runner that will run a separate build for each item //in the configs array. Thanks to @jwhitley for this cleverness print("Starting RequireJS (r.js) Optimizer..."); for (var i = 0; i < __Screwdriver.rjs.moduleConfigs.length; i++) { requirejs.optimize(__Screwdriver.rjs.moduleConfigs[i], function(x) { print("Screwdriver RequireJS Optimizer (r.js)"); print(x); print("Screwdriver RequireJS optimization complete for file: " + __Screwdriver.rjs.moduleConfigs[i].out) print("===============================>SCREWDRIVER<====================================="); }) }
Make it clearer when the r.js optimizer starts
Make it clearer when the r.js optimizer starts
JavaScript
apache-2.0
semperos/screwdriver,semperos/screwdriver
9678e952e50cef724dfae8871ceda7b3dc056a4f
src/services/fetchOverallStats.js
src/services/fetchOverallStats.js
import fetch from 'node-fetch'; import { API_URL, HTTP_HEADERS } from '../constants'; const headers = HTTP_HEADERS; const formatStats = (data, battletag, competitive) => { const stats = data['overall_stats']; const gameMode = competitive ? 'Competitive' : 'Quick Play'; return `*${battletag}*'s Overall Stats (${gameMode}): - Level: ${stats['level'] || 0} - Games: ${stats['games'] || 0} - Wins: ${stats['wins'] || 0} - Losses: ${stats['losses'] || 0} - Win Rate: ${stats['win_rate'] || 0}%`; } export const fetchOverallStats = (battletag, competitive) => { const gameMode = competitive ? 'competitive' : 'general'; const url = `${API_URL}/${battletag}/stats/${gameMode}`; return fetch(url, { headers }) .then(response => response.json()) .then(json => formatStats(json, battletag, competitive)) .catch(error => { return `Sorry, I cannot find the user ${battletag}`; }); }
import fetch from 'node-fetch'; import { API_URL, HTTP_HEADERS } from '../constants'; const headers = HTTP_HEADERS; const formatStats = (data, battletag, competitive) => { const stats = data['overall_stats']; const gameMode = competitive ? 'Competitive' : 'Quick Play'; let level = stats['level']; if (typeof stats['prestige'] === 'number') { level += (stats['prestige'] * 100); } const winRate = ((stats['wins'] / stats['games']) * 100).toFixed(2); return `*${battletag}*'s Overall Stats (${gameMode}): - Level: ${level || 0} - Games: ${stats['games'] || 0} - Wins: ${stats['wins'] || 0} - Losses: ${stats['losses'] || 0} - Win Rate: ${winRate || 0}% - Rating: ${stats['comprank'] || 0}`; } export const fetchOverallStats = (battletag, competitive) => { const gameMode = competitive ? 'competitive' : 'general'; const url = `${API_URL}/${battletag}/stats/${gameMode}`; return fetch(url, { headers }) .then(response => response.json()) .then(json => formatStats(json, battletag, competitive)) .catch(error => { return `Sorry, I cannot find the user ${battletag}`; }); }
Add skill rating and make win rate more precise
Add skill rating and make win rate more precise Fixes #1
JavaScript
mit
chesterhow/overwatch-telegram-bot
ca37507057f8920d078f203fc56cf3070defc8c7
src/List/List.js
src/List/List.js
var React = require('react'); var classNames = require('classnames'); var ListItem = require('./ListItem'); var ListItemGroup = require('./ListItemGroup'); var List = React.createClass({ displayName: 'List', getDefaultProps: function() { return { className: '' } }, getListItems: function(list) { var that = this; var items = list.map(function(item) { if (item.items) { return ( <ListItemGroup tag={item.tag} attributes={item.attributes}> {that.getListItems(item.items)} </ListItemGroup> ); } else { return ( <ListItem tag={item.tag} attributes={item.attributes}> {item.value} </ListItem> ); } }); return items; }, render: function() { var Tag = this.props.tag || 'div'; var defaultClasses = [ 'list', 'list-unstyled' ]; var passedClasses = this.props.className.split(' '); var classes = classNames(_.union(defaultClasses, passedClasses)); return ( <Tag {...this.props} className={classes}> {this.getListItems(this.props.items)} </Tag> ); } }); module.exports = List;
var React = require('react'); var classNames = require('classnames'); var _ = require('underscore'); var ListItem = require('./ListItem'); var ListItemGroup = require('./ListItemGroup'); var List = React.createClass({ displayName: 'List', propTypes: { className: React.PropTypes.string, items: React.PropTypes.array.isRequired, tag: React.PropTypes.string }, getDefaultProps: function() { return { className: '' } }, getListItems: function(list, childIndex) { var that = this; var childIndex = childIndex || 0; var items = list.map(function(item, parentIndex) { var key = parentIndex + '.' + childIndex; childIndex++; if (item.items) { return ( <ListItemGroup key={key} tag={item.tag} attributes={item.attributes}> {that.getListItems(item.items, childIndex)} </ListItemGroup> ); } else { return ( <ListItem key={key} tag={item.tag} attributes={item.attributes}> {item.value} </ListItem> ); } }); return items; }, render: function() { var Tag = this.props.tag || 'div'; var defaultClasses = [ 'list', 'list-unstyled' ]; var passedClasses = this.props.className.split(' '); var classes = classNames(_.union(defaultClasses, passedClasses)); return ( <Tag {...this.props} className={classes}> {this.getListItems(this.props.items)} </Tag> ); } }); module.exports = List;
Add key to iterated objects
Add key to iterated objects
JavaScript
apache-2.0
mesosphere/reactjs-components,mesosphere/reactjs-components
2068d2d2bc6907b2bd7990a933d93d5044cf35e3
src/lib/session/index.js
src/lib/session/index.js
import routes from '../routes' import request from '../request' const create = (opts, email, password) => request.post(opts, routes.session, { email, password }) const verify = Promise.resolve(1) const destroy = Promise.resolve(1) export default { create, verify, destroy, }
import routes from '../routes' import request from '../request' const create = (opts, email, password) => request.post(opts, routes.session, { email, password }) export default { create, }
Remove unused endpoints on session route
Remove unused endpoints on session route
JavaScript
mit
pagarme/pagarme-js
e02a8202e83018b10adabc986b720c552df9bcae
website/app/application/core/projects/project/files/files-controller.js
website/app/application/core/projects/project/files/files-controller.js
Application.Controllers.controller("FilesController", ["$state", FilesController]); function FilesController($state) { //console.log("FileController going to projects.project.files.all"); //$state.go('projects.project.files.all'); var ctrl = this; ctrl.showSearchResults = showSearchResults; ////////////////// function showSearchResults() { $state.go('projects.project.files.search'); } }
Application.Controllers.controller("FilesController", ["$state", FilesController]); function FilesController($state) { var ctrl = this; ctrl.showSearchResults = showSearchResults; init(); ////////////////// function showSearchResults() { $state.go('projects.project.files.search'); } function init() { if ($state.current.name == "projects.project.files") { $state.go('projects.project.files.all'); } } }
Remove console statement. Move initialization logic for controller into init() method.
Remove console statement. Move initialization logic for controller into init() method.
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
78be30be622d78ce3146ae659f1277b5ff127b57
website/app/index/sidebar-projects.js
website/app/index/sidebar-projects.js
Application.Directives.directive("sidebarProjects", sidebarProjectsDirective); function sidebarProjectsDirective() { return { restrict: "AE", replace: true, templateUrl: "index/sidebar-projects.html", controller: "sidebarProjectsDirectiveController" }; } Application.Controllers.controller("sidebarProjectsDirectiveController", ["$scope", "current", "sidebarUtil", "mcapi", "model.projects", sidebarProjectsDirectiveController]); function sidebarProjectsDirectiveController($scope, current, sidebarUtil, mcapi, Projects) { $scope.showProjects = false; $scope.setProject = function(project) { $scope.project = project; current.setProject(project); $scope.showProjects = false; $scope.project.fileCount = sidebarUtil.projectFileCount($scope.project); $scope.project.projectSize = sidebarUtil.projectSize($scope.project); }; $scope.createProject = function(){ if ($scope.model.name === "") { return; } mcapi('/projects') .success(function (data) { console.dir(data); Projects.getList(true).then(function(projects) { $scope.projects = projects; }); }).post({'name': $scope.model.name}); }; }
Application.Directives.directive("sidebarProjects", sidebarProjectsDirective); function sidebarProjectsDirective() { return { restrict: "AE", replace: true, templateUrl: "index/sidebar-projects.html", controller: "sidebarProjectsDirectiveController" }; } Application.Controllers.controller("sidebarProjectsDirectiveController", ["$scope", "current", "sidebarUtil", "mcapi", "model.projects", "$state", sidebarProjectsDirectiveController]); function sidebarProjectsDirectiveController($scope, current, sidebarUtil, mcapi, Projects, $state) { $scope.showProjects = false; $scope.setProject = function(project) { $scope.project = project; current.setProject(project); $scope.showProjects = false; $scope.project.fileCount = sidebarUtil.projectFileCount($scope.project); $scope.project.projectSize = sidebarUtil.projectSize($scope.project); $state.go("projects.project.home", {id: project.id}); }; $scope.createProject = function(){ if ($scope.model.name === "") { return; } mcapi('/projects') .success(function (data) { Projects.getList(true).then(function(projects) { $scope.projects = projects; }); }).post({'name': $scope.model.name}); }; }
Switch project view when user picks a different project.
Switch project view when user picks a different project.
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
94352ff890da1dc1a83651b316eba519d9101243
optimize/index.js
optimize/index.js
var eng = require('./node/engine'); module.exports = { minimize: function(func, options, callback) { eng.runPython('minimize', func, options, callback); }, nonNegLeastSquares: function(A, b, callback) { eng.runPython('nnls', A, b, callback); } }
var eng = require('./node/engine'); module.exports = { localMinimize: function(func, options, callback) { eng.runPython('local', func, options, callback); }, globalMinimize: function(func, options, callback) { eng.runPython('global', func, options, callback); }, nonNegLeastSquares: function(A, b, callback) { eng.runPython('nnls', A, b, callback); } }
Add localMin and globalMin to API
Add localMin and globalMin to API
JavaScript
mit
acjones617/scipy-node,acjones617/scipy-node
fe8f4e74ed73f3c56e8747b393e0036261cc3d4d
app/scripts/components/openstack/openstack-volume/openstack-volume-snapshots.js
app/scripts/components/openstack/openstack-volume/openstack-volume-snapshots.js
const volumeSnapshots = { templateUrl: 'views/partials/filtered-list.html', controller: VolumeSnapshotsListController, controllerAs: 'ListController', bindings: { resource: '<' } }; export default volumeSnapshots; // @ngInject function VolumeSnapshotsListController( baseResourceListController, $scope, $timeout, actionUtilsService) { var controllerScope = this; var ResourceController = baseResourceListController.extend({ init: function() { this.controllerScope = controllerScope; this.listActions = null; var list_type = 'snapshots'; var fn = this._super.bind(this); var vm = this; actionUtilsService.loadNestedActions(this, controllerScope.resource, list_type).then(function(result) { vm.listActions = result; fn(); }); $scope.$on('actionApplied', function(event, name) { if (name === 'snapshot') { $timeout(function() { controllerScope.resetCache(); }); } }); }, getTableOptions: function() { var options = this._super(); options.noDataText = 'You have no snapshots yet'; options.noMatchesText = 'No snapshots found matching filter.'; return options; }, getFilter: function() { return { source_volume_uuid: controllerScope.resource.uuid, resource_type: 'OpenStackTenant.Snapshot' }; }, getTableActions: function() { return this.listActions; }, }); controllerScope.__proto__ = new ResourceController(); }
const volumeSnapshots = { templateUrl: 'views/partials/filtered-list.html', controller: VolumeSnapshotsListController, controllerAs: 'ListController', bindings: { resource: '<' } }; export default volumeSnapshots; // @ngInject function VolumeSnapshotsListController( baseResourceListController, $scope, $timeout, actionUtilsService) { var controllerScope = this; var ResourceController = baseResourceListController.extend({ init: function() { this.controllerScope = controllerScope; this.listActions = null; var list_type = 'snapshots'; var fn = this._super.bind(this); this.loading = true; actionUtilsService.loadNestedActions(this, controllerScope.resource, list_type).then(result => { this.listActions = result; fn(); }); $scope.$on('actionApplied', function(event, name) { if (name === 'snapshot') { $timeout(function() { controllerScope.resetCache(); }); } }); }, getTableOptions: function() { var options = this._super(); options.noDataText = 'You have no snapshots yet'; options.noMatchesText = 'No snapshots found matching filter.'; return options; }, getFilter: function() { return { source_volume_uuid: controllerScope.resource.uuid, resource_type: 'OpenStackTenant.Snapshot' }; }, getTableActions: function() { return this.listActions; }, }); controllerScope.__proto__ = new ResourceController(); }
Use arrow functions instead of vm variable (WAL-400)
Use arrow functions instead of vm variable (WAL-400)
JavaScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
a150a6caa9db55a262335df60a8048e03171a227
feature-detects/es6/promises.js
feature-detects/es6/promises.js
/*! { "name": "ES6 Promises", "property": "promises", "caniuse": "promises", "polyfills": ["es6promises"], "authors": ["Krister Kari", "Jake Archibald"], "tags": ["es6"], "notes": [{ "name": "The ES6 promises spec", "href": "https://github.com/domenic/promises-unwrapping" },{ "name": "Chromium dashboard - ES6 Promises", "href": "http://www.chromestatus.com/features/5681726336532480" },{ "name": "JavaScript Promises: There and back again - HTML5 Rocks", "href": "http://www.html5rocks.com/en/tutorials/es6/promises/" }] } !*/ /* DOC Check if browser implements ECMAScript 6 Promises per specification. */ define(['Modernizr'], function( Modernizr ) { Modernizr.addTest('promises', function() { return 'Promise' in window && // Some of these methods are missing from // Firefox/Chrome experimental implementations 'cast' in window.Promise && 'resolve' in window.Promise && 'reject' in window.Promise && 'all' in window.Promise && 'race' in window.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new window.Promise(function(r) { resolve = r; }); return typeof resolve === 'function'; }()); }); });
/*! { "name": "ES6 Promises", "property": "promises", "caniuse": "promises", "polyfills": ["es6promises"], "authors": ["Krister Kari", "Jake Archibald"], "tags": ["es6"], "notes": [{ "name": "The ES6 promises spec", "href": "https://github.com/domenic/promises-unwrapping" },{ "name": "Chromium dashboard - ES6 Promises", "href": "http://www.chromestatus.com/features/5681726336532480" },{ "name": "JavaScript Promises: There and back again - HTML5 Rocks", "href": "http://www.html5rocks.com/en/tutorials/es6/promises/" }] } !*/ /* DOC Check if browser implements ECMAScript 6 Promises per specification. */ define(['Modernizr'], function( Modernizr ) { Modernizr.addTest('promises', function() { return 'Promise' in window && // Some of these methods are missing from // Firefox/Chrome experimental implementations 'resolve' in window.Promise && 'reject' in window.Promise && 'all' in window.Promise && 'race' in window.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new window.Promise(function(r) { resolve = r; }); return typeof resolve === 'function'; }()); }); });
Remove "cast" from Promise test
Remove "cast" from Promise test Promise.resolve now behaves as Promise.cast
JavaScript
mit
Modernizr/Modernizr,Modernizr/Modernizr
607cedc66dcee8d76c2786e1aa2b2389577bd204
src/plugins/loading-bar.js
src/plugins/loading-bar.js
import Vue from 'vue' import { isSSR } from './platform.js' import QAjaxBar from '../components/ajax-bar/QAjaxBar.js' export default { start () {}, stop () {}, increment () {}, install ({ $q, cfg }) { if (isSSR) { $q.loadingBar = this return } const bar = $q.loadingBar = new Vue({ render: h => h(QAjaxBar, { ref: 'bar', props: cfg.loadingBar }) }).$mount().$refs.bar Object.assign(this, { start: bar.start, stop: bar.stop, increment: bar.increment }) document.body.appendChild($q.loadingBar.$parent.$el) } }
import Vue from 'vue' import { isSSR } from './platform.js' import QAjaxBar from '../components/ajax-bar/QAjaxBar.js' export default { start () {}, stop () {}, increment () {}, install ({ $q, cfg }) { if (isSSR) { $q.loadingBar = this return } const bar = $q.loadingBar = new Vue({ name: 'LoadingBar', render: h => h(QAjaxBar, { ref: 'bar', props: cfg.loadingBar }) }).$mount().$refs.bar Object.assign(this, { start: bar.start, stop: bar.stop, increment: bar.increment }) document.body.appendChild($q.loadingBar.$parent.$el) } }
Add component name for LoadingBar plugin
chore: Add component name for LoadingBar plugin
JavaScript
mit
pdanpdan/quasar,quasarframework/quasar,pdanpdan/quasar,pdanpdan/quasar,rstoenescu/quasar-framework,rstoenescu/quasar-framework,fsgiudice/quasar,fsgiudice/quasar,quasarframework/quasar,pdanpdan/quasar,quasarframework/quasar,quasarframework/quasar,rstoenescu/quasar-framework,fsgiudice/quasar
9496ca53251d22fa7c43af672dbc39feeeace5fe
test/helpers/capture-candidates.js
test/helpers/capture-candidates.js
module.exports = function(pc, candidates, callback) { var timer; pc.onicecandidate = function(evt) { if (evt.candidate) { console.log(evt); candidates.push(evt.candidate); } else { // TODO: trigger callback when supported } }; timer = setInterval(function() { if (pc.iceGatheringState === 'complete') { // release the event handler reference pc.onicecandidate = null; clearInterval(timer); callback(); } }, 100); };
module.exports = function(pc, candidates, callback) { pc.onicecandidate = function(evt) { if (evt.candidate) { console.log(evt); candidates.push(evt.candidate); } else { callback(); } }; };
Remove the timer for monitoring the icegatheringstate
Remove the timer for monitoring the icegatheringstate
JavaScript
bsd-2-clause
ssaroha/node-webrtc,vshymanskyy/node-webrtc,lresc/node-webrtc,siphontv/node-webrtc,martindale/node-webrtc,martindale/node-webrtc,diffalot/node-webrtc,martindale/node-webrtc,siphontv/node-webrtc,siphontv/node-webrtc,ssaroha/node-webrtc,ssaroha/node-webrtc,siphontv/node-webrtc,guymguym/node-webrtc,martindale/node-webrtc,guymguym/node-webrtc,lresc/node-webrtc,lresc/node-webrtc,ssaroha/node-webrtc,diffalot/node-webrtc,ssaroha/node-webrtc,guymguym/node-webrtc,diffalot/node-webrtc,diffalot/node-webrtc,markandrus/node-webrtc,martindale/node-webrtc,markandrus/node-webrtc,vshymanskyy/node-webrtc,diffalot/node-webrtc,vshymanskyy/node-webrtc,markandrus/node-webrtc,markandrus/node-webrtc,lresc/node-webrtc,guymguym/node-webrtc,guymguym/node-webrtc,siphontv/node-webrtc,vshymanskyy/node-webrtc,lresc/node-webrtc,lresc/node-webrtc,vshymanskyy/node-webrtc,markandrus/node-webrtc
088a0c67588f9334eb8dbed9447055eff3fbfe30
example/controllers/football.js
example/controllers/football.js
'use strict' module.exports = (function(){ /** * Import modules */ const footballDb = require('./../db/footballDb') /** * football module API */ return { 'leagues': leagues, 'leagueTable_id': leagueTable_id } /** * football module API -- leagueTable */ function leagueTable_id(id) { // Auto parses id from query-string return footballDb .leagueTable(id) .then(league => { league.title = 'League Table' return league }) } /** * football module API -- leagues */ function leagues() { return footballDb .leagues() .then(leagues => { leagues = leaguesWithLinks(leagues) return { 'title':'Leagues', 'leagues': leagues } }) } /** * Utility auxiliary function */ function leaguesWithLinks(leagues) { return leagues.map(item => { item.leagueHref = "/football/leagueTable/" + item.id return item }) } })()
'use strict' module.exports = (function(){ /** * Import modules */ const footballDb = require('./../db/footballDb') /** * football module API */ return { 'leagues': leagues, 'leagueTable_id': leagueTable_id } /** * football module API -- leagueTable */ function leagueTable_id(id) { // Auto parses id from route parameters return footballDb .leagueTable(id) .then(league => { league.title = 'League Table' return league }) } /** * football module API -- leagues */ function leagues() { return footballDb .leagues() .then(leagues => { leagues = leaguesWithLinks(leagues) return { 'title':'Leagues', 'leagues': leagues } }) } /** * Utility auxiliary function */ function leaguesWithLinks(leagues) { return leagues.map(item => { item.leagueHref = "/football/leagueTable/" + item.id return item }) } })()
Correct comment on parsing route parameters instead of query
Correct comment on parsing route parameters instead of query
JavaScript
mit
CCISEL/connect-controller,CCISEL/connect-controller
5a63f87a9bf6fa7c4ce54f7c5f650b85190fd930
fetch-browser.js
fetch-browser.js
(function () { 'use strict'; function fetchPonyfill(options) { var Promise = options && options.Promise || self.Promise; var XMLHttpRequest = options && options.XMLHttpRequest || self.XMLHttpRequest; var global = self; return (function () { var self = Object.create(global, { fetch: { value: undefined, writable: true } }); // {{whatwgFetch}} return { fetch: self.fetch.bind(global), Headers: self.Headers, Request: self.Request, Response: self.Response }; }()); } if (typeof define === 'function' && define.amd) { define(function () { return fetchPonyfill; }); } else if (typeof exports === 'object') { module.exports = fetchPonyfill; } else { self.fetchPonyfill = fetchPonyfill; } }());
(function () { 'use strict'; function fetchPonyfill(options) { var Promise = options && options.Promise || self.Promise; var XMLHttpRequest = options && options.XMLHttpRequest || self.XMLHttpRequest; var global = self; return (function () { var self = Object.create(global, { fetch: { value: undefined, writable: true } }); // {{whatwgFetch}} return { fetch: self.fetch, Headers: self.Headers, Request: self.Request, Response: self.Response }; }()); } if (typeof define === 'function' && define.amd) { define(function () { return fetchPonyfill; }); } else if (typeof exports === 'object') { module.exports = fetchPonyfill; } else { self.fetchPonyfill = fetchPonyfill; } }());
Remove global binding that is now not needed anymore
Remove global binding that is now not needed anymore
JavaScript
mit
qubyte/fetch-ponyfill,qubyte/fetch-ponyfill
2cb746c292c9c68d04d9393eeccdf398573a84af
build/tests/bootstrap.js
build/tests/bootstrap.js
// Remove the PUBLIC_URL, if defined process.env.PUBLIC_URL = '' process.env.INSPIRE_API_URL = 'inspire-api-url' require('babel-register')() const { jsdom } = require('jsdom') const moduleAlias = require('module-alias') const path = require('path') moduleAlias.addAlias('common', path.join(__dirname, '../../src')) const exposedProperties = ['window', 'navigator', 'document'] global.document = jsdom('<!doctype html><html><body></body></html>') global.window = document.defaultView Object.keys(document.defaultView).forEach((property) => { if (typeof global[property] === 'undefined') { exposedProperties.push(property) global[property] = document.defaultView[property] } }) global.navigator = window.navigator = { userAgent: 'node.js', platform: 'node.js', } const chai = require('chai') const chaiEnzyme = require('chai-enzyme') global.expect = chai.expect chai.use(chaiEnzyme())
const { JSDOM } = require('jsdom') const moduleAlias = require('module-alias') const path = require('path') require('babel-register')() moduleAlias.addAlias('common', path.join(__dirname, '../../src')) // Remove the PUBLIC_URL, if defined process.env.PUBLIC_URL = '' process.env.INSPIRE_API_URL = 'inspire-api-url' const jsdom = new JSDOM('<!doctype html><html><body></body></html>') const exposedProperties = ['window', 'navigator', 'document'] global.window = jsdom.window global.document = global.window.document Object.keys(document.defaultView).forEach((property) => { if (typeof global[property] === 'undefined') { exposedProperties.push(property) global[property] = document.defaultView[property] } }) global.navigator = window.navigator = { userAgent: 'node.js', platform: 'node.js', } const chai = require('chai') const chaiEnzyme = require('chai-enzyme') global.expect = chai.expect chai.use(chaiEnzyme())
Update JSDOM usage due to API change
Update JSDOM usage due to API change
JavaScript
mit
sgmap/inspire,sgmap/inspire
c14bea03e77d0b7573ae087c879cadfc3ca9c970
firefox/prefs.js
firefox/prefs.js
user_pref("accessibility.typeaheadfind.flashBar", 0); user_pref("accessibility.typeaheadfind.prefillwithselection", true); user_pref("browser.backspace_action", 2); user_pref("browser.bookmarks.restore_default_bookmarks", false); user_pref("browser.newtab.url", "about:blank"); user_pref("browser.search.suggest.enabled", false); user_pref("browser.selfsupport.url", ""); user_pref("browser.showQuitWarning", true); user_pref("browser.startup.homepage", "about:blank"); user_pref("browser.tabs.animate", false); user_pref("browser.tabs.closeWindowWithLastTab", false); user_pref("browser.tabs.warnOnClose", false); user_pref("datareporting.healthreport.uploadEnabled", false); user_pref("network.cookie.cookieBehavior", 3); user_pref("network.cookie.lifetimePolicy", 2); user_pref("network.http.referer.spoofSource", true); user_pref("network.http.referer.trimmingPolicy", 2); user_pref("network.http.referer.XOriginPolicy", 2); user_pref("toolkit.telemetry.enabled", false);
user_pref("accessibility.typeaheadfind.flashBar", 0); user_pref("accessibility.typeaheadfind.prefillwithselection", true); user_pref("browser.backspace_action", 2); user_pref("browser.bookmarks.restore_default_bookmarks", false); user_pref("browser.newtab.url", "about:blank"); user_pref("browser.readinglist.enabled", false); user_pref("browser.search.suggest.enabled", false); user_pref("browser.selfsupport.url", ""); user_pref("browser.showQuitWarning", true); user_pref("browser.startup.homepage", "about:blank"); user_pref("browser.tabs.animate", false); user_pref("browser.tabs.closeWindowWithLastTab", false); user_pref("browser.tabs.warnOnClose", false); user_pref("datareporting.healthreport.uploadEnabled", false); user_pref("loop.enabled", false); user_pref("network.cookie.cookieBehavior", 3); user_pref("network.cookie.lifetimePolicy", 2); user_pref("network.http.referer.spoofSource", true); user_pref("network.http.referer.trimmingPolicy", 2); user_pref("network.http.referer.XOriginPolicy", 2); user_pref("readinglist.scheduler.enabled", false); user_pref("toolkit.telemetry.enabled", false);
Disable a few unused features
firefox: Disable a few unused features
JavaScript
mit
poiru/dotfiles,poiru/dotfiles,poiru/dotfiles
9d43d46eac238af0ac1a038916e6ebe21383fc95
gatsby-config.js
gatsby-config.js
module.exports = { siteMetadata: { siteUrl: 'https://chocolate-free.com/', title: 'Chocolate Free', }, plugins: [ { resolve: 'gatsby-source-contentful', options: { spaceId: '0w6gaytm0wfv', accessToken: 'c9414fe612e8c31f402182354c5263f9c6b1f0c611ae5597585cb78692dc2493', }, }, { resolve: 'gatsby-plugin-google-analytics', options: { trackingId: 'UA-89281107-1', }, }, { resolve: 'gatsby-plugin-sitemap' }, { resolve: 'gatsby-plugin-manifest', options: { 'name': 'Chocolate-free', 'short_name': 'ChocoFree', 'start_url': '/', 'background_color': '#e8e8e8', 'icons': [ { 'src': '/android-chrome-192x192.png', 'sizes': '192x192', 'type': 'image/png' }, { 'src': '/android-chrome-512x512.png', 'sizes': '512x512', 'type': 'image/png' } ], 'theme_color': '#e8e8e8', 'display': 'standalone' } }, 'gatsby-plugin-offline', 'gatsby-transformer-remark', 'gatsby-plugin-sass' ], }
module.exports = { siteMetadata: { siteUrl: 'https://chocolate-free.com/', title: 'Chocolate Free', }, plugins: [ { resolve: 'gatsby-source-contentful', options: { spaceId: process.env.CHOCOLATE_FREE_CF_SPACE, accessToken: process.env.CHOCOLATE_FREE_CF_TOKEN }, }, { resolve: 'gatsby-plugin-google-analytics', options: { trackingId: 'UA-89281107-1', }, }, { resolve: 'gatsby-plugin-sitemap' }, { resolve: 'gatsby-plugin-manifest', options: { 'name': 'Chocolate-free', 'short_name': 'ChocoFree', 'start_url': '/', 'background_color': '#e8e8e8', 'icons': [ { 'src': '/android-chrome-192x192.png', 'sizes': '192x192', 'type': 'image/png' }, { 'src': '/android-chrome-512x512.png', 'sizes': '512x512', 'type': 'image/png' } ], 'theme_color': '#e8e8e8', 'display': 'standalone' } }, 'gatsby-plugin-offline', 'gatsby-transformer-remark', 'gatsby-plugin-sass' ], }
Replace api key with env vars
Replace api key with env vars
JavaScript
apache-2.0
Khaledgarbaya/chocolate-free-website,Khaledgarbaya/chocolate-free-website
930bcf06b7cca0993d0c13250b1ae7bd484643ba
src/js/routes.js
src/js/routes.js
'use strict'; angular.module('mission-control').config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { // For unmatched routes $urlRouterProvider.otherwise('/'); // Application routes $stateProvider .state('index', { url: '/', templateUrl: 'views/overview.html', controller: 'OverviewCtrl' }) .state('agenda', { url: '/agenda', templateUrl: 'views/agenda.html', controller: 'AgendaCtrl' }) .state('events', { url: '/events', templateUrl: 'views/events.html', controller: 'EventsCtrl' }) .state('members', { url: '/members', templateUrl: 'views/members.html', controller: 'MembersCtrl' }) .state('sponsors', { url: '/sponsors', templateUrl: 'views/sponsors.html', controller: 'SponsorsCtrl' }) .state('tasks', { url: '/tasks', templateUrl: 'views/tasks.html', controller: 'TasksCtrl' }); } ]);
'use strict'; angular.module('mission-control').config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { // For unmatched routes $urlRouterProvider.otherwise('/'); // Application routes $stateProvider .state('index', { url: '/', templateUrl: 'views/overview.html', controller: 'OverviewCtrl' }) .state('agenda', { url: '/agenda', templateUrl: 'views/agenda.html', controller: 'AgendaCtrl' }) .state('events', { url: '/events', templateUrl: 'views/events.html', controller: 'EventsCtrl' }) .state('members', { url: '/members', templateUrl: 'views/members.html', controller: 'MembersCtrl' }) .state('mentors', { url: '/mentors', templateUrl: 'views/mentors.html', controller: 'MentorsCtrl' }) .state('sponsors', { url: '/sponsors', templateUrl: 'views/sponsors.html', controller: 'SponsorsCtrl' }) .state('tasks', { url: '/tasks', templateUrl: 'views/tasks.html', controller: 'TasksCtrl' }); } ]);
Add mentors route to router
Add mentors route to router
JavaScript
mit
craigcabrey/mission-control,craigcabrey/mission-control
b40447a79ed4d94ba05e379e4192556c271a1e4b
test/browser.spec.js
test/browser.spec.js
var expect = require('chai').expect; var request = require('supertest'); var http = require('http'); var cookie = require('../lib/browser'); describe('server-side cookie', function() { describe('.set', function() { it('should work', function() { cookie.set('yolo', 'swag'); expect(cookie.get('yolo')).to.equal('swag'); }); }); describe('.remove', function() { it('should work', function() { cookie.set('yolo', 'swag'); expect(cookie.get('yolo')).to.equal('swag'); cookie.remove('yolo'); expect(cookie.get('yolo')).to.be.undefined; }); }); });
var expect = require('chai').expect; var request = require('supertest'); var http = require('http'); var cookie = require('../lib/browser'); describe('server-side cookie', function() { describe('.get', function() { it('should work', function() { expect(cookie.get('swag_swag_swag_')).to.be.undefined; }); }); describe('.set', function() { it('should work', function() { cookie.set('yolo', 'swag'); expect(cookie.get('yolo')).to.equal('swag'); }); }); describe('.remove', function() { it('should work', function() { cookie.set('yolo', 'swag'); expect(cookie.get('yolo')).to.equal('swag'); cookie.remove('yolo'); expect(cookie.get('yolo')).to.be.undefined; }); }); });
Add simple test case for browser `.get`
Add simple test case for browser `.get`
JavaScript
mit
srph/cookie-machine
09c0f85065d496bec9e869f3ec170648b99f77c9
lib/middleware/request_proxy.js
lib/middleware/request_proxy.js
// Copyright (C) 2007-2014, GoodData(R) Corporation. var httpProxy = require('http-proxy'); module.exports = function(host) { var currentHost, currentPort; var proxy = new httpProxy.RoutingProxy({ target: { https: true } }); var requestProxy = function(req, res, next) { // Because backend does not answer without set content length if (req.method === 'DELETE') { // Only set content-length to zero if not already specified req.headers['content-length'] = req.headers['content-length'] || '0'; } // White labeled resources are based on host header req.headers['host'] = currentHost + (currentPort!==443 ? ':'+currentPort : ''); // Remove Origin header so it's not evaluated as cross-domain request req.headers['origin'] = null; // Proxy received request to curret backend endpoint proxy.proxyRequest(req, res, { host: currentHost, port: currentPort, target: { // don't choke on self-signed certificates used by *.getgooddata.com rejectUnauthorized: false } }); }; requestProxy.proxy = proxy; requestProxy.setHost = function(value) { var splithost = value ? value.split(/:/) : ''; currentHost = splithost[0]; currentPort = parseInt(splithost[1] || '443', 10); }; // set the host/port combination requestProxy.setHost(host); return requestProxy; };
// Copyright (C) 2007-2014, GoodData(R) Corporation. var httpProxy = require('http-proxy'); module.exports = function(host) { var currentHost, currentPort; var proxy = new httpProxy.RoutingProxy({ target: { https: true } }); var requestProxy = function(req, res, next) { // Because backend does not answer without set content length if (req.method === 'DELETE') { // Only set content-length to zero if not already specified req.headers['content-length'] = req.headers['content-length'] || '0'; } // White labeled resources are based on host header req.headers['host'] = currentHost + (currentPort!==443 ? ':'+currentPort : ''); // Remove Origin header so it's not evaluated as cross-domain request req.headers['origin'] = null; // To prevent CSRF req.headers['referer'] = 'https://' + host; // Proxy received request to curret backend endpoint proxy.proxyRequest(req, res, { host: currentHost, port: currentPort, target: { // don't choke on self-signed certificates used by *.getgooddata.com rejectUnauthorized: false } }); }; requestProxy.proxy = proxy; requestProxy.setHost = function(value) { var splithost = value ? value.split(/:/) : ''; currentHost = splithost[0]; currentPort = parseInt(splithost[1] || '443', 10); }; // set the host/port combination requestProxy.setHost(host); return requestProxy; };
Set referer header to prevent CSRF
Set referer header to prevent CSRF
JavaScript
bsd-3-clause
gooddata/grunt-grizzly,crudo/grunt-grizzly
6e6ec8c967ddb486a979a267016e7eb2b5c7ff4d
eachSeries.js
eachSeries.js
import when from 'when'; let openFiles = ['a.js', 'b.js', 'c.js'], saveFile = (file) => { console.log('saveFile', file); return new Promise((resolve, reject) => { setTimeout( () => { console.log('timeout', file); resolve(file); }, 2000 ); }); }; let results = []; openFiles.reduce( (promise, file) => { return promise .then(saveFile.bind(null, file)) .then((result) => { results.push(result); return results; }); }, Promise.resolve() ) .then((...args) => { console.log('promise done', args); }) .catch((error) => { console.log('promise error', error); }); when.reduce(openFiles, (results, file) => { return saveFile(file) .then((result) => { results.push(result); return results; }); }, []) .then((...args) => { console.log('when done', args); }) .catch((error) => { console.log('when error', error); });
import when from 'when'; let openFiles = ['a.js', 'b.js', 'c.js'], saveFile = (file) => { console.log('saveFile', file); return new Promise((resolve, reject) => { setTimeout( () => { console.log('timeout', file); resolve(file); }, 2000 ); }); }; openFiles.reduce( (promise, file) => promise.then((results) => { return saveFile(file) .then((result) => { results.push(result); return results; }); }), Promise.resolve([]) ) .then((...args) => { console.log('promise done', args); }) .catch((error) => { console.log('promise error', error); }); when.reduce(openFiles, (results, file) => { return saveFile(file) .then((result) => { results.push(result); return results; }); }, []) .then((...args) => { console.log('when done', args); }) .catch((error) => { console.log('when error', error); });
Update each series results to be embedded in the reduce
Update each series results to be embedded in the reduce
JavaScript
mit
jgornick/asyncp
f7d374595d08b3421f0da67932f5fcbb7a092e8d
src/lib/watch.js
src/lib/watch.js
"use strict"; var db = require("./firebase"); // Ensure the updated timestamp is always accurate-ish module.exports = function(ref) { ref.on("child_changed", function(snap) { var key = snap.key(), auth; // Avoid looping forever if(key === "updated_at" || key === "updated_by") { return; } auth = db.getAuth(); // Clean up any old updated timestamps floating around ref.child("updated").remove(); ref.child("updated_at").set(db.TIMESTAMP); ref.child("updated_by").set(auth.uid); }); };
"use strict"; var db = require("./firebase"); // Ensure the updated timestamp is always accurate-ish module.exports = function(ref) { ref.on("child_changed", function(snap) { var key = snap.key(), auth; // Avoid looping forever if(key === "updated_at" || key === "updated_by") { return; } auth = db.getAuth(); // Clean up any old updated timestamps floating around ref.child("updated").remove(); ref.update({ updated_at : db.TIMESTAMP, updated_by : auth.uid }); }); };
Convert two .set() calls into one .update()
Convert two .set() calls into one .update()
JavaScript
mit
tivac/crucible,Ryan-McMillan/crucible,kevinkace/crucible,tivac/anthracite,kevinkace/crucible,tivac/anthracite,tivac/crucible,Ryan-McMillan/crucible
3b0ea4f643c065a14b8bd79d27111e69d3698b2b
erisevents.js
erisevents.js
const eris = justcord.eris; const config = justcord.config; const chat = justcord.chat; eris.on("ready", () => { console.log("Justcord ready!"); // TODO: Add logging utility functions eris.createMessage(config.eris.id, "Server connected to the guild successfully!") }); eris.on("messageCreate", (message) => { if (message.channel.id == config.eris.id && message.member.id != eris.user.id) { chat.broadcast(`${message.member.nick}: ${message.content}`); console.log(`Discord: ${message.member.nick}: ${message.content}`); } });
const eris = justcord.eris; const config = justcord.config; const chat = justcord.chat; eris.on("ready", () => { console.log("Justcord ready!"); // TODO: Add logging utility functions eris.createMessage(config.eris.id, "Server connected to the guild successfully!") }); eris.on("messageCreate", (message) => { if (message.channel.id == config.eris.id && message.member.id != eris.user.id) { let name = message.member.nick; if (!name) name = message.member.user.username; chat.broadcast(`${name}: ${message.content}`); console.log(`Discord: ${name}: ${message.content}`); } });
Use username if nickname is null
Use username if nickname is null
JavaScript
mit
md678685/justcord-3
560f6420d7681201cb404eb39e80f3000102e53c
lib/_memoize-watcher.js
lib/_memoize-watcher.js
'use strict'; var noop = require('es5-ext/function/noop') , assign = require('es5-ext/object/assign') , memoize = require('memoizee') , ee = require('event-emitter') , deferred = require('deferred') , isPromise = deferred.isPromise; module.exports = function (fn/*, options*/) { var factory, memoized; if (fn.memoized) return fn; memoized = memoize(fn, assign(Object(arguments[1]), { refCounter: true })); factory = function () { var watcher, emitter, pipe, args, def; args = arguments; watcher = memoized.apply(this, arguments); if (isPromise(watcher)) { def = deferred(); emitter = def.promise; def.resolve(watcher); } else { emitter = ee(); } pipe = ee.pipe(watcher, emitter); emitter.close = function () { emitter.close = noop; pipe.close(); if (memoized.clearRef.apply(this, args)) watcher.close(); }; return emitter; }; factory.clear = memoized.clear; factory.memoized = true; return factory; };
'use strict'; var noop = require('es5-ext/function/noop') , assign = require('es5-ext/object/assign') , memoize = require('memoizee') , ee = require('event-emitter') , eePipe = require('event-emitter/lib/pipe') , deferred = require('deferred') , isPromise = deferred.isPromise; module.exports = function (fn/*, options*/) { var factory, memoized; if (fn.memoized) return fn; memoized = memoize(fn, assign(Object(arguments[1]), { refCounter: true })); factory = function () { var watcher, emitter, pipe, args, def; args = arguments; watcher = memoized.apply(this, arguments); if (isPromise(watcher)) { def = deferred(); emitter = def.promise; def.resolve(watcher); } else { emitter = ee(); } pipe = eePipe(watcher, emitter); emitter.close = function () { emitter.close = noop; pipe.close(); if (memoized.clearRef.apply(this, args)) watcher.close(); }; return emitter; }; factory.clear = memoized.clear; factory.memoized = true; return factory; };
Update up to changes in event-emitter package
Update up to changes in event-emitter package
JavaScript
isc
medikoo/fs2
79c32b103f5cbd76b5f9d287c89372704cfbc35e
bin/setup.js
bin/setup.js
#!/usr/bin/env node // Must symlink the generator from xtc's modules up to the project's modules. // Else Yeoman won't find it. var path = require('path') fs = require('fs') ; // process.cwd() == __dirname if ('install' === process.env.npm_lifecycle_event) { try { fs.symlinkSync(path.join(process.cwd(), '/node_modules/generator-xtc'), path.join(process.cwd(), '../generator-xtc'), 'dir'); console.log('symlink: generator-xtc into node_modules\n') } catch (e) { if (e.code === 'EEXIST') { console.info('symlink: generator-xtc already already exists node_modules\n'); } else { throw e; } } } // And of course we remove it again before xtc is uninstalled else if ('uninstall' === process.env.npm_lifecycle_event) { try { fs.unlinkSync(path.join(process.cwd(), '../generator-xtc'), 'dir'); console.log('symlink: removed generator-xtc from node_modules\n') } catch (e) { if (e.code !== 'ENOENT') { console.info('symlink: Unable to remove generator-xtc from node_modules\n'); } throw e; } }
#!/usr/bin/env node // Must symlink the generator from xtc's modules up to the project's modules. // Else Yeoman won't find it. var path = require('path') fs = require('fs') ; // process.cwd() == __dirname if ('install' === process.env.npm_lifecycle_event) { try { fs.symlinkSync(path.join(process.cwd(), '/node_modules/generator-xtc'), path.join(process.cwd(), '../generator-xtc'), 'dir'); console.log('symlink: generator-xtc into node_modules\n') } catch (e) { if (e.code === 'EEXIST') { console.info('symlink: generator-xtc already exists in node_modules\n'); } else { throw e; } } } // And of course we remove it again before xtc is uninstalled else if ('uninstall' === process.env.npm_lifecycle_event) { try { fs.unlinkSync(path.join(process.cwd(), '../generator-xtc'), 'dir'); console.log('symlink: removed generator-xtc from node_modules\n') } catch (e) { if (e.code !== 'ENOENT') { console.info('symlink: Unable to remove generator-xtc from node_modules\n'); } throw e; } }
Fix typo in error message
Fix typo in error message
JavaScript
mit
MarcDiethelm/xtc
24bd88bb2965515ac7f9ffecde850e7f63ce23a5
app/scripts/app/routes/items.js
app/scripts/app/routes/items.js
var ItemsRoute = Em.Route.extend({ model: function (params) { return this.api.fetchAll('items', 'groups', params.group_id); }, setupController: function (controller, model) { // allow sub-routes to access the GroupId since it seems the dynamic segment is not available otherwise controller.set('GroupId', model.get('firstObject.GroupId')); this._super(controller, model); }, renderTemplate: function () { this.render('items', { into: 'application', outlet: 'items', }); }, actions: { refresh: function () { this.refresh(); return true; } } }); export default ItemsRoute;
var ItemsRoute = Em.Route.extend({ model: function (params) { this.set('currentGroupId', parseInt(params.group_id, 10)); return this.api.fetchAll('items', 'groups', params.group_id); }, setupController: function (controller, model) { // allow sub-routes to access the GroupId since it seems the dynamic segment is not available otherwise controller.set('GroupId', this.get('currentGroupId')); this._super(controller, model); }, renderTemplate: function () { this.render('items', { into: 'application', outlet: 'items', }); }, actions: { refresh: function () { this.refresh(); return true; } } }); export default ItemsRoute;
Fix setting GroupId on ItemsController when its model is empty
Fix setting GroupId on ItemsController when its model is empty
JavaScript
mit
darvelo/wishlist,darvelo/wishlist
51e2104a004ca63fb1e7f5262e61441b558bd288
packages/react-native-version-check-expo/src/ExpoVersionInfo.js
packages/react-native-version-check-expo/src/ExpoVersionInfo.js
let RNVersionCheck; if (process.env.RNVC_ENV === 'test') { RNVersionCheck = { country: 'ko', packageName: 'com.reactnative.versioncheck', currentBuildNumber: 1, currentVersion: '0.0.1', }; } else { const { Platform } = require('react-native'); const { Constants, Util } = require('expo'); const { manifest = {} } = Constants; const { version = null, android: { versionCode = null, package: androidPackageName = null } = {}, ios: { bundleIdentifier = null, buildNumber = null } = {}, } = manifest; RNVersionCheck = { currentVersion: version, country: Util.getCurrentDeviceCountryAsync(), currentBuildNumber: Platform.select({ android: versionCode, ios: buildNumber, }), packageName: Platform.select({ android: androidPackageName, ios: bundleIdentifier, }), }; } const COUNTRY = RNVersionCheck.country; const PACKAGE_NAME = RNVersionCheck.packageName; const CURRENT_BUILD_NUMBER = RNVersionCheck.currentBuildNumber; const CURRENT_VERSION = RNVersionCheck.currentVersion; export default { getCountry: () => Promise.resolve(COUNTRY), getPackageName: () => PACKAGE_NAME, getCurrentBuildNumber: () => CURRENT_BUILD_NUMBER, getCurrentVersion: () => CURRENT_VERSION, };
let RNVersionCheck; if (process.env.RNVC_ENV === 'test') { RNVersionCheck = { country: 'ko', packageName: 'com.reactnative.versioncheck', currentBuildNumber: 1, currentVersion: '0.0.1', }; } else { const { Platform } = require('react-native'); const { Constants, Localization, Util } = require('expo'); const { manifest = {} } = Constants; const { version = null, android: { versionCode = null, package: androidPackageName = null } = {}, ios: { bundleIdentifier = null, buildNumber = null } = {}, } = manifest; RNVersionCheck = { currentVersion: version, country: `${Constants.expoVersion < 26 ? Util.getCurrentDeviceCountryAsync : Localization.getCurrentDeviceCountryAsync()}`, currentBuildNumber: Platform.select({ android: versionCode, ios: buildNumber, }), packageName: Platform.select({ android: androidPackageName, ios: bundleIdentifier, }), }; } const COUNTRY = RNVersionCheck.country; const PACKAGE_NAME = RNVersionCheck.packageName; const CURRENT_BUILD_NUMBER = RNVersionCheck.currentBuildNumber; const CURRENT_VERSION = RNVersionCheck.currentVersion; export default { getCountry: () => Promise.resolve(COUNTRY), getPackageName: () => PACKAGE_NAME, getCurrentBuildNumber: () => CURRENT_BUILD_NUMBER, getCurrentVersion: () => CURRENT_VERSION, };
Use `Localization.getCurrentDeviceCountryAsync` if its version of expo is over 26 since it's deprecated.
Use `Localization.getCurrentDeviceCountryAsync` if its version of expo is over 26 since it's deprecated. ref:https://github.com/expo/expo-docs/tree/master/versions/v26.0.0/sdk
JavaScript
mit
kimxogus/react-native-version-check,kimxogus/react-native-version-check,kimxogus/react-native-version-check
c1b67784c26c4c2658446dddbed92ef44b8bd84a
web/src/js/app/views/ViewportView.js
web/src/js/app/views/ViewportView.js
cinema.views.ViewportView = Backbone.View.extend({ initialize: function () { this.$el.html(cinema.app.templates.viewport()); this.camera = new cinema.models.CameraModel({ info: this.model }); this.renderView = new cinema.views.VisualizationCanvasWidget({ el: this.$('.c-app-renderer-container'), model: this.model, camera: this.camera }).render(); this.mouseInteractor = new cinema.utilities.RenderViewMouseInteractor({ renderView: this.renderView, camera: this.camera }).enableMouseWheelZoom({ maxZoomLevel: 10, zoomIncrement: 0.05, invertControl: false }).enableDragPan({ keyModifiers: cinema.keyModifiers.SHIFT }).enableDragRotation({ keyModifiers: null }); this.listenTo(this.camera, 'change', this._refreshCamera); }, updateQuery: function (query) { this.renderView.updateQuery(query); }, _refreshCamera: function () { this.renderView.showViewpoint(); }, });
cinema.views.ViewportView = Backbone.View.extend({ initialize: function (opts) { this.$el.html(cinema.app.templates.viewport()); this.camera = opts.camera || new cinema.models.CameraModel({ info: this.model }); this.renderView = new cinema.views.VisualizationCanvasWidget({ el: this.$('.c-app-renderer-container'), model: this.model, camera: this.camera }).render(); this.mouseInteractor = new cinema.utilities.RenderViewMouseInteractor({ renderView: this.renderView, camera: this.camera }).enableMouseWheelZoom({ maxZoomLevel: 10, zoomIncrement: 0.05, invertControl: false }).enableDragPan({ keyModifiers: cinema.keyModifiers.SHIFT }).enableDragRotation({ keyModifiers: null }); this.listenTo(this.camera, 'change', this._refreshCamera); }, updateQuery: function (query) { this.renderView.updateQuery(query); }, _refreshCamera: function () { this.renderView.showViewpoint(); } });
Allow viewport to be initialized with a pre-existing camera model
Allow viewport to be initialized with a pre-existing camera model
JavaScript
bsd-3-clause
Kitware/cinema,Kitware/cinema,Kitware/cinema,Kitware/cinema
1c7c553128fcc842f394c429dfc28dbce934fb86
pegasus/sites.v3/code.org/public/js/applab-docs.js
pegasus/sites.v3/code.org/public/js/applab-docs.js
/*global CodeMirror*/ $(function() { $('pre').each(function() { var preElement = $(this); var code = dedent(preElement.text()).trim(); preElement.empty(); CodeMirror(this, { value: code, mode: 'javascript', lineNumbers: !preElement.is('.inline'), readOnly: true }); }); $("a[href^='http']").attr("target", "_blank"); }); function getIndent(str) { var matches = str.match(/^[\s\\t]*/gm); var indent = matches[0].length; for (var i = 1; i < matches.length; i++) { indent = Math.min(matches[i].length, indent); } return indent; } function dedent(str, pattern) { var indent = getIndent(str); var reg; if (indent === 0) { return str; } if (typeof pattern === 'string') { reg = new RegExp('^' + pattern, 'gm'); } else { reg = new RegExp('^[ \\t]{' + indent + '}', 'gm'); } return str.replace(reg, ''); }
/*global CodeMirror*/ $(function() { $('pre').each(function() { var preElement = $(this); var code = dedent(preElement.text()).trim(); preElement.empty(); CodeMirror(this, { value: code, mode: 'javascript', lineNumbers: !preElement.is('.inline'), readOnly: true }); }); $("a[href^='http']").attr("target", "_blank"); rewrite_urls(); }); /** * Our x-frame-options require that any page that is embedded * in an iframe include embedded as a query arg. */ function rewrite_urls() { var is_embedded = window.location.href.endsWith("embedded"); if (!is_embedded) { return; } $('a').each(function () { var a = this; var href = $(a).attr('href'); if (href.startsWith("/applab/docs")) { var new_href = href; if (href.indexOf("?") > -1) { new_href += "&embedded"; } else { new_href += "?embedded"; } $(a).attr('href', new_href); } }); } function getIndent(str) { var matches = str.match(/^[\s\\t]*/gm); var indent = matches[0].length; for (var i = 1; i < matches.length; i++) { indent = Math.min(matches[i].length, indent); } return indent; } function dedent(str, pattern) { var indent = getIndent(str); var reg; if (indent === 0) { return str; } if (typeof pattern === 'string') { reg = new RegExp('^' + pattern, 'gm'); } else { reg = new RegExp('^[ \\t]{' + indent + '}', 'gm'); } return str.replace(reg, ''); }
Rewrite documentation urls to forward on the embedded flag
Rewrite documentation urls to forward on the embedded flag
JavaScript
apache-2.0
rvarshney/code-dot-org,pickettd/code-dot-org,rvarshney/code-dot-org,dillia23/code-dot-org,pickettd/code-dot-org,rvarshney/code-dot-org,dillia23/code-dot-org,pickettd/code-dot-org,pickettd/code-dot-org,dillia23/code-dot-org,pickettd/code-dot-org,rvarshney/code-dot-org,dillia23/code-dot-org,pickettd/code-dot-org,rvarshney/code-dot-org,rvarshney/code-dot-org,rvarshney/code-dot-org,pickettd/code-dot-org,rvarshney/code-dot-org,pickettd/code-dot-org,dillia23/code-dot-org,dillia23/code-dot-org,dillia23/code-dot-org,dillia23/code-dot-org
45c28fca5c5bfad96691fb61b71967f3eb38ffe6
brainfuck.js
brainfuck.js
(function(global) { 'use strict'; (function(id) { var i, j; var tab = document.getElementById(id); var thead = tab.querySelector('thead'); var tbody = tab.querySelector('tbody'); var tr, th, td; // tr = document.createElement('tr'); // th = document.createElement('td'); // tr.appendChild(th); // for (i = 0; i < 30; i++) { // th = document.createElement('th'); // th.textContent = i + 1; // tr.appendChild(th); // } // thead.appendChild(tr); for (i = 0; i < 3; i++) { tr = document.createElement('tr'); // th = document.createElement('th'); // th.textContent = i + 1; // tr.appendChild(th); for (j = 0; j < 30; j++) { td = document.createElement('td'); td.textContent = 0; tr.appendChild(td); } tbody.appendChild(tr); } })('rams'); })(this)
(function(global) { 'use strict'; (function(id) { var i, j; var tab = document.getElementById(id); var thead = tab.querySelector('thead'); var tbody = tab.querySelector('tbody'); var tr, th, td; // tr = document.createElement('tr'); // th = document.createElement('td'); // tr.appendChild(th); // for (i = 0; i < 30; i++) { // th = document.createElement('th'); // th.textContent = i + 1; // tr.appendChild(th); // } // thead.appendChild(tr); for (i = 0; i < 3; i++) { tr = document.createElement('tr'); tr.id = "row-" + i; // th = document.createElement('th'); // th.textContent = i + 1; // tr.appendChild(th); for (j = 0; j < 30; j++) { td = document.createElement('td'); td.textContent = 0; td.id = "cell-" + (i * 30 + j); tr.appendChild(td); } tbody.appendChild(tr); } })('rams'); })(this)
Add ids to the markup
Add ids to the markup
JavaScript
mit
Lexicality/esolang,Lexicality/esolang
2cdd929e7ee6924387e0f96a84c080d111de6604
config/secrets.js
config/secrets.js
module.exports = { db: process.env.MONGODB || process.env.MONGOHQ_URL || 'mongodb://localhost:27017/gamekeller', sessionSecret: process.env.SESSION_SECRET || 'gkdevel' }
module.exports = { db: process.env.MONGODB || 'mongodb://localhost:27017/gamekeller', sessionSecret: process.env.SESSION_SECRET || 'gkdevel' }
Remove support for MONGOHQ_URL env variable
Remove support for MONGOHQ_URL env variable
JavaScript
mit
gamekeller/next,gamekeller/next
790b051f536065f97da5699f9d9332391d4ec97a
config/targets.js
config/targets.js
/* eslint-env node */ module.exports = { browsers: [ 'ie 9', 'last 1 Chrome versions', 'last 1 Firefox versions', 'last 1 Safari versions' ] };
/* eslint-env node */ // Which browsers are returned can be found at http://browserl.ist/ module.exports = { browsers: [ 'last 1 edge versions', 'last 1 chrome versions', 'firefox esr', //actually points to the last 2 ESR releases as they overlap 'last 1 safari versions', 'last 1 ios versions', 'last 1 android versions', ] };
Drop support for older browsers
Drop support for older browsers By only targeting modern evergreen browsers in our build we can significantly reduce the amount of extra code we generate to be compatible with older browsers. This will make our application smaller to download and faster to parse.
JavaScript
mit
thecoolestguy/frontend,thecoolestguy/frontend,djvoa12/frontend,ilios/frontend,dartajax/frontend,jrjohnson/frontend,dartajax/frontend,ilios/frontend,jrjohnson/frontend,djvoa12/frontend
7f84fd91f2196394261e287b0048ea30612858b3
index.js
index.js
var through = require('through2'); var choppa = function(chunkSize) { chunkSize = chunkSize === undefined ? 1 : chunkSize; var prev = new Buffer(0); var transform = function(chunk, enc, cb) { chunk = Buffer.concat([prev, chunk]); var self = this; if (chunkSize > 0) { while (chunk.length >= chunkSize) { self.push(chunk.slice(0, chunkSize)); chunk = chunk.slice(chunkSize); } prev = chunk; } else { while (chunk.length) { var size = Math.floor(Math.random() * chunk.length) + 1; self.push(chunk.slice(0, size)); chunk = chunk.slice(size); } } cb(); }; var flush = function(cb) { this.push(prev); cb(); }; return through(transform, flush); }; module.exports = choppa;
var through = require('through2'); var choppa = function(chunkSize) { chunkSize = chunkSize === undefined ? 1 : chunkSize; var prev = new Buffer(0); var transform = function(chunk, enc, cb) { chunk = Buffer.concat([prev, chunk]); var self = this; if (chunkSize > 0) { while (chunk.length >= chunkSize) { self.push(chunk.slice(0, chunkSize)); chunk = chunk.slice(chunkSize); } prev = chunk; } else { while (chunk.length) { var size = Math.floor(Math.random() * chunk.length) + 1; self.push(chunk.slice(0, size)); chunk = chunk.slice(size); } } cb(); }; var flush = function(cb) { this.push(prev); cb(); }; return through.obj(transform, flush); }; module.exports = choppa;
Fix async reads from the choppa.
Fix async reads from the choppa.
JavaScript
mit
sorribas/choppa
f5f96e1458e43f2360f16297b8e52eb71c666d8d
index.js
index.js
var aglio = require('aglio'); var through2 = require('through2'); var gutil = require('gulp-util'); var PluginError = gutil.PluginError; var defaults = require('lodash.defaults'); var path = require('path'); module.exports = function (options) { 'use strict'; // Mixes in default options. options = defaults(options || {}, { compress: false, paths: [] }); function transform(file, enc, next) { var self = this; if (file.isNull()) { self.push(file); // pass along return next(); } if (file.isStream()) { self.emit('error', new PluginError('gulp-aglio', 'Streaming not supported')); return next(); } var str = file.contents.toString('utf8'); // Clones the options object. var opts = defaults({ theme: 'default' }, options); // Injects the path of the current file. opts.filename = file.path; // Inject includePath for relative includes opts.includePath = opts.includePath || path.dirname(opts.filename); aglio.render(str, opts, function (err, html) { if (err) { self.emit('error', new PluginError('gulp-aglio', err)); } else { file.contents = new Buffer(html); file.path = gutil.replaceExtension(file.path, '.html'); self.push(file); } next(); }); } return through2.obj(transform); };
var aglio = require('aglio'); var through2 = require('through2'); var gutil = require('gulp-util'); var PluginError = gutil.PluginError; var defaults = require('lodash.defaults'); var path = require('path'); module.exports = function (options) { 'use strict'; // Mixes in default options. options = defaults(options || {}, { compress: false, paths: [] }); function transform(file, enc, next) { var self = this; if (file.isNull()) { self.push(file); // pass along return next(); } if (file.isStream()) { self.emit('error', new PluginError('gulp-aglio', 'Streaming not supported')); return next(); } var str = file.contents.toString('utf8'); // Clones the options object. var opts = defaults({ theme: 'default' }, options); // Injects the path of the current file. opts.filename = file.path; // Inject includePath for relative includes opts.includePath = opts.includePath || path.dirname(opts.filename); try { aglio.render(str, opts, function (err, html) { if (err) { self.emit('error', new PluginError('gulp-aglio', err)); } else { file.contents = new Buffer(html); file.path = gutil.replaceExtension(file.path, '.html'); self.push(file); } next(); }); } catch(err) { self.emit("error", new PluginError("gulp-aglio", err)); } } return through2.obj(transform); };
Fix error when files are not found
:bug: Fix error when files are not found Using include syntax with a wrong path resulted in a crash without emitting an error message.
JavaScript
mit
nnnnathann/gulp-aglio,nnnnathann/gulp-aglio
43b808affcd475e7ad94e4f494c306334323dbb3
index.js
index.js
const getJSON = require('get-json'); const overpass = 'http://overpass-api.de/api/interpreter?data='; const query = '[out:json];way[%22highway%22](around:50,51.424037,-0.148666);out;'; getJSON(`${overpass}${query}`, (err, result) => { if (err) console.log(err); console.log(result); });
const getJSON = require('get-json'); const overpass = 'http://overpass-api.de/api/interpreter?data='; const lat = 51.424037; const long = -0.148666; const distance = 50; const query = `[out:json]; way["highway"](around:${distance},${lat},${long}); out;`; getJSON(`${overpass}${query}`, (err, result) => { if (err) console.log(err); console.log(result); });
Use templates to cleanup query
Use templates to cleanup query
JavaScript
mit
mkhalila/nearest-roads
74f1842a096c184982a94d4fc5a95c1a90d18a63
index.js
index.js
var qs = require('querystring') module.exports = function (network, url, opts) { opts = opts || {} if (!linkfor[network]) throw new Error('Unsupported network ' + network) return linkfor[network](url, opts) } var linkfor = { facebook: function (url, opts) { var share = { u: url } if (opts.t) share.t = opts.t return 'https://www.facebook.com/sharer/sharer.php?' + qs.stringify(share) }, googleplus: function (url, opts) { var share = { url: url } return 'https://plus.google.com/share?' + qs.stringify(share) }, pinterest: function (url, opts) { var share = { url: url } if (opts.media) share.media = opts.media if (opts.description) share.description = opts.description return 'http://pinterest.com/pin/create/button/?' + qs.stringify(share) }, twitter: function (url, opts) { var share = { source: url } if (opts.text) share.text = opts.text if (opts.via) share.via = opts.via return 'https://twitter.com/intent/tweet?' + qs.stringify(share) } }
var qs = require('querystring') module.exports = function (network, url, opts) { opts = opts || {} if (!linkfor[network]) throw new Error('Unsupported network ' + network) return linkfor[network](url, opts) } var linkfor = { facebook: function (url, opts) { var share = { u: url } if (opts.t) share.t = opts.t return 'https://www.facebook.com/sharer/sharer.php?' + qs.stringify(share) }, googleplus: function (url, opts) { var share = { url: url } return 'https://plus.google.com/share?' + qs.stringify(share) }, pinterest: function (url, opts) { var share = { url: url } if (opts.media) share.media = opts.media if (opts.description) share.description = opts.description return 'http://pinterest.com/pin/create/button/?' + qs.stringify(share) }, twitter: function (url, opts) { var share = { source: url } if (opts.text) share.text = opts.text if (opts.via) share.via = opts.via return 'https://twitter.com/intent/tweet?' + qs.stringify(share) } } linkfor['google+'] = linkfor.googleplus
Add google+ as alias for googleplus
Add google+ as alias for googleplus
JavaScript
mit
tableflip/share-my-url
64c4b12d5300c2a52b56b150f7202757c4d7c958
index.js
index.js
var _ = require('lodash'); var postcss = require('postcss'); var SEProperties = require('swedish-css-properties'); var SEValues = require('swedish-css-values'); module.exports = postcss.plugin('postcss-swedish-stylesheets', function (opts) { opts = opts || { properties: {}, values: {} }; if (_.isObject(opts.properties)) { SEProperties = _.merge(SEProperties, opts.properties); } if (_.isObject(opts.values)) { SEValues = _.merge(SEValues, opts.values); } // Work with options here return function (css) { css.walkDecls(function transformDecl(decl) { // Properties _.forEach(SEProperties, function (value, key) { if (decl.prop === value) { decl.prop = key; } }); // Values _.forEach(SEValues, function (value, key) { decl.value = decl.value.replace(value, key); }); // Important if (decl.value.indexOf('!viktigt') >= 0) { decl.value = decl.value.replace(/\s*!viktigt\s*/, ''); decl.important = true; } }); }; });
const _ = require('lodash'); const SEProperties = require('swedish-css-properties'); const SEValues = require('swedish-css-values'); const postcssSwedishStylesheets = (opts = {}) => { if (_.isObject(opts.properties)) { _.merge(SEProperties, opts.properties); } if (_.isObject(opts.values)) { _.merge(SEValues, opts.values); } return { postcssPlugin: 'postcss-swedish-stylesheets', Once(root) { root.walkDecls((decl) => { // Properties _.forEach(SEProperties, (value, key) => { if (decl.prop === value) { decl.prop = key; } }); // Values _.forEach(SEValues, (value, key) => { decl.value = decl.value.replace(value, key); }); // Important if (decl.value.indexOf('!viktigt') >= 0) { decl.value = decl.value.replace(/\s*!viktigt\s*/, ''); decl.important = true; } }); }, }; }; module.exports.postcss = true; module.exports = postcssSwedishStylesheets;
Update plugin to use PostCSS 8
feat: Update plugin to use PostCSS 8
JavaScript
mit
johnie/postcss-swedish-stylesheets
e53f9e79ce9b90480f11341a7427e6e8a63ca65a
index.js
index.js
var exec = require('child_process').exec; module.exports = function sysPrefix() { return new Promise(function(resolve, reject) { exec('python -c \'import sys; print(sys.prefix)\'', function(err, stdout) { if (err !== null) { reject(err); } else { resolve(stdout.toString().trim()); } }); }); }
var exec = require('child_process').exec; module.exports = function sysPrefix() { return new Promise(function(resolve, reject) { exec('python -c "import sys; print(sys.prefix)"', function(err, stdout) { if (err !== null) { reject(err); } else { resolve(stdout.toString().trim()); } }); }); }
Switch to double quotes inside the exec
Switch to double quotes inside the exec This allows the exec call to work properly with Windows.
JavaScript
apache-2.0
rgbkrk/sys-prefix-promise
a2ac0281ef8e4a489b87553edec11f650418ef83
index.js
index.js
const express = require('express'); const shortUrlController = require('./lib/short-url-controller.js'); const stubController = require('./lib/stub-controller.js'); const logger = require('winston'); const port = process.env.PORT || 5000; const app = express(); app.set('view engine', 'pug'); app.use('/', stubController); app.use('/new', shortUrlController); const listener = app.listen(port, () => { logger.info(`Your app is listening on port ${listener.address().port}`); });
require('dotenv').config(); const express = require('express'); const shortUrlController = require('./lib/short-url-controller.js'); const stubController = require('./lib/stub-controller.js'); const logger = require('winston'); const port = process.env.PORT || 5000; const app = express(); app.set('view engine', 'pug'); app.use('/', stubController); app.use('/new', shortUrlController); const listener = app.listen(port, () => { logger.info(`Your app is listening on port ${listener.address().port}`); });
Fix dotenv to work locally instead of just on heroku
Fix dotenv to work locally instead of just on heroku
JavaScript
mit
glynnw/url-shortener,glynnw/url-shortener
4e9b368ea408768aa52b44660b564fa23d344781
index.js
index.js
/*! * array-last <https://github.com/jonschlinkert/array-last> * * Copyright (c) 2014 Jon Schlinkert, contributors. * Licensed under the MIT license. */ var isNumber = require('is-number'); module.exports = function last(arr, n) { if (!Array.isArray(arr)) { throw new Error('expected the first argument to be an array'); } var len = arr.length; if (len === 0) { return null; } n = isNumber(n) ? +n : 1; if (n === 1 && len === 1) { return arr[0]; } var res = new Array(n); while (n--) { res[n] = arr[--len]; } return res; };
/*! * array-last <https://github.com/jonschlinkert/array-last> * * Copyright (c) 2014 Jon Schlinkert, contributors. * Licensed under the MIT license. */ var isNumber = require('is-number'); module.exports = function last(arr, n) { if (!Array.isArray(arr)) { throw new Error('expected the first argument to be an array'); } var len = arr.length; if (len === 0) { return null; } n = isNumber(n) ? +n : 1; if (n === 1) { return arr[len - 1]; } var res = new Array(n); while (n--) { res[n] = arr[--len]; } return res; };
Return a single value when n=1
Return a single value when n=1 * Worked previously: last([1], 1) === 1 * Broken previously: last([1, 2], 1) === 2
JavaScript
mit
jonschlinkert/array-last
bb273759bbb9f9edb716fa6596477fa019057fec
index.js
index.js
/* jshint node: true */ 'use strict'; var fs = require('fs'); module.exports = { name: 'uncharted-describe-models', config: function(env, config) { if (env === 'test') { return; } if (!fs.existsSync('app/schema.json')) { throw new Error('You must include a schema.json in the root of app/'); } var schema = JSON.parse(fs.readFileSync('app/schema.json', 'utf8')); config['model-schema'] = schema; return config; }, includedCommands: function() { return { 'update-models': require('./lib/commands/update-models') }; } };
/* jshint node: true */ 'use strict'; var fs = require('fs'); module.exports = { name: 'uncharted-describe-models', config: function(env, config) { if (!fs.existsSync('app/schema.json')) { throw new Error('You must include a schema.json in the root of app/'); } var schema = JSON.parse(fs.readFileSync('app/schema.json', 'utf8')); config['model-schema'] = schema; return config; }, includedCommands: function() { return { 'update-models': require('./lib/commands/update-models') }; } };
Make sure we always load the schema, even within a test
Make sure we always load the schema, even within a test
JavaScript
mit
unchartedcode/describe-models,unchartedcode/describe-models
206a09a32b2f41f19c7340ec599e5d73e86d8cfc
index.js
index.js
var restify = require('restify'); var messenger = require('./lib/messenger'); var session = require('./lib/session'); var server = restify.createServer(); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.use(restify.authorizationParser()); server.get('/', function (req, res, next) { res.send(200, {status: 'ok'}); }); server.post('/messages', function (req, res, next) { var phoneNumber = req.params.From; session.get(phoneNumber, function(err, user) { if (err) messenger.send(phoneNumber, 'There was some kind of error.') if (user) { messenger.send(phoneNumber, 'Hello, old friend.'); } else { session.set(phoneNumber, 'initial', function () { res.send(phoneNumber, 'Nice to meet you.') }) } }); res.send(200, {status: 'ok'}); }); server.listen(process.env.PORT || '3000', function() { console.log('%s listening at %s', server.name, server.url); });
var restify = require('restify'); var messenger = require('./lib/messenger'); var session = require('./lib/session'); var server = restify.createServer(); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.use(restify.authorizationParser()); server.get('/', function (req, res, next) { res.send(200, {status: 'ok'}); }); server.post('/messages', function (req, res, next) { var phoneNumber = req.params.From; session.get(phoneNumber, function(err, user) { if (err) { messenger.send(phoneNumber, 'There was some kind of error.'); res.send(500, {error: 'Something went wrong.'}); } if (user) { messenger.send(phoneNumber, 'Hello, old friend.'); res.send(200); } else { session.set(phoneNumber, 'initial', function () { messenger.send(phoneNumber, 'Nice to meet you.'); res.send(200); }); } }); res.send(200, {status: 'ok'}); }); server.listen(process.env.PORT || '3000', function() { console.log('%s listening at %s', server.name, server.url); });
Send HTTP responses for all messages
Send HTTP responses for all messages
JavaScript
mpl-2.0
rockawayhelp/emergencybadges,rockawayhelp/emergencybadges
b069edce8a3e82dc64e34678db4dd7fe5c508aa3
index.js
index.js
// var http = require("http"); // app.set('view engine', 'html'); var express = require('express'); var app = express(); app.use(express.static(__dirname + '/views')); app.use(express.static(__dirname + '/scripts')); app.listen(3000, function () { console.log('Example app listening on port 3000!') }) app.get('/', function (req, res) { res.send('Hello World!') }) app.post('/', function (req, res) { res.send('Got a POST request') }) app.put('/user', function (req, res) { res.send('Got a PUT request at /user') }) app.delete('/user', function (req, res) { res.send('Got a DELETE request at /user') })
// var http = require("http"); // app.set('view engine', 'html'); var express = require('express'); var app = express(); app.use(express.static(__dirname + '/views')); app.use(express.static(__dirname + '/scripts')); app.listen(3000, function () { console.log('Example app listening on port 3000!') }) app.get('/', function (req, res) { res.send('Hello World!') }) app.post('/', function (req, res) { res.send('Got a POST request') }) app.put('/user', function (req, res) { res.send('Got a PUT request at /user') }) app.delete('/user', function (req, res) { res.send('Got a DELETE request at /user') }) // Route path: /users/:userId/books/:bookId // Request URL: http://localhost:3000/users/34/books/8989 // req.params: { "userId": "34", "bookId": "8989" } // To define routes with route parameters, simply specify the route parameters in the path of the route as shown below. app.get('/users/:userId/books/:bookId', function (req, res) { res.send(req.params) })
Add info on setting parameters in route
Add info on setting parameters in route
JavaScript
apache-2.0
XanderPSON/febrezehackathon,XanderPSON/febrezehackathon
992c7b2c2cc3f73eaef974a5c885da6fe27ebd6c
index.js
index.js
module.exports = { handlebars: require('./lib/handlebars'), marked: require('./lib/marked'), componentTemplate: 'node_modules/foundation-docs/templates/component.html', handlebarsHelpers: 'node_modules/foundation-docs/helpers/' }
var path = require('path'); var TEMPLATE_PATH = path.join(__dirname, 'templates/component.html'); var HELPERS_PATH = path.join(__dirname, 'helpers'); module.exports = { handlebars: require('./lib/handlebars'), marked: require('./lib/marked'), componentTemplate: path.relative(process.cwd(), TEMPLATE_PATH), handlebarsHelpers: path.relative(process.cwd(), HELPERS_PATH) }
Use relative paths for componentTemplate and handlebarsHelpers paths
Use relative paths for componentTemplate and handlebarsHelpers paths
JavaScript
mit
zurb/foundation-docs,zurb/foundation-docs
d60976582c1c4f8035a41e59c36489f5fbe95be1
index.js
index.js
var Map = require('./lib/map'), Format = require('./lib/format'), safe64 = require('./lib/safe64'); module.exports = { Map: Map, Format: Format, safe64: safe64, pool: function(datasource) { return { create: function(callback) { var resource = new Map(datasource); resource.initialize(function(err) { if (err) throw err; callback(resource); }); }, destroy: function(resource) { resource.destroy(); } }; }, serve: function(resource, options, callback) { resource.render(options, callback); } };
var Map = require('./lib/map'), Format = require('./lib/format'), safe64 = require('./lib/safe64'); module.exports = { Map: Map, Format: Format, safe64: safe64, pool: function(datasource) { return { create: function(callback) { var resource = new Map(datasource); resource.initialize(function(err) { callback(err, resource); }); }, destroy: function(resource) { resource.destroy(); } }; }, serve: function(resource, options, callback) { resource.render(options, callback); } };
Update tilelive pool factory create method to pass errors.
Update tilelive pool factory create method to pass errors.
JavaScript
bsd-3-clause
dshorthouse/tilelive-mapnik,CartoDB/tilelive-mapnik,mapbox/tilelive-mapnik,tomhughes/tilelive-mapnik,wsw0108/tilesource-mapnik
93d89dfef836e493dc2a13b18ff08ee6b020cc91
index.js
index.js
"use strict"; const util = require("gulp-util"); const through = require("through2"); const moment = require("moment"); module.exports = function(options) { options = options || {}; function updateDate(file, options) { const now = moment().format("YYYY/MM/DD"), regex = /Last updated: (\d{4}\/\d{2}\/\d{2})/i, prev = regex.exec(file)[1]; if (options.log) { util.log( `${util.colors.cyan("[gulp-update-humanstxt-date]")} ` + `Found the previous date to be: ${util.colors.red(prev)}. ` + `Replacing with ${util.colors.green(now)}.` ); } file = file.replace(prev, now); return file; } return through.obj(function(file, enc, cb) { if (file.isNull()) { cb(null, file); return; } if (file.isStream()) { cb(new util.PluginError("gulp-update-humanstxt-date", "Streaming not supported")); return; } try { file.contents = new Buffer(updateDate(file.contents.toString(), options)); this.push(file); } catch (err) { this.emit("error", new util.PluginError("gulp-update-humanstxt-date", err)); } cb(); }); };
"use strict"; const util = require("gulp-util"); const through = require("through2"); const moment = require("moment"); module.exports = function(options) { options = options || {}; function updateDate(file, options) { const now = moment().format("YYYY/MM/DD"), regex = /Last updated?: ?(\d{4}\/\d{2}\/\d{2})/i, prev = regex.exec(file)[1]; if (options.log) { util.log( `${util.colors.cyan("[gulp-update-humanstxt-date]")} ` + `Found the previous date to be: ${util.colors.red(prev)}. ` + `Replacing with ${util.colors.green(now)}.` ); } file = file.replace(prev, now); return file; } return through.obj(function(file, enc, cb) { if (file.isNull()) { cb(null, file); return; } if (file.isStream()) { cb(new util.PluginError("gulp-update-humanstxt-date", "Streaming not supported")); return; } try { file.contents = new Buffer(updateDate(file.contents.toString(), options)); this.push(file); } catch (err) { this.emit("error", new util.PluginError("gulp-update-humanstxt-date", err)); } cb(); }); };
Make the 'd' in 'updated' optional along with the space before the date
Make the 'd' in 'updated' optional along with the space before the date
JavaScript
mit
Pinjasaur/gulp-update-humanstxt-date
3e0998496283eb83b66f97d765e069a470f3ba5d
index.js
index.js
'use strict'; module.exports = { name: 'live-reload-middleware', serverMiddleware: function(options) { var app = options.app; options = options.options; if (options.liveReload === true) { var livereloadMiddleware = require('connect-livereload'); app.use(livereloadMiddleware({ port: options.liveReloadPort })); } } };
'use strict'; module.exports = { name: 'live-reload-middleware', serverMiddleware: function(options) { var app = options.app; options = options.options; if (options.liveReload === true) { var livereloadMiddleware = require('connect-livereload'); app.use(livereloadMiddleware({ ignore: [ /\.js(?:\?.*)?$/, /\.css(?:\?.*)$/, /\.svg(?:\?.*)$/, /\.ico(?:\?.*)$/, /\.woff(?:\?.*)$/, /\.png(?:\?.*)$/, /\.jpg(?:\?.*)$/, /\.jpeg(?:\?.*)$/, /\.ttf(?:\?.*)$/ ], port: options.liveReloadPort })); } } };
Fix ignore list to work with query string params.
Fix ignore list to work with query string params.
JavaScript
mit
jbescoyez/ember-cli-inject-live-reload,rwjblue/ember-cli-inject-live-reload,scottkidder/ember-cli-inject-live-reload
688146ec463c255b6000ce72a4462dff1a99cb3c
gatsby-browser.js
gatsby-browser.js
import ReactGA from 'react-ga' import {config} from 'config' ReactGA.initialize(config.googleAnalyticsId); exports.onRouteUpdate = (state, page, pages) => { ReactGA.pageview(state.pathname); };
import ReactGA from 'react-ga' import {config} from 'config' ReactGA.initialize(config.googleAnalyticsId); ReactGA.plugin.require('linkid'); exports.onRouteUpdate = (state, page, pages) => { ReactGA.pageview(state.pathname); };
Add linkid to google analytics
Add linkid to google analytics
JavaScript
bsd-3-clause
tadeuzagallo/blog,tadeuzagallo/blog
8f82186dfb27825a7b2220f9a6c3f66346f0f300
worker/web_client/JobStatus.js
worker/web_client/JobStatus.js
import JobStatus from 'girder_plugins/jobs/JobStatus'; JobStatus.registerStatus({ WORKER_FETCHING_INPUT: { value: 820, text: 'Fetching input', icon: 'icon-download', color: '#89d2e2' }, WORKER_CONVERTING_INPUT: { value: 821, text: 'Converting input', icon: 'icon-shuffle', color: '#92f5b5' }, WORKER_CONVERTING_OUTPUT: { value: 822, text: 'Converting output', icon: 'icon-shuffle', color: '#92f5b5' }, WORKER_PUSHING_OUTPUT: { value: 823, text: 'Pushing output', icon: 'icon-upload', color: '#89d2e2' } });
import JobStatus from 'girder_plugins/jobs/JobStatus'; JobStatus.registerStatus({ WORKER_FETCHING_INPUT: { value: 820, text: 'Fetching input', icon: 'icon-download', color: '#89d2e2' }, WORKER_CONVERTING_INPUT: { value: 821, text: 'Converting input', icon: 'icon-shuffle', color: '#92f5b5' }, WORKER_CONVERTING_OUTPUT: { value: 822, text: 'Converting output', icon: 'icon-shuffle', color: '#92f5b5' }, WORKER_PUSHING_OUTPUT: { value: 823, text: 'Pushing output', icon: 'icon-upload', color: '#89d2e2' }, WORKER_CANCELING: { value: 824, text: 'Canceling', icon: 'icon-cancel', color: '#f89406' } });
Add button to cancel job
WIP: Add button to cancel job
JavaScript
apache-2.0
girder/girder_worker,girder/girder_worker,girder/girder_worker
2e8c529dee0385daf201ecb5fca2e1d4b69d9376
jest-setup.js
jest-setup.js
import Enzyme from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; // Configure Enzyme Enzyme.configure({ adapter: new Adapter() }); // Add RAF for React 16 global.requestAnimationFrame = function requestAnimationFrame(callback) { setTimeout(callback, 0); };
const Enzyme = require('enzyme'); const Adapter = require('enzyme-adapter-react-16'); // Configure Enzyme Enzyme.configure({ adapter: new Adapter() }); // Add RAF for React 16 global.requestAnimationFrame = function requestAnimationFrame(callback) { setTimeout(callback, 0); };
Use require() instead of import().
Use require() instead of import().
JavaScript
mit
milesj/build-tool-config,milesj/build-tool-config,milesj/build-tool-config
441dd784316cf734126b0ca95116070bd6147189
js/components.js
js/components.js
class SearchBox extends React.Component { // constructor(){ // super(); // this.state = { // searched:false; // }; // } render() { return ( <div> CLICK AND HIT ENTER TO SEARCH <form className="search-form" onSubmit={this._handleSubmit.bind(this)}> <input placeholder="search something" ref={input => this._search = input}/> <button type="submit">SEARCH HERE</button> </form> </div> ); } _handleSubmit(event) { event.preventDefault(); let search = this._search.value; let parameters = '?action=opensearch&limit=10&namespace=0&format=json&search=' var cb = '&callback=JSON_CALLBACK'; let url = 'https://en.wikipedia.org/w/api.php'+parameters+search+cb // console.log(url); $.getJSON(url); } } class SearchContainer extends React.Component { // constructor(){ // super(); // this.state = { // searches:{}; // }; // } // render() { // return ( // <div> // {searches.map(search => // <h1></h1> // <p></p> // )} // // </div> // ) // } } ReactDOM.render( <SearchBox />, document.getElementById('mainDiv') );
Write first component and start first API call
Write first component and start first API call
JavaScript
mit
scottychou/WikipediaViewer,scottychou/WikipediaViewer
a1e21bd2df72b0bfd54d2d5ecdab766d6390f785
packages/core/lib/commands/db/commands/serve.js
packages/core/lib/commands/db/commands/serve.js
const command = { command: "serve", description: "Start Truffle's GraphQL UI playground", builder: {}, help: { usage: "truffle db serve", options: [] }, /* This command does starts an express derived server that invokes * `process.exit()` on SIGINT. As a result there is no need to invoke * truffle's own `process.exit()` which is triggered by invoking the `done` * callback. * * Todo: blacklist this command for REPLs */ run: async function(argv) { const Config = require("@truffle/config"); const { playgroundServer } = require("truffle-db"); const config = Config.detect(argv); const port = (config.db && config.db.PORT) || 4444; const { url } = await playgroundServer(config).listen({ port }); console.log(`🚀 Playground listening at ${url}`); console.log(`ℹ Press Ctrl-C to exit`); } }; module.exports = command;
const command = { command: "serve", description: "Start Truffle's GraphQL UI playground", builder: {}, help: { usage: "truffle db serve", options: [] }, /* This command does starts an express derived server that invokes * `process.exit()` on SIGINT. As a result there is no need to invoke * truffle's own `process.exit()` which is triggered by invoking the `done` * callback. * * Todo: blacklist this command for REPLs */ run: async function(argv) { const Config = require("@truffle/config"); const { playgroundServer } = require("truffle-db"); const config = Config.detect(argv); const port = (config.db && config.db.port) || 4444; const { url } = await playgroundServer(config).listen({ port }); console.log(`🚀 Playground listening at ${url}`); console.log(`ℹ Press Ctrl-C to exit`); } }; module.exports = command;
Make the port attribute lowercase
Make the port attribute lowercase ``` // truffle-config.js { // ... db: { port: 69420 } } ```
JavaScript
mit
ConsenSys/truffle
b0ae69002cb6b5e9b3a2e7bee82c5fea1cd6677f
client/index.js
client/index.js
import React from 'react' import ReactDOM from 'react-dom' import { AppContainer } from 'react-hot-loader' import App from './containers/App' ReactDOM.render( <AppContainer> <App/> </AppContainer>, document.getElementById('root') ) if (module.hot) { module.hot.accept('./containers/App', () => { // If you use Webpack 2 in ES modules mode, you can // use <App /> here rather than require() a <NextApp />. const NextApp = require('./containers/App').default ReactDOM.render( <AppContainer> <NextApp/> </AppContainer>, document.getElementById('root') ) }) }
import React from 'react' import ReactDOM from 'react-dom' import { AppContainer } from 'react-hot-loader' import App from './containers/App' ReactDOM.render( <AppContainer> <App/> </AppContainer>, document.getElementById('root') ) if (module.hot) { module.hot.accept('./containers/App', () => { // If you use Webpack 2 in ES modules mode, you can // use <App /> here rather than require() a <NextApp />. const NextApp = require('./containers/App').default ReactDOM.render( <AppContainer> <NextApp/> </AppContainer>, document.getElementById('root') ) }) }
Add line break at end of file
Add line break at end of file
JavaScript
mit
shinosakarb/tebukuro-client
6cacd255d4c963af7454da36656926f213b676f8
client/index.js
client/index.js
require('jquery') require('expose?$!expose?jQuery!jquery') require("bootstrap-webpack") require('./less/index.less')
require('jquery') require('expose?$!expose?jQuery!jquery') require("bootstrap-webpack") require('./less/index.less') $.get('http://10.90.100.1:8080/signalk/v1/api/vessels/self/navigation/position') .then(res => $.get(`http://www.tuuleeko.fi:8000/nearest-station?lat=${res.latitude}&lon=${res.longitude}`)) .then(station => { $.get(`http://www.tuuleeko.fi:8000/observations?geoid=${station.geoid}`) .then(stationObservations => { var obs = stationObservations.observations[stationObservations.observations.length - 1] var forecastHtml = ` <h3>${stationObservations.name} (${(station.distanceMeters / 1000).toFixed(1)} km)</h3> <table class='table'> <tr><th>Wind direction</th><th>Wind speed</th><th>Wind gusts</th></tr> <tr><td>${obs.windDir}°</td><td>${obs.windSpeedMs} m/s</td><td>${obs.windGustMs} m/s</td></tr> </table>` $('body').append(forecastHtml) }) })
Add POC for showing the closes weather observation data
Add POC for showing the closes weather observation data
JavaScript
apache-2.0
chacal/nrf-sensor-receiver,chacal/nrf-sensor-receiver,chacal/nrf-sensor-receiver
b5e2e552814b00858fce4fa844d326e6b3d81bc0
src/index.js
src/index.js
import * as path from 'path'; import {fs} from 'node-promise-es6'; import * as fse from 'fs-extra-promise-es6'; export default class { constructor(basePath) { this.basePath = path.resolve(basePath); } async create() { await fse.mkdirs(this.basePath); } path(...components) { return path.resolve(this.basePath, ...components); } async remove() { await fse.remove(this.path()); } async write(files) { for (const file of Object.keys(files)) { const filePath = this.path(file); const fileContents = files[file]; await fse.ensureFile(filePath); if (typeof fileContents === 'object') { await fse.writeJson(filePath, fileContents); } else { const reindentedFileContents = fileContents .split('\n') .filter((line, index, array) => index !== 0 && index !== array.length - 1 || line.trim() !== '') .reduce(({indentation, contents}, line) => { const whitespaceToRemove = Number.isInteger(indentation) ? indentation : line.match(/^\s*/)[0].length; return { indentation: whitespaceToRemove, contents: `${contents}${line.slice(whitespaceToRemove)}\n` }; }, {contents: ''}).contents; await fs.writeFile(filePath, reindentedFileContents); } } } }
import * as path from 'path'; import {fs} from 'node-promise-es6'; import * as fse from 'fs-extra-promise-es6'; export default class { constructor(basePath) { this.basePath = path.resolve(basePath); } async create() { await fse.mkdirs(this.basePath); } path(...components) { return path.resolve(this.basePath, ...components); } async remove() { await fse.remove(this.path()); } async write(files) { for (const [filePath, fileContents] of Object.entries(files)) { const absoluteFilePath = this.path(filePath); await fse.ensureFile(absoluteFilePath); if (typeof fileContents === 'object') { await fse.writeJson(absoluteFilePath, fileContents); } else { const reindentedFileContents = fileContents .split('\n') .filter((line, index, array) => index !== 0 && index !== array.length - 1 || line.trim() !== '') .reduce(({indentation, contents}, line) => { const whitespaceToRemove = Number.isInteger(indentation) ? indentation : line.match(/^\s*/)[0].length; return { indentation: whitespaceToRemove, contents: `${contents}${line.slice(whitespaceToRemove)}\n` }; }, {contents: ''}).contents; await fs.writeFile(absoluteFilePath, reindentedFileContents); } } } }
Use Object.entries instead of Object.keys
Use Object.entries instead of Object.keys
JavaScript
mit
vinsonchuong/directory-helpers
c9e44c6d990f95bb7e92bfa97fc0a74bf636c290
app/templates/tasks/utils/notify-style-lint.js
app/templates/tasks/utils/notify-style-lint.js
var notify = require("./notify"); module.exports = function notifyStyleLint (stdout) { var messages = stdout.split("\n"); messages.pop(); // Remove last empty new message. if(0 < messages.length) { var message = "{{length}} lint warning(s) found.".replace(/{{length}}/g, messages.length); notify.showNotification({ subtitle: "Task style:lint", message: message, appIcon: notify.appIcon.sass }); } };
var notify = require("./notify"); var util = require("util"); module.exports = function notifyStyleLint (stdout) { var messages = stdout.split("\n"); messages.pop(); // Remove last empty new message. if(0 < messages.length) { var message = util.format("%d lint warning(s) found.", messages.length); notify.showNotification({ subtitle: "Task style:lint", message: message, appIcon: notify.appIcon.sass }); } };
Use built-in utils to format the string.
Use built-in utils to format the string.
JavaScript
mit
rishabhsrao/generator-ironhide-webapp,rishabhsrao/generator-ironhide-webapp,rishabhsrao/generator-ironhide-webapp
b656897309110504fbc52e2c2048ed5dc3d17e23
js/sinbad-app.js
js/sinbad-app.js
appRun(); function appRun() { $(document).ready(function() { console.log("READY"); $(".loading").hide(); $(".complete").show(); //PAGE SWIPES $(document).on('pageinit', function(event){ $('.pages').on("swipeleft", function () { var nextpage = $(this).next('div[data-role="page"]'); if (nextpage.length > 0) { $.mobile.changePage(nextpage, {transition: "slide", changeHash:false }); } }); $('.pages').on("swiperight", function () { var prevpage = $(this).prev('div[data-role="page"]'); if (prevpage.length > 0) { $.mobile.changePage(prevpage, { transition: "slide", reverse: true, changeHash: false }); } }); }); }); }
appRun(); function appRun() { $(document).ready(function() { console.log("READY"); $(".loading").hide(); $(".complete").show(); //PAGE SWIPES $(document).on('pageinit', function(event){ $('.pages').on("swipeleft", function () { var nextpage = $(this).next('div[data-role="page"]'); if (nextpage.length > 0) { $.mobile.changePage(nextpage, {transition: "slide", changeHash:false }); } }); $('.pages').on("swiperight", function () { var prevpage = $(this).prev('div[data-role="page"]'); if (prevpage.length > 0) { $.mobile.changePage(prevpage, { transition: "slide", reverse: true, changeHash: false }); } }); }); //DRAG AND DROP //initialize dragging $("#watercolor").draggable( { revert: true, cursor: 'move', } ); $("#leaves").draggable( { revert: true, cursor: 'move', } ); $("#bubbles").draggable( { revert: true, cursor: 'move', } ); //initialize droppable callback $("#spritesheet").droppable({ tolerance: "pointer", drop: sinbadChange }); console.log("before droppable"); //event handler for drop event function sinbadChange(event, ui) { var currentBrush = ui.draggable.attr('id'); console.log(currentBrush); console.log("in droppable"); if (currentBrush == "watercolor") { $("#spritesheet").removeClass(); $("#spritesheet").addClass("brushfish"); console.log("DROPPED"); } else if (currentBrush == "leaves") { $("#spritesheet").removeClass(); $("#spritesheet").addClass("leaffish"); console.log("DROPPED LEAF"); } else if (currentBrush == "bubbles") { $("#spritesheet").removeClass(); $("#spritesheet").addClass("bubblefish"); console.log("DROPPED BUBBLE"); } else { $("#spritesheet").removeClass(); $("#spritesheet").addClass("plainfish"); } } // //add listener to drop event // $("spritesheet").on("drop", function(event, ui) { // }) }); //end jquery } //end appRun
Add jquery UI drag/drop functionality
Add jquery UI drag/drop functionality
JavaScript
mit
andkerel/sinbad-and-the-phonegap,andkerel/sinbad-and-the-phonegap
0cb6a403de01d6dd60750ac1cc337d1c8f10177b
src/index.js
src/index.js
// @flow const promiseBindMiddleware = ( { dispatch } : { dispatch : Function }, ) => (next: Function) => (action: Object) => { if (action && action.promise && typeof action.promise === 'function') { const { type, metadata, promise, promiseArg } = action dispatch({ type: `${type}_START`, metadata, }) return promise(...(Array.isArray(promiseArg) ? promiseArg : [promiseArg])) .then((data) => { dispatch({ type: `${type}_SUCCESS`, payload: data, metadata, }) return data }, (ex) => { dispatch({ type: `${type}_ERROR`, payload: ex, metadata, }) return ex }) } return next(action) } export default promiseBindMiddleware
// @flow const extendBy = (object: Object, { metadata } : { metadata : any }) => { if (metadata) return { ...object, metadata } return object } const promiseBindMiddleware = ( { dispatch } : { dispatch : Function }, ) => (next: Function) => (action: Object) => { if (action && action.promise && typeof action.promise === 'function') { const { type, metadata, promise, promiseArg } = action dispatch(extendBy({ type: `${type}_START`, }, { metadata })) return promise(...(Array.isArray(promiseArg) ? promiseArg : [promiseArg])) .then((data) => { dispatch(extendBy({ type: `${type}_SUCCESS`, payload: data, }, { metadata })) return data }, (ex) => { dispatch(extendBy({ type: `${type}_ERROR`, payload: ex, }, { metadata })) // TODO change to throw an error return ex }) } return next(action) } export default promiseBindMiddleware
Add meted only if exist
Add meted only if exist
JavaScript
mit
machnicki/redux-promise-bind
a549e6988de5071dbbf397c5fd1f894f5ad0a8f7
assets/js/util/tracking/createDataLayerPush.js
assets/js/util/tracking/createDataLayerPush.js
/** * Internal dependencies */ import { DATA_LAYER } from './index.private'; /** * Returns a function which, when invoked will initialize the dataLayer and push data onto it. * * @param {Object} target Object to enhance with dataLayer data. * @return {Function} Function that pushes data onto the dataLayer. */ export default function createDataLayerPush( target ) { /** * Pushes data onto the data layer. * * @param {...any} args Arguments to push onto the data layer. */ return function dataLayerPush( ...args ) { target[ DATA_LAYER ] = target[ DATA_LAYER ] || []; target[ DATA_LAYER ].push( args ); }; }
/** * Internal dependencies */ import { DATA_LAYER } from './index.private'; /** * Returns a function which, when invoked will initialize the dataLayer and push data onto it. * * @param {Object} target Object to enhance with dataLayer data. * @return {Function} Function that pushes data onto the dataLayer. */ export default function createDataLayerPush( target ) { /** * Pushes data onto the data layer. * Must use `arguments` internally. */ return function dataLayerPush() { target[ DATA_LAYER ] = target[ DATA_LAYER ] || []; target[ DATA_LAYER ].push( arguments ); }; }
Refactor dataLayerPush to use func.arguments.
Refactor dataLayerPush to use func.arguments.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
f6cb55ec87878fdd2849dc4ba5ea6bd19b6c96c0
Analyser/src/Models/FnModels.js
Analyser/src/Models/FnModels.js
export default function(state, ctx, model, helpers) { const ConcretizeIfNative = helpers.ConcretizeIfNative; //TODO: Test IsNative for apply, bind & call model.add(Function.prototype.apply, ConcretizeIfNative(Function.prototype.apply)); model.add(Function.prototype.call, ConcretizeIfNative(Function.prototype.call)); model.add(Function.prototype.bind, ConcretizeIfNative(Function.prototype.bind)); model.add(Object.prototype.hasOwnProperty, function(base, args) { for (let i = 0; i < args.length; i++) { args[i] = state.getConcrete(args[i]); } Function.prototype.hasOwnProperty.apply(state.getConcrete(base), args); }); model.add(Object.prototype.keys, function(base, args) { for (let i = 0; i < args.length; i++) { args[i] = state.getConcrete(args[i]); } return Object.prototype.keys.apply(this.getConcrete(base), args); }); model.add(console.log, function(base, args) { for (let i = 0; i < args.length; i++) { args[i] = state.getConcrete(args[i]); } console.log.apply(base, args); }); }
export default function(state, ctx, model, helpers) { const ConcretizeIfNative = helpers.ConcretizeIfNative; //TODO: Test IsNative for apply, bind & call model.add(Function.prototype.apply, ConcretizeIfNative(Function.prototype.apply)); model.add(Function.prototype.call, ConcretizeIfNative(Function.prototype.call)); model.add(Function.prototype.bind, ConcretizeIfNative(Function.prototype.bind)); model.add(Object.prototype.hasOwnProperty, function(base, args) { for (let i = 0; i < args.length; i++) { args[i] = state.getConcrete(args[i]); } Function.prototype.hasOwnProperty.apply(state.getConcrete(base), args); }); model.add(Object.prototype.keys, function(base, args) { for (let i = 0; i < args.length; i++) { args[i] = state.getConcrete(args[i]); } return Object.prototype.keys.apply(this.getConcrete(base), args); }); model.add(Object.assign, (base, args) => { return Object.assign.call(base, this.getConcrete(args[0]), this.getConcrete(args[1])); }); model.add(console.log, function(base, args) { for (let i = 0; i < args.length; i++) { args[i] = state.getConcrete(args[i]); } console.log.apply(base, args); }); }
Add a model for Object.assign
Add a model for Object.assign
JavaScript
mit
ExpoSEJS/ExpoSE,ExpoSEJS/ExpoSE,ExpoSEJS/ExpoSE