commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
1c9dd302192c8842ffd760e8e1689b602b4350c4
examples/simple/webpack.config.js
examples/simple/webpack.config.js
var path = require( 'path' ); var webpack = require( 'webpack' ); module.exports = { devtool: 'cheap-module-eval-source-map', entry: [ 'webpack-hot-middleware/client', './index.jsx' ], output: { path: path.join( __dirname, 'dist' ), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.optimize.OccurrenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], module: { loaders: [ { test: /\.jsx?$/, loaders: [ 'babel' ], exclude: /node_modules/, include: __dirname } ] } };
var path = require( 'path' ); var webpack = require( 'webpack' ); module.exports = { devtool: 'cheap-module-eval-source-map', entry: [ 'webpack-hot-middleware/client', './index.jsx' ], output: { path: path.join( __dirname, 'dist' ), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.optimize.OccurrenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], module: { loaders: [ { test: /\.jsx?$/, loaders: [ 'babel' ], exclude: /node_modules/, include: __dirname } ] }, resolve: { extensions: [ '', '.js', '.jsx' ], modulesDirectories: [ 'node_modules' ] } };
Add .jsx to resolver for webpack.
Add .jsx to resolver for webpack.
JavaScript
mit
coderkevin/redux-trigger
cd9c75960c99ece71cadd691eb0297850e623a47
spec/javascripts/behaviors/autosize_spec.js
spec/javascripts/behaviors/autosize_spec.js
/* eslint-disable space-before-function-paren, no-var, comma-dangle, no-return-assign, max-len */ import '~/behaviors/autosize'; (function() { describe('Autosize behavior', function() { var load; beforeEach(function() { return setFixtures('<textarea class="js-autosize" style="resize: vertical"></textarea>'); }); it('does not overwrite the resize property', function() { load(); return expect($('textarea')).toHaveCss({ resize: 'vertical' }); }); return load = function() { return $(document).trigger('load'); }; }); }).call(window);
import '~/behaviors/autosize'; function load() { $(document).trigger('load'); } describe('Autosize behavior', () => { beforeEach(() => { setFixtures('<textarea class="js-autosize" style="resize: vertical"></textarea>'); }); it('does not overwrite the resize property', () => { load(); expect($('textarea')).toHaveCss({ resize: 'vertical', }); }); });
Remove iife and eslint disable
Remove iife and eslint disable
JavaScript
mit
mmkassem/gitlabhq,stoplightio/gitlabhq,jirutka/gitlabhq,dreampet/gitlab,jirutka/gitlabhq,mmkassem/gitlabhq,iiet/iiet-git,mmkassem/gitlabhq,axilleas/gitlabhq,dreampet/gitlab,jirutka/gitlabhq,iiet/iiet-git,dreampet/gitlab,axilleas/gitlabhq,stoplightio/gitlabhq,mmkassem/gitlabhq,iiet/iiet-git,axilleas/gitlabhq,dreampet/gitlab,axilleas/gitlabhq,stoplightio/gitlabhq,stoplightio/gitlabhq,jirutka/gitlabhq,iiet/iiet-git
990f5face2b6eab527e91e98e6d20227c1673479
app/js/models/user/User.Module.js
app/js/models/user/User.Module.js
var _ = require('underscore'); var Mosaic = require('mosaic-commons'); var App = require('mosaic-core').App; var Api = App.Api; var Teleport = require('mosaic-teleport'); /** This module manages resource statistics. */ module.exports = Api.extend({ /** * Initializes internal fields. */ _initFields : function() { this._user = null; }, /** * Loads information about selected/active entities. */ start : function() { }, /** Closes this module. */ stop : function() { }, _http : function(url, method) { method = method || 'GET'; var client = Teleport.HttpClient.newInstance({ baseUrl : url }); return client.exec({ path : '', method : method }).then(function(json) { try { return _.isObject(json) ? json : JSON.parse(json); } catch (err) { return; } }); }, logout : function() { return this._http(this.app.options.logoutApiUrl).then(function(user) { return user; }); }, getUserInfo : function() { return this._http(this.app.options.userInfoApiUrl).then(function(user) { if (!user || !user.displayName) return; return user; }); }, });
var _ = require('underscore'); var Mosaic = require('mosaic-commons'); var App = require('mosaic-core').App; var Api = App.Api; var Teleport = require('mosaic-teleport'); /** This module manages resource statistics. */ module.exports = Api.extend({ /** * Initializes internal fields. */ _initFields : function() { this._user = null; }, /** * Loads information about selected/active entities. */ start : function() { }, /** Closes this module. */ stop : function() { }, _http : function(url, method) { method = method || 'GET'; var client = Teleport.HttpClient.newInstance({ baseUrl : url }); return client.exec({ path : '', method : method }).then(function(json) { try { return _.isObject(json) ? json : JSON.parse(json); } catch (err) { return; } }); }, logout : function() { var that = this; return this._http(this.app.options.logoutApiUrl).then(function(user) { return that.notify(); }).then(function() { return user; }); }, getUserInfo : function() { return this._http(this.app.options.userInfoApiUrl).then(function(user) { if (!user || !user.displayName) return; return user; }); }, });
Add notifications for changes in the user module
Add notifications for changes in the user module
JavaScript
mit
ubimix/techonmap-v2,ubimix/techonmap-v2,ubimix/techonmap-v2
a90e96f14501c734d425dbed86ddb0e1b80b75f1
client/app/components/organization/organization.js
client/app/components/organization/organization.js
import angular from 'angular'; import uiRouter from 'angular-ui-router'; import organizationComponent from './organization.component'; import organizationDetail from './organizationDetail/organizationDetail'; require('angular-ui-grid/ui-grid.css'); //require('angular-datatables/dist/plugins/columnfilter/angular-datatables.columnfilter.js'); //require('angular-datatables/dist/plugins/bootstrap/angular-datatables.bootstrap.js'); //require('datatables.net-select'); //require('angular-datatables/dist/plugins/select/angular-datatables.select.min.js'); let organizationModule = angular.module('organization', [ uiRouter, 'navbar', organizationDetail, require('angular-ui-grid') ]) .config(($stateProvider) => { "ngInject"; $stateProvider .state('organization', { url: '/organization', component: 'organization' }); }) .run(['Menu', function(Menu){ Menu.addToMainMenu({ display: "Organization", url: "/organization", requireLogin: true }) }]) .component('organization', organizationComponent) .name; export default organizationModule;
import angular from 'angular'; import uiRouter from 'angular-ui-router'; import organizationComponent from './organization.component'; import organizationDetail from './organizationDetail/organizationDetail'; require('angular-ui-grid/ui-grid.css'); //require('angular-datatables/dist/plugins/columnfilter/angular-datatables.columnfilter.js'); //require('angular-datatables/dist/plugins/bootstrap/angular-datatables.bootstrap.js'); //require('datatables.net-select'); //require('angular-datatables/dist/plugins/select/angular-datatables.select.min.js'); let organizationModule = angular.module('organization', [ uiRouter, 'navbar', organizationDetail, require('angular-ui-grid') ]) .config(($stateProvider) => { "ngInject"; $stateProvider .state('organization', { url: '/organization', component: 'organization' }); }) .run(['Menu', function(Menu){ Menu.addToMainMenu({ display: "Organization", url: "/organization", requireLogin: true, requireDev: true }) }]) .component('organization', organizationComponent) .name; export default organizationModule;
Make org a dev function for now
Make org a dev function for now
JavaScript
agpl-3.0
neteoc/neteoc-ui,neteoc/neteoc-ui,neteoc/neteoc-ui
20d9f937eec0d0e751a6d52098c3cb90d63e6cd1
test/index.js
test/index.js
import glob from 'glob'; import cssHook from 'css-modules-require-hook'; cssHook({generateScopedName: '[name]__[local]'}); glob.sync('**/*-test.js', {realpath: true, cwd: __dirname}).forEach(require);
require('css-modules-require-hook')({ generateScopedName: '[name]__[local]' }); require('glob') .sync('**/*-test.js', { realpath: true, cwd: require('path').resolve(process.cwd(), 'test') }) .forEach(require);
Use ES5 for test endpoint so there is no need for babel transform
Use ES5 for test endpoint so there is no need for babel transform
JavaScript
mit
nkbt/react-component-template
bee278faa8706fe7ebdf36a6cc48801cf0ea86b9
test/index.js
test/index.js
'use strict'; module.exports = function (t, a, d) { var invoked; a(t(function () { a(arguments.length, 0, "Arguments"); invoked = true; }), undefined, "Return"); a(invoked, undefined, "Is not run immediately"); setTimeout(function () { a(invoked, true, "Run in next tick"); d(); }, 10); };
'use strict'; module.exports = function (t, a, d) { var invoked; a(t(function () { a(arguments.length, 0, "Arguments"); invoked = true; }), undefined, "Return"); a(invoked, undefined, "Is not run immediately"); setTimeout(function () { a(invoked, true, "Run in next tick"); invoked = []; t(function () { invoked.push(0); }); t(function () { invoked.push(1); }); t(function () { invoked.push(2); }); setTimeout(function () { a.deep(invoked, [0, 1, 2], "Serial"); d(); }, 10); }, 10); };
Add tests for serial calls
Add tests for serial calls
JavaScript
isc
medikoo/next-tick
29f392e54a4de685118228b21c6d1312e58b9d66
test/index.js
test/index.js
var caps = require('../'); var test = require('tape'); test('works', function(t) { var TEST_ARRAY = [ ['kitten', 0.0], ['Kitten', 1 / 6.0], ['KItten', 1 / 3.0], ['KITten', 0.5], ['KITTen', 2 / 3.0], ['KITTEn', 5 / 6.0], ['KITTEN', 1.0], ['kittens ARE COOL', 7 / 16.0] ]; t.plan(TEST_ARRAY.length); TEST_ARRAY.forEach(function(value) { t.equal(caps(value[0]), value[1]); }); });
var caps = require('../'); var test = require('tape'); test('works', function(t) { var TEST_ARRAY = [ ['kitten', 0.0], ['Kitten', 1 / 6.0], ['KItten', 1 / 3.0], ['KITten', 0.5], ['KITTen', 2 / 3.0], ['KITTEn', 5 / 6.0], ['KITTEN', 1.0], ['kittens ARE COOL', 7 / 16.0], ['kitteñ', 0.0], ['kitteÑ', 1 / 6.0], ['kittÉÑ', 1 / 3.0] ]; t.plan(TEST_ARRAY.length); TEST_ARRAY.forEach(function(value) { t.equal(caps(value[0]), value[1]); }); });
Add tests for accented characters
Add tests for accented characters
JavaScript
mit
nwitch/caps-rate
5ce9c69881ea46aa6b2aa98d6d61e14fe4949f95
script.js
script.js
var html = document.getElementById("html"); var render = document.getElementById("render"); var toggle = document.getElementById("toggle"); var error = document.getElementById("error"); var code = CodeMirror.fromTextArea(document.getElementById("code"), { mode: "javascript" }); function update() { try { var element = new Function( "with(xmgen.svg) { with (xmgen.html) { return " + code.getValue() + "}}" )(); error.innerText = ""; if (toggle.classList.contains("down")) { html.innerText = element.toString(2); CodeMirror.colorize([html], "xml"); } else { render.innerHTML = element.toString(); } } catch (e) { error.innerText = e.toString(); } } code.on("change", update); toggle.addEventListener("click", function() { if (toggle.classList.contains("down")) { toggle.classList.remove("down"); html.innerHTML = ""; } else { toggle.classList.add("down"); render.innerHTML = ""; } update(); }); update();
var html = document.getElementById("html"); var render = document.getElementById("render"); var toggle = document.getElementById("toggle"); var error = document.getElementById("error"); var code = CodeMirror.fromTextArea(document.getElementById("code"), { mode: "javascript" }); function update() { try { var element = new Function( "with(xmgen.svg) { with (xmgen.html) { return " + code.getValue() + "}}" )(); error.textContent = ""; if (toggle.classList.contains("down")) { html.textContent = element.toString(2); CodeMirror.colorize([html], "xml"); } else { render.innerHTML = element.toString(); } } catch (e) { error.textContent = e.toString(); } } code.on("change", update); toggle.addEventListener("click", function() { if (toggle.classList.contains("down")) { toggle.classList.remove("down"); html.innerHTML = ""; } else { toggle.classList.add("down"); render.innerHTML = ""; } update(); }); update();
Use textContent instead of innerText
Use textContent instead of innerText
JavaScript
mit
nucular/xmgen,nucular/xmgen
c6ab3077925eb574062b1b9815bed6c954ab3cb6
lib/server.js
lib/server.js
const express = require('express') const fs = require('fs') const http = require('http') const https = require('https') const path = require('path') function startHttpServer(app, port) { const httpServer = http.Server(app) httpServer.listen(port, () => console.log(`Listening on HTTP port *:${port}`)) } function startHttpsServer(app, port, sslKey, sslCert) { const privateKey = fs.readFileSync(sslKey, 'utf8') const certificate = fs.readFileSync(sslCert, 'utf8') const httpsServer = https.Server({key: privateKey, cert: certificate}, app) httpsServer.listen(port, () => console.log(`Listening on HTTPS port *:${port}`)) } function bindRoutes(app, rootFolder) { const sendFileOptions = {root: path.resolve(rootFolder)} app.use((req, res, next) => { if (req.url.endsWith('gz')) { res.sendFile(req.url, sendFileOptions) } else { res.sendFile(`${req.url}/index.json`, sendFileOptions) } }) } function init(options) { const app = express() bindRoutes(app, options.root) startHttpServer(app, options.port) if (options.https) { startHttpsServer(app, options.https.port, options.https.sslKey, options.https.sslCert) } } module.exports = init
const express = require('express') const fs = require('fs') const http = require('http') const https = require('https') const path = require('path') function startHttpServer(app, port) { const httpServer = http.Server(app) httpServer.listen(port, () => console.log(`Listening on HTTP port *:${port}`)) } function startHttpsServer(app, port, sslKey, sslCert) { const privateKey = fs.readFileSync(sslKey, 'utf8') const certificate = fs.readFileSync(sslCert, 'utf8') const httpsServer = https.Server({key: privateKey, cert: certificate}, app) httpsServer.listen(port, () => console.log(`Listening on HTTPS port *:${port}`)) } function jsonError(res) { return function (err) { if (err) { res.status(err.status).json({}) } } } function bindRoutes(app, rootFolder) { const sendFileOptions = {root: path.resolve(rootFolder)} app.use((req, res, next) => { if (req.url.endsWith('gz')) { res.sendFile(req.url, sendFileOptions, jsonError(res)) } else { res.sendFile(`${req.url}/index.json`, sendFileOptions, jsonError(res)) } }) } function init(options) { const app = express() bindRoutes(app, options.root) startHttpServer(app, options.port) if (options.https) { startHttpsServer(app, options.https.port, options.https.sslKey, options.https.sslCert) } } module.exports = init
Send 404 errors as JSON to keep NPM happy
Send 404 errors as JSON to keep NPM happy
JavaScript
mit
heikkipora/registry-sync,heikkipora/registry-sync,heikkipora/registry-sync
f19500f18b8f577703ce1fe0318f86308335c62e
src/components/FlightTracker/FlightsForm.js
src/components/FlightTracker/FlightsForm.js
import React from 'react' export function FlightsForm({ homeFloor, value, onChange }) { function onFlightsChanged(event) { const flights = parseFloat(event.target.value) onChange(flights) } function addFlights(flights) { onChange(value + flights) } function onAddDefaultFlights() { addFlights(homeFloor) } function addFlight() { addFlights(1) } function subtractFlight() { addFlights(-1) } return ( <div> <fieldset className="input-group"> <span className="input-group-btn"> <button className="btn btn-secondary" onClick={subtractFlight} type="button">-</button> </span> <input type="number" className="form-control" value={value} onChange={onFlightsChanged} /> <span className="input-group-btn"> <button className="btn btn-secondary" onClick={addFlight} type="button">+</button> </span> </fieldset> <button className="btn btn-block btn-primary" onClick={onAddDefaultFlights}> Add {homeFloor} flights </button> <p>{value * 13} ft</p> </div> ) } FlightsForm.propTypes = { homeFloor: React.PropTypes.number, value: React.PropTypes.number, onChange: React.PropTypes.func.isRequired, } FlightsForm.defaultProps = { homeFloor: 1, value: 0, onChange() {}, }
import React from 'react' export function FlightsForm({ homeFloor, value, onChange }) { function onFlightsChanged(event) { const flights = parseFloat(event.target.value) onChange(flights) } function addFlights(flights) { onChange(value + flights) } function onAddDefaultFlights() { addFlights(homeFloor) } function addFlight() { addFlights(1) } function subtractFlight() { addFlights(-1) } return ( <div> <div className="input-group"> <span className="input-group-btn"> <button className="btn btn-secondary" onClick={subtractFlight} type="button">-</button> </span> <input type="number" className="form-control" value={value} onChange={onFlightsChanged} /> <span className="input-group-btn"> <button className="btn btn-secondary" onClick={addFlight} type="button">+</button> </span> </div> <button className="btn btn-block btn-primary" onClick={onAddDefaultFlights}> Add {homeFloor} flights </button> <p>{value * 13} ft</p> </div> ) } FlightsForm.propTypes = { homeFloor: React.PropTypes.number, value: React.PropTypes.number, onChange: React.PropTypes.func.isRequired, } FlightsForm.defaultProps = { homeFloor: 1, value: 0, onChange() {}, }
Fix styling on flights form
Fix styling on flights form
JavaScript
mit
elstgav/step-up,elstgav/stair-climber,elstgav/stair-climber
42b4ff08ac63d894afdf75eee999bb763a2c5b96
src/dataset/pastedataset.js
src/dataset/pastedataset.js
'use strict'; /** * @ngdoc directive * @name vlui.directive:pasteDataset * @description * # pasteDataset */ angular.module('vlui') .directive('pasteDataset', function (Dataset, Alerts, Logger, Config, _, Papa) { return { templateUrl: 'dataset/pastedataset.html', restrict: 'E', replace: true, scope: false, // use scope from datasetSelector link: function postLink(scope/*, element, attrs*/) { scope.datasetName = ''; scope.data = ''; // need to give this a unique name because we share the namespace scope.addPasted = function() { var data; var result = Papa.parse(scope.data, { dynamicTyping: true, header: true }); if (result.errors.length === 0) { data = result.data; } else { _.each(result.errors, function(err) { Alerts.add(err.message, 2000); }); return; } var dataset = { id: Date.now(), // time as id name: scope.datasetName, values: data, group: 'pasted' }; Dataset.dataset = Dataset.add(angular.copy(dataset)); scope.datasetChanged(); scope.datasetName = ''; scope.data = ''; scope.doneAdd(); }; } }; });
'use strict'; /** * @ngdoc directive * @name vlui.directive:pasteDataset * @description * # pasteDataset */ angular.module('vlui') .directive('pasteDataset', function (Dataset, Alerts, Logger, Config, _, dl) { return { templateUrl: 'dataset/pastedataset.html', restrict: 'E', replace: true, scope: false, // use scope from datasetSelector link: function postLink(scope/*, element, attrs*/) { scope.datasetName = ''; scope.data = ''; // need to give this a unique name because we share the namespace scope.addPasted = function() { var data = dl.read(response.data, {type: 'csv'}); var dataset = { id: Date.now(), // time as id name: scope.datasetName, values: data, group: 'pasted' }; Dataset.dataset = Dataset.add(angular.copy(dataset)); scope.datasetChanged(); scope.datasetName = ''; scope.data = ''; scope.doneAdd(); }; } }; });
Use details parser for reading pasted data
Use details parser for reading pasted data
JavaScript
bsd-3-clause
uwdata/vega-lite-ui,vega/vega-lite-ui,uwdata/vega-lite-ui,vega/vega-lite-ui,vega/vega-lite-ui,uwdata/vega-lite-ui
16bc4ac36243d04e1dbc3e7675137cb016ed9c5e
server.js
server.js
var express = require('express'); var redis = require('ioredis'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/endpoints'); var users = require('./routes/users'); var api = express(); // var redis = new Redis('/tmp/redis.sock'); api.get('/', function(req, res){ res.send('Hello World'); }); api.use(function(err, req, res, next){ console.error(err.stack); res.send(500, 'Something broke!'); }); api.set('port', process.env.PORT || 3000); var server = api.listen(api.get('port'), function() { console.log('Listening on port %d', server.address().port); });
var express = require('express'); var redis = require('ioredis'); var path = require('path'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var endpoints = require('./routes/endpoints'); var users = require('./routes/users'); var api = express(); // var redis = new Redis('/tmp/redis.sock'); // view engine setup api.set('views', path.join(__dirname, 'views')); api.set('view engine', 'jade'); api.use(bodyParser.json()); api.use(bodyParser.urlencoded()); api.use(cookieParser()); api.get('/', function(req, res){ res.send('Hello World'); }); api.use(function(err, req, res, next){ console.error(err.stack); res.send(500, 'Something broke!'); }); api.set('port', process.env.PORT || 3000); api.set('env', 'development'); var server = api.listen(api.get('port'), function() { console.log('Listening on port %d', server.address().port); }); api.use(express.static(path.join(__dirname, 'public'))); api.use('/', endpoints); api.use('/users', users); /// error handlers /// catch 404 and forward to error handler api.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // development error handler // will print stacktrace if (api.get('env') === 'development') { api.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user api.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); });
Add error handling, endpoints, and view engine w/ views
Add error handling, endpoints, and view engine w/ views
JavaScript
mit
nathansmyth/node-stack,nathansmyth/node-stack
f7bba22e5b5b3ee2fc1b14402f5c265a8a087170
server.js
server.js
'use strict'; // Dependencies var express = require('express'); var http = require('http'); var bodyparser = require('body-parser'); // Config var app = express(); app.use(bodyparser.json()); app.use(express.static(__dirname + (process.env.STATIC_DIR || '/build'))); // Routing require('./expressRoutes')(app); // Init var server = app.listen(process.env.PORT || 3000, function() { console.log('Lookin legit on port: %d', server.address().port); });
'use strict'; // Dependencies var express = require('express'); var http = require('http'); var bodyparser = require('body-parser'); // Config var app = express(); app.use(bodyparser.json()); app.use(express.static(__dirname + (process.env.STATIC_DIR || '/build'))); // Routing require('./expressRoutes')(app); // Init var port = process.env.PORT || 3000; var server = app.listen(port, function() { console.log('Lookin legit on port: %d', server.address().port); }); exports.port = port;
Add port as an export, for testing
Add port as an export, for testing
JavaScript
mit
Localhost3000/along-the-way
25ca4515d828802927aec301c7721fe4fe294e0b
Melchior/JS/Socket.js
Melchior/JS/Socket.js
var Sockets = {} Sockets.Socket = function Socket (signal) { if(!('WebSocket' in window)) throw new Error("Websockets not supported in this browser") this.connection = io.connect('http://localhost:3001') this.signal = signal this.connection.onopen = function () { //hmmm... } this.connection.onclose = function () { //hmmm... } this.connection.onerror = function(e) { console.error(e) } this.send = function (value) { //stringify? this.connection.send(value) } this.connection.on('data', function(value) { this.signal.push(value) }) } Sockets.createSocketedSignal = function() { var signal = new Signal(), socket = new Sockets.Socket(signal) return signal }
var Sockets = {} Sockets.Socket = function Socket (signal) { if(!('WebSocket' in window)) throw new Error("Websockets not supported in this browser") this.connection = io ? io.connect('http://localhost:3001') : new WebSocket("ws://localhost:3001") this.signal = signal this.send = this.connection.emit ? function (value) { this.connection.emit('data', value) } : function (value) { //stringify? this.connection.send(value) } if(this.connection.on) this.connection.on('data', function(value) { this.signal.push(value) }) else this.connection.onmessage = function(value) { this.signal.push(value) } } Sockets.createSocketedSignal = function() { var signal = new Signal(), socket = new Sockets.Socket(signal) return signal }
Make it less tightly coupled with socket.io
Make it less tightly coupled with socket.io
JavaScript
mit
kjgorman/melchior,kjgorman/melchior,kjgorman/melchior,kjgorman/melchior,kjgorman/melchior,kjgorman/melchior
14382c87363ebc85f58b0da4b5689f8d0f0140bd
src/util/valid-auth-type.js
src/util/valid-auth-type.js
/*global module */ module.exports = function validAuthType(type) { 'use strict'; var authTypes = ['AWS_IAM', 'NONE', 'CUSTOM']; return (authTypes.indexOf(type) >= 0); };
/*global module */ module.exports = function validAuthType(type) { 'use strict'; var authTypes = ['AWS_IAM', 'NONE', 'CUSTOM', 'COGNITO_USER_POOLS']; return (authTypes.indexOf(type) >= 0); };
Allow cognito user pool authorization
Allow cognito user pool authorization
JavaScript
mit
dhackner/claudia,dhackner/claudia
6f19117980bf8943f0c36d310e9b74466e82dc11
src/modules/search/middleware/collection.js
src/modules/search/middleware/collection.js
const { search, exportSearch } = require('../services') const { transformApiResponseToSearchCollection } = require('../transformers') function getCollection (searchEntity, entityDetails, ...itemTransformers) { return async function (req, res, next) { try { res.locals.results = await search({ searchEntity, requestBody: req.body, token: req.session.token, page: req.query.page, isAggregation: false, }).then(transformApiResponseToSearchCollection({ query: req.query }, entityDetails, ...itemTransformers)) next() } catch (error) { next(error) } } } function exportCollection (searchEntity) { return async function (req, res, next) { try { exportSearch({ searchEntity, requestBody: req.body, token: req.session.token, }).then(apiReq => { return apiReq.pipe(res) }).catch(error => { return next(error) }) } catch (error) { next(error) } } } module.exports = { exportCollection, getCollection, }
const { search, exportSearch } = require('../services') const { transformApiResponseToSearchCollection } = require('../transformers') function getCollection (searchEntity, entityDetails, ...itemTransformers) { return async function (req, res, next) { try { res.locals.results = await search({ searchEntity, requestBody: req.body, token: req.session.token, page: req.query.page, isAggregation: false, }).then(transformApiResponseToSearchCollection({ query: req.query }, entityDetails, ...itemTransformers)) next() } catch (error) { next(error) } } } function exportCollection (searchEntity) { return async function (req, res, next) { return exportSearch({ searchEntity, requestBody: req.body, token: req.session.token, }).then(apiReq => { return apiReq.pipe(res) }).catch(error => { return next(error) }) } } module.exports = { exportCollection, getCollection, }
Remove redundant exception handling in exportCollection
Remove redundant exception handling in exportCollection
JavaScript
mit
uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-frontend
6eae6d6034c9b3ceb6e564498d9fc0bfeb4bbc9b
src/Object.js
src/Object.js
/** * @require {core.ext.Object} * @require {core.ext.String} * @require {core.ext.Function} */ core.Class("lowland.Object", { include : [core.property.MGeneric, lowland.base.UserData, lowland.base.Events], construct : function() { lowland.base.UserData.call(this); lowland.base.Events.call(this); } });
/** * @require {core.ext.Object} * @require {core.ext.String} * @require {core.ext.Function} */ core.Class("lowland.Object", { include : [core.property.MGeneric, lowland.base.UserData, lowland.base.Events], construct : function() { lowland.base.UserData.call(this); lowland.base.Events.call(this); }, members : { error : function() { console.error(this.constructor || this, arguments); }, warn : function() { console.warn(this.constructor || this, arguments); } } });
Add warn and error to generic object
Add warn and error to generic object
JavaScript
mit
fastner/lowland,fastner/lowland
5fd9fe62dcd6e442344d202bc7d9c4fa0fea0a18
src/network.js
src/network.js
// https://en.bitcoin.it/wiki/List_of_address_prefixes module.exports = { bitcoin: { bip32: { pub: 0x0488b21e, priv: 0x0488ade4 }, pubKeyHash: 0x00, scriptHash: 0x05, wif: 0x80 }, dogecoin: { pubKeyHash: 0x30, scriptHash: 0x20, wif: 0x9e }, litecoin: { scriptHash: 0x30, }, testnet: { bip32: { pub: 0x043587cf, priv: 0x04358394 }, pubKeyHash: 0x6f, scriptHash: 0xc4, wif: 0xef } }
// https://en.bitcoin.it/wiki/List_of_address_prefixes // Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731 module.exports = { bitcoin: { bip32: { pub: 0x0488b21e, priv: 0x0488ade4 }, pubKeyHash: 0x00, scriptHash: 0x05, wif: 0x80 }, dogecoin: { bip32: { pub: 0x02facafd, priv: 0x02fac398 }, pubKeyHash: 0x1e, scriptHash: 0x16, wif: 0x9e }, litecoin: { bip32: { pub: 0x019da462, priv: 0x019d9cfe }, pubKeyHash: 0x30, scriptHash: 0x05, wif: 0xb0 }, testnet: { bip32: { pub: 0x043587cf, priv: 0x04358394 }, pubKeyHash: 0x6f, scriptHash: 0xc4, wif: 0xef } }
Fix address prefixes, add dogecoin/litecoin BIP32 versions
Fix address prefixes, add dogecoin/litecoin BIP32 versions
JavaScript
mit
bitcoinhaber/bitcoinjs-lib,bpdavenport/bitcoinjs-lib,ptcrypto/bitcoinjs-lib,erikvold/bitcoinjs-lib,junderw/bitcoinjs-lib,BitGo/BitGoJS,p2pmining/bitcoinjs-lib,BitGo/bitcoinjs-lib,bitcoinjs/bitcoinjs-lib,visvirial/bitcoinjs-lib,visvirial/bitcoinjs-lib,habibmasuro/bitcoinjs-lib,blocktrail/bitcoinjs-lib,whitj00/opalcoinjs-lib,anders94/bitcoinjs-lib,oklink-dev/bitcoinjs,fanatid/bitcoinjs-lib,eXcomm/bitcoinjs-lib,Sjors/bitcoinjs-lib,bitcoinjs/bitcoinjs-lib,scotcoin/czarcoinjs-lib,UdjinM6/bitcoinjs-lib-dash,CoinBlack/blackcoinjs-lib,CryptArc/bitcoinjs-lib,BitGo/bitcoinjs-lib,lekkas/bitcoinjs-lib,BitGo/BitGoJS,mano10/bitcoinjs-lib,janko33bd/bitcoinjs-lib,BitGo/BitGoJS,BitGo/BitGoJS,javascriptit/bitcoinjs-lib,junderw/bitcoinjs-lib
62bcabb8826bea721d9d53c6141ea2393737e90d
app/javascript/app/components/stories/stories-actions.js
app/javascript/app/components/stories/stories-actions.js
import { createAction } from 'redux-actions'; import { createThunkAction } from 'utils/redux'; const fetchStoriesInit = createAction('fetchStoriesInit'); const fetchStoriesReady = createAction('fetchStoriesReady'); const fetchStoriesFail = createAction('fetchStoriesFail'); const fetchStories = createThunkAction('fetchStories', () => dispatch => { dispatch(fetchStoriesInit()); fetch('/api/v1/stories') .then(response => { if (response.ok) return response.json(); throw Error(response.statusText); }) .then(data => { dispatch(fetchStoriesReady(data)); }) .catch(error => { console.info(error); dispatch(fetchStoriesFail()); }); }); export default { fetchStories, fetchStoriesInit, fetchStoriesReady, fetchStoriesFail };
import { createAction } from 'redux-actions'; import { createThunkAction } from 'utils/redux'; const fetchStoriesInit = createAction('fetchStoriesInit'); const fetchStoriesReady = createAction('fetchStoriesReady'); const fetchStoriesFail = createAction('fetchStoriesFail'); const TAGS = ['NDC', 'ndcsdg', 'esp', 'climate watch']; const fetchStories = createThunkAction('fetchStories', () => dispatch => { dispatch(fetchStoriesInit()); fetch(`/api/v1/stories?tags=${TAGS}`) .then(response => { if (response.ok) return response.json(); throw Error(response.statusText); }) .then(data => { dispatch(fetchStoriesReady(data)); }) .catch(error => { console.info(error); dispatch(fetchStoriesFail()); }); }); export default { fetchStories, fetchStoriesInit, fetchStoriesReady, fetchStoriesFail };
Add filter tags to stories actions on js app
Add filter tags to stories actions on js app
JavaScript
mit
Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch
603409dc7896549d58ab36821d581820c298c7ee
assets/js/util/api.js
assets/js/util/api.js
/** * Cache data. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { trackEvent } from './'; export async function trackAPIError( method, type, identifier, datapoint, error ) { // Exclude certain errors from tracking based on error code. const excludedErrorCodes = [ 'fetch_error', // Client failed to fetch from WordPress. ]; if ( excludedErrorCodes.indexOf( error.code ) >= 0 ) { return; } await trackEvent( 'api_error', `${ method }:${ type }/${ identifier }/data/${ datapoint }`, `${ error.message } (code: ${ error.code }${ error.data?.reason ? ', reason: ' + error.data.reason : '' } ])`, error.data?.status || error.code ); }
/** * Track API errors. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { trackEvent } from './'; export async function trackAPIError( method, type, identifier, datapoint, error ) { // Exclude certain errors from tracking based on error code. const excludedErrorCodes = [ 'fetch_error', // Client failed to fetch from WordPress. ]; if ( excludedErrorCodes.indexOf( error.code ) >= 0 ) { return; } await trackEvent( 'api_error', `${ method }:${ type }/${ identifier }/data/${ datapoint }`, `${ error.message } (code: ${ error.code }${ error.data?.reason ? ', reason: ' + error.data.reason : '' } ])`, error.data?.status || error.code ); }
Improve track API file header.
Improve track API file header.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
7eb5153314da93c30f41e5615ea55fb672e5534e
server/app.js
server/app.js
// Server startup script // ===================== // Responsible for configuring the server, // inserting middleware, and starting the // app up. // // Note: this was written on my iPhone, please excuse typos 'use strict' let express = require('express'), exphbs = require('express-handlebars'), app = express(), _ = require('lodash'), config = _.merge(require(__dirname + '/config/app').common, require(__dirname + '/config/app')[process.env.NODE_ENV]); // App configuration // ----------------- // Configure views and other settings app.engine('hbs', exphbs(config.handlebars)); app.set('view engine', 'hbs'); app.set('views', __dirname + '/views'); // Middleware // ---------- // Insert, configure, update middleware // Routes // ------ // Initialize user facing routes require('./controllers')(app); // Start server // ------------ // Start the server let server = app.listen(process.env.PORT, () => { console.log('Started app on localhost:' + server.address().port); });
// Server startup script // ===================== // Responsible for configuring the server, // inserting middleware, and starting the // app up. // // Note: this was written on my iPhone, please excuse typos 'use strict' let express = require('express'), exphbs = require('express-handlebars'), app = express(), _ = require('lodash'), config = _.merge(require(__dirname + '/config/app').common, require(__dirname + '/config/app')[process.env.NODE_ENV]); // App configuration // ----------------- // Configure views and other settings app.engine('hbs', exphbs(config.handlebars)); app.set('view engine', 'hbs'); app.set('views', __dirname + '/views'); // Middleware // ---------- // Insert, configure, update middleware if (_.includes(['development', 'test'], process.env.NODE_ENV)) { // DEVELOPMENT/TEST MIDDLEWARE app.use(express.static(__dirname + '/public')); } // Routes // ------ // Initialize user facing routes require('./controllers')(app); // Start server // ------------ // Start the server let server = app.listen(process.env.PORT, () => { console.log('Started app on localhost:' + server.address().port); });
Add static server middleware that is active in non-production environments only.
Add static server middleware that is active in non-production environments only.
JavaScript
mit
billpatrianakos/coverage-web,billpatrianakos/coverage-web,billpatrianakos/coverage-web
37b2967fc7523e849273d4b739184cdfc3778761
src/commands/rover/PingCommand.js
src/commands/rover/PingCommand.js
const Command = require('../Command') module.exports = class PingCommand extends Command { constructor (client) { super(client, { name: 'ping', properName: 'Ping', description: 'Ping the bot to see API latency' }) } async fn (msg) { msg.channel.send('Pinging...').then(message => { message.edit(`:ping_pong: Pong! Took **${message.createdTimestamp - msg.createdTimestamp}ms**`) }) } }
const Command = require('../Command') module.exports = class PingCommand extends Command { constructor (client) { super(client, { name: 'ping', properName: 'Ping', description: 'Ping the bot to see API latency', userPermissions: [] }) } async fn (msg) { msg.channel.send('Pinging...').then(message => { message.edit(`:ping_pong: Pong! Took **${message.createdTimestamp - msg.createdTimestamp}ms**`) }) } }
Allow ping command to be used by anyone
Allow ping command to be used by anyone
JavaScript
apache-2.0
evaera/RoVer
4c5679e121aa1a5c32fd18c40619df0c01c93ff5
app/config/sockjs_server.js
app/config/sockjs_server.js
(function() { 'use strict'; define(['sockjs'], function (sockjs) { var sockjs_opts = { sockjs_url: 'http://cdn.sockjs.org/sockjs-0.3.min.js' }; return sockjs.createServer(sockjs_opts); }); }());
(function() { 'use strict'; define(['sockjs'], function (sockjs) { return sockjs.createServer(); }); }());
Remove unused SockJS server-side config options
Remove unused SockJS server-side config options
JavaScript
mit
ndhoule/underscoreboard,ndhoule/underscoreboard
55dbc0efa497718406293b8d1d0165464c212413
client/src/teams/reducer.js
client/src/teams/reducer.js
import { ADD_TEAM_SUCCESS } from './actionCreators' let initialState = [ { id: 2, name: 'gym', colour: "#49078d", balance: 105463 }, { id: 1, name: 'fred', colour: "#23fe4d", balance: 105463 }, { id: 3, name: 'suup', colour: "#1fffe4", balance: 105463 } ] export default (state=initialState, action) => { switch (action.type) { case ADD_TEAM_SUCCESS: return Object.keys(action.response.teams).map(key => action.response.teams[key]) default: return state } }
import { ADD_TEAM_SUCCESS } from './actionCreators' const teams_in = (hash) => Object.keys(hash).map(key => hash[key]) export default (state=[], action) => { switch (action.type) { case ADD_TEAM_SUCCESS: return teams_in(action.response.teams) default: return state } }
Delete the hard-coded fake teams
Delete the hard-coded fake teams
JavaScript
mit
xpsurgery/shopping-cart,xpsurgery/shopping-cart,xpsurgery/shopping-cart
03ae44a0ef4d4c96f2578c317967bf38778f27b0
src/tracker.js
src/tracker.js
'use strict'; var trackStar = (function(){ function TrackStar() { var integrations = {}; if(!(this instanceof TrackStar)){ return new TrackStar(); } this.getIntegrations = function() { return integrations; }; this.integrate = function(integrationsObj) { if (Object.prototype.toString.call(integrationsObj) !== '[object Object]') { throw new Error('trackStar requires an Object of integrations'); } for(var key in integrationsObj){ var val = integrationsObj[key]; if (integrations.hasOwnProperty(key)) { integrations[key] = integrations[key].concat(val); } else { integrations[key] = [].concat(val); } } return this; }; // Start testing API this.wipeClean = TrackStar; // End testing API return this; } function sendFunction (context, functionName, opts) { var integrations = context.getIntegrations(); for (var key in integrations){ _integrationsMasterList[key][functionName](opts); }; } TrackStar.prototype.trackPageView = function() { sendFunction(this, 'trackPageView'); }; TrackStar.prototype.trackConversion = function(){ sendFunction(this, 'trackConversion'); }; TrackStar.prototype.trackAction = function(opts){ sendFunction(this, 'trackAction', opts); }; return window.trackStar = TrackStar(); }());
'use strict'; var trackStar = (function(){ function TrackStar() { var integrations = {}; if(!(this instanceof TrackStar)){ return new TrackStar(); } this.getIntegrations = function() { return integrations; }; this.integrate = function(integrationsObj) { if (Object.prototype.toString.call(integrationsObj) !== '[object Object]') { throw new Error('trackStar requires an Object of integrations'); } for(var key in integrationsObj){ if (integrationsObj.hasOwnProperty[key]){ var val = integrationsObj[key]; if (integrations.hasOwnProperty(key)) { integrations[key] = integrations[key].concat(val); } else { integrations[key] = [].concat(val); } } } return this; }; // Start testing API this.wipeClean = TrackStar; // End testing API return this; } function sendFunction (context, functionName, opts) { var integrations = context.getIntegrations(); for (var key in integrations){ if(integrations.hasOwnProperty(key)){ _integrationsMasterList[key][functionName](opts); } } } TrackStar.prototype.trackPageView = function() { sendFunction(this, 'trackPageView'); }; TrackStar.prototype.trackConversion = function(){ sendFunction(this, 'trackConversion'); }; TrackStar.prototype.trackAction = function(opts){ sendFunction(this, 'trackAction', opts); }; return window.trackStar = TrackStar(); }());
Make sure we're not grabbing any prototype props
Make sure we're not grabbing any prototype props Probably unnecessary, but let's be safe
JavaScript
apache-2.0
dustincoates/trackstar
20fbc6c4ccda450b31c39c739f5c438c994a67ed
src/wrapper.js
src/wrapper.js
/** Copyright (c) 2013 Jan Nicklas Released under MIT license */ /* global define: false, jQuery: true */ /* jshint sub:true */ // RequireJS amd factory // http://stackoverflow.com/questions/10918063/how-to-make-a-jquery-plugin-loadable-with-requirejs#answer-11890239 (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else { // Run without AMD factory(jQuery); } }(function ($) { 'use strict'; // @@ code @@ // }));
/** Copyright (c) 2013 Jan Nicklas Released under MIT license */ /* global define: false, jQuery: true */ /* jshint sub:true */ // RequireJS amd factory // http://stackoverflow.com/questions/10918063/how-to-make-a-jquery-plugin-loadable-with-requirejs#answer-11890239 (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else { // Run without AMD factory(jQuery); } }(function ($) { 'use strict'; // @@ include ariaMenu.js @@ // }));
Add the name of the included script
Add the name of the included script
JavaScript
mit
jantimon/ariaMenu,jantimon/ariaMenu
ce99af2e737a2afc6ffcb6a2c5e6869953b21757
app/javascript/modules/EmailParliament/index.js
app/javascript/modules/EmailParliament/index.js
import React, { useState } from 'react'; import classnames from 'classnames'; import { search } from './api'; import SearchByPostcode from './SearchByPostcode'; import EmailComposer from './EmailComposer'; import ComponentWrapper from '../../components/ComponentWrapper'; import { redirect } from '../../util/redirector'; export const init = options => { if (!options.config || !options.config.active) return; if (options.el) { render( <EmailParliament config={options.config} onSend={options.onSend} />, options.el ); } }; const EmailParliament = props => { const [target, setTarget] = useState(null); const searchClassname = classnames({ 'hidden-irrelevant': target !== null, }); return ( <div className="EmailParliament"> <ComponentWrapper locale={props.config.locale}> <SearchByPostcode className={searchClassname} onChange={setTarget} /> <EmailComposer title={props.config.title} postcode={''} target={target} subject={props.config.subject} template={props.config.template} onSend={props.onSend || redirect} /> </ComponentWrapper> </div> ); }; export default EmailParliament;
import React, { useState } from 'react'; import { render } from 'react-dom'; import classnames from 'classnames'; import { search } from './api'; import SearchByPostcode from './SearchByPostcode'; import EmailComposer from './EmailComposer'; import ComponentWrapper from '../../components/ComponentWrapper'; import { redirect } from '../../util/redirector'; export const init = options => { if (!options.config || !options.config.active) return; if (options.el) { render( <EmailParliament config={options.config} onSend={options.onSend} />, options.el ); } }; const EmailParliament = props => { const [target, setTarget] = useState(null); const searchClassname = classnames({ 'hidden-irrelevant': target !== null, }); return ( <div className="EmailParliament"> <ComponentWrapper locale={props.config.locale}> <SearchByPostcode className={searchClassname} onChange={setTarget} /> <EmailComposer title={props.config.title} postcode={''} target={target} subject={props.config.subject} template={props.config.template} onSend={props.onSend || redirect} /> </ComponentWrapper> </div> ); }; export default EmailParliament;
Fix `render is undefined` in EmailParliament
Fix `render is undefined` in EmailParliament
JavaScript
mit
SumOfUs/Champaign,SumOfUs/Champaign,SumOfUs/Champaign,SumOfUs/Champaign,SumOfUs/Champaign
407921321c4746588b60c441f69820368ed8bee3
app/assets/scripts/components/community-card.js
app/assets/scripts/components/community-card.js
'use strict'; import React from 'react'; var CommunityCard = React.createClass({ displayName: 'CommunityCard', propTypes: { title: React.PropTypes.string, linkTitle: React.PropTypes.string, url: React.PropTypes.string, imageNode: React.PropTypes.node, children: React.PropTypes.object }, render: function () { return ( <article className='card card--horizontal card--horizontal--align-middle'> <div className='card__contents'> <figure className='card__media'> <div className='card__thumbnail'> {this.props.imageNode} </div> </figure> <div className="card__copy"> <header className='card__header'> <h1 className='card__title'><a title={this.props.linkTitle} href={this.props.url}>{this.props.title}</a></h1> </header> <div className='card__body'> {this.props.children} <a title={this.props.linkTitle} href={this.props.url}>Learn More</a> </div> </div> </div> </article> ); } }); module.exports = CommunityCard;
'use strict'; import React from 'react'; import c from 'classnames'; var CommunityCard = React.createClass({ displayName: 'CommunityCard', propTypes: { title: React.PropTypes.string, linkTitle: React.PropTypes.string, url: React.PropTypes.string, imageNode: React.PropTypes.node, horizontal: React.PropTypes.bool, children: React.PropTypes.object }, getDefaultProps: function () { return { horizontal: false }; }, render: function () { return ( <article className={c('card', {'card--horizontal card--horizontal--align-middle': this.props.horizontal})}> <div className='card__contents'> <figure className='card__media'> <div className='card__thumbnail'> {this.props.imageNode} </div> </figure> <div className="card__copy"> <header className='card__header'> <h1 className='card__title'><a title={this.props.linkTitle} href={this.props.url}>{this.props.title}</a></h1> </header> <div className='card__body'> {this.props.children} <a title={this.props.linkTitle} href={this.props.url}>Learn More</a> </div> </div> </div> </article> ); } }); module.exports = CommunityCard;
Make community card horizontal by default
Make community card horizontal by default
JavaScript
bsd-3-clause
openaq/openaq.org,openaq/openaq.github.io,openaq/openaq.github.io,openaq/openaq.org,openaq/openaq.github.io,openaq/openaq.org
a12d5f8834dd451a6d70a3a1b9f8a60753246ce6
src/pages/Application/ApplicationDropdown.js
src/pages/Application/ApplicationDropdown.js
import React from 'react'; import { changeApplicationFieldValue } from '../../actions/application'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; const ApplicationTextField = ({changeApplicationFieldValue, field, applicationForm, disabled, isLoading, styles, options}) => ( <select value={applicationForm[field] || ""} onChange={ (e) => changeApplicationFieldValue(field,e.target.value) } disabled={(disabled || false) || isLoading} className="dropdown" > { Object.keys(options).map((t,i) => <option key={i} value={t}>{t}</option>) } {/* <option value="grapefruit">Grapefruit</option> <option value="lime">Lime</option> <option value="coconut">Coconut</option> <option value="mango">Mango</option> */} </select> ); function mapStateToProps (state) { return { applicationForm: state.application.applicationForm, isLoading: state.application.isLoading }; } const mapDispatchToProps = (dispatch) => { return bindActionCreators({changeApplicationFieldValue}, dispatch) }; export default connect(mapStateToProps, mapDispatchToProps)(ApplicationTextField);
import React from 'react'; import { changeApplicationFieldValue } from '../../actions/application'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; const ApplicationDropdown = ({changeApplicationFieldValue, field, applicationForm, disabled, isLoading, styles, options}) => ( <select value={applicationForm[field] || ""} onChange={ (e) => changeApplicationFieldValue(field,e.target.value) } disabled={(disabled || false) || isLoading} className="dropdown" > { Object.keys(options).map((t,i) => <option key={i} value={t}>{t}</option>) } {/* <option value="grapefruit">Grapefruit</option> <option value="lime">Lime</option> <option value="coconut">Coconut</option> <option value="mango">Mango</option> */} </select> ); function mapStateToProps (state) { return { applicationForm: state.application.applicationForm, isLoading: state.application.isLoading }; } const mapDispatchToProps = (dispatch) => { return bindActionCreators({changeApplicationFieldValue}, dispatch) }; export default connect(mapStateToProps, mapDispatchToProps)(ApplicationDropdown);
Update dropdown with properr var name
Update dropdown with properr var name
JavaScript
agpl-3.0
BoilerMake/frontend,BoilerMake/frontend
0c3cf9273f3bef100484b50bbdb1968cddc06717
src/katagroup.js
src/katagroup.js
import Kata from './kata.js'; export default class KataGroup { static withKatas(groupName, rawKataItems) { var group = new KataGroup(); group.name = groupName; group.createKatas(rawKataItems); group.sortByName(); return group; } createKatas(rawKataItems) { this.katas = rawKataItems.map(item => Kata.fromRawItem(item)); } sortByName() { this.katas.sort((kata1, kata2) => toInt(kata1.id) < toInt(kata2.id) ? -1 : 1); } get highestId() { if (this.katas.length === 0) { return 0; } return this.katas[this.katas.length - 1].id; } } const toInt = (string) => Number.parseInt(string, 10);
import Kata from './kata.js'; export default class KataGroup { static withKatas(groupName, rawKataItems) { var group = new KataGroup(); group.name = groupName; group.createKatas(rawKataItems); group.sortByName(); return group; } createKatas(rawKataItems) { this.katas = rawKataItems.map(item => Kata.fromRawItem(item)); } sortByName() { this.katas.sort((kata1, kata2) => kata1.id < kata2.id ? -1 : 1); } get highestId() { if (this.katas.length === 0) { return 0; } return this.katas[this.katas.length - 1].id; } }
Remove unnecessary conversion, that is done now at kata creation time.
Remove unnecessary conversion, that is done now at kata creation time.
JavaScript
mit
tddbin/es6katas.org
0a643864d51d550234a6391b761512467cf44e73
src/modules/navigation/reducer.js
src/modules/navigation/reducer.js
import { isArray } from 'lodash'; import { AppNavigator } from 'DailyScrum/src/Scenes'; export default (state, action) => { const { type } = action; if (type === 'Navigation/NAVIGATE' && isRouteSameAsLastRouteFromNavigationStateSelector(state, action)) { console.warn( 'You pressed the navigation button two times, pushing two times to the same route.\n\n' + 'The last dispatch was canceled. \n\n' + 'If the call was intended, you can add an exception in redux routing.', action ); return state || {}; } const newState = AppNavigator.router.getStateForAction(action, state); return newState || state; }; const isRouteSameAsLastRouteFromNavigationStateSelector = (state, action) => { const lastRoute = routeFromNavigationStateSelector(state); if (!lastRoute) { return false; } // FUTURE add exceptions here (params in lastRoute.params, action.params) return lastRoute.routeName === action.routeName; }; export const routeFromNavigationStateSelector = state => { const currentRootRoute = state.routes[state.index]; let route; if (isArray(currentRootRoute.routes)) { route = currentRootRoute.routes[currentRootRoute.index]; } else { route = currentRootRoute; } return route; };
import { isArray, isEqual } from 'lodash'; import { AppNavigator } from 'DailyScrum/src/Scenes'; export default (state, action) => { const { type } = action; if (type === 'Navigation/NAVIGATE' && isRouteSameAsLastRouteFromNavigationStateSelector(state, action)) { console.warn( 'You pressed the navigation button two times, pushing two times to the same route.\n\n' + 'The last dispatch was canceled. \n\n' + 'If the call was intended, you can add an exception in redux routing.', action ); return state || {}; } const newState = AppNavigator.router.getStateForAction(action, state); return newState || state; }; const isRouteSameAsLastRouteFromNavigationStateSelector = (state, action) => { const lastRoute = routeFromNavigationStateSelector(state); if (!lastRoute) { return false; } // FUTURE add exceptions here (params in lastRoute.params, action.params) if (lastRoute.routeName !== action.routeName) { return false; } return isEqual(lastRoute.params, action.params); }; export const routeFromNavigationStateSelector = state => { const currentRootRoute = state.routes[state.index]; let route; if (isArray(currentRootRoute.routes)) { route = currentRootRoute.routes[currentRootRoute.index]; } else { route = currentRootRoute; } return route; };
Fix navigating twice with params
Fix navigating twice with params
JavaScript
mit
Minishlink/DailyScrum,Minishlink/DailyScrum,Minishlink/DailyScrum,Minishlink/DailyScrum,Minishlink/DailyScrum
0a95b27d95b6310072080a41e1edcb5af75b32d1
server/routes/UserRoutes.js
server/routes/UserRoutes.js
import express from 'express'; import UserController from '../controllers/UserController'; const userRouter = express.Router(); userRouter.post('/api/user/signup', UserController.createUser()); userRouter.post('/api/user/signin', [ UserController.validateRequest(), UserController.authenticateUser() ]); userRouter.use('/api', [ UserController.getClientAuthToken(), UserController.authorizeUser() ]); userRouter.get('/api/user/groups', UserController.getUserGroups()); export default userRouter;
import express from 'express'; import UserController from '../controllers/UserController'; const userRouter = express.Router(); userRouter.post('/api/user/signup', UserController.createUser()); userRouter.post('/api/user/signin', [ UserController.validateRequest(), UserController.authenticateUser() ]); userRouter.use('/api', [ UserController.getClientAuthToken(), UserController.authorizeUser() ]); userRouter.put('/api/user', UserController.updateUser()); userRouter.delete('/api/user', UserController.deleteUser()); userRouter.get('/api/user/groups', UserController.getUserGroups()); export default userRouter;
Add endpoints to update and delete user
[feat]: Add endpoints to update and delete user
JavaScript
mit
tomipaul/PostIt,tomipaul/PostIt
c7fff6c1a91a69a54b9096d3698433abbcf2dd8e
source/main/utils/getNumberOfEpochsConsolidated.js
source/main/utils/getNumberOfEpochsConsolidated.js
// @flow import fs from 'fs'; import path from 'path'; import { appFolderPath } from '../config'; import { getNumberOfEpochsConsolidatedChannel } from '../ipc/getNumberOfEpochsConsolidated.ipc'; import type { GetNumberOfEpochsConsolidatedChannelResponse } from '../../common/ipc/api'; export const getNumberOfEpochsConsolidated = () => { getNumberOfEpochsConsolidatedChannel .onRequest((): Promise<GetNumberOfEpochsConsolidatedChannelResponse> => { const epochsPath = path.join(appFolderPath, 'DB-1.0', 'epochs'); let latestConsolidatedEpoch = 0; if (fs.existsSync(epochsPath)) { const epochfiles = fs .readdirSync(epochsPath) .filter(file => file.indexOf('.epoch') > -1) .map(file => parseInt(file.split('.').shift(), 10)); if (epochfiles.length) latestConsolidatedEpoch = Math.max(...epochfiles); } return Promise.resolve(latestConsolidatedEpoch); }); };
// @flow import fs from 'fs'; import path from 'path'; import { appFolderPath } from '../config'; import { getNumberOfEpochsConsolidatedChannel } from '../ipc/getNumberOfEpochsConsolidated.ipc'; import type { GetNumberOfEpochsConsolidatedChannelResponse } from '../../common/ipc/api'; import { environment } from '../environment'; const { isLinux } = environment; export const getNumberOfEpochsConsolidated = () => { getNumberOfEpochsConsolidatedChannel .onRequest((): Promise<GetNumberOfEpochsConsolidatedChannelResponse> => { const epochsPath = isLinux ? path.join(appFolderPath, 'DB', 'epochs') : path.join(appFolderPath, 'DB-1.0', 'epochs'); let latestConsolidatedEpoch = 0; if (fs.existsSync(epochsPath)) { const epochfiles = fs .readdirSync(epochsPath) .filter(file => file.indexOf('.epoch') > -1) .map(file => parseInt(file.split('.').shift(), 10)); if (epochfiles.length) latestConsolidatedEpoch = Math.max(...epochfiles); } return Promise.resolve(latestConsolidatedEpoch); }); };
Correct path for EPOCH files in Linux
[DDW-557] Correct path for EPOCH files in Linux
JavaScript
apache-2.0
input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus
67a92bb20333d5aca9d8b02f76ba9c6d94795fd6
src/Footer.js
src/Footer.js
import React from 'react'; import './scss/footer.scss'; const Footer = () => { return ( <footer> <p>© 2016 Michael Kohler - JavaScript frontend and backend developer with a passion for Web Standards</p> </footer> ); }; export default Footer;
import React from 'react'; import './scss/footer.scss'; const Footer = () => { return ( <footer> <p>© 2016 Michael Kohler - Data accurate from 2013 onwards, before some are missing..</p> </footer> ); }; export default Footer;
Add data accuracy note in footer
Add data accuracy note in footer
JavaScript
mpl-2.0
MichaelKohler/where,MichaelKohler/where
dae0c1ce82b2c0abfde8b633728dd393b094e0c1
lib/widgets/host_details_panel.js
lib/widgets/host_details_panel.js
'use strict'; let blessed = require('blessed'); let _ = require('lodash'); let config = require('../../config/config'); module.exports = function () { let hostDetailsPanel = blessed.list({ top: 5, bottom: 5, left: '30%', tags: true, border: {type: 'line'}, keys: true, scrollable: true, style: config.styles.main }); hostDetailsPanel.updateItems = function (host) { let items = []; _.forEach(host, function (val, key) { if (_.isArray(val)) val = val.join(', '); let content = '{bold}' + key + '{/bold} : ' + val + '\n'; items.push(content); }); this.setItems(items); }; return hostDetailsPanel; };
'use strict'; let blessed = require('blessed'); let _ = require('lodash'); let config = require('../../config/config'); module.exports = function () { let hostDetailsPanel = blessed.list({ top: 5, bottom: 5, left: '30%', tags: true, border: {type: 'line'}, keys: true, scrollable: true, style: config.styles.main }); hostDetailsPanel.updateItems = function (host) { let items = []; _.forEach(host, function (val, key) { if (_.isArray(val)) val = val.join(', '); key = key[0].toUpperCase() + key.slice(1); let content = '{bold}' + key + '{/bold} : ' + val + '\n'; items.push(content); }); this.setItems(items); }; return hostDetailsPanel; };
Fix keys case into details panel
Fix keys case into details panel
JavaScript
mit
etissieres/ssh-config-ui
a2e6df5e9dee79f636b21016c8a5b1b810679e19
consumer-ui/src/app/config/angular-translate.js
consumer-ui/src/app/config/angular-translate.js
angular.module('nnConsumerUi') .config(function($translateProvider) { $translateProvider.translations('fi', { 'REQUIRED_FIELD': 'Pakollinen kenttä', 'CHARACTERS_LEFT': 'Merkkiä jäljellä', 'CHOOSE_FILE': 'Valitse tiedosto', 'PRINT_BUTTON': 'Tulosta', 'SEND_MAIL_BUTTON': 'Lähetä sähköpostiin', 'MAIL_SENT_TEXT': 'Sähköposti lähetetty' }); $translateProvider.translations('sv', { 'REQUIRED_FIELD': 'Obligatoriskt fält', 'CHARACTERS_LEFT': 'Tecken kvar', 'CHOOSE_FILE': 'Välj fil', 'PRINT_BUTTON': 'Skriv ut', 'SEND_MAIL_BUTTON': 'Skicka till e-post', 'MAIL_SENT_TEXT': 'E-post skickad' }); $translateProvider.translations('en', { 'REQUIRED_FIELD': 'Required field', 'CHARACTERS_LEFT': 'Characters left', 'CHOOSE_FILE': 'Choose file', 'PRINT_BUTTON': 'Print', 'SEND_MAIL_BUTTON': 'Send to e-mail', 'MAIL_SENT_TEXT': 'E-mail sent' }); $translateProvider.preferredLanguage('fi'); $translateProvider.useSanitizeValueStrategy(null); });
angular.module('nnConsumerUi') .config(function($translateProvider) { $translateProvider.translations('fi', { 'REQUIRED_FIELD': 'Pakollinen kenttä', 'CHARACTERS_LEFT': 'Merkkiä jäljellä', 'CHOOSE_FILE': 'Valitse tiedosto', 'PRINT_BUTTON': 'Tulosta', 'SEND_MAIL_BUTTON': 'Lähetä sähköpostiin', 'MAIL_SENT_TEXT': 'Sähköposti lähetetty', 'NEXT_TEXT': 'Seuraava' }); $translateProvider.translations('sv', { 'REQUIRED_FIELD': 'Obligatoriskt fält', 'CHARACTERS_LEFT': 'Tecken kvar', 'CHOOSE_FILE': 'Välj fil', 'PRINT_BUTTON': 'Skriv ut', 'SEND_MAIL_BUTTON': 'Skicka till e-post', 'MAIL_SENT_TEXT': 'E-post skickad', 'NEXT_TEXT': 'Nästa' }); $translateProvider.translations('en', { 'REQUIRED_FIELD': 'Required field', 'CHARACTERS_LEFT': 'Characters left', 'CHOOSE_FILE': 'Choose file', 'PRINT_BUTTON': 'Print', 'SEND_MAIL_BUTTON': 'Send to e-mail', 'MAIL_SENT_TEXT': 'E-mail sent', 'NEXT_TEXT': 'Next' }); $translateProvider.preferredLanguage('fi'); $translateProvider.useSanitizeValueStrategy(null); });
Add missing translation to consumer-ui
Add missing translation to consumer-ui
JavaScript
mit
nordsoftware/nettineuvoja,nordsoftware/nettineuvoja,nordsoftware/nettineuvoja,nordsoftware/nettineuvoja,nordsoftware/nettineuvoja
5e456f6017c550a56d685963f007b8f73563fb57
tasks/jscs.js
tasks/jscs.js
"use strict"; var Vow = require( "vow" ); module.exports = function( grunt ) { var filter = Array.prototype.filter, JSCS = require( "./lib/jscs" ).init( grunt ); grunt.registerMultiTask( "jscs", "JavaScript Code Style checker", function() { var done = this.async(), options = this.options({ config: null }), jscs = new JSCS( options ), checks = this.filesSrc.map(function( path ) { return jscs.check( path ); }); Vow.allResolved( checks ).spread(function() { // Filter unsuccessful promises var results = filter.call( arguments, function( promise ) { return promise.isFulfilled(); // Make array of errors }).map(function( promise ) { return promise.valueOf()[ 0 ]; }); jscs.setErrors( results ).report().notify(); done( options.force || !jscs.count() ); }); }); };
"use strict"; var Vow = require( "vow" ); module.exports = function( grunt ) { var filter = Array.prototype.filter, JSCS = require( "./lib/jscs" ).init( grunt ); grunt.registerMultiTask( "jscs", "JavaScript Code Style checker", function() { var done = this.async(), options = this.options({ // null is a default value, but its equivalent to `true`, // with this way it's easy to distinguish specified value config: null }), jscs = new JSCS( options ), checks = this.filesSrc.map(function( path ) { return jscs.check( path ); }); Vow.allResolved( checks ).spread(function() { // Filter unsuccessful promises var results = filter.call( arguments, function( promise ) { return promise.isFulfilled(); // Make array of errors }).map(function( promise ) { return promise.valueOf()[ 0 ]; }); jscs.setErrors( results ).report().notify(); done( options.force || !jscs.count() ); }); }); };
Add comment for null as default value
Add comment for null as default value
JavaScript
mit
markelog/grunt-checker
5525d5f5d22faf3a65324de927de277cbb877e94
app/utils/george-foreman.js
app/utils/george-foreman.js
export default class GeorgeForeman { constructor() { } }
export default class GeorgeForeman { constructor() { this.generation = GeorgeForeman.addGeneration(); } name() { return `George Foreman ${this.formatGeneration()}`; } formatGeneration() { switch (this.generation) { case 2: return "II"; default: return ""; } } static addGeneration() { if(!this.generation && this.generation !== 1) { this.generation = 1; } else { this.generation += 1; } return this.generation; } }
Implement class/static method for George
Implement class/static method for George
JavaScript
mit
Riverside-Ruby/learning-es6,Riverside-Ruby/learning-es6
a89ea164e9bc1a883283bd9c610a8f0738c53828
Kwc/Statistics/OptBox/Component.defer.js
Kwc/Statistics/OptBox/Component.defer.js
var $ = require('jQuery'); var onReady = require('kwf/on-ready'); var cookieOpt = require('kwf/cookie-opt'); onReady.onRender('.kwcClass', function (el, config) { if (!cookieOpt.isSetOpt()) { if (config.showBanner) { setTimeout(function(){ $('body').addClass('kwfUp-showCookieBanner'); }, 1000); } el.show(); el.find('.kwcBem__accept').click(function(e) { e.preventDefault(); cookieOpt.setOpt('in'); el.hide(); $('body').removeClass('kwfUp-showCookieBanner'); }); } }); cookieOpt.onOptChange(function(value) { $('body').find('.kwcClass').hide(); });
var $ = require('jQuery'); var onReady = require('kwf/on-ready'); var cookieOpt = require('kwf/cookie-opt'); onReady.onRender('.kwcClass', function (el, config) { if (!cookieOpt.isSetOpt()) { if (config.showBanner) { setTimeout(function(){ $('body').addClass('kwfUp-showCookieBanner'); onReady.callOnContentReady($('body'), { action: 'widthChange' }); }, 1000); } el.show(); el.find('.kwcBem__accept').click(function(e) { e.preventDefault(); cookieOpt.setOpt('in'); el.hide(); $('body').removeClass('kwfUp-showCookieBanner'); onReady.callOnContentReady($('body'), { action: 'widthChange' }); }); } }); cookieOpt.onOptChange(function(value) { $('body').find('.kwcClass').hide(); });
Call resizeevent on body when cookiebanner change visibility Make it possible to change something in web after the visibility of the cookiebanner changed. For example to move fixed content, if the cookiebanner appears on top of the page.
Call resizeevent on body when cookiebanner change visibility Make it possible to change something in web after the visibility of the cookiebanner changed. For example to move fixed content, if the cookiebanner appears on top of the page.
JavaScript
bsd-2-clause
koala-framework/koala-framework,koala-framework/koala-framework
85cd4f35e321082c407bb41ab6ea6f22b7bf1017
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var streamify = require('gulp-streamify'); var size = require('gulp-size'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var del = require('del'); var config = { namespace: 'braintree', src: { js: { all: './src/**/*.js', main: './index.js', watch: './public/js/**/*.js', output: 'app.built.js', min: 'app.built.min.js' } }, dist: {js: 'dist/js'} }; gulp.task('js', function () { return browserify(config.src.js.main) .bundle() .pipe(source(config.src.js.output)) .pipe(streamify(size())) .pipe(gulp.dest(config.dist.js)) .pipe(streamify(uglify())) .pipe(streamify(size())) .pipe(rename(config.src.js.min)) .pipe(gulp.dest(config.dist.js)); }); gulp.task('watch', ['js'], function () { gulp.watch(config.src.js.watch, ['js']); }); gulp.task('clean', function (done) { del([config.dist.js], done); }); gulp.task('build', ['clean', 'js']);
'use strict'; var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var streamify = require('gulp-streamify'); var size = require('gulp-size'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var del = require('del'); var config = { src: { js: { all: './src/**/*.js', main: './index.js', watch: './public/js/**/*.js', output: 'app.built.js', min: 'app.built.min.js' } }, options: { standalone: 'creditCardType' }, dist: {js: 'dist/js'} }; gulp.task('js', function () { return browserify(config.src.js.main, config.options) .bundle() .pipe(source(config.src.js.output)) .pipe(streamify(size())) .pipe(gulp.dest(config.dist.js)) .pipe(streamify(uglify())) .pipe(streamify(size())) .pipe(rename(config.src.js.min)) .pipe(gulp.dest(config.dist.js)); }); gulp.task('watch', ['js'], function () { gulp.watch(config.src.js.watch, ['js']); }); gulp.task('clean', function (done) { del([config.dist.js], done); }); gulp.task('build', ['clean', 'js']);
Add standalone field to browserify build
Add standalone field to browserify build closes #29
JavaScript
mit
braintree/credit-card-type
9839b8526e45a1f5d8b99ffab99a37e06f3f6598
client/js/directives/header-entry-directive.js
client/js/directives/header-entry-directive.js
"use strict"; angular.module("hikeio"). directive("headerEntry", function() { return { scope: { align: "@", label: "@", url: "@" }, template: "<a href='{{url}}'>" + "<div style='float:{{align}}' >" + "<div class='header-separator' data-ng-show='align == \"right\"'></div>" + "<div class='header-entry' data-ng-transclude>" + "<span class='label' data-ng-show='label'>{{label}}</span>" + "</div>" + "<div class='header-separator' data-ng-show='align == \"left\"'></div>" + "</div>" + "</a>", transclude: true }; });
"use strict"; angular.module("hikeio"). directive("headerEntry", function() { return { scope: { align: "@", label: "@", url: "@" }, template: "<a href='{{url}}'>" + "<div data-ng-style='{float:align}' >" + "<div class='header-separator' data-ng-show='align == \"right\"'></div>" + "<div class='header-entry' data-ng-transclude>" + "<span class='label' data-ng-show='label'>{{label}}</span>" + "</div>" + "<div class='header-separator' data-ng-show='align == \"left\"'></div>" + "</div>" + "</a>", transclude: true }; });
Use ng-style to fix header float issue on ie10.
Use ng-style to fix header float issue on ie10.
JavaScript
mit
zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io
8f4e0f16a0985578c49462475df6abf89540c673
gulpfile.js
gulpfile.js
/* * Paper.js - The Swiss Army Knife of Vector Graphics Scripting. * http://paperjs.org/ * * Copyright (c) 2011 - 2016, Juerg Lehni & Jonathan Puckey * http://scratchdisk.com/ & http://jonathanpuckey.com/ * * Distributed under the MIT license. See LICENSE file for details. * * All rights reserved. */ var gulp = require('gulp'), qunit = require('gulp-qunit'); gulp.task('test', function() { return gulp.src('./test/index.html') .pipe(qunit()); });
/* * Paper.js - The Swiss Army Knife of Vector Graphics Scripting. * http://paperjs.org/ * * Copyright (c) 2011 - 2016, Juerg Lehni & Jonathan Puckey * http://scratchdisk.com/ & http://jonathanpuckey.com/ * * Distributed under the MIT license. See LICENSE file for details. * * All rights reserved. */ var gulp = require('gulp'), qunit = require('gulp-qunit'); gulp.task('test', function() { return gulp.src('./test/index.html') .pipe(qunit({ timeout: 10 })); });
Increase QUnit timeout to 10s, as Travis doesn't finish in time.
Increase QUnit timeout to 10s, as Travis doesn't finish in time.
JavaScript
mit
lehni/paper.js,iconexperience/paper.js,lehni/paper.js,iconexperience/paper.js,lehni/paper.js,iconexperience/paper.js
845280ecb6b8ad4c97ca248a6f7322e1fd38da25
lib/api.js
lib/api.js
var parse = require('./parse'); module.exports = function(data) { this.token = data.token; }; module.exports.prototype = { get: function() { query = parse.query(arguments); callback = parse.callback(arguments); }, post: function() { }, put: function() { }, del: function() { } };
var parse = require('./parse'); module.exports = function(data) { this.token = data.token; }; module.exports.prototype = { get: function() { query = parse.query(arguments); callback = parse.callback(arguments); }, post: function() { query = parse.query(arguments); callback = parse.callback(arguments); }, put: function() { query = parse.query(arguments); callback = parse.callback(arguments); }, del: function() { query = parse.query(arguments); callback = parse.callback(arguments); } };
Add query and callback parsing to get/post/put/del
Add query and callback parsing to get/post/put/del
JavaScript
apache-2.0
phonegap/node-phonegap-build-api
1c1f3d90b4b66f335351ae4d66c86ca98cb8b339
packages/react-app-rewired/index.js
packages/react-app-rewired/index.js
const babelLoaderMatcher = function(rule) { return rule.loader && rule.loader.indexOf("babel-loader/") != -1; } const getLoader = function(rules, matcher) { var loader; rules.some(rule => { return loader = matcher(rule) ? rule : getLoader(rule.use || rule.oneOf || [], matcher); }); return loader; }; const getBabelLoader = function(rules) { return getLoader(rules, babelLoaderMatcher); } const injectBabelPlugin = function(pluginName, config) { const loader = getBabelLoader(config.module.rules); if (!loader) { console.log("babel-loader not found"); return config; } loader.options.plugins = [pluginName].concat(loader.options.plugins || []); return config; }; module.exports = { getLoader, getBabelLoader, injectBabelPlugin };
const path = require('path'); const babelLoaderMatcher = function(rule) { return rule.loader && rule.loader.indexOf(`babel-loader${path.sep}`) != -1; } const getLoader = function(rules, matcher) { var loader; rules.some(rule => { return loader = matcher(rule) ? rule : getLoader(rule.use || rule.oneOf || [], matcher); }); return loader; }; const getBabelLoader = function(rules) { return getLoader(rules, babelLoaderMatcher); } const injectBabelPlugin = function(pluginName, config) { const loader = getBabelLoader(config.module.rules); if (!loader) { console.log("babel-loader not found"); return config; } loader.options.plugins = [pluginName].concat(loader.options.plugins || []); return config; }; module.exports = { getLoader, getBabelLoader, injectBabelPlugin };
Fix plugin injection on Windows
Fix plugin injection on Windows
JavaScript
mit
timarney/react-app-rewired,timarney/react-app-rewired
893bfb091ed0e6f9f46672ca280334171098defe
src/config.js
src/config.js
let userConfig; try { userConfig = require('../config'); } catch (e) { throw new Error(`Config file could not be found or read! The error given was: ${e.message}`); } const defaultConfig = { "token": null, "mailGuildId": null, "mainGuildId": null, "logChannelId": null, "prefix": "!", "snippetPrefix": "!!", "status": "Message me for help!", "responseMessage": "Thank you for your message! Our mod team will reply to you here as soon as possible.", "inboxServerPermission": null, "alwaysReply": false, "alwaysReplyAnon": false, "useNicknames": false, "ignoreAccidentalThreads": false, "enableGreeting": false, "greetingMessage": "The message the bot sends to a new user", "greetingAttachment": "Put a file path here", "port": 8890, "url": null }; const finalConfig = Object.assign({}, defaultConfig); for (const [prop, value] of Object.entries(userConfig)) { if (! defaultConfig.hasOwnProperty(prop)) { throw new Error(`Invalid option: ${prop}`); } finalConfig[prop] = value; } if (! finalConfig.token) throw new Error('Missing token!'); if (! finalConfig.mailGuildId) throw new Error('Missing mailGuildId (inbox server id)!'); if (! finalConfig.mainGuildId) throw new Error('Missing mainGuildId!'); module.exports = finalConfig;
let userConfig; try { userConfig = require('../config'); } catch (e) { throw new Error(`Config file could not be found or read! The error given was: ${e.message}`); } const defaultConfig = { "token": null, "mailGuildId": null, "mainGuildId": null, "logChannelId": null, "prefix": "!", "snippetPrefix": "!!", "status": "Message me for help!", "responseMessage": "Thank you for your message! Our mod team will reply to you here as soon as possible.", "inboxServerPermission": null, "alwaysReply": false, "alwaysReplyAnon": false, "useNicknames": false, "ignoreAccidentalThreads": false, "enableGreeting": false, "greetingMessage": null, "greetingAttachment": null, "port": 8890, "url": null }; const finalConfig = Object.assign({}, defaultConfig); for (const [prop, value] of Object.entries(userConfig)) { if (! defaultConfig.hasOwnProperty(prop)) { throw new Error(`Invalid option: ${prop}`); } finalConfig[prop] = value; } if (! finalConfig.token) throw new Error('Missing token!'); if (! finalConfig.mailGuildId) throw new Error('Missing mailGuildId (inbox server id)!'); if (! finalConfig.mainGuildId) throw new Error('Missing mainGuildId!'); module.exports = finalConfig;
Set greeting defaults to null
Set greeting defaults to null
JavaScript
mit
Dragory/modmailbot
13c8749224dd2d7014953acd295cb582bbefaf10
display-stats.js
display-stats.js
// ==UserScript== // @name Display Stats // @namespace https://github.com/EFox2413/initiumGrease // @version 0.1 // @description try to take over the world! // @author EFox2413 // @match https://www.playinitium.com/* // @grant none // ==/UserScript== /* jshint -W097 */ 'use strict'; var $ = window.jQuery; var charDiv = $('.character-display-box').children(" div:nth-child(3)").children( 'a' ); var statsItems; var statsID = ["S", "D", "I", "W"]; var href = $( '.character-display-box').children().first().attr( "rel" ); $.ajax({ url: href, type: "GET", success: function(data) { statsItems = $(data).find('.main-item-subnote'); statsItems.each(function( index ) { if ( index > 0 ) { charDiv.append( " <span style=\"font-size:small\"> " + statsID[index - 1] + ":" + $( this ).text().split(" ")[0] + " </span>"); } }); } });
// ==UserScript== // @name Display Stats // @namespace https://github.com/EFox2413/initiumGrease // @version 0.1 // @description try to take over the world! // @author EFox2413 // @match https://www.playinitium.com/* // @match http://www.playinitium.com/* // @grant none // ==/UserScript== /* jshint -W097 */ 'use strict'; var $ = window.jQuery; var charDiv = $('.character-display-box').children(" div:nth-child(3)").children( 'a' ); var statsItems; var statsID = ["S", "D", "I", "W"]; var href = $( '.character-display-box').children().first().attr( "rel" ); $.ajax({ url: href, type: "GET", success: function(data) { statsItems = $(data).find('.main-item-subnote'); statsItems.each(function( index ) { if ( index > 0 ) { charDiv.append( " <span style=\"font-size:small\"> " + statsID[index - 1] + ":" + $( this ).text().split(" ")[0] + " </span>"); } }); } });
Add an additional match line for http
Add an additional match line for http Add an additional match line for http so the script script runs on http/s.
JavaScript
mit
EFox2413/initiumGrease
d08eeb39468740085f1488e7e031e8122dba0124
gulpfile.js
gulpfile.js
/// var pkg = require("./package.json") , gulp = require("gulp") , plumber = require("gulp-plumber") /// // Lint JS /// var jshint = require("gulp-jshint") , jsonFiles = [".jshintrc", "*.json"] , jsFiles = ["*.js", "src/**/*.js"] gulp.task("scripts.lint", function() { gulp.src([].concat(jsonFiles).concat(jsFiles)) .pipe(plumber()) .pipe(jshint(".jshintrc")) .pipe(jshint.reporter("jshint-stylish")) }) var jscs = require("gulp-jscs") gulp.task("scripts.cs", function() { gulp.src(jsFiles) .pipe(plumber()) .pipe(jscs()) }) gulp.task("scripts", ["scripts.lint", "scripts.cs"]) gulp.task("watch", function() { gulp.watch(jsFiles, ["scripts"]) }) gulp.task("default", ["scripts", "watch"])
/// var pkg = require("./package.json") , gulp = require("gulp") , plumber = require("gulp-plumber") /// // Lint JS /// var jshint = require("gulp-jshint") , jsonFiles = [".jshintrc", "*.json"] , jsFiles = ["*.js", "src/**/*.js"] gulp.task("scripts.lint", function() { gulp.src([].concat(jsonFiles).concat(jsFiles)) .pipe(plumber()) .pipe(jshint(".jshintrc")) .pipe(jshint.reporter("jshint-stylish")) }) var jscs = require("gulp-jscs") gulp.task("scripts.cs", function() { gulp.src(jsFiles) .pipe(plumber()) .pipe(jscs()) }) gulp.task("scripts", ["scripts.lint", "scripts.cs"]) gulp.task("watch", function() { gulp.watch(jsFiles, ["scripts"]) }) gulp.task("default", ["scripts", "watch"]) var buildBranch = require("buildbranch") gulp.task("publish", function(cb) { buildBranch({folder: "src"} , function(err) { if (err) { throw err } console.log(pkg.name + " published.") cb() }) })
Add publish task (for gh-pages)
Add publish task (for gh-pages)
JavaScript
mit
MoOx/parallaxify,MoOx/parallaxify
9dc4e7c955b0252f1e5b0a89f2dc1cfbaf030088
lib/cartodb/middleware/context/db-conn-setup.js
lib/cartodb/middleware/context/db-conn-setup.js
const _ = require('underscore'); module.exports = function dbConnSetup (pgConnection) { return function dbConnSetupMiddleware (req, res, next) { const { user } = res.locals; pgConnection.setDBConn(user, res.locals, (err) => { req.profiler.done('setDBConn'); if (err) { if (err.message && -1 !== err.message.indexOf('name not found')) { err.http_status = 404; } return next(err); } _.defaults(res.locals, { dbuser: global.environment.postgres.user, dbpassword: global.environment.postgres.password, dbhost: global.environment.postgres.host, dbport: global.environment.postgres.port }); res.set('X-Served-By-DB-Host', res.locals.dbhost); next(); }); }; };
const _ = require('underscore'); module.exports = function dbConnSetup (pgConnection) { return function dbConnSetupMiddleware (req, res, next) { const { user } = res.locals; pgConnection.setDBConn(user, res.locals, (err) => { req.profiler.done('dbConnSetup'); if (err) { if (err.message && -1 !== err.message.indexOf('name not found')) { err.http_status = 404; } return next(err); } _.defaults(res.locals, { dbuser: global.environment.postgres.user, dbpassword: global.environment.postgres.password, dbhost: global.environment.postgres.host, dbport: global.environment.postgres.port }); res.set('X-Served-By-DB-Host', res.locals.dbhost); next(); }); }; };
Use the right step name for profiling
Use the right step name for profiling
JavaScript
bsd-3-clause
CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb
bdfc949f40eef5f43febb7e1fb2e53874fad399f
source/assets/javascripts/syntax-highlight.js
source/assets/javascripts/syntax-highlight.js
import hljs from 'highlight.js/lib/highlight'; import javascript from 'highlight.js/lib/languages/javascript'; import ruby from 'highlight.js/lib/languages/ruby'; import elixir from 'highlight.js/lib/languages/elixir'; import shell from 'highlight.js/lib/languages/shell'; import bash from 'highlight.js/lib/languages/bash'; import css from 'highlight.js/lib/languages/css'; import nginx from 'highlight.js/lib/languages/nginx'; import json from 'highlight.js/lib/languages/json'; const languages = { javascript, ruby, elixir, shell, bash, css, nginx, json, }; Object.entries(languages).forEach(([name, language]) => { hljs.registerLanguage(name, language); }); hljs.initHighlightingOnLoad();
import highlight from 'highlight.js/lib/highlight'; import bash from 'highlight.js/lib/languages/bash'; import css from 'highlight.js/lib/languages/css'; import elixir from 'highlight.js/lib/languages/elixir'; import html from 'highlight.js/lib/languages/html'; import javascript from 'highlight.js/lib/languages/javascript'; import json from 'highlight.js/lib/languages/json'; import nginx from 'highlight.js/lib/languages/nginx'; import ruby from 'highlight.js/lib/languages/ruby'; import shell from 'highlight.js/lib/languages/shell'; import yaml from 'highlight.js/lib/languages/yaml'; const languages = { bash, css, elixir, html, javascript, json, nginx, ruby, shell, yaml, }; Object.entries(languages).forEach(([name, language]) => { highlight.registerLanguage(name, language); }); highlight.initHighlightingOnLoad();
Add more languages to highlight
Add more languages to highlight
JavaScript
mit
rossta/rossta.github.com,rossta/rossta.github.com,rossta/rossta.github.com
c9707e7a63d446ae1c60814c705d48b604b9ddca
htteepee.js
htteepee.js
/*globals module, require*/ var stack = require('stack'), http = require('http'), _hs = http.createServer; http.createServer = function createServer () { 'use strict'; return _hs.call(http, stack.apply(stack, Array.prototype.slice.call(arguments)) ); }; http.createMiddlewareServer = function (mws) { 'use strict'; mws = typeof mws === 'function' ? [mws] : mws; return function () { return _hs.call(http, stack.apply(stack, mws.concat(Array.prototype.slice.call(arguments))) ); }; }; module.exports = http;
/*globals module, require*/ var stack = require('stack'), http = require('http'), _hs = http.createServer; http.createServer = function createServer () { 'use strict'; return _hs.call(http, stack.apply(stack, Array.prototype.slice.call(arguments)) ); }; http.createMiddlewareServer = function (mws) { 'use strict'; mws = Array.prototype.slice.call(arguments); return function () { return _hs.call(http, stack.apply(stack, mws.concat(Array.prototype.slice.call(arguments))) ); }; }; module.exports = http;
Change away froma accepting array to accepting arguments like our own createServer
Change away froma accepting array to accepting arguments like our own createServer
JavaScript
mit
brettz9/htteepee
c5f148c6ec29c86671471bcde50cea809479b5c6
client/app/mirage/config.js
client/app/mirage/config.js
export default function() { }
export default function() { this.get('/orders', function(db, request) { return { data: [ { id: 1, type: "order", attributes: { organizerName: "Пицца Темпо", orderTime: "14:00", moneyRequired: 300000, moneyCurrent: 100000 } }, ] }; }); }
Add test endpoint for /orders
Add test endpoint for /orders
JavaScript
mit
yandex-shri-minsk-2016/yummy-time,yandex-shri-minsk-2016/yummy-time,yandex-shri-minsk-2016/yummy-time
622c972dd4d23923b40799cf945206c0c774b5bb
helper.js
helper.js
Handlebars.registerHelper('select_box', function(field, options) { var html_options, _this = this; if (!field) { return; } if (options.hash.optionValues && options.hash.optionValues.length > 0) { optionsValues = options.hash.optionValues } else { optionsValues = _this["" + field + "Options"](); } html_options = []; _.each(optionsValues, function(option) { var selected; selected = _this[field] === option ? ' selected' : ''; return html_options.push("<option value='" + option + "'" + selected + ">" + _.humanize(option) + "</option>"); }); html = "<select class='form-control' name='" + field + "'>" + (html_options.join('')) + "</select>" return new Handlebars.SafeString(html); }); Handlebars.registerHelper('check_box', function(field) { var capitalizedField, checked; if (!field) { return; } checked = this[field] === 'true' ? ' checked' : ''; html = "<label><input name='" + field + "' type='hidden' value='false'><input name='" + field + "' type='checkbox' value='true' " + checked + ">" + _.humanize(field) + "</label>"; return new Handlebars.SafeString(html); });
Handlebars.registerHelper('select_box', function(field, options) { var html_options, _this = this; if (!field) { return; } if (options.hash['class']) { html_class = " " + options.hash['class'] } else { html_class = "" } if (options.hash.optionValues && options.hash.optionValues.length > 0) { optionsValues = options.hash.optionValues } else { optionsValues = _this["" + field + "Options"](); } html_options = []; _.each(optionsValues, function(option) { var selected; selected = _this[field] === option ? ' selected' : ''; return html_options.push("<option value='" + option + "'" + selected + ">" + _.humanize(option) + "</option>"); }); html = "<select class='form-control" + html_class + "' name='" + field + "'>" + (html_options.join('')) + "</select>" return new Handlebars.SafeString(html); }); Handlebars.registerHelper('check_box', function(field) { var capitalizedField, checked; if (!field) { return; } checked = this[field] === 'true' ? ' checked' : ''; html = "<label><input name='" + field + "' type='hidden' value='false'><input name='" + field + "' type='checkbox' value='true' " + checked + ">" + _.humanize(field) + "</label>"; return new Handlebars.SafeString(html); });
Add support for adding classes to the select box
Add support for adding classes to the select box
JavaScript
mit
meteorclub/simple-form
4b027289b5f1aebca17f64b7fe240bfe0a0c2930
build-regular-expression.js
build-regular-expression.js
var captureDigit = '([1-9][0-9]*)' var EUCD = new RegExp( '^' + captureDigit + 'e' + optional(captureDigit + 'u') + optional(captureDigit + 'c') + optional(captureDigit + 'd') + '$') function optional(reString) { return ( '(?:' + reString + ')?' ) } process.stdout.write(( 'module.exports = ' + EUCD + '\n' ))
var captureDigit = '([1-9][0-9]*)' var regularExpression = new RegExp( '^' + captureDigit + 'e' + optional(captureDigit + 'u') + optional(captureDigit + 'c') + optional(captureDigit + 'd') + '$') function optional(reString) { return ( '(?:' + reString + ')?' ) } process.stdout.write(( 'module.exports = ' + regularExpression + '\n' ))
Rename variable in regular expression build script
Rename variable in regular expression build script
JavaScript
mit
kemitchell/reviewers-edition-parse.js
96d80da6ba02307d4b4c115f9f9ffea8ef998d2c
chrome-cordova/plugins/chrome-common/errors.js
chrome-cordova/plugins/chrome-common/errors.js
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. try { var runtime = require('org.chromium.runtime.runtime'); } catch(e) {} // Typical Usage: // // if (fail_condition) // return callbackWithError('You should blah blah', fail, optional_args_to_fail...) function callbackWithError(msg, callback) { if (typeof callback !== 'function') { console.error(msg); return; } try { if (typeof runtime !== 'undefined') { runtime.lastError = { 'message' : msg }; } else { console.error(msg); } callback.apply(null, Array.prototype.slice.call(arguments, 2)); } finally { if (typeof runtime !== 'undefined') delete runtime.lastError; } } module.exports = { callbackWithError: callbackWithError };
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. try { var runtime = require('org.chromium.runtime.runtime'); } catch(e) {} // Typical Usage: // // if (fail_condition) // return callbackWithError('You should blah blah', fail, optional_args_to_fail...) function callbackWithError(msg, callback) { var err; if (typeof msg == 'string') { err = { 'message' : msg }; } else { err = msg; } if (typeof callback !== 'function') { console.error(err.message); return; } try { if (typeof runtime !== 'undefined') { runtime.lastError = err; } else { console.error(err.message); } callback.apply(null, Array.prototype.slice.call(arguments, 2)); } finally { if (typeof runtime !== 'undefined') delete runtime.lastError; } } module.exports = { callbackWithError: callbackWithError };
Allow setting error.code as well as error.message for callbackWithError()
Allow setting error.code as well as error.message for callbackWithError()
JavaScript
bsd-3-clause
chirilo/mobile-chrome-apps,MobileChromeApps/mobile-chrome-apps,wudkj/mobile-chrome-apps,xiaoyanit/mobile-chrome-apps,guozanhua/mobile-chrome-apps,xiaoyanit/mobile-chrome-apps,guozanhua/mobile-chrome-apps,xiaoyanit/mobile-chrome-apps,guozanhua/mobile-chrome-apps,MobileChromeApps/mobile-chrome-apps,liqingzhu/mobile-chrome-apps,liqingzhu/mobile-chrome-apps,wudkj/mobile-chrome-apps,chirilo/mobile-chrome-apps,chirilo/mobile-chrome-apps,wudkj/mobile-chrome-apps,MobileChromeApps/mobile-chrome-apps,MobileChromeApps/mobile-chrome-apps,guozanhua/mobile-chrome-apps,chirilo/mobile-chrome-apps,liqingzhu/mobile-chrome-apps,liqingzhu/mobile-chrome-apps,wudkj/mobile-chrome-apps,xiaoyanit/mobile-chrome-apps
581ca42c1e0c35fbeef9fffc501292d10e15974d
app/assets/javascripts/georgia/application.js
app/assets/javascripts/georgia/application.js
//= require jquery //= require jquery.ui.all //= require georgia/jquery.ui.touch-punch //= require jquery_ujs //= require jquery-fileupload //= require twitter/bootstrap //= require select2 //= require shadowbox //= require mousetrap //= require georgia/keybindings //= require georgia/jquery.mjs.nestedSortable //= require georgia/tags //= require georgia/pages //= require georgia/media //= require georgia/form-actions //= require ckeditor/init //= require handlebars.runtime //= require underscore //= require backbone //= require .//backbone-relational //= require .//panels //= require_tree ./../../templates/ //= require_tree .//models //= require_tree .//collections //= require_tree .//views //= require_tree .//routers //= require_tree .
//= require jquery //= require jquery.ui.all //= require jquery_ujs //= require jquery-fileupload //= require twitter/bootstrap //= require select2 //= require shadowbox //= require mousetrap //= require ckeditor/init //= require_tree .//ckeditor //= require handlebars.runtime //= require underscore //= require backbone //= require_tree ./../../templates/ //= require_tree .//models //= require_tree .//collections //= require_tree .//views //= require_tree .//routers //= require .//backbone-relational //= require .//bootstrap //= require .//featured-image //= require .//form-actions //= require .//jquery.mjs.nestedSortable //= require .//jquery.ui.touch-punch //= require .//keybindings //= require .//media //= require .//pages //= require .//panels //= require .//tags
Fix double inclusion of jquery
Fix double inclusion of jquery
JavaScript
mit
georgia-cms/georgia,georgia-cms/georgia,georgia-cms/georgia
8f233b5f65981b79ef88f2c1dad315fe6e9e34d3
js/mock-sensor.js
js/mock-sensor.js
// This mock sensor implementation triggers an event with some data every once in a while var emitter = require( "events" ).EventEmitter, possibleStrings = [ "Helsinki", "Espoo", "Tampere", "Oulu", "Mikkeli", "Ii" ]; // Return a random integer between 0 and @upperLimit function randomInteger( upperLimit ) { return Math.round( ( 1 + Math.random() ) * upperLimit ); } module.exports = function mockSensor() { var returnValue = new emitter(), trigger = function() { returnValue.emit( "change", { someValue: Math.round( Math.random() * 42 ), someOtherValue: possibleStrings[ randomInteger( possibleStrings.length - 1 ) ] } ); setTimeout( trigger, randomInteger( 1000 ) + 1000 ); }; setTimeout( trigger, randomInteger( 1000 ) + 1000 ); return returnValue; };
// This mock sensor implementation triggers an event with some data every once in a while var emitter = require( "events" ).EventEmitter, possibleStrings = [ "Helsinki", "Espoo", "Tampere", "Oulu", "Mikkeli", "Ii" ]; // Return a random integer between 0 and @upperLimit function randomInteger( upperLimit ) { return Math.round( Math.random() * upperLimit ); } module.exports = function mockSensor() { var returnValue = new emitter(), trigger = function() { var someValue = Math.round( Math.random() * 42 ), someOtherValue = possibleStrings[ randomInteger( possibleStrings.length - 1 ) ]; returnValue.emit( "change", { someValue: someValue, someOtherValue: someOtherValue } ); setTimeout( trigger, randomInteger( 1000 ) + 1000 ); }; setTimeout( trigger, randomInteger( 1000 ) + 1000 ); return returnValue; };
Fix mock sensor randomization code
Examples: Fix mock sensor randomization code
JavaScript
mit
zolkis/iotivity-node,zqzhang/iotivity-node,zolkis/iotivity-node,zqzhang/iotivity-node,zolkis/iotivity-node,zolkis/iotivity-node,zqzhang/iotivity-node,zqzhang/iotivity-node,zqzhang/iotivity-node,zolkis/iotivity-node
ecbb97b5d0b9698de4ceb47a94cd7499460cbf11
lib/transactional-email.js
lib/transactional-email.js
const REQUIRED_FIELDS = Object.freeze(['to']); const OPTIONAL_FIELDS = Object.freeze([ 'customer_id', 'transactional_message_id', 'message_data', 'from', 'from_id', 'reply_to', 'reply_to_id', 'bcc', 'subject', 'body', 'plaintext_body', 'amp_body', 'fake_bcc', 'hide_body', ]); module.exports = class TransactionalEmail { headers = {}; attachments = {}; constructor(opts) { REQUIRED_FIELDS.forEach((field) => { this[field] = opts[field]; }); OPTIONAL_FIELDS.forEach((field) => { this[field] = opts[field]; }); } attach(name, data) { if (data instanceof Buffer) { this.attachments[name] = data.toString('base64'); } else if (typeof data === 'string') { this.attachments[name] = fs.readFileSync(data, 'base64'); } else { throw new Error(`unknown attachment type: ${typeof data}`); } } toObject() { let attrs = { attachments: this.attachments, headers: this.headers, }; [...REQUIRED_FIELDS, ...OPTIONAL_FIELDS].forEach((prop) => { attrs[prop] = this[prop]; }); return attrs; } };
const REQUIRED_FIELDS = Object.freeze(['to']); const OPTIONAL_FIELDS = Object.freeze([ 'customer_id', 'transactional_message_id', 'message_data', 'from', 'from_id', 'reply_to', 'reply_to_id', 'bcc', 'subject', 'body', 'plaintext_body', 'amp_body', 'fake_bcc', 'hide_body', ]); module.exports = class TransactionalEmail { constructor(opts) { REQUIRED_FIELDS.forEach((field) => { this[field] = opts[field]; }); OPTIONAL_FIELDS.forEach((field) => { this[field] = opts[field]; }); this.headers = {}; this.attachments = {}; } attach(name, data) { if (data instanceof Buffer) { this.attachments[name] = data.toString('base64'); } else if (typeof data === 'string') { this.attachments[name] = fs.readFileSync(data, 'base64'); } else { throw new Error(`unknown attachment type: ${typeof data}`); } } toObject() { let attrs = { attachments: this.attachments, headers: this.headers, }; [...REQUIRED_FIELDS, ...OPTIONAL_FIELDS].forEach((prop) => { attrs[prop] = this[prop]; }); return attrs; } };
Fix syntax for node 10
Fix syntax for node 10
JavaScript
mit
customerio/customerio-node,customerio/customerio-node,customerio/customerio-node
0e3abf3fd573780b0898240ba06b1a19a4e2f1b4
controllers/transactions.js
controllers/transactions.js
'use strict'; var mongoose = require('mongoose'); var Transaction = require('../models/Transaction'); mongoose.Promise = global.Promise; module.exports = mongoose.connection; var index = function (req, res, next) { Transaction.find({}).exec().then(function (trans) { res.json(trans); }).catch(function(error){ next(error); }); }; var show = function (req, res, next) { Transaction.find({"_id": req.params.id}).exec() .then(function(trans){ res.json(trans); }).catch(function(error){ next(error); }); }; var create = function (req, res, next) { Transaction.create({ user_id: req.body.user_id, product_id: req.body.product_id, status: req.body.status, qty: req.body.qty }).then(function(trans){ res.json(trans); }) .catch(function(error){ next(error); }); }; var update = function (req, res, next) { // Transaction.findByIdAndUpdate(req.params.id, { $set: modify }, { new: true }).exec().then(function(trans) { // //console.log(person.toJSON()); // }) // .catch(console.error) }; module.exports = { index, show, create, update };
'use strict'; var mongoose = require('mongoose'); var Transaction = require('../models/Transaction'); mongoose.Promise = global.Promise; module.exports = mongoose.connection; var index = function (req, res, next) { Transaction.find({}).exec().then(function (trans) { res.json(trans); }).catch(function(error){ next(error); }); }; var show = function (req, res, next) { Transaction.find({"_id": req.params.id}).exec() .then(function(trans){ res.json(trans); }).catch(function(error){ next(error); }); }; var create = function (req, res, next) { // console.log(req.get('Content-Type')); // res.json(req.body.user_id); Transaction.create({ "user_id": req.body.user_id, "product_id": req.body.product_id, "status": req.body.status, "qty": req.body.qty }).then(function(trans){ res.json(trans); }) .catch(function(error){ next(error); }); }; var update = function (req, res, next) { // Transaction.findByIdAndUpdate(req.params.id, { $set: modify }, { new: true }).exec().then(function(trans) { // //console.log(person.toJSON()); // }) // .catch(console.error) }; module.exports = { index, show, create, update };
Add create method in Transcation controller. -cwc
Add create method in Transcation controller. -cwc Next thing to do is add update method.
JavaScript
mit
Church-ill/project3-back,Church-ill/project3-back,Church-ill/project3-back
c2de65fb35c1e621e711527b7d2f357d1c4c3885
chat-plugins/development.js
chat-plugins/development.js
/** * Development commands plugin * * This houses the bot's development commands. * These commands should only be used if the operator knows what their doing. * * @license MIT license */ 'use strict'; exports.commands = { js: 'eval', eval: function (target, room, user, cmd) { if (!target) return Chat.send(room, `Usage: ${Config.cmdchar}${cmd} [target]`); try { Chat.send(room, eval(target)); } catch (e) { Chat.send(room, e.stack); } }, reload: 'hotpatch', hotpatch: function (target, room, user) { try { Chat.reload(); Chat.send(room, 'Chat has been hotpatched successfully.'); } catch (e) { Chat.send(room, `Failed to hotpatch chat:\n${e.stack}`); } }, };
/** * Development commands plugin * * This houses the bot's development commands. * These commands should only be used if the operator knows what their doing. * * @license MIT license */ 'use strict'; exports.commands = { js: 'eval', eval: function (target, room, user, cmd) { if (!target) return Chat.send(room, `Usage: ${Config.cmdchar}${cmd} [target]`); try { Chat.send(room, `Javascript\n${eval(target)}`); } catch (e) { Chat.send(room, `Javascript\n${e.stack}`); } }, reload: 'hotpatch', hotpatch: function (target, room, user) { try { Chat.reload(); Chat.send(room, 'Chat has been hotpatched successfully.'); } catch (e) { Chat.send(room, `Javascript\nFailed to hotpatch chat:\n${e.stack}`); } }, };
Enable Javascript syntax highlighting in some cmds
Enable Javascript syntax highlighting in some cmds
JavaScript
mit
panpawn/Discord-Bot
cf18968b1115f67dbb48c36834d1ba08e32aeb8d
js/nalyt.js
js/nalyt.js
$(document).ready(function(){ if (analytics) { $('a[target=_blank]').click(function (e) { var url = this.getAttribute("href") || this.getAttribute("xlink:href"); analytics.track("externalLink", {url: url}); }); window.onpopstate = function (event) { analytics.page("Slide", {url: location.href}); } } });
$(document).ready(function(){ if (analytics) { $('a[target=_blank]').click(function (e) { var url = this.getAttribute("href") || this.getAttribute("xlink:href"); analytics.track("Clicked External Link", {url: url}); }); window.onpopstate = function (event) { analytics.page("Slide", {url: location.href}); } } });
Change name of the event
Change name of the event
JavaScript
mit
cyberFund/cyberep.cyber.fund,cyberFund/cyberep.cyber.fund
202b819f2e1f1caa1c00f4503900de2ceef1d3bb
app/gbi_server/static/js/admin/create_user.js
app/gbi_server/static/js/admin/create_user.js
$(document).ready(function() { $('#verified').click(function() { if($(this).attr("checked")) { $('#activate').removeAttr('disabled'); } else { $('#activate').attr('disabled', 'disabled'); } }); $('#activate').attr('disabled', 'disabled'); });
$(document).ready(function() { $('#verified').click(function() { if($(this).attr("checked")) { $('#activate').removeAttr('disabled'); } else { $('#activate').attr('disabled', 'disabled'); } }); $('#activate').attr('disabled', 'disabled'); $('#type').change(function() { if($(this).val() != 0) { $('#florlp_name').parents('div.control-group:first').hide(); } else { $('#florlp_name').parents('div.control-group:first').show(); } }); });
Hide florlp_name when type not 0
Hide florlp_name when type not 0
JavaScript
apache-2.0
omniscale/gbi-server,omniscale/gbi-server,omniscale/gbi-server
d7bfb87ea5580463c9fc058ea0718ac90a3f32f1
src/auth/authApi.service.js
src/auth/authApi.service.js
(function (angular) { 'use strict'; angular .module('movieClub.auth') .factory('authApi', authApi); function authApi($firebaseAuth, usersApi, firebaseRef) { var factory = { login: login, logout: logout, onAuth: onAuth, register: register }, authRef = $firebaseAuth(firebaseRef); return factory; function login(email, password) { var credentials = { email: email, password: password }; return authRef.$authWithPassword(credentials); } function logout() { authRef.$unauth(); } function onAuth(func) { return authRef.$onAuth(func); } function register(username, email, password) { var credentials = { email: email, password: password }; return authRef.$createUser(credentials) .then(function () { return login(email, password) .then(function (auth) { var user = usersApi.getById(auth.uid); user.username = username; user.$save(); return user.$loaded(); }); }); } } }(window.angular));
(function (angular) { 'use strict'; angular .module('movieClub.auth') .factory('authApi', authApi); function authApi($firebaseAuth, usersApi, firebaseRef) { var factory = { login: login, logout: logout, onAuth: onAuth, register: register }, authRef = $firebaseAuth(firebaseRef); return factory; function login(email, password) { return authRef.$authWithPassword({email: email, password: password}); } function logout() { authRef.$unauth(); } function register(username, email, password) { return authRef.$createUser({email: email, password: password}) .then(_.partial(login, email, password)) .then(_.partialRight(addUsername, username)); } function onAuth(func) { return authRef.$onAuth(func); } function addUsername(auth, username) { var user = usersApi.getById(auth.uid); user.username = username; user.$save(); return user.$loaded(); } } }(window.angular));
Use promise chaining during registration
Use promise chaining during registration
JavaScript
mit
charwking/movie-club,charwking/movie-club,charwking/movie-club
1024e5132e2f39fdaa46ee9f538046ef6e9d17ff
grunt/config/css-mqpacker.js
grunt/config/css-mqpacker.js
module.exports = function(grunt) { grunt.config('css_mqpacker', { options: { map: false, // enable/disable source maps }, main: { src: '<%= project.styles_dev %>/main.dev.css', dest: '<%= project.styles_dev %>/main.dev.css', }, mobile: { src: '<%= project.styles_dev %>/mobile.dev.css', dest: '<%= project.styles_dev %>/mobile.dev.css', }, }); };
module.exports = function(grunt) { grunt.config('css_mqpacker', { options: { map: false, // enable/disable source maps sort: true, }, main: { src: '<%= project.styles_dev %>/main.dev.css', dest: '<%= project.styles_dev %>/main.dev.css', }, mobile: { src: '<%= project.styles_dev %>/mobile.dev.css', dest: '<%= project.styles_dev %>/mobile.dev.css', }, }); };
Add sort media queries to Grunt mqpacker config.
Add sort media queries to Grunt mqpacker config.
JavaScript
mit
jolantis/altair,jolantis/altair
e9841437c4834710354bf0c00ccf5d7c9eb8ffaa
src/components/App/index.js
src/components/App/index.js
import React from 'react' const App = () => ( <h1>Hello from React</h1> ) export default App
import React from 'react' import Counter from '../../containers/Counter' const App = () => ( <div> <Counter /> </div> ) export default App
Put the Counter into App
Put the Counter into App
JavaScript
mit
epicsharp/react-boilerplate,RSS-Dev/live-html,epicsharp/react-boilerplate,RSS-Dev/live-html
4aa4466ac5f30870be92724a571c557dc48dc4ed
src/repl/main.js
src/repl/main.js
import Repl from './Repl.html'; import examples from './examples.js'; function tryParseData ( encoded ) { try { return JSON.parse( decodeURIComponent( atob( encoded ) ) ); } catch ( err ) { return {}; } } if ( typeof svelte !== 'undefined' ) { const dataMatch = /data=(.+)$/.exec( window.location.search ); const { source, data } = dataMatch ? tryParseData( dataMatch[1] ) : {}; const gistMatch = /gist=(.+)$/.exec( window.location.search ); const gist = gistMatch ? gistMatch[1] : ( source ? null : examples[0].gist ); const repl = new Repl({ target: document.querySelector( 'main' ), data: { gist, source, data } }); window.repl = repl; } else { document.querySelector( 'main' ).innerHTML = `<p style='text-align: center; margin: 0; padding: 4em 3em 8em 3em; line-height: 1.5;'>Svelte generates components that work in all modern JavaScript environments, but the Svelte compiler only runs in Node 6+ and browsers that support ES2015 features. Please reopen this page in a different browser such as Chrome.</p>`; }
import Repl from './Repl.html'; import examples from './examples.js'; function tryParseData ( encoded ) { try { return JSON.parse( decodeURIComponent( atob( encoded ) ) ); } catch ( err ) { return {}; } } if ( typeof svelte !== 'undefined' ) { const dataMatch = /data=(.+)$/.exec( window.location.search ); const { source, data } = dataMatch ? tryParseData( dataMatch[1] ) : {}; const gistMatch = /gist=(.+)$/.exec( window.location.search ); const gist = gistMatch ? gistMatch[1] : ( source ? null : examples[0].gist ); const repl = new Repl({ target: document.querySelector( '.repl' ), data: { gist, source, data } }); window.repl = repl; } else { document.querySelector( '.repl' ).innerHTML = `<p style='text-align: center; margin: 0; padding: 4em 3em 8em 3em; line-height: 1.5;'>Svelte generates components that work in all modern JavaScript environments, but the Svelte compiler only runs in Node 6+ and browsers that support ES2015 features. Please reopen this page in a different browser such as Chrome.</p>`; }
Adjust REPL component target element
Adjust REPL component target element
JavaScript
mit
sveltejs/svelte.technology,sveltejs/svelte.technology
ec23be002f6658e2743f02a673e30cacd704b34c
src/components/Nav/index.js
src/components/Nav/index.js
import React, { Component } from 'react'; import { NavLink } from 'react-router-dom'; import nav from '../icons/nav'; import styles from './index.module.less'; export default class index extends Component { constructor() { super(); this.state = {}; } render() { const { routerData } = this.props; return ( <div className={styles.nav}> {this.props.menuData.map((item, idx) => { let icon = item.icon; if (Object.keys(nav).includes(icon)) { icon = nav[icon]; } if (/^https?:(?:\/\/)?/.test(item.path)) { return <a key={idx} target="__blank" href={item.path}>{icon}</a>; } let noPath = null; if (!routerData[item.path] && item.children && item.children.length > 0) { noPath = item.children[0].path; } return <NavLink activeClassName={styles.selected} key={idx} to={noPath || item.path}>{icon}</NavLink>; })} </div> ); } }
import React, { Component } from 'react'; import { NavLink } from 'react-router-dom'; import { Tooltip } from '@uiw/core'; import nav from '../icons/nav'; import styles from './index.module.less'; export default class index extends Component { constructor() { super(); this.state = {}; } render() { const { routerData } = this.props; return ( <div className={styles.nav}> {this.props.menuData.map((item, idx) => { let icon = item.icon; if (Object.keys(nav).includes(icon)) { icon = nav[icon]; } if (/^https?:(?:\/\/)?/.test(item.path)) { return ( <a key={idx} target="__blank" href={item.path}> <Tooltip placement="right" content={item.name}> {icon} </Tooltip> </a> ); } let noPath = null; if (!routerData[item.path] && item.children && item.children.length > 0) { noPath = item.children[0].path; } return ( <NavLink activeClassName={styles.selected} key={idx} to={noPath || item.path}> <Tooltip placement="right" content={item.name}> {icon} </Tooltip> </NavLink> ); })} </div> ); } }
Modify the website nav style.
docs: Modify the website nav style.
JavaScript
mit
uiw-react/uiw,uiw-react/uiw
b0609358beb1785b07e1eb2b643a9e25a8b500a4
js/app.js
js/app.js
(function() { 'use strict'; // Model var Task = Backbone.Model.extend({ defaults: { title: 'do something!', completed: false }, validate: function (attr) { if (_.isEmpty(attr.title)) { return 'title must not be empty!'; } }, toggle: function () { this.set('completed', !this.get('completed')); } }); var task1 = new Task({ completed: true }); // setter // task1.set('title', 'newTitle'); // console.log(task1.toJSON()); // getter // var title = task1.get('title'); // console.log(title); // validattion console.log(task1.toJSON().title); task1.set({title: ''}, {validate: true}); console.log(task1.toJSON().title); }());
(function() { 'use strict'; // Model var Task = Backbone.Model.extend({ defaults: { title: 'do something!', completed: false } }); var task = new Task(); // View var TaskView = Backbone.View.extend({ tagName: 'li' }); var taskView = new TaskView({ model: task }); console.log(taskView.$el); }());
Create list tag in View.
Create list tag in View.
JavaScript
mit
shgtkshruch/dotinstall-backbone
230e7fa0663afc90df0359c574309afe8d018749
app/services/interceptor/api-interceptor.service.js
app/services/interceptor/api-interceptor.service.js
(function () { 'use strict'; angular .module('doleticApp') .service('APIInterceptorService', APIInterceptorService); APIInterceptorService.$inject = ['$rootScope', '$q', 'AuthService', 'store']; function APIInterceptorService($rootScope, $q, AuthService) { var service = this; service.request = function (config) { var access_token = AuthService.getAccessToken(); var token_type = AuthService.getTokenType(); if (access_token && token_type) { config.headers.Authorization = token_type + " " + access_token; } return config; }; service.responseError = function (rejection) { return $q.reject(rejection); }; service.requestError = function (rejection) { //SharedVariables.messageBox.show = true; return $q.reject(rejection); }; } })();
(function () { 'use strict'; angular .module('doleticApp') .service('APIInterceptorService', APIInterceptorService); APIInterceptorService.$inject = ['$rootScope', '$q', 'AuthService', '$injector', 'MessageBoxService']; function APIInterceptorService($rootScope, $q, AuthService, $injector, MessageBoxService) { var service = this; service.request = function (config) { var access_token = AuthService.getAccessToken(); var token_type = AuthService.getTokenType(); if (access_token && token_type) { config.headers.Authorization = token_type + " " + access_token; } return config; }; service.responseError = function(response) { if (response.status == 401){ MessageBoxService.showError('Erreur 401',response.statusText); logout(); } return $q.reject(response); }; service.requestError = function (rejection) { //SharedVariables.messageBox.show = true; return $q.reject(rejection); }; function logout() { AuthService.setLogged(false); AuthService.setAccessToken(null); $injector.get('$state').go('login'); // event.preventDefault(); } } })();
Add api 401 unauthorized interception and redirect to login
Add api 401 unauthorized interception and redirect to login
JavaScript
mit
JuCN/DoleticRESTClient,ETICINSATechnologies/DoleticRESTClient,nsorin/DoleticRESTClient,JuCN/DoleticRESTClient,ETICINSATechnologies/DoleticRESTClient,nsorin/DoleticRESTClient
ee03bf731294a55a6c59d567f4540dc7e8d88d16
package.js
package.js
Package.describe({ summary: "Meteor unit testing framework for packages", name: "spacejamio:munit", version: "1.0.0", git: "https://github.com/spacejamio/meteor-munit.git" }); Package.onUse(function (api, where) { api.versionsFrom('0.9.0'); api.use(["coffeescript", "underscore"]); api.use(["tinytest","test-helpers"]); api.use(["spacejamio:chai","spacejamio:sinon"]); api.imply(["tinytest","test-helpers"]); api.imply(["spacejamio:chai","spacejamio:sinon"]); api.addFiles("namespaces.js"); api.addFiles("async_multi.js"); api.addFiles("Munit.coffee"); api.addFiles("Helpers.coffee"); api.addFiles("Describe.coffee"); api.export(['lvTestAsyncMulti']); api.export(['Munit', 'chai']); api.export(['describe', 'it', 'beforeAll', 'beforeEach', 'afterEach', 'afterAll']); }); Package.onTest(function(api) { api.use(["coffeescript", "spacejamio:munit"]); api.addFiles("tests/TestRunnerTest.coffee"); api.addFiles("tests/HelpersTest.coffee"); api.addFiles("tests/DescribeTest.coffee"); });
Package.describe({ summary: "Meteor unit testing framework for packages", name: "spacejamio:munit", version: "1.0.0", git: "https://github.com/spacejamio/meteor-munit.git" }); Package.onUse(function (api, where) { api.versionsFrom('0.9.0'); api.use(["coffeescript", "underscore"]); api.use(["tinytest","test-helpers"]); api.use(["spacejamio:chai@1.0.0", "spacejamio:sinon@1.0.0"]); api.imply(["tinytest","test-helpers"]); api.imply(["spacejamio:chai@1.0.0", "spacejamio:sinon@1.0.0"]); api.addFiles("namespaces.js"); api.addFiles("async_multi.js"); api.addFiles("Munit.coffee"); api.addFiles("Helpers.coffee"); api.addFiles("Describe.coffee"); api.export(['lvTestAsyncMulti']); api.export(['Munit', 'chai']); api.export(['describe', 'it', 'beforeAll', 'beforeEach', 'afterEach', 'afterAll']); }); Package.onTest(function(api) { api.use(["coffeescript", "spacejamio:munit"]); api.addFiles("tests/TestRunnerTest.coffee"); api.addFiles("tests/HelpersTest.coffee"); api.addFiles("tests/DescribeTest.coffee"); });
Add version contraints for sinon and chai
Add version contraints for sinon and chai
JavaScript
mit
awatson1978/clinical-verification,practicalmeteor/meteor-munit
801a263ea3a7aac846b860b8933669a728af06d0
src/contexts/NodeContext.js
src/contexts/NodeContext.js
const {JsContext} = require('stencila') /** * A Node.js context for executing Javascript code */ class NodeContext extends JsContext {} NodeContext.spec = { name: 'NodeContext', base: 'Context', aliases: ['js', 'node'] } module.exports = NodeContext
const {JsContext} = require('stencila') /** * A Node.js context for executing Javascript code */ class NodeContext extends JsContext {} NodeContext.spec = { name: 'NodeContext', client: 'ContextHttpClient', aliases: ['js', 'node'] } module.exports = NodeContext
Switch to new spec protocol
Switch to new spec protocol
JavaScript
apache-2.0
stencila/node,stencila/node
9a7d99c50367f8b9e0fcf31d5e326ac622672850
src/shapes.js
src/shapes.js
/** * Values suitable for use within `propTypes` of components. * * @module higherform */ import { PropTypes } from 'react'; export const FormShape = PropTypes.shape({ validate: PropTypes.func, errors: PropTypes.objectOf(PropTypes.arrayOf(PropTypes.string)), }); export const FieldShape = PropTypes.object; export const FieldsShape = PropTypes.objectOf(FieldShape);
/** * Values suitable for use within `propTypes` of components. * * @module higherform */ import { PropTypes } from 'react'; export const FormShape = PropTypes.shape({ submit: PropTypes.func, errors: PropTypes.object, }); export const FieldShape = PropTypes.object; export const FieldsShape = PropTypes.objectOf(FieldShape);
Use the Correct PropTypes for the FormShape
Use the Correct PropTypes for the FormShape
JavaScript
mit
AgencyPMG/higherform,AgencyPMG/higherform
d8c5d622facc6459b1e97f99bac8d9cc1819480f
abstract.js
abstract.js
'use strict'; var assign = require('es5-ext/object/assign') , setPrototypeOf = require('es5-ext/object/set-prototype-of') , d = require('d') , captureStackTrace = Error.captureStackTrace , AbstractError; AbstractError = function AbstractError(message/*, code, ext*/) { var ext, code; if (!(this instanceof AbstractError)) { return new AbstractError(message, code, arguments[2]); } code = arguments[1]; ext = arguments[2]; if (ext == null) { if (code && (typeof code === 'object')) { ext = code; code = null; } } if (ext != null) assign(this, ext); this.message = String(message); if (code != null) this.code = String(code); this.name = this.constructor.name; if (captureStackTrace) captureStackTrace(this, this.constructor); }; if (setPrototypeOf) setPrototypeOf(AbstractError, Error); AbstractError.prototype = Object.create(Error.prototype, { constructor: d(AbstractError) }); module.exports = AbstractError;
'use strict'; var assign = require('es5-ext/object/assign') , setPrototypeOf = require('es5-ext/object/set-prototype-of') , d = require('d') , captureStackTrace = Error.captureStackTrace , AbstractError; AbstractError = function AbstractError(message/*, code, ext*/) { var ext, code; if (!(this instanceof AbstractError)) { return new AbstractError(message, arguments[1], arguments[2]); } code = arguments[1]; ext = arguments[2]; if (ext == null) { if (code && (typeof code === 'object')) { ext = code; code = null; } } if (ext != null) assign(this, ext); this.message = String(message); if (code != null) this.code = String(code); this.name = this.constructor.name; if (captureStackTrace) captureStackTrace(this, this.constructor); }; if (setPrototypeOf) setPrototypeOf(AbstractError, Error); AbstractError.prototype = Object.create(Error.prototype, { constructor: d(AbstractError) }); module.exports = AbstractError;
Fix pass of arguments issue
Fix pass of arguments issue
JavaScript
mit
medikoo/error-create
b9be6a6fccd7558f3aa704972c4ac53e377c43c1
src/foam/dao/DAOProperty.js
src/foam/dao/DAOProperty.js
/** * @license * Copyright 2016 Google Inc. 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. */ foam.CLASS({ package: 'foam.dao', name: 'DAOProperty', extends: 'Property', documentation: 'Property for storing a reference to a DAO.', requires: [ 'foam.dao.ProxyDAO' ], properties: [ { name: 'view', value: {class: 'foam.comics.InlineBrowserView'}, } ], methods: [ function installInProto(proto) { this.SUPER(proto); var name = this.name; var prop = this; Object.defineProperty(proto, name + '$proxy', { get: function daoProxyGetter() { var proxy = prop.ProxyDAO.create({delegate: this[name]}); this[name + '$proxy'] = proxy; this.sub('propertyChange', name, function(_, __, ___, s) { proxy.delegate = s.get(); }); return proxy; }, configurable: true }); } ] });
/** * @license * Copyright 2016 Google Inc. 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. */ foam.CLASS({ package: 'foam.dao', name: 'DAOProperty', extends: 'FObjectProperty', documentation: 'Property for storing a reference to a DAO.', requires: [ 'foam.dao.ProxyDAO' ], properties: [ { name: 'view', value: {class: 'foam.comics.InlineBrowserView'}, }, ['of', 'foam.dao.DAO'] ], methods: [ function installInProto(proto) { this.SUPER(proto); var name = this.name; var prop = this; Object.defineProperty(proto, name + '$proxy', { get: function daoProxyGetter() { var proxy = prop.ProxyDAO.create({delegate: this[name]}); this[name + '$proxy'] = proxy; this.sub('propertyChange', name, function(_, __, ___, s) { proxy.delegate = s.get(); }); return proxy; }, configurable: true }); } ] });
Fix java generatino of DAOSink.
Fix java generatino of DAOSink.
JavaScript
apache-2.0
foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2,foam-framework/foam2,foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2,jacksonic/vjlofvhjfgm
b8eedc06fef0a78f6d58a49c0efec766d186d67e
db/controllers/bookmarks.js
db/controllers/bookmarks.js
var Bookmark = require('../models/index.js').Bookmark; var create = function(props, callback) { Bookmark.build(props) .save() .then(function(bookmark) { callback(bookmark); }).catch(function(err) { console.log(err); }); }; var findAll = function(callback) { Bookmark.findAll().then(function(bookmarks) { callback(bookmarks); }).catch(function(err) { console.log(err); }); }; var findOne = function(query, callback) { Bookmark.findOne(query).done(function(bookmark) { console.log(bookmark, 'BOOOKMARK'); callback(bookmark); }); }; exports.create = create; exports.findAll = findAll; exports.findOne = findOne;
var Bookmark = require('../models/index.js').Bookmark; var create = function(props, callback) { Bookmark.build(props) .save() .then(function(bookmark) { callback(bookmark); }).catch(function(err) { console.log(err); }); }; var findAll = function(callback) { Bookmark.findAll().then(function(bookmarks) { callback(bookmarks); }).catch(function(err) { console.log(err); }); }; var findOne = function(query, callback) { Bookmark.findOne(query).done(function(bookmark) { console.log('🍊 Found one bookmark in db:', query); callback(bookmark); }); }; exports.create = create; exports.findAll = findAll; exports.findOne = findOne;
Improve conciseness of console.log messages
Improve conciseness of console.log messages
JavaScript
mit
francoabaroa/escape-reality,lowtalkers/escape-reality,lowtalkers/escape-reality,francoabaroa/escape-reality
02a3f5b3fb131e05b10a4dc0fe868ea28b275f61
lib/BaseObject.js
lib/BaseObject.js
module.exports = exports = function BaseObject(key, myRedis, options) { this.key = key; if (myRedis && !options) { options = myRedis; myRedis = null; } if (!options) options = {}; this.options = options; this.myRedis = myRedis; }; exports.prototype.redis = function() { return this.myRedis || require('../index').connect(); }; exports.prototype.inspect = function() { return '#<' + this.constructor.name + ' key: ' + this.key + ' opts: ' + JSON.stringify(this.options) + '>'; }; require('./serialize').mixin(exports);
module.exports = exports = function BaseObject(key, myRedis, options) { this.key = key; if (myRedis && !options) { options = myRedis; myRedis = null; } if (!options) options = {}; this.options = options; this.myRedis = myRedis; }; exports.prototype.redis = function() { return this.myRedis || require('../index').connect(); }; exports.prototype.clear = function(callback) { this.redis().del(this.key, callback); }; exports.prototype.inspect = function() { return '#<' + this.constructor.name + ' key: ' + this.key + '>'; }; require('./serialize').mixin(exports);
Add clear command to base object, and simplify inspect
Add clear command to base object, and simplify inspect
JavaScript
mit
hfwang/node-redis-objects
ad002ab21ef7400ef8df3314ac739a544e1220d3
both/router/routes.js
both/router/routes.js
/*****************************************************************************/ /* Client and Server Routes */ /*****************************************************************************/ Router.configure({ layoutTemplate: 'MasterLayout', loadingTemplate: 'Loading', notFoundTemplate: 'NotFound' }); Router.route('/', { name: 'marketing' }); Router.route('/pages', { name: 'pages.index' }); Router.route('/pages/new', { name: 'pages.new' }); Router.route('/pages/:_id', { name: 'pages.show' }); Router.route('/settings', { name: 'settings.index' }); Router.route('/users/:_id', { name: 'users.show' }); Router.route('/users/:_id/edit', { name:'users.edit' }); var requireLogin = function () { if (!Meteor.user()) { if (Meteor.loggingIn()) { this.render(this.loadingTemplate); } else { this.render('AccessDenied'); } } else { this.next(); } }; Router.onBeforeAction('dataNotFound'); Router.onBeforeAction(requireLogin, { only: [ 'pages.index', 'pages.new', 'settings.index', 'users.show', 'users.edit' ] });
/*****************************************************************************/ /* Client and Server Routes */ /*****************************************************************************/ Router.configure({ layoutTemplate: 'MasterLayout', loadingTemplate: 'Loading', notFoundTemplate: 'NotFound' }); Router.route('/', { name: 'marketing' }); Router.route('/pages', { name: 'pages.index' }); Router.route('/pages/new', { name: 'pages.new' }); Router.route('/pages/:_id', { name: 'pages.show' }); Router.route('/settings', { name: 'settings.index' }); Router.route('/users/:_id', { name: 'users.show' }); Router.route('/users/:_id/edit', { name:'users.edit' }); var requireLogin = function () { if (!Meteor.user()) { if (Meteor.loggingIn()) { this.render(this.loadingTemplate); } else { this.render('AccessDenied'); } } else { this.next(); } }; Router.onBeforeAction('dataNotFound'); Router.onBeforeAction(requireLogin, { except: [ 'marketing', 'pages.show' ] });
Use route whitelist method for security
Use route whitelist method for security
JavaScript
mit
bojicas/letterhead,bojicas/letterhead
cf17c59c7ad1848edd16c10cfcbf493aa6640b0f
lib/env_loader.js
lib/env_loader.js
'use strict'; var os = require('os'); var path = require('path'); var dotenv = require('dotenv'); var defaultMappings = { username: 'SCS_USERNAME', password: 'SCS_PASSWORD' }; module.exports = { /** * @param {Object} program * @param {Object} argumentMappings - optional */ loadConfig(program, argumentMappings) { // Try to load the config from the user home dotenv.config({ path: path.resolve(os.homedir(), '.scs-commander'), silent: true }); // Copy env values to the program, but don't overwrite passed arguments var mappings = argumentMappings || defaultMappings; Object.keys(mappings).forEach(argKey => { var envKey = mappings[argKey]; if (envKey in process.env && !(argKey in program)) { program[argKey] = process.env[envKey]; } }); } }
'use strict'; var os = require('os'); var path = require('path'); var dotenv = require('dotenv'); var defaultMappings = { username: 'SCS_USERNAME', password: 'SCS_PASSWORD' }; module.exports = { /** * @param {Object} program * @param {Object} argumentMappings - optional */ loadConfig(program, argumentMappings) { // Try to load the config from the user home dotenv.config({ path: path.resolve(os.homedir(), '.scs-commander'), silent: true }); // Check for a 'username' passed as an argument to the program, because we don't // want to set the password from the .env file, if a different username was passed var originalUsername = program.username; // Copy env values to the program, but don't overwrite passed arguments var mappings = argumentMappings || defaultMappings; Object.keys(mappings).forEach(argKey => { var envKey = mappings[argKey]; if (envKey in process.env && !(argKey in program)) { program[argKey] = process.env[envKey]; } }); // Reset the password set in the porogram, if the passed username and the one // now in the program don't match. This allows to overwrite the account to be // used, even if all account data is set in the .env file. if (originalUsername && originalUsername.length > 0 && process.env[defaultMappings.username] != originalUsername) { delete program.password; } } }
Fix overwriting of username by passing ‘-u|—username’
Fix overwriting of username by passing ‘-u|—username’
JavaScript
mit
VIISON/scs-commander
7a25a4d2236ddc7cee625ba2137b086614bb15a6
src/main/webapp/gulpfile.js
src/main/webapp/gulpfile.js
'use strict'; var gulp = require('gulp'); var jshint = require('gulp-jshint'); var csslint = require('gulp-csslint'); gulp.task('lint', ['jshint', 'csslint']); gulp.task('jshint', function() { return gulp.src('./js/*.js') .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')); }); gulp.task('csslint', function() { return gulp.src('./css/*.css') .pipe(csslint()) .pipe(csslint.reporter('checkstyle-xml')); });
// jshint ignore:start 'use strict'; var gulp = require('gulp'); var jshint = require('gulp-jshint'); var csslint = require('gulp-csslint'); gulp.task('lint', ['jshint', 'csslint']); gulp.task('jshint', function() { return gulp.src('./js/*.js') .pipe(jshint()) .pipe(jshint.reporter('checkstyle')); }); gulp.task('csslint', function() { return gulp.src('./css/*.css') .pipe(csslint()) .pipe(csslint.reporter('checkstyle-xml')); });
Use checkstyle output from jshint reporter
[TECG-125] Use checkstyle output from jshint reporter
JavaScript
apache-2.0
ciandt-dev/tech-gallery,ciandt-dev/tech-gallery,ciandt-dev/tech-gallery
34b352a0a6bae910dfb825ee74ec8c15848e5cfc
batch/pubsub/queue-seeker.js
batch/pubsub/queue-seeker.js
'use strict'; var QUEUE = require('../job_queue').QUEUE; function QueueSeeker(pool) { this.pool = pool; } module.exports = QueueSeeker; QueueSeeker.prototype.seek = function (callback) { var initialCursor = ['0']; var users = {}; var self = this; this.pool.acquire(QUEUE.DB, function(err, client) { if (err) { return callback(err); } self._seek(client, initialCursor, users, function(err, users) { self.pool.release(QUEUE.DB, client); return callback(err, Object.keys(users)); }); }); }; QueueSeeker.prototype._seek = function (client, cursor, users, callback) { var self = this; var redisParams = [cursor[0], 'MATCH', QUEUE.PREFIX + '*']; client.scan(redisParams, function(err, currentCursor) { if (err) { return callback(null, users); } var queues = currentCursor[1]; if (queues) { queues.forEach(function (queue) { var user = queue.substr(QUEUE.PREFIX.length); users[user] = true; }); } var hasMore = currentCursor[0] !== '0'; if (!hasMore) { return callback(null, users); } self._seek(client, currentCursor, users, callback); }); };
'use strict'; var QUEUE = require('../job_queue').QUEUE; var MAX_SCAN_ATTEMPTS = 50; function QueueSeeker(pool) { this.pool = pool; } module.exports = QueueSeeker; QueueSeeker.prototype.seek = function (callback) { var initialCursor = ['0']; var attemps = 0; var users = {}; var self = this; this.pool.acquire(QUEUE.DB, function(err, client) { if (err) { return callback(err); } self._seek(client, initialCursor, users, attemps, function(err, users) { self.pool.release(QUEUE.DB, client); return callback(err, Object.keys(users)); }); }); }; QueueSeeker.prototype._seek = function (client, cursor, users, attemps, callback) { var self = this; var redisParams = [cursor[0], 'MATCH', QUEUE.PREFIX + '*']; client.scan(redisParams, function(err, currentCursor) { if (err) { return callback(null, users); } var queues = currentCursor[1]; if (queues) { queues.forEach(function (queue) { var user = queue.substr(QUEUE.PREFIX.length); users[user] = true; }); } var hasMore = currentCursor[0] !== '0' && attemps < MAX_SCAN_ATTEMPTS; if (!hasMore) { return callback(null, users); } attemps += 1; self._seek(client, currentCursor, users, attemps, callback); }); };
Use max number of attempts to scan user queues
Use max number of attempts to scan user queues
JavaScript
bsd-3-clause
CartoDB/CartoDB-SQL-API,CartoDB/CartoDB-SQL-API
41f93f380688849092f036a37a0f0a40d94ef473
test/primitives/amount.js
test/primitives/amount.js
// Import AVA import test from 'ava' // Imports import Amount from '../../src/primitives/amount' import BigNumber from 'bignumber.js' // Test data const testNumber = 78953286724 const testValue = '78953286724' /** * Value must be BigNumber. */ test('value must be BigNumber', t => { const number = 8 t.throws(() => { new Amount(number) }) }) /** * Create a new amount. */ test('create', t => { const value = new BigNumber('8') t.notThrows(() => { new Amount(value) }) }) /** * Access value in wei. */ test('access wei', t => { const value = new BigNumber(testValue) const amount = new Amount(value) t.true(amount.wei.equals(value)) })
// Import AVA import test from 'ava' // Imports import Amount from '../../src/primitives/amount' import BigNumber from 'bignumber.js' // Test data const testNumber = 78953286724 const testValue = '78953286724' /** * Value must be BigNumber. */ test('value must be BigNumber', t => { t.throws(() => { new Amount(testNumber) }) }) /** * Create a new amount. */ test('create', t => { const value = new BigNumber(testValue) t.notThrows(() => { new Amount(value) }) }) /** * Access value in wei. */ test('access wei', t => { const value = new BigNumber(testValue) const amount = new Amount(value) t.true(amount.wei.equals(value)) })
Use centralized test data for Amount tests
Use centralized test data for Amount tests
JavaScript
unlicense
jestcrows/ethtaint,jestcrows/ethtaint
c30d406e330c1c69877cd80e9f3b9ba3cdddc983
src/direct-linking/content_script/rendering.js
src/direct-linking/content_script/rendering.js
import { retryUntil } from '../utils' import { descriptorToRange, markRange } from './annotations' import styles from './styles.css' export async function highlightAnnotation({ annotation }) { // console.log('highlighting') const descriptor = annotation.anchors[0].descriptor const range = await retryUntil( () => descriptorToRange({ descriptor }), range => range !== null, { intervalMiliseconds: 200, timeoutMiliseconds: 5000, }, ) console.log('Memex - found range:', range, range.toString()) markRange({ range, cssClass: styles['memex-highlight'] }) }
import * as AllRaven from 'raven-js' import { retryUntil } from '../utils' import { descriptorToRange, markRange } from './annotations' import styles from './styles.css' const Raven = AllRaven['default'] export async function highlightAnnotation({ annotation }) { // console.log('highlighting') await Raven.context(async () => { const descriptor = annotation.anchors[0].descriptor Raven.captureBreadcrumb({ message: 'annotation-selector-received', category: 'annotations', data: annotation, }) const range = await retryUntil( () => descriptorToRange({ descriptor }), range => range !== null, { intervalMiliseconds: 200, timeoutMiliseconds: 5000, }, ) console.log('Memex - found range:', range, range.toString()) markRange({ range, cssClass: styles['memex-highlight'] }) }) }
Add annotation selector breacrumb for Direct Linking
Add annotation selector breacrumb for Direct Linking
JavaScript
mit
WorldBrain/WebMemex,WorldBrain/WebMemex
cf93826d032895946baf0bfc9742b45dc8623a46
test/index.js
test/index.js
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; require('./tcurl.js'); require('./as-json.js'); require('./as-http.js'); require('./health.js');
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; require('./tcurl.js'); require('./as-thrift.js'); require('./as-json.js'); require('./as-http.js'); require('./health.js');
Add as thrift test to suite
Add as thrift test to suite
JavaScript
mit
uber/tcurl,uber/tcurl,benfleis/tcurl,bobegir/tcurl
bd8e1369263d865f8457ef47c592876279db8be7
lib/util.js
lib/util.js
const Q = require('q'); // Regex to test if the string is likely a facebook user ID const USER_ID_REGEX = /^\d+$/; async function getFBUserInfoByID(api, id) { return await Q.nfcall(api.getUserInfo, id); } async function findFBUser(api, search_str, allowNonFriends) { let userID = search_str; // If the search string isnt a userID, we should search // for the user by name if (!USER_ID_REGEX.test(search_str)) { let userData = await Q.nfcall(api.getUserID, name); userID = userData[0].userID; } const userInfoMap = await getFBUserInfoByID(api, userID); const userInfo = userInfoMap[userID]; if (!userInfo.isFriend && !allowNonFriends) throw new Error( 'User not your friend, they may not be your top ' + name + ", try using '@facebot friends <partial_name>' to get their id or fb vanity name to use" ); // The userinfo object doesnt have an id with it, so add it as its useful userID.id = userID; return userInfo; } module.exports = { findFBUser, };
const Q = require('q'); // Regex to test if the string is likely a facebook user ID const USER_ID_REGEX = /^\d+$/; async function getFBUserInfoByID(api, id) { return await Q.nfcall(api.getUserInfo, id); } async function findFBUser(api, search_str, allowNonFriends) { let userID = search_str; // If the search string isnt a userID, we should search // for the user by name if (!USER_ID_REGEX.test(search_str)) { let userData = await Q.nfcall(api.getUserID, search_str); userID = userData[0].userID; } const userInfoMap = await getFBUserInfoByID(api, userID); const userInfo = userInfoMap[userID]; if (!userInfo.isFriend && !allowNonFriends) throw new Error( 'User not your friend, they may not be your top ' + name + ", try using '@facebot friends <partial_name>' to get their id or fb vanity name to use" ); // The userinfo object doesnt have an id with it, so add it as its useful userInfo.id = userID; return userInfo; } module.exports = { findFBUser, };
Fix issues with findUser refactor
Fix issues with findUser refactor
JavaScript
mit
Weetbix/facebot
a2a86fb46d2d170675dbab2145835871933bad01
common/models/user.js
common/models/user.js
'use strict'; module.exports = function(User) { if (process.env.NODE_ENV !== 'testing') { User.afterRemote('create', async (context, user) => { const options = { type: 'email', protocol: process.env.PROTOCOL || 'http', port: process.env.DISPLAY_PORT || 3000, host: process.env.HOSTNAME || 'localhost', to: user.email, from: 'noreply@redborder.com', user: user, }; user.verify(options, (err, response) => { if (err) { User.deleteById(user.id); throw err; } }); }); } };
'use strict'; class StubMailer { static send(options, context, cb) { cb(null, null); } } module.exports = function(User) { User.afterRemote('create', async (context, user) => { let options = null; if (process.env.NODE_ENV === 'testing') { options = { type: 'email', from: 'test', mailer: StubMailer, }; } else { options = { type: 'email', protocol: process.env.PROTOCOL || 'http', port: process.env.DISPLAY_PORT || 3000, host: process.env.HOSTNAME || 'localhost', to: user.email, from: 'noreply@redborder.com', user: user, }; } user.verify(options, (err, response) => { if (err) { User.deleteById(user.id); throw err; } }); }); };
Use fake mailer on tests
:sparkes: Use fake mailer on tests
JavaScript
agpl-3.0
redBorder/license-manager-api
18c04888ea69acaa86bf43246a1aa135c50c03df
app/utils/query-converter.js
app/utils/query-converter.js
/* global URI */ /** * QueryConverter stores a list of string to string pairs * as a hash (Embereño for POJO) and can export that list as a JSON string, * a URL query string, or a hash. * We will use the JSON string representation as an ID for Ember Data. * To ensure a 1-1 mapping from queries to IDs, * ID representation of a query must be sorted alphabetically by key. */ export default function QueryConverter() { this.fromId = function(id){ this.hash = JSON.parse(id); }; this.fromHash = function(hash){ this.hash = hash; }; this.fromQueryString = function(qString){ this.hash = URI(qString).query(true); }; this.toId = function(){ // JS objects maintain insertion ordering! Woah. // http://stackoverflow.com/questions/5467129/sort-javascript-object-by-key/31102605#31102605 var orderedHash = {}; var unorderedHash = this.hash; Object.keys(this.hash).sort().forEach(function(key){ orderedHash[key] = unorderedHash[key]; }); return JSON.stringify(orderedHash); }; this.toHash = function(){ return this.hash; }; this.toQueryString = function(){ return URI('').addQuery(this.hash).toString(); }; }
/* global URI */ /** * QueryConverter stores a list of string to string pairs * as a hash (Embereño for POJO) and can export that list as a JSON string, * a URL query string, or a hash. * We will use the JSON string representation as an ID for Ember Data. * To ensure a 1-1 mapping from queries to IDs, * ID representation of a query must be sorted alphabetically by key. */ export default function QueryConverter() { this.fromId = function(id){ this.hash = JSON.parse(id); return this; }; this.fromHash = function(hash){ this.hash = hash; return this; }; this.fromQueryString = function(qString){ this.hash = URI(qString).query(true); return this; }; this.toId = function(){ // JS objects maintain insertion ordering! Woah. // http://stackoverflow.com/questions/5467129/sort-javascript-object-by-key/31102605#31102605 var orderedHash = {}; var unorderedHash = this.hash; console.log(unorderedHash); Object.keys(this.hash).sort().forEach(function(key){ orderedHash[key] = unorderedHash[key]; }); return JSON.stringify(orderedHash); }; this.toHash = function(){ return this.hash; }; this.toQueryString = function(){ return URI('').addQuery(this.hash).toString(); }; }
Allow method chaining in QueryConverter
Allow method chaining in QueryConverter
JavaScript
mit
UrbanCCD-UChicago/plenario-explorer,UrbanCCD-UChicago/plenario-explorer,UrbanCCD-UChicago/plenario-explorer
5554134cd1b7f4170a8f100672969ed856a3a929
src/sprites/Common/index.js
src/sprites/Common/index.js
import Phaser from 'phaser'; import { tile, nextTile, alignToGrid, pixelToTile } from '../../tiles'; import { clone } from '../../utils'; import objectPool from '../../object-pool'; import tween from './tween'; export default class extends Phaser.Image { constructor(game, x, y, sprite, frame, id, objectType) { const alignedCoords = alignToGrid({ x, y }); x = alignedCoords.x; y = alignedCoords.y; super(game, x, y, sprite, frame); this.anchor.setTo(0.5, 0.5); // use a bunch of different properties to hopefully achieve a unique id this.id = id || this.key + this.frame + this.x + this.y + (Math.floor(Math.random() * 100) + 1); this.objectType = objectType || 'generic'; this.timers = []; this.tile = {}; this.setTile(); } move(nextPixelCoord, callback) { this.moving = true; tween.call(this, nextPixelCoord, 35, function() { this.moving = false; this.setTile(); if (callback) callback.call(this); }); } setTile() { this.tile = tile.call(this); } resetObject() { this.setTile(); this.timers = []; } destroy() { this.kill(); this.destroyed = true; objectPool.remove(this); } }
import Phaser from 'phaser'; import { tile, nextTile, alignToGrid, pixelToTile } from '../../tiles'; import { clone } from '../../utils'; import objectPool from '../../object-pool'; import tween from './tween'; export default class extends Phaser.Image { constructor(game, x, y, sprite, frame, id, objectType) { const alignedCoords = alignToGrid({ x, y }); x = alignedCoords.x; y = alignedCoords.y; super(game, x, y, sprite, frame); this.anchor.setTo(0.5, 0.5); // use a bunch of different properties to hopefully achieve a unique id this.id = id || this.key + this.frame + this.x + this.y + (Math.floor(Math.random() * 100) + 1); this.objectType = objectType || 'generic'; this.timers = []; this.tile = {}; this.setTile(); } move(nextPixelCoord, callback) { this.moving = true; tween.call(this, nextPixelCoord, 35, function() { this.moving = false; this.setTile(); if (callback) callback.call(this); }); } setTile() { this.tile = tile.call(this); } resetObject() { this.setTile(); this.timers = []; this.destroyed = false; } destroy() { this.kill(); this.destroyed = true; objectPool.remove(this); } }
Reset destroyed flag on reset
Reset destroyed flag on reset
JavaScript
mit
ThomasMays/incremental-forest,ThomasMays/incremental-forest
a896071d4c282a23662e6aa3cfcaaf4a69cb901a
test/tzset.js
test/tzset.js
var should = require('should') , time = require('../') describe('tzset()', function () { beforeEach(function () { process.env.TZ = 'UTC' }) it('should work with no arguments', function () { process.env.TZ = 'US/Pacific' time.tzset() time.currentTimezone.should.equal('US/Pacific') }) it('should work with 1 argument', function () { time.tzset('US/Pacific') time.currentTimezone.should.equal('US/Pacific') }) it('should return a "zoneinfo" object', function () { var info = time.tzset() info.should.have.property('tzname').with.lengthOf(2) info.should.have.property('timezone') info.should.have.property('daylight') }) it('should set `process.env.TZ`', function () { time.tzset('US/Pacific') process.env.TZ.should.equal('US/Pacific') }) })
var should = require('should') , time = require('../') describe('tzset()', function () { beforeEach(function () { process.env.TZ = 'UTC' }) it('should work with no arguments', function () { process.env.TZ = 'US/Pacific' time.tzset() time.currentTimezone.should.equal('US/Pacific') }) it('should work with 1 argument', function () { time.tzset('US/Pacific') time.currentTimezone.should.equal('US/Pacific') }) it('should return a "zoneinfo" object', function () { var info = time.tzset() info.should.have.property('tzname').with.lengthOf(2) info.should.have.property('timezone') info.should.have.property('daylight') }) it('should set `process.env.TZ`', function () { time.tzset('US/Pacific') process.env.TZ.should.equal('US/Pacific') }) it('should work with known values', function () { var info info = time.tzset('UTC') info.tzname[0].should.equal('UTC') info.timezone.should.equal(0) info.daylight.should.equal(0) info = time.tzset('America/Los_Angeles') info.tzname[0].should.equal('PST') info.tzname[1].should.equal('PDT') info.timezone.should.not.equal(0) info = time.tzset('America/Phoenix') info.tzname[0].should.equal('MST') info.tzname[1].should.equal('MDT') info.timezone.should.not.equal(0) info = time.tzset('Europe/Copenhagen') info.tzname[0].should.equal('CET') info.tzname[1].should.equal('CEST') info.timezone.should.not.equal(0) }) })
Add a test testing some known timezone values.
Add a test testing some known timezone values.
JavaScript
mit
TooTallNate/node-time,TooTallNate/node-time,santigimeno/node-time,santigimeno/node-time,santigimeno/node-time,TooTallNate/node-time
60d2770c762811bcd21ab9324d683ea9daedb27c
_src-js/home.js
_src-js/home.js
import window from 'global/window'; import document from 'global/document'; import $ from 'jquery'; import videojs from 'video.js'; const player = window.player = videojs('preview-player', { fluid: true, plugins: { mux: { data: { property_key: 'VJSISBEST', video_title: 'The Boids!', video_id: 1 } } } }); player.on('ready', function() { player.removeClass('placeholder'); }); const overlay = $('.videojs-hero-overlay'); player.on(['play', 'playing'], function() { overlay.addClass('transparent'); }); player.on(['pause'], function() { overlay.removeClass('transparent'); }); // Poor man's lazy loading the iframe content to speed up homeage loading setTimeout(function(){ Array.prototype.forEach.call(document.querySelectorAll('iframe'), function(ifrm){ const src = ifrm.getAttribute('temp-src'); if (src) { ifrm.setAttribute('src', src); } }); }, 1000);
import window from 'global/window'; import document from 'global/document'; import $ from 'jquery'; import videojs from 'video.js'; const player = window.player = videojs('preview-player', { fluid: true, plugins: { mux: { data: { property_key: 'VJSISBEST', video_title: 'Disney\'s Oceans', video_id: 1 } } } }); player.on('ready', function() { player.removeClass('placeholder'); }); const overlay = $('.videojs-hero-overlay'); player.on(['play', 'playing'], function() { overlay.addClass('transparent'); }); player.on(['pause'], function() { overlay.removeClass('transparent'); }); // Poor man's lazy loading the iframe content to speed up homeage loading setTimeout(function(){ Array.prototype.forEach.call(document.querySelectorAll('iframe'), function(ifrm){ const src = ifrm.getAttribute('temp-src'); if (src) { ifrm.setAttribute('src', src); } }); }, 1000);
Fix the title of the main video
Fix the title of the main video
JavaScript
mit
videojs/videojs.com
b6c8c4c49aa05e66504efbae37a2838ddf046564
public_records_portal/static/js/all_requests.js
public_records_portal/static/js/all_requests.js
$(document).ready(function(){ Modernizr.load({ test: Modernizr.inputtypes.date, nope: ['http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js', 'jquery-ui.css'], complete: function () { $('input[type=date]').datepicker({ dateFormat: 'yy-mm-dd' }); } }); });
$(document).ready(function(){ Modernizr.load({ test: Modernizr.inputtypes.date, nope: ['http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js','http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/themes/base/jquery-ui.css'], complete: function () { $('input[type=date]').datepicker({ dateFormat: 'yy-mm-dd' }); } }); });
Update to use correct jquery-ui.css file
Update to use correct jquery-ui.css file
JavaScript
apache-2.0
CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords
e35487c6fb979c0931cd2a3505f4c9063705c702
lib/prefork.js
lib/prefork.js
var prefork = require('../build/Release/prefork').prefork, fs = require('fs'); module.exports = function (options) { options = options || {}; var outfd, errfd; if (Array.isArray(options.customFds) && options.customFds.length < 3) { options.customFds.unshift(-1); } if (options.stdout && typeof options.stdout === 'string') { outfd = fs.openSync(options.stdout, 'a'); } if (options.stderr && typeof options.stderr === 'string') { errfd = fs.openSync(options.stderr, 'a'); } else if (outfd) { errfd = outfd; } if (outfd && errfd) { options.customFds = [ -1, outfd, errfd ]; } prefork(options); };
var prefork = require('../build/Release/prefork').prefork, fs = require('fs'); module.exports = function (options) { options = options || {}; var infd = -1, outfd = -1, errfd = -1, customFds; if (options.stdin && typeof options.stdin === 'string') { infd = fs.openSync(options.stdin, 'r'); } if (options.stdout && typeof options.stdout === 'string') { outfd = fs.openSync(options.stdout, 'a'); } if (options.stderr && typeof options.stderr === 'string') { errfd = fs.openSync(options.stderr, 'a'); } else if (outfd) { errfd = outfd; } if (Array.isArray(options.customFds)) { customFds = options.customFds; } else { customFds = [ infd, outfd, errfd ]; } prefork(customFds); };
Add options.stdin, clean up options logic.
[api] Add options.stdin, clean up options logic.
JavaScript
mit
AvianFlu/node-prefork,AvianFlu/node-prefork,AvianFlu/node-prefork
9b34ee7d9ab3d2cacedcf549273fbca9c6465cb3
api/test/api.js
api/test/api.js
var chai = require('chai'); var chaiHttp = require('chai-http'); var server = require('../app'); var should = chai.should(); // var expect = chai.expect; // var request = require("request"); describe("Date-a-Dog Server", function() { describe("Rest API tests", function() { it('Should return user profile for test user on /api/loginTest', function(done) { chai.request(server) .post('/api/loginTest') .end(function(err, res){ res.should.have.status(200); res.should.be.json; res.body.should.be.a('object'); res.body.should.have.property('id'); res.body.id.should.equal('119889308491710'); done(); }); }); }); });
var chai = require('chai'); var chaiHttp = require('chai-http'); var server = require('../app'); var should = chai.should(); // var expect = chai.expect; // var request = require("request"); chai.use(chaiHttp); describe("Date-a-Dog Server", function() { describe("Rest API tests", function() { it('Should return user profile for test user on /api/loginTest', function(done) { chai.request(server) .post('/api/loginTest') .end(function(err, res){ res.should.have.status(200); res.should.be.json; res.body.should.be.a('object'); res.body.should.have.property('id'); res.body.id.should.equal('119889308491710'); done(); }); }); }); });
Update to first Rest API test
Update to first Rest API test
JavaScript
mit
Date-a-Dog/Date-a-Dog,Date-a-Dog/Date-a-Dog,jammua/dog-dating-app,Date-a-Dog/Date-a-Dog
51167144a5be785042ff15a9435f6ea8c75d6c53
pages/_app.js
pages/_app.js
import '@/css/tailwind.css' import '@/css/prism.css' import { ThemeProvider } from 'next-themes' import Head from 'next/head' import siteMetadata from '@/data/siteMetadata' import Analytics from '@/components/analytics' import LayoutWrapper from '@/components/LayoutWrapper' import { ClientReload } from '@/components/ClientReload' const isDevelopment = process.env.NODE_ENV === 'development' const isSocket = process.env.SOCKET export default function App({ Component, pageProps }) { return ( <ThemeProvider attribute="class" defaultTheme={siteMetadata.theme}> <Head> <meta content="width=device-width, initial-scale=1" name="viewport" /> </Head> {isDevelopment && isSocket && <ClientReload />} <Analytics /> <LayoutWrapper> <Component {...pageProps} /> </LayoutWrapper> </ThemeProvider> ) }
import '@/css/tailwind.css' import '@/css/prism.css' import { ThemeProvider } from 'next-themes' import Head from 'next/head' import moment from 'moment' import siteMetadata from '@/data/siteMetadata' import Analytics from '@/components/analytics' import LayoutWrapper from '@/components/LayoutWrapper' import { ClientReload } from '@/components/ClientReload' const isDevelopment = process.env.NODE_ENV === 'development' const isSocket = process.env.SOCKET const { version } = require('../package.json') const build = moment().format('YYYYMMDDHHmmss') export default function App({ Component, pageProps }) { return ( <ThemeProvider attribute="class" defaultTheme={siteMetadata.theme}> <Head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="version" content={version + '.' + build} /> </Head> {isDevelopment && isSocket && <ClientReload />} <Analytics /> <LayoutWrapper> <Component {...pageProps} /> </LayoutWrapper> </ThemeProvider> ) }
Add meta version for build version
Add meta version for build version
JavaScript
mit
ravuthz/ravuthz.github.io,ravuthz/ravuthz.github.io
3eaf3d248b0118353260a4c9b2f8ecdc23fff359
test/suites/080-dataview.js
test/suites/080-dataview.js
describe('Dataview', function () { this.bail(true) this.timeout(20 * 1000) it('Switch to "Dataview" tab', function (done) { eTT().tab('Dataview').click(done) }) it('Click on second "customDataviewReference" dataview item', function (done) { eTT().dataview('customDataviewReference').select(1, done) }) it('Click on first "customDataviewReference1" dataview item with itemCls', function (done) { eTT().dataview('customDataviewReference1').select(0, done, 'name-item'); }) })
describe('Dataview', function () { this.bail(true) this.timeout(20 * 1000) it('Switch to "Dataview" tab', function (done) { eTT().tab('Dataview').click(done) }) it('Click on second "customDataviewReference" dataview item', function (done) { eTT().dataview('customDataviewReference').select(1, done) }) it('Click on first "customDataviewReference1" dataview item with itemCls', function (done) { eTT().dataview('customDataviewReference1').select(0, done); }) })
Remove cls and swap args
Remove cls and swap args
JavaScript
mit
antonfisher/extjs-testing-tool,antonfisher/extjs-testing-tool,antonfisher/node-mocha-extjs,antonfisher/node-mocha-extjs,antonfisher/mocha-extjs,antonfisher/node-mocha-extjs,antonfisher/extjs-testing-tool,antonfisher/mocha-extjs,antonfisher/mocha-extjs
e44aba0a81f3eaef631290c10776d94d033c74d9
src/templates/interactions/interaction-list.js
src/templates/interactions/interaction-list.js
import { bindable, inject } from 'aurelia-framework'; import imagesLoaded from 'imagesloaded'; import Masonry from 'masonry-layout'; import { EventAggregator } from 'aurelia-event-aggregator'; import { RefreshView } from 'resources/messages'; @inject(EventAggregator) export class InteractionListCustomElement { @bindable interactions = null; constructor(ea) { this.ea = ea; this.refreshView = ea.subscribe(RefreshView, msg => this.createMasonry()); } isAttached = false; attached() { this.isAttached = true; this.createMasonry(); } createMasonry() { var container = document.querySelector('#posts'); imagesLoaded(container, function () { var msnry = new Masonry(container, { columnWidth: ".post", itemSelector: '.post', percentPosition: true, gutter: 10 }); }); } postsChanged() { if (this.isAttached) { this.createMasonry(); } } }
import { bindable, inject } from 'aurelia-framework'; import Masonry from 'masonry-layout'; import { EventAggregator } from 'aurelia-event-aggregator'; import { RefreshedView } from 'resources/messages'; import { Router } from 'aurelia-router'; @inject(EventAggregator, Router) export class InteractionListCustomElement { @bindable interactions = null; constructor(ea, router) { this.ea = ea; this.theRouter = router; this.viewRefreshed = ea.subscribe(RefreshedView, msg => this.createMasonry()); } isAttached = false; attached() { this.isAttached = true; this.createMasonry(); } detached() { this.viewRefreshed(); this.msnry.destroy(); } loadUserRoute(user) { this.theRouter.navigateToRoute("userprofile", { user_id: user }); } createMasonry() { var container = document.querySelector('#posts'); this.msnry = new Masonry(container, { columnWidth: ".post", itemSelector: '.post', percentPosition: true, gutter: 10 }); } postsChanged() { if (this.isAttached) { this.createMasonry(); } } }
Update interactions, removed image and added in the correct event
Update interactions, removed image and added in the correct event
JavaScript
mit
mttmccb/dark_social,mttmccb/dark_social,mttmccb/dark_social
fee15f1ba4479c2cbfa2005cea0f46bf53b9604c
src/article/TableCellNode.js
src/article/TableCellNode.js
import { XMLTextElement } from 'substance' import { TEXT } from '../kit' export default class TableCellNode extends XMLTextElement { constructor (...args) { super(...args) this.rowIdx = -1 this.colIdx = -1 } get rowspan () { return _parseSpan(this.getAttribute('rowspan')) } get colspan () { return _parseSpan(this.getAttribute('colspan')) } isShadowed () { return this.shadowed } getMasterCell () { return this.masterCell } } TableCellNode.type = 'table-cell' TableCellNode.schema = { content: TEXT('bold', 'italic', 'sup', 'sub', 'monospace', 'ext-link', 'xref', 'inline-formula') } function _parseSpan (str) { let span = parseInt(str, 10) if (isFinite(span)) { return Math.max(span, 1) } else { return 1 } }
import { XMLTextElement } from 'substance' import { TEXT } from '../kit' export default class TableCellNode extends XMLTextElement { constructor (...args) { super(...args) this.rowIdx = -1 this.colIdx = -1 } get rowspan () { return _parseSpan(this.getAttribute('rowspan')) } get colspan () { return _parseSpan(this.getAttribute('colspan')) } isShadowed () { return this.shadowed } getMasterCell () { return this.masterCell } } TableCellNode.type = 'table-cell' TableCellNode.schema = { content: TEXT('bold', 'italic', 'sup', 'sub', 'monospace', 'ext-link', 'xref', 'inline-formula', 'inline-graphic') } function _parseSpan (str) { let span = parseInt(str, 10) if (isFinite(span)) { return Math.max(span, 1) } else { return 1 } }
Allow for inline-graphic in table cell.
Allow for inline-graphic in table cell.
JavaScript
mit
substance/texture,substance/texture
9163d9dbc4f58aefbc620934c3db961f0bbf0477
mocks/index.js
mocks/index.js
var config = require('../lib/config'), cors = require('../lib/cors'), fs = require('fs'); var paths = [], len = 0; exports.init = function() { if (config.mocksEnabled) { console.log("Mock server enabled"); var pathSource = require('./paths'); for (var name in pathSource) { paths.push({ regex: new RegExp(name), source: pathSource[name] }); } len = paths.length; } }; exports.provider = function(req, res, next) { if (config.mocksEnabled) { var replaceUrl = req.url.replace(/\?username=mobile&password=1111&/, '?'); for (var i = 0; i < len; i++) { var path = paths[i]; if (path.regex.test(replaceUrl)) { console.log('Mocking url', req.url, 'to', (typeof path.source !== 'function' ? 'file' + path.source : 'callback')); cors.applyCORS(req.headers.host, res); if (req.method !== 'HEAD') { req.method = 'GET'; // The static provider which this eventually uses does not like the options command, which breaks the mocking } if (typeof path.source === 'function') { res.send(path.source.apply(path.source, Array.prototype.slice.call(replaceUrl.match(path.regex), 1))); } else { res.sendfile(__dirname + '/' + path.source); } return; } } } next(); };
var config = require('../lib/config'), cors = require('../lib/cors'), fs = require('fs'); var paths = [], len = 0; exports.init = function() { if (config.mocksEnabled) { console.log("Mock server enabled"); } var pathSource = require('./paths'); for (var name in pathSource) { paths.push({ regex: new RegExp(name), source: pathSource[name] }); } len = paths.length; }; exports.provider = function(req, res, next) { if (config.mocksEnabled) { var replaceUrl = req.url.replace(/\?username=mobile&password=1111&/, '?'); for (var i = 0; i < len; i++) { var path = paths[i]; if (path.regex.test(replaceUrl)) { console.log('Mocking url', req.url, 'to', (typeof path.source !== 'function' ? 'file' + path.source : 'callback')); cors.applyCORS(req.headers.host, res); if (req.method !== 'HEAD') { req.method = 'GET'; // The static provider which this eventually uses does not like the options command, which breaks the mocking } if (typeof path.source === 'function') { res.send(path.source.apply(path.source, Array.prototype.slice.call(replaceUrl.match(path.regex), 1))); } else { res.sendfile(__dirname + '/' + path.source); } return; } } } next(); };
Allow runtime toggling of mocks
Allow runtime toggling of mocks
JavaScript
mit
walmartlabs/mock-server,walmartlabs/mock-server
41e38cf5affb703233b4aa0097af8e7d10e4e817
config/deprecation-workflow.js
config/deprecation-workflow.js
/* global window */ window.deprecationWorkflow = window.deprecationWorkflow || {}; window.deprecationWorkflow.config = { workflow: [ { handler: 'silence', matchId: 'ember-metal.get-with-default' }, { handler: 'silence', matchId: 'manager-capabilities.modifiers-3-13' }, //https://github.com/emberjs/ember-render-modifiers/issues/32 { handler: 'silence', matchId: 'this-property-fallback' }, { handler: 'silence', matchId: 'ember-lifeline-deprecated-addeventlistener' }, { handler: 'silence', matchId: 'ember-test-helpers.setup-rendering-context.render' }, { handler: 'silence', matchId: 'routing.transition-methods' }, { handler: 'silence', matchId: 'ember-cli-page-object.is-property' }, ], };
/* global window */ window.deprecationWorkflow = window.deprecationWorkflow || {}; window.deprecationWorkflow.config = { workflow: [ { handler: 'silence', matchId: 'manager-capabilities.modifiers-3-13' }, //https://github.com/emberjs/ember-render-modifiers/issues/32 { handler: 'silence', matchId: 'this-property-fallback' }, { handler: 'silence', matchId: 'ember-lifeline-deprecated-addeventlistener' }, { handler: 'silence', matchId: 'ember-test-helpers.setup-rendering-context.render' }, { handler: 'silence', matchId: 'routing.transition-methods' }, { handler: 'silence', matchId: 'ember-cli-page-object.is-property' }, ], };
Remove get with default deprecation
Remove get with default deprecation This is cleared in our app, we don't need to silence it anymore.
JavaScript
mit
jrjohnson/frontend,dartajax/frontend,ilios/frontend,ilios/frontend,dartajax/frontend,jrjohnson/frontend
af6cdec03b5ff9934466b7625e887d76f0a862ce
script.js
script.js
(() => { 'use strict'; var player = "O"; var moves = []; var winningCombos = [ ["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["1", "5", "9"], ["3", "5", "7"], ["1", "4", "7"], ["2", "5", "8"], ["3", "6", "9"]]; window.play = (sq) => { if (sq.innerHTML !== "O" && sq.innerHTML !== "X") { drawMark(sq); saveMove(sq); if (isWinner()) { colourWinner(); }; changePlayer(); } }; var drawMark = td => td.innerHTML = player; var saveMove = td => moves[td.id] = player; var isWinner = () => (winningCombos.filter(isWinningCombo).length > 0); var isWinningCombo = combo => (combo.filter(sq => moves[sq] === player).length === 3); var colourWinner = () => winningCombos.filter(isWinningCombo).map(colourCombo); var colourCombo = combo => combo.map(sq => document.getElementById(sq + "").style.backgroundColor = "green"); var changePlayer = () => (player === "O") ? player = "X" : player = "O"; })();
(() => { 'use strict'; var player = "O"; var moves = []; var winningCombos = [ ["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["1", "5", "9"], ["3", "5", "7"], ["1", "4", "7"], ["2", "5", "8"], ["3", "6", "9"]]; window.play = (sq) => { if (sq.innerHTML !== "O" && sq.innerHTML !== "X") { drawMark(sq); saveMove(sq); if (isWinner()) { colourWinner(); }; changePlayer(); } }; var drawMark = td => td.innerHTML = player; var saveMove = td => moves[td.id] = player; var isWinner = () => (winningCombos.filter(isWinningCombo).length > 0); var isWinningCombo = combo => (combo.filter(sq => moves[sq] === player).length === 3); var colourWinner = () => winningCombos.filter(isWinningCombo).forEach(colourCombo); var colourCombo = combo => combo.forEach(sq => document.getElementById(sq + "").style.backgroundColor = "green"); var changePlayer = () => (player === "O") ? player = "X" : player = "O"; })();
Change from map to forEach.
Change from map to forEach.
JavaScript
mit
olillevik/olillevik.github.io,olillevik/olillevik.github.io
6d0b782f76d6c05a5a2bb6c085de8a8767cf3b06
app/assets/javascripts/tenon/tenon_manifest.js
app/assets/javascripts/tenon/tenon_manifest.js
//= require jquery //= require jquery_ujs // -- Plugins, in alphabetical order //= require backstretch //= require bootstrap //= require bootstrap.collapse //= require bootstrap.modal //= require bootstrap.tabs //= require canvasjs.min //= require cocoon //= require imagesloaded //= require jquery-fileupload/basic //= require jquery-fileupload/vendor/tmpl //= require jquery.debounce //= require jquery.equalHeights //= require jquery.hoverIntent //= require jquery.Jcrop //= require jquery.mousewheel //= require jquery.radioSlider //= require jquery.twoLevelSort //= require jquery.ui.sortable //= require medium-editor //= require select2 // -- Plugins that need to be loaded in order //= require moment //= require bootstrap.datetimepicker //= require lodash //= require underscore.string //= require underscore.inflection // -- Tenon things, don't mess with the order //= require ./tenon //= require ./tenon_dispatcher //= require_tree ./templates //= require_tree ./controllers //= require_tree ./features //= require_self $(function() { Tenon.init(); });
//= require jquery //= require jquery_ujs // -- Plugins, in alphabetical order //= require backstretch //= require bootstrap //= require bootstrap.collapse //= require bootstrap.modal //= require bootstrap.tabs //= require canvasjs.min //= require cocoon //= require imagesloaded //= require jquery-fileupload/basic //= require jquery-fileupload/vendor/tmpl //= require jquery.debounce //= require jquery.equalHeights //= require jquery.hoverIntent //= require jquery.Jcrop //= require jquery.mousewheel //= require jquery.radioSlider //= require jquery.twoLevelSort //= require jquery.ui.sortable //= require medium-editor //= require select2 // -- Plugins that need to be loaded in order //= require moment //= require bootstrap.datetimepicker //= require lodash //= require underscore.string //= require underscore.inflection // -- Tenon things, don't mess with the order //= require ./tenon //= require ./tenon_dispatcher //= require_tree ./templates //= require_tree ./controllers //= require_tree ./features //= require tenon_addons //= require_self $(function() { Tenon.init(); });
Call the custom tenon files
Call the custom tenon files
JavaScript
mit
factore/tenon,factore/tenon,factore/tenon,factore/tenon
0df84d28c5767cfd17c54d3eff5d338ad5c31768
src/components/status-tag.js
src/components/status-tag.js
import React from 'react'; import PropTypes from 'prop-types'; import {css} from 'react-emotion'; const wipStyle = css` background-color: tomato; color: ivory; font-variant: small-caps; line-height: 1.1; padding: 0 2px; `; const expStyle = css` background-color: deepskyblue; color: ivory; font-variant: small-caps; line-height: 1.1; padding: 0 2px; `; const StatusTag = ({label}) => { switch (label) { case 'wip': return <small className={wipStyle}>wip</small>; case 'exp': return <small className={expStyle}>exp</small>; default: return null; } }; StatusTag.propTypes = { label: PropTypes.string, }; export default StatusTag;
import React from 'react'; import PropTypes from 'prop-types'; import {css} from 'react-emotion'; const wipStyle = css` background-color: tomato; color: ivory; font-variant: small-caps; line-height: 1.1; padding: 0 2px; font-size: 12px; border-bottom: none; `; const expStyle = css` background-color: deepskyblue; color: ivory; font-variant: small-caps; line-height: 1.1; padding: 0 2px; font-size: 12px; border-bottom: none; `; const StatusTag = ({label}) => { switch (label) { case 'wip': return <abbr title="work in progress" className={wipStyle}>wip</abbr>; case 'exp': return <abbr className={expStyle} title="experimental">exp</abbr>; default: return null; } }; StatusTag.propTypes = { label: PropTypes.string, }; export default StatusTag;
Use abbr for status tags
style: Use abbr for status tags Signed-off-by: Arnau Siches <3ce1c0b0b7032cdfdae7820ed353835a9a8f94c3@digital.cabinet-office.gov.uk>
JavaScript
mit
openregister/specification