commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
25b2d06fe260f734ef6944062f410a74c3100bb5
sound-wave.js
sound-wave.js
const fs = require('fs'); const sampleRate = 44100, resolution = 16; const maxLevel = Math.pow(2, resolution - 1) - 1, BinaryArray = { 8: Int8Array, 16: Int16Array, 32: Int32Array }[resolution]; function sineWave(frequency, duration) { var samplesCount = duration * sampleRate, array = new BinaryArray(samplesCount); for (var sampleNumber = 0; sampleNumber < samplesCount; sampleNumber++) { var currentTime = sampleNumber / sampleRate, signal = Math.sin(2 * Math.PI * frequency * currentTime), level = Math.floor(signal * maxLevel); array[sampleNumber] = level; } return array; } function writePCM(filename, frequency, duration) { var array = sineWave(frequency, duration), buffer = new Buffer(array); fs.writeFile(filename, buffer, 'binary'); } writePCM('440hz.pcm', 440, 10);
const fs = require('fs'); const sampleRate = 44100, resolution = 16; const maxLevel = Math.pow(2, resolution - 1) - 1, BinaryArray = { 8: Int8Array, 16: Int16Array, 32: Int32Array }[resolution]; function sineWave(frequency, duration) { var samplesCount = Math.floor(duration * sampleRate), array = new BinaryArray(samplesCount); for (var sampleNumber = 0; sampleNumber < samplesCount; sampleNumber++) { var currentTime = sampleNumber / sampleRate, signal = Math.sin(2 * Math.PI * frequency * currentTime), level = Math.floor(signal * maxLevel); array[sampleNumber] = level; } return array; } function writePCM(filename, frequency, duration) { var array = sineWave(frequency, duration), buffer = new Buffer(array.buffer); fs.writeFile(filename, buffer, 'binary'); } writePCM('440hz.pcm', 440, 10);
Use array.buffer so that TypedArray and Buffer share the same memory
Use array.buffer so that TypedArray and Buffer share the same memory
JavaScript
mit
aqrln/sound-wave
4080e7daa4b5a9e7e37273036ac9e489bea226b9
spec/support/fixtures/stripejs-mock.js
spec/support/fixtures/stripejs-mock.js
class Element { mount(el) { if (typeof el === "string") { el = document.querySelector(el); } el.classList.add('StripeElement'); el.innerHTML = ` <input id="stripe-cardnumber" name="cardnumber" placeholder="Card number" size="16" type="text"> <input name="exp-date" placeholder="MM / YY" size="6" type="text"> <input name="cvc" placeholder="CVC" size="3" type="text"> `; } addEventListener(event) { return true; } } window.Stripe = () => { const fetchLastFour = () => { return document.getElementById("stripe-cardnumber").value.substr(-4, 4); }; return { createPaymentMethod: () => { return new Promise(resolve => { resolve({ paymentMethod: { id: "pm_123", card: { brand: 'visa', last4: fetchLastFour(), exp_month: "10", exp_year: "2050" } } }); }); }, elements: () => { return { create: (type, options) => new Element() }; }, createToken: card => { return new Promise(resolve => { resolve({ token: { id: "tok_123", card: { last4: fetchLastFour() } } }); }); } }; };
// StripeJS fixture for using Stripe in feature specs. Mimics credit card form and Element objects. // Based on: https://github.com/thoughtbot/fake_stripe/blob/v0.3.0/lib/fake_stripe/assets/v3.js // The original has been adapted to work with OFN (see commit history for details). class Element { mount(el) { if (typeof el === "string") { el = document.querySelector(el); } el.classList.add('StripeElement'); el.innerHTML = ` <input id="stripe-cardnumber" name="cardnumber" placeholder="Card number" size="16" type="text"> <input name="exp-date" placeholder="MM / YY" size="6" type="text"> <input name="cvc" placeholder="CVC" size="3" type="text"> `; } addEventListener(event) { return true; } } window.Stripe = () => { const fetchLastFour = () => { return document.getElementById("stripe-cardnumber").value.substr(-4, 4); }; return { createPaymentMethod: () => { return new Promise(resolve => { resolve({ paymentMethod: { id: "pm_123", card: { brand: 'visa', last4: fetchLastFour(), exp_month: "10", exp_year: "2050" } } }); }); }, elements: () => { return { create: (type, options) => new Element() }; }, createToken: card => { return new Promise(resolve => { resolve({ token: { id: "tok_123", card: { last4: fetchLastFour() } } }); }); } }; };
Add comments in StripeJS mock
Add comments in StripeJS mock
JavaScript
agpl-3.0
lin-d-hop/openfoodnetwork,openfoodfoundation/openfoodnetwork,lin-d-hop/openfoodnetwork,Matt-Yorkley/openfoodnetwork,mkllnk/openfoodnetwork,lin-d-hop/openfoodnetwork,Matt-Yorkley/openfoodnetwork,Matt-Yorkley/openfoodnetwork,mkllnk/openfoodnetwork,openfoodfoundation/openfoodnetwork,mkllnk/openfoodnetwork,openfoodfoundation/openfoodnetwork,lin-d-hop/openfoodnetwork,openfoodfoundation/openfoodnetwork,Matt-Yorkley/openfoodnetwork,mkllnk/openfoodnetwork
6f83ef247f86a8581c9b66841cdea826a6fd90ed
server/config/db.js
server/config/db.js
var connection = { client: 'mysql', connection: { host: process.env.HOST, database: process.env.APP_NAME, user: process.env.DB_USER, password: process.env.DB_PASSWORD, charset: 'utf8' } }; var knex = require('knex')(connection); connection.database = process.env.APP_NAME; var db = require('bookshelf')(knex); module.exports = db;
var connection = { client: 'mysql', connection: { host: 'localhost', database: process.env.APP_NAME, user: process.env.DB_USER, password: process.env.DB_PASSWORD, charset: 'utf8' } }; var knex = require('knex')(connection); connection.database = process.env.APP_NAME; var db = require('bookshelf')(knex); module.exports = db;
Adjust database host to always be localhost
Adjust database host to always be localhost
JavaScript
mit
chkakaja/sentimize,formidable-coffee/masterfully,formidable-coffee/masterfully,chkakaja/sentimize
7f6e9e09e064c6d8b51960a579375684d660ecc9
src/client.js
src/client.js
import React from 'react' import ReactDOM from 'react-dom' /* Create a simple component without JSX <div> React Tutorial </div> */ const App = function() { return React.createElement('div', null, 'React Tutorial'); } ReactDOM.render(<App />, document.getElementById('app'))
import React from 'react' import ReactDOM from 'react-dom' /* Create a simple component without JSX <div> React Tutorial </div> */ const App = function() { // return React.createElement('div', null, 'React Tutorial'); return <div>React Tutorial</div>; } ReactDOM.render(<App />, document.getElementById('app'))
Create a simple component with JSX
Create a simple component with JSX
JavaScript
mit
suranartnc/react-tutorial
27e809275ab1132260bf0327b6134d60e095844c
src/dollrs.js
src/dollrs.js
import create from './create'; export default function $$(ufo, context) { if (typeof ufo === 'string') { // if it seems to be HTML, create an elements if (/^\s*</.test(ufo)) { return create(ufo); } if (context) { return $$(context) .reduce((result, element) => result.concat($$(element.querySelectorAll(ufo))), []); } return $$(document.querySelectorAll(ufo)); } else if (ufo instanceof Node) { return [ufo]; } else if (ufo instanceof Array) { return ufo; } else if (ufo instanceof NodeList || ufo instanceof HTMLCollection) { return Array.prototype.slice.call(ufo); } return []; }
import create from './create'; export default function $$(ufo, context) { if (typeof ufo === 'string') { // if it seems to be HTML, create an elements if (/^\s*</.test(ufo)) { return $$(create(ufo)); } if (context) { return $$(context) .reduce((result, element) => result.concat($$(element.querySelectorAll(ufo))), []); } return $$(document.querySelectorAll(ufo)); } else if (ufo instanceof Node) { return [ufo]; } else if (ufo instanceof Array) { return ufo; } else if (ufo instanceof NodeList || ufo instanceof HTMLCollection) { return Array.from(ufo); } return []; }
Return array when creating from string and better conversion to array
Return array when creating from string and better conversion to array
JavaScript
mit
lohfu/dollr
c1a494f0250e742d548c1585bb71ed16730ab45a
lib/spawnHelper.js
lib/spawnHelper.js
var childProcess = require('child_process'); var q = require('q'); var runCommand = function(command) { var deferred = q.defer(); console.log('Running command: [%s]', command); var commandArray = command.split(/\s/); // First arg: command, then pass arguments as array. var child = childProcess.spawn(commandArray[0], commandArray.slice(1)); child.stdout.on('data', function(data) { var line = data.toString(); process.stdout.write(line); // Wait until the port is ready to resolve the promise. if (line.match(/Server listening on/g)) { deferred.resolve(); } }); // The process uses stderr for debugging info. Ignore errors. child.stderr.on('data', process.stderr.write); return deferred.promise; }; module.exports = { runCommand: runCommand };
var childProcess = require('child_process'); var q = require('q'); /** * Spawn a child process given a command. Wait for the process to start given * a regexp that will be matched against stdout. * * @param {string} command The command to execute. * @param {RegExp} waitRegexp An expression used to test when the process has * started. * @return {Q.promise} A promise that resolves when the process has stated. */ var runCommand = function(command, waitRegexp) { var deferred = q.defer(); console.log('Running command: [%s]', command); var commandArray = command.split(/\s/); // First arg: command, then pass arguments as array. var child = childProcess.spawn(commandArray[0], commandArray.slice(1)); child.stdout.on('data', function(data) { var line = data.toString(); process.stdout.write(line); // Wait until the port is ready to resolve the promise. if (line.match(waitRegexp)) { deferred.resolve(); } }); // The process uses stderr for debugging info. Ignore errors. child.stderr.on('data', process.stderr.write); return deferred.promise; }; module.exports = { runCommand: runCommand };
Add waitRegexp as an argument.
Add waitRegexp as an argument.
JavaScript
mit
andresdominguez/elementor,andresdominguez/elementor
c2fc624fd9d7d836a4f423baf8c64b0a053bb24f
src/kinvey.js
src/kinvey.js
import { Promise } from 'es6-promise'; import { Kinvey as CoreKinvey, isDefined, KinveyError } from 'kinvey-js-sdk/dist/export'; import { Client } from './client'; export class Kinvey extends CoreKinvey { static initialize(config) { const client = Kinvey.init(config); return Promise.resolve(client.getActiveUser()); } static init(options = {}) { if (!isDefined(options.appKey)) { throw new KinveyError('No App Key was provided.' + ' Unable to create a new Client without an App Key.'); } if (!isDefined(options.appSecret) && !isDefined(options.masterSecret)) { throw new KinveyError('No App Secret or Master Secret was provided.' + ' Unable to create a new Client without an App Key.'); } return Client.init(options); } }
import { Promise } from 'es6-promise'; import url from 'url'; import { Kinvey as CoreKinvey, isDefined, KinveyError, CacheRequest, RequestMethod } from 'kinvey-js-sdk/dist/export'; import { Client } from './client'; const USERS_NAMESPACE = 'user'; const ACTIVE_USER_COLLECTION_NAME = 'kinvey_active_user'; export class Kinvey extends CoreKinvey { static initialize(config) { const client = Kinvey.init(config); const activeUser = client.getActiveUser(); if (isDefined(activeUser)) { return Promise.resolve(activeUser); } const request = new CacheRequest({ method: RequestMethod.GET, url: url.format({ protocol: client.apiProtocol, host: client.apiHost, pathname: `/${USERS_NAMESPACE}/${client.appKey}/${ACTIVE_USER_COLLECTION_NAME}` }) }); return request.execute() .then(response => response.data) .then((activeUsers) => { if (activeUsers.length > 0) { return activeUsers[0]; } return null; }) .then((activeUser) => { if (isDefined(activeUser)) { return client.setActiveUser(activeUser); } return activeUser; }); } static init(options = {}) { if (!isDefined(options.appKey)) { throw new KinveyError('No App Key was provided.' + ' Unable to create a new Client without an App Key.'); } if (!isDefined(options.appSecret) && !isDefined(options.masterSecret)) { throw new KinveyError('No App Secret or Master Secret was provided.' + ' Unable to create a new Client without an App Secret.'); } return Client.init(options); } }
Load the active user using the previous stored location if an active user does not exist
Load the active user using the previous stored location if an active user does not exist
JavaScript
apache-2.0
Kinvey/kinvey-html5-lib
85518b0b853f9feee2822df289501508c7af6d19
transformers/browserchannel/server.js
transformers/browserchannel/server.js
'use strict'; /** * Minimum viable Browserchannel server for Node.js that works through the primus * interface. * * @runat server * @api private */ module.exports = function server() { var browserchannel = require('browserchannel') , Spark = this.Spark , primus = this.primus , query = {}; // // We've received a new connection, create a new Spark. The Spark will // automatically announce it self as a new connection once it's created (after // the next tick). // this.service = browserchannel.server({ base: primus.pathname }, function connection(socket) { var spark = new Spark( socket.headers // HTTP request headers. , socket.address // IP address. , query // Query string, not allowed by browser channel. , socket.id // Unique connection id. ); spark.on('outgoing::end', function end() { socket.close(); }).on('outgoing::data', function write(data) { socket.send(data); }); socket.on('close', spark.emits('end')); socket.on('message', spark.emits('data')); }); // // Listen to upgrade requests. // this.on('request', function request(req, res, next) { // // The browser.channel returns a middleware layer. // this.service(req, res, next); }); };
'use strict'; /** * Minimum viable Browserchannel server for Node.js that works through the primus * interface. * * @runat server * @api private */ module.exports = function server() { var browserchannel = require('browserchannel') , Spark = this.Spark , primus = this.primus , query = {}; // // We've received a new connection, create a new Spark. The Spark will // automatically announce it self as a new connection once it's created (after // the next tick). // this.service = browserchannel.server({ base: primus.pathname }, function connection(socket) { var spark = new Spark( socket.headers // HTTP request headers. , socket.address // IP address. , query // Query string, not allowed by browser channel. , socket.id // Unique connection id. ); spark.on('outgoing::end', function end() { socket.stop(); }).on('outgoing::data', function write(data) { socket.send(data); }); socket.on('close', spark.emits('end')); socket.on('message', spark.emits('data')); }); // // Listen to upgrade requests. // this.on('request', function request(req, res, next) { // // The browser.channel returns a middleware layer. // this.service(req, res, next); }); };
Use stop instead of close, it fixes, things.
[minor] Use stop instead of close, it fixes, things.
JavaScript
mit
primus/primus,basarat/primus,dercodebearer/primus,colinbate/primus,modulexcite/primus,basarat/primus,colinbate/primus,STRML/primus,colinbate/primus,beni55/primus,dercodebearer/primus,dercodebearer/primus,clanwqq/primus,beni55/primus,modulexcite/primus,modulexcite/primus,clanwqq/primus,primus/primus,primus/primus,basarat/primus,STRML/primus,STRML/primus,clanwqq/primus,beni55/primus
75e74cf1d434f564535fd1fef06ab18963a57277
src/resource/RefraxParameters.js
src/resource/RefraxParameters.js
/** * Copyright (c) 2015-present, Joshua Hollenbeck * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ /** * A RefraxStore is a wrapper around the RefraxFragmentCache object that offers * a Subscribable interface to resource mutations. */ class RefraxParameters { constructor(params) { this.params = params; } } export default RefraxParameters;
/** * Copyright (c) 2015-present, Joshua Hollenbeck * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ const RefraxTools = require('RefraxTools'); /** * A RefraxParameters is a wrapper around an object to identify it as a * set of parameters. */ class RefraxParameters { constructor(params) { RefraxTools.extend(this, params); } } export default RefraxParameters;
Update Parameters to be self extending vs containing to conform to Options
Update Parameters to be self extending vs containing to conform to Options
JavaScript
bsd-3-clause
netarc/refrax,netarc/refrax
b08bdaf5628bb9c1a13c20110f7cae593c6c66c5
test/helpers.js
test/helpers.js
// ---------------------------------------------------------------------------- // // helpers.js // // ---------------------------------------------------------------------------- var dyno = require('../dyno-leveldb.js'); function newDyno() { return dyno('/tmp/' + (new Date()).toISOString()); }; // ---------------------------------------------------------------------------- function pad(str, length) { while ( str.length < length ) { str = '0' + str; } return str; } // first thing to do is make a simple timestamp function var i = 0; function timestamp() { i++; return (new Date()).toISOString() + '-' + pad(i, 16); } // ---------------------------------------------------------------------------- module.exports.timestamp = timestamp; module.exports.newDyno = newDyno; // ----------------------------------------------------------------------------
// ---------------------------------------------------------------------------- // // helpers.js // // ---------------------------------------------------------------------------- var dyno = require('../dyno-leveldb.js'); function newDyno() { return dyno('/tmp/' + (new Date()).toISOString()); }; // ---------------------------------------------------------------------------- function pad(str, length) { str = '' + str; while ( str.length < length ) { str = '0' + str; } return str; } // first thing to do is make a simple timestamp function var i = 0; function timestamp() { i++; return (new Date()).toISOString() + '-' + pad(i, 8); } // ---------------------------------------------------------------------------- module.exports.timestamp = timestamp; module.exports.newDyno = newDyno; // ----------------------------------------------------------------------------
Make sure the pad() function works correctly
Make sure the pad() function works correctly
JavaScript
mit
chilts/modb-dyno-leveldb
4dca2713e1cd68f08177a62e06f8ba1bfe6dc925
src/native/index.js
src/native/index.js
import 'babel-polyfill'; import React from 'react'; import { ApolloProvider } from 'react-apollo'; import { AppRegistry } from 'react-native'; import { NativeRouter } from 'react-router-native'; import config from 'react-native-config'; import Raven from 'raven-js'; import RavenRNPlugin from 'raven-js/plugins/react-native'; import App from './components/App'; import client from './configs/apollo'; import store from './store'; // Initialize Sentry error reporting RavenRNPlugin(Raven); Raven.config(config.SENTRY_DSN, { release: config.RELEASE_ID }); console.disableYellowBox = true; // All of our configuration level stuff - routing, GraphQL, Native-Base theme const Root = () => ( <ApolloProvider client={client} store={store}> <NativeRouter> <App /> </NativeRouter> </ApolloProvider> ); AppRegistry.registerComponent('strap', () => Root);
import 'babel-polyfill'; import React from 'react'; import { ApolloProvider } from 'react-apollo'; import { AppRegistry } from 'react-native'; import { NativeRouter } from 'react-router-native'; import config from 'react-native-config'; import Raven from 'raven-js'; import RavenRNPlugin from 'raven-js/plugins/react-native'; import App from './components/App'; import client from './configs/apollo'; import store from './store'; // Initialize Sentry error reporting RavenRNPlugin(Raven); Raven.config(config.SENTRY_DSN, { release: config.RELEASE_ID }).install(); console.disableYellowBox = true; // All of our configuration level stuff - routing, GraphQL, Native-Base theme const Root = () => ( <ApolloProvider client={client} store={store}> <NativeRouter> <App /> </NativeRouter> </ApolloProvider> ); AppRegistry.registerComponent('strap', () => Root);
Add missing install call to raven config
feat(native): Add missing install call to raven config
JavaScript
mit
meatwallace/strap,meatwallace/strap,meatwallace/strap
78476fd9e92f986e641c5bb8d07ec37451d04fe9
test/karma.js
test/karma.js
import karma from '../src/karma'; describe('karma config', function() { it('should generate config', function() { // Success is not throwing at this point. The simple karma tests // will do the actual verification karma({set() {}}); }); });
/* eslint-disable no-process-env */ import karma from '../src/karma'; import {expect} from 'chai'; describe('karma config', function() { const KARMA_BROWSER = process.env.KARMA_BROWSER; afterEach(function() { if (KARMA_BROWSER) { process.env.KARMA_BROWSER = KARMA_BROWSER; } else { delete process.env.KARMA_BROWSER; } }); it('should generate config', function() { // Success is not throwing at this point. The simple karma tests // will do the actual verification karma({set() {}}); }); it('should default to chrome browser', function() { process.env.KARMA_BROWSER = ''; let config; karma({set(_config) { config = _config; }}); expect(config.browsers).to.eql(['Chrome']); }); it('should allow custom browser', function() { process.env.KARMA_BROWSER = 'test!'; let config; karma({set(_config) { config = _config; }}); expect(config.browsers).to.eql(['test!']); }); });
Add missing coverage for KARMA_BROWSER flag
Add missing coverage for KARMA_BROWSER flag
JavaScript
mit
kpdecker/linoleum-node,kpdecker/linoleum-electron,kpdecker/linoleum-electron,kpdecker/linoleum-webpack,kpdecker/linoleum
2307e2272e30d580b62ca2006dc99045cd63a9e8
test/suite.js
test/suite.js
var siteName = "tlks.io"; // http://tlks.io/ casper.test.begin('Testing tlks.io UI', 2, function(test) { var url = "http://tlks.io/"; casper.start(url); casper.then(function() { this.test.assert(this.getCurrentUrl() === url, 'url is the one expected'); }); casper.then(function() { this.test.assertHttpStatus(200, siteName + ' is up'); }); casper.run(function() { this.test.done(); this.exit(); }); });
var siteName = "tlks.io"; // http://tlks.io/ casper.test.begin('Testing tlks.io UI', 2, function(test) { var url = "http://tlks.io/"; casper.start(url); casper.then(function() { this.test.assert(this.getCurrentUrl() === url, 'url is the one expected'); }); casper.then(function() { this.test.assertHttpStatus(200, siteName + ' is up'); }); casper.run(function() { this.test.done(); }); }); // http://tlks.io/about casper.test.begin('Testing tlks.io : About UI', 2, function(test) { var url = "http://tlks.io/about"; casper.start(url); casper.then(function() { this.test.assert(this.getCurrentUrl() === url, 'url is the one expected'); }); casper.then(function() { this.test.assertHttpStatus(200, siteName + ' is up'); }); casper.run(function() { this.test.done(); this.exit(); }); });
Test About for HTTP 200
Test About for HTTP 200
JavaScript
mit
tlksio/front,tlksio/front
b4030f75471af2309f3bd4a75fff708f8cbc0eb5
test/types.js
test/types.js
import test from 'ava'; import whenDomReady from '../'; test('whenDomReady is a function', t => { t.is(typeof whenDomReady, 'function'); }); test('whenDomReady returns a Promise', t => { t.true(whenDomReady() instanceof Promise); }); test('whenDomReady.resume is a function', t => { t.is(typeof whenDomReady.resume, 'function'); }); test('whenDomReady.resume returns a function that returns a promise', t => { const returnValue = whenDomReady.resume(); t.is(typeof returnValue, 'function'); t.true(returnValue() instanceof Promise); });
import test from 'ava'; import jsdom from 'jsdom'; import whenDomReady from '../'; test('whenDomReady is a function', t => { t.is(typeof whenDomReady, 'function'); }); test('whenDomReady returns a Promise', t => { t.true(whenDomReady() instanceof Promise); }); test('whenDomReady.resume is a function', t => { t.is(typeof whenDomReady.resume, 'function'); }); test('whenDomReady.resume returns a function that returns a promise', t => { const returnValue = whenDomReady.resume(); t.is(typeof returnValue, 'function'); t.true(returnValue() instanceof Promise); }); test.cb('Promise value always resolves to undefined', t => { t.plan(2); const config = { html: '', onload: window => { const promises = []; promises.push(whenDomReady(() => 'foo', window.document).then(val => t.is(val, undefined))); promises.push(whenDomReady(window.document).then(val => t.is(val, undefined))); Promise.all(promises).then(() => t.end()); } }; jsdom.env(config); });
Test Promise value always resolves to undefined
Test Promise value always resolves to undefined
JavaScript
mit
lukechilds/when-dom-ready
3429aee6bfedfdce9498f73aab55f1039c59190b
examples/dev-kits/main.js
examples/dev-kits/main.js
module.exports = { stories: ['./stories/*.*'], webpack: async (config, { configType }) => ({ ...config, module: { ...config.module, rules: [ ...config.module.rules, { test: /\.(ts|tsx)$/, loader: require.resolve('babel-loader'), options: { presets: [['react-app', { flow: false, typescript: true }]], }, }, ], }, resolve: { ...config.resolve, extensions: [...(config.resolve.extensions || []), '.ts', '.tsx'], }, }), };
module.exports = { stories: ['./stories/*.*'], webpack: async (config, { configType }) => ({ ...config, module: { ...config.module, rules: [ ...config.module.rules, { test: /\.(ts|tsx)$/, loader: require.resolve('babel-loader'), options: { presets: [['react-app', { flow: false, typescript: true }]], }, }, ], }, resolve: { ...config.resolve, extensions: [...(config.resolve.extensions || []), '.ts', '.tsx'], }, }), managerWebpack: async config => ({ ...config, module: { ...config.module, rules: [ ...config.module.rules, { test: /manager\.js$/, loader: require.resolve('babel-loader'), options: { presets: [['react-app', { flow: false, typescript: true }]], }, }, ], }, }), };
FIX manager using ESM in dev-kits example
FIX manager using ESM in dev-kits example
JavaScript
mit
storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook
f16f1eae610c1bc78e8b0ebb3aca7bd4b717db19
db/sequelizeConnect.js
db/sequelizeConnect.js
var Sequelize = require('sequelize'), pg = require('pg').native; module.exports = function(opts) { if (!opts.DATABASE_URL) { throw(new Error('Must specify DATABASE_URL in config.json or as environment variable')); } // TODO Support other databases var match = process.env.DATABASE_URL.match(/postgres:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/(.+)/), db = new Sequelize(match[5], match[1], match[2], { dialect: 'postgres', protocol: 'postgres', port: match[4], host: match[3], logging: false, native: true, define: { underscored: true } }); db.authenticate() .error(function(err){ throw(new Error('Cannot connect to postgres db: ' + err)); }) .success(function(){ console.log('Connected to PostgreSQL db'); }); return db; };
var Sequelize = require('sequelize'), pg = require('pg').native; module.exports = function(opts) { if (!opts.DATABASE_URL) { throw(new Error('Must specify DATABASE_URL in config.json or as environment variable')); } // TODO Support other databases var match = opts.DATABASE_URL.match(/postgres:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/(.+)/), db = new Sequelize(match[5], match[1], match[2], { dialect: 'postgres', protocol: 'postgres', port: match[4], host: match[3], logging: false, native: true, define: { underscored: true } }); db.authenticate() .error(function(err){ throw(new Error('Cannot connect to postgres db: ' + err)); }) .success(function(){ console.log('Connected to PostgreSQL db'); }); return db; };
Fix error where DATABASE_URL does not exist in environment
Fix error where DATABASE_URL does not exist in environment
JavaScript
isc
bankonme/ripple-rest,ripple/ripple-rest,dmathewwws/my-ripple-rest,sparro/ripple-rest,lumberj/ripple-rest,xdv/ripple-rest,radr/radr-rest,sparro/ripple-rest,Treefunder/ripple-rest,dmathewwws/my-ripple-rest,hserang/ripple-rest,dmathewwws/my-ripple-rest,dinexcode/ripple-rest-dinex
c971930ec987ae24f392f47c2b1b9b731f0cb4e9
web/app/scripts/services/userservice.js
web/app/scripts/services/userservice.js
'use strict'; /** * @ngdoc service * @name dormManagementToolApp.userService * @description * # userService * Service in the dormManagementToolApp. */ angular.module('dormManagementToolApp') .service('UserService', function () { var mv = this; this.user = JSON.parse(localStorage.getItem('user')); this.getName = function () { return mv.user.name; }; this.getId = function () { return mv.user.id; }; this.getDormId = function () { return mv.user.dorm_id; }; });
'use strict'; /** * @ngdoc service * @name dormManagementToolApp.userService * @description * # userService * Service in the dormManagementToolApp. */ angular.module('dormManagementToolApp') .service('UserService', function () { var mv = this; this.user = JSON.parse(localStorage.getItem('user')); this.getName = function () { if (localStorage.getItem('user')) if (mv.user != null) return mv.user.name; else { mv.user = JSON.parse(localStorage.getItem('user')); return mv.user.name } else return null }; this.getId = function () { if (localStorage.getItem('user')) if (mv.user != null) return mv.user.id; else { mv.user = JSON.parse(localStorage.getItem('user')); return mv.user.id } else return null }; this.getDormId = function () { if (localStorage.getItem('user')) if (mv.user != null) return mv.user.dorm_id; else { mv.user = JSON.parse(localStorage.getItem('user')); return mv.user.dorm_id } else return null }; });
Check whether object exists before retrieving
Check whether object exists before retrieving
JavaScript
mit
TomGijselinck/dorm-management-tool,TomGijselinck/dorm-management-tool,TomGijselinck/dorm-management-tool
e05522cee60dd4d4baaadeee80869f063add486f
src/middleware/parsePayload.js
src/middleware/parsePayload.js
import getRawBody from 'raw-body' export default (limit) => { limit = (limit || '512kb') return (req, res, next) => { // Parse payload into buffer getRawBody(req, { length: req.headers['content-length'], limit, }, function (err, buffer) { if (err) return next(err) if (buffer.length) { req.buffer = buffer return next() } res.writeHead(204) res.end('No binary payload provided.') }) } }
import getRawBody from 'raw-body' export default (limit) => { limit = (limit || '512kb') return (req, res, next) => { // Parse payload into buffer getRawBody(req, { length: req.headers['content-length'], limit, }, function (err, buffer) { if (err) return next(err) if (buffer.length) { req.buffer = buffer return next() } res.writeHead(400) res.end('No binary payload provided.') }) } }
Fix error code for missing payload.
Fix error code for missing payload.
JavaScript
mit
kukua/concava
7f4a80cbc397353af2d89199567a2db12179f9fa
components/widgets/psi/index.js
components/widgets/psi/index.js
import { Component } from 'react' import 'isomorphic-fetch' export default class PageSpeedInsights extends Component { static defaultProps = { filter_third_party_resources: true, locale: 'de_DE', strategy: 'desktop' } state = { score: 0 } async componentDidMount () { let url = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed' url += `?url=${this.props.url}` url += `&filter_third_party_resources=${this.props.filter_third_party_resources}` url += `&locale=${this.props.locale}` url += `&strategy=${this.props.strategy}` const res = await fetch(url) // eslint-disable-line no-undef const json = await res.json() this.setState({ score: json.ruleGroups.SPEED.score }) } render () { return ( <div> <h3>PageSpeed Score</h3> <p>{this.state.score}</p> </div> ) } }
import { Component } from 'react' import 'isomorphic-fetch' import Progress from '../../progress' import Widget from '../../widget' export default class PageSpeedInsights extends Component { static defaultProps = { filter_third_party_resources: true, locale: 'de_DE', strategy: 'desktop' } state = { score: 0 } async componentDidMount () { const { url, filter_third_party_resources, locale, strategy } = this.props let requestUrl = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed' requestUrl += `?url=${url}` // eslint-disable-next-line camelcase requestUrl += `&filter_third_party_resources=${filter_third_party_resources}` requestUrl += `&locale=${locale}` requestUrl += `&strategy=${strategy}` // eslint-disable-next-line no-undef const res = await fetch(requestUrl) const json = await res.json() this.setState({ score: json.ruleGroups.SPEED.score }) } render () { const { score } = this.state return ( <Widget title='PageSpeed Score'> <Progress value={score} /> </Widget> ) } }
Use widget and progress component
Use widget and progress component
JavaScript
mit
danielbayerlein/dashboard,danielbayerlein/dashboard
b1efa119cce7e6d14c7315221282402df6810f85
src/chain.js
src/chain.js
import animate from './animate'; import {assign} from './utils'; const helpers = { delay(msec) { this._opts.delay = msec; return this; }, progress(fn, tween = null) { this._props.tween = tween || this._props.tween || [1, 0]; this._opts.progress = fn; return this; } }; export default function chain(el, props, opts) { const fn = function fn(done) { fn._opts.complete = done; animate(fn._el, fn._props, fn._opts); }; fn._el = el; fn._props = props; fn._opts = opts; assign(fn, helpers); return fn; }
import animate from './animate'; import {assign} from './utils'; const helpers = { delay(msec) { this._opts.delay = msec; return this; }, duration(msec) { this._opts.duration = msec; return this; }, easing(name) { this._opts.easing = name; return this; }, progress(fn, tween = null) { this._props.tween = tween || this._props.tween || [1, 0]; this._opts.progress = fn; return this; }, display(value) { this._opts.display = value; return this; }, visibility(value) { this._opts.visibility = value; return this; }, loop(count) { this._opts.loop = count; return this; } }; export default function chain(el, props, opts) { const fn = function fn(done) { fn._opts.complete = done; animate(fn._el, fn._props, fn._opts); }; fn._el = el; fn._props = props; fn._opts = opts; assign(fn, helpers); return fn; }
Add helper functions to update velocity options
Add helper functions to update velocity options
JavaScript
mit
ktsn/vq
b247bd12cf14b573d098603d948fea9ab3199d2d
groups.js
groups.js
const groupRe = /^((:?\w|\-|,|, )+):\s*/i , reverts = require('./reverts') function toGroups (summary) { summary = reverts.cleanSummary(summary) var m = summary.match(groupRe) return (m && m[1]) || '' } function cleanSummary (summary) { return (summary || '').replace(groupRe, '') } function isReleaseCommit (summary) { return /^Working on v?\d{1,2}\.\d{1,3}\.\d{1,3}$/.test(summary) || /^\d{4}-\d{2}-\d{2},? Version \d{1,2}\.\d{1,3}\.\d{1,3} (["'][A-Za-z ]+["'] )?\((Stable|LTS|Maintenance)\)/.test(summary) || /^\d{4}-\d{2}-\d{2},? io.js v\d{1,2}\.\d{1,3}\.\d{1,3} Release/.test(summary) || /^\d+\.\d+\.\d+$/.test(summary) // `npm version X` style commit } module.exports.toGroups = toGroups module.exports.cleanSummary = cleanSummary module.exports.isReleaseCommit = isReleaseCommit
const groupRe = /^((:?\w|\-|,|, )+):\s*/i , reverts = require('./reverts') function toGroups (summary) { summary = reverts.cleanSummary(summary) var m = summary.match(groupRe) return (m && m[1]) || '' } function cleanSummary (summary) { return (summary || '').replace(groupRe, '') } function isReleaseCommit (summary) { return /^Working on v?\d{1,2}\.\d{1,3}\.\d{1,3}$/.test(summary) || /^\d{4}-\d{2}-\d{2},? Version \d{1,2}\.\d{1,3}\.\d{1,3} (["'][A-Za-z ]+["'] )?\((Current|Stable|LTS|Maintenance)\)/.test(summary) || /^\d{4}-\d{2}-\d{2},? io.js v\d{1,2}\.\d{1,3}\.\d{1,3} Release/.test(summary) || /^\d+\.\d+\.\d+$/.test(summary) // `npm version X` style commit } module.exports.toGroups = toGroups module.exports.cleanSummary = cleanSummary module.exports.isReleaseCommit = isReleaseCommit
Rename Node.js "Stable" releases to "Current"
Rename Node.js "Stable" releases to "Current"
JavaScript
mit
rvagg/changelog-maker
3e2e1baeb0208be9c40d6d208c31792a4cc8e842
src/index.js
src/index.js
require("./stylesheets/main.less"); var settings = require("./settings"); var commands = codebox.require("core/commands"); var manager = new codebox.tabs.Manager({ tabMenu: false }); manager.$el.addClass("component-panels"); // Add tabs to grid codebox.app.grid.addView(manager, { width: 20, at: 0 }); // Render the tabs manager manager.render(); // Toggle panels display commands.register({ id: "view.panels.toggle", title: "View: Toggle Side Bar", run: function() { settings.data.set("visible", !settings.data.get("visible")); codebox.settings.save(); } }); // Update visibility settings.data.on("change:visible", function() { manager._gridOptions.enabled = settings.data.get("visible"); codebox.app.grid.update(); }); // Make the tab manager global codebox.panels = manager;
require("./stylesheets/main.less"); var settings = require("./settings"); var commands = codebox.require("core/commands"); var manager = new codebox.tabs.Manager({ tabMenu: false }); manager.$el.addClass("component-panels"); // Add tabs to grid codebox.app.grid.addView(manager, { width: 20, at: 0 }); // Render the tabs manager manager.render(); // Toggle panels display commands.register({ id: "view.panels.toggle", title: "View: Toggle Side Bar", run: function() { settings.data.set("visible", !settings.data.get("visible")); codebox.settings.save(); } }); // Update visibility settings.data.on("change:visible", function() { manager._gridOptions.enabled = settings.data.get("visible"); codebox.app.grid.update(); }); // Add to View menu if (codebox.menubar) { codebox.menubar.createMenu("view", { caption: "Toggle Side Bar", command: "view.panels.toggle" }); } // Make the tab manager global codebox.panels = manager;
Add command in view menu
Add command in view menu
JavaScript
apache-2.0
etopian/codebox-package-panels,CodeboxIDE/package-panels
eb04bb23e4d5496a8870a810ad201551915d11dd
src/index.js
src/index.js
import 'babel-polyfill'; const window = (typeof window !== 'undefined') ? window : {}; // Default config values. const defaultConfig = { loggingFunction: () => true, loadInWorker: true, // FIXME cambia il nome }; // Config used by the module. const config = {}; // ***** Private functions ***** const formatError = (error = {}) => error; // Public function. const funcExecutor = (funcToCall, args = [], scope = undefined) => { try { funcToCall.apply(scope, ...args); } catch (e) { // TODO trova modo per fare la compose nativa config.loggingFunction(formatError(e)); throw e; } }; // FIXME capire se è permesso avere la window come default const attachGlobalHandler = (scope = window) => { scope.onerror = () => { // TODO trova modo per fare la compose nativa config.loggingFunction(formatError({ ...arguments })); return false; }; }; export default function LogIt(userConfig = defaultConfig) { Object.assign(config, userConfig); return { funcExecutor, attachGlobalHandler, }; }
import 'babel-polyfill'; import Catcher from './catcher'; import Logger from './logger'; // Default config values. const defaultConfig = { scope: (typeof window !== 'undefined') ? window : {}, loggingFunction: () => true, useWorker: true, errorBuffer: 5, }; // Config used by the module. let config = {}; const sendErrorToLogger = formattedError => formattedError; export default function LogIt(userConfig = {}) { // TODO npm i --save-dev babel-preset-stage-2 config = { ...defaultConfig, ...userConfig }; return { ...Catcher, }; }
Move cathing functions to catch file
Move cathing functions to catch file
JavaScript
mit
mattiaocchiuto/log-it
46f2979acf5216df541f0dcc1bbb969cba43aef9
src/index.js
src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import { BrowserRouter, Route } from 'react-router-dom'; import promise from 'redux-promise' import PostsIndex from './components/posts_index'; import PostsNew from './components/posts_new'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware(promise)(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <BrowserRouter> <div> <Route path="/" component={PostsIndex} /> <Route path="/posts/new" component={PostsNew} /> </div> </BrowserRouter> </Provider> , document.querySelector('.container'));
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import { BrowserRouter, Route, Switch } from 'react-router-dom'; import promise from 'redux-promise' import PostsIndex from './components/posts_index'; import PostsNew from './components/posts_new'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware(promise)(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <BrowserRouter> <div> <Switch> <Route path="/posts/new" component={PostsNew} /> <Route path="/" component={PostsIndex} /> </Switch> </div> </BrowserRouter> </Provider> , document.querySelector('.container'));
Fix bug by adding Switch to the routes and more specific routes shown first in code
Fix bug by adding Switch to the routes and more specific routes shown first in code
JavaScript
mit
kevinw123/ReduxBlog,kevinw123/ReduxBlog
5205cc041e05ed01258681d88b438cbe58c464d2
src/index.js
src/index.js
'use strict'; var Promise = require('bluebird'); var sinon = require('sinon'); function thenable (promiseFactory) { return Object.keys(Promise.prototype) .filter(function (method) { return Promise.prototype.hasOwnProperty(method) && method !== 'then'; }) .reduce(function (acc, method) { acc[method] = function () { var args = arguments; var promise = this.then(); return promise[method].apply(promise, args); }; return acc; }, { then: function (resolve, reject) { return promiseFactory().then(resolve, reject); } }); } function resolves (value) { /*jshint validthis:true */ return this.returns(thenable(function () { return new Promise(function (resolve) { resolve(value); }); })); } sinon.stub.resolves = resolves; sinon.behavior.resolves = resolves; function rejects (err) { if (typeof err === 'string') { err = new Error(err); } /*jshint validthis:true */ return this.returns(thenable(function () { return new Promise(function (resolve, reject) { reject(err); }); })); } sinon.stub.rejects = rejects; sinon.behavior.rejects = rejects; module.exports = function (_Promise_) { if (typeof _Promise_ !== 'function') { throw new Error('A Promise constructor must be provided'); } else { Promise = _Promise_; } return sinon; };
'use strict'; var Promise = require('bluebird'); var sinon = require('sinon'); function thenable (promiseFactory) { return Object.getOwnPropertyNames(Promise.prototype) .filter(function (method) { return method !== 'then'; }) .reduce(function (acc, method) { acc[method] = function () { var args = arguments; var promise = this.then(); return promise[method].apply(promise, args); }; return acc; }, { then: function (resolve, reject) { return promiseFactory().then(resolve, reject); } }); } function resolves (value) { /*jshint validthis:true */ return this.returns(thenable(function () { return new Promise(function (resolve) { resolve(value); }); })); } sinon.stub.resolves = resolves; sinon.behavior.resolves = resolves; function rejects (err) { if (typeof err === 'string') { err = new Error(err); } /*jshint validthis:true */ return this.returns(thenable(function () { return new Promise(function (resolve, reject) { reject(err); }); })); } sinon.stub.rejects = rejects; sinon.behavior.rejects = rejects; module.exports = function (_Promise_) { if (typeof _Promise_ !== 'function') { throw new Error('A Promise constructor must be provided'); } else { Promise = _Promise_; } return sinon; };
Use Object.getOwnPropertyNames for compatibility with native promises
Use Object.getOwnPropertyNames for compatibility with native promises
JavaScript
mit
bendrucker/sinon-as-promised,hongkheng/sinon-as-promised
7d7f578ad3d163da121ffdd3d8ee4fd6500da318
src/index.js
src/index.js
function createDynamicFunction(customAction) { return Function('action', 'return function (){ return action.apply(this, [...arguments]) };')(customAction); } function formatFunctionName(type) { let formattedName = ''; function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } type.split('_').map((val, i) => { if (i === 0) { formattedName += val.toLowerCase(); } else { formattedName += capitalizeFirstLetter(val.toLowerCase()); } return true; }); return formattedName; } function generalFactory(type, payloadTranslator) { return function nomeDaSostituire(data) { const action = { type, }; if (data) { switch (typeof payloadTranslator) { case 'function': action.payload = payloadTranslator(data); break; default: action.payload = data; break; } } return action; }; } module.exports = function actionsCreatorFactory(actionsConfig) { const funcToExport = {}; actionsConfig.map((config) => { let type = null; let payload = null; if (typeof config === 'string') { type = config; } else { type = config.type; payload = config.payload; } const functionName = formatFunctionName(type); const customFunction = generalFactory(type, payload); const customStringFunction = createDynamicFunction(customFunction); funcToExport[functionName] = customStringFunction; return true; }); return funcToExport; };
function formatFunctionName(type) { let formattedName = ''; function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } type.split('_').map((val, i) => { if (i === 0) { formattedName += val.toLowerCase(); } else { formattedName += capitalizeFirstLetter(val.toLowerCase()); } return true; }); return formattedName; } function generalFactory(type, payloadTranslator) { return function nomeDaSostituire(data) { const action = { type, }; if (data) { switch (typeof payloadTranslator) { case 'function': action.payload = payloadTranslator(data); break; default: action.payload = data; break; } } return action; }; } module.exports = function actionsCreatorFactory(actionsConfig) { const funcToExport = {}; actionsConfig.map((config) => { let type = null; let payload = null; if (typeof config === 'string') { type = config; } else { type = config.type; payload = config.payload; } const functionName = formatFunctionName(type); const customFunction = generalFactory(type, payload); const customStringFunction = customFunction; funcToExport[functionName] = customStringFunction; return true; }); return funcToExport; };
Remove not useful function creator
Remove not useful function creator
JavaScript
mit
mattiaocchiuto/actions-creator-factory
f406e16d6084c38a714fa532f93eccffe1a826b1
js/simple_lottery.js
js/simple_lottery.js
let possibilites = 1; for (let i = 53; i >= 48; i--) { possibilites *= i; } console.log('The odds are %d to 1', possibilites);
let possibilites = 1; for (let i = 53; i >= 48; i--) { possibilites *= i; } console.log('The odds are %d to 1', possibilites);
Use standard JS indent width
Use standard JS indent width
JavaScript
mit
rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/ple
25ed756722fb765e3900d8b409b2b09a592fd310
src/timer.js
src/timer.js
var Timer = (function(Event, Util) { 'use strict'; // Internal constants for the various timer states. var Waiting = 0, Inspecting = 1, Ready = 2, Running = 3, Stopped = 4; var state = Waiting; var startTime = undefined, endTime = undefined, solveTime = undefined; var intervalID = undefined; function isWaiting() { return state === Waiting; } function isReady() { return state === Ready; } function isRunning() { return state === Running; } function onWaiting() { endTime = undefined; } function onRunning() { startTime = Util.getMilli(); intervalID = Util.setInterval(runningEmitter, 100); } function onStopped() { endTime = Util.getMilli(); Util.clearInterval(intervalID); setState(Waiting); } function setState(new_state) { state = new_state; switch(state) { case Waiting: onWaiting(); break; case Running: onRunning(); break; case Stopped: onStopped(); break; } } function runningEmitter() { Event.emit("timer/running"); } function triggerDown() { if (isWaiting()) { setState(Ready); } else if (isRunning()) { setState(Stopped); } } function triggerUp() { if (isReady()) { setState(Running); } } function getCurrent() { return (endTime || Util.getMilli()) - startTime; } return { triggerDown: triggerDown, triggerUp: triggerUp, getCurrent: getCurrent }; }); if (typeof module !== 'undefined') module.exports = Timer;
var Timer = (function(Event, Util) { 'use strict'; // Internal constants for the various timer states. var Waiting = 0, Inspecting = 1, Ready = 2, Running = 3, Stopped = 4; var state = Waiting; var startTime, endTime, solveTime; var intervalID; function isWaiting() { return state === Waiting; } function isReady() { return state === Ready; } function isRunning() { return state === Running; } function onWaiting() { endTime = undefined; } function onRunning() { startTime = Util.getMilli(); intervalID = Util.setInterval(runningEmitter, 100); } function onStopped() { endTime = Util.getMilli(); Util.clearInterval(intervalID); setState(Waiting); } function setState(new_state) { state = new_state; switch(state) { case Waiting: onWaiting(); break; case Running: onRunning(); break; case Stopped: onStopped(); break; } } function runningEmitter() { Event.emit("timer/running"); } function triggerDown() { if (isWaiting()) { setState(Ready); } else if (isRunning()) { setState(Stopped); } } function triggerUp() { if (isReady()) { setState(Running); } } function getCurrent() { return (endTime || Util.getMilli()) - startTime; } return { triggerDown: triggerDown, triggerUp: triggerUp, getCurrent: getCurrent }; }); if (typeof module !== 'undefined') module.exports = Timer;
Remove explicit assignment to undefined.
Remove explicit assignment to undefined. jshint complains about these.
JavaScript
mit
jjtimer/jjtimer-core
b4ded385e4cc520cc90ef46d3491ff0927d6ada8
package/environments/development.js
package/environments/development.js
const Environment = require('../environment') const { dev_server } = require('../config') const assetHost = require('../asset_host') const webpack = require('webpack') module.exports = class extends Environment { constructor() { super() if (dev_server.hmr) { this.plugins.set('HotModuleReplacement', new webpack.HotModuleReplacementPlugin()) this.plugins.set('NamedModules', new webpack.NamedModulesPlugin()) } } toWebpackConfig() { const result = super.toWebpackConfig() if (dev_server.hmr) { result.output.filename = '[name]-[hash].js' } result.output.pathinfo = true result.devtool = 'cheap-eval-source-map' result.devServer = { host: dev_server.host, port: dev_server.port, https: dev_server.https, hot: dev_server.hmr, contentBase: assetHost.path, publicPath: assetHost.publicPath, clientLogLevel: 'none', compress: true, historyApiFallback: true, headers: { 'Access-Control-Allow-Origin': '*' }, watchOptions: { ignored: /node_modules/ }, stats: { errorDetails: true } } return result } }
const Environment = require('../environment') const { dev_server } = require('../config') const assetHost = require('../asset_host') const webpack = require('webpack') module.exports = class extends Environment { constructor() { super() if (dev_server.hmr) { this.plugins.set('HotModuleReplacement', new webpack.HotModuleReplacementPlugin()) this.plugins.set('NamedModules', new webpack.NamedModulesPlugin()) } } toWebpackConfig() { const result = super.toWebpackConfig() if (dev_server.hmr) { result.output.filename = '[name]-[hash].js' } result.output.pathinfo = true result.devtool = 'cheap-eval-source-map' result.devServer = { host: dev_server.host, port: dev_server.port, https: dev_server.https, hot: dev_server.hmr, contentBase: assetHost.path, publicPath: assetHost.publicPath, clientLogLevel: 'none', compress: true, historyApiFallback: true, headers: { 'Access-Control-Allow-Origin': '*' }, overlay: true, watchContentBase: true, watchOptions: { ignored: /node_modules/ }, stats: { errorDetails: true } } return result } }
Add overlay option for debugging
Add overlay option for debugging
JavaScript
mit
rails/webpacker,usertesting/webpacker,gauravtiwari/webpacker,rails/webpacker,usertesting/webpacker,rossta/webpacker,rossta/webpacker,usertesting/webpacker,rossta/webpacker,rossta/webpacker,gauravtiwari/webpacker,gauravtiwari/webpacker
8dc057b796b34150de611314f27800da70df690a
src/tizen/SplashScreenProxy.js
src/tizen/SplashScreenProxy.js
var exec = require('cordova/exec'); module.exports = { splashscreen: { win: null, show: function() { win= window.open('splashscreen.html'); }, hide: function() { win.close(); win = null; } } }; require("cordova/tizen/commandProxy").add("SplashScreen", module.exports);
( function() { win = null; module.exports = { show: function() { if ( win === null ) { win = window.open('splashscreen.html'); } }, hide: function() { if ( win !== null ) { win.close(); win = null; } } }; require("cordova/tizen/commandProxy").add("SplashScreen", module.exports); })();
Correct structure, and only ever create one splashscreen window.
Proxy: Correct structure, and only ever create one splashscreen window.
JavaScript
apache-2.0
Panajev/cordova-plugin-splashscreen,editweb/cordova-plugin-splashscreen,Newstex/cordova-plugin-splashscreen,polyvi/cordova-plugin-splashscreen,Seedstars/cordova-plugin-splashscreen,polyvi/cordova-plugin-splashscreen,corimf/cordova-plugin-splashscreen,petermetz/cordova-plugin-splashscreen,IWAtech/cordova-plugin-splashscreen,caseywebdev/cordova-plugin-splashscreen,purplecabbage/cordova-plugin-splashscreen,Seedstars/cordova-plugin-splashscreen,asiFarran/cordova-plugin-splashscreen,kitmaxdevelop/cordova-plugin-splashscreen,Panajev/cordova-plugin-splashscreen,hebert-nr/spin,petermetz/cordova-plugin-splashscreen,sportstech/cordova-plugin-splashscreen,dpolivy/cordova-plugin-splashscreen,hebert-nr/spin,hebert-nr/spin,petermetz/cordova-plugin-splashscreen,journeyapps/cordova-splashscreen,bamlab/cordova-plugin-splashscreen,Panajev/cordova-plugin-splashscreen,Panajev/cordova-plugin-splashscreen,dpolivy/cordova-plugin-splashscreen,caseywebdev/cordova-plugin-splashscreen,polyvi/cordova-plugin-splashscreen,blackberry-webworks/cordova-plugin-splashscreen,revolunet/cordova-plugin-splashscreen,blackberry-webworks/cordova-plugin-splashscreen,apache/cordova-plugin-splashscreen,Icenium/cordova-plugin-splashscreen,asiFarran/cordova-plugin-splashscreen,jfrumar/cordova-plugin-splashscreen,sportstech/cordova-plugin-splashscreen,Choppel/cordova-plugin-splashscreen,kitmaxdevelop/cordova-plugin-splashscreen,kitmaxdevelop/cordova-plugin-splashscreen,bamlab/cordova-plugin-splashscreen,purplecabbage/cordova-plugin-splashscreen,blackberry-webworks/cordova-plugin-splashscreen,asiFarran/cordova-plugin-splashscreen,Newstex/cordova-plugin-splashscreen,Icenium/cordova-plugin-splashscreen,purplecabbage/cordova-plugin-splashscreen,caseywebdev/cordova-plugin-splashscreen,chrskrchr/cordova-plugin-splashscreen,journeyapps/cordova-splashscreen,corimf/cordova-plugin-splashscreen,jfrumar/cordova-plugin-splashscreen,dpolivy/cordova-plugin-splashscreen,Seedstars/cordova-plugin-splashscreen,blackberry-webworks/cordova-plugin-splashscreen,purplecabbage/cordova-plugin-splashscreen,editweb/cordova-plugin-splashscreen,dpolivy/cordova-plugin-splashscreen,IWAtech/cordova-plugin-splashscreen,jfrumar/cordova-plugin-splashscreen,journeyapps/cordova-splashscreen,Choppel/cordova-plugin-splashscreen,kitmaxdevelop/cordova-plugin-splashscreen,journeyapps/cordova-splashscreen,Icenium/cordova-plugin-splashscreen,corimf/cordova-plugin-splashscreen,Lazza/cordova-plugin-splashscreen,caseywebdev/cordova-plugin-splashscreen,Seedstars/cordova-plugin-splashscreen,Lazza/cordova-plugin-splashscreen,chrskrchr/cordova-plugin-splashscreen,revolunet/cordova-plugin-splashscreen,IWAtech/cordova-plugin-splashscreen,petermetz/cordova-plugin-splashscreen,editweb/cordova-plugin-splashscreen,Newstex/cordova-plugin-splashscreen,corimf/cordova-plugin-splashscreen,editweb/cordova-plugin-splashscreen,hebert-nr/spin,bamlab/cordova-plugin-splashscreen,Choppel/cordova-plugin-splashscreen,Icenium/cordova-plugin-splashscreen,chrskrchr/cordova-plugin-splashscreen,jfrumar/cordova-plugin-splashscreen,chrskrchr/cordova-plugin-splashscreen,Lazza/cordova-plugin-splashscreen,Newstex/cordova-plugin-splashscreen,IWAtech/cordova-plugin-splashscreen,revolunet/cordova-plugin-splashscreen,Choppel/cordova-plugin-splashscreen,polyvi/cordova-plugin-splashscreen,asiFarran/cordova-plugin-splashscreen,hebert-nr/spin,Lazza/cordova-plugin-splashscreen,bamlab/cordova-plugin-splashscreen,revolunet/cordova-plugin-splashscreen,sportstech/cordova-plugin-splashscreen,sportstech/cordova-plugin-splashscreen
69a0f5204ff7132e244e2866f69f3f7375e19318
app/assets/javascripts/application.js
app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require_tree . //= require bootstrap // Replace link targets with JavaScript handlers to prevent iOS fullscreen web // app from opening links in extra browser app if (navigator.userAgent.match(/(ipod|iphone|ipad)/i)) { $(function() { $('body a[href]').click(function(e) { e.preventDefault(); top.location.href = this; }); }); }
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require_tree . //= require bootstrap // Replace link targets with JavaScript handlers to prevent iOS fullscreen web // app from opening links in extra browser app if (navigator.userAgent.match(/(ipod|iphone|ipad)/i)) { $(function() { $('body a[href]').click(function(e) { e.preventDefault(); top.location.href = this; }); }); } //hide notification bars after a few seconds $('.alert').delay(10000).fadeOut('slow');
Hide notification bars after a few seconds.
Hide notification bars after a few seconds. Former-commit-id: 8dc17c173ff496666879f82c6544e0826d8d36f5
JavaScript
mit
chaosdorf/mete,chaosdorf/mete,YtvwlD/mete,YtvwlD/mete,YtvwlD/mete,chaosdorf/mete,chaosdorf/mete,YtvwlD/mete
e69b09323f232fe2982ca8e764b432dbf39457c2
web/static/js/app.js
web/static/js/app.js
/* VENDOR */ require( "material-design-lite" ); /* APPLICATION */ const { initTerms } = require( "./term.js" ); initTerms();
/* VENDOR */ require( "material-design-lite" ); import "phoenix_html" /* APPLICATION */ const { initTerms } = require( "./term.js" ); initTerms();
Add import of phoenix_html back
Add import of phoenix_html back Without this import the delete links stopped working
JavaScript
mit
digitalnatives/course_planner,digitalnatives/course_planner,digitalnatives/course_planner
e0a369fec549498071504e19070bfdd69c49478b
packages/react-jsx-highcharts/src/components/PlotBandLine/UsePlotBandLineLifecycle.js
packages/react-jsx-highcharts/src/components/PlotBandLine/UsePlotBandLineLifecycle.js
import React, { useRef, useEffect, useState } from 'react'; import uuid from 'uuid/v4'; import { attempt } from 'lodash-es'; import useModifiedProps from '../UseModifiedProps'; import useAxis from '../UseAxis'; export default function usePlotBandLineLifecycle(props, plotType) { const { id = uuid, axisId, children, ...rest } = props; const axis = useAxis(axisId); const idRef = useRef(); const [plotbandline, setPlotbandline] = useState(null); const modifiedProps = useModifiedProps(rest); useEffect(() => { if (!axis) return; if (!plotbandline || modifiedProps !== false) { if (!plotbandline) { idRef.current = typeof id === 'function' ? id() : id; } const myId = idRef.current; const opts = { id: myId, ...rest }; if (plotbandline) axis.removePlotBandOrLine(idRef.current); axis.addPlotBandOrLine(opts, plotType); setPlotbandline({ id: myId, getPlotBandLine: () => { const plotbandlineObject = axis.object.plotLinesAndBands.find( plb => plb.id === myId ); return plotbandlineObject; } }); } }); useEffect(() => { return () => { attempt(axis.removePlotBandOrLine, idRef.current); }; }, []); return plotbandline; }
import React, { useRef, useEffect, useState } from 'react'; import uuid from 'uuid/v4'; import { attempt } from 'lodash-es'; import useModifiedProps from '../UseModifiedProps'; import useAxis from '../UseAxis'; export default function usePlotBandLineLifecycle(props, plotType) { const { id = uuid, axisId, children, ...rest } = props; const axis = useAxis(axisId); const idRef = useRef(); const [plotbandline, setPlotbandline] = useState(null); const modifiedProps = useModifiedProps(rest); useEffect(() => { if (!axis) return; if (!plotbandline || modifiedProps !== false) { if (!plotbandline) { idRef.current = typeof id === 'function' ? id() : id; } const myId = idRef.current; const opts = { id: myId, ...rest }; if (plotbandline) axis.removePlotBandOrLine(idRef.current); axis.addPlotBandOrLine(opts, plotType); setPlotbandline({ id: myId, getPlotBandLine: () => { if (axis && axis.object && axis.object.plotLinesAndBands) { const plotbandlineObject = axis.object.plotLinesAndBands.find( plb => plb.id === myId ); return plotbandlineObject; } } }); } }); useEffect(() => { return () => { attempt(axis.removePlotBandOrLine, idRef.current); }; }, []); return plotbandline; }
Fix plotband label unmount crashing
Fix plotband label unmount crashing
JavaScript
mit
whawker/react-jsx-highcharts,whawker/react-jsx-highcharts
3abec636fa6b84f8813855cbfca5c03cbbd8f9b7
src/helper.js
src/helper.js
var fs = require("fs"); var path = require("path"); var Helper = module.exports = { getConfig: function () { var filename = process.env.SHOUT_CONFIG; if(!filename || !fs.exists(filename)) { filename = this.resolveHomePath("config.js"); if(!fs.exists(filename)) { filename = path.resolve(__dirname, "..", "config"); } } return require(filename); }, getHomeDirectory: function () { return ( (process.env.SHOUT_CONFIG && fs.exists(process.env.SHOUT_CONFIG) && this.getConfig().home) || process.env.SHOUT_HOME || path.resolve(process.env.HOME, ".shout") ); }, resolveHomePath: function () { var fragments = [ Helper.HOME ].concat([].slice.apply(arguments)); return path.resolve.apply(path, fragments); } }; Helper.HOME = Helper.getHomeDirectory()
var fs = require("fs"); var path = require("path"); var Helper = module.exports = { getConfig: function () { var filename = process.env.SHOUT_CONFIG; if(!filename || !fs.existsSync(filename)) { filename = this.resolveHomePath("config.js"); if(!fs.existsSync(filename)) { filename = path.resolve(__dirname, "..", "config"); } } return require(filename); }, getHomeDirectory: function () { return ( (process.env.SHOUT_CONFIG && fs.existsSync(process.env.SHOUT_CONFIG) && this.getConfig().home) || process.env.SHOUT_HOME || path.resolve(process.env.HOME, ".shout") ); }, resolveHomePath: function () { var fragments = [ Helper.HOME ].concat([].slice.apply(arguments)); return path.resolve.apply(path, fragments); } }; Helper.HOME = Helper.getHomeDirectory()
Fix fs.exists to existsSync where necessary
Fix fs.exists to existsSync where necessary
JavaScript
mit
FryDay/lounge,realies/lounge,erming/shout,nickel715/shout,harishanand95/shout_irc_bouncer_openshift,rockhouse/lounge,cha2maru/shout,astorije/shout,metsjeesus/lounge,williamboman/shout,sebastiencs/lounge,williamboman/lounge,williamboman/lounge,thelounge/lounge,ScoutLink/lounge,metsjeesus/lounge,astorije/shout,olivierlambert/shout,libertysoft3/lounge-autoconnect,busseyl/shout,karen-irc/karen,run-project/shout,MaxLeiter/lounge,FryDay/lounge,ScoutLink/lounge,williamboman/lounge,Audio/shout,ScoutLink/lounge,MaxLeiter/shout,rockhouse/lounge,realies/lounge,harishanand95/shout_irc_bouncer_openshift,erming/shout,run-project/shout,FryDay/lounge,MaxLeiter/shout,metsjeesus/lounge,rockhouse/lounge,busseyl/shout,libertysoft3/lounge-autoconnect,cha2maru/shout,diddledan/shout,MaxLeiter/lounge,williamboman/shout,floogulinc/Shuo,togusafish/floogulinc-_-Shuo,MaxLeiter/lounge,Calinou/shout,diddledan/shout,togusafish/floogulinc-_-Shuo,nickel715/shout,Audio/shout,floogulinc/Shuo,sebastiencs/lounge,olivierlambert/shout,sebastiencs/lounge,thelounge/lounge,realies/lounge,libertysoft3/lounge-autoconnect,karen-irc/karen,Calinou/shout
aa323b4dbd0a372c02db1e63757c8127226fcabb
example/future/src/channelTitleEditor/render.js
example/future/src/channelTitleEditor/render.js
module.exports = (model, dispatch) => { const root = document.createElement('div'); if (model.channelOnEdit === null) { return root; } const c = model.channelOnEdit; const title = model.channels[c].title; const row = document.createElement('div'); row.classList.add('row'); row.classList.add('row-input'); const form = document.createElement('form'); const text = document.createElement('input'); text.type = 'text'; text.value = title; form.appendChild(text); const okBtn = document.createElement('button'); okBtn.innerHTML = 'OK'; okBtn.addEventListener('click', ev => { dispatch({ type: 'EDIT_CHANNEL_TITLE', channel: c, title: text.value }); }); form.appendChild(okBtn); row.appendChild(form); root.appendChild(row); return root; }
module.exports = (model, dispatch) => { const root = document.createElement('div'); if (model.channelOnEdit === null) { return root; } const c = model.channelOnEdit; const title = model.channels[c].title; const row = document.createElement('div'); row.classList.add('row'); row.classList.add('row-input'); const form = document.createElement('form'); const text = document.createElement('input'); text.type = 'text'; text.value = title; form.appendChild(text); const okBtn = document.createElement('button'); okBtn.type = 'button'; okBtn.innerHTML = 'OK'; form.appendChild(okBtn); row.appendChild(form); root.appendChild(row); // Events setTimeout(() => { text.focus(); }, 200); form.addEventListener('submit', ev => { ev.preventDefault(); dispatch({ type: 'EDIT_CHANNEL_TITLE', channel: c, title: text.value }); }); okBtn.addEventListener('click', ev => { dispatch({ type: 'EDIT_CHANNEL_TITLE', channel: c, title: text.value }); }); return root; }
Enable form submit by pressing enter
Enable form submit by pressing enter
JavaScript
mit
axelpale/lately,axelpale/lately
fddf6e7c054bbf2786dce7a559914b923eecd835
lib/client/kadira.js
lib/client/kadira.js
Kadira = {}; Kadira.options = __meteor_runtime_config__.kadira; if(Kadira.options && Kadira.options.endpoint) { Kadira.syncedDate = new Ntp(Kadira.options.endpoint); Kadira.syncedDate.sync(); } /** * Send error metrics/traces to kadira server * @param {Object} payload Contains browser info and error traces */ Kadira.sendErrors = function (errors) { var retryCount = 0; var endpoint = Kadira.options.endpoint + '/errors'; var retry = new Retry({ minCount: 0, baseTimeout: 1000*5, maxTimeout: 1000*60, }); var payload = { errors: JSON.stringify(errors) }; tryToSend(); function tryToSend() { if(retryCount < 5) { retry.retryLater(retryCount++, sendPayload); } else { console.warn('Error sending error traces to kadira server'); } } function sendPayload () { $.ajax({ url: endpoint, data: payload, crossDomain: true, error: tryToSend }); } } Kadira.getBrowserInfo = function () { return { browser: window.navigator.userAgent, userId: Meteor.userId, url: location.href }; }
Kadira = {}; Kadira.options = __meteor_runtime_config__.kadira; if(Kadira.options && Kadira.options.endpoint) { Kadira.syncedDate = new Ntp(Kadira.options.endpoint); Kadira.syncedDate.sync(); } /** * Send error metrics/traces to kadira server * @param {Object} payload Contains browser info and error traces */ Kadira.sendErrors = function (errors) { var retryCount = 0; var endpoint = Kadira.options.endpoint + '/errors'; var retry = new Retry({ minCount: 0, baseTimeout: 1000*5, maxTimeout: 1000*60, }); var payload = { errors: JSON.stringify(errors) }; tryToSend(); function tryToSend() { if(retryCount < 5) { retry.retryLater(retryCount++, sendPayload); } else { console.warn('Error sending error traces to kadira server'); } } function sendPayload () { $.ajax({ url: endpoint, data: payload, jsonp: 'callback', dataType: 'jsonp', error: tryToSend }); } } Kadira.getBrowserInfo = function () { return { browser: window.navigator.userAgent, userId: Meteor.userId, url: location.href }; }
Send data using jsonp instead of cors
Send data using jsonp instead of cors
JavaScript
mit
chatr/kadira,meteorhacks/kadira
e34bb65b3c79fb9fd0a6c83b6bc360211493269a
test/spec.js
test/spec.js
var chai = require('chai'), expect = chai.expect; describe('the program', function () { it('can handle the truth', function () { expect(true).to.equal(true); }); });
const {expect} = require('chai'); describe('the program', function () { it('can handle the truth', function () { expect(true).to.equal(true); }); });
Rewrite require to ES6 destructuring
Rewrite require to ES6 destructuring
JavaScript
mit
c089/kata-setup-js
2c7128c4852f441ae759d2951ad21e15e45ce4eb
tests/acceptance/test.setup.js
tests/acceptance/test.setup.js
import React from 'react'; import ReactDOM from 'react-dom'; import App from './app.setup.js'; import $ from 'jquery'; export default function setup() { const component = ReactDOM.render(<App />, document.getElementById('test-area')); const $component = $(ReactDOM.findDOMNode(component)); return $component; }
import React from 'react'; import ReactDOM from 'react-dom'; import App from './app.setup.js'; import $ from 'jquery'; export default function setup() { const component = ReactDOM.render(<App />, document.getElementById('test-area')); const $component = $(ReactDOM.findDOMNode(component)); return $component; } afterEach(function() { ReactDOM.unmountComponentAtNode(document.getElementById('test-area')); });
Clean up the DOM between tests
Clean up the DOM between tests
JavaScript
mit
NiGhTTraX/react-test-buffet,NiGhTTraX/react-test-buffet,NiGhTTraX/react-test-buffet
9fcdd11aae9226aadc1ce30b58c3045b03d20f27
app/components/PlayerScoreComponent.js
app/components/PlayerScoreComponent.js
import React from 'react'; import styles from "../css/App.css"; export class PlayerScoreComponent extends React.Component { /** * Constructor * @param props */ constructor(props) { super(props); this.state = { score: 0 } } updateScore = () => { let score = parseInt(this.refs.score.value); if (Number.isInteger(score)) { this.setState({score: this.state.score + score}); } }; render() { return ( <div key={Math.random()}> <div className={styles["user-score"] + " input-group"}> <input type="number" className="form-control" ref="score" /> <span className="input-group-btn"> <button className="btn btn-default" type="button" onClick={score => this.updateScore()}>{this.props.player.name} - {this.state.score}</button> </span> </div> </div> ); } }
import React from 'react'; import styles from "../css/App.css"; export class PlayerScoreComponent extends React.Component { /** * Constructor * @param props */ constructor(props) { super(props); this.state = { score: 0, history: [] } } updateScore = () => { let score = parseInt(this.refs.score.value); if (Number.isInteger(score)) { this.setState({score: this.state.score + score}); let history = this.state.history; history.push(score); this.setState({history: history}); } }; undo = () => { let lastValue = this.state.history.slice(-1)[0]; if (Number.isInteger(parseInt(lastValue))) { this.state.history.pop(); this.setState({score: this.state.score - lastValue}); } } render() { return ( <div key={Math.random()}> <div className={styles["user-score"] + " input-group"}> <span className="input-group-btn"> <button className="btn btn-warning" type="button" onClick={score => this.undo()}>Undo</button> </span> <input type="number" className="form-control" ref="score" /> <span className="input-group-btn"> <button className="btn btn-success" type="button" onClick={score => this.updateScore()}>{this.props.player.name} - {this.state.score}</button> </span> </div> </div> ); } }
Undo functionality. In case you typed the wrong number...
Undo functionality. In case you typed the wrong number...
JavaScript
mit
AdrGeorgescu/claim,AdrGeorgescu/claim
49d328595b5f2ffc1a1e9e308a2bbb7395ca17b4
objects/isObject/isObject.js
objects/isObject/isObject.js
/** * Checks if "value" is the language type of "Object". * @param {*} value The value to check. * @returns {boolean} Returns true if "value" is an object, else false. */ function isObject(value) { var type = typeof value; return value && (type === 'function' || type === 'object' || false); }
/** * Checks if "value" is the language type of "Object". * @param {*} value The value to check. * @returns {boolean} Returns true if "value" is an object, else false. */ function isObject(value) { var type = typeof value; return !!value && (type === 'function' || type === 'object' || false); }
Fix return value for undefined parameter
Fix return value for undefined parameter
JavaScript
mit
georapbox/smallsJS,georapbox/smallsJS,georapbox/jsEssentials
09cbef1ae2eab9030c311970f1f139bb46502388
packages/lesswrong/server/migrations/2019-05-09-denormalizeReadStatus.js
packages/lesswrong/server/migrations/2019-05-09-denormalizeReadStatus.js
import { registerMigration } from './migrationUtils'; import { forEachDocumentBatchInCollection } from '../queryUtil.js'; import { LWEvents } from '../../lib/collections/lwevents' import { ReadStatuses } from '../../lib/collections/readStatus' registerMigration({ name: "denormalizeReadStatus", idempotent: true, action: async () => { forEachDocumentBatchInCollection({ collection: LWEvents, batchSize: 10000, filter: {name: "post-view"}, callback: (postViews) => { const updates = postViews.map(view => ({ updateOne: { filter: { postId: view.docmentId, userId: view.userId, }, update: { $max: { lastUpdated: view.createdAt, }, $set: { isRead: true }, }, upsert: true, } })); ReadStatuses.rawCollection().bulkWrite(updates); } }) } });
import { registerMigration } from './migrationUtils'; import { forEachDocumentBatchInCollection } from '../queryUtil.js'; import { LWEvents } from '../../lib/collections/lwevents' import { ReadStatuses } from '../../lib/collections/readStatus/collection.js' registerMigration({ name: "denormalizeReadStatus", idempotent: true, action: async () => { forEachDocumentBatchInCollection({ collection: LWEvents, batchSize: 10000, filter: {name: "post-view"}, callback: (postViews) => { const updates = postViews.map(view => ({ updateOne: { filter: { postId: view.docmentId, userId: view.userId, }, update: { $max: { lastUpdated: view.createdAt, }, $set: { isRead: true }, }, upsert: true, } })); ReadStatuses.rawCollection().bulkWrite(updates); } }) } });
Fix broken import in migraiton script
Fix broken import in migraiton script
JavaScript
mit
Discordius/Telescope,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Lesswrong2
9f1d694c16cb4a0c56440b55dc20368f3b23dfbc
core/cb.project/nodejs/index.js
core/cb.project/nodejs/index.js
var path = require("path"); module.exports = { id: "nodejs", name: "Node.JS", detector: path.resolve(__dirname, "detector.sh"), runner: [ { id: "run", script: path.resolve(__dirname, "run.sh") } ], ignoreRules: [ "/node_modules" ] };
var path = require("path"); module.exports = { id: "nodejs", name: "Node.JS", detector: path.resolve(__dirname, "detector.sh"), runner: [ { name: "npm start", id: "run", script: path.resolve(__dirname, "run.sh") } ], ignoreRules: [ "/node_modules" ] };
Change name for default node.js runner
Change name for default node.js runner
JavaScript
apache-2.0
LogeshEswar/codebox,quietdog/codebox,nobutakaoshiro/codebox,fly19890211/codebox,listepo/codebox,rajthilakmca/codebox,rodrigues-daniel/codebox,fly19890211/codebox,blubrackets/codebox,quietdog/codebox,ronoaldo/codebox,Ckai1991/codebox,etopian/codebox,indykish/codebox,code-box/codebox,kustomzone/codebox,etopian/codebox,listepo/codebox,rajthilakmca/codebox,indykish/codebox,kustomzone/codebox,CodeboxIDE/codebox,nobutakaoshiro/codebox,lcamilo15/codebox,Ckai1991/codebox,blubrackets/codebox,smallbal/codebox,rodrigues-daniel/codebox,smallbal/codebox,ahmadassaf/Codebox,code-box/codebox,LogeshEswar/codebox,ronoaldo/codebox,lcamilo15/codebox,CodeboxIDE/codebox,ahmadassaf/Codebox
b9478a6221ab986044e4ea5f74ce9713c20bf398
lib/providers/persistence-provider.js
lib/providers/persistence-provider.js
const NotificationBuilder = require('./notification/notification-builder'); class PersistenceProvider { constructor(bridge) { this.toSave = []; this.bridge = bridge; this.toProcessAction = []; this.publications = []; this.fetches = []; } save(obj) { this.toSave.push(obj); } processAction(obj, action) { this.toProcessAction.push({ target: obj, action: action }); } createFetchRequest() { let [type, apiVersion, uid] = Array.prototype.slice.call(arguments); return this.bridge.newFetchRequest(type, apiVersion, uid); } publishOutbound() { if (!arguments.length) { return new NotificationBuilder((publication) => { this.publications.push(publication); }); } else if (arguments.length === 1) { throw new TypeError('Single parameter publishOutbound function is not supported at this time.'); } else if (arguments.length === 2) { this.publications.push({ target: arguments[0], topic: arguments[1] }); } else { throw new TypeError('Unsupported parameters used in publishOutbound function. Please check persistenceProvider API.'); } } getSaves() { return this.toSave.slice(); } getActionsToProcess() { return this.toProcessAction.slice(); } getPublications() { return this.publications.slice(); } reset() { this.toSave = []; this.toProcessAction = []; this.publications = []; } } module.exports = PersistenceProvider;
const NotificationBuilder = require('./notification/notification-builder'); class PersistenceProvider { constructor(bridge) { this.toSave = []; this.bridge = bridge; this.toProcessAction = []; this.publications = []; this.fetches = []; this.toSave = []; } save(obj) { this.toSave.push(obj); } processAction(obj, action) { this.toProcessAction.push({ target: obj, action: action }); } createFetchRequest() { let [type, apiVersion, uid] = Array.prototype.slice.call(arguments); return this.bridge.newFetchRequest(type, apiVersion, uid); } publishOutbound() { if (!arguments.length) { return new NotificationBuilder((publication) => { this.publications.push(publication); }); } else if (arguments.length === 1) { throw new TypeError('Single parameter publishOutbound function is not supported at this time.'); } else if (arguments.length === 2) { this.publications.push({ target: arguments[0], topic: arguments[1] }); } else { throw new TypeError('Unsupported parameters used in publishOutbound function. Please check persistenceProvider API.'); } } getSaves() { return this.toSave.slice(); } getActionsToProcess() { return this.toProcessAction.slice(); } getPublications() { return this.publications.slice(); } reset() { this.toSave = []; this.toProcessAction = []; this.publications = []; } } module.exports = PersistenceProvider;
Fix bad refactor on PersistenceProvider
Fix bad refactor on PersistenceProvider
JavaScript
mit
AppXpress/axus,AppXpress/axus
6c0d35d8a6466ac0f5b0d3d3db063fe0d2446984
features/unique/support/unique.fixture.js
features/unique/support/unique.fixture.js
/** * Dependencies */ var Waterline = require('waterline'); module.exports = Waterline.Collection.extend({ identity: 'unique', tableName: 'uniqueTable', connection: 'uniqueConn', primaryKey: 'id', attributes: { name: { type: 'string', autoMigrations: { columnType: 'varchar' } }, email: { type: 'string', autoMigrations: { unique: true, columnType: 'varchar' } }, type: { type: 'string', autoMigrations: { columnType: 'varchar' } }, id: { type: 'number', autoMigrations: { autoIncrement: true, columnType: 'integer' } } } });
/** * Dependencies */ var Waterline = require('waterline'); module.exports = Waterline.Collection.extend({ identity: 'unique', tableName: 'uniqueTable', connection: 'uniqueConn', primaryKey: 'id', attributes: { name: { type: 'string', autoMigrations: { columnType: 'varchar' } }, email: { type: 'string', required: true, autoMigrations: { unique: true, columnType: 'varchar' } }, type: { type: 'string', autoMigrations: { columnType: 'varchar' } }, id: { type: 'number', autoMigrations: { autoIncrement: true, columnType: 'integer' } } } });
Make unique attribute required, to please sails-disk
Make unique attribute required, to please sails-disk
JavaScript
mit
balderdashy/waterline-adapter-tests
2fa647749dbd896ba960e8d3b0eacb2362502c4d
test/index.js
test/index.js
process.env.MONGOHQ_URL = 'mongodb://localhost:27017/jsonresume-tests'; var mongoUrl = process.env.MONGOHQ_URL; var mongo = require('../db'); // This bit of code runs before ANY tests start. before(function beforeAllTests(done) { // Connect to db before running tests mongo.connect(mongoUrl, function(err) { if (err) { console.log('Error connecting to Mongo.', { err: err }); return process.exit(1) } mongo.drop(done); }); });
var mongoose = require('mongoose'); process.env.MONGOHQ_URL = 'mongodb://localhost:27017/jsonresume-tests'; // register model schemas require('../models/user'); require('../models/resume'); require('../lib/mongoose-connection'); function dropMongoDatabase(callback) { // Drop the database once connected (or immediately if connected). var CONNECTION_STATES = mongoose.Connection.STATES; var readyState = mongoose.connection.readyState; var connected = false; var drop = function() { mongoose.connection.db.dropDatabase(function(err) { if (err) { throw err; } callback(err); }); }; if (CONNECTION_STATES[readyState] === 'connected') { drop(); } else { mongoose.connection.once('connected', drop); } } // This bit of code runs before ANY tests start. before(function beforeAllTests(done) { dropMongoDatabase(done); });
Update mocha before test setup to use mongoose.
Update mocha before test setup to use mongoose.
JavaScript
mit
vfulco/registry-server,vfulco/registry-server,bartuspan/registry-server,vfulco/registry-server,jsonresume/registry-server,jsonresume/registry-server,bartuspan/registry-server,bartuspan/registry-server,jsonresume/registry-server
dc643a838c45f4f4eae481e958919783b37bc5c2
test/index.js
test/index.js
'use strict'; var test = require('tape'); var nets = require('nets'); var requestGlobalDefaults = require('../'); test('defaulting/overriding a custom querystring', function (t) { t.plan(2); var defaultOptions = { json: true, // so we don't have to JSON.parse(body) later qs: { 'request-globaldefaults': 'default value', }, }; var overrideOptions = { url: 'https://httpbin.org/get', qs: { 'request-globaldefaults': 'override value', }, }; // The path used here should be `nets` result for require.resolve('request') // This path can change based on your dependencies and npm version. var innerRequest = require('nets/node_modules/request'); requestGlobalDefaults(defaultOptions, innerRequest); nets('https://httpbin.org/get', function (error, response, body) { if (error) { t.fail(error); } else { t.equal(body.args['request-globaldefaults'], 'default value'); } }); nets(overrideOptions, function (error, response, body) { if (error) { t.fail(error); } else { t.equal(body.args['request-globaldefaults'], 'override value'); } }); });
'use strict'; var test = require('tape'); var nets = require('nets'); var iferr = require('iferr'); var requestGlobalDefaults = require('../'); test('defaulting/overriding a custom querystring', function (t) { t.plan(2); var defaultOptions = { json: true, // so we don't have to JSON.parse(body) later qs: { 'request-globaldefaults': 'default value', }, }; var overrideOptions = { url: 'https://httpbin.org/get', qs: { 'request-globaldefaults': 'override value', }, }; // The path used here should be `nets` result for require.resolve('request') // This path can change based on your dependencies and npm version. var innerRequest = require('nets/node_modules/request'); requestGlobalDefaults(defaultOptions, innerRequest); nets('https://httpbin.org/get', iferr(t.fail, function (response, body) { t.equal(body.args['request-globaldefaults'], 'default value'); })); nets(overrideOptions, iferr(t.fail, function (response, body) { t.equal(body.args['request-globaldefaults'], 'override value'); })); });
Use `iferr` to simplify tests
Use `iferr` to simplify tests
JavaScript
mit
josephfrazier/request-globaldefaults
d6c6ad8beb0376474c6a1ee936c20dec0d7b8b06
test/qunit.js
test/qunit.js
"use strict"; let qUnit = require("qunit"); qUnit.setup({ log: { errors: true, tests: true, globalSummary: true, testing: true }, maxBlockDuration: 2000 }); // one code and tests file qUnit.run({ code: "test/adapter/qunit.js", tests: "test/tick-generator.js" }, err => { if (err) { console.log(err); } });
"use strict"; const fs = require("fs"); let qUnit = require("qunit"); qUnit.setup({ log: { errors: true, tests: true, globalSummary: true, testing: true }, maxBlockDuration: 2000 }); qUnit.run(fs.readdirSync("test") .filter(name => -1 === ["adapter", "qunit.js"].indexOf(name)) .map(name => { return { code: "test/adapter/qunit.js", tests: "test/" + name }; }), err => { if (err) { console.log(err); } });
Read test folder to get files
Read test folder to get files
JavaScript
mit
ArnaudBuchholz/bubu-timer
ef4bc8d7c2438eff88b8de5dc6b1597a68734dc4
tasksUtils.js
tasksUtils.js
const {TASKS_TYPES} = require('./conf/consts') const getTaskType = (taskName) =>{ for (let task_type of TASKS_TYPES) { for (let keyword of task_type.keywords) { if(taskName..toUpperCase().includes(keyword.toUpperCase())) return task_type.name } } } module.exports.formatTasks = (rawtasks,fromDate) => { console.log('Formatting raw data.') let ftasks = rawtasks.map(el => { // map the project_id attribute of all tasks and save in 'formatted tasks' //Set task task type el.task_type = getTaskType(el.name) el.assignee = el.assignee.name // we are only interested in the Assignee's name. We don't check if this exists since one of our filters for getting the task is the assignee return el }) // Filter only tasks that have a "completed at" value and that the "completed_at" month is the same // as the month we are requesting (There seems to be no way to filter these out directly in the // request to the server) let completedTasks = [] ftasks.forEach(function(task){ if(task.completed_at !== '' && task.completed_at !== null && (new Date(task.completed_at)).getUTCMonth() === (new Date(fromDate)).getUTCMonth()){ completedTasks.push(task) } }) return completedTasks }
const {TASKS_TYPES} = require('./conf/consts') const getTaskType = (taskName) =>{ for (let task_type of TASKS_TYPES) { for (let keyword of task_type.keywords) { if(taskName.toUpperCase().includes(keyword.toUpperCase())) return task_type.name } } } module.exports.formatTasks = (rawtasks,fromDate) => { console.log('Formatting raw data.') let ftasks = rawtasks.map(el => { // map the project_id attribute of all tasks and save in 'formatted tasks' //Set task task type el.task_type = getTaskType(el.name) el.assignee = el.assignee.name // we are only interested in the Assignee's name. We don't check if this exists since one of our filters for getting the task is the assignee return el }) // Filter only tasks that have a "completed at" value and that the "completed_at" month is the same // as the month we are requesting (There seems to be no way to filter these out directly in the // request to the server) let completedTasks = [] ftasks.forEach(function(task){ if(task.completed_at !== '' && task.completed_at !== null && (new Date(task.completed_at)).getUTCMonth() === (new Date(fromDate)).getUTCMonth()){ completedTasks.push(task) } }) return completedTasks }
Make search for classifying tasks case insensitive.
Make search for classifying tasks case insensitive.
JavaScript
mit
rojasmi1/asana-exporter
e31e7230b9dde86f74fa502b12d6640ff819d824
examples/Button/BasicButton.js
examples/Button/BasicButton.js
import React from 'react'; import Button from 'src/Button'; import FlexRow from '../FlexRow'; function handleButtonClick() { // eslint-disable-next-line no-console console.log('Button clicked'); } function BasicButtonExample() { return ( <FlexRow> <Button basic="Blue Button" aside="Default color" tag="Tag" icon="add" onClick={handleButtonClick} /> <Button color="red" basic="Red" aside="Variants" tag="Tag" icon="add" /> <Button color="white" basic="White" aside="Variants" tag="Tag" icon="add" /> <Button color="black" basic="Black" aside="Variants" tag="Tag" icon="add" /> </FlexRow> ); } export default BasicButtonExample;
import React from 'react'; import { action } from '@kadira/storybook'; import Button from 'src/Button'; import FlexRow from '../FlexRow'; function BasicButtonExample() { return ( <FlexRow> <Button basic="Blue Button" aside="Default color" tag="Tag" icon="add" onClick={action('clicked')} /> <Button color="red" basic="Red" aside="Variants" tag="Tag" icon="add" /> <Button color="white" basic="White" aside="Variants" tag="Tag" icon="add" /> <Button color="black" basic="Black" aside="Variants" tag="Tag" icon="add" /> </FlexRow> ); } export default BasicButtonExample;
Use `action` provided by storybook
[examples] Use `action` provided by storybook
JavaScript
apache-2.0
iCHEF/gypcrete,iCHEF/gypcrete
2775a265d077d4f74545204322bc7e9cc0d820f9
test/index.js
test/index.js
'use strict'; /** * Module dependencies. */ var assert = require('chai').assert; var mocks = require('./mocks/'); var htmlparser = require('htmlparser2'); /** * Tests for parser. */ describe('html-dom-parser', function() { describe('server parser', function() { var parser = require('../'); it('is equivalent to `htmlparser2.parseDOM()`', function() { // html Object.keys(mocks.html).forEach(function(type) { var html = mocks.html[type]; assert.deepEqual(parser(html), htmlparser.parseDOM(html)); }); // svg Object.keys(mocks.svg).forEach(function(type) { var svg = mocks.svg[type]; assert.deepEqual(parser(svg), htmlparser.parseDOM(svg)); }); }); }); });
'use strict'; /** * Module dependencies. */ var assert = require('chai').assert; var mocks = require('./mocks/'); var htmlparser = require('htmlparser2'); /** * Helper that creates and runs tests based on mock data. * * @param {Function} parser - The parser. * @param {Object} mockObj - The mock object. */ function runTests(parser, mockObj) { Object.keys(mockObj).forEach(function(type) { it(type, function() { var data = mockObj[type]; assert.deepEqual(parser(data), htmlparser.parseDOM(data)); }) }); } /** * Tests for parser. */ describe('html-dom-parser', function() { // server describe('server parser', function() { var parser = require('../'); // should be equivalent to `htmlparser2.parseDOM()` runTests(parser, mocks.html); runTests(parser, mocks.svg); }); });
Refactor tests with `runTests()` helper
Refactor tests with `runTests()` helper `runTests()` will create and run tests given parser and mock data. Since the helper creates an `it()` block for each mock object key, this allows the tests to be DRY and clear. Also, debugging will be easier since the type of parser test being run is made explicit.
JavaScript
mit
remarkablemark/html-dom-parser,remarkablemark/html-dom-parser,remarkablemark/html-dom-parser,remarkablemark/html-dom-parser
2de05d905510edac666cc65cab62d017680f4ce7
config.js
config.js
{ "host": "localhost", "port": 7777, "keyLength": 6, "maxLength": 400000, "staticMaxAge": 86400, "recompressStaticAssets": true, "logging": [ { "level": "verbose", "type": "Console", "colorize": true } ], "storage": { "type": "redis", "host": "localhost", "port": 6379, "db": 2, "expire": 3600 }, "documents": { "about": "./about.md" } }
{ "host": "localhost", "port": 7777, "keyLength": 6, "maxLength": 400000, "staticMaxAge": 86400, "recompressStaticAssets": true, "logging": [ { "level": "verbose", "type": "Console", "colorize": true } ], "storage": { "type": "redis", "host": "localhost", "port": 6379, "db": 2, "expire": 2592000 }, "documents": { "about": "./about.md" } }
Change expiration to 30 days
Change expiration to 30 days
JavaScript
mit
jirutka/haste-server,jirutka/haste-server
07ae3f3123e16e88ea84642cb64fe724595bf8a1
config.js
config.js
var config = {}; config.thinkingThings = { logLevel: 'ERROR', port: 8000, root: '/thinkingthings', sleepTime: 300 }; config.ngsi = { logLevel: 'ERROR', defaultType: 'ThinkingThing', contextBroker: { host: '192.168.56.101', port: '1026' }, server: { port: 4041 }, deviceRegistry: { type: 'memory' }, types: { 'ThinkingThing': { service: 'smartGondor', subservice: '/gardens', type: 'ThinkingThing', commands: [], lazy: [], active: [ { name: 'humidity', type: 'Number' } ] } }, service: 'smartGondor', subservice: '/gardens', providerUrl: 'http://192.168.56.1:4041', deviceRegistrationDuration: 'P1M' }; module.exports = config;
var config = {}; config.thinkingThings = { logLevel: 'ERROR', port: 8000, root: '/thinkingthings', sleepTime: 300 }; config.ngsi = { logLevel: 'ERROR', defaultType: 'ThinkingThing', contextBroker: { host: '127.0.0.1', port: '1026' }, server: { port: 4041 }, deviceRegistry: { type: 'memory' }, types: { 'ThinkingThing': { service: 'smartGondor', subservice: '/gardens', type: 'ThinkingThing', commands: [], lazy: [], active: [ { name: 'humidity', type: 'Number' } ] } }, service: 'smartGondor', subservice: '/gardens', providerUrl: 'http://127.0.0.1:4041', deviceRegistrationDuration: 'P1M' }; module.exports = config;
FIX Use localhost as default URL
FIX Use localhost as default URL
JavaScript
agpl-3.0
telefonicaid/iotagent-thinking-things,telefonicaid/iotagent-thinking-things,telefonicaid/iotagent-thinking-things
bd4627650af445e5207728a9fda36b92ebd9ecb0
examples/simple-svg/app/simple-svg.js
examples/simple-svg/app/simple-svg.js
import Circle from './stores/Circle' import Microcosm from '../../../dist/Microcosm' export default class SimpleSVG extends Microcosm { constructor() { super() this.addStore('circle', Circle) if (module.hot) { module.hot.accept('./stores/Circle', () => { Circle.register = require('./stores/Circle').register }) } } }
import Circle from './stores/Circle' import Microcosm from '../../../src/Microcosm' export default class SimpleSVG extends Microcosm { constructor() { super() this.addStore('circle', Circle) if (module.hot) { module.hot.accept('./stores/Circle', () => { Circle.register = require('./stores/Circle').register }) } } }
Use src Microcosm in simple svg example
Use src Microcosm in simple svg example
JavaScript
mit
vigetlabs/microcosm,leobauza/microcosm,vigetlabs/microcosm,leobauza/microcosm,vigetlabs/microcosm,leobauza/microcosm
e3ea4dc888a757b94e6c2a319874c4c532473c95
app/scripts/dimApp.i18n.js
app/scripts/dimApp.i18n.js
(function() { "use strict"; // See https://angular-translate.github.io/docs/#/guide angular.module('dimApp') .config(['$translateProvider', function($translateProvider) { $translateProvider.useSanitizeValueStrategy('escape'); $translateProvider .translations('en', { Level: "Level", Weapons: "Weapons", Armor: "Armor", Equip: "Equip", Vault: "Vault", Vanguard: "Vanguard" }) .translations('it', { Level: "Livello", Weapons: "Armi", Armor: "Armatura", Equip: "Equipaggia", Vault: "Deposito" }) .translations('de', { Equip: "Ausstatten", Vault: "Ausrüstungstresor" }) .translations('fr', { }) .translations('es', { Level: "Nivel", Weapons: "Arma", Armor: "Armadura", Vault: "Bóveda", Vanguard: "Vanguardia" }) .translations('ja', { }) .translations('pt-br', { }) .fallbackLanguage('en'); }]); })();
(function() { "use strict"; // See https://angular-translate.github.io/docs/#/guide angular.module('dimApp') .config(['$translateProvider', function($translateProvider) { $translateProvider.useSanitizeValueStrategy('escape'); $translateProvider .translations('en', { Level: "Level", Weapons: "Weapons", Armor: "Armor", Equip: "Equip", Vault: "Vault", Vanguard: "Vanguard" }) .translations('it', { Level: "Livello", Weapons: "Armi", Armor: "Armatura", Equip: "Equipaggia", Vault: "Deposito" }) .translations('de', { Weapons: "Waffen", Armor: "Schutz", Equip: "Ausstatten", Vault: "Ausrüstungstresor" }) .translations('fr', { Level: "Niveau", Weapons: "Armes", Armor: "Armure", Equip: "Équiper", Vault: "Coffres" }) .translations('es', { Level: "Nivel", Weapons: "Armas", Armor: "Armadura", Equip: "Equipar", Vault: "Bóveda", Vanguard: "Vanguardia" }) .translations('ja', { }) .translations('pt-br', { Level: "Nivel", Weapons: "Armas", Armor: "Armadura", Equip: "Equipar", Vault: "Cofres" }) .fallbackLanguage('en'); }]); })();
Update German, French, Spanish, and Portugese-Brasil Translations
Update German, French, Spanish, and Portugese-Brasil Translations All pulled by changing system language on PS4 and accessing Destiny in a different language.
JavaScript
mit
delphiactual/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM,chrisfried/DIM,DestinyItemManager/DIM,LouisFettet/DIM,bhollis/DIM,delphiactual/DIM,LouisFettet/DIM,48klocs/DIM,delphiactual/DIM,48klocs/DIM,chrisfried/DIM,bhollis/DIM,delphiactual/DIM,DestinyItemManager/DIM,48klocs/DIM,bhollis/DIM,bhollis/DIM,chrisfried/DIM,chrisfried/DIM
a968b2b1d19adebb2d1637ee9f9c151d848cbec2
app/scripts/components/openstack/openstack-backup/module.js
app/scripts/components/openstack/openstack-backup/module.js
import openstackBackupsService from './openstack-backups-service'; import openstackBackupsList from './openstack-backups-list'; import backupSnapshotsList from './backup-snapshots-list'; export default module => { module.service('openstackBackupsService', openstackBackupsService); module.directive('openstackBackupsList', openstackBackupsList); module.directive('backupSnapshotsList', backupSnapshotsList); module.config(actionConfig); module.config(tabsConfig); }; // @ngInject function actionConfig(ActionConfigurationProvider, DEFAULT_EDIT_ACTION) { ActionConfigurationProvider.register('OpenStackTenant.Backup', { order: [ 'edit' ], options: { edit: angular.merge({}, DEFAULT_EDIT_ACTION, { successMessage: 'Backup has been updated', fields: { kept_until: { help_text: 'Guaranteed time of backup retention. If null - keep forever.', label: 'Kept until', required: false, type: 'datetime' } } }) } }); } // @ngInject function tabsConfig(ResourceTabsConfigurationProvider, DEFAULT_RESOURCE_TABS) { ResourceTabsConfigurationProvider.register('OpenStackTenant.Backup', { order: [ ...DEFAULT_RESOURCE_TABS.order, 'snapshots', ], options: angular.merge({}, DEFAULT_RESOURCE_TABS.options, { snapshots: { heading: 'Snapshots', component: 'backupSnapshotsList' }, }) }); }
import openstackBackupsService from './openstack-backups-service'; import openstackBackupsList from './openstack-backups-list'; import backupSnapshotsList from './backup-snapshots-list'; export default module => { module.service('openstackBackupsService', openstackBackupsService); module.directive('openstackBackupsList', openstackBackupsList); module.directive('backupSnapshotsList', backupSnapshotsList); module.config(actionConfig); module.config(tabsConfig); }; // @ngInject function actionConfig(ActionConfigurationProvider, DEFAULT_EDIT_ACTION) { ActionConfigurationProvider.register('OpenStackTenant.Backup', { order: [ 'edit', 'restore', 'destroy', ], options: { edit: angular.merge({}, DEFAULT_EDIT_ACTION, { successMessage: 'Backup has been updated', fields: { kept_until: { help_text: 'Guaranteed time of backup retention. If null - keep forever.', label: 'Kept until', required: false, type: 'datetime' } } }) } }); } // @ngInject function tabsConfig(ResourceTabsConfigurationProvider, DEFAULT_RESOURCE_TABS) { ResourceTabsConfigurationProvider.register('OpenStackTenant.Backup', { order: [ ...DEFAULT_RESOURCE_TABS.order, 'snapshots', ], options: angular.merge({}, DEFAULT_RESOURCE_TABS.options, { snapshots: { heading: 'Snapshots', component: 'backupSnapshotsList' }, }) }); }
Enable backup restore and destroy actions.
Enable backup restore and destroy actions.
JavaScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
5de29f23895437016a80690dab47b4f9712b7888
app/assets/javascripts/analytics/init.js
app/assets/javascripts/analytics/init.js
(function (window) { "use strict"; window.GOVUK = window.GOVUK || {}; const trackingId = 'UA-26179049-1'; // Disable analytics by default window[`ga-disable-${trackingId}`] = true; const initAnalytics = function () { // guard against being called more than once if (!('analytics' in window.GOVUK)) { window[`ga-disable-${trackingId}`] = false; // Load Google Analytics libraries window.GOVUK.Analytics.load(); // Configure profiles and make interface public // for custom dimensions, virtual pageviews and events window.GOVUK.analytics = new GOVUK.Analytics({ trackingId: trackingId, cookieDomain: 'auto', anonymizeIp: true, displayFeaturesTask: null, transport: 'beacon', name: 'GOVUK.analytics', expires: 365 }); // Track initial pageview window.GOVUK.analytics.trackPageview(); } }; window.GOVUK.initAnalytics = initAnalytics; })(window);
(function (window) { "use strict"; window.GOVUK = window.GOVUK || {}; const trackingId = 'UA-75215134-1'; // Disable analytics by default window[`ga-disable-${trackingId}`] = true; const initAnalytics = function () { // guard against being called more than once if (!('analytics' in window.GOVUK)) { window[`ga-disable-${trackingId}`] = false; // Load Google Analytics libraries window.GOVUK.Analytics.load(); // Configure profiles and make interface public // for custom dimensions, virtual pageviews and events window.GOVUK.analytics = new GOVUK.Analytics({ trackingId: trackingId, cookieDomain: 'auto', anonymizeIp: true, displayFeaturesTask: null, transport: 'beacon', name: 'GOVUK.analytics', expires: 365 }); // Track initial pageview window.GOVUK.analytics.trackPageview(); } }; window.GOVUK.initAnalytics = initAnalytics; })(window);
Fix Google Analytics tracking code
Fix Google Analytics tracking code
JavaScript
mit
alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin
4aec723718849b36b53f79e96fa3f37c1c06827c
app/components/tracking-bar/component.js
app/components/tracking-bar/component.js
/** * @module timed * @submodule timed-components * @public */ import Component from 'ember-component' import service from 'ember-service/inject' const ENTER_CHAR_CODE = 13 /** * The tracking bar component * * @class TrackingBarComponent * @extends Ember.Component * @public */ export default Component.extend({ tracking: service('tracking'), /** * Key press event * * Start activity if the pressed key is enter * * @event keyPress * @param {jQuery.Event} e The keypress event * @public */ keyPress(e) { if ( e.charCode === ENTER_CHAR_CODE && !e.target.classList.contains('tt-input') ) { this.get('tracking.startActivity').perform() } } })
/** * @module timed * @submodule timed-components * @public */ import Component from 'ember-component' import service from 'ember-service/inject' import { observes } from 'ember-computed-decorators' import { later } from 'ember-runloop' const ENTER_CHAR_CODE = 13 /** * The tracking bar component * * @class TrackingBarComponent * @extends Ember.Component * @public */ export default Component.extend({ tracking: service('tracking'), /** * Key press event * * Start activity if the pressed key is enter * * @event keyPress * @param {jQuery.Event} e The keypress event * @public */ keyPress(e) { if ( e.charCode === ENTER_CHAR_CODE && !e.target.classList.contains('tt-input') ) { this.get('tracking.startActivity').perform() } }, /** * Set the focus to the comment field as soon as the task is selected * * The 'later' needs to be there so that the focus happens after all the * other events are done. Otherwise it'd focus the play button. * * @method _setCommentFocus * @public */ @observes('tracking.activity.task') _setCommentFocus() { if (this.get('tracking.activity.task.id')) { later(this, () => { this.$('input[name=comment]').focus() }) } } })
Set the focus to the comment box after selecting a task
Set the focus to the comment box after selecting a task
JavaScript
agpl-3.0
anehx/timed-frontend,adfinis-sygroup/timed-frontend,anehx/timed-frontend,adfinis-sygroup/timed-frontend,adfinis-sygroup/timed-frontend
f0e830f75ade265e61f3db9126f55b6ac6a484fa
app/users/users.service.js
app/users/users.service.js
{ class UsersService { create () { console.log('CREATED!'); console.log(user); } } angular.module('meganote.users') .service('UsersService', UsersService); }
{ angular.module('meganote.users') .service('UsersService', [ '$hhtp', 'API_BASE', ($http, API_BASE) => { class UsersService { create (users) { $http.get(API_BASE) .then( res => { console.log(res.data); } ); } } return new UsersService(); } ]); }
Refactor SignUp directive to use UsersService.
Refactor SignUp directive to use UsersService.
JavaScript
mit
zachmillikan/meganote,zachmillikan/meganote
2bfd14b5881c2fc53678a0de6d0ae3a6d3f39d36
e2e/github.spec.js
e2e/github.spec.js
'use strict'; describe('github banner', function() { beforeEach(function() { browser.get('http://localhost:3000/'); }); it('should load', function() { var list = element.all(by.css( 'a[href="https://github.com/solarnz/ec2pric.es"]' )); expect(list.count()).toBe(1); }); });
'use strict'; describe('github banner', function() { var banner; beforeEach(function() { browser.get('http://localhost:3000/'); banner = element(by.css( 'a[href="https://github.com/solarnz/ec2pric.es"]' )); }); it('should be present', function() { expect(banner.isPresent).toBeTruthy(); }); });
Clean up the github banner tests a little bit
[e2e] Clean up the github banner tests a little bit
JavaScript
mit
solarnz/ec2pric.es,solarnz/ec2pric.es,solarnz/ec2pric.es
f1407008fd4492c8482febb6ea875f26fc74b28f
src/components/ContextPropagator/index.js
src/components/ContextPropagator/index.js
import React from 'react'; function getViewportData() { let viewport = 'xs'; if (window.innerWidth >= 544) viewport = 'sm'; if (window.innerWidth >= 768) viewport = 'md'; if (window.innerWidth >= 992) viewport = 'lg'; if (window.innerWidth >= 1200) viewport = 'xl'; return viewport; } function renderThemedChildren(props) { return React.Children.map(props.children, (child) => { if (!child) return null; return React.cloneElement(child, { theme: props.theme, viewport: getViewportData() }); }); } const ContextPropagator = (props) => { return ( <div style={props.wrapperStyle}> { renderThemedChildren(props) } </div> ); } ContextPropagator.propTypes = { wrapperStyle: React.PropTypes.object, children: React.PropTypes.arrayOf(React.PropTypes.element) }; export default ContextPropagator;
import React from 'react'; function getViewportData() { let viewport = 'xs'; if (window.innerWidth >= 544) viewport = 'sm'; if (window.innerWidth >= 768) viewport = 'md'; if (window.innerWidth >= 992) viewport = 'lg'; if (window.innerWidth >= 1200) viewport = 'xl'; return viewport; } function renderThemedChildren(props) { return React.Children.map(props.children, (child) => { if (!child) return null; return React.cloneElement(child, { theme: props.theme, viewport: getViewportData() }); }); } const ContextPropagator = (props) => { return ( <div style={props.wrapperStyle}> { renderThemedChildren(props) } </div> ); } ContextPropagator.propTypes = { wrapperStyle: React.PropTypes.object, children: React.PropTypes.node }; export default ContextPropagator;
Use node instead of element array for prop validation
Use node instead of element array for prop validation
JavaScript
mit
line64/landricks-components
cea4a0a8d90a1226924576b039ff36661d74fdf0
src/components/Editor/ConditionalPanel.js
src/components/Editor/ConditionalPanel.js
// @flow const React = require("react"); const { DOM: dom } = React; const ReactDOM = require("react-dom"); require("./ConditionalPanel.css"); function renderConditionalPanel({ condition, closePanel, setBreakpoint }: { condition: boolean, closePanel: Function, setBreakpoint: Function }) { let panel = document.createElement("div"); function onKey(e: SyntheticKeyboardEvent) { if (e.key != "Enter") { return; } if (e.target && e.target.value) { setBreakpoint(e.target.value); closePanel(); } } ReactDOM.render( dom.div( { className: "conditional-breakpoint-panel" }, dom.div({ className: "prompt", dangerouslySetInnerHTML: { __html: "&raquo;" } }), dom.input({ defaultValue: condition, placeholder: L10N.getStr("editor.conditionalPanel.placeholder"), onKeyPress: onKey }) ), panel ); return panel; } module.exports = { renderConditionalPanel };
// @flow const React = require("react"); const { DOM: dom } = React; const ReactDOM = require("react-dom"); require("./ConditionalPanel.css"); function renderConditionalPanel({ condition, closePanel, setBreakpoint }: { condition: boolean, closePanel: Function, setBreakpoint: Function }) { let panel = document.createElement("div"); function onKey(e: SyntheticKeyboardEvent) { if (e.key != "Enter") { return; } if (e.target && e.target.value) { setBreakpoint(e.target.value); closePanel(); } } ReactDOM.render( dom.div( { className: "conditional-breakpoint-panel" }, dom.div({ className: "prompt" }, "»"), dom.input({ defaultValue: condition, placeholder: L10N.getStr("editor.conditionalPanel.placeholder"), onKeyPress: onKey }) ), panel ); return panel; } module.exports = { renderConditionalPanel };
Fix to use unicode char instead of innerHTML
issue(1946): Fix to use unicode char instead of innerHTML
JavaScript
mpl-2.0
borian/debugger.html,bomsy/debugger.html,bomsy/debugger.html,wldcordeiro/debugger.html,clarkbw/debugger.html,jbhoosreddy/debugger.html,tommai78101/debugger.html,devtools-html/debugger.html,bomsy/debugger.html,devtools-html/debugger.html,devtools-html/debugger.html,jbhoosreddy/debugger.html,tommai78101/debugger.html,devtools-html/debugger.html,clarkbw/debugger.html,wldcordeiro/debugger.html,darkwing/debugger.html,amitzur/debugger.html,jbhoosreddy/debugger.html,darkwing/debugger.html,clarkbw/debugger.html,darkwing/debugger.html,ruturajv/debugger.html,ruturajv/debugger.html,darkwing/debugger.html,ruturajv/debugger.html,ruturajv/debugger.html,darkwing/debugger.html,jasonLaster/debugger.html,devtools-html/debugger.html,bomsy/debugger.html,borian/debugger.html,jasonLaster/debugger.html,tommai78101/debugger.html,ruturajv/debugger.html,wldcordeiro/debugger.html,devtools-html/debugger.html,ruturajv/debugger.html,jasonLaster/debugger.html,darkwing/debugger.html,tommai78101/debugger.html,ruturajv/debugger.html,bomsy/debugger.html,borian/debugger.html,amitzur/debugger.html,jasonLaster/debugger.html,jasonLaster/debugger.html,jbhoosreddy/debugger.html,jbhoosreddy/debugger.html,jasonLaster/debugger.html,amitzur/debugger.html,wldcordeiro/debugger.html,jbhoosreddy/debugger.html,bomsy/debugger.html,jbhoosreddy/debugger.html,clarkbw/debugger.html,devtools-html/debugger.html,jasonLaster/debugger.html,amitzur/debugger.html,tommai78101/debugger.html,darkwing/debugger.html,borian/debugger.html,amitzur/debugger.html,amitzur/debugger.html,wldcordeiro/debugger.html,wldcordeiro/debugger.html,borian/debugger.html,bomsy/debugger.html,clarkbw/debugger.html,wldcordeiro/debugger.html,borian/debugger.html
d09f6f7c50a07654b64b3f5d93c6132f3da2dee8
src/components/utility/NavHelper/index.js
src/components/utility/NavHelper/index.js
import app from 'ampersand-app' import React, {Component, PropTypes} from 'react' import localLinks from 'local-links' import * as modalActions from 'gModules/modal/actions.js' import {connect} from 'react-redux'; @connect() export default class NavHelper extends Component{ displayName: 'NavHelper' onClick (event) { const pathname = localLinks.getLocalPathname(event) if (pathname) { event.preventDefault() app.router.history.navigate(pathname) this.props.dispatch(modalActions.close()) } } render () { return ( <div className='navHelper' onClick={this.onClick.bind(this)}> {this.props.children} </div> ) } }
import app from 'ampersand-app' import React, {Component, PropTypes} from 'react' import localLinks from 'local-links' import * as modalActions from 'gModules/modal/actions.js' import {connect} from 'react-redux'; import $ from 'jquery' @connect() export default class NavHelper extends Component{ displayName: 'NavHelper' onClick (event) { const pathname = localLinks.getLocalPathname(event) if (pathname) { event.preventDefault() app.router.history.navigate(pathname) this.props.dispatch(modalActions.close()) } } componentDidMount(){ $(document).on('keydown', (e) => { if (e.which === 8 && $(e.target).is('body')) { e.preventDefault(); } }); } render () { return ( <div className='navHelper' onClick={this.onClick.bind(this)}> {this.props.children} </div> ) } }
Use NavHelper to ensure that backspace when nothing is selected will not go back in history
Use NavHelper to ensure that backspace when nothing is selected will not go back in history
JavaScript
mit
getguesstimate/guesstimate-app
dbcd077bd025dd71e21ab140839573a5f2f124d9
server/server.js
server/server.js
import express from 'express'; import path from 'path'; import lodashExpress from 'lodash-express'; import fs from 'fs'; const app = express(); const staticPath = path.join(__dirname, '../build/'); app.use(express.static(staticPath)); lodashExpress(app, 'html'); app.set('view engine', 'html'); const hash = fs.readFileSync(path.join(staticPath, 'hash')); app.get('/', (req, res) => { res.redirect('/portal') }); app.get('/portal*', (req, res) => { res.render('index-prod', {hash}); }) app.listen(3000, function() { console.log('Server is listening on port 3000'); });
import express from 'express'; import path from 'path'; import lodashExpress from 'lodash-express'; import fs from 'fs'; const app = express(); const staticPath = path.join(__dirname, '../build/'); app.use(express.static(staticPath)); lodashExpress(app, 'html'); app.set('view engine', 'html'); const hash = fs.readFileSync(path.join(staticPath, 'hash')); app.get('/', (req, res) => { res.redirect('/portal') }); app.get('/portal*', (req, res) => { res.render('index-prod', {hash}); }) const port = +(process.env.HTTP_PORT || 3000); app.listen(, function() { console.log(`hdo-portal is listening on port ${port}`); });
Make port configurable through env
Make port configurable through env
JavaScript
bsd-3-clause
holderdeord/hdo-portal,holderdeord/hdo-portal
b5e0c3586002333d49edb6a3c2cf4c287728c333
examples/basic/components/App.js
examples/basic/components/App.js
import React from 'react' import { Link, hashHistory } from 'react-router' export default function App({ children }) { return ( <div> <header> Links: {' '} <Link to="/">Home</Link> {' '} <Link to="/foo">Foo</Link> {' '} <Link to="/bar">Bar</Link> </header> <div> <button onClick={() => hashHistory.push('/foo')}>Go to /foo</button> </div> <div style={{ marginTop: '1.5em' }}>{children}</div> </div> ) }
import React from 'react' import { Link, browserHistory } from 'react-router' export default function App({ children }) { return ( <div> <header> Links: {' '} <Link to="/">Home</Link> {' '} <Link to="/foo">Foo</Link> {' '} <Link to="/bar">Bar</Link> </header> <div> <button onClick={() => browserHistory.push('/foo')}>Go to /foo</button> </div> <div style={{ marginTop: '1.5em' }}>{children}</div> </div> ) }
Use browserHistory instead of hashHistory
Use browserHistory instead of hashHistory
JavaScript
mit
reactjs/react-router-redux,rackt/redux-simple-router
feb1c6d015ddd0e72b8a856ef2242e5742ea21ea
server.js
server.js
var express = require('express'); var app = express(); app.set('port', process.env.PORT || 3000); //custom 404 page. app.use(function (req, res){ res.type('text/plain'); res.status(404); res,send('404 - Not Found'); }); //custom 500 page. app.use(function (err, req, res, next){ console.error(err.stack); res.type('text/plain'); res.status(500); res.send('500 - Server Error'); }); app.listen(app.get('port'), function(){ console.log('Express started on http://localhost:' + app.get('port' + '; press Ctrl-C to terminate.')); });
var express = require('express'); var app = express(); var path = require('path'); app.set('port', process.env.PORT || 3000); // View engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs');//Set the view engine to ejs for renderring html content. // Default landing page app.get('/', function(req, res) { res.send('Welcome'); }); // Custom 404 page. app.use(function (req, res){ res.type('text/plain'); res.status(404); res.send('404 - Not Found'); }); // Custom 500 page. app.use(function (err, req, res, next){ console.error(err.stack); res.type('text/plain'); res.status(500); res.send('500 - Server Error'); }); // Start the server app.listen(app.get('port'), function(){ console.log('Express started.'); });
Set the view engine, set the welcome page
Set the view engine, set the welcome page
JavaScript
mit
zhang96/WarmerForWeb,zhang96/Warmer.Pro,zhang96/WarmerForWeb,zhang96/Warmer.Pro
ae2a14404ed51d0beb73a068685d512e6442b3ae
server.js
server.js
"use strict" var namespace = 'azure-service-bus-nodejs', accessKey = '[Access key for this namespace]', azure = require('azure'); var client = azure.createServiceBusService(namespace, accessKey); client.listTopics(function(error, result, response) { if (error) { console.log(error); return; } console.log(JSON.stringify(result, null, 3)); });
"use strict" var namespace = 'azure-service-bus-nodejs', accessKey = '[Access key for this namespace]', azure = require('azure'), http = require('http'); var client = azure.createServiceBusService(namespace, accessKey); var server = http.createServer(function(httpReq, httpResp) { client.listTopics(function(error, result, response) { if (error) { httpResp.writeHead(500, {'Content-Type': 'application/json'}); httpResp.write(JSON.stringify(error, null, 3)); httpResp.end(); return; } var topics = result.map(function(topic) { return { name: topic.TopicName, totalSubscriptions: topic.SubscriptionCount, totalSize: topic.SizeInBytes }; }); httpResp.writeHead(200, {'Content-Type': 'application/json'}); httpResp.write(JSON.stringify(topics, null, 3)); httpResp.end(); }); }); server.listen(8080);
Make it a web service
Make it a web service
JavaScript
mit
robjoh/azure-service-bus-nodejs
c71e3a603fb6b6d2ae84742136b183e5b51ad3f1
server.js
server.js
var cuecard = require('cuecard'); cuecard.configure({ title: 'Getting Closure', html: __dirname + '/slides.html', css: __dirname + '/slides.css' }); cuecard.server.listen(3000);
var cuecard = require('cuecard'); cuecard.create({ port: 3000, remoteUrl: '/my-remote-url', title: 'Getting Closure', html: __dirname + '/slides.html', css: __dirname + '/slides.css' });
Use port and remoteUrl options
Use port and remoteUrl options
JavaScript
mit
markdalgleish/cuecard-example
9d1d8549922e5b3b4f98f33507fee464d1b3ed3e
server.js
server.js
var express = require('express'); var app = express(); app.use(express.static('public')); app.listen(3000, function () { console.log('Example app listening on port 3000!'); });
var express = require('express'); var app = express(); app.use(express.static('public', {index: 'index.html'})); app.listen(3000, function () { console.log('Example app listening on port 3000!'); });
Configure path to index.html manually
Configure path to index.html manually
JavaScript
mit
denisnarush/postcard,denisnarush/postcard
33b7617767406cee986341e64c54bc9ff01ce91e
server.js
server.js
var sql = require('msnodesql'); // Change the connectionString. Example // "Driver={SQL Server Native Client 11.0};Server=tcp:?????.database.windows.net,1433;Database=????;Uid=?????@?????;Pwd=?????"; var connectionString = ""; var testQuery = "SELECT 1"; if(connectionString == "") { console.log("This script cannot run without a connection string"); return; } var http = require('http'); var port = process.env.PORT || 1337; var httpServer = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); sql.open(connectionString, function(err, conn) { if(err) res.end("Connection Failed \n"); conn.query(testQuery, [], function(err, result) { if(err) res.end("Query Failed \n"); else res.end("Query result - " + result[0]['Column0'] + " \n"); }); }); }); httpServer.listen(port); console.log('Server running at localhost:'+port);
var sql = require('msnodesql'); // Change the connectionString. Example // "Driver={SQL Server Native Client 11.0};Server=tcp:?????.database.windows.net,1433;Database=????;Uid=?????@?????;Pwd=?????"; var connectionString = ""; var testQuery = "SELECT 1"; if(connectionString == "") { console.log("This script cannot run without a connection string"); return; } var http = require('http'); var port = process.env.PORT || 1337; var httpServer = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); sql.query(connectionString, testQuery, function(err, result) { if(err) res.end("Query Failed \n"); else res.end("Query result: " + result[0]['Column0'] + " \n"); }); }); httpServer.listen(port); console.log('Server running at localhost:'+port);
Use sql.query instead of sql.open/conn.query
Use sql.query instead of sql.open/conn.query This is a bit of a shortcut, but the readability of the code is greatly improved.
JavaScript
mit
jorgeazevedo/node-sqlserver-unofficial
ff428f4525cf58a2488baa45073b4a4be703407c
lib/chat_server.js
lib/chat_server.js
var socketio = require('socket.io'); var io; var guestNumber = 1; var nickNames = {}; var namesUsed = []; var currentRoom = {}; exports.listen = function(server) { io = socketio.listen(server); io.set('log level', 1); io.sockets.on('connection', function(socket) { guestNumber = assignGuestName(socket, guestNumber, nickNames, namesUsed); joinRoom(socket, 'Lobby'); handleMessageBroadcasting(socket, nickNames); handleNameChangeAttempts(socket, nickNames, namesUsed); handleRoomJoining(socket); socket.on('rooms', function() { socket.emit('rooms', io.sockets.manager.rooms); }); handleClientDisconnection(socket, nickNames, namesUsed); }); }; function assignGuestName(socket, guestNumber, nickNames, namesUsed) { var name = 'Guest' + guestNumber; nickNames[socket.id] = name; socket.emit('nameResult', { success: true, name: name }); namesUsed.push(name); return guestNumber + 1; }
var socketio = require('socket.io'); var io; var guestNumber = 1; var nickNames = {}; var namesUsed = []; var currentRoom = {}; exports.listen = function(server) { io = socketio.listen(server); io.set('log level', 1); io.sockets.on('connection', function(socket) { guestNumber = assignGuestName(socket, guestNumber, nickNames, namesUsed); joinRoom(socket, 'Lobby'); handleMessageBroadcasting(socket, nickNames); handleNameChangeAttempts(socket, nickNames, namesUsed); handleRoomJoining(socket); socket.on('rooms', function() { socket.emit('rooms', io.sockets.manager.rooms); }); handleClientDisconnection(socket, nickNames, namesUsed); }); }; function assignGuestName(socket, guestNumber, nickNames, namesUsed) { var name = 'Guest' + guestNumber; nickNames[socket.id] = name; socket.emit('nameResult', { success: true, name: name }); namesUsed.push(name); return guestNumber + 1; } function joinRoom(socket, room) { socket.join(room); currentRoom[socket.id] = room; socket.emit('joinResult', {room: room}); socket.broadcast.to(room).emit('message', { text: nickNames[socket.io] + 'has joined' + room + '.' }); var usersInRoom = io.sockets.clients(room); if (usersInRoom.length > 1) { var usersInRoomSummary = 'Users currently in ' + room + ': '; for(var index in usersInRoom) { var userSocketId = usersInRoom[index].id; if (userSocketId != socket.id) { if (index > 0) { usersInRoomSummary += ', '; } usersInRoomSummary += nickNames[userSocketId]; } } usersInRoomSummary += '.'; socket.emit('message', {text: usersInRoomSummary}); } }
Add helper function for joining rooms
Add helper function for joining rooms
JavaScript
mit
sebsonic2o/chatrooms,sebsonic2o/chatrooms
05d43a85f256ad1bd1728138fad46a8392c2475e
etc/notebook/custom/custom.js
etc/notebook/custom/custom.js
/* JupyROOT JS */ // Terminal button $(document).ready(function() { $('div#header-container').append("<a href='terminals/1' class='btn btn-default btn-sm navbar-btn pull-right' style='margin-right: 4px; margin-left: 2px;'>Terminal</a>"); });
/* JupyROOT JS */ // Terminal button $(document).ready(function() { $('div#header-container').append("<a href='/terminals/1' class='btn btn-default btn-sm navbar-btn pull-right' style='margin-right: 4px; margin-left: 2px;'>Terminal</a>"); });
Fix path to terminal from ROOTbook
Fix path to terminal from ROOTbook
JavaScript
lgpl-2.1
mattkretz/root,sawenzel/root,mhuwiler/rootauto,gganis/root,agarciamontoro/root,abhinavmoudgil95/root,karies/root,mattkretz/root,abhinavmoudgil95/root,olifre/root,root-mirror/root,buuck/root,Y--/root,sawenzel/root,lgiommi/root,bbockelm/root,mattkretz/root,agarciamontoro/root,gbitzes/root,beniz/root,olifre/root,davidlt/root,thomaskeck/root,davidlt/root,pspe/root,gganis/root,beniz/root,bbockelm/root,pspe/root,thomaskeck/root,gbitzes/root,CristinaCristescu/root,agarciamontoro/root,esakellari/root,olifre/root,mkret2/root,abhinavmoudgil95/root,georgtroska/root,root-mirror/root,root-mirror/root,beniz/root,mattkretz/root,abhinavmoudgil95/root,thomaskeck/root,jrtomps/root,zzxuanyuan/root-compressor-dummy,mattkretz/root,pspe/root,sawenzel/root,pspe/root,zzxuanyuan/root-compressor-dummy,CristinaCristescu/root,mhuwiler/rootauto,root-mirror/root,thomaskeck/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root-compressor-dummy,agarciamontoro/root,jrtomps/root,Y--/root,olifre/root,zzxuanyuan/root-compressor-dummy,krafczyk/root,veprbl/root,satyarth934/root,jrtomps/root,buuck/root,mhuwiler/rootauto,beniz/root,lgiommi/root,root-mirror/root,bbockelm/root,olifre/root,simonpf/root,georgtroska/root,esakellari/root,olifre/root,krafczyk/root,davidlt/root,zzxuanyuan/root,karies/root,karies/root,gganis/root,gbitzes/root,zzxuanyuan/root,esakellari/root,satyarth934/root,zzxuanyuan/root,CristinaCristescu/root,buuck/root,abhinavmoudgil95/root,davidlt/root,gganis/root,mkret2/root,thomaskeck/root,BerserkerTroll/root,BerserkerTroll/root,jrtomps/root,karies/root,gbitzes/root,agarciamontoro/root,agarciamontoro/root,simonpf/root,zzxuanyuan/root,simonpf/root,lgiommi/root,georgtroska/root,krafczyk/root,krafczyk/root,esakellari/root,karies/root,simonpf/root,zzxuanyuan/root,jrtomps/root,davidlt/root,simonpf/root,mkret2/root,thomaskeck/root,pspe/root,zzxuanyuan/root-compressor-dummy,sawenzel/root,mhuwiler/rootauto,agarciamontoro/root,root-mirror/root,bbockelm/root,abhinavmoudgil95/root,beniz/root,bbockelm/root,karies/root,satyarth934/root,georgtroska/root,mkret2/root,zzxuanyuan/root,Y--/root,root-mirror/root,georgtroska/root,sawenzel/root,esakellari/root,gbitzes/root,Y--/root,thomaskeck/root,zzxuanyuan/root,abhinavmoudgil95/root,mkret2/root,satyarth934/root,bbockelm/root,abhinavmoudgil95/root,CristinaCristescu/root,Y--/root,mhuwiler/rootauto,krafczyk/root,mkret2/root,esakellari/root,BerserkerTroll/root,georgtroska/root,sawenzel/root,agarciamontoro/root,pspe/root,root-mirror/root,mattkretz/root,pspe/root,simonpf/root,veprbl/root,mkret2/root,beniz/root,esakellari/root,zzxuanyuan/root,davidlt/root,bbockelm/root,zzxuanyuan/root,krafczyk/root,Y--/root,karies/root,simonpf/root,jrtomps/root,veprbl/root,abhinavmoudgil95/root,gganis/root,sawenzel/root,BerserkerTroll/root,lgiommi/root,sawenzel/root,simonpf/root,BerserkerTroll/root,olifre/root,esakellari/root,mkret2/root,CristinaCristescu/root,buuck/root,Y--/root,gbitzes/root,bbockelm/root,pspe/root,sawenzel/root,BerserkerTroll/root,mhuwiler/rootauto,thomaskeck/root,pspe/root,veprbl/root,buuck/root,georgtroska/root,zzxuanyuan/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root-compressor-dummy,CristinaCristescu/root,mattkretz/root,beniz/root,karies/root,bbockelm/root,gganis/root,beniz/root,agarciamontoro/root,mattkretz/root,BerserkerTroll/root,buuck/root,BerserkerTroll/root,mattkretz/root,jrtomps/root,mhuwiler/rootauto,BerserkerTroll/root,root-mirror/root,lgiommi/root,davidlt/root,bbockelm/root,gganis/root,georgtroska/root,beniz/root,satyarth934/root,thomaskeck/root,buuck/root,karies/root,lgiommi/root,mkret2/root,simonpf/root,zzxuanyuan/root-compressor-dummy,jrtomps/root,BerserkerTroll/root,simonpf/root,satyarth934/root,krafczyk/root,gbitzes/root,zzxuanyuan/root,zzxuanyuan/root-compressor-dummy,veprbl/root,mhuwiler/rootauto,BerserkerTroll/root,jrtomps/root,georgtroska/root,veprbl/root,buuck/root,gganis/root,CristinaCristescu/root,veprbl/root,georgtroska/root,georgtroska/root,jrtomps/root,krafczyk/root,krafczyk/root,gganis/root,veprbl/root,sawenzel/root,bbockelm/root,davidlt/root,veprbl/root,lgiommi/root,krafczyk/root,buuck/root,lgiommi/root,satyarth934/root,karies/root,gbitzes/root,pspe/root,davidlt/root,mhuwiler/rootauto,mkret2/root,jrtomps/root,zzxuanyuan/root-compressor-dummy,mhuwiler/rootauto,agarciamontoro/root,buuck/root,davidlt/root,zzxuanyuan/root,olifre/root,CristinaCristescu/root,satyarth934/root,Y--/root,Y--/root,abhinavmoudgil95/root,root-mirror/root,agarciamontoro/root,pspe/root,esakellari/root,mkret2/root,lgiommi/root,mattkretz/root,satyarth934/root,mattkretz/root,sawenzel/root,root-mirror/root,karies/root,simonpf/root,lgiommi/root,Y--/root,krafczyk/root,veprbl/root,Y--/root,buuck/root,satyarth934/root,CristinaCristescu/root,CristinaCristescu/root,esakellari/root,satyarth934/root,lgiommi/root,abhinavmoudgil95/root,esakellari/root,thomaskeck/root,CristinaCristescu/root,olifre/root,mhuwiler/rootauto,olifre/root,beniz/root,davidlt/root,veprbl/root,gbitzes/root,gbitzes/root,gganis/root,gbitzes/root,beniz/root,gganis/root,olifre/root
2ea9a52b16694b87e70ea40b53d65139dca21d69
tests/dummy/app/controllers/embed-test.js
tests/dummy/app/controllers/embed-test.js
import Ember from 'ember'; export default Ember.Controller.extend({ fetchedNode: null, fetchedChild: null, actions: { fetchNodePreprintsEmbedded() { this.store.findRecord('node', 'ee2t9').then((node) => { this.set('fetchedNode', node); }); }, fetchNodeParentEmbedded() { this.store.findRecord('node', 'pe8s6').then((node) => { this.set('fetchedChild', node); }); } } });
import Ember from 'ember'; export default Ember.Controller.extend({ fetchedNode: null, fetchedChild: null, actions: { fetchNodePreprintsEmbedded() { this.store.findRecord('node', '7gzxb', {include: 'preprints'}).then((node) => { this.set('fetchedNode', node); }); }, fetchNodeParentEmbedded() { this.store.findRecord('node', 'ddyuz', {include: 'parent'}).then((node) => { this.set('fetchedChild', node); }); } } });
Update dummy app to use included resources.
Update dummy app to use included resources.
JavaScript
apache-2.0
jamescdavis/ember-osf,chrisseto/ember-osf,binoculars/ember-osf,binoculars/ember-osf,CenterForOpenScience/ember-osf,CenterForOpenScience/ember-osf,baylee-d/ember-osf,baylee-d/ember-osf,crcresearch/ember-osf,chrisseto/ember-osf,jamescdavis/ember-osf,crcresearch/ember-osf
fd1c175f514530902d9d84d498f1e0feb2662164
src/draft.js
src/draft.js
var Draft = { mixins: {}, // TODO:50 test safety checks for Draft.px() px: function(val) { var num = parseFloat(val, 10); var units = testUnits(val); // Remain unchanged if units are already px if (units == 'px') { return num; } // Points and picas (pt, pc) else if (units == 'pt') { return Draft.px(num / 72 + 'in'); } else if (units == 'pc') { return Draft.px(num * 12 + 'pt'); } // Imperial units (in, ft, yd, mi) else if (units == 'in') { return num * defaults.dpi; } else if (units == 'ft') { return Draft.px(num * 12 + 'in'); } else if (units == 'yd') { return Draft.px(num * 3 + 'ft'); } else if (units == 'mi') { return Draft.px(num * 1760 + 'yd'); } // Metric units (mm, cm, m, km) else if (units.endsWith('m')) { if (units == 'mm') { num *= 1; } else if (units == 'cm') { num *= 10; } else if (units == 'km') { num *= 1000000; } return Draft.px(num / 25.4 + 'in'); } else { return undefined; } } };
var Draft = { mixins: {}, // TODO:50 test safety checks for Draft.px() px: function(val) { var num = parseFloat(val, 10); var units = testUnits(val); switch (units) { // Remain unchanged if units are already px case 'px': return num; // Points and picas (pt, pc) case 'pc': num *= 12; // Falls through case 'pt': num /= 72; break; // Metric units (mm, cm, dm, m, km) case 'km': num *= 1000; // Falls through case 'm': num *= 10; // Falls through case 'dm': num *= 10; // Falls through case 'cm': num *= 10; // Falls through case 'mm': num /= 25.4; break; // Imperial units (in, ft, yd, mi) case 'mi': num *= 1760; // Falls through case 'yd': num *= 3; // Falls through case 'ft': num *= 12; // Falls through case 'in': break; default: return undefined; } return num * Draft.defaults.dpi; } };
Use switch statement for Draft.px()
Use switch statement for Draft.px()
JavaScript
mit
D1SC0tech/draft.js,D1SC0tech/draft.js
9c9c05568a6d59b49d14871106b78983947c5a08
samples/composition/field.js
samples/composition/field.js
import {Block} from '../../dist/cyclow' import Confirm from './confirm' const Field = () => Block({ outputs: ['submission'], components: {confirm: Confirm()}, on: { init: instruction => [state => ({instruction, input: ''}), 'confirm.init'], text: newText => state => ({...state, input: newText}), 'confirm.confirmation': (_, {input}) => [['out.submission', input]], state: ({input}) => [['confirm.disabled', !input]] }, view: ({instruction, input}, {confirm}) => ({content: [ `${instruction}:`, { tag: 'input', attrs: {id: 'field', value: input}, on: {keyup: (e, next) => next(['text', e.target.value])} }, confirm ]}) }) export default Field
import {Block} from '../../dist/cyclow' import Confirm from './confirm' const Field = () => Block({ outputs: ['submission'], components: {confirm: Confirm()}, on: { init: instruction => [state => ({instruction, input: ''}), 'confirm.init'], text: newText => state => ({...state, input: newText}), 'confirm.confirmation': (_, {input}) => [ ['out.submission', input], state => ({...state, input: ''}) ], state: ({input}) => [['confirm.disabled', !input]] }, view: ({instruction, input}, {confirm}) => ({content: [ `${instruction}:`, { tag: 'input', attrs: {id: 'field', value: input}, on: {keyup: (e, next) => next(['text', e.target.value])} }, confirm ]}) }) export default Field
Clear inputbox after click Confirm button
Clear inputbox after click Confirm button
JavaScript
mit
pmros/cyclow,pmros/cyclow
3cfa25602973dc839bbe43e306115bf51e78bb5a
src/index.js
src/index.js
import syntax from '@babel/plugin-syntax-jsx' import pureAnnotation from './visitors/pure' import minify from './visitors/minify' import displayNameAndId from './visitors/displayNameAndId' import templateLiterals from './visitors/templateLiterals' import assignStyledRequired from './visitors/assignStyledRequired' import transpileCssProp from './visitors/transpileCssProp' export default function({ types: t }) { return { inherits: syntax, visitor: { // These visitors insert newly generated code and missing import/require statements Program: { enter(path, state) { state.required = false }, }, JSXAttribute(path, state) { transpileCssProp(t)(path, state) }, CallExpression(path, state) { displayNameAndId(t)(path, state) pureAnnotation(t)(path, state) }, TaggedTemplateExpression(path, state) { minify(t)(path, state) displayNameAndId(t)(path, state) templateLiterals(t)(path, state) pureAnnotation(t)(path, state) }, VariableDeclarator(path, state) { assignStyledRequired(t)(path, state) }, }, } }
import syntax from '@babel/plugin-syntax-jsx' import pureAnnotation from './visitors/pure' import minify from './visitors/minify' import displayNameAndId from './visitors/displayNameAndId' import templateLiterals from './visitors/templateLiterals' import assignStyledRequired from './visitors/assignStyledRequired' import transpileCssProp from './visitors/transpileCssProp' export default function({ types: t }) { return { inherits: syntax, visitor: { JSXAttribute(path, state) { transpileCssProp(t)(path, state) }, CallExpression(path, state) { displayNameAndId(t)(path, state) pureAnnotation(t)(path, state) }, TaggedTemplateExpression(path, state) { minify(t)(path, state) displayNameAndId(t)(path, state) templateLiterals(t)(path, state) pureAnnotation(t)(path, state) }, VariableDeclarator(path, state) { assignStyledRequired(t)(path, state) }, }, } }
Remove unnecessary default of state.required to false
Remove unnecessary default of state.required to false
JavaScript
mit
styled-components/babel-plugin-styled-components
7b6f1d8ba03d1e83ded3a1d0f1ee3693d70c1d52
src/index.js
src/index.js
var creep = exports; var _ = require('lodash'); var config = require('./config'); require('./filters/js'); require('./filters/coffee'); require('./parsers/matter'); creep.config = require('./config'); creep.crawl = require('./crawl'); creep.query = require('./query'); creep.filters = require('./filters'); creep.parsers = require('./parsers'); creep.utils = require('./utils'); creep.list = function(query) { }; creep.link = function(query) { }; creep.unlink = function(query) { }; _.each(config.parsers, function(parser, name) { creep.parsers.register.exts(name, parser.exts); });
var creep = exports; var _ = require('lodash'); var config = require('./config'); require('./filters/js'); require('./filters/coffee'); require('./parsers/matter'); creep.config = require('./config'); creep.crawl = require('./crawl'); creep.query = require('./query'); creep.filters = require('./filters'); creep.parsers = require('./parsers'); creep.utils = require('./utils'); _.each(config.parsers, function(parser, name) { creep.parsers.register.exts(name, parser.exts); });
Remove old api method stubs that won't be happening anymore
Remove old api method stubs that won't be happening anymore
JavaScript
mit
justinvdm/creep
9869a9e02b379a6b3fd4d536f67d2b9d5be0f4af
src/index.js
src/index.js
// External dependencies const os = require('os'); const Koa = require('koa'); const send = require('koa-send'); const logger = require('koa-logger'); const assert = require('assert'); const debug = require('debug')('reviewly'); // Internal modules const config = require('./config')(); assert(!!config, `config needs to be defined for ${ process.env.NODE_ENV }`); // Setup the app const app = new Koa(); const rootFolder = process.env.ROOT_FOLDER || os.homedir(); // Add middleware app.use(logger()); // Serve folder based on subdomain app.use(async (ctx) => { const subdomains = ctx.req.headers.host.split('.'); const featureName = subdomains[0]; const path = ctx.path === '/' ? 'index.html' : ctx.path; debug('rootFolder', rootFolder, 'featureName', featureName, 'path', path); // TODO NRT: Verify the resource exists, if not, return index.html await send(ctx, path, { root: `${ rootFolder }/${ featureName }` }); }); // Start server app.listen(config.port, () => /* eslint-disable no-console */ console.log(`Reviewly successfuly started on port ${ config.port } with NODE_ENV ${ process.env.NODE_ENV }`) /* eslint-enable no-console */); // Export server to allow testing module.exports = app;
// External dependencies const os = require('os'); const Koa = require('koa'); const send = require('koa-send'); const logger = require('koa-logger'); const assert = require('assert'); const debug = require('debug')('reviewly'); // Internal modules const config = require('./config')(); assert(!!config, `config needs to be defined for ${ process.env.NODE_ENV }`); // Setup the app const app = new Koa(); const rootFolder = process.env.ROOT_FOLDER || os.homedir(); // Add middleware app.use(logger()); // Serve folder based on subdomain app.use(async (ctx) => { const subdomains = ctx.req.headers.host.split('.'); const featureName = subdomains[1]; const path = ctx.path === '/' ? 'index.html' : ctx.path; debug('rootFolder', rootFolder, 'featureName', featureName, 'path', path); // TODO NRT: Verify the resource exists, if not, return index.html await send(ctx, path, { root: `${ rootFolder }/${ featureName }` }); }); // Start server app.listen(config.port, () => /* eslint-disable no-console */ console.log(`Reviewly successfuly started on port ${ config.port } with NODE_ENV ${ process.env.NODE_ENV }`) /* eslint-enable no-console */); // Export server to allow testing module.exports = app;
Use second subdomain as feature name
Use second subdomain as feature name
JavaScript
mit
mycsHQ/reviewly,mycsHQ/reviewly
889f5ec27735158e5e22c9bc72344558af8559e5
src/index.js
src/index.js
'use strict' import md5 from './md5' import fs from 'fs' const filename = process.argv[2] md5(fs.ReadStream(filename)).then((sum) => { console.log(`MD5 sum of "${filename}" is ${sum}`) })
'use strict' import md5 from './md5' import fs from 'fs' const filename = process.argv[2] md5(fs.ReadStream(filename)).then((sum) => { console.log(`MD5 sum of "${filename}" is ${sum}`) }).catch((err) => { console.log(`something is wrong: ${err}`) })
Handle error case in cli
Handle error case in cli
JavaScript
mit
ansoncat/es6-npm-demo
5aacf727f86f377cf1163e2861d647ab680b3836
src/index.js
src/index.js
import { consola } from './utils'; import initWebSocket from './initWebSocket'; import closeWebSocket from './closeWebSocket'; import * as types from './types'; export * from './types'; const createMiddleware = () => { let websocket; return store => next => (action) => { switch (action.type) { case types.WEBSOCKET_CONNECT: websocket = closeWebSocket(websocket); websocket = initWebSocket(store, action.payload); return next(action); case types.WEBSOCKET_SEND: if (websocket) { websocket.send(JSON.stringify(action.payload)); } consola.warn('WebSocket is not open. To open, dispatch action WEBSOCKET_CONNECT.'); return next(action); case types.WEBSOCKET_DISCONNECT: websocket = closeWebSocket(websocket); return next(action); default: return next(action); } }; }; export default createMiddleware();
import { consola } from './utils'; import initWebSocket from './initWebSocket'; import closeWebSocket from './closeWebSocket'; import * as types from './types'; export * from './types'; const createMiddleware = () => { let websocket; return store => next => (action) => { switch (action.type) { case types.WEBSOCKET_CONNECT: websocket = closeWebSocket(websocket); websocket = initWebSocket(store, action.payload); return next(action); case types.WEBSOCKET_SEND: if (websocket) { websocket.send(JSON.stringify(action.payload)); } else { consola.warn('WebSocket is not open. To open, dispatch action WEBSOCKET_CONNECT.'); } return next(action); case types.WEBSOCKET_DISCONNECT: websocket = closeWebSocket(websocket); return next(action); default: return next(action); } }; }; export default createMiddleware();
Correct warning print to only happen if the socket is not available.
Correct warning print to only happen if the socket is not available.
JavaScript
mit
iamgutz/web-redux-socket
b66dd722c9222a3ace2830ebb049dc621ae3df4d
src/store.js
src/store.js
import { createStore, compose, applyMiddleware } from 'redux'; import generateCards from './middlewares/generateCards.js'; import calculateScore from './middlewares/calculateScore.js'; import createLogger from 'redux-logger'; import reducer from './reducers/index.js'; const configureStore = initialState => { const logger = createLogger(); return compose( applyMiddleware(logger, generateCards, calculateScore), window.devToolsExtension ? window.devToolsExtension() : f => f )(createStore)(reducer, initialState); }; export default configureStore;
import { createStore, compose, applyMiddleware } from 'redux'; import generateCards from './middlewares/generateCards.js'; import calculateScore from './middlewares/calculateScore.js'; import createLogger from 'redux-logger'; import reducer from './reducers/index.js'; const configureStore = initialState => { const logger = createLogger(); return compose( applyMiddleware(logger, generateCards, calculateScore), typeof window === 'object' && typeof window.devToolsExtension !== 'undefined' ? window.devToolsExtension() : f => f )(createStore)(reducer, initialState); }; export default configureStore;
Check window before referencing it to prevent issues when running in Node
Check window before referencing it to prevent issues when running in Node
JavaScript
mit
iamakulov/Colr,iamakulov/Colr
25878d12becb0de97547d05042d578a03360f382
test/test.js
test/test.js
var fs = require('fs') var test = require('tap').test var walkSync = require('../') test('walkSync', function (t) { t.deepEqual(walkSync('fixtures'), [ 'dir/', 'dir/bar.txt', 'dir/subdir/', 'dir/subdir/baz.txt', 'dir/zzz.txt', 'foo.txt', 'symlink1', 'symlink2' ]) t.end() })
var fs = require('fs') var test = require('tap').test var walkSync = require('../') test('walkSync', function (t) { t.deepEqual(walkSync('fixtures'), [ 'dir/', 'dir/bar.txt', 'dir/subdir/', 'dir/subdir/baz.txt', 'dir/zzz.txt', 'foo.txt', 'symlink1', 'symlink2' ]) t.throws(function () { walkSync('doesnotexist') }, { name: 'Error', message: "ENOENT, no such file or directory 'doesnotexist/'" }) t.throws(function () { walkSync('fixtures/foo.txt') }, { name: 'Error', message: "ENOTDIR, not a directory 'fixtures/foo.txt/'" }) t.end() })
Test failure modes as well
Test failure modes as well
JavaScript
mit
stefanpenner/node-walk-sync,greyhwndz/node-walk-sync,joliss/node-walk-sync,chadhietala/node-walk-sync,joliss/node-walk-sync
addf7a7e917f1932076e28c16fde788f1d77592e
github.js
github.js
module.exports = { 'GitHub example testing': function (test) { test .open('https://github.com') .waitForElement('input[name=q]') .assert.title().is('GitHub · Build software better, together.', 'GitHub has the correct page title!') .type('input[name=q]', 'dalekjs') .submit('.js-site-search-form') .assert.text('.sort-bar > h3:nth-child(2)', 'We\'ve found 53 repository results') .waitFor(function() { return $('li.repo-list-item:nth-child(1) > h3:nth-child(2) > a:nth-child(1)').text() === 'dalekjs/dalek' }) .done(); } };
module.exports = { 'GitHub example testing': function (test) { test .open('https://github.com') .waitForElement('input[name=q]') .assert.title().is('GitHub · Build software better, together.', 'GitHub has the correct page title!') .type('input[name=q]', 'dalekjs') .submit('.js-site-search-form') .waitFor(function() { return $('li.repo-list-item:nth-child(1) > h3:nth-child(2) > a:nth-child(1)').text() === 'dalekjs/dalek' }) .assert.text('.sort-bar > h3:nth-child(2)', 'We\'ve found 53 repository results') .done(); } };
Change execution order within test
Change execution order within test
JavaScript
mit
jorilytter/dalekjs-example
f6963995c7feabcd861cfbfc3f4e5b3d0ecb0c76
bin/commands/new.js
bin/commands/new.js
var chalk = require('chalk'); var inquirer = require('inquirer'); var fs = require('fs-extra'); var path = require('path'); module.exports = function(libDir) { return { init: init }; function init(name) { console.log('Creating a new project: %s', chalk.underline(name)); inquirer.prompt([{ type: "confirm", name: "needTravis", message: "Copying over files to current directory. Press enter to confirm", default: true }], function(answers) { console.log('copying over files...'); fs.copy(libDir, process.cwd(), function (err) { if (err) return console.error(err) console.log("success! - files copied"); }) }) } }
var chalk = require('chalk'); var inquirer = require('inquirer'); var fs = require('fs-extra'); var path = require('path'); var PROMPT_OPTIONS = [{ type: "confirm", name: "okToCopyFiles", message: "Copying over files to current directory. Press enter to confirm", default: true }] module.exports = function(libDir) { return { init: init }; function init(name) { console.log('Creating a new project: %s', chalk.underline(name)); inquirer.prompt(PROMPT_OPTIONS, inquirerCallback) } function inquirerCallback(answers) { console.log('copying over files...'); fs.copy(libDir, process.cwd(), function (err) { if (err) return console.error(err) console.log("success! - files copied"); }) } }
Add prompts to array. Split up copy code into function
refactor: Add prompts to array. Split up copy code into function
JavaScript
mit
cartridge/cartridge-cli,code-computerlove/quarry,code-computerlove/slate-cli
a78255c69510a0aef4d0636aed113f10896d901a
app/client/src/dl-tools/components/import-people-from-jira/import-from-jira.component.js
app/client/src/dl-tools/components/import-people-from-jira/import-from-jira.component.js
define([ '@shared/people' ], function() { function createPersonDataFromJiraUser(jiraUser) { return { full_name: jiraUser.displayName, email: jiraUser.email, username: jiraUser.name, avatar: jiraUser.avatarUrls ? jiraUser.avatarUrls['48x48'] : null }; } return { /* @ngInject */ controller($rootScope, PeopleApi, PersonApi, JiraDataSource) { this.importPerson = (jiraUser) => { return JiraDataService.getApiClient().user() .get({ username: jiraUser.name }, function(jiraUser) { let personData = createPersonDataFromJiraUser(jiraUser); let saveHandlers = [() => { $rootScope.$broadcast('people-changed'); }, () => { // todo: publish a global message. }]; PersonApi.get({id: '@' + personData.username}).$promise .then(person => { Object.assign(person, personData); person.$update({id: person.id}, ...saveHandlers); }, () => { PeopleApi.create(personData, ...saveHandlers); }); }); }; }, templateUrl: 'dl-tools/components/import-people-from-jira/import-from-jira.tpl.html', bindings: { people: '<' }, }; });
define([ '@shared/people' ], function() { function createPersonDataFromJiraUser(jiraUser) { return { full_name: jiraUser.displayName, email: jiraUser.email, username: jiraUser.name, avatar: jiraUser.avatarUrls ? jiraUser.avatarUrls['48x48'] : null }; } return { /* @ngInject */ controller($rootScope, PeopleApi, PersonApi, JiraDataSource) { this.importPerson = (jiraUser) => { return JiraDataSource.getApiClient().user() .get({ username: jiraUser.name }, function(jiraUser) { let personData = createPersonDataFromJiraUser(jiraUser); let saveHandlers = [() => { $rootScope.$broadcast('people-changed'); }, () => { // todo: publish a global message. }]; PersonApi.get({id: '@' + personData.username}).$promise .then(person => { Object.assign(person, personData); person.$update({id: person.id}, ...saveHandlers); }, () => { PeopleApi.create(personData, ...saveHandlers); }); }); }; }, templateUrl: 'dl-tools/components/import-people-from-jira/import-from-jira.tpl.html', bindings: { people: '<' }, }; });
Change JiraDataService to JiraDataSource in @dl-tools/import-people-from-jira
Change JiraDataService to JiraDataSource in @dl-tools/import-people-from-jira
JavaScript
mit
highpine/highpine,highpine/highpine,highpine/highpine
19767ec9cd7f5692dac46743fa616c4a877f8b05
public/app/main.js
public/app/main.js
(function () { 'use strict'; // Initialise RequireJS module loader require.config({ urlArgs: 'm=' + (new Date()).getTime(), baseUrl: '/app/', paths: { // RequireJS extensions text: '../lib/text/text', // Vendor libraries knockout: '../lib/knockout/dist/knockout.debug', lodash: '../lib/lodash/lodash', jquery: '../lib/jquery/dist/jquery', bootstrap: '../lib/bootstrap/dist/js/bootstrap', typeahead: '../lib/typeahead.js/dist/typeahead.jquery', bloodhound: '../lib/typeahead.js/dist/bloodhound', page: '../lib/page/page', // Application modules config: 'config/', models: 'models/', services: 'services/', ui: 'ui/', util: 'util/' }, shim: { bloodhound: { exports: 'Bloodhound' }, typeahead: { deps: [ 'jquery' ] } } }); // Boot the application require([ 'jquery' ], function () { require([ 'bootstrap' ], function () { var environment = 'development'; if (environment !== 'production') { console.log('Running in "' + environment + '" environment'); } require([ 'config/env/' + environment, 'util/router' ], function (configure, router) { configure(); router(); }); }); }); }());
(function () { 'use strict'; // Initialise RequireJS module loader require.config({ urlArgs: 'm=' + (new Date()).getTime(), baseUrl: '/app/', paths: { // RequireJS extensions text: '../lib/text/text', // Vendor libraries knockout: '../lib/knockout/dist/knockout.debug', lodash: '../lib/lodash/lodash', jquery: '../lib/jquery/dist/jquery', bootstrap: '../lib/bootstrap/dist/js/bootstrap', typeahead: '../lib/typeahead.js/dist/typeahead.jquery', bloodhound: '../lib/typeahead.js/dist/bloodhound', page: '../lib/page/page', // Application modules config: 'config/', models: 'models/', services: 'services/', ui: 'ui/', util: 'util/' }, shim: { bloodhound: { exports: 'Bloodhound' }, typeahead: { deps: [ 'jquery' ] } } }); // Boot the application require([ 'jquery' ], function () { require([ 'bootstrap' ], function () { var environment = 'development'; if (environment !== 'production' && console && typeof console.log === 'function') { console.log('Running in "' + environment + '" environment'); } require([ 'config/env/' + environment, 'util/router' ], function (configure, router) { configure(); router(); }); }); }); }());
Add safety check for `console.log` on app startup.
Add safety check for `console.log` on app startup.
JavaScript
mit
rwahs/research-frontend,rwahs/research-frontend
eddb477cb6da9c97204586d4733823a66acd7a6b
app/models/location_model.js
app/models/location_model.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var LocationSchema = new Schema({ name: String, city: String, address: String, img: String, description: String, }); LocationSchema.set("_perms", { admin: "crud", user: "r", all: "r" }); module.exports = mongoose.model('Location', LocationSchema);
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var LocationSchema = new Schema({ name: String, city: String, address: String, img: String, description: String, email: String, }); LocationSchema.set("_perms", { admin: "crud", user: "r", all: "r" }); module.exports = mongoose.model('Location', LocationSchema);
Add email address to location
Add email address to location
JavaScript
mit
10layer/jexpress,10layer/jexpress
49f8b491762c09ab6bb58c5268a8b009d8b0a22d
app/services/http-service.js
app/services/http-service.js
'use strict'; module.exports = function(app) { app.factory('httpService', function($http, $location) { // Generic helper function var http = function(method, params) { params.id = params.id || ''; var promise = $http[method]('/api/0_0_1/data/' + params.id, params.data) .error(function(error, status) { console.log('Error in http ' + method + ': ' + error + ' | status ' + status); if (status === 401) { $location.path('/signin'); } }); return promise; }; // Specific verbs var httpVerbs = { get: function() { return http('get', {}); }, post: function(data) { return http('post', { data: data }); }, put: function(data) { return http('put', { data: data, id: data._id }); }, delete: function(data) { return http('delete', { id: data._id }); } }; return httpVerbs; }); };
'use strict'; /** * DRY out REST requests to the data API */ module.exports = function(app) { app.factory('httpService', function($http, $location) { // Generic helper function var http = function(method, params) { params.id = params.id || ''; var promise = $http[method]('/api/0_0_1/data/' + params.id, params.data) .error(function(error, status) { console.log('Error in http ' + method + ': ' + error + ' | status ' + status); if (status === 401) { $location.path('/signin'); } }); return promise; }; // Specific verbs var httpVerbs = { get: function() { return http('get', {}); }, post: function(data) { return http('post', { data: data }); }, put: function(data) { return http('put', { data: data, id: data._id }); }, delete: function(data) { return http('delete', { id: 'delete/' + data._id }); }, // Dev only deleteAll: function() { return http('delete', { id: 'deleteAll' }); } }; return httpVerbs; }); };
Add deleteAll() as its own method
Add deleteAll() as its own method
JavaScript
mit
Sextant-WDB/sextant-ng
b319a78a3c84f8bb1e27343ed45190610640a9dc
app/services/ilios-config.js
app/services/ilios-config.js
import Ember from 'ember'; const { inject, computed } = Ember; const { service } = inject; export default Ember.Service.extend({ ajax: service(), config: computed(function(){ var url = '/application/config'; const ajax = this.get('ajax'); return ajax.request(url); }), itemFromConfig(key){ return this.get('config').then(config => { return config.config[key]; }); }, userSearchType: computed('config.userSearchType', function(){ return this.itemFromConfig('userSearchType'); }), authenticationType: computed('config.type', function(){ return this.itemFromConfig('type'); }), maxUploadSize: computed('config.maxUploadSize', function(){ return this.itemFromConfig('maxUploadSize'); }), apiVersion: computed('config.apiVersion', function(){ return this.itemFromConfig('apiVersion'); }) });
import Ember from 'ember'; const { inject, computed, isPresent } = Ember; const { service } = inject; export default Ember.Service.extend({ ajax: service(), serverVariables: service(), config: computed('apiHost', function(){ const apiHost = this.get('apiHost'); const url = apiHost + '/application/config'; const ajax = this.get('ajax'); return ajax.request(url); }), itemFromConfig(key){ return this.get('config').then(config => { return config.config[key]; }); }, userSearchType: computed('config.userSearchType', function(){ return this.itemFromConfig('userSearchType'); }), authenticationType: computed('config.type', function(){ return this.itemFromConfig('type'); }), maxUploadSize: computed('config.maxUploadSize', function(){ return this.itemFromConfig('maxUploadSize'); }), apiVersion: computed('config.apiVersion', function(){ return this.itemFromConfig('apiVersion'); }), apiNameSpace: computed('serverVariables.apiNameSpace', function(){ const serverVariables = this.get('serverVariables'); const apiNameSpace = serverVariables.get('apiNameSpace'); if (isPresent(apiNameSpace)) { //remove trailing slashes return apiNameSpace.replace(/\/+$/, ""); } return ''; }), apiHost: computed('serverVariables.apiHost', function(){ const serverVariables = this.get('serverVariables'); const apiHost = serverVariables.get('apiHost'); if (isPresent(apiHost)) { //remove trailing slashes return apiHost.replace(/\/+$/, ""); } return ''; }), });
Put serverVariables stuff into iliosConfig
Put serverVariables stuff into iliosConfig Our config service is a better home for this information since we can control what is returned. This prevents trailing slashes from accidentally making it in as well as handles empty strings better.
JavaScript
mit
gabycampagna/frontend,jrjohnson/frontend,ilios/frontend,dartajax/frontend,gboushey/frontend,djvoa12/frontend,djvoa12/frontend,dartajax/frontend,gboushey/frontend,thecoolestguy/frontend,gabycampagna/frontend,thecoolestguy/frontend,jrjohnson/frontend,ilios/frontend
2738baf3a0a59f0108793b041ccf588ee2b15660
redef/patron-client/src/frontend/store/index.js
redef/patron-client/src/frontend/store/index.js
import { browserHistory } from 'react-router' import thunkMiddleware from 'redux-thunk' import { createStore, applyMiddleware, compose } from 'redux' import { routerMiddleware } from 'react-router-redux' import createLogger from 'redux-logger' import persistState from 'redux-localstorage' import adapter from 'redux-localstorage/lib/adapters/localStorage' import filter from 'redux-localstorage-filter' import rootReducer from '../reducers' const storage = compose( filter([ 'application.locale' ]) )(adapter(window.localStorage)) const reduxRouterMiddleware = routerMiddleware(browserHistory) let middleware = [ thunkMiddleware, reduxRouterMiddleware ] if (process.env.NODE_ENV !== 'production') { // Only apply in development mode const loggerMiddleware = createLogger() middleware = [ ...middleware, loggerMiddleware ] } const createPersistentStoreWithMiddleware = compose( applyMiddleware(...middleware), persistState(storage, 'patron-client') )(createStore) const store = createPersistentStoreWithMiddleware(rootReducer) export default store
import { browserHistory } from 'react-router' import thunkMiddleware from 'redux-thunk' import { createStore, applyMiddleware, compose } from 'redux' import { routerMiddleware } from 'react-router-redux' import createLogger from 'redux-logger' import persistState from 'redux-localstorage' import adapter from 'redux-localstorage/lib/adapters/localStorage' import filter from 'redux-localstorage-filter' import rootReducer from '../reducers' const storage = compose( filter([ 'application.locale' ]) )(adapter(window.localStorage)) const reduxRouterMiddleware = routerMiddleware(browserHistory) const middleware = [ thunkMiddleware, reduxRouterMiddleware ] if (process.env.NODE_ENV !== 'production') { const loggerMiddleware = createLogger() middleware.push(loggerMiddleware) } const store = createStore(rootReducer, compose( applyMiddleware(...middleware), persistState(storage, 'patron-client') )) export default store
Update syntax for creating the store, to harmonize with more recent examples
patron-client: Update syntax for creating the store, to harmonize with more recent examples
JavaScript
mit
digibib/ls.ext,digibib/ls.ext,digibib/ls.ext,digibib/ls.ext
08dd859dcae4ba8da26bc665ac8d90a771e7879c
scripts/behaviors/npcs/randommove.js
scripts/behaviors/npcs/randommove.js
var otherPlayers = require('../../../src/command_util.js').CommandUtil.otherPlayerInRoom; exports.listeners = { playerEnter: chooseRandomExit }; //FIXME: Occasionally causes crash because of undefined. function chooseRandomExit(room, rooms, player, players, npc) { return function(room, rooms, player, players, npc) { if (isCoinFlip()) { var exits = room.getExits(); var chosen = getRandomFromArr(exits); if (!chosen.hasOwnProperty('mob_locked')) { var uid = npc.getUuid(); var chosenRoom = rooms.getAt(chosen.location); npc.setRoom(chosen.location); chosenRoom.addNpc(uid); room.removeNpc(uid); player.say(npc.getShortDesc(player.getLocale()) + getLeaveMessage( player, chosenRoom)); players.eachIf( otherPlayers.bind( null, player), function(p) { p.say(npc.getShortDesc( p.getLocale()) + getLeaveMessage(p, chosenRoom)) }); } } } } function getLeaveMessage(player, chosenRoom) { if (chosenRoom && chosenRoom.title) return ' leaves for ' + chosenRoom.title[player.getLocale()]; return ' leaves.' } //TODO: Candidates for utilification. function isCoinFlip() { return Math.round(Math.random()); } function getRandomFromArr(arr) { return arr[Math.floor(Math.random() * arr.length)]; }
var otherPlayers = require('../../../src/command_util.js').CommandUtil.otherPlayerInRoom; exports.listeners = { playerEnter: chooseRandomExit }; function chooseRandomExit(room, rooms, player, players, npc) { return function(room, rooms, player, players, npc) { if (isCoinFlip()) { var exits = room.getExits(); var chosen = getRandomFromArr(exits); if (!chosen.hasOwnProperty('mob_locked')) { var uid = npc.getUuid(); var chosenRoom = rooms.getAt(chosen.location); try { npc.setRoom(chosen.location); chosenRoom.addNpc(uid); room.removeNpc(uid); player.say(npc.getShortDesc(player.getLocale()) + getLeaveMessage( player, chosenRoom)); players.eachIf( otherPlayers.bind( null, player), function(p) { p.say(npc.getShortDesc( p.getLocale()) + getLeaveMessage(p, chosenRoom)) }); } catch(e) { console.log("EXCEPTION: ", e); console.log("NPC: ", npc); } } } } } function getLeaveMessage(player, chosenRoom) { if (chosenRoom && chosenRoom.title) return ' leaves for ' + chosenRoom.title[player.getLocale()]; return ' leaves.' } //TODO: Candidates for utilification. function isCoinFlip() { return Math.round(Math.random()); } function getRandomFromArr(arr) { return arr[Math.floor(Math.random() * arr.length)]; }
Add error handling to random move.
Add error handling to random move.
JavaScript
mit
seanohue/ranviermud,seanohue/ranviermud,shawncplus/ranviermud
34256c37fd75062ad09b178e2bcc7c5669a2fc1e
routes/prototype_170331/overseas-first/steps.js
routes/prototype_170331/overseas-first/steps.js
module.exports = { '/':{ fields: ['age-day', 'age-year', 'age-month'], backLink: '../filter-common/what-do-you-want-to-do-overseas', next: '/issued' }, '/issued':{ fields: ['issuing-authority', 'expiry-year', 'expiry-month'], backLink: './', next: '/country-born' }, '/country-born': { controller: require('../../../controllers/application-country'), controller: require('../../../controllers/go-overseas'), fields: ['application-country'], backLink: './issued', next: 'france-first', nextAlt: 'france-first', nextAltAltAlt: 'spain-first' /* if they are from Spain - first hidden as renewal */ }, '/france-first': { backLink: './country-born', }, '/spain-first': { backLink: './country-born', } };
module.exports = { '/':{ fields: ['age-day', 'age-year', 'age-month'], backLink: '../filter-common/what-do-you-want-to-do-overseas', next: '/country-born' }, '/issued':{ fields: ['issuing-authority', 'expiry-year', 'expiry-month'], backLink: './', next: '/country-born' }, '/country-born': { controller: require('../../../controllers/application-country'), controller: require('../../../controllers/go-overseas'), fields: ['application-country'], backLink: './', next: 'france-first', nextAlt: 'france-first', nextAltAltAlt: 'spain-first' /* if they are from Spain - first hidden as renewal */ }, '/france-first': { backLink: './country-born', }, '/spain-first': { backLink: './country-born', } };
Fix for overseas first - to skip the issued question
Fix for overseas first - to skip the issued question
JavaScript
mit
UKHomeOffice/passports-prototype,UKHomeOffice/passports-prototype
b71ef6056b343a2fb129105f7048d6f369368e07
server/app/models/Session.js
server/app/models/Session.js
import Sequelize from 'sequelize'; import db from '../db'; const Session = db.define( 'Session', { id: { type: Sequelize.STRING(255), primaryKey: true, }, expires: { type: Sequelize.INTEGER.UNSIGNED, allowNull: false, }, data: { type: Sequelize.TEXT, allowNull: false, }, }, { charset: 'ascii', collate: 'ascii_bin', } ); export default Session;
import Sequelize from 'sequelize'; import db from '../db'; const Session = db.define( 'Session', { id: { type: Sequelize.STRING(255), primaryKey: true, }, expires: { type: Sequelize.INTEGER.UNSIGNED, allowNull: false, }, data: { type: Sequelize.TEXT, allowNull: false, }, }, { charset: 'ascii', collate: 'ascii_bin', timestamps: false, } ); export default Session;
Fix bug with sessions table: no createdAt needed
Fix bug with sessions table: no createdAt needed
JavaScript
mit
pxpeterxu/react-express-scaffolding,pxpeterxu/react-express-scaffolding,pxpeterxu/react-express-scaffolding
3c477f1e53939eb80a3b0eec39fedfed6f9abb88
app/js/arethusa/global_error_handler.js
app/js/arethusa/global_error_handler.js
"use strict"; angular.module('arethusa').factory('GlobalErrorHandler', [ '$window', '$analytics', function($window, $analytics) { var oldErrorHandler = $window.onerror; $window.onerror = function errorHandler(errorMessage, url, lineNumber) { $analytics.eventTrack(errorMessage + " @" + url + " : " + lineNumber, { category: 'error', label: errorMessage }); if (oldErrorHandler) return oldErrorHandler(errorMessage, url, lineNumber); return false; }; } ]); angular.module('arethusa').factory('$exceptionHandler', [ '$analytics', '$log', function($analytics, $log) { return function(exception, cause) { $log.error.apply($log, arguments); $analytics.eventTrack(exception + ": " + cause, { category: 'error', label: exception }); }; } ]);
"use strict"; angular.module('arethusa').factory('GlobalErrorHandler', [ '$window', '$analytics', function($window, $analytics) { var oldErrorHandler = $window.onerror; $window.onerror = function errorHandler(errorMessage, url, lineNumber) { $analytics.eventTrack(errorMessage + " @" + url + " : " + lineNumber, { category: 'error', label: errorMessage }); if (oldErrorHandler) return oldErrorHandler(errorMessage, url, lineNumber); return false; }; } ]); angular.module('arethusa').factory('$exceptionHandler', [ '$analytics', '$log', function($analytics, $log) { return function errorHandler(exception, cause) { $log.error.apply($log, arguments); var trace = printStackTrace(); $analytics.eventTrack(exception + ': ' + cause, { category: 'error', label: trace.join(', ') }); }; } ]);
Add stacktrace to error event
Add stacktrace to error event
JavaScript
mit
Masoumeh/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,Masoumeh/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,PonteIneptique/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa
a4a6c786de79919da06d0392fccbb1b2a05cb97f
addon/array-pauser.js
addon/array-pauser.js
import Em from 'ember'; import { ArrayController } from 'ember-legacy-controllers'; var get = Em.get; var copy = Em.copy; var ArrayPauser = ArrayController.extend({ isPaused: false, buffer: Em.computed(function () { return Em.A(); }), addToBuffer: function (idx, removedCount, added) { var buffer = get(this, 'buffer'); buffer.pushObject([idx, removedCount, added]); }, clearBuffer: Em.observer('isPaused', function () { var buffer = get(this, 'buffer'); var arrangedContent = get(this, 'arrangedContent'); buffer.forEach(function ([idx, removedCount, added]) { arrangedContent.replace(idx, removedCount, added); }); buffer.clear(); }), arrangedContent: Em.computed('content', function () { var content = get(this, 'content'); var clone = copy(content); return clone; }), contentArrayDidChange: function (arr, idx, removedCount, addedCount) { var added = arr.slice(idx, idx + addedCount); var isPaused = get(this, 'isPaused'); var arrangedContent; if (isPaused) { this.addToBuffer(idx, removedCount, added); } else { arrangedContent = get(this, 'arrangedContent'); arrangedContent.replace(idx, removedCount, added); } } }); export default ArrayPauser;
import Em from 'ember'; import { ArrayController } from 'ember-legacy-controllers'; var get = Em.get; var copy = Em.copy; var ArrayPauser = ArrayController.extend({ isPaused: false, buffer: Em.computed(function () { return Em.A(); }), addToBuffer: function (idx, removedCount, added) { var buffer = get(this, 'buffer'); buffer.pushObject([idx, removedCount, added]); }, clearBuffer: Em.observer('isPaused', function () { var buffer = get(this, 'buffer'); var arrangedContent = get(this, 'arrangedContent'); buffer.forEach((args) => { arrangedContent.replace(...args); }); buffer.clear(); }), arrangedContent: Em.computed('content', function () { var content = get(this, 'content'); var clone = copy(content); return clone; }), contentArrayDidChange: function (arr, idx, removedCount, addedCount) { var added = arr.slice(idx, idx + addedCount); var isPaused = get(this, 'isPaused'); var arrangedContent; if (isPaused) { this.addToBuffer(idx, removedCount, added); } else { arrangedContent = get(this, 'arrangedContent'); arrangedContent.replace(idx, removedCount, added); } } }); export default ArrayPauser;
Use array spread operator in replace method
Use array spread operator in replace method
JavaScript
mit
j-/ember-cli-array-pauser,j-/ember-cli-array-pauser
f67806ab6e2b2d21c8c36c4eef086c8452300e35
app/scripts/cliche/constants/schemas.js
app/scripts/cliche/constants/schemas.js
/** * Author: Milica Kadic * Date: 2/3/15 * Time: 3:03 PM */ 'use strict'; angular.module('registryApp.cliche') .constant('rawJob', { inputs: {}, allocatedResources: { cpu: 0, mem: 0 } }) .constant('rawTool', { 'id': '', 'class': 'CommandLineTool', '@context': 'https://github.com/common-workflow-language/common-workflow-language/blob/draft-1/specification/tool-description.md', label: '', description: '', owner: [], contributor: [], requirements: [ { 'class': 'DockerRequirement', imgRepo: '', imgTag: '', imgId: '' }, { 'class': 'CpuRequirement', value: 500 }, { 'class': 'MemRequirement', value: 1000 } ], inputs: [], outputs: [], //moved CLI adapter to root baseCommand: [''], stdin: '', stdout: '', argAdapters: [] }) .constant('rawTransform', { 'class': 'Expression', engine: '#cwl-js-engine', script: '' });
/** * Author: Milica Kadic * Date: 2/3/15 * Time: 3:03 PM */ 'use strict'; angular.module('registryApp.cliche') .constant('rawJob', { inputs: {}, allocatedResources: { cpu: 0, mem: 0 } }) .constant('rawTool', { 'id': '', 'class': 'CommandLineTool', '@context': 'https://github.com/common-workflow-language/common-workflow-language/blob/draft-1/specification/tool-description.md', label: '', description: '', owner: [], contributor: [], requirements: [ { 'class': 'DockerRequirement', imgRepo: '', imgTag: '', imgId: '' }, { 'class': 'CPURequirement', value: 1 }, { 'class': 'MemRequirement', value: 1000 } ], inputs: [], outputs: [], //moved CLI adapter to root baseCommand: [''], stdin: '', stdout: '', argAdapters: [] }) .constant('rawTransform', { 'class': 'Expression', engine: '#cwl-js-engine', script: '' });
Fix in CPU requirement naming
Fix in CPU requirement naming
JavaScript
apache-2.0
rabix/cottontail-editors,rabix/cottontail-editors
8384e09d4cc331535070790ed15cee8258f15aa8
index.ios.js
index.ios.js
import { AppRegistry, StatusBar } from 'react-native'; import Garage from './app/components/garage'; StatusBar.setBarStyle('light-content', true); AppRegistry.registerComponent('Garage', () => Garage);
import { AppRegistry, } from 'react-native'; import Garage from './app/components/garage'; AppRegistry.registerComponent('Garage', () => Garage);
Remove need to change status bar
Remove need to change status bar
JavaScript
apache-2.0
dillonhafer/garage-ios,dillonhafer/garage-ios
cdedd3830b75ee5bbeb056d79aee5e4dbb58306e
index.ios.js
index.ios.js
/** * Sample React Native App * https://github.com/facebook/react-native */ 'use strict'; import Cycle from '@cycle/core'; import {makeReactNativeDriver} from '@cycle/react-native'; import Rx from 'rx'; var React = require('react-native'); var { AppRegistry, StyleSheet, Text, View, } = React; function main ({RN}) { var count$ = RN.select('button').events('press') .startWith(0) .scan((total, _) => total + 1); return { RN: count$.map(count => ( <View style={styles.container}> <Text style={styles.welcome} selector="button">Wow such react native cycle {count}</Text> </View> )) }; } var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); Cycle.run(main, { RN: makeReactNativeDriver('MindYourBreath') });
/** * Sample React Native App * https://github.com/facebook/react-native */ 'use strict'; import Cycle from '@cycle/core'; import {makeReactNativeDriver} from '@cycle/react-native'; import Rx from 'rx'; var React = require('react-native'); var { AppRegistry, StyleSheet, Text, View, } = React; function view (count) { var dynamicStyles = StyleSheet.create({ orb: { fontSize: 20, textAlign: 'center', margin: 10, backgroundColor: '#663399', height: 200 + count * 10, width: 200 + count * 10, borderRadius: 100 + count * 5 } }) return ( <View style={styles.container}> <Text style={dynamicStyles.orb} selector="button"></Text> </View> ); } function main ({RN}) { var count$ = RN.select('button').events('press') .startWith(0) .scan((total, _) => total + 1); return { RN: count$.map(view) }; } var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, backgroundColor: '#663399', height: 200, width: 200, borderRadius: 100 }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); Cycle.run(main, { RN: makeReactNativeDriver('MindYourBreath') });
Add a purple circle that gets bigger when clicked
Add a purple circle that gets bigger when clicked
JavaScript
mit
Widdershin/mind-your-breath,Widdershin/mind-your-breath
dbe17764c812869b7217ab0c9e4cd7c345bd9401
app/app.run.js
app/app.run.js
angular.module('mewpipe') .run(run); run.$inject = ['$rootScope','$location','$auth']; function run($rootScope, $location, $auth){ $rootScope.$on('$routeChangeStart', function(event, next){ var acceptAnonymous = next.data.authentication.anonymous; var acceptConnected = next.data.authentication.connected; var isAuthenticated = $auth.isAuthenticated(); if( isAuthenticated && !acceptConnected || !isAuthenticated && !acceptAnonymous ){ //$location.path('/login'); } }); }
angular.module('mewpipe') .run(run); run.$inject = ['$rootScope','$location','$auth']; function run($rootScope, $location, $auth){ $rootScope.$on('$routeChangeStart', function(event, next){ var acceptAnonymous = next.data.authentication.anonymous; var acceptConnected = next.data.authentication.connected; var isAuthenticated = $auth.isAuthenticated(); $rootScope.isAuthenticated = isAuthenticated; if( isAuthenticated && !acceptConnected || !isAuthenticated && !acceptAnonymous ){ //$location.path('/login'); } }); }
Add isAuthenticated value in root scope
Add isAuthenticated value in root scope
JavaScript
mit
AlexandreCollet/mewpipe_webapp,AlexandreCollet/mewpipe_webapp,AlexandreCollet/mewpipe_webapp
97e6af605a1b7b4652a9ad8974ce5244d793b353
internals/testing/karma.conf.js
internals/testing/karma.conf.js
const webpackConfig = require('../webpack/webpack.test.babel'); const path = require('path'); module.exports = (config) => { config.set({ frameworks: ['mocha'], reporters: ['coverage', 'mocha'], browsers: process.env.TRAVIS // eslint-disable-line no-nested-ternary ? ['ChromeTravis'] : process.env.APPVEYOR ? ['IE'] : ['Chrome'], autoWatch: false, singleRun: true, files: [ { pattern: './test-bundler.js', watched: false, served: true, included: true, }, ], preprocessors: { ['./test-bundler.js']: ['webpack', 'sourcemap'], // eslint-disable-line no-useless-computed-key }, webpack: webpackConfig, // make Webpack bundle generation quiet webpackMiddleware: { noInfo: true, }, customLaunchers: { ChromeTravis: { base: 'Chrome', flags: ['--no-sandbox'], }, }, coverageReporter: { dir: path.join(process.cwd(), 'coverage'), reporters: [ { type: 'lcov', subdir: 'lcov' }, { type: 'html', subdir: 'html' }, { type: 'text-summary' }, ], }, }); };
const webpackConfig = require('../webpack/webpack.test.babel'); const path = require('path'); module.exports = (config) => { config.set({ frameworks: ['mocha'], reporters: ['coverage', 'mocha'], browsers: process.env.TRAVIS // eslint-disable-line no-nested-ternary ? ['ChromeTravis'] : process.env.APPVEYOR ? ['IE'] : ['Chrome'], autoWatch: false, singleRun: true, files: [ { pattern: './test-bundler.js', watched: false, served: true, included: true, }, ], preprocessors: { ['./test-bundler.js']: ['webpack', 'sourcemap'], // eslint-disable-line no-useless-computed-key }, webpack: webpackConfig, // make Webpack bundle generation quiet webpackMiddleware: { noInfo: true, stats: 'errors-only', }, customLaunchers: { ChromeTravis: { base: 'Chrome', flags: ['--no-sandbox'], }, }, coverageReporter: { dir: path.join(process.cwd(), 'coverage'), reporters: [ { type: 'lcov', subdir: 'lcov' }, { type: 'html', subdir: 'html' }, { type: 'text-summary' }, ], }, }); };
Hide Webpack terminal spam on test errors
Hide Webpack terminal spam on test errors
JavaScript
mit
SilentCicero/react-boilerplate,TheTopazWombat/levt-2,kaizen7-nz/gold-star-chart,gihrig/react-boilerplate,mikejong0815/Temp,s0enke/react-boilerplate,kaizen7-nz/gold-star-chart,gihrig/react-boilerplate-logic,AnhHT/react-boilerplate,ipselon/react-boilerplate-clone,gtct/wallet.eine.com,mmaedel/react-boilerplate,blockfs/frontend-react,perry-ugroop/ugroop-react-dup2,likesalmon/likesalmon-react-boilerplate,KarandikarMihir/react-boilerplate,dbrelovsky/react-boilerplate,romanvieito/ball-simpler,jasoncyu/always-be-bulking,KarandikarMihir/react-boilerplate,samit4me/react-boilerplate,SilentCicero/react-boilerplate,StrikeForceZero/react-typescript-boilerplate,Proxiweb/react-boilerplate,mxstbr/react-boilerplate,shiftunion/bot-a-tron,dbrelovsky/react-boilerplate,haxorbit/chiron,w01fgang/react-boilerplate,gihrig/react-boilerplate,haithemT/app-test,StrikeForceZero/react-typescript-boilerplate,gtct/wallet.eine.com,Demonslyr/Donut.WFE.Customer,chaintng/react-boilerplate,rlagman/raphthelagman,abasalilov/react-boilerplate,samit4me/react-boilerplate,TheTopazWombat/levt-2,Dattaya/react-boilerplate-object,shiftunion/bot-a-tron,gihrig/react-boilerplate-logic,Jan-Jan/react-hackathon-boilerplate,react-boilerplate/react-boilerplate,jasoncyu/always-be-bulking,chaintng/react-boilerplate,Jan-Jan/react-hackathon-boilerplate,absortium/frontend,Proxiweb/react-boilerplate,codermango/BetCalculator,be-oi/beoi-training-client,gtct/wallet.eine.com,s0enke/react-boilerplate,romanvieito/ball-simpler,Dmitry-N-Medvedev/motor-collection,StrikeForceZero/react-typescript-boilerplate,tomazy/react-boilerplate,mikejong0815/Temp,abasalilov/react-boilerplate,Demonslyr/Donut.WFE.Customer,absortium/frontend,mxstbr/react-boilerplate,codermango/BetCalculator,Dmitry-N-Medvedev/motor-collection,Proxiweb/react-boilerplate,blockfs/frontend-react,be-oi/beoi-training-client,JonathanMerklin/react-boilerplate,react-boilerplate/react-boilerplate,Dmitry-N-Medvedev/motor-collection,kossel/react-boilerplate,w01fgang/react-boilerplate,haxorbit/chiron,pauleonardo/demo-trans,kossel/react-boilerplate,ipselon/react-boilerplate-clone,pauleonardo/demo-trans,AnhHT/react-boilerplate,perry-ugroop/ugroop-react-dup2,likesalmon/likesalmon-react-boilerplate,gtct/wallet.eine.com,tomazy/react-boilerplate,Dattaya/react-boilerplate-object,Dmitry-N-Medvedev/motor-collection,s0enke/react-boilerplate,mmaedel/react-boilerplate,rlagman/raphthelagman,haithemT/app-test,JonathanMerklin/react-boilerplate
1d5624ce7d0915973996ce760fe7afc3076d1d38
show-linked-media-in-page.js
show-linked-media-in-page.js
(function() { const linkedImages = document.querySelectorAll('a[href$=".gif"], a[href$=".jpeg"], a[href$=".jpg"], a[href$=".png"], a[href$=".apng"], a[href$=".webp"]'); linkedImages.forEach(function(a) { a.insertAdjacentHTML('afterend', '<div class="large-picture-wrap"><img alt="" src="'+a.href.replaceAll('"','&quot;')+'" /></div>') }); const linkedVideos = document.querySelectorAll('a[href$=".mov"], a[href$=".mp4"], a[href$=".avi"], a[href$=".webm"], a[href$=".wmv"]'); linkedVideos.forEach(function(a) { a.insertAdjacentHTML('afterend', '<div class="large-picture-wrap"><video controls src="'+a.href.replaceAll('"','&quot;')+'" style="max-width:100%"></video></div>') }); })();
(function() { const linkedImages = document.querySelectorAll('a[href$=".gif"], a[href$=".jpeg"], a[href$=".jpg"], a[href$=".png"], a[href$=".apng"], a[href$=".webp"]'); linkedImages.forEach(function(a) { a.insertAdjacentHTML('afterend', '<div><img alt="" src="'+a.href.replaceAll('"','&quot;')+'" style="max-width:100%" /></div>') }); const linkedVideos = document.querySelectorAll('a[href$=".mov"], a[href$=".mp4"], a[href$=".avi"], a[href$=".webm"], a[href$=".wmv"]'); linkedVideos.forEach(function(a) { a.insertAdjacentHTML('afterend', '<div><video controls src="'+a.href.replaceAll('"','&quot;')+'" style="max-width:100%"></video></div>') }); })();
Remove undefined class name from show-linked-media
Remove undefined class name from show-linked-media
JavaScript
mit
alanhogan/bookmarklets,alanhogan/bookmarklets