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
bb7dc88b6bdb324dfc2feb627a86d1125e8d51a4
test/javascripts/unit/hide_department_children_test.js
test/javascripts/unit/hide_department_children_test.js
module("Hide department children", { setup: function() { this.$departments = $( '<div class="js-hide-department-children">' + '<div class="department">' + '<div class="child-organisations">' + '<p>child content</p>' + '</div>' + '</div>' + '</div>'); $('#qunit-fixture').append(this.$departments); } }); test("should create toggle link before department list", function() { GOVUK.hideDepartmentChildren.init(); equals(this.$departments.find('.view-all').length, 1); console.log(this.$departments.html()); }); test("should toggle class when clicking view all link", function() { GOVUK.hideDepartmentChildren.init(); ok(this.$departments.find('.department').hasClass('js-hiding-children')); this.$departments.find('.view-all').click(); ok(!this.$departments.find('.department').hasClass('js-hiding-children')); });
module("Hide department children", { setup: function() { this.$departments = $( '<div class="js-hide-department-children">' + '<div class="department">' + '<div class="child-organisations">' + '<p>child content</p>' + '</div>' + '</div>' + '</div>'); $('#qunit-fixture').append(this.$departments); } }); test("should create toggle link before department list", function() { GOVUK.hideDepartmentChildren.init(); equals(this.$departments.find('.view-all').length, 1); }); test("should toggle class when clicking view all link", function() { GOVUK.hideDepartmentChildren.init(); ok(this.$departments.find('.department').hasClass('js-hiding-children')); this.$departments.find('.view-all').click(); ok(!this.$departments.find('.department').hasClass('js-hiding-children')); });
Remove left over console log
Remove left over console log
JavaScript
mit
robinwhittleton/whitehall,askl56/whitehall,hotvulcan/whitehall,askl56/whitehall,YOTOV-LIMITED/whitehall,YOTOV-LIMITED/whitehall,ggoral/whitehall,alphagov/whitehall,hotvulcan/whitehall,ggoral/whitehall,alphagov/whitehall,askl56/whitehall,alphagov/whitehall,YOTOV-LIMITED/whitehall,robinwhittleton/whitehall,robinwhittleton/whitehall,ggoral/whitehall,YOTOV-LIMITED/whitehall,hotvulcan/whitehall,ggoral/whitehall,alphagov/whitehall,robinwhittleton/whitehall,hotvulcan/whitehall,askl56/whitehall
e28746346eb2439cf4f9fe3fbf02474cb39c65b6
testpilot/frontend/static-src/app/models/experiment.js
testpilot/frontend/static-src/app/models/experiment.js
import app from 'ampersand-app'; import Model from 'ampersand-model'; import querystring from 'querystring'; export default Model.extend({ urlRoot: '/api/experiments', extraProperties: 'allow', props: { enabled: {type: 'boolean', default: false} }, // This shouldn't be necessary; see comments in collections/experiments.js ajaxConfig: { headers: { 'Accept': 'application/json' }}, // TODO(DJ): this will be removed when we start tracking // install state through the User Installation model. // https://github.com/mozilla/testpilot/issues/195 initialize() { app.on('addon-install:install-ended', addon => { if (addon.id === this.id) { this.enabled = true; } }); app.on('addon-uninstall:uninstall-ended', addon => { if (addon.id === this.id) { this.enabled = false; } }); }, buildSurveyURL(ref) { const installed = Object.keys(app.me.installed); const queryParams = querystring.stringify({ ref: ref, experiment: this.title, installed: installed }); return `${this.survey_url}?${queryParams}`; } });
import app from 'ampersand-app'; import Model from 'ampersand-model'; import querystring from 'querystring'; export default Model.extend({ urlRoot: '/api/experiments', extraProperties: 'allow', props: { enabled: {type: 'boolean', default: false} }, // This shouldn't be necessary; see comments in collections/experiments.js ajaxConfig: { headers: { 'Accept': 'application/json' }}, // TODO(DJ): this will be removed when we start tracking // install state through the User Installation model. // https://github.com/mozilla/testpilot/issues/195 initialize() { app.on('addon-install:install-ended', addon => { if (addon.id === this.id) { this.enabled = true; } }); app.on('addon-uninstall:uninstall-ended', addon => { if (addon.id === this.id) { this.enabled = false; } }); }, buildSurveyURL(ref) { const queryParams = querystring.stringify({ ref: ref, experiment: this.title, installed: app.me.installed ? Object.keys(app.me.installed) : [] }); return `${this.survey_url}?${queryParams}`; } });
Fix fail on Object.keys(app.me.installed) which was holding up page loads.
Fix fail on Object.keys(app.me.installed) which was holding up page loads. - fixes #964
JavaScript
mpl-2.0
ckprice/testpilot,lmorchard/testpilot,lmorchard/testpilot,lmorchard/idea-town-server,lmorchard/testpilot,mozilla/idea-town,lmorchard/idea-town,meandavejustice/testpilot,fzzzy/testpilot,dannycoates/testpilot,mozilla/idea-town,fzzzy/testpilot,clouserw/testpilot,mathjazz/testpilot,mathjazz/testpilot,6a68/testpilot,flodolo/testpilot,mathjazz/testpilot,lmorchard/idea-town-server,flodolo/testpilot,mozilla/idea-town-server,ckprice/testpilot,flodolo/testpilot,6a68/testpilot,clouserw/testpilot,meandavejustice/testpilot,fzzzy/testpilot,mozilla/testpilot,6a68/idea-town,mozilla/testpilot,ckprice/testpilot,chuckharmston/testpilot,6a68/testpilot,meandavejustice/testpilot,clouserw/testpilot,mozilla/testpilot,meandavejustice/testpilot,mozilla/idea-town,lmorchard/idea-town,chuckharmston/testpilot,mozilla/idea-town,6a68/idea-town,dannycoates/testpilot,6a68/idea-town,clouserw/testpilot,dannycoates/testpilot,6a68/testpilot,mozilla/idea-town-server,lmorchard/idea-town,ckprice/testpilot,chuckharmston/testpilot,6a68/idea-town,mozilla/testpilot,lmorchard/testpilot,dannycoates/testpilot,chuckharmston/testpilot,mozilla/idea-town-server,flodolo/testpilot,fzzzy/testpilot,mathjazz/testpilot,mozilla/idea-town-server,lmorchard/idea-town-server,lmorchard/idea-town,lmorchard/idea-town-server
b1d751400723877c47e7c9fa4eddf8012fedee9d
js/devtools.js
js/devtools.js
// Script executed every time the devtools are opened. // custom panel chrome.devtools.panels.create("Backbone Debugger", "img/panel.png", "panel.html"); // custom sidebar pane in the elements panel chrome.devtools.panels.elements.createSidebarPane("Backbone Debugger", function(sidebar) { chrome.devtools.panels.elements.onSelectionChanged.addListener(function() { sidebar.setHeight("35px"); sidebar.setPage("elementsSidebar.html"); }); });
// Script executed every time the devtools are opened. // custom panel chrome.devtools.panels.create("Backbone", "img/panel.png", "panel.html"); // custom sidebar pane in the elements panel chrome.devtools.panels.elements.createSidebarPane("Backbone", function(sidebar) { chrome.devtools.panels.elements.onSelectionChanged.addListener(function() { sidebar.setHeight("35px"); sidebar.setPage("elementsSidebar.html"); }); });
Change the name of Panel and Elements sidebar pane to 'Backbone'
Change the name of Panel and Elements sidebar pane to 'Backbone'
JavaScript
mpl-2.0
Maluen/Backbone-Debugger,jbreeden/Backbone-Debugger,Maluen/Backbone-Debugger,jbreeden/Backbone-Debugger
1bba0e18bc7221580308890087a5334c0122ebf7
app.js
app.js
// Problem: We need a simple way to look at a user's badge count and JavaScript point from a web browser // Solution: Use Node.js to perform the profile look ups and server our template via HTTP // 1. Create a web server var http = require('http'); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.write('This is before the end\n'); response.end('Hello World\n'); }).listen(3000); console.log('Server is running on port 3000'); // 2. Handle HTTP route GET / and POST / i.e. Home // if url == "/" && GET // show search // if url == "/" && POST // redirect to /:username // 3. Handle HTTP route GET /:username i.e. /chalkers // if url == "/...." // get json from Treehouse // on "end" // show profile // on "error" // show error // 4. Function that handles the reading of files and merge in value. // read from file and get a string // merge values in to string
// Problem: We need a simple way to look at a user's badge count and JavaScript point from a web browser // Solution: Use Node.js to perform the profile look ups and server our template via HTTP // 1. Create a web server var http = require('http'); http.createServer(function (request, response) { homeRoute(request, response); }).listen(3000); console.log('Server is running on port 3000'); // 2. Handle HTTP route GET / and POST / i.e. Home function homeRoute(request, response) { // if url == "/" && GET if (request.url === "/") { // show search response.writeHead(200, {'Content-Type': 'text/plain'}); response.write('Header\n'); response.write('Search\n'); response.end('Footer\n'); } // if url == "/" && POST // redirect to /:username } // 3. Handle HTTP route GET /:username i.e. /chalkers // if url == "/...." // get json from Treehouse // on "end" // show profile // on "error" // show error // 4. Function that handles the reading of files and merge in value. // read from file and get a string // merge values in to string
Create Web Server & Handle route GET and POST
Create Web Server & Handle route GET and POST
JavaScript
apache-2.0
JordanPortfolio/NodeJS-temp,JordanPortfolio/NodeJS-temp
3e6db5efd2d25ab673f8c77734ecb9b4de924588
app.js
app.js
var express = require('express'); var bunyan = require('bunyan'); var log = bunyan.createLogger({ name: 'app' }); var app = express(); var webhooks = require('datashaman-webhooks'); webhooks.boot(app, 'somesecret'); app.post('/', webhooks.router(function(req, res, event) { log.info(req.body, event); switch (event) { case 'ping': res.send('Ping'); } })); app.listen(8080);
var express = require('express'); var bunyan = require('bunyan'); var log = bunyan.createLogger({ name: 'app' }); var app = express(); var webhooks = require('datashaman-webhooks'); webhooks.boot(app, 'somesecret'); app.post('/', webhooks.router(function(req, res, event) { log.info(req.body, event); switch (event) { case 'ping': res.send('Ping'); break; default: res.send('Unhandled event: ' + event); } })); app.listen(8080);
Add default case to example file
Add default case to example file
JavaScript
mit
datashaman/datashaman-webhooks
12bfc0b76c17b34baf779bc8debfa6fadb312890
server/db/models/userModel.js
server/db/models/userModel.js
const Sequelize = require('sequelize'); const db = require('../db.js'); const Users = db.define('users', { id: { type: Sequelize.UUID, defaultValue: Sequelize.UUIDV1, primaryKey: true, }, facebook_id: { type: Sequelize.STRING, }, first_name: { type: Sequelize.STRING, }, last_name: { type: Sequelize.STRING, }, photo_url: { type: Sequelize.STRING, }, description: { type: Sequelize.STRING(256), defaultValue: 'Click here to edit!', }, // would like to add counter cache for request count and connection count }, { freezeTableName: true, } ); module.exports = Users;
const Sequelize = require('sequelize'); const db = require('../db.js'); const Users = db.define('users', { id: { type: Sequelize.UUID, defaultValue: Sequelize.UUIDV1, primaryKey: true, }, facebook_id: { type: Sequelize.STRING, }, first_name: { type: Sequelize.STRING, }, last_name: { type: Sequelize.STRING, }, photo_url: { type: Sequelize.STRING, }, description: { type: Sequelize.STRING(256), }, // would like to add counter cache for request count and connection count }, { freezeTableName: true, } ); module.exports = Users;
Remove default description on user model
Remove default description on user model
JavaScript
mit
VictoriousResistance/iDioma,VictoriousResistance/iDioma
bc07195fadc3d654a02917947e0dac2feb43e0bc
services/permissions/model.js
services/permissions/model.js
'use strict' const mongoose = require('mongoose') const PermissionSchema = new mongoose.Schema({ regex: { type: String, required: true, unique: true }, roles: { type: [ String ], required: true }, dateCreated: { type: Date, default: Date.now } }) PermissionSchema.statics.findMatches = function (email, cb) { const collected = [] this.find({}, function (err, permissions) { if (err) cb(err) for (let i = 0; i < permissions.length; i++) { const regex = new RegExp(permissions[i].regex) if (email.search(regex) > -1) collected.push(permissions[i]) } cb(null, collected) }) } module.exports = mongoose.model('Permission', PermissionSchema)
'use strict' const mongoose = require('mongoose') const PermissionSchema = new mongoose.Schema({ regex: { type: Object, required: true, unique: true }, roles: { type: [ String ], required: true }, dateCreated: { type: Date, default: Date.now } }) PermissionSchema.statics.findMatches = function (email, cb) { this.find({}, (err, permissions) => { if (err) cb(err) // return only permissions whose regex match the email cb(null, permissions ? permissions.filter(permission => permission.regex.test(email)) : null) }) } PermissionSchema.path('regex').set(function (regex) { return regex instanceof RegExp ? regex : new RegExp(regex) }) module.exports = mongoose.model('Permission', PermissionSchema)
Save RegExp object to database instead of string, and more concise filter
Save RegExp object to database instead of string, and more concise filter
JavaScript
mit
thebitmill/midwest-membership-services
db04398e499a8725a0391e10d1955b7c805cb209
test/remove.js
test/remove.js
#!/usr/bin/env node 'use strict'; /** Load modules. */ var fs = require('fs'), path = require('path'); /** Resolve program params. */ var args = process.argv.slice(process.argv[0] === process.execPath ? 2 : 0), filePath = path.resolve(args[1]); var pattern = (function() { var result = args[0], delimiter = result.charAt(0), lastIndex = result.lastIndexOf(delimiter); return RegExp(result.slice(1, lastIndex), result.slice(lastIndex + 1)); }()); /** Used to match lines of code. */ var reLine = /.*/gm; /*----------------------------------------------------------------------------*/ fs.writeFileSync(filePath, fs.readFileSync(filePath, 'utf8').replace(pattern, function(match) { return match.replace(reLine, ''); }));
#!/usr/bin/env node 'use strict'; var fs = require('fs'), path = require('path'); var args = (args = process.argv) .slice((args[0] === process.execPath || args[0] === 'node') ? 2 : 0); var filePath = path.resolve(args[1]), reLine = /.*/gm, slice = Array.prototype.slice; var pattern = (function() { var result = args[0], delimiter = result.charAt(0), lastIndex = result.lastIndexOf(delimiter); return RegExp(result.slice(1, lastIndex), result.slice(lastIndex + 1)); }()); /*----------------------------------------------------------------------------*/ fs.writeFileSync(filePath, fs.readFileSync(filePath, 'utf8').replace(pattern, function(match) { var snippet = slice.call(arguments, -3, -1)[0]; return match.replace(snippet, snippet.replace(reLine, '')); }));
Add support for removing the last capture group.
Add support for removing the last capture group.
JavaScript
mit
rlugojr/lodash,msmorgan/lodash,beaugunderson/lodash,steelsojka/lodash,boneskull/lodash,msmorgan/lodash,steelsojka/lodash,rlugojr/lodash,beaugunderson/lodash,boneskull/lodash
1c26e7c754a77a6775ce7c8461dc6e47e856ebad
src/resources/assets/js/SparkKioskNotify/spark-kiosk-notify.js
src/resources/assets/js/SparkKioskNotify/spark-kiosk-notify.js
Vue.component('spark-kiosk-notify', { props: [ ], data() { return { 'notifications': [], 'users': [], 'newNotification': { "user_id": null } }; }, ready(){ this.getNotifications(); this.getUsers(); }, methods: { /** * Get all of the announcements. */ getNotifications: function(){ this.$http.get('/skn/notifications') .then(response => { this.notifications = response.data; }); }, /** * Get all of the users. */ getUsers: function(){ this.$http.get('/skn/users') .then(response => { this.users = response.data; }); }, /** * Create Notification. */ createNotification: function(){ this.$http.get('/skn/notifications/create', this.createNotification) .then(response => { this.createNotification = {}; this.getNotifications(); }); } } });
Vue.component('spark-kiosk-notify', { props: [ ], data() { return { 'notifications': [], 'users': [], 'newNotification': { "user_id": null } }; }, ready(){ this.getNotifications(); this.getUsers(); }, methods: { /** * Get all of the announcements. */ getNotifications: function(){ this.$http.get('/skn/notifications') .then(response => { this.notifications = response.data; }); }, /** * Get all of the users. */ getUsers: function(){ this.$http.get('/skn/users') .then(response => { this.users = response.data; }); }, /** * Create Notification. */ createNotification: function(){ this.$http.post('/skn/notifications/create', this.newNotification) .then(response => { this.newNotification = {}; this.getNotifications(); }); } } });
Change to 'newNotification', change to post
Change to 'newNotification', change to post
JavaScript
mit
vmitchell85/spark-kiosk-notify,vmitchell85/spark-kiosk-notify,vmitchell85/spark-kiosk-notify
2983df1c5a6363f1cdd827a9ac006ff71ddd259c
corehq/apps/domain/static/domain/js/case_search_main.js
corehq/apps/domain/static/domain/js/case_search_main.js
hqDefine('domain/js/case_search_main', [ 'jquery', 'hqwebapp/js/initial_page_data', 'domain/js/case_search', ], function( $, initialPageData, caseSearch ) { $(function () { var viewModel = caseSearch.CaseSearchConfig({ values: initialPageData.get('values'), caseTypes: initialPageData.get('case_types'), }); $('#case-search-config').koApplyBindings(viewModel); $('#case-search-config').on('change', viewModel.change).on('click', ':button', viewModel.change); }); });
hqDefine('domain/js/case_search_main', [ 'jquery', 'hqwebapp/js/initial_page_data', 'domain/js/case_search', 'hqwebapp/js/knockout_bindings.ko', // save button ], function( $, initialPageData, caseSearch ) { $(function () { var viewModel = caseSearch.CaseSearchConfig({ values: initialPageData.get('values'), caseTypes: initialPageData.get('case_types'), }); $('#case-search-config').koApplyBindings(viewModel); $('#case-search-config').on('change', viewModel.change).on('click', ':button', viewModel.change); }); });
Add knockout bindings as dependency to case search
Add knockout bindings as dependency to case search
JavaScript
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
4954b4b8f0e9325dbfe7bfa5baf9ece539f03347
js/endpoints.js
js/endpoints.js
/** * Created by Neil on 29/09/13. */ function signin(mode, callback, clientID) { // clientID filled in by template, immediate = true because we should not need to ask permission again gapi.auth.authorize({client_id: clientID, scope: ["https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"], immediate: true, response_type: 'token'}, // Can't use id tokens as we can't get the user if from an id token callback); } function userAuthed() { var request = gapi.client.oauth2.userinfo.get().execute(function (resp) { // Check the token by calling userinfo, if it's ok call our end point if (!resp.code) { var token = gapi.auth.getToken(); gapi.client.mylatitude.location.last().execute(function (resp) { // this does not do anything yet it's just a test. // console.log(resp); }); } }); }
/** * Created by Neil on 29/09/13. */ function signin(mode, callback, clientID) { // clientID filled in by template, immediate = true because we should not need to ask permission again gapi.auth.authorize({client_id: clientID, scope: ["https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"], immediate: true, response_type: 'token'}, // Can't use id tokens as we can't get the user if from an id token callback); } function userAuthed() { var request = gapi.client.oauth2.userinfo.get().execute(function (resp) { // Check the token by calling userinfo, if it's ok call our end point if (!resp.code) { var token = gapi.auth.getToken(); gapi.client.mylatitude.locations.latest().execute(function (resp) { // this does not do anything yet it's just a test. // console.log(resp); }); } }); }
Change the name of the endpoint
Change the name of the endpoint
JavaScript
mit
nparley/mylatitude,nparley/mylatitude,nparley/mylatitude
c99f338e1ff0141d256e75150cd9c1e126429682
src/settings.js
src/settings.js
'use babel'; export default { binary: { title: 'Binary path', description: 'Path for elm-format', type: 'string', default: '/usr/local/bin/elm-format', order: 1, }, formatOnSave: { title: 'Format on save', description: 'Do we format when you save files?', type: 'boolean', default: true, order: 2, }, showNotifications: { title: 'Show notifications on save', description: 'Do you want to see the bar when we save?', type: 'boolean', default: false, order: 3, }, showErrorNotifications: { title: 'Show error notifications on save', description: 'Do you want to see the bar when we save?', type: 'boolean', default: true, order: 4, }, };
'use babel'; export default { binary: { title: 'Binary path', description: 'Path for elm-format', type: 'string', default: 'elm-format', order: 1, }, formatOnSave: { title: 'Format on save', description: 'Do we format when you save files?', type: 'boolean', default: true, order: 2, }, showNotifications: { title: 'Show notifications on save', description: 'Do you want to see the bar when we save?', type: 'boolean', default: false, order: 3, }, showErrorNotifications: { title: 'Show error notifications on save', description: 'Do you want to see the bar when we save?', type: 'boolean', default: true, order: 4, }, };
Use "elm-format" as the default binary path
Use "elm-format" as the default binary path Not all people have elm-format installed into /usr/local/bin/elm-format (I installed it via package manager so it's in /usr/bin/elm-format), but I assume most of the people have it int their PATH. This should fix #18 for most users.
JavaScript
mit
triforkse/atom-elm-format
bdbafc18317070530573bd28a2ec5241c793340b
ghost/admin/routes/posts.js
ghost/admin/routes/posts.js
import styleBody from 'ghost/mixins/style-body'; import AuthenticatedRoute from 'ghost/routes/authenticated'; var paginationSettings = { status: 'all', staticPages: 'all', page: 1, limit: 15 }; var PostsRoute = AuthenticatedRoute.extend(styleBody, { classNames: ['manage'], model: function () { // using `.filter` allows the template to auto-update when new models are pulled in from the server. // we just need to 'return true' to allow all models by default. return this.store.filter('post', paginationSettings, function () { return true; }); }, setupController: function (controller, model) { this._super(controller, model); controller.set('paginationSettings', paginationSettings); }, actions: { openEditor: function (post) { this.transitionTo('editor', post); } } }); export default PostsRoute;
import styleBody from 'ghost/mixins/style-body'; import AuthenticatedRoute from 'ghost/routes/authenticated'; var paginationSettings = { status: 'all', staticPages: 'all', page: 1 }; var PostsRoute = AuthenticatedRoute.extend(styleBody, { classNames: ['manage'], model: function () { // using `.filter` allows the template to auto-update when new models are pulled in from the server. // we just need to 'return true' to allow all models by default. return this.store.filter('post', paginationSettings, function () { return true; }); }, setupController: function (controller, model) { this._super(controller, model); controller.set('paginationSettings', paginationSettings); }, actions: { openEditor: function (post) { this.transitionTo('editor', post); } } }); export default PostsRoute;
Remove limit from ember post API calls
Remove limit from ember post API calls ref #3004 - this is unnecessary and causing bugs
JavaScript
mit
TryGhost/Ghost,TryGhost/Ghost,TryGhost/Ghost
76326fa424405c3930855652d69ee603ab7df5e7
bot/utils/twitter/tweetWeather.js
bot/utils/twitter/tweetWeather.js
/** * @module * Tweet the current weather. */ const {postStatus} = require('./../../api/twitter-api'); const weather = require('./../weather/getWeather'); const logger = require('./../logger'); const moment = require('moment-timezone'); const tweetWeather = async(address='Manila, Philippines') => { let curTime = moment.tz('Asia/Manila').format('hh:mm A'); try { let curForecast = await weather.getCurrForecast(address); let data = { status: curForecast.currently.summary, temp: curForecast.currently.temperature, precip: (curForecast.currently.precipProbability * 100) + '%', humid: (curForecast.currently.humidity * 100) + '%' } let tweetHead = `As of ${curTime} in ${address}\nThere will be ${curForecast.hourly.summary}\n\n`; let tweetBody = `Weather Status: ${data.status}\nTemperature: ${data.temp}\nPrecipitation: ${data.precip}\nHumidity: ${data.humid}`; await postStatus({status: tweetHead + tweetBody}); } catch (err) { logger.error('Error tweeting current weather forecast', {error: err}); } }; tweetWeather(); module.exports = tweetWeather;
/** * @module * Tweet the current weather. */ const {postStatus} = require('./../../api/twitter-api'); const weather = require('./../weather/getWeather'); const logger = require('./../logger'); const moment = require('moment-timezone'); const tweetWeather = async(address='Manila, Philippines') => { let curTime = moment.tz('Asia/Manila').format('hh:mm A'); try { let curForecast = await weather.getCurrForecast(address); let data = { status: curForecast.currently.summary, temp: curForecast.currently.temperature, precip: (curForecast.currently.precipProbability * 100) + '%', humid: (curForecast.currently.humidity * 100) + '%' } let tweetHead = `As of ${curTime} in ${address}\nThere will be ${curForecast.hourly.summary}\n\n`; let tweetBody = `Weather Status: ${data.status}\nTemperature: ${data.temp}\nPrecipitation: ${data.precip}\nHumidity: ${data.humid}`; // TODO: Find a workaround to post a tweet status over 140 characters. let tweetPost = await postStatus({status: tweetHead}); logger.info('Tweeted a new weather update', {tweet: tweetPost.text}); } catch (err) { logger.error('Error tweeting current weather forecast', {error: err}); } }; tweetWeather(); module.exports = tweetWeather;
Update weather tweet message to only tweetHead
Update weather tweet message to only tweetHead
JavaScript
mit
Ollen/dale-bot
9d68a8e39598e53cee8c7ba26ab6096f9dfdd219
spread_operator/app-finish.js
spread_operator/app-finish.js
'use strict' let levelOnePokemons = ['Pikachu','Magikarp','Balbasaur']; let allPokemons = ['Meowth', 'Poliwag', ...levelOnePokemons]; console.log(allPokemons); let pikachuName = "Pikachu"; let arrayWords = [...pikachuName]; console.log(arrayWords);
'use strict' let levelOnePokemons = ['Pikachu','Magikarp','Balbasaur']; // Insert array to another array let allPokemons = ['Meowth', 'Poliwag', ...levelOnePokemons]; console.log(allPokemons); let pikachuName = "Pikachu"; // Split into literal array with spread operator let arrayWords = [...pikachuName]; console.log(arrayWords);
Add comment for explain step
Add comment for explain step
JavaScript
apache-2.0
teerasej/training-javascript-es6-beginner-thai
543a31cc11fdb145cde89c42b44f1bd0d22cef6d
gulpfile.js
gulpfile.js
const gulp = require('gulp'); const gutil = require('gulp-util'); const eslint = require('gulp-eslint'); const excludeGitignore = require('gulp-exclude-gitignore'); const mocha = require('gulp-mocha'); const istanbul = require('gulp-istanbul'); gulp.task('linter', eslintCheck); gulp.task('default', gulp.series('linter', gulp.series(istanbulCover, mochaTest))); function eslintCheck() { return gulp.src('**/*.js') .pipe(excludeGitignore()) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); } function istanbulCover() { return gulp.src('generators/**/index.js') .pipe(istanbul({includeUntested: true})) .pipe(istanbul.hookRequire()); } function mochaTest() { return gulp.src('test/**/*.js') .pipe(mocha({reporter: 'spec'})) .once('error', err => { gutil.log(gutil.colors.red('[Mocha]'), err.toString()); process.exit(1); }) .pipe(istanbul.writeReports()); }
const gulp = require('gulp'); const gutil = require('gulp-util'); const eslint = require('gulp-eslint'); const excludeGitignore = require('gulp-exclude-gitignore'); const mocha = require('gulp-mocha'); const istanbul = require('gulp-istanbul'); gulp.task('linter', eslintCheck); gulp.task('default', gulp.series('linter', gulp.series(istanbulCover, mochaTest))); function eslintCheck() { return gulp.src(['**/*.js', '!**/templates/**']) .pipe(excludeGitignore()) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); } function istanbulCover() { return gulp.src('generators/**/index.js') .pipe(istanbul({includeUntested: true})) .pipe(istanbul.hookRequire()); } function mochaTest() { return gulp.src('test/**/*.js') .pipe(mocha({reporter: 'spec'})) .once('error', err => { gutil.log(gutil.colors.red('[Mocha]'), err.toString()); process.exit(1); }) .pipe(istanbul.writeReports()); }
Add ignored files in gulp-eslint conf
Add ignored files in gulp-eslint conf
JavaScript
mit
FountainJS/generator-fountain-tslint
437b52a37060631ae6cce3bd2002db0d7143a3f7
gulpfile.js
gulpfile.js
'use strict'; const gulp = require('gulp'); const babel = require('gulp-babel'); gulp.task('default', () => gulp.src('lib/delve.js') .pipe(babel({ presets: ['es2015'] })) .pipe(gulp.dest('dist')) );
'use strict'; const gulp = require('gulp'); const clean = require('gulp-clean'); const babel = require('gulp-babel'); gulp.task('clean-dist', () => gulp.src('dist/', { read: false }) .pipe(clean()) ); gulp.task('default', [ 'clean-dist' ], () => gulp.src('lib/*.js') .pipe(babel({ presets: [ 'es2015' ] })) .pipe(gulp.dest('dist')) );
Add gulp clean & build tasks
Add gulp clean & build tasks
JavaScript
mit
tylerFowler/delvejs
f69dacc5aecab76e7dd3920decce6950f8c6d300
gulpfile.js
gulpfile.js
/* global require */ var gulp = require('gulp'), spawn = require('child_process').spawn, ember, node; gulp.task('server', function () { if (node) node.kill(); // Kill server if one is running node = spawn('node', ['server.js'], {cwd: 'node', stdio: 'inherit'}); node.on('close', function (code) { if (code === 8) { console.log('Node error detected, waiting for changes...'); } }); }); gulp.task('ember', function () { ember = spawn('./node_modules/.bin/ember', ['server', '--port=4900', '--proxy=http://localhost:3900'], {cwd: 'ember', stdio: 'inherit'}); ember.on('close', function (code) { if (code === 8) { console.log('Ember error detected, waiting for changes...'); } }); }); gulp.task('default', function () { gulp.run('server'); gulp.run('ember'); // Reload server if files changed gulp.watch(['node/**/*.js'], function () { gulp.run('server'); }); }); // kill node server on exit process.on('exit', function() { if (node) node.kill(); if (ember) ember.kill(); });
/* global require */ var gulp = require('gulp'), spawn = require('child_process').spawn, ember, node; gulp.task('node', function () { if (node) node.kill(); // Kill server if one is running node = spawn('node', ['server.js'], {cwd: 'node', stdio: 'inherit'}); node.on('close', function (code) { if (code === 8) { console.log('Node error detected, waiting for changes...'); } }); }); gulp.task('ember', function () { ember = spawn('./node_modules/.bin/ember', ['server', '--port=4900', '--proxy=http://localhost:3900'], {cwd: 'ember', stdio: 'inherit'}); ember.on('close', function (code) { if (code === 8) { console.log('Ember error detected, waiting for changes...'); } }); }); gulp.task('default', function () { gulp.run('node'); gulp.run('ember'); // Reload node if files changed gulp.watch(['node/**/*.js'], function () { gulp.run('node'); }); }); // kill node server on exit process.on('exit', function() { if (node) node.kill(); if (ember) ember.kill(); });
Rename server task to node
Rename server task to node
JavaScript
bsd-3-clause
FreeMusicNinja/freemusic.ninja,FreeMusicNinja/freemusic.ninja
866967ddb5ca862c34394113472f9ec543b7549c
gulpfile.js
gulpfile.js
var fontName = 'seti', gulp = require('gulp'), iconfont = require('gulp-iconfont'), iconfontCss = require('gulp-iconfont-css'), svgmin = require('gulp-svgmin'); gulp.task('font', function(){ gulp.src(['./icons/*.svg']) .pipe(iconfontCss({ fontName: fontName, path: './styles/_fonts/_template.less', targetPath: '../seti.less/', fontPath: './styles/_fonts/seti/' })) .pipe(iconfont({ normalize: true, fontName: fontName, formats: ['ttf', 'eot', 'woff', 'woff2', 'svg'] })) .pipe(gulp.dest('./styles/_fonts/seti/')); }); gulp.task('icon', ['svg', 'font']); gulp.task('icons', ['svg', 'font']); gulp.task('svg', function() { gulp.src('./icons/*.svg') .pipe(svgmin()) .pipe(gulp.dest('./icons')); });
var fontName = 'seti', gulp = require('gulp'), iconfont = require('gulp-iconfont'), iconfontCss = require('gulp-iconfont-css'), svgmin = require('gulp-svgmin'); gulp.task('font', function(){ gulp.src(['./icons/*.svg']) .pipe(iconfontCss({ fontName: fontName, path: './styles/_fonts/_template.less', targetPath: '../seti.less/', fontPath: './styles/_fonts/seti/' })) .pipe(iconfont({ normalize: true, fontHeight: 1000, fontName: fontName, formats: ['ttf', 'eot', 'woff', 'woff2', 'svg'] })) .pipe(gulp.dest('./styles/_fonts/seti/')); }); gulp.task('icon', ['svg', 'font']); gulp.task('icons', ['svg', 'font']); gulp.task('svg', function() { gulp.src('./icons/*.svg') .pipe(svgmin()) .pipe(gulp.dest('./icons')); });
Set font height to improve glyph quality
Set font height to improve glyph quality
JavaScript
mit
jesseweed/seti-ui
30013e03caa57ce57090d36c812aa6d128db3348
gulpfile.js
gulpfile.js
var gulp = require('gulp'), connect = require('gulp-connect'), stylus = require('gulp-stylus'), prefix = require('gulp-autoprefixer'); var paths = { styles: 'css/bare-ninja.styl', html: './*.html' }; gulp.task('connect', function() { connect.server({ livereload: true }); }); gulp.task('html', function () { gulp.src(paths.html) .pipe(connect.reload()); }); gulp.task('styles', function () { gulp.src(paths.styles) .pipe(stylus()) .pipe(prefix('last 2 version', 'ie 8', 'ie 9')) .pipe(gulp.dest('./css')) .pipe(connect.reload()); }); gulp.task('watch', function () { gulp.watch(paths.styles, ['styles']); gulp.watch(paths.html, ['html']); }); // The default task (called when you run `gulp` from cli) gulp.task('default', ['styles', 'connect', 'watch']);
var gulp = require('gulp'), connect = require('gulp-connect'), stylus = require('gulp-stylus'), prefix = require('gulp-autoprefixer'); var paths = { styles: 'css/**/*.styl', html: './*.html' }; gulp.task('connect', function() { connect.server({ livereload: true }); }); gulp.task('html', function () { gulp.src(paths.html) .pipe(connect.reload()); }); gulp.task('styles', function () { gulp.src('css/bare-ninja.styl') .pipe(stylus()) .pipe(prefix('last 2 version', 'ie 8', 'ie 9')) .pipe(gulp.dest('./css')) .pipe(connect.reload()); }); gulp.task('watch', function () { gulp.watch(paths.styles, ['styles']); gulp.watch(paths.html, ['html']); }); // The default task (called when you run `gulp` from cli) gulp.task('default', ['styles', 'connect', 'watch']);
Fix LiveReload for all .styl files
Fix LiveReload for all .styl files
JavaScript
mit
trevanhetzel/barekit,trevanhetzel/barekit
65fc00db12ebad06df6557bc3276eccc493566e2
gulpfile.js
gulpfile.js
require('babel/register') var gulp = require('gulp') var $ = require("gulp-load-plugins")() var runSequence = require("run-sequence") gulp.task("build", function() { return gulp.src("src/**/*.js") .pipe($.babel()) .pipe(gulp.dest("lib")) }) gulp.task("lint", function() { return gulp.src("src/**/*.js") .pipe($.eslint()) .pipe($.eslint.format()) }) gulp.task("test", function() { process.env.NODE_ENV = "test" return gulp.src("test/**/*.js") .pipe($.mocha({ reporter: "spec", clearRequireCache: true, ignoreLeaks: true })) }) gulp.task("default", function(cb) { return runSequence("build", "test", cb) })
require('babel/register') var gulp = require('gulp') var $ = require("gulp-load-plugins")() var runSequence = require("run-sequence") gulp.task("build", function() { return gulp.src("src/**/*.js") .pipe($.babel()) .pipe(gulp.dest("lib")) }) gulp.task("lint", function() { return gulp.src("src/**/*.js") .pipe($.eslint()) .pipe($.eslint.format()) }) gulp.task("test", function() { process.env.NODE_ENV = "test" return gulp.src("test/**/*.js") .pipe($.mocha({ reporter: "spec", clearRequireCache: true, ignoreLeaks: true })) }) gulp.task("default", function(cb) { return runSequence("build", "test", cb) }) function release(importance) { return new Promise(function(resolve) { // Select package.json gulp.src(["package.json"]) // Bump version on the package.json .pipe($.bump({type: importance})) .pipe(gulp.dest('./')) // Commit the changes .pipe($.git.commit("Bump version")) // Tag our version .pipe($.tagVersion()) .on("end", function() { $.git.push("origin", "master", {args: "--follow-tags"}, function() { resolve() }) }) }) } gulp.task("release:minor", _.partial(release, "minor")); gulp.task("release:major", _.partial(release, "major")); gulp.task("release:patch", _.partial(release, "patch"));
Add release task (needs npm publish still)
Add release task (needs npm publish still)
JavaScript
mit
launchbadge/node-bok
371a70778560330e5730acf1a76c6de17c578d17
gulpfile.js
gulpfile.js
"use strict" let gulp = require('gulp'); let ts = require('gulp-typescript'); let tsProject = ts.createProject("tsconfig.json"); gulp.task("default", () => { return tsProject.src() .pipe(tsProject()) .js.pipe(gulp.dest("dist")); });
"use strict" let gulp = require("gulp"); let sourcemaps = require("gulp-sourcemaps"); let ts = require("gulp-typescript"); let tsProject = ts.createProject("tsconfig.json"); gulp.task("default", () => { let tsResult = tsProject.src() .pipe(sourcemaps.init()) .pipe(tsProject()); return tsResult.js .pipe(sourcemaps.write()) .pipe(gulp.dest("dist")) }); gulp.task("watch", ["default"], () => { gulp.watch("*.ts", ["default"]); });
Set up gulp watch to automatically compile TypeScript files
Set up gulp watch to automatically compile TypeScript files
JavaScript
apache-2.0
munumafia/EasyJSON,munumafia/EasyJSON
33ba0535b53c580d91b6b2de3d8b919ae3d5c781
helpers/sharedb-server.js
helpers/sharedb-server.js
var ShareDB = require('sharedb'); ShareDB.types.register(require('rich-text').type); module.exports = new ShareDB({ db: require('sharedb-mongo')('mongodb://localhost:27017/quill-sharedb-cursors') });
var ShareDB = require('sharedb'); ShareDB.types.register(require('rich-text').type); module.exports = new ShareDB({ db: require('sharedb-mongo')(process.env.MONGODB_URI || 'mongodb://localhost/quill-sharedb-cursors?auto_reconnect=true') });
Add MONGODB_URI env var config
Add MONGODB_URI env var config
JavaScript
mit
pedrosanta/quill-sharedb-cursors,pedrosanta/quill-sharedb-cursors
d485edf1145ccfba4e8668c13dfd5ed2170624da
lib/AdapterJsRTCObjectFactory.js
lib/AdapterJsRTCObjectFactory.js
'use strict'; /** * An RTC Object factory that works in Firefox and Chrome when adapter.js is present */ function AdapterJsRTCObjectFactory() { this.createIceServer = function(url, username, password) { return createIceServer(url, username, password); }; this.createRTCSessionDescription = function (sessionDescriptionString) { return new RTCSessionDescription(sessionDescriptionString); }; this.createRTCIceCandidate = function (rtcIceCandidateString) { return new RTCIceCandidate(rtcIceCandidateString); }; this.createRTCPeerConnection = function(config) { return new RTCPeerConnection(config); }; } module.exports = AdapterJsRTCObjectFactory;
'use strict'; var Utils = require("cyclon.p2p-common"); /** * An RTC Object factory that works in Firefox and Chrome when adapter.js is present */ function AdapterJsRTCObjectFactory(logger) { Utils.checkArguments(arguments, 1); this.createIceServer = function (url, username, password) { if (typeof(createIceServer) !== "undefined") { return createIceServer(url, username, password); } else { logger.error("adapter.js not present or unsupported browser!"); return null; } }; this.createRTCSessionDescription = function (sessionDescriptionString) { if (typeof(RTCSessionDescription) !== "undefined") { return new RTCSessionDescription(sessionDescriptionString); } else { logger.error("adapter.js not present or unsupported browser!"); return null; } }; this.createRTCIceCandidate = function (rtcIceCandidateString) { if (typeof(RTCIceCandidate) !== "undefined") { return new RTCIceCandidate(rtcIceCandidateString); } else { logger.error("adapter.js not present or unsupported browser!"); return null; } }; this.createRTCPeerConnection = function (config) { if (typeof(RTCPeerConnection) !== "undefined") { return new RTCPeerConnection(config); } else { logger.error("adapter.js not present or unsupported browser!"); return null; } }; } module.exports = AdapterJsRTCObjectFactory;
Handle missing adapter.js more gracefully
Handle missing adapter.js more gracefully
JavaScript
mit
nicktindall/cyclon.p2p-rtc-client,nicktindall/cyclon.p2p-rtc-client
900b593d7c66248086892b9cedfa24563fb8e270
gulpfile.js
gulpfile.js
const inlineNg2Template = require('gulp-inline-ng2-template'); const gulp = require('gulp'); const clean = require('gulp-clean'); const tmpDir = './tmp'; const distDir = './dist'; gulp.task('inline-templates', ['clean-tmp'], function () { return gulp.src('./src/**/*.ts') .pipe(inlineNg2Template({ base: '/src', target: 'es6', useRelativePaths: true })) .pipe(gulp.dest(tmpDir)); }); gulp.task('clean-tmp', function () { return gulp.src(tmpDir, { read: false }) .pipe(clean()); }); gulp.task('clean-dist', function () { return gulp.src(distDir, { read: false }) .pipe(clean()); }); gulp.task('copy-package-json', function () { return gulp.src('package.json') .pipe(gulp.dest(distDir)); }); gulp.task('copy-misc-files', function () { return gulp.src(['README.MD', 'LICENSE']) .pipe(gulp.dest(distDir)); }); gulp.task('copy-all', ['copy-package-json', 'copy-misc-files']);
const inlineNg2Template = require('gulp-inline-ng2-template'); const gulp = require('gulp'); const clean = require('gulp-clean'); const tmpDir = './tmp'; const distDir = './dist'; gulp.task('inline-templates', ['clean-tmp'], function () { return gulp.src('./src/**/*.ts') .pipe(inlineNg2Template({ base: '/src', target: 'es6', useRelativePaths: true })) .pipe(gulp.dest(tmpDir)); }); gulp.task('clean-tmp', function () { return gulp.src(tmpDir, { read: false }) .pipe(clean()); }); gulp.task('clean-dist', function () { return gulp.src(distDir, { read: false }) .pipe(clean()); }); gulp.task('copy-package-json', function () { return gulp.src('package.json') .pipe(gulp.dest(distDir)); }); gulp.task('copy-misc-files', function () { return gulp.src(['README.MD', 'LICENSE', 'CHANGELOG.MD']) .pipe(gulp.dest(distDir)); }); gulp.task('copy-all', ['copy-package-json', 'copy-misc-files']);
Add CHANGELOG.MD to copy-misc-files task
Add CHANGELOG.MD to copy-misc-files task
JavaScript
mit
mpalourdio/ng-http-loader,mpalourdio/ng-http-loader,mpalourdio/ng-http-loader
64b03b3b7209ea61c03f35616b399c755c933541
sysapps/device_capabilities_new/device_capabilities_api.js
sysapps/device_capabilities_new/device_capabilities_api.js
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Implementation of the W3C's Device Capabilities API. // http://www.w3.org/2012/sysapps/device-capabilities/ var internal = requireNative('internal'); internal.setupInternalExtension(extension); var v8tools = requireNative('v8tools'); var common = requireNative('sysapps_common'); common.setupSysAppsCommon(internal, v8tools); var Promise = requireNative('sysapps_promise').Promise; var DeviceCapabilities = function() { common.BindingObject.call(this, common.getUniqueId()); internal.postMessage("deviceCapabilitiesConstructor", [this._id]); this._addMethodWithPromise("getAVCodecs", Promise); this._addMethodWithPromise("getCPUInfo", Promise); this._addMethodWithPromise("getMemoryInfo", Promise); this._addMethodWithPromise("getStorageInfo", Promise); }; DeviceCapabilities.prototype = new common.BindingObjectPrototype(); DeviceCapabilities.prototype.constructor = DeviceCapabilities; exports = new DeviceCapabilities();
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Implementation of the W3C's Device Capabilities API. // http://www.w3.org/2012/sysapps/device-capabilities/ var internal = requireNative('internal'); internal.setupInternalExtension(extension); var v8tools = requireNative('v8tools'); var common = requireNative('sysapps_common'); common.setupSysAppsCommon(internal, v8tools); var Promise = requireNative('sysapps_promise').Promise; var DeviceCapabilities = function() { common.BindingObject.call(this, common.getUniqueId()); common.EventTarget.call(this); internal.postMessage("deviceCapabilitiesConstructor", [this._id]); this._addEvent("storageattach"); this._addEvent("storagedetach"); this._addMethodWithPromise("getAVCodecs", Promise); this._addMethodWithPromise("getCPUInfo", Promise); this._addMethodWithPromise("getMemoryInfo", Promise); this._addMethodWithPromise("getStorageInfo", Promise); }; DeviceCapabilities.prototype = new common.EventTargetPrototype(); DeviceCapabilities.prototype.constructor = DeviceCapabilities; exports = new DeviceCapabilities();
Make the JavaScript shim dispatch events
[SysApps] Make the JavaScript shim dispatch events The first thing to be done is make the JavaScript DeviceCapabilties an EventTarget (which is also a BindingObject). The BindingObjects are JavaScripts objects with a link with some native object and they use a unique ID for routing messages between them. common.EventTarget.call(this) initializes the EventTarget and makes this._addEvent() possible. Now all the blanks are filled and we are good to go. The next step would be replace the StorageInfoProviderMock with a real implementation for each platform we support. No need to touch on anything else.
JavaScript
bsd-3-clause
tomatell/crosswalk,rakuco/crosswalk,weiyirong/crosswalk-1,amaniak/crosswalk,crosswalk-project/crosswalk,fujunwei/crosswalk,chinakids/crosswalk,siovene/crosswalk,rakuco/crosswalk,hgl888/crosswalk-efl,Pluto-tv/crosswalk,rakuco/crosswalk,leonhsl/crosswalk,RafuCater/crosswalk,crosswalk-project/crosswalk-efl,pk-sam/crosswalk,siovene/crosswalk,zliang7/crosswalk,huningxin/crosswalk,jondong/crosswalk,pk-sam/crosswalk,darktears/crosswalk,dreamsxin/crosswalk,pk-sam/crosswalk,weiyirong/crosswalk-1,hgl888/crosswalk,amaniak/crosswalk,weiyirong/crosswalk-1,baleboy/crosswalk,myroot/crosswalk,fujunwei/crosswalk,xzhan96/crosswalk,rakuco/crosswalk,xzhan96/crosswalk,xzhan96/crosswalk,stonegithubs/crosswalk,mrunalk/crosswalk,bestwpw/crosswalk,Bysmyyr/crosswalk,tomatell/crosswalk,jpike88/crosswalk,axinging/crosswalk,PeterWangIntel/crosswalk,minggangw/crosswalk,ZhengXinCN/crosswalk,myroot/crosswalk,darktears/crosswalk,tedshroyer/crosswalk,shaochangbin/crosswalk,heke123/crosswalk,bestwpw/crosswalk,jondwillis/crosswalk,mrunalk/crosswalk,tedshroyer/crosswalk,chuan9/crosswalk,crosswalk-project/crosswalk-efl,hgl888/crosswalk,TheDirtyCalvinist/spacewalk,crosswalk-project/crosswalk,zliang7/crosswalk,zliang7/crosswalk,hgl888/crosswalk-efl,XiaosongWei/crosswalk,DonnaWuDongxia/crosswalk,chinakids/crosswalk,axinging/crosswalk,myroot/crosswalk,ZhengXinCN/crosswalk,jpike88/crosswalk,jondwillis/crosswalk,minggangw/crosswalk,Bysmyyr/crosswalk,huningxin/crosswalk,chuan9/crosswalk,qjia7/crosswalk,jondwillis/crosswalk,baleboy/crosswalk,axinging/crosswalk,amaniak/crosswalk,darktears/crosswalk,XiaosongWei/crosswalk,alex-zhang/crosswalk,qjia7/crosswalk,Bysmyyr/crosswalk,weiyirong/crosswalk-1,hgl888/crosswalk-efl,qjia7/crosswalk,TheDirtyCalvinist/spacewalk,baleboy/crosswalk,hgl888/crosswalk-efl,jpike88/crosswalk,XiaosongWei/crosswalk,tedshroyer/crosswalk,XiaosongWei/crosswalk,alex-zhang/crosswalk,crosswalk-project/crosswalk,minggangw/crosswalk,shaochangbin/crosswalk,jondong/crosswalk,darktears/crosswalk,minggangw/crosswalk,crosswalk-project/crosswalk,chinakids/crosswalk,darktears/crosswalk,hgl888/crosswalk-efl,weiyirong/crosswalk-1,alex-zhang/crosswalk,marcuspridham/crosswalk,marcuspridham/crosswalk,alex-zhang/crosswalk,zeropool/crosswalk,RafuCater/crosswalk,stonegithubs/crosswalk,dreamsxin/crosswalk,alex-zhang/crosswalk,crosswalk-project/crosswalk-efl,xzhan96/crosswalk,PeterWangIntel/crosswalk,TheDirtyCalvinist/spacewalk,PeterWangIntel/crosswalk,tomatell/crosswalk,PeterWangIntel/crosswalk,zliang7/crosswalk,crosswalk-project/crosswalk-efl,Bysmyyr/crosswalk,PeterWangIntel/crosswalk,DonnaWuDongxia/crosswalk,chinakids/crosswalk,PeterWangIntel/crosswalk,RafuCater/crosswalk,tedshroyer/crosswalk,minggangw/crosswalk,crosswalk-project/crosswalk,tomatell/crosswalk,chinakids/crosswalk,tedshroyer/crosswalk,marcuspridham/crosswalk,amaniak/crosswalk,tedshroyer/crosswalk,axinging/crosswalk,bestwpw/crosswalk,tomatell/crosswalk,siovene/crosswalk,DonnaWuDongxia/crosswalk,bestwpw/crosswalk,rakuco/crosswalk,jondong/crosswalk,bestwpw/crosswalk,marcuspridham/crosswalk,myroot/crosswalk,zliang7/crosswalk,amaniak/crosswalk,siovene/crosswalk,xzhan96/crosswalk,amaniak/crosswalk,marcuspridham/crosswalk,alex-zhang/crosswalk,hgl888/crosswalk-efl,Bysmyyr/crosswalk,jondwillis/crosswalk,leonhsl/crosswalk,Pluto-tv/crosswalk,bestwpw/crosswalk,jondong/crosswalk,stonegithubs/crosswalk,jpike88/crosswalk,zeropool/crosswalk,hgl888/crosswalk,tomatell/crosswalk,jondong/crosswalk,lincsoon/crosswalk,darktears/crosswalk,DonnaWuDongxia/crosswalk,hgl888/crosswalk,zliang7/crosswalk,dreamsxin/crosswalk,marcuspridham/crosswalk,jondwillis/crosswalk,zliang7/crosswalk,TheDirtyCalvinist/spacewalk,chuan9/crosswalk,leonhsl/crosswalk,dreamsxin/crosswalk,baleboy/crosswalk,XiaosongWei/crosswalk,zeropool/crosswalk,zeropool/crosswalk,tedshroyer/crosswalk,xzhan96/crosswalk,siovene/crosswalk,minggangw/crosswalk,dreamsxin/crosswalk,rakuco/crosswalk,fujunwei/crosswalk,mrunalk/crosswalk,marcuspridham/crosswalk,fujunwei/crosswalk,heke123/crosswalk,fujunwei/crosswalk,heke123/crosswalk,jpike88/crosswalk,myroot/crosswalk,jpike88/crosswalk,rakuco/crosswalk,qjia7/crosswalk,minggangw/crosswalk,crosswalk-project/crosswalk-efl,ZhengXinCN/crosswalk,fujunwei/crosswalk,crosswalk-project/crosswalk,pk-sam/crosswalk,Bysmyyr/crosswalk,stonegithubs/crosswalk,mrunalk/crosswalk,jpike88/crosswalk,ZhengXinCN/crosswalk,Pluto-tv/crosswalk,heke123/crosswalk,baleboy/crosswalk,hgl888/crosswalk,hgl888/crosswalk,bestwpw/crosswalk,PeterWangIntel/crosswalk,leonhsl/crosswalk,darktears/crosswalk,lincsoon/crosswalk,marcuspridham/crosswalk,zeropool/crosswalk,zeropool/crosswalk,stonegithubs/crosswalk,pk-sam/crosswalk,mrunalk/crosswalk,fujunwei/crosswalk,jondong/crosswalk,heke123/crosswalk,qjia7/crosswalk,huningxin/crosswalk,xzhan96/crosswalk,XiaosongWei/crosswalk,huningxin/crosswalk,pk-sam/crosswalk,leonhsl/crosswalk,lincsoon/crosswalk,Pluto-tv/crosswalk,baleboy/crosswalk,Pluto-tv/crosswalk,baleboy/crosswalk,leonhsl/crosswalk,hgl888/crosswalk,ZhengXinCN/crosswalk,heke123/crosswalk,siovene/crosswalk,hgl888/crosswalk,DonnaWuDongxia/crosswalk,stonegithubs/crosswalk,chuan9/crosswalk,huningxin/crosswalk,shaochangbin/crosswalk,DonnaWuDongxia/crosswalk,Pluto-tv/crosswalk,dreamsxin/crosswalk,xzhan96/crosswalk,crosswalk-project/crosswalk-efl,dreamsxin/crosswalk,shaochangbin/crosswalk,crosswalk-project/crosswalk,crosswalk-project/crosswalk,Bysmyyr/crosswalk,alex-zhang/crosswalk,heke123/crosswalk,ZhengXinCN/crosswalk,jondwillis/crosswalk,RafuCater/crosswalk,baleboy/crosswalk,tomatell/crosswalk,axinging/crosswalk,myroot/crosswalk,leonhsl/crosswalk,weiyirong/crosswalk-1,axinging/crosswalk,TheDirtyCalvinist/spacewalk,zliang7/crosswalk,minggangw/crosswalk,stonegithubs/crosswalk,lincsoon/crosswalk,Bysmyyr/crosswalk,weiyirong/crosswalk-1,lincsoon/crosswalk,heke123/crosswalk,RafuCater/crosswalk,DonnaWuDongxia/crosswalk,shaochangbin/crosswalk,chuan9/crosswalk,Pluto-tv/crosswalk,XiaosongWei/crosswalk,amaniak/crosswalk,huningxin/crosswalk,rakuco/crosswalk,jondong/crosswalk,axinging/crosswalk,jondong/crosswalk,shaochangbin/crosswalk,mrunalk/crosswalk,lincsoon/crosswalk,RafuCater/crosswalk,hgl888/crosswalk-efl,lincsoon/crosswalk,lincsoon/crosswalk,crosswalk-project/crosswalk-efl,pk-sam/crosswalk,chuan9/crosswalk,siovene/crosswalk,zeropool/crosswalk,chinakids/crosswalk,darktears/crosswalk,jondwillis/crosswalk,TheDirtyCalvinist/spacewalk,qjia7/crosswalk,chuan9/crosswalk,ZhengXinCN/crosswalk,RafuCater/crosswalk
8c42ee718563fd7c82bacba65baf65cb12dd09fc
js/browser/resizeManager.js
js/browser/resizeManager.js
jsio('import browser.events') var logger = logging.getLogger(jsio.__path); var windowResizeCallbacks = []; function handleResize() { if (!windowResizeCallbacks.length) { return; } var size = exports.getWindowSize(); for (var i=0, callback; callback = windowResizeCallbacks[i]; i++) { callback(size); } } browser.events.add(window, 'resize', handleResize); exports = { onWindowResize: function(callback) { callback(exports.getWindowSize()); windowResizeCallbacks.push(callback); }, cancelWindowResize: function(targetCallback) { for (var i=0, callback; callback = windowResizeCallbacks[i]; i++) { if (callback == targetCallback) { continue; } windowResizeCallbacks.splice(i, 1); return; } }, getWindowSize: function() { return { width: window.innerWidth, height: window.innerHeight }; }, fireResize: handleResize }
jsio('import browser.events') var logger = logging.getLogger(jsio.__path); var windowResizeCallbacks = []; function handleResize() { if (!windowResizeCallbacks.length) { return; } var size = exports.getWindowSize(); for (var i=0, callback; callback = windowResizeCallbacks[i]; i++) { callback(size); } } browser.events.add(window, 'resize', handleResize); exports = { onWindowResize: function(callback) { callback(exports.getWindowSize()); windowResizeCallbacks.push(callback); }, cancelWindowResize: function(targetCallback) { for (var i=0, callback; callback = windowResizeCallbacks[i]; i++) { if (callback != targetCallback) { continue; } windowResizeCallbacks.splice(i, 1); return; } }, getWindowSize: function() { return { width: window.innerWidth, height: window.innerHeight }; }, fireResize: handleResize }
Fix bug where cancelWindowResize, would remove the wrong callback
Fix bug where cancelWindowResize, would remove the wrong callback
JavaScript
mit
marcuswestin/fin
3799c780d5b9ca0cfd97f3795c1ce456b78d4261
gesso/index.js
gesso/index.js
// Re-using Gesso entry point // Detect whether this is called from a built bundle from the browser, or as the build project. if (typeof window !== 'undefined') { // Client-side require module.exports = { canvas: document.getElementById('gesso-target') }; } else { // Server-side require -- use module.require so the build doesn't detect this var command = module.require('./command'); module.exports = { globalMain: command.globalMain, packagelessMain: command.packagelessMain, main: command.main }; }
// Re-using Gesso entry point // Detect whether this is called from a built bundle from the browser, or as the build project. /* globals window */ if (typeof window !== 'undefined') { // Client-side require module.exports = { canvas: window.document.getElementById('gesso-target') }; } else { // Server-side require -- use module.require so the build doesn't detect this var command = module.require('./command'); module.exports = { globalMain: command.globalMain, packagelessMain: command.packagelessMain, main: command.main }; }
Use window.document for client-side require.
Use window.document for client-side require.
JavaScript
mit
gessojs/gessojs,gessojs/gessojs
150741269e8cc655ad7041faa1cf825fbf5a4515
WebComponentsMonkeyPatch.js
WebComponentsMonkeyPatch.js
/** * Evidently superinspired by Chris Wilson's AudioContext-MonkeyPatch library, * and just patching webkitCreateShadowRoot to createShadowRoot */ (function() { if( HTMLElement.prototype.webkitCreateShadowRoot !== undefined && HTMLElement.prototype.createShadowRoot === undefined ) { HTMLElement.prototype.createShadowRoot = HTMLElement.prototype.webkitCreateShadowRoot; } })(); (function() { if('register' in document || 'registerElement' in document){ document.register = document.registerElement = document.register || document.register; } })();
/** * Evidently superinspired by Chris Wilson's AudioContext-MonkeyPatch library, */ (function() { // Unprefixed createShadowRoot if( HTMLElement.prototype.webkitCreateShadowRoot !== undefined && HTMLElement.prototype.createShadowRoot === undefined ) { HTMLElement.prototype.createShadowRoot = HTMLElement.prototype.webkitCreateShadowRoot; } // Alias document.register to document.registerElement if('register' in document || 'registerElement' in document){ document.register = document.registerElement = document.register || document.register; } })();
Use only one function call
Use only one function call
JavaScript
apache-2.0
sole/WebComponentsMonkeyPatch
5cda8ad7e27dbbafc2ab2c7d6569fec6546db2ce
colorImageSelector.js
colorImageSelector.js
/* for each li color = find span color --- this.text url = find main prod image -- this.url category Swatch Color Button = matching color.url end on click */ var colorBtnSrc = {}; $("span:contains('Color')").parents().eq(2).find('.productAttributeValue li').each( function getColorPhotosSrcs(){ var listings = $(this); prodColor = $(this).find('.name').text(); console.log(prodColor); $(this).find('label').click(); // find url of img when this li is checked and store it // for (i = 0; i < listings.length; i++) { // var colorImgSrc += $(document).find('.MagicZoomPlus img').attr('src'); // console.log(colorImgSrc); // } colorBtnSrc[prodColor] = $(document).find('.MagicZoomPlus img').attr('src'); }) console.log(colorBtnSrc); //$("span:contains('Color')").parents().eq(2).find('.productAttributeValue li').removeClass('selectedValue').find('.radio span').removeClass('checked'); //$("span:contains('Color')").parents().eq(2).find('.productAttributeValue li').eq(2).addClass('selectedValue').find('.radio span').addClass('checked'); //$("span:contains('Color')").parents().eq(2).find('.productAttributeValue li').eq(2).find('label').click();
/* for each li color = find span color --- this.text url = find main prod image -- this.url category Swatch Color Button = matching color.url end on click */ var colorBtnSrc = {}; $("span:contains('Color')").parents().eq(2).find('.productAttributeValue li').each( function getColorPhotosSrcs(){ var listings = $(this); prodColor = $(this).find('.name').text(); console.log(prodColor); $(this).find('label').click(); // find url of img when this li is checked and store it // for (i = 0; i < listings.length; i++) { // var colorImgSrc += $(document).find('.MagicZoomPlus img').attr('src'); // console.log(colorImgSrc); // } colorBtnSrc[prodColor] = $(document).find('.MagicZoomPlus').attr('src'); }) console.log(colorBtnSrc); //$("span:contains('Color')").parents().eq(2).find('.productAttributeValue li').removeClass('selectedValue').find('.radio span').removeClass('checked'); //$("span:contains('Color')").parents().eq(2).find('.productAttributeValue li').eq(2).addClass('selectedValue').find('.radio span').addClass('checked'); //$("span:contains('Color')").parents().eq(2).find('.productAttributeValue li').eq(2).find('label').click();
Update to image src selector
Update to image src selector
JavaScript
mit
iamandrebulatov/BC-Category-Page-Color-Swatch
a145c78423cab08cfb412f6d7c61ef87cef2199c
src/config/constants.js
src/config/constants.js
import firebase from 'firebase' const config = { apiKey: "AIzaSyDHL6JFTyBcaV60WpE4yXfeO0aZbzA9Xbk", authDomain: "practice-auth.firebaseapp.com", databaseURL: "https://practice-auth.firebaseio.com", } firebase.initializeApp(config) export const ref = firebase.database().ref() export const firebaseAuth = firebase.auth
import firebase from 'firebase'; const config = { apiKey: process.env.REACT_APP_FIREBASE_API, authDomain: process.env.REACT_APP_FIREBASE_DOMAIN, databaseURL: process.env.REACT_APP_FIREBASE_DATABASE, storageBucket: process.env.REACT_APP_FIREBASE_BUCKET, messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER, }; firebase.initializeApp(config); export const ref = firebase.database().ref(); export const firebaseAuth = firebase.auth;
Read firebase creds from .env
Read firebase creds from .env
JavaScript
mit
nadavspi/UnwiseConnect,nadavspi/UnwiseConnect,nadavspi/UnwiseConnect
f6b8055acfc4127580725989fa0db32ece35f566
src/activities/when-graphs-mislead/client/scripts/parameters.js
src/activities/when-graphs-mislead/client/scripts/parameters.js
/** * @file Define the parameters for the activity's chart. */ define({ yLimitsUSD: { label: 'y-axis limits ($USD)', min: 0, max: 280000, step: 1000 }, yLimitsPct: { label: 'y-axis limits (% change)', min: 0, max: 1.2, step: 0.01 }, xLimits: { label: 'x-axis limits (year)', min: 1960, max: 2013, step: 1 }, yUnit: { label: 'y-axis unit', dflt: 'USD', values: { Pct: '% change in USD', USD: 'Real GDP per capita ($USD)' } } });
/** * @file Define the parameters for the activity's chart. */ define({ yLimitsUSD: { label: 'y-axis limits ($USD)', min: 0, max: 280000, step: 1000 }, yLimitsPct: { label: 'y-axis limits (% change)', min: 0, max: 1.3, step: 0.01 }, xLimits: { label: 'x-axis limits (year)', min: 1960, max: 2013, step: 1 }, yUnit: { label: 'y-axis unit', dflt: 'USD', values: { Pct: '% change in USD', USD: 'Real GDP per capita ($USD)' } } });
Increase limits for percentage change
Increase limits for percentage change
JavaScript
mpl-2.0
councilforeconed/interactive-activities,councilforeconed/interactive-activities,jugglinmike/cee,councilforeconed/interactive-activities,jugglinmike/cee
d33e9df3e82505d60c16324fb1a5fec6204bb5bb
gulpfile.js
gulpfile.js
var _ = require('lodash'); var gulp = require('gulp'); var gulp_mocha = require('gulp-mocha'); var gulp_jshint = require('gulp-jshint'); var gulp_jsdoc = require("gulp-jsdoc"); var files = ['lib/**/*.js']; var tests = ['test/**/*.spec.js']; var alljs = files.concat(tests); var readme = 'README.md'; function ignoreError(err) { this.emit('end'); } gulp.task('test', function() { return gulp.src(tests).pipe(new gulp_mocha({reporter: 'spec'})).on('error', ignoreError); }); gulp.task('watch:test', function() { // TODO: Only run tests that are linked to file changes by doing // something smart like reading through the require statements return gulp.watch(alljs, ['test']); }); gulp.task('jsdoc', function() { return gulp.src(files.concat([readme])) .pipe(gulp_jsdoc.parser()) .pipe(gulp_jsdoc.generator('./docs', { path: 'ink-docstrap', theme: 'flatly', })) }); gulp.task('lint', function() { return gulp.src(alljs) .pipe(gulp_jshint()) .pipe(gulp_jshint.reporter('default')); }); gulp.task('default', ['lint', 'jsdoc', 'test']);
var _ = require('lodash'); var gulp = require('gulp'); var gulp_mocha = require('gulp-mocha'); var gulp_jshint = require('gulp-jshint'); var gulp_jsdoc = require("gulp-jsdoc"); var files = ['lib/**/*.js']; var tests = ['test/**/*.spec.js']; var alljs = files.concat(tests); var readme = 'README.md'; function ignoreError(err) { this.emit('end'); } function testAllFiles() { return gulp.src(tests).pipe(new gulp_mocha({reporter: 'spec'})); } gulp.task('test', testAllFiles); gulp.task('test-nofail', function() { return testAllFiles().on('error', ignoreError); }); gulp.task('watch:test', function() { // TODO: Only run tests that are linked to file changes by doing // something smart like reading through the require statements return gulp.watch(alljs, ['test-nofail']); }); gulp.task('jsdoc', function() { return gulp.src(files.concat([readme])) .pipe(gulp_jsdoc.parser()) .pipe(gulp_jsdoc.generator('./docs', { path: 'ink-docstrap', theme: 'flatly', })) }); gulp.task('lint', function() { return gulp.src(alljs) .pipe(gulp_jshint()) .pipe(gulp_jshint.reporter('default')); }); gulp.task('default', ['lint', 'jsdoc', 'test']);
Make test fails for CI
Make test fails for CI
JavaScript
mit
bankonme/bitcore-channel,homeopatchy/bitcore-channel,eXcomm/bitcore-channel,braydonf/bitcore-channel,maraoz/bitcore-channel,bitpay/bitcore-channel,studio666/bitcore-channel
9afda10bfeb4d07e3ba2e40e93ebec125d41d7ed
tests/search.js
tests/search.js
/** * search.js - Search form tests. */ casper.test.begin('Tests search form submission and results', 2, function suite(test) { casper.start(); // Open the homepage. casper.customThenOpen('/', function() { casper.waitFor(function check() { // Fill out the search form with 'health' and submit it. return this.evaluate(function() { jQuery('#site_search_text').val('health'); jQuery('#site_search_text').trigger('input'); return jQuery('div#site-search input[type="submit"]').trigger('click'); }); }, function then() { // Check current URL and search results. test.assertUrlMatch(/search\/health/, 'Current path is search/health'); test.assertExists('div.view-search-pane div.view-content div.views-row', 'Search results are listed under "Stories".'); }, function timeout() { this.echo("Search form has not been submitted.").exit(); }); }); casper.run(function() { test.done(); }); });
/** * Search form tests. */ casper.test.begin('Tests search form submission and results', 2, function suite(test) { casper.start(); // Open the homepage. casper.customThenOpen('/', function() { casper.waitFor(function check() { // Fill out the search form with 'health' and submit it. return this.evaluate(function() { jQuery('#site_search_text').val('health'); jQuery('#site_search_text').trigger('input'); return jQuery('div#site-search input[type="submit"]').trigger('click'); }); }, function then() { // Check current URL and search results. test.assertUrlMatch(/search\/health/, 'Current path is search/health'); test.assertExists('div.view-search-pane div.view-content div.views-row', 'Search results are listed under "Stories".'); }, function timeout() { this.echo("Search form has not been submitted.").exit(); }); }); casper.run(function() { test.done(); }); });
Remove unneded filename from header docblock.
Remove unneded filename from header docblock.
JavaScript
mit
Lullabot/casperjs_foundation,Lullabot/casperjs_foundation
801df6499b96c860a2d108dea053304131ab56fd
server/app.js
server/app.js
'use strict'; /** * Module dependencies. */ var express = require('express'); var routes = require('./routes'); var memos = require('./routes/memos'); var http = require('http'); var path = require('path'); var app = express(); // all environments app.set('port', process.env.PORT || 8000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.favicon()); // app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' === app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/memos/*', memos.list); app.get('/memos', memos.list); app.get('/files/*', memos.get); var server = http.createServer(app); server.listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); }); var io = require('socket.io').listen(server, {'log level': 0}); memos.start(io);
'use strict'; /** * Module dependencies. */ var express = require('express'); var routes = require('./routes'); var memos = require('./routes/memos'); var http = require('http'); var path = require('path'); var app = express(); // all environments app.set('port', process.env.PORT || 9001); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.favicon()); // app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' === app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/memos/*', memos.list); app.get('/memos', memos.list); app.get('/files/*', memos.get); var server = http.createServer(app); server.listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); }); var io = require('socket.io').listen(server, {'log level': 0}); memos.start(io);
Change port number to 9001
Change port number to 9001
JavaScript
mit
eqot/memo
bc83a3b4a6b834e972cb2a723e692ec8491a290b
gulpfile.js
gulpfile.js
/** * @author Frank David Corona Prendes <frankdavid.corona@gmail.com> * @copyright MIT 2016 Frank David Corona Prendes * @description Tarea Gulp para la compresion de ficheros JS * @version 1.0.1 */ (function () { 'use strict'; var gulp = require('gulp'); var uglify = require('gulp-uglify'); var pump = require('pump'); var argv = require('yargs').argv; var recursive = require('recursive-readdir'); var logger = require('gulp-logger'); gulp.task('gcompress', function () { recursive('"' + [argv.source + '"' + '/**/*.js'], function (err, file) { var options = { mangle: false }; pump([ gulp.src([argv.source + '/**/*.js']) .pipe(logger({ before: 'Starting compression...', after: 'Compression complete!', showChange: true })) .pipe(uglify(options, uglify)), gulp.dest(argv.destino + '/dist/') ]); }); }); })();
/** * @author Frank David Corona Prendes <frankdavid.corona@gmail.com> * @copyright MIT 2016 Frank David Corona Prendes * @description Tarea Gulp para la compresion de ficheros JS * @version 1.0.1 */ (function () { 'use strict'; var gulp = require('gulp'); var uglify = require('gulp-uglify'); var pump = require('pump'); var argv = require('yargs').argv; var recursive = require('recursive-readdir'); var logger = require('gulp-logger'); gulp.task('default', function () { recursive('"' + [argv.source + '"' + '/**/*.js'], function (err, file) { var options = { mangle: false }; pump([ gulp.src([argv.source + '/**/*.js']) .pipe(logger({ before: 'Starting compression...', after: 'Compression complete!', showChange: true })) .pipe(uglify(options, uglify)), gulp.dest(argv.destino + '/dist/') ]); }); }); })();
Change name of the default task
Change name of the default task
JavaScript
mit
frankdavidcorona/gcompress
1e0b79aa7b62e3162b98c277db248236b75f3a4a
gulpfile.js
gulpfile.js
var gulp = require('gulp'), concat = require('gulp-concat'), rename = require('gulp-rename'), uglify = require('gulp-uglify'); var SRC = 'src/*.js'; var DEST = 'dist/'; gulp.task('build', function() { gulp.src(SRC) .pipe(concat('jsonapi-datastore.js')) .pipe(gulp.dest(DEST)) .pipe(uglify()) .pipe(rename({ extname: '.min.js' })) .pipe(gulp.dest(DEST)); }); gulp.task('default', ['build']);
var gulp = require('gulp'), concat = require('gulp-concat'), rename = require('gulp-rename'), uglify = require('gulp-uglify'), mocha = require('gulp-mocha'); var SRC = 'src/*.js', DEST = 'dist/'; gulp.task('build', function() { gulp.src(SRC) .pipe(concat('jsonapi-datastore.js')) .pipe(gulp.dest(DEST)) .pipe(uglify()) .pipe(rename({ extname: '.min.js' })) .pipe(gulp.dest(DEST)); }); gulp.task('test', ['build'], function() { gulp.src('test/*.js') .pipe(mocha()); }); gulp.task('default', ['build']);
Add gulp task for testing.
Add gulp task for testing.
JavaScript
mit
jamesdixon/jsonapi-datastore,niksy/jsonapi-datastore,beauby/jsonapi-datastore,jprincipe/jsonapi-datastore
ffd4229e0940e26d7e4d5e948180c40bf14eb871
lib/sandbox.js
lib/sandbox.js
/* * Sandbox - A stripped down object of things that plugins can perform. * This object will be passed to plugins on command and hook execution. */ Sandbox = function(irc, commands, usage) { this.bot = { say: function(to, msg) { irc.say(to, msg); }, action: function(to, msg) { irc.action(to, msg); }, commands: commands, usage: usage }; }; exports.Sandbox = Sandbox;
var path = require('path'); /* * Sandbox - A stripped down object of things that plugins can perform. * This object will be passed to plugins on command and hook execution. */ Sandbox = function(irc, commands, usage) { this.bot = { say: function(to, msg) { irc.say(to, msg); }, action: function(to, msg) { irc.action(to, msg); }, commands: commands, usage: usage }; }; /* * Update Sandbox. */ Sandbox.prototype.update = function(commands, usage) { this.bot.commands = commands; this.bot.usage = usage; }; /* * AdminSandbox - A less stripped down object of things that admin plugin * can take advantage of. */ AdminSandbox = function(treslek) { this.bot = { say: function(to, msg) { treslek.irc.say(to, msg); }, action: function(to, msg) { treslek.irc.action(to, msg); }, join: function(channel, callback) { treslek.irc.join(channel, callback); }, part: function(channel, callback) { treslek.irc.part(channel, callback); }, load: function(plugin, callback) { var pluginFile = path.resolve(treslek.conf.plugins_dir, plugin); treslek.loadPlugin(pluginFile, function(err) { callback(); }); }, reload: function(plugin, callback) { var pluginFile = path.resolve(treslek.conf.plugins_dir, plugin); if (!treslek.plugins.hasOwnProperty(pluginFile)) { callback('Unknown plugin: ' + plugin); return; } treslek.reloadPlugin(pluginFile, function(err) { callback(); }); }, unload: function(plugin, callback) { var pluginFile = path.resolve(treslek.conf.plugins_dir, plugin); if (!treslek.plugins.hasOwnProperty(pluginFile)) { callback('Unknown plugin: ' + plugin); return; } treslek.unloadPlugin(pluginFile, function(err) { callback(); }); }, ignore: function(nick) { treslek.ignoreNick(nick); }, unignore: function(nick) { treslek.unignoreNick(nick); } }; }; exports.Sandbox = Sandbox; exports.AdminSandbox = AdminSandbox;
Add AdminSandbox for use with admin plugins.
Add AdminSandbox for use with admin plugins.
JavaScript
mit
jirwin/treslek,rackerlabs/treslek
d4b4d280ac3948dba4fe682deded95423e165685
polyglot/src/test/resources/test-js-plugins/hello-interceptor.js
polyglot/src/test/resources/test-js-plugins/hello-interceptor.js
export const options = { name: "helloWorldInterceptor", description: "modifies the response of helloWorldService", interceptPoint: "RESPONSE" } export function handle(req, res) { LOGGER.debug('response {}', res.getContent()); const rc = JSON.parse(res.getContent() || '{}'); let modifiedBody = { msg: rc.msg + ' from Italy with Love', note: '\'from Italy with Love\' was added by \'helloWorldInterceptor\' that modifies the response of \'helloWorldService\'' } res.setContent(JSON.stringify(modifiedBody)); res.setContentTypeAsJson(); } export function resolve(req) { return req.isHandledBy("helloWorldService") && req.isGet() && req.getContent(); }
export const options = { name: "helloWorldInterceptor", description: "modifies the response of helloWorldService", interceptPoint: "RESPONSE" } export function handle(req, res) { LOGGER.debug('response {}', res.getContent()); const rc = JSON.parse(res.getContent() || '{}'); let modifiedBody = { msg: rc.msg + ' from Italy with Love', note: '\'from Italy with Love\' was added by \'helloWorldInterceptor\' that modifies the response of \'helloWorldService\'' } res.setContent(JSON.stringify(modifiedBody)); res.setContentTypeAsJson(); } export function resolve(req) { return req.isHandledBy("helloWorldService") && req.isGet() && req.getContent() !== null; }
Fix resolve() on test js interceptor
:bug: Fix resolve() on test js interceptor [skip ci]
JavaScript
agpl-3.0
SoftInstigate/restheart,SoftInstigate/restheart,SoftInstigate/restheart,SoftInstigate/restheart
d1eb4d23bdf6d84a17a9ef7175f6901ca7f40178
migrations/2_deploy_contracts.js
migrations/2_deploy_contracts.js
// var usingOraclize = artifacts.require("./usingOraclize.sol"); var Arbiter = artifacts.require("./Arbiter.sol"); var Judge = artifacts.require("./Judge.sol"); var ComputationService = artifacts.require("./ComputationService.sol"); module.exports = function(deployer) { //deployer.deploy(usingOraclize); //deployer.link(ConvertLib, MetaCoin); var contracts = []; // deploy one Arbiter contracts.push(Arbiter); // deploy one Judge contracts.push(Judge); // deploy six computation services for (i = 0; i < 6; i++) { contracts.push(ComputationService); } deployer.deploy(contracts); };
// var usingOraclize = artifacts.require("./usingOraclize.sol"); var Arbiter = artifacts.require("./Arbiter.sol"); var Judge = artifacts.require("./Judge.sol"); var ComputationService = artifacts.require("./ComputationService.sol"); module.exports = function(deployer) { var arbiter, judge, computation; deployer.deploy(Arbiter); deployer.deploy(Judge); deployer.then(function() { return Judge.deployed(); }).then(function(instance) { judge = instance; return Arbiter.deployed(); }).then(function(instance) { arbiter = instance; return arbiter.setJudge(judge.address); }); // deploy six computation services for (i = 0; i < 6; i++) { deployer.deploy(ComputationService); deployer.then(function() { return ComputationService.deployed(); }).then(function(instance) { computation = instance; return computation.registerOperation(0); }); deployer.then(function() { return Arbiter.deployed(); }).then(function(instance) { arbiter = instance; return ComputationService.deployed(); }).then(function(instance) { computation = instance; return computation.enableArbiter(arbiter.address); }); } };
Include registratin of judge and services in arbiter
Include registratin of judge and services in arbiter
JavaScript
mit
nud3l/verifying-computation-solidity,nud3l/verifying-computation-solidity
a1354ce9155bb6609f56421033a5e889372d2b63
tetris.js
tetris.js
var removeExcessSpaces = function(htmlString) { var processedString = htmlString.replace(/\s+</g, '<'); processedString = processedString.replace(/>\s+/g, '>'); processedString = processedString.replace(/\:</g, ': <'); return processedString; } var ready = function(fn) { if(document.readyState != 'loading') { fn(); } else { document.addEventListener('DOMContentLoaded', fn); } } ready(function() { document.querySelector('body').innerHTML = removeExcessSpaces(document.querySelector('body').innerHTML); // Ensure the periodic table overlay is positioned correctly var tableLeft = document.querySelector('#tetris-table').offsetLeft; var tableTop = document.querySelector('#tetris-table').offsetTop; document.querySelector('#table-overlay').style.left = tableLeft + 1 + 'px'; document.querySelector('#table-overlay').style.top = tableTop + 1 + 'px'; // This variable is global for the purposes of development and debugging // Once the game is complete, remove the variable assignment window.gameControl = new Controller(); });
var removeExcessSpaces = function(htmlString) { var processedString = htmlString.replace(/\s+</g, '<'); processedString = processedString.replace(/>\s+/g, '>'); processedString = processedString.replace(/_/g, ' '); return processedString; } var ready = function(fn) { if(document.readyState != 'loading') { fn(); } else { document.addEventListener('DOMContentLoaded', fn); } } ready(function() { document.querySelector('body').innerHTML = removeExcessSpaces(document.querySelector('body').innerHTML); // Ensure the periodic table overlay is positioned correctly var tableLeft = document.querySelector('#tetris-table').offsetLeft; var tableTop = document.querySelector('#tetris-table').offsetTop; document.querySelector('#table-overlay').style.left = tableLeft + 1 + 'px'; document.querySelector('#table-overlay').style.top = tableTop + 1 + 'px'; // This variable is global for the purposes of development and debugging // Once the game is complete, remove the variable assignment window.gameControl = new Controller(); });
Update whitespace removal to convert underscores to spaces
Update whitespace removal to convert underscores to spaces
JavaScript
mit
peternatewood/tetrelementis,RoyTuesday/tetrelementis,RoyTuesday/tetrelementis,peternatewood/tetrelementis
b48f8416fd6637d7fce284ff4e47b01df4829d57
src/core/AudioletParameter.js
src/core/AudioletParameter.js
var AudioletParameter = new Class({ initialize: function(node, inputIndex, value) { this.node = node; if (typeof inputIndex != 'undefined' && inputIndex != null) { this.input = node.inputs[inputIndex]; } else { this.input = null; } this.value = value || 0; }, isStatic: function() { var input = this.input; return (!(input && input.connectedFrom.length && !(input.buffer.isEmpty))); }, isDynamic: function() { var input = this.input; return (input && input.connectedFrom.length && !(input.buffer.isEmpty)); }, setValue: function(value) { this.value = value; }, getValue: function() { return this.value; }, getChannel: function() { return this.input.buffer.channels[0]; } });
var AudioletParameter = new Class({ initialize: function(node, inputIndex, value) { this.node = node; if (typeof inputIndex != 'undefined' && inputIndex != null) { this.input = node.inputs[inputIndex]; } else { this.input = null; } this.value = value || 0; }, isStatic: function() { var input = this.input; return (input == null || input.connectedFrom.length == 0 || input.buffer.isEmpty); }, isDynamic: function() { var input = this.input; return (input != null && input.connectedFrom.length > 0 && !input.buffer.isEmpty); }, setValue: function(value) { this.value = value; }, getValue: function() { return this.value; }, getChannel: function() { return this.input.buffer.channels[0]; } });
Simplify isStatic and isDynamic logic, and make sure they return boolean values
Simplify isStatic and isDynamic logic, and make sure they return boolean values
JavaScript
apache-2.0
oampo/Audiolet,Kosar79/Audiolet,oampo/Audiolet,kn0ll/Audiolet,Kosar79/Audiolet,Kosar79/Audiolet,mcanthony/Audiolet,kn0ll/Audiolet,mcanthony/Audiolet,bobby-brennan/Audiolet,bobby-brennan/Audiolet
1935b925cc03c9e0d711b7e63c441580394e6d16
addon-test-support/index.js
addon-test-support/index.js
import { getContext, settled } from '@ember/test-helpers'; import { run } from '@ember/runloop'; export function setBreakpoint(breakpoint) { let breakpointArray = Array.isArray(breakpoint) ? breakpoint : [breakpoint]; let { owner } = getContext(); let breakpoints = owner.lookup('breakpoints:main'); let media = owner.lookup('service:media'); for (let breakpointName of breakpointArray) { if (breakpointName === 'auto') { media.set('_mocked', false); return; } if (Object.keys(breakpoints).indexOf(breakpointName) === -1) { throw new Error(`Breakpoint "${breakpointName}" is not defined in your breakpoints file`); } } run(() => { media.matches = breakpointArray; media._triggerMediaChanged(); }); return settled(); }
import { getContext, settled } from '@ember/test-helpers'; import { run } from '@ember/runloop'; export function setBreakpoint(breakpoint) { let breakpointArray = Array.isArray(breakpoint) ? breakpoint : [breakpoint]; let { owner } = getContext(); let breakpoints = owner.lookup('breakpoints:main'); let media = owner.lookup('service:media'); for (let i = 0; i < breakpointArray.length; i++) { let breakpointName = breakpointArray[i]; if (breakpointName === 'auto') { media.set('_mocked', false); return; } if (Object.keys(breakpoints).indexOf(breakpointName) === -1) { throw new Error(`Breakpoint "${breakpointName}" is not defined in your breakpoints file`); } } run(() => { media.matches = breakpointArray; media._triggerMediaChanged(); }); return settled(); }
Make test support setBreakpoint IE11 compatible
Make test support setBreakpoint IE11 compatible
JavaScript
mit
freshbooks/ember-responsive,freshbooks/ember-responsive
c3a05985a25b38714e54de13c865f5322dc1b9d3
examples/method_routing/server.js
examples/method_routing/server.js
var jayson = require(__dirname + '/../..'); var format = require('util').format; var methods = { // a method that prints every request add: function(a, b, callback) { callback(null, a + b); } }; var server = jayson.server(methods, { router: function(method) { // regular by-name routing first if(typeof(this._methods[method]) === 'function') return this._methods[method]; if(method === 'add_2') return this._methods.add.bind(this, 2); } }); server.http().listen(3000);
var jayson = require(__dirname + '/../..'); var format = require('util').format; var methods = { // a method that prints every request add: function(a, b, callback) { callback(null, a + b); } }; var server = jayson.server(methods, { router: function(method) { // regular by-name routing first if(typeof(this._methods[method]) === 'function') return this._methods[method]; if(method === 'add_2') { var fn = server.getMethod('add').getHandler(); return jayson.Method(fn.bind(null, 2)); } } }); server.http().listen(3000);
Convert method routing example to new method definition
Convert method routing example to new method definition
JavaScript
mit
taoyuan/jayson,Lughino/jayson,Meettya/jayson,tedeh/jayson,taoyuan/remjson,tedeh/jayson
253d4358a60fb685b2e5583bb9a9245ed42ef140
examples/method_routing/server.js
examples/method_routing/server.js
var jayson = require(__dirname + '/../..'); var format = require('util').format; var methods = { // a method that prints every request add: function(a, b, callback) { callback(null, a + b); } }; var server = jayson.server(methods, { router: function(method) { // regular by-name routing first if(typeof(this._methods[method]) === 'function') return this._methods[method]; if(method === 'add_2') return this._methods.add.bind(this, 2); } }); server.http().listen(3000);
var jayson = require(__dirname + '/../..'); var format = require('util').format; var methods = { // a method that prints every request add: function(a, b, callback) { callback(null, a + b); } }; var server = jayson.server(methods, { router: function(method) { // regular by-name routing first if(typeof(this._methods[method]) === 'function') return this._methods[method]; if(method === 'add_2') { var fn = server.getMethod('add').getHandler(); return jayson.Method(fn.bind(null, 2)); } } }); server.http().listen(3000);
Convert method routing example to new method definition
Convert method routing example to new method definition
JavaScript
mit
Meettya/jayson,tedeh/jayson,Lughino/jayson,taoyuan/jayson,tedeh/jayson,taoyuan/remjson
627acdbfdeae585e449162fa15275df7ea270215
src/js/ripple/utils.web.js
src/js/ripple/utils.web.js
var exports = module.exports = require('./utils.js'); // We override this function for browsers, because they print objects nicer // natively than JSON.stringify can. exports.logObject = function (msg, obj) { if (/MSIE/.test(navigator.userAgent)) { console.log(msg, JSON.stringify(obj)); } else { console.log(msg, "", obj); } };
var exports = module.exports = require('./utils.js'); // We override this function for browsers, because they print objects nicer // natively than JSON.stringify can. exports.logObject = function (msg, obj) { var args = Array.prototype.slice.call(arguments, 1); args = args.map(function(arg) { if (/MSIE/.test(navigator.userAgent)) { return JSON.stringify(arg, null, 2); } else { return arg; } }); args.unshift(msg); console.log.apply(console, args); };
Update in-browser logging to accommodate n-args
Update in-browser logging to accommodate n-args
JavaScript
isc
darkdarkdragon/ripple-lib,ripple/ripple-lib,ripple/ripple-lib,wilsonianb/ripple-lib,wilsonianb/ripple-lib,darkdarkdragon/ripple-lib,ripple/ripple-lib,darkdarkdragon/ripple-lib,wilsonianb/ripple-lib,ripple/ripple-lib
4b0c212b213b91fc37031c08aae5a30337728c79
public/script.js
public/script.js
'use strict'; /* * Tanura demo app. * * This is the main script of the app demonstrating Tanura's features. */ /** * Bootstrapping routine. */ window.onload = () => { console.log("Initializing Tanura..."); tanura.init( {video: true}, () => { console.log("Initialized."); // Example of how to handle Tanura's internally generated events. tanura.eventHandler.register( 'resize', () => console.log("Caught a resize.")); }); }
'use strict'; /* * Tanura demo app. * * This is the main script of the app demonstrating Tanura's features. */ /** * Bootstrapping routine. */ window.onload = () => { console.log("Initializing Tanura..."); tanura.init( {video: true}, () => { console.log("Initialized."); // Example of how to handle Tanura's internally generated events. tanura.eventHandler.register( 'client_resized', () => console.log("Caught a resize.")); }); }
Use the new event names in the demo.
Use the new event names in the demo.
JavaScript
agpl-3.0
theOtherNuvanda/Tanura,theOtherNuvanda/Tanura,theOtherNuvanda/Tanura
1a024423c0ca91047eaeaa2d7fdc397d5a3b0635
src/components/apply/SubmitButton.js
src/components/apply/SubmitButton.js
import React, { Component } from 'react' import PropTypes from 'prop-types' import api from 'api' import { LargeButton } from '@hackclub/design-system' class SubmitButton extends Component { static propTypes = { status: PropTypes.oneOf(['incomplete', 'complete', 'submitted']).isRequired, applicationId: PropTypes.number.isRequired, callback: PropTypes.func } state = { loading: false } handleSubmit = () => { const { status, applicationId, callback } = this.props this.setState({ loading: true }) // NOTE(@maxwofford): Give it 3 seconds of waiting to build up anticipation if (status !== 'complete') return null const startTime = Time.now api .post(`v1/new_club_applications/${applicationId}/submit`) .then(json => { callback(json) }) .catch(e => { alert(e.statusText) }) .finally(_ => { this.setState({ loading: false }) }) } render() { const { status } = this.props const { loading } = this.state return ( <LargeButton onClick={this.handleSubmit} bg={loading ? 'black' : status === 'submitted' ? 'success' : 'primary'} disabled={status !== 'complete' || loading} w={1} mt={2} mb={4} f={3} children={ status === 'submitted' ? 'We’ve recieved your application' : 'Submit your application' } /> ) } } export default SubmitButton
import React, { Component } from 'react' import PropTypes from 'prop-types' import api from 'api' import { LargeButton } from '@hackclub/design-system' class SubmitButton extends Component { static propTypes = { status: PropTypes.oneOf(['incomplete', 'complete', 'submitted']).isRequired, applicationId: PropTypes.number.isRequired, callback: PropTypes.func } state = { loading: false } handleSubmit = () => { const { status, applicationId, callback } = this.props this.setState({ loading: true }) if (status !== 'complete') return null // NOTE(@maxwofford): Give it 3 seconds of waiting to build up anticipation setTimeout(() => { api .post(`v1/new_club_applications/${applicationId}/submit`) .then(json => { callback(json) }) .catch(e => { alert(e.statusText) }) .finally(_ => { this.setState({ loading: false }) }) }, 3000) } render() { const { status } = this.props const { loading } = this.state return ( <LargeButton onClick={this.handleSubmit} bg={loading ? 'black' : status === 'submitted' ? 'success' : 'primary'} disabled={status !== 'complete' || loading} w={1} mt={2} mb={4} f={3} children={ status === 'submitted' ? 'We’ve recieved your application' : 'Submit your application' } /> ) } } export default SubmitButton
Add 3 second delay to application submission
Add 3 second delay to application submission
JavaScript
mit
hackclub/website,hackclub/website,hackclub/website
faa0e6ac15aca4dbae679cc20da587b4254f91ed
src/chrome/notification.js
src/chrome/notification.js
export class Notification { /** * @typedef NotificationOptions * @property {string} title * @property {string} message * @property {('basic'|'sms')} [type='basic'] */ /** * * @param {NotificationOptions} options */ constructor(options) { this.read = false; this.title = options.title; this.message = options.message; } /** * Converts the notification to a JSON object * @return {object} */ toJSON() { return { read: false, title: this.title, message: this.message, }; } }
export class Notification { /** * @typedef NotificationData * @property {boolean} [read] * @property {string} title * @property {string} message * @property {('basic'|'sms')} [type='basic'] */ /** * * @param {NotificationData} data */ constructor(data) { this.read = 'read' in data ? data.read : false; this.title = data.title; this.message = data.message; } /** * Converts the notification to a JSON object * @return {object} */ toJSON() { return { read: this.read, title: this.title, message: this.message, }; } static fromJSON(json) { return new Notification(json); } }
Add fromJSON, fix bug in toJSON
Add fromJSON, fix bug in toJSON
JavaScript
mit
nextgensparx/quantum-router,nextgensparx/quantum-router
067de672c56f6e61d0563bf2deac4a0b67a8f8e4
src/components/apply/SubmitButton.js
src/components/apply/SubmitButton.js
import React, { Component } from 'react' import api from 'api' import storage from 'storage' import { LargeButton } from '@hackclub/design-system' class SubmitButton extends Component { constructor(props) { super(props) this.handleSubmit = this.handleSubmit.bind(this) } handleSubmit() { const { status, applicationId, callback } = this.props if (status !== 'complete') { return null } api .post(`v1/new_club_applications/${applicationId}/submit`, { authToken: storage.get('authToken') }) .then(json => { callback(json) alert('Your application has been submitted!') }) .catch(e => { alert(e.statusText) }) } render() { // this.updateState() // I'm trying to update the update button state when an application is reset const { status } = this.props // incomplete, complete, submitted return ( <LargeButton onClick={this.handleSubmit} bg={status === 'submitted' ? 'accent' : 'primary'} disabled={status !== 'complete'} w={1} mb={2} > {status === 'submitted' ? 'We’ve recieved your application' : 'Submit your application'} </LargeButton> ) } } export default SubmitButton
import React, { Component } from 'react' import api from 'api' import storage from 'storage' import { LargeButton } from '@hackclub/design-system' class SubmitButton extends Component { constructor(props) { super(props) this.handleSubmit = this.handleSubmit.bind(this) } handleSubmit() { const { status, applicationId, callback } = this.props if (status !== 'complete') { return null } api .post(`v1/new_club_applications/${applicationId}/submit`, { authToken: storage.get('authToken') }) .then(json => { callback(json) }) .catch(e => { alert(e.statusText) }) } render() { // this.updateState() // I'm trying to update the update button state when an application is reset const { status } = this.props // incomplete, complete, submitted return ( <LargeButton onClick={this.handleSubmit} bg={status === 'submitted' ? 'accent' : 'primary'} disabled={status !== 'complete'} w={1} mb={2} > {status === 'submitted' ? 'We’ve recieved your application' : 'Submit your application'} </LargeButton> ) } } export default SubmitButton
Remove alert on application submission
Remove alert on application submission
JavaScript
mit
hackclub/website,hackclub/website,hackclub/website
87fd189a152a926ba4a5b66bcdc70f09e7e6f6ec
js/turducken.js
js/turducken.js
"use strict"; function User( fName, lName) { this.fName = fName; this.lName = lName; //this.img = img; //need to add images and urls... this.posts = []; } User.prototype.newPost = function( content, socMedia ) { this.posts.push( new Post( content, socMedia )); } function pushToLocalStorage( user ) { var userString = JSON.stringify( user ); localStorage.setItem('user', userString); console.log("pushed " + userString); } function getFromLocalStorage( ) { var userString = localStorage.getItem('user'); var user = JSON.parse(userString); if ( user ){ console.log( user.posts); }; } User.prototype.render = function() { console.table( this.posts ); // var row = document.createElement( 'tr' ); // createCell( 'td', this.posts.content, row ); // for (var i = 0; i < times.length; i++) { // createCell( 'td', this.posts.content, row ); // } // table.appendChild( row ); } // function createCell( cellType, content, row ) { // var cell = document.createElement( cellType ); // cell.innerText = content; // row.appendChild( cell ); // } function Post( content, socMedia ){ this.content = content; this.socMedia = socMedia; this.time = new Date().getTime(); } function init(){ populate(); bensonwigglepuff.render(); pushToLocalStorage( bensonwigglepuff ); getFromLocalStorage( bensonwigglepuff ); } window.addEventListener("load", init);
"use strict"; function User( fName, lName) { this.fName = fName; this.lName = lName; //this.img = img; //need to add images and urls... this.posts = []; } User.prototype.newPost = function( content, socMedia ) { this.posts.push( new Post( content, socMedia )); } User.prototype.render = function() { console.table( this.posts ); } function Post( content, socMedia ){ this.content = content; this.socMedia = socMedia; this.time = new Date().getTime(); } function pushToLocalStorage( user ) { var userString = JSON.stringify( user ); localStorage.setItem('user', userString); console.log("pushed " + userString); } function getFromLocalStorage( ) { var userString = localStorage.getItem('user'); var user = JSON.parse(userString); if ( user ){ console.log( user.posts); }; } function init(){ populate(); bensonwigglepuff.render(); pushToLocalStorage( bensonwigglepuff ); getFromLocalStorage( bensonwigglepuff ); } window.addEventListener("load", init);
Reorder functions to align with execution flow.
Reorder functions to align with execution flow.
JavaScript
mit
sevfitz/turducken,sevfitz/turducken
8885b2f7712407d05d677b2c03822a40843509aa
js/calci.js
js/calci.js
$(document).ready(function() { $('.key').click(function() { var number = $(this).text(); $('#preview').append(number); }); });
function handleInput(key) { $('#preview').append(key); } $(document).ready(function() { $('.key').click(function() { var key = $(this).text(); if(key == "0") { if($('#preview').html() != "0") { handleInput(key); } } else { handleInput(key); } }); });
Handle edge cases with zero key
Handle edge cases with zero key
JavaScript
mit
CodeAstra/calculator,CodeAstra/calculator
bd87fe2da4bbf994ad72226de12c00ecf01223a2
src/client/sendMessages.js
src/client/sendMessages.js
'use strict'; /* This declares the function that will send a message */ function sendMessage(e) { e.preventDefault(); const inputNode = e.target.message; const message = inputNode.value; console.log("Sending message:", message); // Clear node inputNode.value = ''; // Send the message const xhr = new XMLHttpRequest(); xhr.onload = (e) => { const response = xhr.response; console.log(response); } xhr.addEventListener("error", (e) => { console.log(e); }); xhr.open("POST", config.hostUrl); xhr.setRequestHeader("Content-type", "text/plain"); xhr.send(message); } function initializeForm() { const form = document.getElementsByTagName('form')[0]; form.addEventListener('submit', sendMessage); } initializeForm();
'use strict'; /* This declares the function that will send a message */ function sendMessage(e) { e.preventDefault(); const inputNode = e.target.message; const message = inputNode.value + '\n'; console.log("Sending message:", message); // Clear node inputNode.value = ''; // Send the message const xhr = new XMLHttpRequest(); xhr.onload = (e) => { const response = xhr.response; console.log(response); } xhr.addEventListener("error", (e) => { console.log(e); }); xhr.open("POST", config.hostUrl); xhr.setRequestHeader("Content-type", "text/plain"); xhr.send(message); } function initializeForm() { const form = document.getElementsByTagName('form')[0]; form.addEventListener('submit', sendMessage); } initializeForm();
Add newline to all sent messages
Add newline to all sent messages
JavaScript
mit
The1502Initiative/Instantaneous,The1502Initiative/Instantaneous,The1502Initiative/Instantaneous
f262509674196d05fc929b5b7c111a3a66f6f92c
app/actions/asyncActions.js
app/actions/asyncActions.js
import AsyncQueue from '../utils/asyncQueueStructures'; let asyncQueue = new AsyncQueue(); const endAsync = () => { return { type: 'ASYNC_INACTIVE' }; }; const callAsync = (dispatchFn, delay = 500, dispatchEnd, newState) => { if (!asyncQueue.size) { asyncQueue.listenForEnd(dispatchEnd); } asyncQueue.add(dispatchFn, delay, newState); return { type: 'ASYNC_ACTIVE' }; }; const setDelay = (newDelay) => { return { type: 'SET_DELAY', newDelay }; }; export default { callAsync, endAsync, setDelay };
import AsyncQueue from '../utils/asyncQueueStructures'; let asyncQueue = new AsyncQueue(); const endAsync = () => ({ type: 'ASYNC_INACTIVE' }); const startAsync = () => ({ type: 'ASYNC_ACTIVE' }); const callAsync = (dispatchFn, newState) => (dispatch, getState) => { if (!asyncQueue.size) { asyncQueue.listenForEnd(dispatch.bind(null, endAsync)); } asyncQueue.add(dispatchFn, getState().async.delay, newState); dispatch(startAsync()); }; const setDelay = (newDelay) => { return { type: 'SET_DELAY', newDelay }; }; export default { callAsync, endAsync, setDelay, startAsync };
Use thunx to access delay state
Use thunx to access delay state
JavaScript
mit
ivtpz/brancher,ivtpz/brancher
07f4d6e7ab4899cb1b85f12e9b0b05c0c0171341
src/community/community.js
src/community/community.js
import sqlite from 'sqlite' import winston from 'winston' export default class Community { static async init() { if (this.db) { return } this.db = await sqlite.open('/data/community.sqlite3').catch(winston.error) await this.db .run('CREATE TABLE IF NOT EXISTS villagers (guildId INTEGER, userId INTEGER, bnetServer TEXT, bnetId TEXT, PRIMARY KEY(guildId, userId, bnetServer))') .catch(winston.error) } }
import sqlite from 'sqlite' import winston from 'winston' export default class Community { static async init() { if (this.db) { return } this.db = await sqlite.open('/data/community.sqlite3').catch(winston.error) await this.db .run('CREATE TABLE IF NOT EXISTS villagers (guildId INTEGER, userId INTEGER, bnetServer TEXT, bnetId TEXT, PRIMARY KEY(guildId, userId, bnetServer))') .catch(winston.error) await this.db .run('CREATE TABLE IF NOT EXISTS quests (guildId INTEGER, userId INTEGER, bnetServer TEXT, bnetId TEXT, createdAt INTEGER, PRIMARY KEY(guildId, userId, bnetServer))') .catch(winston.error) setTimeout(async () => { await this.dropOldQuests() }, (10 * 60 * 1000)) } static async dropOldQuests() { winston.verbose('Auto-deleting quests that more than 1 day old.') const oneDayAgo = new Date() oneDayAgo.setDate(oneDayAgo.getDate() + 1) const oldestTimestamp = Math.floor(oneDayAgo / 1000) await this.db.all('DELETE FROM quests WHERE createdAt < ?', oldestTimestamp) } }
Add automated, timed removal of quests
Add automated, timed removal of quests
JavaScript
mit
tinnvec/stonebot,tinnvec/stonebot
55c074a2c627187327dd98800d9524a9e725cb95
src/components/HomePage.js
src/components/HomePage.js
import React from 'react'; import {browserHistory} from 'react-router' import Login from './Login'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as actions from '../actions/LoginActions'; import {AUTHENTICATED, DEFAULT, ERROR, LOADING} from '../constants/loginStates' export const HomePage = (props) => { let onLogin = phone => { props.actions.login(phone) } console.log(props.loginState) if (props.loginState === AUTHENTICATED) { browserHistory.push('/status') } return ( <div> <Login error={props.errorMessage} onClick={onLogin}/> </div> ); }; function mapStateToProps(state, ownprops) { const errorMessage = 'Login failed try again' return { data: state.loginReducer, loginState: state.loginReducer.loginState, errorMessage: state.loginReducer.loginState === ERROR ? errorMessage : null }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actions, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(HomePage);
import React from 'react'; import {browserHistory} from 'react-router' import Login from './Login'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as actions from '../actions/LoginActions'; import {AUTHENTICATED, DEFAULT, ERROR, LOADING} from '../constants/loginStates' import CircularProgress from 'material-ui/CircularProgress'; export const HomePage = (props) => { let onLogin = phone => { props.actions.login(phone) } console.log(props.loginState) if (props.loginState === AUTHENTICATED) { browserHistory.push('/status') } return ( <div> <div style={props.spinnerStyles}> <CircularProgress /> </div> <Login error={props.errorMessage} onClick={onLogin}/> </div> ); }; function mapStateToProps(state, ownprops) { const errorMessage = 'Login failed try again' return { data: state.loginReducer, loginState: state.loginReducer.loginState, errorMessage: state.loginReducer.loginState === ERROR ? errorMessage : null, spinnerStyles: { display: state.loginReducer.loginState === LOADING ? 'block' : 'hidden' } } } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actions, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(HomePage);
Add spinner when loggin in
Add spinner when loggin in
JavaScript
mit
nathejk/status-app,nathejk/status-app
443c0f43039d6fd1fda9760d5fb2570f2a930ebd
packages/stockflux-watchlist/public/notificationHandler.js
packages/stockflux-watchlist/public/notificationHandler.js
/*eslint-disable-next-line no-unused-vars*/ function onNotificationMessage(message) { document.getElementById('symbol').innerHTML = message.symbol; document.getElementById('message').innerHTML = message.messageText; document.getElementById('watchlist-name').innerHTML = message.watchlistName ? ' ' + message.watchlistName + ' ' : ' '; const imageSrc = message.alreadyInWatchlist ? 'ArrowUp.png' : 'CardIcon.png'; const image = document.getElementById('icon'); image.src = imageSrc; image.className = message.alreadyInWatchlist ? 'arrow-up' : 'card-icon'; }
// eslint-disable-next-line no-unused-vars function onNotificationMessage(message) { document.getElementById('symbol').innerHTML = message.symbol; document.getElementById('message').innerHTML = message.messageText; document.getElementById('watchlist-name').innerHTML = message.watchlistName ? ' ' + message.watchlistName + ' ' : ' '; const imageSrc = message.alreadyInWatchlist ? 'ArrowUp.png' : 'CardIcon.png'; const image = document.getElementById('icon'); image.src = imageSrc; image.className = message.alreadyInWatchlist ? 'arrow-up' : 'card-icon'; }
Change multi-line comment to single-line
Change multi-line comment to single-line
JavaScript
mit
owennw/OpenFinD3FC,ScottLogic/bitflux-openfin,owennw/OpenFinD3FC,ScottLogic/StockFlux,ScottLogic/StockFlux,ScottLogic/bitflux-openfin
aa94224f57fcd86704ff01ee1c7af299a75c95f8
lib/services/alter-items.js
lib/services/alter-items.js
const errors = require('@feathersjs/errors'); const getItems = require('./get-items'); const replaceItems = require('./replace-items'); module.exports = function (func) { if (!func) { func = () => {}; } if (typeof func !== 'function') { throw new errors.BadRequest('Function required. (alter)'); } return context => { let items = getItems(context); const isArray = Array.isArray(items); (isArray ? items : [items]).forEach( (item, index) => { const result = func(item, context); if (result != null) { if (isArray) { items[index] = result; } else { items = result; } } } ); const isDone = replaceItems(context, items); if (!isDone || typeof isDone.then !== 'function') { return context; } return isDone.then(() => context); }; };
const errors = require('@feathersjs/errors'); const getItems = require('./get-items'); const replaceItems = require('./replace-items'); module.exports = function (func) { if (!func) { func = () => {}; } if (typeof func !== 'function') { throw new errors.BadRequest('Function required. (alter)'); } return context => { let items = getItems(context); const isArray = Array.isArray(items); (isArray ? items : [items]).forEach( (item, index) => { const result = func(item, context); if (typeof result === 'object' && result !== null) { if (isArray) { items[index] = result; } else { items = result; } } } ); const isDone = replaceItems(context, items); if (!isDone || typeof isDone.then !== 'function') { return context; } return isDone.then(() => context); }; };
Improve alterItems: better null-check for the returned value
Improve alterItems: better null-check for the returned value
JavaScript
mit
feathersjs/feathers-hooks-common
ffb497ac013b005aff799cb4523e9b772519636b
connectors/amazon-alexa.js
connectors/amazon-alexa.js
'use strict'; Connector.playerSelector = '#d-content'; Connector.getArtistTrack = () => { if (isPlayingLiveRadio()) { let songTitle = $('.d-queue-info .song-title').text(); return Util.splitArtistTrack(songTitle); } let artist = $('#d-info-text .d-sub-text-1').text(); let track = $('#d-info-text .d-main-text').text(); return { artist, track }; }; Connector.albumSelector = '#d-info-text .d-sub-text-2'; Connector.isPlaying = () => $('#d-primary-control .play').size() === 0; function isPlayingLiveRadio() { return $('#d-secondary-control-left .disabled').size() === 1 && $('#d-secondary-control-right .disabled').size() === 1; }
'use strict'; Connector.playerSelector = '#d-content'; Connector.remainingTimeSelector = '.d-np-time-display.remaining-time'; Connector.currentTimeSelector = '.d-np-time-display.elapsed-time'; Connector.getDuration = () => { let elapsed = Util.stringToSeconds($(Connector.currentTimeSelector).text()); let remaining = -Util.stringToSeconds($(Connector.remainingTimeSelector).text()); return (remaining + elapsed); }; Connector.getRemainingTime = () => { let remaining = -Util.stringToSeconds($(Connector.remainingTimeSelector).text()); return remaining; }; Connector.getArtistTrack = () => { if (isPlayingLiveRadio()) { let songTitle = $('.d-queue-info .song-title').text(); return Util.splitArtistTrack(songTitle); } let artist = $('#d-info-text .d-sub-text-1').text(); let track = $('#d-info-text .d-main-text').text(); return { artist, track }; }; Connector.albumSelector = '#d-info-text .d-sub-text-2'; Connector.isPlaying = () => { let songProgress = $('.d-np-progress-slider .d-slider-container .d-slider-track').attr('aria-valuenow'); let duration = Connector.getDuration(); // The app doesn't update the progress bar or time remaining straight away (and starts counting down from an hour). This is a workaround to avoid detecting an incorrect duration time. if (duration > 3600 || songProgress == 100) { return false; } return $('#d-primary-control .play').size() === 0; } function isPlayingLiveRadio() { return $('#d-secondary-control-left .disabled').size() === 1 && $('#d-secondary-control-right .disabled').size() === 1; }
Add duration parsing to Amazon Alexa connector
Add duration parsing to Amazon Alexa connector
JavaScript
mit
david-sabata/web-scrobbler,carpet-berlin/web-scrobbler,david-sabata/web-scrobbler,carpet-berlin/web-scrobbler,galeksandrp/web-scrobbler,galeksandrp/web-scrobbler,fakelbst/Chrome-Last.fm-Scrobbler,alexesprit/web-scrobbler,inverse/web-scrobbler,fakelbst/Chrome-Last.fm-Scrobbler,inverse/web-scrobbler,alexesprit/web-scrobbler
5fbfc2f76f3365c75ab2523d7807a4f3dc89a288
omod/src/main/webapp/resources/scripts/services/visitService.js
omod/src/main/webapp/resources/scripts/services/visitService.js
angular.module('visitService', ['ngResource', 'uicommons.common']) .factory('Visit', function($resource) { return $resource("/" + OPENMRS_CONTEXT_PATH + "/ws/rest/v1/visit/:uuid", { uuid: '@uuid' },{ query: { method:'GET', isArray:false } // OpenMRS RESTWS returns { "results": [] } }); }) .factory('VisitService', function(Visit) { return { /** * Fetches Visits * * @param params to search against * @returns $promise of array of matching Visits (REST ref representation by default) */ getVisits: function(params) { return Visit.query(params).$promise.then(function(res) { return res.results; }); }, // if visit has uuid property this will update, else it will create new saveVisit: function(visit) { return new Visit(visit).$save(); } } });
angular.module('visitService', ['ngResource', 'uicommons.common']) .factory('Visit', function($resource) { return $resource("/" + OPENMRS_CONTEXT_PATH + "/ws/rest/v1/visit/:uuid", { uuid: '@uuid' },{ query: { method:'GET', isArray:false } // OpenMRS RESTWS returns { "results": [] } }); }) .factory('VisitService', function(Visit, $resource) { return { /** * Fetches Visits * * @param params to search against * @returns $promise of array of matching Visits (REST ref representation by default) */ getVisits: function(params) { return Visit.query(params).$promise.then(function(res) { return res.results; }); }, // if visit has uuid property this will update, else it will create new saveVisit: function(visit) { return new Visit(visit).$save(); }, visitAttributeResourceFor: function(visit) { return $resource("/" + OPENMRS_CONTEXT_PATH + "/ws/rest/v1/visit/:visitUuid/attribute/:uuid", { visitUuid: visit.uuid, uuid: '@uuid' },{ query: { method:'GET', isArray:false } // OpenMRS RESTWS returns { "results": [] } }); } } });
Support accessing visit/attribute sub-resource via REST
Support accessing visit/attribute sub-resource via REST
JavaScript
mpl-2.0
jdegraft/openmrs-module-uicommons,yadamz/first-module,yadamz/first-module,jdegraft/openmrs-module-uicommons,jdegraft/openmrs-module-uicommons,yadamz/first-module,yadamz/first-module,jdegraft/openmrs-module-uicommons
4326d2baf1350e19c87db457a1e170e73bd0a11d
src/js/streams/stream-user.js
src/js/streams/stream-user.js
YUI.add("stream-user", function(Y) { "use strict"; var falco = Y.namespace("Falco"), streams = Y.namespace("Falco.Streams"), User; User = function() {}; User.prototype = { _create : function() { var stream; stream = falco.twitter.stream("user", { with : "followings" }); stream.on("tweet", this._tweet.bind(this)); stream.on("friends", this._friends.bind(this)); this._stream = stream; }, _tweet : function(data) { this.fire("tweet", { tweet : data, src : "user" }); }, _friends : function(data) { this.fire("friends", data.friends.map(function(id) { return { id : id }; })); } }; Y.augment(User, streams.Base); streams.User = User; streams.user = new User(); }, "@VERSION@", { requires : [ // YUI "oop", "event-custom", // Streams "stream-base" ] });
YUI.add("stream-user", function(Y) { "use strict"; var falco = Y.namespace("Falco"), streams = Y.namespace("Falco.Streams"), User; User = function() {}; User.prototype = { _create : function() { var stream; stream = falco.twitter.stream("user"); stream.on("tweet", this._tweet.bind(this)); stream.on("friends", this._friends.bind(this)); this._stream = stream; }, _tweet : function(data) { this.fire("tweet", { tweet : data, src : "user" }); }, _friends : function(data) { this.fire("friends", data.friends.map(function(id) { return { id : id }; })); } }; Y.augment(User, streams.Base); streams.User = User; streams.user = new User(); }, "@VERSION@", { requires : [ // YUI "oop", "event-custom", // Streams "stream-base" ] });
Remove unnecessary param, it's the default
Remove unnecessary param, it's the default
JavaScript
mit
tivac/falco,tivac/falco
c41ba3df26018ff84e6c5e73f06c7df36e508243
src/js/utils/ValidatorUtil.js
src/js/utils/ValidatorUtil.js
var ValidatorUtil = { isDefined: function (value) { return value != null && value !== '' || typeof value === 'number'; }, isEmail: function (email) { return email != null && email.length > 0 && !/\s/.test(email) && /.+@.+\..+/ .test(email); }, isEmpty: function (data) { if (typeof data === 'number' || typeof data === 'boolean') { return false; } if (typeof data === 'undefined' || data === null) { return true; } if (typeof data.length !== 'undefined') { return data.length === 0; } return Object.keys(data).reduce(function (memo, key) { if (data.hasOwnProperty(key)) { memo++; } return memo; }, 0) === 0; }, isInteger: function (value) { const number = parseFloat(value); return Number.isInteger(number); }, isNumber: function (value) { const number = parseFloat(value); return !Number.isNaN(number) && Number.isFinite(number); }, isNumberInRange: function (value, range = {}) { const {min = 0, max = Number.POSITIVE_INFINITY} = range; const number = parseFloat(value); return !Number.isNaN(number) && number >= min && number <= max; } }; module.exports = ValidatorUtil;
var ValidatorUtil = { isDefined: function (value) { return value != null && value !== '' || typeof value === 'number'; }, isEmail: function (email) { return email != null && email.length > 0 && !/\s/.test(email) && /.+@.+\..+/ .test(email); }, isEmpty: function (data) { if (typeof data === 'number' || typeof data === 'boolean') { return false; } if (typeof data === 'undefined' || data === null) { return true; } if (typeof data.length !== 'undefined') { return data.length === 0; } return Object.keys(data).reduce(function (memo, key) { if (data.hasOwnProperty(key)) { memo++; } return memo; }, 0) === 0; }, isInteger: function (value) { return ValidatorUtil.isNumber(value) && Number.isInteger(parseFloat(value)); }, isNumber: function (value) { const number = parseFloat(value); return !Number.isNaN(number) && Number.isFinite(number); }, isNumberInRange: function (value, range = {}) { const {min = 0, max = Number.POSITIVE_INFINITY} = range; const number = parseFloat(value); return ValidatorUtil.isNumber(value) && number >= min && number <= max; } }; module.exports = ValidatorUtil;
Use is number util to test input
Use is number util to test input
JavaScript
apache-2.0
dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui
b7f8dfb12f79012e5ded0b14684ad75ae7dc1821
lib/main.js
lib/main.js
// Define keyboard shortcuts for showing and hiding a custom panel. var { Cc, Ci } = require("chrome"); var { Hotkey } = require("hotkeys"); var panel = require("panel"); var timers = require("timers"); var data = require("self").data; var osString = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).OS; var osWarnFile; // Load the right warning if (osString == "Darwin") { osWarnFile = "warnmac.html"; } else { osWarnFile = "warn.html"; } // Create the panel to show the warning var myPanel = panel.Panel({ width: 300, height: 65, contentURL: data.url(osWarnFile), }); // Display the warning function showPanel() { myPanel.show(); timers.setTimeout(function() { myPanel.hide(); }, 2000); } // Handle the keypress var showHotKey = Hotkey({ combo: "accel-q", onPress: function() { // We're already showing the warning if (myPanel.isShowing) { myPanel.hide(); Cc['@mozilla.org/toolkit/app-startup;1'] .getService(Ci.nsIAppStartup) .quit(Ci.nsIAppStartup.eAttemptQuit) } // Show the warning since we didn't quit yet showPanel(); } });
// Define keyboard shortcuts for showing and hiding a custom panel. var { Cc, Ci } = require("chrome"); var { Hotkey } = require("hotkeys"); var panel = require("panel"); var timers = require("timers"); var data = require("self").data; var runtime = require("runtime"); var osString = runtime.OS; var osWarnFile; // Load the right warning if (osString === "Darwin") { osWarnFile = "warnmac.html"; } else { osWarnFile = "warn.html"; } // Create the panel to show the warning var myPanel = panel.Panel({ width: 300, height: 65, contentURL: data.url(osWarnFile), }); // Display the warning function showPanel() { myPanel.show(); timers.setTimeout(function() { myPanel.hide(); }, 2000); } // Handle the keypress var showHotKey = Hotkey({ combo: "accel-q", onPress: function() { // We're already showing the warning if (myPanel.isShowing) { myPanel.hide(); Cc['@mozilla.org/toolkit/app-startup;1'] .getService(Ci.nsIAppStartup) .quit(Ci.nsIAppStartup.eAttemptQuit) } // Show the warning since we didn't quit yet showPanel(); } });
Use the interface from add-on sdk for OS
Use the interface from add-on sdk for OS
JavaScript
mit
rhelmer/warn-before-quit,rhelmer/warn-before-quit,nigelbabu/warn-before-quit,nigelbabu/warn-before-quit
a75fef48bfb440a22fdc9605d4e677b87ebf290f
local-cli/core/Constants.js
local-cli/core/Constants.js
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow * @format */ 'use strict'; const ASSET_REGISTRY_PATH = 'react-native/Libraries/Image/AssetRegistry'; module.exports = {ASSET_REGISTRY_PATH};
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow * @format */ 'use strict'; const ASSET_REGISTRY_PATH = 'react-native/Libraries/Image/AssetRegistry'; const ASSET_SOURCE_RESOLVER_PATH = 'react-native/Libraries/Image/AssetSourceResolver'; module.exports = { ASSET_REGISTRY_PATH, ASSET_SOURCE_RESOLVER_PATH, };
Add code for generating remote assets
Add code for generating remote assets Reviewed By: davidaurelio Differential Revision: D6201839 fbshipit-source-id: 78c81eae03c6137ba9bbe33cd7aab8b87020f8d2
JavaScript
bsd-3-clause
jevakallio/react-native,Bhullnatik/react-native,exponentjs/react-native,facebook/react-native,ptmt/react-native-macos,ptmt/react-native-macos,pandiaraj44/react-native,hoastoolshop/react-native,pandiaraj44/react-native,kesha-antonov/react-native,facebook/react-native,hammerandchisel/react-native,hoangpham95/react-native,exponentjs/react-native,kesha-antonov/react-native,janicduplessis/react-native,arthuralee/react-native,facebook/react-native,janicduplessis/react-native,arthuralee/react-native,exponent/react-native,hoastoolshop/react-native,janicduplessis/react-native,hoastoolshop/react-native,exponent/react-native,exponentjs/react-native,dikaiosune/react-native,facebook/react-native,jevakallio/react-native,pandiaraj44/react-native,jevakallio/react-native,ptmt/react-native-macos,arthuralee/react-native,exponentjs/react-native,kesha-antonov/react-native,rickbeerendonk/react-native,arthuralee/react-native,exponentjs/react-native,myntra/react-native,dikaiosune/react-native,exponent/react-native,exponentjs/react-native,kesha-antonov/react-native,exponentjs/react-native,hoastoolshop/react-native,hoangpham95/react-native,kesha-antonov/react-native,cdlewis/react-native,dikaiosune/react-native,myntra/react-native,hoangpham95/react-native,rickbeerendonk/react-native,hammerandchisel/react-native,hoastoolshop/react-native,javache/react-native,pandiaraj44/react-native,cdlewis/react-native,hoangpham95/react-native,exponent/react-native,Bhullnatik/react-native,jevakallio/react-native,ptmt/react-native-macos,facebook/react-native,myntra/react-native,exponentjs/react-native,jevakallio/react-native,kesha-antonov/react-native,janicduplessis/react-native,hoastoolshop/react-native,janicduplessis/react-native,arthuralee/react-native,myntra/react-native,dikaiosune/react-native,hoangpham95/react-native,exponent/react-native,ptmt/react-native-macos,hammerandchisel/react-native,facebook/react-native,ptmt/react-native-macos,exponent/react-native,pandiaraj44/react-native,javache/react-native,rickbeerendonk/react-native,ptmt/react-native-macos,jevakallio/react-native,pandiaraj44/react-native,pandiaraj44/react-native,ptmt/react-native-macos,cdlewis/react-native,rickbeerendonk/react-native,hammerandchisel/react-native,cdlewis/react-native,Bhullnatik/react-native,myntra/react-native,janicduplessis/react-native,dikaiosune/react-native,kesha-antonov/react-native,facebook/react-native,myntra/react-native,Bhullnatik/react-native,hoangpham95/react-native,myntra/react-native,jevakallio/react-native,facebook/react-native,hammerandchisel/react-native,jevakallio/react-native,cdlewis/react-native,hoastoolshop/react-native,rickbeerendonk/react-native,dikaiosune/react-native,rickbeerendonk/react-native,Bhullnatik/react-native,janicduplessis/react-native,exponent/react-native,kesha-antonov/react-native,cdlewis/react-native,myntra/react-native,hammerandchisel/react-native,hoangpham95/react-native,rickbeerendonk/react-native,hammerandchisel/react-native,exponent/react-native,facebook/react-native,janicduplessis/react-native,cdlewis/react-native,Bhullnatik/react-native,javache/react-native,cdlewis/react-native,javache/react-native,javache/react-native,cdlewis/react-native,Bhullnatik/react-native,rickbeerendonk/react-native,Bhullnatik/react-native,myntra/react-native,kesha-antonov/react-native,dikaiosune/react-native,javache/react-native,pandiaraj44/react-native,hoangpham95/react-native,rickbeerendonk/react-native,hammerandchisel/react-native,javache/react-native,javache/react-native,dikaiosune/react-native,hoastoolshop/react-native,jevakallio/react-native,javache/react-native
12bfc2fdd9c1574eb37a68dc7b8fa9508b082118
lib/vector2d.js
lib/vector2d.js
class Vector2D { constructor(x, y) { this.x = x; this.y = y; } add(vec) { return new Vector2D(this.x + vec.x, this.y + vec.y); } multiply(factor) { return new Vector2D(this.x * factor, this.y * factor); } } Vector2D.fromPolar = function(deg, len) { let rad = deg * (180 / Math.PI), xf = Math.round(Math.cos(rad) * 1000) / 1000, yf = Math.round(Math.sin(rad) * 1000) / 1000; return new Vector2D(xf, yf).multiply(len); }; export default function Vecor2DFactory(...args) { return new Vector2D(...args); };
class Vector2D { constructor(x, y) { this.x = x; this.y = y; } add(vec) { return new Vector2D(this.x + vec.x, this.y + vec.y); } multiply(factor) { return new Vector2D(this.x * factor, this.y * factor); } length() { return Math.sqrt(this.x * this.x, this.y * this.y); } angle() { return Math.atan2(this.y, this.x) * (180 / Math.PI); } toPolar() { return [this.angle(), this.length()]; } } Vector2D.fromPolar = function(deg, len) { let rad = deg / (180 / Math.PI), xf = Math.round(Math.cos(rad) * 1000) / 1000, yf = Math.round(Math.sin(rad) * 1000) / 1000; return new Vector2D(xf, yf).multiply(len); }; export default function Vecor2DFactory(...args) { return new Vector2D(...args); };
Add more functionality to vectors
Add more functionality to vectors
JavaScript
mit
190n/five.js
29a464500056d1b0c80e4056139931cb77dacd53
public/fastboot-is-mobile.js
public/fastboot-is-mobile.js
/* globals define, FastBoot */ (function() { define('ismobilejs', ['exports'], function(exports) { 'use strict'; let isMobileClass = FastBoot.require('ismobilejs'); // Change the context so that when isMobile internally sets the results of // the user agent tests to the current scope, it doesn't use the FastBoot // global scope, which is full of unnecessary stuff. return { default: isMobileClass.bind(exports) }; }); })();
/* globals define, FastBoot */ (function() { define('ismobilejs', ['exports'], function(exports) { 'use strict'; var isMobileClass = FastBoot.require('ismobilejs'); // Change the context so that when isMobile internally sets the results of // the user agent tests to the current scope, it doesn't use the FastBoot // global scope, which is full of unnecessary stuff. return { default: isMobileClass.bind(exports) }; }); })();
Fix strict mode typo in fastboot module export
Fix strict mode typo in fastboot module export
JavaScript
mit
sandydoo/ember-is-mobile,sandydoo/ember-is-mobile
fd5ee5b257ef44549c870abc620527dda9d4a358
src/mm-action/mm-action.js
src/mm-action/mm-action.js
/** * @license * Copyright (c) 2015 MediaMath Inc. All rights reserved. * This code may only be used under the BSD style license found at http://mediamath.github.io/strand/LICENSE.txt */ Polymer({ is: "mm-action", behaviors: [ StrandTraits.Stylable ], properties: { ver:{ type:String, value:"<<version>>", }, href: { type: String, value: false, reflectToAttribute: true }, underline: { type: Boolean, value: false, reflectToAttribute: true }, target: { type: String, value: "_self", reflectToAttribute: true }, disabled: { type: Boolean, value: false, reflectToAttribute: true } }, PRIMARY_ICON_COLOR: Colors.D0, ready: function() { // if there is an icon - colorize it: var items = Array.prototype.slice.call(Polymer.dom(this.$.icon).getDistributedNodes()); if (items.length) { items[0].setAttribute("primary-color", this.PRIMARY_ICON_COLOR); } }, updateClass: function(underline) { var o = {}; o["action"] = true; o["underline"] = underline; return this.classList(o); } });
/** * @license * Copyright (c) 2015 MediaMath Inc. All rights reserved. * This code may only be used under the BSD style license found at http://mediamath.github.io/strand/LICENSE.txt */ (function (scope) { scope.Action = Polymer({ is: "mm-action", behaviors: [ StrandTraits.Stylable ], properties: { ver:{ type:String, value:"<<version>>", }, href: { type: String, value: false, reflectToAttribute: true }, underline: { type: Boolean, value: false, reflectToAttribute: true }, target: { type: String, value: "_self", reflectToAttribute: true }, disabled: { type: Boolean, value: false, reflectToAttribute: true } }, PRIMARY_ICON_COLOR: Colors.D0, ready: function() { // if there is an icon - colorize it: var items = Array.prototype.slice.call(Polymer.dom(this.$.icon).getDistributedNodes()); if (items.length) { items[0].setAttribute("primary-color", this.PRIMARY_ICON_COLOR); } }, updateClass: function(underline) { var o = {}; o["action"] = true; o["underline"] = underline; return this.classList(o); } }); })(window.Strand = window.Strand || {});
Add correct IIF and scope
Add correct IIF and scope
JavaScript
bsd-3-clause
sassomedia/strand,anthonykoerber/strand,shuwen/strand,dlasky/strand,shuwen/strand,sassomedia/strand,anthonykoerber/strand,dlasky/strand
9b44e8f5367bf24b6d5c21d35f402bc0686c1383
src/modules/Application.js
src/modules/Application.js
class GelatoApplication extends Backbone.Model { constructor() { Backbone.$('body').prepend('<gelato-application></gelato-application>'); Backbone.$('gelato-application').append('<gelato-dialogs></gelato-dialogs>'); Backbone.$('gelato-application').append('<gelato-navbar></gelato-navbar>'); Backbone.$('gelato-application').append('<gelato-pages></gelato-pages>'); Backbone.$('gelato-application').append('<gelato-footer></gelato-footer>'); super(arguments); } getHeight() { return Backbone.$('gelato-application').height(); } getWidth() { return Backbone.$('gelato-application').width(); } isLandscape() { return this.getWidth() > this.getHeight(); } isPortrait() { return this.getWidth() <= this.getHeight(); } reload(forcedReload) { location.reload(forcedReload); } } Gelato = Gelato || {}; Gelato.Application = GelatoApplication;
class GelatoApplication extends Backbone.View { constructor(options) { options = options || {}; options.tagName = 'gelato-application'; super(options); } render() { $(document.body).prepend(this.el); this.$el.append('<gelato-navbar></gelato-navbar>'); this.$el.append('<gelato-pages></gelato-pages>'); this.$el.append('<gelato-footer></gelato-footer>'); this.$el.append('<gelato-dialogs></gelato-dialogs>'); return this; } getHeight() { return Backbone.$('gelato-application').height(); } getWidth() { return Backbone.$('gelato-application').width(); } isLandscape() { return this.getWidth() > this.getHeight(); } isPortrait() { return this.getWidth() <= this.getHeight(); } } Gelato = Gelato || {}; Gelato.Application = GelatoApplication;
Make application function more like a backbone view
Make application function more like a backbone view
JavaScript
mit
jernung/gelato,jernung/gelato,mcfarljw/gelato-framework,mcfarljw/backbone-gelato,mcfarljw/backbone-gelato,mcfarljw/gelato-framework
cc4f209f011639d4f6888a39e71b1145e58cf5c5
src/route/changelogs.js
src/route/changelogs.js
const router = require('express').Router(); const scraper = require('../service/scraper'); router.get('/', (req, res, next) => { const packageName = req.query.package; if (!packageName) { const err = new Error('Undefined query'); err.satus = 404; next(err); } scraper .scan(packageName) .then(result => { const changes = result.changes; res.json({ packageName, changes }); }) .catch(error => { const err = new Error('Could not request info'); err.status = 404; next(err); }); }); module.exports = router;
const router = require('express').Router(); const scraper = require('../service/scraper'); router.get('/:package/latest', (req, res, next) => { const packageName = req.params.package; if (!packageName) { const err = new Error('Undefined query'); err.satus = 404; next(err); } scraper .scan(packageName) .then(result => { const changes = result.changes; res.json({ packageName, changes }); }) .catch(error => { const err = new Error('Could not request info'); err.status = 404; next(err); }); }); module.exports = router;
Change package query from query param to path variable
Change package query from query param to path variable
JavaScript
mit
enric-sinh/android-changelog-api
b32f0a37a944afeda9d59eb8169dbad0419c5e0e
controllers/locale.js
controllers/locale.js
/* * @author Martin HΓΈgh <mh@mapcentia.com> * @copyright 2013-2018 MapCentia ApS * @license http://www.gnu.org/licenses/#AGPL GNU AFFERO GENERAL PUBLIC LICENSE 3 */ var express = require('express'); var router = express.Router(); router.get('/locale', function(request, response) { var lang = request.acceptsLanguages('en', 'en-US', 'da', 'da-DK'); if (lang) { if (lang === "en") { lang = "en-US"; } if (lang === "da") { lang = "da-DK"; } } else { lang = "en-US"; } lang = lang.replace("-","_"); response.set('Content-Type', 'application/javascript'); //response.send("window._vidiLocale='" + lang + "'"); response.send("var urlVars = (function getUrlVars() {var mapvars = {};var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {mapvars[key] = value;});return mapvars;})(); if (urlVars.locale !== undefined){window._vidiLocale=urlVars.locale.split('#')[0]} else {window._vidiLocale='" + lang + "'}"); }); module.exports = router;
/* * @author Martin HΓΈgh <mh@mapcentia.com> * @copyright 2013-2018 MapCentia ApS * @license http://www.gnu.org/licenses/#AGPL GNU AFFERO GENERAL PUBLIC LICENSE 3 */ var express = require('express'); var router = express.Router(); var ipaddr = require('ipaddr.js'); router.get('/locale', function(request, response) { var ip = ipaddr.process(request.ip).toString(); var lang = request.acceptsLanguages('en', 'en-US', 'da', 'da-DK'); if (lang) { if (lang === "en") { lang = "en-US"; } if (lang === "da") { lang = "da-DK"; } } else { lang = "en-US"; } lang = lang.replace("-","_"); response.set('Content-Type', 'application/javascript'); //response.send("window._vidiLocale='" + lang + "'"); response.send("window._vidiIp = '" + ip + "'; var urlVars = (function getUrlVars() {var mapvars = {};var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {mapvars[key] = value;});return mapvars;})(); if (urlVars.locale !== undefined){window._vidiLocale=urlVars.locale.split('#')[0]} else {window._vidiLocale='" + lang + "'}"); }); module.exports = router;
Return the clients IP address
Return the clients IP address
JavaScript
agpl-3.0
mapcentia/vidi,mapcentia/vidi,mapcentia/vidi,mapcentia/vidi
943bc6d05065524b158ac7fc3be450126db3a558
website/app/application/core/projects/project/provenance/wizard/show-template-details.js
website/app/application/core/projects/project/provenance/wizard/show-template-details.js
Application.Directives.directive("showTemplateDetails", showTemplateDetailsDirective); function showTemplateDetailsDirective() { return { restrict: "E", replace: true, scope: { template: "=template", }, controller: "showTemplateDetailsDirectiveController", templateUrl: "application/core/projects/project/provenance/wizard/show-template-details.html" }; } Application.Controllers.controller("showTemplateDetailsDirectiveController", ["$scope", showTemplateDetailsDirectiveController]); function showTemplateDetailsDirectiveController($scope) { }
Application.Directives.directive("showTemplateDetails", ["RecursionHelper", showTemplateDetailsDirective]); function showTemplateDetailsDirective(RecursionHelper) { return { restrict: "E", replace: true, scope: { template: "=template", }, controller: "showTemplateDetailsDirectiveController", templateUrl: "application/core/projects/project/provenance/wizard/show-template-details.html", compile: function(element) { return RecursionHelper.compile(element, function(scope, iElement, iAttrs, controller, transcludeFn) { }); } }; } Application.Controllers.controller("showTemplateDetailsDirectiveController", ["$scope", showTemplateDetailsDirectiveController]); function showTemplateDetailsDirectiveController($scope) { }
Allow directive to be called recursively.
Allow directive to be called recursively.
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
5ae8a55a75bef8a0af6d330842000152e2830c0e
lib/text.js
lib/text.js
exports._regExpRegExp = /^\/(.+)\/([im]?)$/; exports._lineRegExp = /\r\n|\r|\n/; exports.splitLines = function (text) { var lines = []; var match, line; while (match = exports._lineRegExp.exec(text)) { line = text.slice(0, match.index) + match[0]; text = text.slice(line.length); lines.push(line); } lines.push(text); return lines; }; exports.escapeRegExp = function (text) { return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }; exports.regExpIndexOf = function(str, regex, index) { index = index || 0; var offset = str.slice(index).search(regex); return (offset >= 0) ? (index + offset) : offset; }; exports.regExpLastIndexOf = function (str, regex, index) { if (index === 0 || index) str = str.slice(0, Math.max(0, index)); var i; var offset = -1; while ((i = str.search(regex)) !== -1) { offset += i + 1; str = str.slice(i + 1); } return offset; };
exports._regExpRegExp = /^\/(.+)\/([im]?)$/; exports._lineRegExp = /\r\n|\r|\n/; exports.splitLines = function (text) { var lines = []; var match, line; while (match = exports._lineRegExp.exec(text)) { line = text.slice(0, match.index) + match[0]; text = text.slice(line.length); lines.push(line); } lines.push(text); return lines; }; exports.regExpIndexOf = function(str, regex, index) { index = index || 0; var offset = str.slice(index).search(regex); return (offset >= 0) ? (index + offset) : offset; }; exports.regExpLastIndexOf = function (str, regex, index) { if (index === 0 || index) str = str.slice(0, Math.max(0, index)); var i; var offset = -1; while ((i = str.search(regex)) !== -1) { offset += i + 1; str = str.slice(i + 1); } return offset; };
Remove escapeRegExp in favor of lodash.escapeRegExp
Remove escapeRegExp in favor of lodash.escapeRegExp
JavaScript
mit
slap-editor/slap-util
2edfecbcd8b891a839e3ee36ed18d8052900d134
src/dispatchResponse.js
src/dispatchResponse.js
/** * @flow */ type ResData = { newStates: {[key: string]: string} }; /** * Encode the updated states, to send to the client. * * @param updatedStates {StatesObject} The updated states * @param encodeState {(string, any) => string} A function that will encode the state, of a given store, to be * passed over an HTTP request * * @return {ResData} The data to respond to the client with */ export function encode(updatedStates: StatesObject, encodeState: EncodeStateFunc): ResData { //TODO return {}; } /** * Decode the states from the server. * * @param response {ResData} The response form the server * @param decodeState {(string, string) => any} A function that will decode the state of a given store * * @return {StatesObject} The updated states */ export function decode(response: ResData, decodeState: DecodeStateFunc): StatesObject { //TODO return {}; }
/** * @flow */ type ResData = { newStates: {[key: string]: string} }; /** * Encode the updated states, to send to the client. * * @param updatedStates {StatesObject} The updated states * @param encodeState {(string, any) => string} A function that will encode the state, of a given store, to be * passed over an HTTP request * * @return {ResData} The data to respond to the client with */ export function encode(updatedStates: StatesObject, encodeState: EncodeStateFunc): ResData { const newStates = {}; for(let storeName in updatedStates) { const updatedState = updatedStates[storeName]; newStates[storeName] = encodeState(storeName, updatedState); } return { newStates }; } /** * Decode the states from the server. * * @param response {ResData} The response form the server * @param decodeState {(string, string) => any} A function that will decode the state of a given store * * @return {StatesObject} The updated states */ export function decode(response: ResData, decodeState: DecodeStateFunc): StatesObject { const { newStates } = response; const updatedStates = {}; for(let storeName in newStates) { const newState = newStates[storeName]; updatedStates[storeName] = decodeState(storeName, newState); } return updatedStates; }
Implement the Response's 'encode(...)' and 'decode(...)' Functions
Implement the Response's 'encode(...)' and 'decode(...)' Functions Implement 'encode(...)' and 'decode(...)' functions for the the response.
JavaScript
mit
nheyn/express-isomorphic-dispatcher
0692f1a02b2dd231b40f06dce5941fdf15feecac
packages/react-cookie/src/withCookies.js
packages/react-cookie/src/withCookies.js
import React, { Component } from 'react'; import { instanceOf, func } from 'prop-types'; import Cookies from 'universal-cookie'; import hoistStatics from 'hoist-non-react-statics'; export default function withCookies(WrapperComponent) { class Wrapper extends Component { static displayName = `withCookies(${Component.displayName || Component.name})`; static WrapperComponent = WrapperComponent; static propTypes = { wrappedComponentRef: func }; static contextTypes = { cookies: instanceOf(Cookies).isRequired }; constructor(props, context) { super(props); context.cookies.addChangeListener(this.onChange); } componentWillUnmount() { this.context.cookies.removeChangeListener(this.onChange); } onChange = () => { this.forceUpdate(); }; render() { const { wrappedComponentRef, ...remainingProps } = this.props; const allCookies = this.context.cookies.getAll(); return ( <WrapperComponent {...remainingProps} cookies={this.context.cookies} allCookies={allCookies} ref={wrappedComponentRef} /> ); } } return hoistStatics(Wrapper, WrapperComponent, { WrappedComponent: true }); }
import React, { Component } from 'react'; import { instanceOf, func } from 'prop-types'; import Cookies from 'universal-cookie'; import hoistStatics from 'hoist-non-react-statics'; export default function withCookies(WrapperComponent) { class Wrapper extends Component { static displayName = `withCookies(${WrapperComponent.displayName || WrapperComponent.name})`; static WrapperComponent = WrapperComponent; static propTypes = { wrappedComponentRef: func }; static contextTypes = { cookies: instanceOf(Cookies).isRequired }; constructor(props, context) { super(props); context.cookies.addChangeListener(this.onChange); } componentWillUnmount() { this.context.cookies.removeChangeListener(this.onChange); } onChange = () => { this.forceUpdate(); }; render() { const { wrappedComponentRef, ...remainingProps } = this.props; const allCookies = this.context.cookies.getAll(); return ( <WrapperComponent {...remainingProps} cookies={this.context.cookies} allCookies={allCookies} ref={wrappedComponentRef} /> ); } } return hoistStatics(Wrapper, WrapperComponent, { WrappedComponent: true }); }
Fix undefined name of component
Fix undefined name of component Fix minor misspel, `Component` is `React.Component` now, should use name of `WrapperComponent` in `displayName`
JavaScript
mit
eXon/react-cookie,reactivestack/cookies,reactivestack/cookies,reactivestack/cookies
2800cd66ab65cc464c5ddeb1a619a2ed9e254e35
src/update.js
src/update.js
// @flow export default function (el: HTMLTextAreaElement, headToCursor: string, cursorToTail: ?string) { const curr = el.value, // strA + strB1 + strC next = headToCursor + (cursorToTail || ''), // strA + strB2 + strC activeElement = document.activeElement; // Calculate length of strA and strC let aLength = 0, cLength = 0; while (aLength < curr.length && aLength < next.length && curr[aLength] === next[aLength]) { aLength++; } while (curr[curr.length - cLength - 1] === next[next.length - cLength - 1]) { cLength++; } aLength = Math.min(aLength, Math.min(curr.length, next.length) - cLength); // Select strB1 el.setSelectionRange(aLength, curr.length - cLength); // Get strB2 const strB2 = next.substring(aLength, next.length - cLength); // Replace strB1 with strB2 el.focus(); if (!document.execCommand('insertText', false, strB2)) { // Document.execCommand returns false if the command is not supported. // Firefox and IE returns false in this case. el.value = next; } // Move cursor to the end of headToCursor el.setSelectionRange(headToCursor.length, headToCursor.length); activeElement && activeElement.focus(); return el; }
// @flow export default function (el: HTMLTextAreaElement, headToCursor: string, cursorToTail: ?string) { const curr = el.value, // strA + strB1 + strC next = headToCursor + (cursorToTail || ''), // strA + strB2 + strC activeElement = document.activeElement; // Calculate length of strA and strC let aLength = 0, cLength = 0; while (aLength < curr.length && aLength < next.length && curr[aLength] === next[aLength]) { aLength++; } while (curr.length - cLength - 1 >= 0 && next.length - cLength - 1 >= 0 && curr[curr.length - cLength - 1] === next[next.length - cLength - 1]) { cLength++; } aLength = Math.min(aLength, Math.min(curr.length, next.length) - cLength); // Select strB1 el.setSelectionRange(aLength, curr.length - cLength); // Get strB2 const strB2 = next.substring(aLength, next.length - cLength); // Replace strB1 with strB2 el.focus(); if (!document.execCommand('insertText', false, strB2)) { // Document.execCommand returns false if the command is not supported. // Firefox and IE returns false in this case. el.value = next; } // Move cursor to the end of headToCursor el.setSelectionRange(headToCursor.length, headToCursor.length); activeElement && activeElement.focus(); return el; }
Fix a second infinite loop
Fix a second infinite loop
JavaScript
mit
yuku-t/undate,yuku-t/undate
ea89c8e3f4068f775cca71dbfd6c2d8410addecb
lib/assets/javascripts/cartodb/new_common/url_shortener.js
lib/assets/javascripts/cartodb/new_common/url_shortener.js
var $ = require('jquery'); var LocalStorage = require('./local_storage'); var LOGIN = 'vizzuality'; var KEY = 'R_de188fd61320cb55d359b2fecd3dad4b'; var UrlShortener = function() { this.localStorage = new LocalStorage('cartodb_urls'); }; UrlShortener.prototype.fetch = function(originalUrl, callbacks) { var cachedUrl = this.localStorage.search(originalUrl); if (cachedUrl) { return callbacks.success(cachedUrl); } var self = this; $.ajax({ url: 'https://api-ssl.bitly.com/v3/shorten?longUrl=' + encodeURIComponent(originalUrl) + '&login=' + LOGIN + '&apiKey=' + KEY, type: 'GET', async: false, dataType: 'jsonp', success: function(res) { if (res && res.data && res.data.url) { var shortURL = res.data.url; var d = {}; d[originalUrl] = shortURL; self.localStorage.add(d); callbacks.success(shortURL); } else { callbacks.error(originalUrl); } }, error: function() { callbacks.error(originalUrl); } }); }; module.exports = UrlShortener;
var $ = require('jquery'); var LocalStorage = require('./local_storage'); var LOGIN = 'vizzuality'; var KEY = 'R_de188fd61320cb55d359b2fecd3dad4b'; var UrlShortener = function() { this.localStorage = new LocalStorage('cartodb_urls2'); // to not clash with old local storage cache, they're incompatible }; UrlShortener.prototype.fetch = function(originalUrl, callbacks) { var cachedUrl = this.localStorage.search(originalUrl); if (cachedUrl) { return callbacks.success(cachedUrl); } var self = this; $.ajax({ url: 'https://api-ssl.bitly.com/v3/shorten?longUrl=' + encodeURIComponent(originalUrl) + '&login=' + LOGIN + '&apiKey=' + KEY, type: 'GET', async: false, dataType: 'jsonp', success: function(res) { if (res && res.data && res.data.url) { var shortURL = res.data.url; var d = {}; d[originalUrl] = shortURL; self.localStorage.add(d); callbacks.success(shortURL); } else { callbacks.error(originalUrl); } }, error: function() { callbacks.error(originalUrl); } }); }; module.exports = UrlShortener;
Change key used for url shortener
Change key used for url shortener Incompatible with old keys, so do not use same key
JavaScript
bsd-3-clause
thorncp/cartodb,UCL-ShippingGroup/cartodb-1,thorncp/cartodb,DigitalCoder/cartodb,codeandtheory/cartodb,DigitalCoder/cartodb,nyimbi/cartodb,nuxcode/cartodb,UCL-ShippingGroup/cartodb-1,DigitalCoder/cartodb,codeandtheory/cartodb,nuxcode/cartodb,CartoDB/cartodb,bloomberg/cartodb,future-analytics/cartodb,nyimbi/cartodb,codeandtheory/cartodb,nyimbi/cartodb,dbirchak/cartodb,splashblot/dronedb,CartoDB/cartodb,bloomberg/cartodb,CartoDB/cartodb,bloomberg/cartodb,raquel-ucl/cartodb,dbirchak/cartodb,dbirchak/cartodb,raquel-ucl/cartodb,future-analytics/cartodb,raquel-ucl/cartodb,raquel-ucl/cartodb,UCL-ShippingGroup/cartodb-1,nyimbi/cartodb,future-analytics/cartodb,nuxcode/cartodb,UCL-ShippingGroup/cartodb-1,bloomberg/cartodb,codeandtheory/cartodb,codeandtheory/cartodb,splashblot/dronedb,thorncp/cartodb,splashblot/dronedb,DigitalCoder/cartodb,CartoDB/cartodb,UCL-ShippingGroup/cartodb-1,DigitalCoder/cartodb,dbirchak/cartodb,dbirchak/cartodb,thorncp/cartodb,future-analytics/cartodb,CartoDB/cartodb,nuxcode/cartodb,thorncp/cartodb,raquel-ucl/cartodb,nuxcode/cartodb,nyimbi/cartodb,splashblot/dronedb,bloomberg/cartodb,splashblot/dronedb,future-analytics/cartodb
3b3de3a210fe69cd4e95f0c218801992cab0c88c
src/store/student-store.js
src/store/student-store.js
import { Store } from 'consus-core/flux'; import CartStore from './cart-store'; let student = null; class StudentStore extends Store{ hasOverdueItems(items){ return items.some(element => { return element.timestamp <= new Date().getTime(); }); } getStudent() { return student; } } const store = new StudentStore(); store.registerHandler('STUDENT_FOUND', data => { student = { //NOTE: this data is tentative id : data.id, name: data.name, items: data.items, hasOverdueItem: store.hasOverdueItems(data.items) }; store.emitChange(); }); store.registerHandler('CLEAR_ALL_DATA', () => { student = null; }); store.registerHandler('CHECKOUT_SUCCESS', () => { student.items = student.items.concat(CartStore.getItems()); store.emitChange(); }); store.registerHandler('CHECKIN_SUCCESS', data => { let index = student.items.findIndex(element => { return element.address === data.itemAddress; }); student.items.splice(index, 1); store.emitChange(); }); export default store;
import { Store } from 'consus-core/flux'; import CartStore from './cart-store'; import { searchStudent } from '../lib/api-client'; let student = null; class StudentStore extends Store{ hasOverdueItems(items){ return items.some(element => { return element.timestamp <= new Date().getTime(); }); } getStudent() { return student; } } const store = new StudentStore(); store.registerHandler('STUDENT_FOUND', data => { student = { //NOTE: this data is tentative id : data.id, name: data.name, items: data.items, hasOverdueItem: store.hasOverdueItems(data.items) }; store.emitChange(); }); store.registerHandler('CLEAR_ALL_DATA', () => { student = null; }); store.registerHandler('CHECKOUT_SUCCESS', () => { /*API call made from store to update student from server after checkout completes, then the store will emit change when student is found.*/ searchStudent(student.id); }); store.registerHandler('CHECKIN_SUCCESS', data => { let index = student.items.findIndex(element => { return element.address === data.itemAddress; }); student.items.splice(index, 1); store.emitChange(); }); export default store;
Update student from server after checkout completes
Update student from server after checkout completes
JavaScript
unlicense
TheFourFifths/consus-client,TheFourFifths/consus-client
0be67d85e1d203b41d1dddded41f8d634e01a44f
packages/truffle-contract/statuserror.js
packages/truffle-contract/statuserror.js
var TruffleError = require("truffle-error"); var inherits = require("util").inherits; var defaultGas = 90000; var web3 = require("web3"); inherits(StatusError, TruffleError); function StatusError(args, tx, receipt) { var message; var gasLimit = parseInt(args.gas) || defaultGas; if(receipt.gasUsed === gasLimit){ message = "Transaction: " + tx + " exited with an error (status 0 - invalid opcode).\n" + "Please check that the transaction:\n" + " - satisfies all conditions set by Solidity `assert` statements.\n" + " - has enough gas to execute all internal Solidity function calls.\n"; } else { message = "Transaction: " + tx + " exited with an error (status 0 - revert).\n" + "Please check that the transaction:\n" + " - satisfies all conditions set by Solidity `require` statements.\n" + " - does not trigger a Solidity `revert` statement.\n"; } StatusError.super_.call(this, message); this.tx = tx; this.receipt = receipt; } module.exports = StatusError;
var TruffleError = require("truffle-error"); var inherits = require("util").inherits; var web3 = require("web3"); inherits(StatusError, TruffleError); var defaultGas = 90000; function StatusError(args, tx, receipt) { var message; var gasLimit = parseInt(args.gas) || defaultGas; if(receipt.gasUsed === gasLimit){ message = "Transaction: " + tx + " exited with an error (status 0 - invalid opcode).\n" + "Please check that the transaction:\n" + " - satisfies all conditions set by Solidity `assert` statements.\n" + " - has enough gas to execute all internal Solidity function calls.\n"; } else { message = "Transaction: " + tx + " exited with an error (status 0 - revert).\n" + "Please check that the transaction:\n" + " - satisfies all conditions set by Solidity `require` statements.\n" + " - does not trigger a Solidity `revert` statement.\n"; } StatusError.super_.call(this, message); this.tx = tx; this.receipt = receipt; } module.exports = StatusError;
Move errant variable away from require block
Move errant variable away from require block
JavaScript
mit
ConsenSys/truffle
88540362b4b676d68a2b5db474b9cb1bd7316aa3
packages/motion/src/cli/index.js
packages/motion/src/cli/index.js
#!/usr/bin/env node 'use strict' import commander from 'commander' const parameters = require('minimist')(process.argv.slice(2)) const command = parameters['_'][0] const validCommands = ['new', 'build', 'update', 'init'] // TODO: Check for updates // Note: This is a trick to make multiple commander commands work with single executables process.argv = process.argv.slice(0, 2).concat(process.argv.slice(3)) if (!command || command === 'run') { require('./motion-run') } else if (validCommands.indexOf(command) !== -1) { require(`./motion-${command}`) } else { console.error(` Usage: motion run your motion app motion new [name] [template] start a new app motion build build for production motion update update motion motion init add a motion config to an existing app (temporary, awaiting https://github.com/motion/motion/issues/339) `.trim()) process.exit(1) }
#!/usr/bin/env node 'use strict' const command = process.argv[2] || '' const validCommands = ['new', 'build', 'update', 'init'] // TODO: Check for updates // Note: This is a trick to make multiple commander commands work with single executables process.argv = process.argv.slice(0, 2).concat(process.argv.slice(3)) let showHelp = command === '--help' if (!showHelp && (!command || command === 'run')) { require('./motion-run') } else if (!showHelp && validCommands.indexOf(command) !== -1) { require(`./motion-${command}`) } else { console.error(` Usage: motion alias for 'motion run' motion run run your motion app motion new [name] [template] start a new app motion build build for production motion update update motion motion init add a motion config to an existing app (temporary, awaiting https://github.com/motion/motion/issues/339) `.trim()) process.exit(1) }
Enhance the main cli entry file
:art: Enhance the main cli entry file
JavaScript
mpl-2.0
flintjs/flint,flintjs/flint,motion/motion,flintjs/flint,motion/motion
8486a37ca95cc2c211ec6a66b618e986e3d7dec6
server/server.js
server/server.js
const express = require('express'), bodyParser = require('body-parser'); const {mongoose} = require('./db/mongoose'), dbHandler = require('./db/dbHandler'); let app = express(); let port = porcess.env.PORT || 3000; app.use(bodyParser.json()); app.route('/todos') .get((req, res) => { dbHandler.findTodos().then((value) => { res.send({ todos: value.data }); }).catch((err) => { console.error('There was an error fetching the todos.', err); res.status(err.code).send({message: err.message}); }); }) .post((req, res) => { dbHandler.saveTodo(req.body.text).then((value) => { res.send(value.data); }).catch((err) => { console.error('There was an error saving the todo.', err); res.status(err.code).send({message: err.message}); }); }); app.route('/todos/:id') .get((req, res) => { dbHandler.findTodo(req.params.id).then((value) => { res.send({ todo: value.data }); }).catch((err) => { console.error('There was an error fetching the todo.', err); res.status(err.code).send({message: err.message}); }) }) app.listen(port, () => { console.log(`Started up at port ${port}`); }); module.exports = {app};
const express = require('express'), bodyParser = require('body-parser'); const {mongoose} = require('./db/mongoose'), dbHandler = require('./db/dbHandler'); let app = express(); let port = process.env.PORT || 3000; app.use(bodyParser.json()); app.route('/todos') .get((req, res) => { dbHandler.findTodos().then((value) => { res.send({ todos: value.data }); }).catch((err) => { console.error('There was an error fetching the todos.', err); res.status(err.code).send({message: err.message}); }); }) .post((req, res) => { dbHandler.saveTodo(req.body.text).then((value) => { res.send(value.data); }).catch((err) => { console.error('There was an error saving the todo.', err); res.status(err.code).send({message: err.message}); }); }); app.route('/todos/:id') .get((req, res) => { dbHandler.findTodo(req.params.id).then((value) => { res.send({ todo: value.data }); }).catch((err) => { console.error('There was an error fetching the todo.', err); res.status(err.code).send({message: err.message}); }) }) app.listen(port, () => { console.log(`Started up at port ${port}`); }); module.exports = {app};
Fix a typo setting the port
Fix a typo setting the port
JavaScript
mit
daniellara/smooky-todoes
75a7442f43aeaa63727ba09c892cb7b4f5e4f1c5
test/api/scenarios.spec.js
test/api/scenarios.spec.js
import { API } from 'api'; import Scenarios from 'api/scenarios'; describe('scenarios', () => { afterEach(() => { API.clearStorage(); }); it('should have currentScenario be set to "MockedRequests"', () => { expect(Scenarios.currentScenario).toBe('MockedRequests'); }); it('should get 0 scenarios', () => { expect(Scenarios.scenarios.length).toBe(0); }); it('should add a scenario', () => { expect(Scenarios.scenarios.length).toBe(0); Scenarios.addScenario('test scenario'); expect(Scenarios.scenarios.length).toBe(1); expect(Scenarios.scenarios[0].name).toBe('test scenario'); }); });
import { API } from 'api'; import Scenarios from 'api/scenarios'; describe('scenarios', () => { afterEach(() => { API.clearStorage(); }); it('should have currentScenario be set to "MockedRequests"', () => { expect(Scenarios.currentScenario).toBe('MockedRequests'); }); it('should get 0 scenarios', () => { expect(Scenarios.scenarios.length).toBe(0); }); it('should add a scenario', () => { expect(Scenarios.scenarios.length).toBe(0); Scenarios.addScenario('test scenario'); expect(Scenarios.scenarios.length).toBe(1); expect(Scenarios.scenarios[0].name).toBe('test scenario'); }); it('should set the current scenario', () => { Scenarios.addScenario('test scenario'); Scenarios.setCurrentScenario(Scenarios.scenarios[0].id); expect(Scenarios.currentScenario).toBe(Scenarios.scenarios[0].id); }); it('should get a scenario by id', () => { Scenarios.addScenario('test scenario'); let scenario = Scenarios.getById(Scenarios.scenarios[0].id); expect(scenario).toBe(Scenarios.scenarios[0]); }); it('should get a scenario by name', () => { Scenarios.addScenario('test scenario'); let scenario = Scenarios.getByName('test scenario'); expect(scenario).toBe(Scenarios.scenarios[0]); }); it('should duplicate a scenario', () => { Scenarios.addScenario('test scenario'); expect(Scenarios.scenarios.length).toBe(1); Scenarios.duplicateScenario(Scenarios.scenarios[0].id); expect(Scenarios.getByName('test scenario copy')).toBeDefined(); expect(Scenarios.scenarios.length).toBe(2); }); it('should rename a scenario', () => { Scenarios.addScenario('test scenario'); expect(Scenarios.scenarios[0].name).toBe('test scenario'); Scenarios.renameScenario(Scenarios.scenarios[0].id, 'renamed scenario'); expect(Scenarios.scenarios[0].name).toBe('renamed scenario'); }); it('should remove a scenario', () => { expect(Scenarios.scenarios.length).toBe(0); Scenarios.addScenario('test scenario'); expect(Scenarios.scenarios.length).toBe(1); Scenarios.removeScenario(Scenarios.scenarios[0].id); expect(Scenarios.scenarios.length).toBe(0); }); });
Add additional scenarios test cases
Add additional scenarios test cases
JavaScript
mit
500tech/bdsm,500tech/mimic,500tech/mimic,500tech/bdsm
17bc27925e2b02d4910cd6598af4bcbda7e4d8f0
src/tasks/watchBuild.js
src/tasks/watchBuild.js
/* * Copyright 2014 Workiva, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ module.exports = function(gulp, options, subtasks) { var taskname = 'watch:build'; gulp.desc(taskname, 'Watch source files for changes and rebuild'); var fn = function(done) { gulp.watch(options.glob.all, { cwd: options.path.src }, ['build']); }; gulp.task(taskname, ['build'], fn); };
/* * Copyright 2014 Workiva, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ module.exports = function(gulp, options, subtasks) { var taskname = 'watch:build'; gulp.desc(taskname, 'Watch source files for changes and rebuild'); var fn = function(done) { gulp.watch([ options.path.src + options.glob.all, options.path.styles + options.glob.all ], ['build']); }; gulp.task(taskname, ['build'], fn); };
Add styles to watched directories for watch:build/watch
Add styles to watched directories for watch:build/watch
JavaScript
apache-2.0
robertbaker/wGulp,Workiva/wGulp,Workiva/wGulp,jimhotchkin-wf/wGulp,jimhotchkin-wf/wGulp,robertbaker/wGulp,robertbaker/wGulp,jimhotchkin-wf/wGulp,Workiva/wGulp
e5159760eea2faff47cc88518f5b4c3317b6b4ec
src/utils/gulp/gulp-tasks-linters.js
src/utils/gulp/gulp-tasks-linters.js
var path = require('path'); var eslint = require('gulp-eslint'); var merge = require('lodash/object/merge'); var shelljs = require('shelljs'); function failLintBuild() { process.exit(1); } function scssLintExists() { return shelljs.which('scss-lint'); } module.exports = function(gulp, options) { var scssLintPath = path.resolve(__dirname, 'scss-lint.yml'); var esLintPath = path.resolve(__dirname, 'eslintrc'); var customEslint = options.customEslintPath ? require(options.customEslintPath) : {}; gulp.task('scsslint', function() { if (options.scsslint) { if (scssLintExists()) { var scsslint = require('gulp-scss-lint'); return gulp.src(options.scssAssets || []).pipe(scsslint({ 'config': scssLintPath })).pipe(scsslint.failReporter()).on('error', failLintBuild); } else { console.error('[scsslint] scsslint skipped!'); console.error('[scsslint] scss-lint is not installed. Please install ruby and the ruby gem scss-lint.'); } } }); gulp.task('jslint', function() { var eslintRules = merge({ configFile: esLintPath }, customEslint); return gulp.src(options.jsAssets || []) .pipe(eslint(eslintRules)) .pipe(eslint.formatEach()) .pipe(eslint.failOnError()); }); };
var path = require('path'); var eslint = require('gulp-eslint'); var merge = require('lodash/object/merge'); var shelljs = require('shelljs'); function scssLintExists() { return shelljs.which('scss-lint'); } module.exports = function(gulp, options) { var scssLintPath = path.resolve(__dirname, 'scss-lint.yml'); var esLintPath = path.resolve(__dirname, 'eslintrc'); var customEslint = options.customEslintPath ? require(options.customEslintPath) : {}; gulp.task('scsslint', function() { if (options.scsslint) { if (scssLintExists()) { var scsslint = require('gulp-scss-lint'); return gulp.src(options.scssAssets || []).pipe(scsslint({ 'config': scssLintPath })).pipe(scsslint.failReporter()); } else { console.error('[scsslint] scsslint skipped!'); console.error('[scsslint] scss-lint is not installed. Please install ruby and the ruby gem scss-lint.'); } } }); gulp.task('jslint', function() { var eslintRules = merge({ configFile: esLintPath }, customEslint); return gulp.src(options.jsAssets || []) .pipe(eslint(eslintRules)) .pipe(eslint.formatEach()) .pipe(eslint.failOnError()); }); };
Print all scsslint errors before existing.
Print all scsslint errors before existing.
JavaScript
apache-2.0
samogami/grommet,codeswan/grommet,phuson/grommet,HewlettPackard/grommet,davrodpin/grommet,HewlettPackard/grommet,samogami/grommet,Dinesh-Ramakrishnan/grommet,primozs/grommet,marlonpp/grommet-old,nanndoj/grommet,kylebyerly-hp/grommet,davrodpin/grommet,nickjvm/grommet,HewlettPackard/grommet,marlonpp/grommet-old,codeswan/grommet,linde12/grommet,primozs/grommet,grommet/grommet,grommet/grommet,nickjvm/grommet,Dinesh-Ramakrishnan/grommet,grommet/grommet,phuson/grommet,nanndoj/grommet
b5af356f623429c5472f968ad2a84da9b599a7c4
test/setup.js
test/setup.js
import 'babel-polyfill' import fs from 'fs' import path from 'path' import jsdom from 'jsdom' import dotenv from 'dotenv' import chai, { expect } from 'chai' import chaiImmutable from 'chai-immutable' import sinon from 'sinon' import sinonChai from 'sinon-chai' import chaiSaga from './support/saga_helpers' chai.use(chaiSaga) chai.use(chaiImmutable) chai.use(sinonChai) dotenv.load() global.ENV = require('../env') global.chai = chai global.expect = expect global.sinon = sinon if (!global.document) { const html = fs.readFileSync(path.join(__dirname, '../public/template.html'), 'utf-8') const exposedProperties = ['document', 'navigator', 'window'] global.document = jsdom.jsdom(html) global.window = document.defaultView global.navigator = { userAgent: 'node.js' } global.URL = { createObjectURL: input => input } const enums = [ ...Object.keys(document.defaultView), ...['Image'], ] enums.forEach((property) => { if (typeof global[property] === 'undefined') { exposedProperties.push(property) global[property] = document.defaultView[property] } }) }
import 'babel-polyfill' import fs from 'fs' import path from 'path' import jsdom from 'jsdom' import dotenv from 'dotenv' import chai, { expect } from 'chai' import chaiImmutable from 'chai-immutable' import sinon from 'sinon' import sinonChai from 'sinon-chai' import chaiSaga from './support/saga_helpers' chai.use(chaiSaga) chai.use(chaiImmutable) chai.use(sinonChai) dotenv.load() global.ENV = require('../env') global.chai = chai global.expect = expect global.sinon = sinon if (!global.document) { const html = fs.readFileSync(path.join(__dirname, '../public/template.html'), 'utf-8') const exposedProperties = ['document', 'navigator', 'window'] global.document = jsdom.jsdom(html) global.window = document.defaultView global.navigator = { userAgent: 'node.js' } global.URL = { createObjectURL: input => input } const enums = [ ...Object.keys(document.defaultView), ...['Image'], ] enums.forEach((property) => { if (typeof global[property] === 'undefined') { exposedProperties.push(property) global[property] = document.defaultView[property] } }) } // this is a polyfill to get enquire.js to work in a headless // environment. it is required by react-slick for carousels window.matchMedia = window.matchMedia || function () { return { matches: false, addListener: () => {}, removeListener: () => {}, } }
Add a polyfill for matchMedia to get tests to run
Add a polyfill for matchMedia to get tests to run
JavaScript
mit
ello/webapp,ello/webapp,ello/webapp
9752da995a819fad7859f0bce13f1370bfda9f7b
server/routes/user-routes.js
server/routes/user-routes.js
var bcrypt = require('bcryptjs'); var router = require('express').Router(); var User = require('../models/user'); router.post('/', function(req, res) { var salt = bcrypt.genSaltSync(10); var user = new User({ username: req.body.user.username, name: req.body.user.name, password_digest: bcrypt.hashSync(req.body.user.password, salt) }); user.save().then(function(userData) { res.json({ message: 'Thanks for signing up!', user: userData }); }, function(err) { console.log(err); }); }); module.exports = router;
var bcrypt = require('bcryptjs'); var jwt = require('jsonwebtoken'); var router = require('express').Router(); var User = require('../models/user'); router.post('/', function(req, res) { var salt = bcrypt.genSaltSync(10); var user = new User({ username: req.body.user.username, name: req.body.user.name, password_digest: bcrypt.hashSync(req.body.user.password, salt) }); user.save().then(function(userData) { var token = jwt.sign( userData._id, process.env.JWT_SECRET, { expiresIn: 24 * 60 * 60 }); res.json({ message: 'Thanks for signing up!', user: userData, auth_token: token }); }, function(err) { console.log(err); }); }); module.exports = router;
Include auth token in sign up response.
Include auth token in sign up response.
JavaScript
mit
FretlessJS-2016-03/notely,FretlessJS-2016-03/notely
a707369a96aa892764775146c0ca081c9b95c712
routes/front.js
routes/front.js
var express = require('express'); var router = express.Router(); router.get('/token', function (req, res) { res.redirect('/'); }); router.get('/*', function (req, res, next) { res.render('user/dashboard', { layout: 'user', title: 'Busy' }); }); module.exports = router;
var express = require('express'); var router = express.Router(); router.get('/*', function (req, res, next) { res.render('user/dashboard', { layout: 'user', title: 'Busy' }); }); module.exports = router;
Remove token endPoint; need to redeploy.
Remove token endPoint; need to redeploy.
JavaScript
mit
Sekhmet/busy,busyorg/busy,ryanbaer/busy,Sekhmet/busy,busyorg/busy,ryanbaer/busy
a115c44bcc17d6e6956d9d07030c2bb79c8a8f42
ssr-express/demo/app.js
ssr-express/demo/app.js
/** * Copyright 2018 The AMP HTML Authors. All Rights Reserved. * * 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. */ 'use strict'; const express = require('express'); const path = require('path'); const app = express(); const AmpSsrMiddleware = require('../index.js'); const ampSsr = require('amp-toolbox-ssr'); // Setup the middleware and pass the ampSsr instance that will perform the transformations. const ampSsrMiddleware = AmpSsrMiddleware.create({ampSsr: ampSsr}); // It's important that the ampSsrMiddleware is added *before* the static middleware. // This allows the middleware to intercept the page rendered by static and transform it. app.use(ampSsrMiddleware); const staticMiddleware = express.static(path.join(__dirname, '/public')); app.use(staticMiddleware); const DEFAULT_PORT = 3000; const port = process.env.PORT || DEFAULT_PORT; app.listen(port, () => { console.log('Example app listening on port 3000!'); });
/** * Copyright 2018 The AMP HTML Authors. All Rights Reserved. * * 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. */ 'use strict'; const express = require('express'); const path = require('path'); const app = express(); const AmpSsrMiddleware = require('../index.js'); // It's important that the ampSsrMiddleware is added *before* the static middleware. // This allows the middleware to intercept the page rendered by static and transform it. app.use(AmpSsrMiddleware.create()); const staticMiddleware = express.static(path.join(__dirname, '/public')); app.use(staticMiddleware); const DEFAULT_PORT = 3000; const port = process.env.PORT || DEFAULT_PORT; app.listen(port, () => { console.log('Example app listening on port 3000!'); });
Remove amp-ssr component from demo
Remove amp-ssr component from demo Change-Id: I39067fd6e71f28a5365b447824280b7c4f71a01d
JavaScript
apache-2.0
ampproject/amp-toolbox,google/amp-toolbox,google/amp-toolbox,ampproject/amp-toolbox,google/amp-toolbox,ampproject/amp-toolbox,ampproject/amp-toolbox
99a416385af062898d0709b64493dcb8859e9e27
src/e2e-tests/basic.e2e.js
src/e2e-tests/basic.e2e.js
var assert = require('assert'); describe("Basic Test", function(){ it("Loads the basic demo page and sends values to server", function(){ browser.url('http://localhost:7888/src/e2e-tests/basic-demo-page?auto-activate-glasswing') browser.waitUntil(function () { var a = browser.execute(function(){ return window.a }).value return a == 25; }, 20000, 'expected a to be set to 25 by the page') browser.waitUntil(function () { var a = browser.execute(function(){ return window.__jscb.recordedValueBuffer.length }).value console.log("length", a) return a == 0; }, 20000, 'expected values to be sent to server and value buffer to be reset'); }) it("Shows simple.js in the Glasswing file listing", function(){ browser.url('http://localhost:9500') var fileLinksTable = $(".file-links") fileLinksTable.waitForExist(5000) var jsFilePath = "http://localhost:7888/src/e2e-tests/basic-demo-page/basic-demo.js" assert(fileLinksTable.getText().indexOf(jsFilePath) !== -1) }) }) })
var assert = require('assert'); function assertContains(string, containedValue){ assert(string.indexOf(containedValue) !== -1) } describe("Basic Test", function(){ it("Loads the basic demo page and sends values to server", function(){ browser.url('http://localhost:7888/src/e2e-tests/basic-demo-page?auto-activate-glasswing') browser.waitUntil(function () { var a = browser.execute(function(){ return window.a }).value return a == 25; }, 20000, 'expected a to be set to 25 by the page') browser.waitUntil(function () { var a = browser.execute(function(){ return window.__jscb.recordedValueBuffer.length }).value console.log("length", a) return a == 0; }, 20000, 'expected values to be sent to server and value buffer to be reset'); }) it("Shows simple.js in the Glasswing file listing", function(){ browser.url('http://localhost:9500') var fileLinksTable = $(".file-links") fileLinksTable.waitForExist(5000) var jsFilePath = "http://localhost:7888/src/e2e-tests/basic-demo-page/basic-demo.js" assertContains(fileLinksTable.getText(), jsFilePath) }) it("Shows annotated source", function(){ browser.click(".file-links a"); var monacoEditor = $(".monaco-editor") monacoEditor.waitForExist(10000) assertContains(monacoEditor.getText(), "function square") }).timeout(100000) })
Check annotated source code renders.
Check annotated source code renders.
JavaScript
mit
mattzeunert/glasswing,mattzeunert/glasswing,mattzeunert/glasswing
b4ab5d7ff3556f9a40c425afaa4dab5601b37027
models/paste.js
models/paste.js
const mongoose = require('mongoose'); const shortid = require('shortid'); const paste = new mongoose.Schema({ _id: { type: String, default: shortid.generate }, paste: { type: String }, expiresAt: { type: Date, expires: 0, default: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7) } }, { timestamps: true }); module.exports = mongoose.model('Paste', paste);
const mongoose = require('mongoose'); const shortid = require('shortid'); const paste = new mongoose.Schema({ _id: { type: String, default: shortid.generate }, paste: { type: String }, expiresAt: { type: Date, expires: 0 } }, { timestamps: true }); module.exports = mongoose.model('Paste', paste);
Remove default expiry on model
Remove default expiry on model
JavaScript
mit
JoeBiellik/paste,JoeBiellik/paste
0f3369a02a6386d8bfb895de09faa9b1c168715d
src/app/components/msp/common/consent-modal/i18n/data/en/index.js
src/app/components/msp/common/consent-modal/i18n/data/en/index.js
module.exports = { title: 'Information collection notice', body: 'The information in this application is collected by the Ministry of Health under section 26(a) of the Freedom of Information and Protection of Privacy Act and will be used to determine eligibility for provincial health care benefits in BC and administer Premium Assistance. Should you have any questions about the collection of this personal information please <a href="http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents-contact-us" target="_blank">contact Health Insurance of BC</a> <i class="fa fa-external-link" aria-hidden="true"></i>.', agreeLabel: 'I have read and understand the information above and would like to continue to apply for MSP', continueButton: 'Continue' }
module.exports = { title: 'Information collection notice', body: '<p>The data you enter on this form is saved locally to the computer or device you are using. The data will be deleted when you close the web browser you are using or after your submit your application.</p><p>The information in this application is collected by the Ministry of Health under section 26(a) of the Freedom of Information and Protection of Privacy Act and will be used to determine eligibility for provincial health care benefits in BC and administer Premium Assistance. Should you have any questions about the collection of this personal information please <a href="http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents-contact-us" target="_blank">contact Health Insurance of BC</a> <i class="fa fa-external-link" aria-hidden="true"></i>.</p>', agreeLabel: 'I have read and understand the information above and would like to continue to apply for MSP', continueButton: 'Continue' }
Add info re: data saving
Add info re: data saving
JavaScript
apache-2.0
bcgov/MyGovBC-MSP,bcgov/MyGovBC-MSP,bcgov/MyGovBC-MSP,bcgov/MyGovBC-MSP
e2bff214c4773626816d3f58d19a2a84451c333d
src/astring_plugin/index.js
src/astring_plugin/index.js
import astring from 'astring'; // Create a custom generator that inherits from Astring's default generator const customGenerator = Object.assign({}, astring.defaultGenerator, { Literal(node, state) { if (node.raw != null) { const first = node.raw.charAt(0); const last = node.raw.charAt(node.raw.length - 1); if ((first === 12300 && last === 12301) // γ€Œγ€ || (first === 8216 && last === 8217)) { // β€˜β€™ state.output.write(`'${node.raw.slice(1, node.raw.length - 1)}'`); } if ((first === 12302 && last === 12303) // γ€Žγ€ || (first === 8220 && last === 8221)) { // β€œβ€ state.output.write(`"${node.raw.slice(1, node.raw.length - 1)}"`); } if ((first === 34 && last === 34) || (first === 39 && last === 39)) { // "" or '' state.output.write(node.raw); } else { // HaLang-specific string literals state.output.write(node.value); } } else if (node.regex != null) { this.RegExpLiteral(node, state); } else { state.output.write(JSON.stringify(node.value)); } }, }); export default customGenerator;
import astring from 'astring'; // Create a custom generator that inherits from Astring's default generator const customGenerator = Object.assign({}, astring.defaultGenerator, { Literal(node, state) { if (node.raw != null) { const first = node.raw.charAt(0).charCodeAt(); const last = node.raw.charAt(node.raw.length - 1).charCodeAt(); if ((first === 12300 && last === 12301) // γ€Œγ€ || (first === 8216 && last === 8217)) { // β€˜β€™ state.output.write(`'${node.raw.slice(1, node.raw.length - 1)}'`); } else if ((first === 12302 && last === 12303) // γ€Žγ€ || (first === 8220 && last === 8221)) { // β€œβ€ state.output.write(`"${node.raw.slice(1, node.raw.length - 1)}"`); } else if ((first === 34 && last === 34) || (first === 39 && last === 39)) { // "" or '' state.output.write(node.raw); } else { // HaLang-specific string literals state.output.write(node.value); } } else if (node.regex != null) { this.RegExpLiteral(node, state); } else { state.output.write(JSON.stringify(node.value)); } }, }); export default customGenerator;
Fix the bug hidden in astring plugin
Fix the bug hidden in astring plugin
JavaScript
mit
laosb/hatp
8a5185e85c1f6206ed59256b2a6c2e996af96a6b
tools/bundle-deploy.js
tools/bundle-deploy.js
const { execSync } = require('child_process'); const path = require('path'); execSync(` git config user.email "andrey.a.gubanov@gmail.com" && git config user.name "Andrey Gubanov (his digital copy)" && git clone -b gh-pages https://$GH_TOKEN@github.com/matreshkajs/matreshka-router.git && npm run bundle && cd bundle && git add . && git commit --allow-empty -m $npm_package_version && git push https://$GH_TOKEN@github.com/matreshkajs/matreshka-router.git gh-pages `, { cwd: path.resolve(__dirname, '..') });
const { execSync } = require('child_process'); const path = require('path'); execSync(` git config user.email "andrey.a.gubanov@gmail.com" && git config user.name "Andrey Gubanov (his digital copy)" && git clone -b gh-pages https://$GH_TOKEN@github.com/matreshkajs/matreshka-router.git bundle && npm run bundle && cd bundle && git add . && git commit --allow-empty -m $npm_package_version && git push https://$GH_TOKEN@github.com/matreshkajs/matreshka-router.git gh-pages `, { cwd: path.resolve(__dirname, '..') });
Clone bundle repo tu bundle folder
fix: Clone bundle repo tu bundle folder
JavaScript
mit
matreshkajs/matreshka-router,finom/matreshka_router
fc31a6711da30682e208cc257b567c136fe9a6b5
client/src/entrypoints/snippets/snippet-chooser-modal.js
client/src/entrypoints/snippets/snippet-chooser-modal.js
import $ from 'jquery'; window.SNIPPET_CHOOSER_MODAL_ONLOAD_HANDLERS = { choose: function (modal) { function ajaxifyLinks(context) { $('a.snippet-choice', modal.body).on('click', function () { modal.loadUrl(this.href); return false; }); $('.pagination a', context).on('click', function () { loadResults(this.href); return false; }); } var searchForm$ = $('form.snippet-search', modal.body); var searchUrl = searchForm$.attr('action'); var request; function search() { loadResults(searchUrl, searchForm$.serialize()); return false; } function loadResults(url, data) { var opts = { url: url, success: function (resultsData, status) { request = null; $('#search-results').html(resultsData); ajaxifyLinks($('#search-results')); }, error: function () { request = null; }, }; if (data) { opts.data = data; } request = $.ajax(opts); } $('form.snippet-search', modal.body).on('submit', search); $('#snippet-chooser-locale', modal.body).on('change', search); $('#id_q').on('input', function () { if (request) { request.abort(); } clearTimeout($.data(this, 'timer')); var wait = setTimeout(search, 200); $(this).data('timer', wait); }); ajaxifyLinks(modal.body); }, chosen: function (modal, jsonData) { modal.respond('snippetChosen', jsonData.result); modal.close(); }, };
import $ from 'jquery'; import { SearchController } from '../../includes/chooserModal'; window.SNIPPET_CHOOSER_MODAL_ONLOAD_HANDLERS = { choose: function (modal) { function ajaxifyLinks(context) { $('a.snippet-choice', modal.body).on('click', function () { modal.loadUrl(this.href); return false; }); $('.pagination a', context).on('click', function () { searchController.fetchResults(this.href); return false; }); } const searchController = new SearchController({ form: $('form.snippet-search', modal.body), resultsContainerSelector: '#search-results', onLoadResults: (context) => { ajaxifyLinks(context); }, }); searchController.attachSearchInput('#id_q'); searchController.attachSearchFilter('#snippet-chooser-locale'); ajaxifyLinks(modal.body); }, chosen: function (modal, jsonData) { modal.respond('snippetChosen', jsonData.result); modal.close(); }, };
Use SearchController on snippet chooser modal
Use SearchController on snippet chooser modal
JavaScript
bsd-3-clause
wagtail/wagtail,wagtail/wagtail,rsalmaso/wagtail,wagtail/wagtail,thenewguy/wagtail,thenewguy/wagtail,zerolab/wagtail,rsalmaso/wagtail,wagtail/wagtail,rsalmaso/wagtail,thenewguy/wagtail,zerolab/wagtail,thenewguy/wagtail,rsalmaso/wagtail,zerolab/wagtail,zerolab/wagtail,wagtail/wagtail,rsalmaso/wagtail,thenewguy/wagtail,zerolab/wagtail
fc610c08cd26d108ee1e48da4b19bd8c90cf570f
app/assets/javascripts/spree/backend/solidus_paypal_braintree.js
app/assets/javascripts/spree/backend/solidus_paypal_braintree.js
//= require spree/braintree_hosted_form.js $(function() { var $paymentForm = $("#new_payment"), $hostedFields = $("[data-braintree-hosted-fields]"); function onError (err) { var msg = err.name + ": " + err.message; show_flash("error", msg); console.error(err); } // exit early if we're not looking at the New Payment form, or if no // SolidusPaypalBraintree payment methods have been configured. if (!$paymentForm.length || !$hostedFields.length) { return; } $hostedFields.each(function() { var $this = $(this), $new = $("[name=card]", $this); var id = $this.data("id"); var hostedFieldsInstance; $new.on("change", function() { var isNew = $(this).val() === "new"; function setHostedFieldsInstance(instance) { hostedFieldsInstance = instance; return instance; } if (isNew && hostedFieldsInstance === null) { braintreeForm = new BraintreeHostedForm($paymentForm, $this, id); braintreeForm.initializeHostedFields(). then(setHostedFieldsInstance). then(braintreeForm.addFormHook(onError)). fail(onError); } }); }); });
//= require spree/braintree_hosted_form.js $(function() { var $paymentForm = $("#new_payment"), $hostedFields = $("[data-braintree-hosted-fields]"); function onError (err) { var msg = err.name + ": " + err.message; show_flash("error", msg); console.error(err); } // exit early if we're not looking at the New Payment form, or if no // SolidusPaypalBraintree payment methods have been configured. if (!$paymentForm.length || !$hostedFields.length) { return; } $.when( $.getScript("https://js.braintreegateway.com/web/3.9.0/js/client.min.js"), $.getScript("https://js.braintreegateway.com/web/3.9.0/js/hosted-fields.min.js") ).done(function() { $hostedFields.each(function() { var $this = $(this), $new = $("[name=card]", $this); var id = $this.data("id"); var hostedFieldsInstance; $new.on("change", function() { var isNew = $(this).val() === "new"; function setHostedFieldsInstance(instance) { hostedFieldsInstance = instance; return instance; } if (isNew && hostedFieldsInstance === null) { braintreeForm = new BraintreeHostedForm($paymentForm, $container, id); braintreeForm.initializeHostedFields(). then(setHostedFieldsInstance). then(braintreeForm.addFormHook(onError)). fail(onError); } }); }); }); });
Load the braintree client on demand libs in admin
Load the braintree client on demand libs in admin Like in frontend we load the braintree client libs on demand and then initialize the hosted fields.
JavaScript
bsd-3-clause
solidusio/solidus_paypal_braintree,solidusio/solidus_paypal_braintree,solidusio/solidus_paypal_braintree,solidusio/solidus_paypal_braintree
5b30c625b6d59e087341259174e78b97db07eb4a
lib/nb-slug.js
lib/nb-slug.js
'use strict'; var diacritics = require('./diacritics'); function nbSlug(name) { var diacriticsMap = {}; for (var i = 0; i < diacritics.length; i++) { var letters = diacritics[i].letters; for (var j = 0; j < letters.length ; j++) { diacriticsMap[letters[j]] = diacritics[i].base; } } function removeDiacritics (str) { return str.replace(/[^\u0000-\u007E]/g, function(a){ return diacriticsMap[a] || a; }); } var slug = removeDiacritics(String(name || '').trim()) .replace(/^\s\s*/, '') // Trim start .replace(/\s\s*$/, '') // Trim end .toLowerCase() // Camel case is bad .replace(/[^a-z0-9_\-~!\+\s]+/g, '') // Exchange invalid chars .replace(/[\s]+/g, '-') // Swap whitespace for single hyphen .replace(/--/g, '-') .replace(/--/g, '-') .replace(/--/g, '-') .replace(/--/g, '-') .trim(); while (slug[slug.length - 1] === '-') { slug = slug.slice(0, -1); } return slug; } module.exports = nbSlug;
'use strict'; var diacritics = require('./diacritics'); function nbSlug(name) { var diacriticsMap = {}; for (var i = 0; i < diacritics.length; i++) { var letters = diacritics[i].letters; for (var j = 0; j < letters.length ; j++) { diacriticsMap[letters[j]] = diacritics[i].base; } } function removeDiacritics (str) { return str.replace(/[^\u0000-\u007E]/g, function(a){ return diacriticsMap[a] || a; }); } var slug = removeDiacritics(String(name || '').trim()) .replace(/^\s\s*/, '') // Trim start .replace(/\s\s*$/, '') // Trim end .toLowerCase() // Camel case is bad .replace(/[^a-z0-9\-\s]+/g, '') // Exchange invalid chars .replace(/[\s]+/g, '-') // Swap whitespace for single hyphen .replace(/-{2,}/g, '-') // Replace consecutive single hypens .trim(); while (slug[slug.length - 1] === '-') { slug = slug.slice(0, -1); } return slug; } module.exports = nbSlug;
Remove -, !, + and ~ from the slug too
Remove -, !, + and ~ from the slug too
JavaScript
unlicense
nurimba/nb-slug,nurimba/nb-slug
55ab768d9fd5adf4fbefa3db2d121fdbe6c840f4
resources/js/modules/accordion.js
resources/js/modules/accordion.js
import 'accordion/src/accordion.js'; (function() { "use strict"; document.querySelectorAll('.accordion').forEach(function(item) { new Accordion(item, { onToggle: function(target){ // Only allow one accordion item open at time target.accordion.folds.forEach(fold => { if(fold !== target) { fold.open = false; } }); // Allow the content to be shown if its open or hide it when closed target.content.classList.toggle('hidden') }, enabledClass: 'enabled' }); // Hide all accordion content from the start so content inside it isn't part of the tabindex item.querySelectorAll('.content').forEach(function(item) { item.classList.add('hidden'); }); // Remove the role="tablist" since it is not needed item.removeAttribute('role'); }); document.querySelectorAll('ul.accordion > li').forEach(function(item) { // Apply the required content fold afterwards to simplify the html item.querySelector('div').classList.add('fold'); }); })();
import 'accordion/src/accordion.js'; (function() { "use strict"; document.querySelectorAll('.accordion').forEach(function(item) { new Accordion(item, { onToggle: function(target){ // Only allow one accordion item open at time target.accordion.folds.forEach(fold => { if(fold !== target) { fold.open = false; } }); // Allow the content to be shown if its open or hide it when closed target.content.classList.toggle('hidden') }, enabledClass: 'enabled' }); // Hide all accordion content from the start so content inside it isn't part of the tabindex item.querySelectorAll('.content').forEach(function(item) { item.classList.add('hidden'); }); // Remove the role="tablist" since it is not needed item.removeAttribute('role'); item.querySelectorAll('li a:first-child').forEach(function(item) { item.setAttribute('role', 'button'); }); }); document.querySelectorAll('ul.accordion > li').forEach(function(item) { // Apply the required content fold afterwards to simplify the html item.querySelector('div').classList.add('fold'); }); })();
Set the role to button instead of tab
Set the role to button instead of tab
JavaScript
mit
waynestate/base-site,waynestate/base-site
2a8170bd4f0ed6fad4dcd8441c2e8d162fbc4431
simple-todos.js
simple-todos.js
if (Meteor.isClient) { // This code only runs on the client Template.body.helpers({ tasks: [ { text: "This is task 1" }, { text: "This is task 2" }, { text: "This is task 3" } ] }); }
Tasks = new Mongo.Collection("tasks"); if (Meteor.isClient) { // This code only runs on the client Template.body.helpers({ tasks: function () { return Tasks.find({}); } }); }
Make tasks a MongoDB collection.
Make tasks a MongoDB collection.
JavaScript
mit
chooie/meteor-todo
c5ca7c86331bb349c4bd3ccd7d5c12cdce0fa924
utils/getOutputPath.js
utils/getOutputPath.js
const path = require('path'); const getOptions = require('./getOptions'); module.exports = (options, jestRootDir) => { // Override outputName and outputDirectory with outputFile if outputFile is defined let output = options.outputFile; if (!output) { // Set output to use new outputDirectory and fallback on original output const outputName = (options.uniqueOutputName === 'true') ? getOptions.getUniqueOutputName() : options.outputName output = path.join(options.outputDirectory, outputName); } const finalOutput = getOptions.replaceRootDirInOutput(jestRootDir, output); return finalOutput; };
const path = require('path'); const getOptions = require('./getOptions'); module.exports = (options, jestRootDir) => { // Override outputName and outputDirectory with outputFile if outputFile is defined let output = options.outputFile; if (!output) { // Set output to use new outputDirectory and fallback on original output const outputName = (options.uniqueOutputName === 'true') ? getOptions.getUniqueOutputName() : options.outputName output = getOptions.replaceRootDirInOutput(jestRootDir, options.outputDirectory); const finalOutput = path.join(output, outputName); return finalOutput; } const finalOutput = getOptions.replaceRootDirInOutput(jestRootDir, output); return finalOutput; };
Replace <rootDir> prior to path.join().
Replace <rootDir> prior to path.join(). This allows outputDirectory to be formatted like <rootDir>/../some/dir. In that case, path.join() assumes the .. cancels out the <rootDir>, which seems entirely reasonable. Unfortunately, it means the final value is some/dir, and that ends up rooted at process.cwd(), which doesn't always match <rootDir>. Handling the <rootDir> replacement first allevaites this problem.
JavaScript
apache-2.0
palmerj3/jest-junit
39b2bb6cf1148bb0c63d19b52473c46e77c5c212
src/components/SSOLanding.js
src/components/SSOLanding.js
import React from 'react'; import PropTypes from 'prop-types'; import { withRouter } from 'react-router'; import Link from 'react-router-dom/Link'; import queryString from 'query-string'; const SSOLanding = (props) => { const search = props.location.search; if (!search) { return <div>No search string</div>; } const query = queryString.parse(search); const token = query['sso-token']; if (!token) { return <div>No <tt>sso-token</tt> query parameter</div>; } props.stripes.setToken(token); return ( <div> <p>Logged in with: token <tt>{token}</tt></p> <p><Link to="/">continue</Link></p> </div> ); }; SSOLanding.propTypes = { location: PropTypes.shape({ search: PropTypes.string, }).isRequired, stripes: PropTypes.shape({ setToken: PropTypes.func.isRequired, }).isRequired, }; export default withRouter(SSOLanding);
import React from 'react'; import PropTypes from 'prop-types'; import { withRouter } from 'react-router'; import Link from 'react-router-dom/Link'; import queryString from 'query-string'; const SSOLanding = (props) => { const search = props.location.search; if (!search) { return <div>No search string</div>; } const query = queryString.parse(search); const token = query['ssoToken']; if (!token) { return <div>No <tt>ssoToken</tt> query parameter</div>; } props.stripes.setToken(token); return ( <div> <p>Logged in with: token <tt>{token}</tt></p> <p><Link to="/">continue</Link></p> </div> ); }; SSOLanding.propTypes = { location: PropTypes.shape({ search: PropTypes.string, }).isRequired, stripes: PropTypes.shape({ setToken: PropTypes.func.isRequired, }).isRequired, }; export default withRouter(SSOLanding);
Change name of SSO token parameter from sso-token to ssoToken
Change name of SSO token parameter from sso-token to ssoToken This makes is consistent with the cookie-name that I am about to implement. The spec for cookies says hyphens are OK in the name, but not everyone's experience agrees: see https://stackoverflow.com/a/27235182 Modifies STCOR-20; relates to STCOR-38.
JavaScript
apache-2.0
folio-org/stripes-core,folio-org/stripes-core,folio-org/stripes-core
5193f5908f8929b7908649950161d9531c04f8b1
lib/assets/javascripts/new-dashboard/store/utils/getCARTOData.js
lib/assets/javascripts/new-dashboard/store/utils/getCARTOData.js
export default function getCARTOData () { if (window.CartoConfig) { return window.CartoConfig.data; } return { user_data: window.user_data, organization_notifications: window.organization_notifications }; }
export default function getCARTOData () { if (window.CartoConfig) { return window.CartoConfig.data; } return { user_data: window.user_data, organization_notifications: window.organization_notifications || [] }; }
Set organization_notifications to [] if no notificarions are available
Set organization_notifications to [] if no notificarions are available
JavaScript
bsd-3-clause
CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb