commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
fcf582951eb7d9fee2211fefc3506282e03d8e8f
src/store/api/assettypes.js
src/store/api/assettypes.js
import client from '@/store/api/client' export default { getAssetTypes (callback) { client.get('/api/data/asset-types?relations=true', callback) }, getAssetType (assetTypeId, callback) { client.get(`/api/data/entity-types/${assetTypeId}`, callback) }, newAssetType (assetType, callback) { const data = { name: assetType.name, task_types: assetType.task_types } return client.ppost('/api/data/entity-types', data) }, updateAssetType (assetType, callback) { const data = { name: assetType.name, task_types: assetType.task_types } return client.pput(`/api/data/entity-types/${assetType.id}`, data) }, deleteAssetType (assetType, callback) { return client.pdel(`/api/data/entity-types/${assetType.id}`) } }
import client from '@/store/api/client' export default { getAssetTypes (callback) { client.get('/api/data/asset-types', callback) }, getAssetType (assetTypeId, callback) { client.get(`/api/data/entity-types/${assetTypeId}`, callback) }, newAssetType (assetType, callback) { const data = { name: assetType.name, task_types: assetType.task_types } return client.ppost('/api/data/entity-types', data) }, updateAssetType (assetType, callback) { const data = { name: assetType.name, task_types: assetType.task_types } return client.pput(`/api/data/entity-types/${assetType.id}`, data) }, deleteAssetType (assetType, callback) { return client.pdel(`/api/data/entity-types/${assetType.id}`) } }
Remove useless flag on get asset types call
[assets] Remove useless flag on get asset types call
JavaScript
agpl-3.0
cgwire/kitsu,cgwire/kitsu
--- +++ @@ -2,7 +2,7 @@ export default { getAssetTypes (callback) { - client.get('/api/data/asset-types?relations=true', callback) + client.get('/api/data/asset-types', callback) }, getAssetType (assetTypeId, callback) {
d2a9dc303a745d4fc2a23d700a1439794ed167d4
products/static/products/app/js/services.js
products/static/products/app/js/services.js
'use strict'; app.factory('Product', function($http) { function getUrl(id = '') { return 'http://127.0.0.1:8000/api/products/' + id + '?format=json'; } return { get: function(id, callback) { return $http.get(getUrl(id)).success(callback); }, query: function(page, page_size, callback) { return $http.get(getUrl() + '&page_size=' + page_size + '&page=' + page).success(callback); }, save: function(product, callback) { return $http.post(getUrl(), product).success(callback); }, remove: function(id, callback) { return $http.delete(getUrl(id)).success(callback); }, put: function(product, callback) { return $http.put(getUrl(product.id), product).success(callback); } }; });
'use strict'; app.factory('Product', function($http) { function getUrl(id) { id = typeof id !== 'undefined' ? id : ''; return 'http://127.0.0.1:8000/api/products/' + id + '?format=json'; } return { get: function(id, callback) { return $http.get(getUrl(id)).success(callback); }, query: function(page, page_size, callback) { return $http.get(getUrl() + '&page_size=' + page_size + '&page=' + page).success(callback); }, save: function(product, callback) { return $http.post(getUrl(), product).success(callback); }, remove: function(id, callback) { return $http.delete(getUrl(id)).success(callback); }, put: function(product, callback) { return $http.put(getUrl(product.id), product).success(callback); } }; });
Remove dependency on default parameters in JS
Remove dependency on default parameters in JS Apparently it's only supported by Firefox, source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/default_parameters This issue was brought up in #3.
JavaScript
mit
matachi/product-gallery,matachi/product-gallery,matachi/product-gallery
--- +++ @@ -2,7 +2,8 @@ app.factory('Product', function($http) { - function getUrl(id = '') { + function getUrl(id) { + id = typeof id !== 'undefined' ? id : ''; return 'http://127.0.0.1:8000/api/products/' + id + '?format=json'; }
4bc603aa8135011cf717ea7645b6eb18bb80d869
src/_wlk/bugsnag.js
src/_wlk/bugsnag.js
/* global window, uw */ import bugsnag from 'bugsnag-js'; import { version } from '../../package.json'; const client = bugsnag({ apiKey: 'a3246545081c8decaf0185c7a7f8d402', appVersion: version, /** * Add current user information. */ beforeSend(report) { const state = uw.store.getState(); const user = state.auth && state.auth.user; if (user) { // eslint-disable-next-line no-param-reassign report.user = { id: user._id, name: user.username, }; } }, }); window.bugsnag = client;
/* global window, uw */ import bugsnag from 'bugsnag-js'; import { version } from '../../package.json'; let userId = null; try { userId = localStorage.errorReportId; if (!userId) { userId = Math.random().toString(32).slice(2, 8); localStorage.errorReportId = userId; } } catch { userId = 'anonymous'; } const client = bugsnag({ apiKey: 'a3246545081c8decaf0185c7a7f8d402', appVersion: version, collectUserIp: false, /** * Add current user information. */ beforeSend(report) { const state = uw.store.getState(); const user = state.auth && state.auth.user; if (user) { // eslint-disable-next-line no-param-reassign report.user = { id: user._id, name: user.username, }; } else { report.user = { id: userId, name: 'Guest', }; } }, }); window.bugsnag = client;
Remove IP addresses from error reports
[WLK-INSTANCE] Remove IP addresses from error reports
JavaScript
mit
welovekpop/uwave-web-welovekpop.club,welovekpop/uwave-web-welovekpop.club
--- +++ @@ -2,9 +2,21 @@ import bugsnag from 'bugsnag-js'; import { version } from '../../package.json'; +let userId = null; +try { + userId = localStorage.errorReportId; + if (!userId) { + userId = Math.random().toString(32).slice(2, 8); + localStorage.errorReportId = userId; + } +} catch { + userId = 'anonymous'; +} + const client = bugsnag({ apiKey: 'a3246545081c8decaf0185c7a7f8d402', appVersion: version, + collectUserIp: false, /** * Add current user information. */ @@ -17,6 +29,11 @@ id: user._id, name: user.username, }; + } else { + report.user = { + id: userId, + name: 'Guest', + }; } }, });
aa3d6ad4d2d4ef7742df07d9f8c63c5f0a2ac440
src/app/libs/Api.js
src/app/libs/Api.js
import queryString from "query-string"; class Api { static get(url, data = {}) { return this.request(url + (Object.keys(data).length > 0 ? ('?' + queryString.stringify(data)) : '' ), undefined, "GET"); } static post(url, data = {}) { return this.request(url, data, "POST"); } static delete(url, data = {}) { return this.request(url, data, "DELETE"); } static patch(url, data = {}) { return this.request(url, data, "PATCH"); } static request(url, data, method) { let req = fetch("http://" + window.location.hostname + ':8080/api/' + url, { method: method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(data) }); return new Promise((resolve, reject) => { req.then((response) => { response.json().then((data) => { if (response.ok && data.success) { resolve(data.data); } else { let e = new Error(data.message); e.response = response; reject(e); } }).catch(() => { let e = new Error('Malformed response'); e.response = response; reject(e); }) }).catch((e) => { reject(new Error(e)); }) }); } } export default Api;
import queryString from "query-string"; class Api { static get(url, data = {}) { return this.request(url + (Object.keys(data).length > 0 ? ('?' + queryString.stringify(data)) : '' ), undefined, "GET"); } static post(url, data = {}) { return this.request(url, data, "POST"); } static delete(url, data = {}) { return this.request(url, data, "DELETE"); } static patch(url, data = {}) { return this.request(url, data, "PATCH"); } static request(url, data, method) { let req = fetch("http://" + window.location.hostname + ':8080/api/' + url, { method: method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(data) }); return new Promise((resolve, reject) => { req.then((response) => { response.json().then((data) => { if (response.ok && data.success) { resolve(data.data); } else { let e = new Error(data.message); e.response = response; reject(e); } }).catch(() => { if(response.ok) { let e = new Error('Malformed response'); e.response = response; reject(e); } else { let e = new Error(response.statusText); e.response = response; reject(e); } }) }).catch((e) => { reject(new Error(e)); }) }); } } export default Api;
Use the error string if we have one for malformed json
Use the error string if we have one for malformed json
JavaScript
mit
gilfillan9/spotify-jukebox-v2,gilfillan9/spotify-jukebox-v2
--- +++ @@ -37,9 +37,16 @@ reject(e); } }).catch(() => { - let e = new Error('Malformed response'); - e.response = response; - reject(e); + if(response.ok) { + let e = new Error('Malformed response'); + e.response = response; + reject(e); + } else { + let e = new Error(response.statusText); + e.response = response; + reject(e); + } + }) }).catch((e) => { reject(new Error(e));
2f9bde3ad5a2e3dd104c812b6c81f4077fe0aa1e
vendor/nwmatcher/selector_engine.js
vendor/nwmatcher/selector_engine.js
Prototype._original_property = window.NW; //= require "repository/src/nwmatcher" Prototype.Selector = (function(engine) { function select(selector, scope) { return engine.select(selector, scope || document, Element.extend); } return { engine: engine, select: select, match: engine.match }; })(NW.Dom); // Restore globals. window.NW = Prototype._original_property; delete Prototype._original_property;
Prototype._original_property = window.NW; //= require "repository/src/nwmatcher" Prototype.Selector = (function(engine) { var select = engine.select; if (Element.extend !== Prototype.K) { select = function select(selector, scope) { return engine.select(selector, scope, Element.extend); }; } return { engine: engine, select: select, match: engine.match }; })(NW.Dom); // Restore globals. window.NW = Prototype._original_property; delete Prototype._original_property;
Simplify the NWMatcher adapter and optimize it for browsers that don't need to extend DOM elements.
prototype: Simplify the NWMatcher adapter and optimize it for browsers that don't need to extend DOM elements. [jddalton]
JavaScript
mit
292388900/prototype,erpframework/prototype,sdumitriu/prototype,lamsieuquay/prototype,ridixcr/prototype,lamsieuquay/prototype,erpframework/prototype,baiyanghese/prototype,lamsieuquay/prototype,Jiasm/prototype,Gargaj/prototype,erpframework/prototype,fashionsun/prototype,sstephenson/prototype,ridixcr/prototype,Gargaj/prototype,fashionsun/prototype,sstephenson/prototype,loduis/prototype,sdumitriu/prototype,ldf7801528/prototype,leafo/prototype,Jiasm/prototype,loduis/prototype,Jiasm/prototype,sstephenson/prototype,ldf7801528/prototype,292388900/prototype,Gargaj/prototype,ShefronYudy/prototype,leafo/prototype,sdumitriu/prototype,fashionsun/prototype,loduis/prototype,ShefronYudy/prototype,292388900/prototype,ShefronYudy/prototype,ridixcr/prototype,ldf7801528/prototype,baiyanghese/prototype
--- +++ @@ -2,8 +2,12 @@ //= require "repository/src/nwmatcher" Prototype.Selector = (function(engine) { - function select(selector, scope) { - return engine.select(selector, scope || document, Element.extend); + var select = engine.select; + + if (Element.extend !== Prototype.K) { + select = function select(selector, scope) { + return engine.select(selector, scope, Element.extend); + }; } return {
fe71390baca97c018af1b47174d6459600971de4
demo/webmodule.js
demo/webmodule.js
// a simple web app/module importFromModule('helma.skin', 'render'); function main_action() { var context = { title: 'Module Demo', href: href }; render('skins/modules.html', context); } // module scopes automatically support JSAdapter syntax! function __get__(name) { if (name == 'href') { return req.path; } else { return this[name]; } }
// a simple web app/module importFromModule('helma.skin', 'render'); function main_action() { var context = { title: 'Module Demo', href: req.path }; render('skins/modules.html', context); }
Fix demo app: modules no longer act as JSAdapters
Fix demo app: modules no longer act as JSAdapters git-svn-id: fac99be8204c57f0935f741ea919b5bf0077cdf6@9147 688a9155-6ab5-4160-a077-9df41f55a9e9
JavaScript
apache-2.0
ringo/ringojs,Transcordia/ringojs,ringo/ringojs,ringo/ringojs,oberhamsi/ringojs,ringo/ringojs,ashwinrayaprolu1984/ringojs,oberhamsi/ringojs,Transcordia/ringojs,ashwinrayaprolu1984/ringojs,oberhamsi/ringojs,Transcordia/ringojs,Transcordia/ringojs,ashwinrayaprolu1984/ringojs,ashwinrayaprolu1984/ringojs
--- +++ @@ -4,16 +4,7 @@ function main_action() { var context = { title: 'Module Demo', - href: href + href: req.path }; render('skins/modules.html', context); } - -// module scopes automatically support JSAdapter syntax! -function __get__(name) { - if (name == 'href') { - return req.path; - } else { - return this[name]; - } -}
01ce1bde07bfe675ad2cfd1e32f5cbd76dd53922
imports/api/messages.js
imports/api/messages.js
import { Mongo } from 'meteor/mongo'; import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { SimpleSchema } from 'meteor/aldeed:simple-schema'; export const Messages = new Mongo.Collection('messages'); Messages.deny({ insert() { return true; }, update() { return true; }, remove() { return true; } }); export const newMessage = new ValidatedMethod({ name: 'messages.new', validate: new SimpleSchema({ event: { type: String }, text: { type: String } }).validator(), run({ event, text }) { if (!this.userId) { throw new Meteor.Error('not-authorized'); } return Messages.insert({ event, user: this.userId, time: new Date(), text }); } }); export const removeMessage = new ValidatedMethod({ name: 'messages.remove', validate: new SimpleSchema({ id: { type: String } }).validator(), run({ id }) { if (!this.userId) { throw new Meteor.Error('not-authorized'); } Messages.remove({ '_id': id }); } }); if (Meteor.isServer) { // This code only runs on the server Meteor.publish('messages', function msgsPublication() { return Messages.find({}); }); }
import { Mongo } from 'meteor/mongo'; import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { SimpleSchema } from 'meteor/aldeed:simple-schema'; export const Messages = new Mongo.Collection('messages'); Messages.deny({ insert() { return true; }, update() { return true; }, remove() { return true; } }); export const newMessage = new ValidatedMethod({ name: 'messages.new', validate: new SimpleSchema({ event: { type: String }, text: { type: String } }).validator(), run({ event, text }) { if (!this.userId) { throw new Meteor.Error('not-authorized'); } return Messages.insert({ event, user: Meteor.user().username, time: new Date(), text }); } }); export const removeMessage = new ValidatedMethod({ name: 'messages.remove', validate: new SimpleSchema({ id: { type: String } }).validator(), run({ id }) { if (!this.userId) { throw new Meteor.Error('not-authorized'); } Messages.remove({ '_id': id }); } }); if (Meteor.isServer) { // This code only runs on the server Meteor.publish('messages', function msgsPublication() { return Messages.find({}); }); }
Save comment with username instead of user id
Save comment with username instead of user id
JavaScript
mit
f-martinez11/ActiveU,f-martinez11/ActiveU
--- +++ @@ -28,7 +28,7 @@ } return Messages.insert({ event, - user: this.userId, + user: Meteor.user().username, time: new Date(), text });
3cfc6e9d2234ec8b60c748888a88f2fe675ec872
tests/unit/components/dashboard-widget-test.js
tests/unit/components/dashboard-widget-test.js
import { test , moduleForComponent } from 'appkit/tests/helpers/module-for'; import DashboardWidgetComponent from 'appkit/components/dashboard-widget'; moduleForComponent('dashboard-widget', 'Unit - Dashboard widget component', { subject: function() { var bayeuxStub = { subscribe: Ember.K }; var subscribeStub = sinon.stub(bayeuxStub, 'subscribe', function() { var subscribedStub = { then: Ember.K }; sinon.stub(subscribedStub, 'then'); return subscribedStub; }); var obj = DashboardWidgetComponent.create({ bayeux: bayeuxStub, channel: '/awesome-metrics' }); return obj; } }); test('it exists', function() { ok(this.subject() instanceof DashboardWidgetComponent); }); test('subscribes to its channel', function() { ok(this.subject().get('bayeux').subscribe.calledOnce); });
import { test , moduleForComponent } from 'appkit/tests/helpers/module-for'; import DashboardWidgetComponent from 'appkit/components/dashboard-widget'; moduleForComponent('dashboard-widget', 'Unit - Dashboard widget component', { subject: function() { // Mock Faye/bayeux subscribe process; avoid network calls. var bayeuxStub = { subscribe: Ember.K }; var subscribeStub = sinon.stub(bayeuxStub, 'subscribe', function() { var subscribedStub = { then: Ember.K }; sinon.stub(subscribedStub, 'then'); return subscribedStub; }); var obj = DashboardWidgetComponent.create({ bayeux: bayeuxStub, channel: 'awesome-metrics' }); return obj; } }); test('it exists', function() { ok(this.subject() instanceof DashboardWidgetComponent); }); test('it subscribes using #bayeux', function() { ok(this.subject().get('bayeux').subscribe.calledOnce); }); test('it subscribes to #channel', function() { ok(this.subject().get('bayeux').subscribe.calledWith("/awesome-metrics")); });
Improve Faye/Bayeux coverage in widget specs.
Improve Faye/Bayeux coverage in widget specs.
JavaScript
mit
substantial/substantial-dash-client
--- +++ @@ -3,6 +3,8 @@ moduleForComponent('dashboard-widget', 'Unit - Dashboard widget component', { subject: function() { + + // Mock Faye/bayeux subscribe process; avoid network calls. var bayeuxStub = { subscribe: Ember.K }; var subscribeStub = sinon.stub(bayeuxStub, 'subscribe', function() { var subscribedStub = { then: Ember.K }; @@ -12,7 +14,7 @@ var obj = DashboardWidgetComponent.create({ bayeux: bayeuxStub, - channel: '/awesome-metrics' + channel: 'awesome-metrics' }); return obj; } @@ -22,6 +24,10 @@ ok(this.subject() instanceof DashboardWidgetComponent); }); -test('subscribes to its channel', function() { +test('it subscribes using #bayeux', function() { ok(this.subject().get('bayeux').subscribe.calledOnce); }); + +test('it subscribes to #channel', function() { + ok(this.subject().get('bayeux').subscribe.calledWith("/awesome-metrics")); +});
9acb51cda733751729fbe33c29c666c40cbdae35
src/Header/index.js
src/Header/index.js
import React from 'react'; import NavMenu from './NavMenu'; export default class Header extends React.Component { constructor(props) { super(props); } render() { let navMenu; if (this.props.config.headerMenuLinks.length > 0) { navMenu = <NavMenu links={this.props.config.headerMenuLinks} /> } return ( <header className="masthead" style={{backgroundColor: '#4C5664'}}> <div className="container"> <a href={this.props.config.rootUrl} className="masthead-logo">{this.props.config.name}</a> {navMenu} </div> </header> ); } }
import React from 'react'; import NavMenu from './NavMenu'; export default class Header extends React.Component { constructor(props) { super(props); } render() { let navMenu; if (this.props.config.headerMenuLinks.length > 0) { navMenu = <NavMenu links={this.props.config.headerMenuLinks} /> } return ( <header className="masthead" style={{backgroundColor: this.props.config.headerColor}}> <div className="container"> <a href={this.props.config.rootUrl} className="masthead-logo">{this.props.config.name}</a> {navMenu} </div> </header> ); } }
Add header background color based on config
Add header background color based on config
JavaScript
apache-2.0
naltaki/naltaki-front,naltaki/naltaki-front
--- +++ @@ -14,7 +14,7 @@ } return ( - <header className="masthead" style={{backgroundColor: '#4C5664'}}> + <header className="masthead" style={{backgroundColor: this.props.config.headerColor}}> <div className="container"> <a href={this.props.config.rootUrl} className="masthead-logo">{this.props.config.name}</a> {navMenu}
7441c6d4f8648391f556de91382a066bf6971da4
src/MasterPlugin.js
src/MasterPlugin.js
import Plugin from "./Plugin"; export default class MasterPlugin extends Plugin { static get plugin() { return { name: "MasterPlugin", description: "", help: "This plugin has access to PluginManager and will perform all the 'meta'/'super' actions.", type: Plugin.Type.SPECIAL, visibility: Plugin.Visibility.HIDDEN, needs: { database: true, utils: true } }; } constructor(listener, pluginManager) { super(listener); this.pluginManager = pluginManager; } onCommand({message, command, args}, reply) { if (command !== "help") return; const data = this.pluginManager.plugins .map(pl => pl.plugin) .filter(pl => pl.visibility !== Plugin.Visibility.HIDDEN); if (args.length === 0) { reply({ type: "text", text: data .map(pl => `*${pl.name}*: ${pl.description}`) .join("\n"), options: { parse_mode: "markdown", disable_web_page_preview: true } }); } else { const pluginName = args[0].toLowerCase(); const plugin = data .filter(pl => pl.name.toLowerCase() === pluginName)[0]; reply({ type: "text", text: `*${plugin.name}* - ${plugin.description}\n\n${plugin.help}`, options: { parse_mode: "markdown", disable_web_page_preview: true } }); } } }
import Plugin from "./Plugin"; export default class MasterPlugin extends Plugin { static get plugin() { return { name: "MasterPlugin", description: "", help: "This plugin has access to PluginManager and will perform all the 'meta'/'super' actions.", type: Plugin.Type.SPECIAL, visibility: Plugin.Visibility.HIDDEN, needs: { database: true, utils: true } }; } constructor(listener, pluginManager) { super(listener); this.pluginManager = pluginManager; } onCommand({message, command, args}, reply) { if (command !== "help") return; const data = this.pluginManager.plugins .map(pl => pl.plugin) .filter(pl => pl.visibility !== Plugin.Visibility.HIDDEN); if (args.length === 0) { reply({ type: "text", text: data .map(pl => `*${pl.name}*: ${pl.description}`) .join("\n"), options: { parse_mode: "markdown", disable_web_page_preview: true } }); } else { const pluginName = args[0].toLowerCase(); const plugin = data .filter(pl => pl.name.toLowerCase() === pluginName)[0]; if (plugin) { reply({ type: "text", text: `*${plugin.name}* - ${plugin.description}\n\n${plugin.help}`, options: { parse_mode: "markdown", disable_web_page_preview: true } }); } } } }
Add null check on help generation
Add null check on help generation
JavaScript
mit
crisbal/Telegram-Bot-Node,crisbal/Node-Telegram-Bot,crisbal/Node-Telegram-Bot,crisbal/Telegram-Bot-Node
--- +++ @@ -44,14 +44,17 @@ const pluginName = args[0].toLowerCase(); const plugin = data .filter(pl => pl.name.toLowerCase() === pluginName)[0]; - reply({ - type: "text", - text: `*${plugin.name}* - ${plugin.description}\n\n${plugin.help}`, - options: { - parse_mode: "markdown", - disable_web_page_preview: true - } - }); + + if (plugin) { + reply({ + type: "text", + text: `*${plugin.name}* - ${plugin.description}\n\n${plugin.help}`, + options: { + parse_mode: "markdown", + disable_web_page_preview: true + } + }); + } } } }
fecd31dd46b4f790f9c0cfe28eff3909fd0945b5
lib/ee.js
lib/ee.js
var slice = [].slice; module.exports = { on: function on(ev, handler) { var events = this._events, eventsArray = events[ev]; if (!eventsArray) { eventsArray = events[ev] = []; } eventsArray.push(handler); }, removeListener: function removeListener(ev, handler) { var array = this._events[ev]; array && array.splice(array.indexOf(handler), 1); }, emit: function emit(ev) { var args = slice.call(arguments, 1), array = this._events[ev]; array && array.forEach(invokeHandler, this); function invokeHandler(handler) { handler.apply(this, args); } }, once: function once(ev, handler) { this.on(ev, proxy); function proxy() { handler.apply(this, arguments); this.removeListener(ev, handler); } }, constructor: function constructor() { this._events = {}; return this; } };
var slice = [].slice; module.exports = { on: function on(ev, handler) { var events = this._events, eventsArray = events[ev]; if (!eventsArray) { eventsArray = events[ev] = []; } eventsArray.push(handler); }, removeListener: function removeListener(ev, handler) { var array = this._events[ev]; array && array.splice(array.indexOf(handler), 1); }, emit: function emit(ev) { var args = slice.call(arguments, 1), array = this._events[ev]; for (var i = 0, len = array.length; i < len; i++) { array[i].apply(this, args); } }, once: function once(ev, handler) { this.on(ev, proxy); function proxy() { handler.apply(this, arguments); this.removeListener(ev, handler); } }, constructor: function constructor() { this._events = {}; return this; } };
Use `for` instead of `forEach` as it minifies better.
Use `for` instead of `forEach` as it minifies better.
JavaScript
mit
Raynos/eventemitter-light
--- +++ @@ -20,10 +20,8 @@ var args = slice.call(arguments, 1), array = this._events[ev]; - array && array.forEach(invokeHandler, this); - - function invokeHandler(handler) { - handler.apply(this, args); + for (var i = 0, len = array.length; i < len; i++) { + array[i].apply(this, args); } }, once: function once(ev, handler) {
36335b37034025d76f8c758f9617292d9889fb73
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { "use strict"; // Display the execution time of grunt tasks require("time-grunt")(grunt); // Load all grunt-tasks in 'Build/Grunt-Options'. var gruntOptionsObj = require("load-grunt-configs")(grunt, { "config" : { src: "Build/Grunt-Options/*.js" } }); grunt.initConfig(gruntOptionsObj); // Load all grunt-plugins that are specified in the 'package.json' file. require('jit-grunt')(grunt); /** * Default grunt task. * Compiles all .scss/.sass files with ':dev' options and * validates all js-files inside Resources/Private/Javascripts with JSHint. */ grunt.registerTask("default", ["compass:dev", "jshint"]); /** * Travis CI task * Test all specified grunt tasks. */ grunt.registerTask("travis", ["init", "replace:init", "jshint", "deploy", "undeploy"]); /** * Load custom tasks * Load all Grunt-Tasks inside the 'Build/Grunt-Tasks' dir. */ grunt.loadTasks("Build/Grunt-Tasks"); };
module.exports = function(grunt) { "use strict"; // Display the execution time of grunt tasks require("time-grunt")(grunt); // Load all grunt-tasks in 'Build/Grunt-Options'. var gruntOptionsObj = require("load-grunt-configs")(grunt, { "config" : { src: "Build/Grunt-Options/*.js" } }); grunt.initConfig(gruntOptionsObj); // Load all grunt-plugins that are specified in the 'package.json' file. require('jit-grunt')(grunt, { replace: 'grunt-text-replace' }); /** * Default grunt task. * Compiles all .scss/.sass files with ':dev' options and * validates all js-files inside Resources/Private/Javascripts with JSHint. */ grunt.registerTask("default", ["compass:dev", "jshint"]); /** * Travis CI task * Test all specified grunt tasks. */ grunt.registerTask("travis", ["init", "replace:init", "jshint", "deploy", "undeploy"]); /** * Load custom tasks * Load all Grunt-Tasks inside the 'Build/Grunt-Tasks' dir. */ grunt.loadTasks("Build/Grunt-Tasks"); };
Fix the jit-grunt mapping for the replace task
[BUGFIX] Fix the jit-grunt mapping for the replace task
JavaScript
mit
t3b/t3b_template,t3b/t3b_template,t3b/t3b_template,t3b/t3b_template,t3b/t3b_template
--- +++ @@ -13,7 +13,9 @@ grunt.initConfig(gruntOptionsObj); // Load all grunt-plugins that are specified in the 'package.json' file. - require('jit-grunt')(grunt); + require('jit-grunt')(grunt, { + replace: 'grunt-text-replace' + }); /**
ce22c210ed48656ab3dae5b2cff8cd2e8fa662c5
js/game.js
js/game.js
var Game = function(boardString){ var board = ''; this.board = ''; if (arguments.length === 1) { this.board = this.toArray(boardString); } else { function random() { return Math.floor(Math.random() * 10 + 6); }; var firstTwo = random(), secondTwo = random(); for ( var i = 0; i < 16; i++ ) { if (i === firstTwo || i === secondTwo) { board += '2'; } else { board += '0'; }; }; this.board = this.toArray(board); } }; Game.prototype = { toString: function() { for( var i = 0; i < 16; i += 4){ this.array = this.board.slice(0 + i, 4 + i) console.log(this.array) } }, toArray: function(chars) { var boardArray = []; for( var i = 0; i < 16; i += 4) { var subarray = chars.slice(0 + i, 4 + i); boardArray.push(subarray.split('')); } return boardArray; } };
var Game = function(boardString){ var board = ''; this.board = ''; if (arguments.length === 1) { this.board = this.toArray(boardString); } else { function random() { return Math.floor(Math.random() * 10 + 6); }; var firstTwo = random(), secondTwo = random(); for ( var i = 0; i < 16; i++ ) { if (i === firstTwo || i === secondTwo) { board += '2'; } else { board += '0'; }; }; this.board = this.toArray(board); } }; Game.prototype = { toString: function() { this.board.forEach(function(row) { console.log(row.join('')); }); }, toArray: function(chars) { var boardArray = []; for( var i = 0; i < 16; i += 4) { var subarray = chars.slice(0 + i, 4 + i); boardArray.push(subarray.split('')); } return boardArray; } };
Modify toString method for board array format
Modify toString method for board array format
JavaScript
mit
suprfrye/galaxy-256,suprfrye/galaxy-256
--- +++ @@ -22,10 +22,9 @@ Game.prototype = { toString: function() { - for( var i = 0; i < 16; i += 4){ - this.array = this.board.slice(0 + i, 4 + i) - console.log(this.array) - } + this.board.forEach(function(row) { + console.log(row.join('')); + }); }, toArray: function(chars) {
cadc230be233de7ac0f0a809b2b0a078950b1416
components/Footer.js
components/Footer.js
import React from 'react'; import Link from '../components/Link'; import { StyleSheet, css } from 'glamor/aphrodite'; export default () => { return ( <footer className={css(styles.footer)}> <div className={css(styles.container)}> <p className={css(styles.text)}> Missing a library?{' '} <Link isStyled href="https://github.com/react-community/native-directory#how-to-add-a-library"> Add it to the directory </Link>. Want to learn more about React Native? Check out the{' '} <Link isStyled href="https://facebook.github.io/react-native/docs/getting-started.html"> offical docs </Link>, and{' '} <Link isStyled href="https://expo.io"> Expo </Link>. </p> </div> </footer> ); }; let styles = StyleSheet.create({ footer: { borderTop: '1px solid #ECECEC', width: '100%', }, container: { width: '100%', maxWidth: '1319px', padding: '24px 24px 24px 24px', margin: '0 auto 0 auto', }, });
import React from 'react'; import Link from '../components/Link'; import { StyleSheet, css } from 'glamor/aphrodite'; export default () => { return ( <footer className={css(styles.footer)}> <div className={css(styles.container)}> <p className={css(styles.text)}> Missing a library?{' '} <Link isStyled href="https://github.com/react-community/native-directory#how-do-i-add-a-library"> Add it to the directory </Link>. Want to learn more about React Native? Check out the{' '} <Link isStyled href="https://facebook.github.io/react-native/docs/getting-started.html"> offical docs </Link>, and{' '} <Link isStyled href="https://expo.io"> Expo </Link>. </p> </div> </footer> ); }; let styles = StyleSheet.create({ footer: { borderTop: '1px solid #ECECEC', width: '100%', }, container: { width: '100%', maxWidth: '1319px', padding: '24px 24px 24px 24px', margin: '0 auto 0 auto', }, });
Fix anchor of the "Add it to the directory" link
Fix anchor of the "Add it to the directory" link
JavaScript
mit
react-community/native-directory
--- +++ @@ -10,7 +10,7 @@ Missing a library?{' '} <Link isStyled - href="https://github.com/react-community/native-directory#how-to-add-a-library"> + href="https://github.com/react-community/native-directory#how-do-i-add-a-library"> Add it to the directory </Link>. Want to learn more about React Native? Check out the{' '} <Link
d6cff2ae3baf9de7f8156545fda5bb67361c36c2
components/Header.js
components/Header.js
import Head from 'next/head'; export default () => <header> <Head> <style>{` body { font-family: "Helvetica Neue", Arial, sans-serif; } `}</style> </Head> </header>;
import Head from 'next/head'; export default () => <header> <Head> <style global jsx>{` body { font-family: "Helvetica Neue", Arial, sans-serif; } `}</style> </Head> </header>;
Fix flash of unstyled text
Fix flash of unstyled text
JavaScript
mit
pmdarrow/react-todo
--- +++ @@ -3,7 +3,7 @@ export default () => <header> <Head> - <style>{` + <style global jsx>{` body { font-family: "Helvetica Neue", Arial, sans-serif; }
09c78c2316fdb2a1cb72b7bf5694404d4125927d
src/components/providers/cdg/Prefs/Prefs.js
src/components/providers/cdg/Prefs/Prefs.js
import React from 'react' export default class Prefs extends React.Component { static propTypes = { prefs: React.PropTypes.object.isRequired, setPrefs: React.PropTypes.func.isRequired, providerRefresh: React.PropTypes.func.isRequired, } toggleEnabled = this.toggleEnabled.bind(this) handleRefresh = this.handleRefresh.bind(this) toggleEnabled(e) { e.preventDefault() let prefs = Object.assign({}, this.props.prefs) prefs.enabled = !prefs.enabled this.props.setPrefs('provider.cdg', prefs) } handleRefresh() { this.props.providerRefresh('cdg') } render() { const { prefs } = this.props let paths = prefs.paths || [] paths = paths.map(path => ( <p key={path}>{path}</p> )) return ( <div> <label> <input type='checkbox' checked={prefs.enabled} onClick={this.toggleEnabled}/> <strong> CD+Graphics</strong> </label> <button onClick={this.handleRefresh}>Refresh</button> {paths} </div> ) } }
import React from 'react' export default class Prefs extends React.Component { static propTypes = { prefs: React.PropTypes.object.isRequired, setPrefs: React.PropTypes.func.isRequired, providerRefresh: React.PropTypes.func.isRequired, } toggleEnabled = this.toggleEnabled.bind(this) handleRefresh = this.handleRefresh.bind(this) toggleEnabled(e) { e.preventDefault() let prefs = Object.assign({}, this.props.prefs) prefs.enabled = !prefs.enabled this.props.setPrefs('provider.cdg', prefs) } handleRefresh() { this.props.providerRefresh('cdg') } render() { const { prefs } = this.props if (!prefs) return null const enabled = prefs.enabled === true let paths = prefs.paths || [] paths = paths.map(path => ( <p key={path}>{path}</p> )) return ( <div> <label> <input type='checkbox' checked={enabled} onClick={this.toggleEnabled}/> <strong> CD+Graphics</strong> </label> <button onClick={this.handleRefresh}>Refresh</button> {paths} </div> ) } }
Fix rendering before prefs loaded
Fix rendering before prefs loaded
JavaScript
isc
bhj/karaoke-forever,bhj/karaoke-forever
--- +++ @@ -23,6 +23,9 @@ render() { const { prefs } = this.props + if (!prefs) return null + + const enabled = prefs.enabled === true let paths = prefs.paths || [] paths = paths.map(path => ( @@ -32,7 +35,7 @@ return ( <div> <label> - <input type='checkbox' checked={prefs.enabled} onClick={this.toggleEnabled}/> + <input type='checkbox' checked={enabled} onClick={this.toggleEnabled}/> <strong> CD+Graphics</strong> </label> <button onClick={this.handleRefresh}>Refresh</button>
e8c621a87d93590901e128ab8e2fb8b649b63270
modules/blueprint.js
modules/blueprint.js
var BlueprintClient = require('xively-blueprint-client-js'); var client = new BlueprintClient({ authorization: process.env.BLUEPRINT_AUTHORIZATION }); module.exports = client;
var BlueprintClient = require('xively-blueprint-client-js'); var client = new BlueprintClient({ authorization: process.env.BLUEPRINT_AUTHORIZATION }); console.log('Client initialized with authorization >', process.env.BLUEPRINT_AUTHORIZATION); module.exports = client;
Add logging with Blueprint authorization token
Add logging with Blueprint authorization token
JavaScript
mit
Altoros/refill-them-api
--- +++ @@ -4,4 +4,6 @@ authorization: process.env.BLUEPRINT_AUTHORIZATION }); +console.log('Client initialized with authorization >', process.env.BLUEPRINT_AUTHORIZATION); + module.exports = client;
61766f5cd277420d68299c78c43bec051a23be4d
api/run-server.js
api/run-server.js
var server = require('./server'); var port = process.env.port || 3000; server.listen(port, function() { console.log('Listening on port ' + port); });
var server = require('./server'); var port = process.env.PORT || 3000; server.listen(port, function() { console.log('Listening on port ' + port); });
Use correct port env variable
Use correct port env variable
JavaScript
mit
jeffcharles/number-switcher-3000,jeffcharles/number-switcher-3000,jeffcharles/number-switcher-3000
--- +++ @@ -1,6 +1,6 @@ var server = require('./server'); -var port = process.env.port || 3000; +var port = process.env.PORT || 3000; server.listen(port, function() { console.log('Listening on port ' + port); });
eaf2461432f490fee0e8812889c90bd88eb7a0fe
realtime/index.js
realtime/index.js
const io = require('socket.io'), winston = require('winston'); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, {'timestamp': true}); const PORT = 3031; winston.info('Rupture real-time service starting'); winston.info('Listening on port ' + PORT); var socket = io.listen(PORT); socket.on('connection', function(client) { winston.info('New connection from client ' + client.id); client.on('get-work', function() { winston.info('get-work from client ' + client.id); client.emit('do-work', { url: 'https://facebook.com/?breach-test', amount: 1000, timeout: 0 }); }); client.on('disconnect', function() { winston.info('Client ' + client.id + ' disconnected'); }); });
const io = require('socket.io'), winston = require('winston'); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, {'timestamp': true}); const PORT = 3031; winston.info('Rupture real-time service starting'); winston.info('Listening on port ' + PORT); var socket = io.listen(PORT); socket.on('connection', function(client) { winston.info('New connection from client ' + client.id); client.on('get-work', function() { winston.info('get-work from client ' + client.id); client.emit('do-work', { url: 'https://facebook.com/?breach-test', amount: 1000, timeout: 0 }); }); client.on('work-completed', function({work, success, host}) { winston.info('Client indicates work completed: ', work, success, host); }); client.on('disconnect', function() { winston.info('Client ' + client.id + ' disconnected'); }); });
Add logging for server-side work completed event
Add logging for server-side work completed event
JavaScript
mit
dimkarakostas/rupture,dimriou/rupture,dimriou/rupture,esarafianou/rupture,dionyziz/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimkarakostas/rupture,esarafianou/rupture,dionyziz/rupture,dionyziz/rupture,dimriou/rupture,dimriou/rupture,dimriou/rupture,dionyziz/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dionyziz/rupture
--- +++ @@ -22,6 +22,9 @@ timeout: 0 }); }); + client.on('work-completed', function({work, success, host}) { + winston.info('Client indicates work completed: ', work, success, host); + }); client.on('disconnect', function() { winston.info('Client ' + client.id + ' disconnected'); });
e7bcd073726ab546c41883e68648aadbe7cdeed2
assets/js/main.js
assets/js/main.js
(function(document){ function setStyle(style, param) { var range, sel; if (window.getSelection) { sel = window.getSelection(); if (sel.getRangeAt) { range = sel.getRangeAt(0); } document.designMode = "on"; if (range) { sel.removeAllRanges(); sel.addRange(range); } document.execCommand(style, false, param); document.designMode = "off"; } } Mousetrap.bind('mod+b', function(e) { e.preventDefault(); setStyle("bold"); }); Mousetrap.bind('mod+i', function(e) { e.preventDefault(); setStyle("italic"); }); Mousetrap.bind('mod+u', function(e) { e.preventDefault(); setStyle("underline"); }); function addImage(e) { e.stopPropagation(); e.preventDefault(); var file = e.dataTransfer.files[0], reader = new FileReader(); reader.onload = function (event) { var newImage = document.createElement('span'); newImage.innerHTML = "<img src=" + event.target.result + " >"; e.target.appendChild(newImage); }; reader.readAsDataURL(file); } var pad = document.getElementById('pad'); pad.addEventListener('drop', addImage, false); })(document);
(function(document){ function setStyle(style, param) { var range, sel; if (window.getSelection) { sel = window.getSelection(); if (sel.getRangeAt) { range = sel.getRangeAt(0); } document.designMode = "on"; if (range) { sel.removeAllRanges(); sel.addRange(range); } document.execCommand(style, false, param); document.designMode = "off"; } } Mousetrap.bind('mod+b', function(e) { e.preventDefault(); setStyle("bold"); }); Mousetrap.bind('mod+i', function(e) { e.preventDefault(); setStyle("italic"); }); Mousetrap.bind('mod+u', function(e) { e.preventDefault(); setStyle("underline"); }); function addImage(e) { e.stopPropagation(); e.preventDefault(); x = e.clientX; y = e.clientY; var file = e.dataTransfer.files[0], reader = new FileReader(); reader.onload = function (event) { var dataURI = event.target.result; var img = document.createElement("img"); img.src = dataURI; if (document.caretPositionFromPoint) { var pos = document.caretPositionFromPoint(x, y); range = document.createRange(); range.setStart(pos.offsetNode, pos.offset); range.collapse(); range.insertNode(img); }else if (document.caretRangeFromPoint) { range = document.caretRangeFromPoint(x, y); range.insertNode(img); } }; reader.readAsDataURL(file); } var pad = document.getElementById('pad'); pad.addEventListener('drop', addImage, false); })(document);
Add image the right way
Add image the right way
JavaScript
mit
guilhermecomum/minimal-editor
--- +++ @@ -36,14 +36,26 @@ function addImage(e) { e.stopPropagation(); e.preventDefault(); + x = e.clientX; + y = e.clientY; var file = e.dataTransfer.files[0], reader = new FileReader(); reader.onload = function (event) { - var newImage = document.createElement('span'); - newImage.innerHTML = "<img src=" + event.target.result + " >"; - e.target.appendChild(newImage); + var dataURI = event.target.result; + var img = document.createElement("img"); + img.src = dataURI; + if (document.caretPositionFromPoint) { + var pos = document.caretPositionFromPoint(x, y); + range = document.createRange(); + range.setStart(pos.offsetNode, pos.offset); + range.collapse(); + range.insertNode(img); + }else if (document.caretRangeFromPoint) { + range = document.caretRangeFromPoint(x, y); + range.insertNode(img); + } }; reader.readAsDataURL(file);
b491985b4a59f368633a225905f582933fa47f0e
packages/babel-compiler/package.js
packages/babel-compiler/package.js
Package.describe({ name: "babel-compiler", summary: "Parser/transpiler for ECMAScript 2015+ syntax", // Tracks the npm version below. Use wrap numbers to increment // without incrementing the npm version. Hmm-- Apparently this // isn't possible because you can't publish a non-recommended // release with package versions that don't have a pre-release // identifier at the end (eg, -dev) version: '6.19.0-beta.14' }); Npm.depends({ 'meteor-babel': '0.19.1' }); Package.onUse(function (api) { api.use('ecmascript-runtime'); api.addFiles([ 'babel.js', 'babel-compiler.js' ], 'server'); api.export('Babel', 'server'); api.export('BabelCompiler', 'server'); });
Package.describe({ name: "babel-compiler", summary: "Parser/transpiler for ECMAScript 2015+ syntax", // Tracks the npm version below. Use wrap numbers to increment // without incrementing the npm version. Hmm-- Apparently this // isn't possible because you can't publish a non-recommended // release with package versions that don't have a pre-release // identifier at the end (eg, -dev) version: '6.19.0-beta.14' }); Npm.depends({ 'meteor-babel': '0.19.1' }); Package.onUse(function (api) { api.use('ecmascript-runtime', 'server'); api.addFiles([ 'babel.js', 'babel-compiler.js' ], 'server'); api.export('Babel', 'server'); api.export('BabelCompiler', 'server'); });
Make babel-runtime use ecmascript-runtime on server only.
Make babel-runtime use ecmascript-runtime on server only.
JavaScript
mit
Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor
--- +++ @@ -14,7 +14,7 @@ }); Package.onUse(function (api) { - api.use('ecmascript-runtime'); + api.use('ecmascript-runtime', 'server'); api.addFiles([ 'babel.js',
1b4be05beb4d717c13796e404e019ee6d4a543ce
app/javascript/sugar/posts/embeds.js
app/javascript/sugar/posts/embeds.js
import $ from "jquery"; import Sugar from "../../sugar"; /** * Handlers for scripted embed (social) quirks */ $(Sugar).bind("ready", function(){ // Initialize twitter embeds when new posts load or previewed $(Sugar).bind("postsloaded", function(event, posts) { if (posts.length && window.twttr && window.twttr.widgets) { window.twttr.widgets.load(posts[0].parentNode); } }); var scrollHeightCache = document.documentElement.scrollHeight; var scrollYCache = window.scrollY; const resizeObserver = new ResizeObserver(function (entries) { entries.forEach(function () { if (scrollYCache !== window.scrollY) { // Chrome updates the scroll position, but not the scroll! window.scrollTo(window.scrollX, window.scrollY); } else if (document.documentElement.scrollHeight !== scrollHeightCache) { var scrollYBy = document.documentElement.scrollHeight - scrollHeightCache; window.scrollBy(0, scrollYBy); } scrollYCache = window.scrollY; scrollHeightCache = document.documentElement.scrollHeight; }); }); resizeObserver.observe(document.querySelector(".posts")); });
import $ from "jquery"; import Sugar from "../../sugar"; /** * Handlers for scripted embed (social) quirks */ $(Sugar).bind("ready", function(){ const postsContainer = document.querySelector(".posts"); // Initialize twitter embeds when new posts load or previewed $(Sugar).bind("postsloaded", function(event, posts) { if (posts.length && window.twttr && window.twttr.widgets) { window.twttr.widgets.load(posts[0].parentNode); } }); if (postsContainer) { let scrollHeightCache = document.documentElement.scrollHeight; let scrollYCache = window.scrollY; const resizeObserver = new ResizeObserver(function (entries) { entries.forEach(function () { if (scrollYCache !== window.scrollY) { // Chrome updates the scroll position, but not the scroll! window.scrollTo(window.scrollX, window.scrollY); } else if (document.documentElement.scrollHeight !== scrollHeightCache) { const scrollYBy = document.documentElement.scrollHeight - scrollHeightCache; window.scrollBy(0, scrollYBy); } scrollYCache = window.scrollY; scrollHeightCache = document.documentElement.scrollHeight; }); }); resizeObserver.observe(postsContainer); } });
Check that posts exist before applying the resizeObserver
Check that posts exist before applying the resizeObserver
JavaScript
mit
elektronaut/sugar,elektronaut/sugar,elektronaut/sugar,elektronaut/sugar
--- +++ @@ -5,6 +5,7 @@ * Handlers for scripted embed (social) quirks */ $(Sugar).bind("ready", function(){ + const postsContainer = document.querySelector(".posts"); // Initialize twitter embeds when new posts load or previewed $(Sugar).bind("postsloaded", function(event, posts) { @@ -13,21 +14,22 @@ } }); - var scrollHeightCache = document.documentElement.scrollHeight; - var scrollYCache = window.scrollY; - const resizeObserver = new ResizeObserver(function (entries) { - entries.forEach(function () { - if (scrollYCache !== window.scrollY) { - // Chrome updates the scroll position, but not the scroll! - window.scrollTo(window.scrollX, window.scrollY); - } else if (document.documentElement.scrollHeight !== scrollHeightCache) { - var scrollYBy = document.documentElement.scrollHeight - scrollHeightCache; - window.scrollBy(0, scrollYBy); - } - scrollYCache = window.scrollY; - scrollHeightCache = document.documentElement.scrollHeight; + if (postsContainer) { + let scrollHeightCache = document.documentElement.scrollHeight; + let scrollYCache = window.scrollY; + const resizeObserver = new ResizeObserver(function (entries) { + entries.forEach(function () { + if (scrollYCache !== window.scrollY) { + // Chrome updates the scroll position, but not the scroll! + window.scrollTo(window.scrollX, window.scrollY); + } else if (document.documentElement.scrollHeight !== scrollHeightCache) { + const scrollYBy = document.documentElement.scrollHeight - scrollHeightCache; + window.scrollBy(0, scrollYBy); + } + scrollYCache = window.scrollY; + scrollHeightCache = document.documentElement.scrollHeight; + }); }); - }); - - resizeObserver.observe(document.querySelector(".posts")); + resizeObserver.observe(postsContainer); + } });
f8d22f8ded7ea448a643f248c346d46e85a929ea
js/query-cache.js
js/query-cache.js
define([], function () { var caches = {}; function Cache(method) { this.method = method; this._store = {}; } /** xml -> Promise<Result> **/ Cache.prototype.submit = function submit (query) { var xml = query.toXML(); var current = this._store[xml]; if (current) { return current; } else { return this._store[xml] = query[this.method](); } }; return {getCache: getCache}; function getCache (method) { return caches[method] || (caches[method] = new Cache(method)); } });
define([], function () { var caches = {}; function Cache(method, service) { this.method = method; this._store = {}; this.service = service; } /** xml -> Promise<Result> **/ Cache.prototype.submit = function submit (query) { var key, current; if (this.method === 'findById') { key = query.type + '@' + query.id; } else { key = query.toXML(); } var current = this._store[key]; if (current) { return current; } else if (this.method === 'findById') { return this._store[key] = this.service.findById(query.type, query.id); } else { return this._store[key] = query[this.method](); } }; return {getCache: getCache}; function getCache (method, service) { var key = method; if (service != null) { key += service.root; } return caches[key] || (caches[key] = new Cache(method, service)); } });
Allow cache methods that are run from the service.
Allow cache methods that are run from the service.
JavaScript
apache-2.0
yochannah/show-list-tool,alexkalderimis/show-list-tool,yochannah/show-list-tool,intermine-tools/show-list-tool,intermine-tools/show-list-tool,intermine-tools/show-list-tool,yochannah/show-list-tool
--- +++ @@ -2,26 +2,38 @@ var caches = {}; - function Cache(method) { + function Cache(method, service) { this.method = method; this._store = {}; + this.service = service; } /** xml -> Promise<Result> **/ Cache.prototype.submit = function submit (query) { - var xml = query.toXML(); - var current = this._store[xml]; + var key, current; + if (this.method === 'findById') { + key = query.type + '@' + query.id; + } else { + key = query.toXML(); + } + var current = this._store[key]; if (current) { return current; + } else if (this.method === 'findById') { + return this._store[key] = this.service.findById(query.type, query.id); } else { - return this._store[xml] = query[this.method](); + return this._store[key] = query[this.method](); } }; return {getCache: getCache}; - function getCache (method) { - return caches[method] || (caches[method] = new Cache(method)); + function getCache (method, service) { + var key = method; + if (service != null) { + key += service.root; + } + return caches[key] || (caches[key] = new Cache(method, service)); } });
7d8217e5404375885c14539d5a3cdd6799755154
packages/youtube/package.js
packages/youtube/package.js
Package.describe({ name: 'pntbr:youtube', version: '0.0.1', summary: 'Manage Youtube\'s videos', git: 'https://github.com/goacademie/fanhui', documentation: 'README.md' }) Package.onUse(function(api) { api.versionsFrom('1.2.1') api.use(['ecmascript', 'mongo']) api.use(['iron:router', 'templating', 'session'], 'client') api.addFiles('collection.js') api.addFiles(['server/model.js'], 'server') api.addFiles([ 'client/youtube.html', 'client/style.css', 'client/router.js', 'client/list-vdos.html', 'client/list-vdos.js', 'client/insert-vdo.html', 'client/insert-vdo.js' ], 'client') api.export(['notifBadYoutubeId'], 'client') api.export('Vdos', 'server') api.export([ 'Vdos', 'youtubeIdCheckLength', 'queryValueByFieldName', 'checkTitle', 'categoryByTitle', 'dateByTitle', 'rankByTitle'], 'client') }) Package.onTest(function(api) { api.use(['ecmascript', 'tinytest', 'pntbr:youtube']) api.use(['iron:router@1.0.0', 'templating'], 'client') api.addFiles('tests-stubs.js') api.addFiles('tests-youtube.js') })
Package.describe({ name: 'pntbr:youtube', version: '0.0.1', summary: 'Manage Youtube\'s videos', git: 'https://github.com/goacademie/fanhui', documentation: 'README.md' }) Package.onUse(function(api) { api.versionsFrom('1.2.1') api.use(['ecmascript', 'mongo']) api.use(['iron:router', 'templating', 'session'], 'client') api.addFiles('collection.js') api.addFiles(['server/model.js'], 'server') api.addFiles([ 'client/youtube.html', 'client/style.css', 'client/router.js', 'client/list-vdos.html', 'client/list-vdos.js', 'client/insert-vdo.html', 'client/insert-vdo.js' ], 'client') api.export(['notifBadYoutubeId'], 'client') api.export('Vdos', 'server') api.export([ 'youtubeIdCheckLength', 'queryValueByFieldName', 'checkTitle', 'categoryByTitle', 'dateByTitle', 'rankByTitle'], 'client') }) Package.onTest(function(api) { api.use(['ecmascript', 'tinytest', 'pntbr:youtube']) api.use(['iron:router@1.0.0', 'templating'], 'client') api.addFiles('tests-stubs.js') api.addFiles('tests-youtube.js') })
Disable Vdos collection on client
Disable Vdos collection on client
JavaScript
mit
goacademie/fanhui,goacademie/fanhui
--- +++ @@ -24,7 +24,6 @@ api.export(['notifBadYoutubeId'], 'client') api.export('Vdos', 'server') api.export([ - 'Vdos', 'youtubeIdCheckLength', 'queryValueByFieldName', 'checkTitle',
1b4db6e15bf268d9e46e36d6538b31469afba482
feature-detects/unicode.js
feature-detects/unicode.js
/*! { "name": "Unicode characters", "property": "unicode", "tags": ["encoding"], "warnings": [ "positive Unicode support doesn't mean you can use it inside <title>, this seems more related to OS & Language packs" ] } !*/ /* DOC Detects if unicode characters are supported in the current document. */ define(['Modernizr', 'createElement', 'testStyles', 'isSVG'], function(Modernizr, createElement, testStyles, isSVG) { /** * Unicode special character support * * Detection is made by testing missing glyph box rendering against star character * If widths are the same, this "probably" means the browser didn't support the star character and rendered a glyph box instead * Just need to ensure the font characters have different widths */ Modernizr.addTest('unicode', function() { var bool; var missingGlyph = createElement('span'); var star = createElement('span'); testStyles('#modernizr{font-family:Arial,sans;font-size:300em;}', function(node) { missingGlyph.innerHTML = isSVG ? '\u5987' : '&#5987'; star.innerHTML = isSVG ? '\u2606' : '&#9734'; node.appendChild(missingGlyph); node.appendChild(star); bool = 'offsetWidth' in missingGlyph && missingGlyph.offsetWidth !== star.offsetWidth; }); return bool; }); });
/*! { "name": "Unicode characters", "property": "unicode", "tags": ["encoding"], "warnings": [ "positive Unicode support doesn't mean you can use it inside <title>, this seems more related to OS & Language packs" ] } !*/ /* DOC Detects if unicode characters are supported in the current document. */ define(['Modernizr', 'createElement', 'testStyles', 'isSVG'], function(Modernizr, createElement, testStyles, isSVG) { /** * Unicode special character support * * Detection is made by testing missing glyph box rendering against star character * If widths are the same, this "probably" means the browser didn't support the star character and rendered a glyph box instead * Just need to ensure the font characters have different widths */ Modernizr.addTest('unicode', function() { var bool; var missingGlyph = createElement('span'); var star = createElement('span'); testStyles('#modernizr{font-family:Arial,sans;font-size:300em;}', function(node) { missingGlyph.innerHTML = isSVG ? '\u5987' : '&#5987;'; star.innerHTML = isSVG ? '\u2606' : '&#9734;'; node.appendChild(missingGlyph); node.appendChild(star); bool = 'offsetWidth' in missingGlyph && missingGlyph.offsetWidth !== star.offsetWidth; }); return bool; }); });
Add semicolons to avoid generating typos
Add semicolons to avoid generating typos
JavaScript
mit
Modernizr/Modernizr,Modernizr/Modernizr
--- +++ @@ -26,8 +26,8 @@ testStyles('#modernizr{font-family:Arial,sans;font-size:300em;}', function(node) { - missingGlyph.innerHTML = isSVG ? '\u5987' : '&#5987'; - star.innerHTML = isSVG ? '\u2606' : '&#9734'; + missingGlyph.innerHTML = isSVG ? '\u5987' : '&#5987;'; + star.innerHTML = isSVG ? '\u2606' : '&#9734;'; node.appendChild(missingGlyph); node.appendChild(star);
e4802320d96c78afb3b69b18b69cb71f605c9977
config/staging.js
config/staging.js
module.exports = { app_host_port: 'streetmix-staging.herokuapp.com', restapi_baseuri: "http://streetmix-api-staging.herokuapp.com", facebook_app_id: '175861739245183' }
module.exports = { app_host_port: 'streetmix-staging.herokuapp.com', restapi_baseuri: 'http://streetmix-api-staging.herokuapp.com', facebook_app_id: '175861739245183' }
Revert "Tryign double quotes to prevent HTML entity encoding."
Revert "Tryign double quotes to prevent HTML entity encoding." This reverts commit 656c393aaa66e558179ad94f08812bd3c931b690.
JavaScript
bsd-3-clause
codeforamerica/streetmix,magul/streetmix,codeforamerica/streetmix,codeforamerica/streetmix,macGRID-SRN/streetmix,magul/streetmix,kodujdlapolski/streetmix,magul/streetmix,CodeForBrazil/streetmix,CodeForBrazil/streetmix,kodujdlapolski/streetmix,kodujdlapolski/streetmix,macGRID-SRN/streetmix,macGRID-SRN/streetmix,CodeForBrazil/streetmix
--- +++ @@ -1,5 +1,5 @@ module.exports = { app_host_port: 'streetmix-staging.herokuapp.com', - restapi_baseuri: "http://streetmix-api-staging.herokuapp.com", + restapi_baseuri: 'http://streetmix-api-staging.herokuapp.com', facebook_app_id: '175861739245183' }
9a97f6929af78c0bfffeca2f96a9c47f7fa1e943
plugins/no-caching/index.js
plugins/no-caching/index.js
var robohydra = require('robohydra'), RoboHydraHead = robohydra.heads.RoboHydraHead; function getBodyParts(config) { "use strict"; var noCachingPath = config.nocachingpath || '/.*'; return {heads: [new RoboHydraHead({ path: noCachingPath, handler: function(req, res, next) { // Tweak client cache-related headers so ensure no // caching, then let the request be dispatched normally delete req.headers['if-modified-since']; req.headers['cache-control'] = 'no-cache'; next(req, res); } })]}; } exports.getBodyParts = getBodyParts;
var robohydra = require('robohydra'), RoboHydraHead = robohydra.heads.RoboHydraHead; function getBodyParts(config) { "use strict"; var noCachingPath = config.nocachingpath || '/.*'; return {heads: [new RoboHydraHead({ path: noCachingPath, handler: function(req, res, next) { // Tweak client cache-related headers so ensure no // caching, then let the request be dispatched normally delete req.headers['if-modified-since']; delete req.headers['if-none-match']; req.headers['cache-control'] = 'no-cache'; next(req, res); } })]}; } exports.getBodyParts = getBodyParts;
Delete the if-none-match header in the no-caching plugin
Delete the if-none-match header in the no-caching plugin
JavaScript
apache-2.0
mlev/robohydra,robohydra/robohydra,robohydra/robohydra,mlev/robohydra,mlev/robohydra
--- +++ @@ -12,6 +12,7 @@ // Tweak client cache-related headers so ensure no // caching, then let the request be dispatched normally delete req.headers['if-modified-since']; + delete req.headers['if-none-match']; req.headers['cache-control'] = 'no-cache'; next(req, res);
deadb3b799e40640be486ec5c6f7f39f54eae162
config/web.js
config/web.js
module.exports = { public_host_name: 'http://watchmen.letsnode.com/', // required for OAuth dance auth: { GOOGLE_CLIENT_ID: process.env.WATCHMEN_GOOGLE_CLIENT_ID || '<Create credentials from Google Dev Console>', GOOGLE_CLIENT_SECRET: process.env.WATCHMEN_GOOGLE_CLIENT_SECRET || '<Create credentials from Google Dev Console>' }, ga_analytics_ID: process.env.WATCHMEN_GOOGLE_ANALYTICS_ID };
module.exports = { public_host_name: process.env.WATCHMEN_BASE_URL || 'http://watchmen.letsnode.com/', // required for OAuth dance auth: { GOOGLE_CLIENT_ID: process.env.WATCHMEN_GOOGLE_CLIENT_ID || '<Create credentials from Google Dev Console>', GOOGLE_CLIENT_SECRET: process.env.WATCHMEN_GOOGLE_CLIENT_SECRET || '<Create credentials from Google Dev Console>' }, ga_analytics_ID: process.env.WATCHMEN_GOOGLE_ANALYTICS_ID };
Add WATCHMEN_BASE_URL env var to configure base url
Add WATCHMEN_BASE_URL env var to configure base url
JavaScript
mit
corinis/watchmen,labianchin/WatchMen,plyo/watchmen,corinis/watchmen,NotyIm/WatchMen,iloire/WatchMen,Cellington1/Status,NotyIm/WatchMen,labianchin/WatchMen,plyo/watchmen,labianchin/WatchMen,NotyIm/WatchMen,plyo/watchmen,ravi/watchmen,ravi/watchmen,Cellington1/Status,iloire/WatchMen,Cellington1/Status,corinis/watchmen,iloire/WatchMen,ravi/watchmen
--- +++ @@ -1,6 +1,6 @@ module.exports = { - public_host_name: 'http://watchmen.letsnode.com/', // required for OAuth dance + public_host_name: process.env.WATCHMEN_BASE_URL || 'http://watchmen.letsnode.com/', // required for OAuth dance auth: { GOOGLE_CLIENT_ID: process.env.WATCHMEN_GOOGLE_CLIENT_ID || '<Create credentials from Google Dev Console>',
084fd3d7bc7c227c313d2f23bce1413af02f935a
lib/background.js
lib/background.js
var path = require('path'); var nightwatch = require('nightwatch'); var originalArgv = JSON.parse(process.argv[2]); nightwatch.cli(function(argv) { for (var key in originalArgv) { if (key === 'env' && argv['parallel-mode'] === true) { continue; } argv[key] = originalArgv[key]; } if (argv.test) { argv.test = path.resolve(argv.test); } nightwatch.runner(argv, function(success) { if (!success) { process.exit(1); } else { process.exit(0); } }); });
var path = require('path'); var nightwatch = require('nightwatch'); var originalArgv = JSON.parse(process.argv[2]); nightwatch.cli(function(argv) { for (var key in originalArgv) { if (key === 'env' && originalArgv[key].indexOf(',') > -1 && argv['parallel-mode'] === true) { continue; } argv[key] = originalArgv[key]; } if (argv.test) { argv.test = path.resolve(argv.test); } nightwatch.runner(argv, function(success) { if (!success) { process.exit(1); } else { process.exit(0); } }); });
Fix correct check for env argument passed
Fix correct check for env argument passed
JavaScript
mit
tatsuyafw/gulp-nightwatch,StoneCypher/gulp-nightwatch
--- +++ @@ -4,7 +4,7 @@ nightwatch.cli(function(argv) { for (var key in originalArgv) { - if (key === 'env' && argv['parallel-mode'] === true) { + if (key === 'env' && originalArgv[key].indexOf(',') > -1 && argv['parallel-mode'] === true) { continue; } argv[key] = originalArgv[key];
2fbe38df3bba8886de9295ef637b65ea8ac664af
lib/i18n/index.js
lib/i18n/index.js
/** * i18n plugin * register handlebars handler which looks up translations in a dictionary */ var path = require("path"); var fs = require("fs"); var handlebars = require("handlebars"); module.exports = function makePlugin() { return function (opts) { var data = { "en": {} }; //load translation data if (opts.locales) { try { opts.locales.forEach( function (loc) { content = fs.readFileSync(path.join(__dirname + "../../../", loc.file)); data[loc.locale] = JSON.parse(content); }); } catch (e) { console.error(e); } } handlebars.registerHelper("i18n", function (msg) { if (msg && this.file.locale && data[this.file.locale] && data[this.file.locale][msg]) { return data[this.file.locale][msg]; } return msg; }); return function(files, metalsmith, done){ for (filename in files) { // add locale metadata to files var locale = filename.split("/")[0]; files[filename]['locale'] = locale; } done(); }; }; };
/** * i18n plugin * register handlebars handler which looks up translations in a dictionary */ var path = require("path"); var fs = require("fs"); var handlebars = require("handlebars"); module.exports = function makePlugin() { return function (opts) { var data = { "en": {} }; //load translation data if (opts.locales) { try { opts.locales.forEach( function (loc) { try { content = fs.readFileSync(path.join(__dirname + "../../../", loc.file)); data[loc.locale] = JSON.parse(content); } catch (e) { console.error("Failed to load: " + e.path); } }); } catch (e) { console.error(e); } } handlebars.registerHelper("i18n", function (msg) { if (msg && this.file.locale && data[this.file.locale] && data[this.file.locale][msg]) { return data[this.file.locale][msg]; } return msg; }); return function(files, metalsmith, done){ for (filename in files) { // add locale metadata to files var locale = filename.split("/")[0]; files[filename]['locale'] = locale; } done(); }; }; };
Handle missing title localisation file.
Handle missing title localisation file.
JavaScript
mit
playcanvas/developer.playcanvas.com,playcanvas/developer.playcanvas.com
--- +++ @@ -17,8 +17,12 @@ if (opts.locales) { try { opts.locales.forEach( function (loc) { - content = fs.readFileSync(path.join(__dirname + "../../../", loc.file)); - data[loc.locale] = JSON.parse(content); + try { + content = fs.readFileSync(path.join(__dirname + "../../../", loc.file)); + data[loc.locale] = JSON.parse(content); + } catch (e) { + console.error("Failed to load: " + e.path); + } }); } catch (e) { console.error(e);
6721766466e5cf2231fcc81fa9cdee2972835a93
lib/jsonReader.js
lib/jsonReader.js
var fs = require('fs'); var JSONStream = require('JSONStream'); var jsonReader = {}; jsonReader.read = function (fileName, callback) { return fs.readFile(fileName, function(err, data) { if (err) throw err; return callback(data); }); }; jsonReader.readStartStationStream = function (fileName, callback) { return fs.createReadStream(fileName) .pipe(JSONStream.parse('trips.*.start_station_id')); }; module.exports = jsonReader;
var fs = require('fs') var jsonReader = {} jsonReader.read = function (fileName, callback) { return fs.readFile(fileName, function (err, data) { if (err) { throw err } return callback(data) }) } jsonReader.readStream = function (fileName) { return fs.createReadStream(fileName) } module.exports = jsonReader
Clean up and make a separate method for return a readStream
Clean up and make a separate method for return a readStream
JavaScript
mit
superhansa/bikesluts,superhansa/bikesluts
--- +++ @@ -1,17 +1,18 @@ -var fs = require('fs'); -var JSONStream = require('JSONStream'); +var fs = require('fs') -var jsonReader = {}; +var jsonReader = {} jsonReader.read = function (fileName, callback) { - return fs.readFile(fileName, function(err, data) { - if (err) throw err; - return callback(data); - }); -}; + return fs.readFile(fileName, function (err, data) { + if (err) { + throw err + } -jsonReader.readStartStationStream = function (fileName, callback) { + return callback(data) + }) +} + +jsonReader.readStream = function (fileName) { return fs.createReadStream(fileName) - .pipe(JSONStream.parse('trips.*.start_station_id')); -}; +} -module.exports = jsonReader; +module.exports = jsonReader
5162a6d35a605c13d32dadf8a821e569248db98e
Gruntfile.js
Gruntfile.js
require('js-yaml'); module.exports = function (grunt) { grunt.loadNpmTasks('grunt-contrib-jst'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.loadNpmTasks('grunt-karma'); grunt.initConfig({ paths: require('js_paths.yml'), mochaTest: { jsbox_apps: { src: ['<%= paths.tests.jsbox_apps.spec %>'], } }, jst: { options: { processName: function(filename) { // process the template names the arb Django Pipelines way return filename .replace('go/base/static/templates/', '') .replace(/\..+$/, '') .split('/') .join('_'); } }, templates: { files: { "<%= paths.client.templates.dest %>": [ "<%= paths.client.templates.src %>" ] } }, }, karma: { dev: { singleRun: true, reporters: ['dots'], configFile: 'karma.conf.js' } } }); grunt.registerTask('test:jsbox_apps', [ 'mochaTest:jsbox_apps' ]); grunt.registerTask('test:client', [ 'jst:templates', 'karma:dev' ]); grunt.registerTask('test', [ 'test:jsbox_apps', 'test:client' ]); grunt.registerTask('default', [ 'test' ]); };
require('js-yaml'); var path = require('path'); module.exports = function (grunt) { grunt.loadNpmTasks('grunt-contrib-jst'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.loadNpmTasks('grunt-karma'); grunt.initConfig({ paths: require('js_paths.yml'), mochaTest: { jsbox_apps: { src: ['<%= paths.tests.jsbox_apps.spec %>'], } }, jst: { options: { processName: function(filename) { var dir = path.dirname(filename); dir = path.relative('go/base/static/templates', dir); var parts = dir.split('/'); parts.push(path.basename(filename, '.jst')); // process the template names the arb Django Pipelines way return parts.join('_'); } }, templates: { files: { "<%= paths.client.templates.dest %>": [ "<%= paths.client.templates.src %>" ] } }, }, karma: { dev: { singleRun: true, reporters: ['dots'], configFile: 'karma.conf.js' } } }); grunt.registerTask('test:jsbox_apps', [ 'mochaTest:jsbox_apps' ]); grunt.registerTask('test:client', [ 'jst:templates', 'karma:dev' ]); grunt.registerTask('test', [ 'test:jsbox_apps', 'test:client' ]); grunt.registerTask('default', [ 'test' ]); };
Make use of node path utils when processing the jst names for jst grunt task
Make use of node path utils when processing the jst names for jst grunt task
JavaScript
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
--- +++ @@ -1,4 +1,5 @@ require('js-yaml'); +var path = require('path'); module.exports = function (grunt) { grunt.loadNpmTasks('grunt-contrib-jst'); @@ -15,12 +16,14 @@ jst: { options: { processName: function(filename) { + var dir = path.dirname(filename); + dir = path.relative('go/base/static/templates', dir); + + var parts = dir.split('/'); + parts.push(path.basename(filename, '.jst')); + // process the template names the arb Django Pipelines way - return filename - .replace('go/base/static/templates/', '') - .replace(/\..+$/, '') - .split('/') - .join('_'); + return parts.join('_'); } }, templates: {
1170229827ef0e2e4dc78bd65bf71ab6ce7875fc
lib/node-linux.js
lib/node-linux.js
/** * @class nodelinux * This is a standalone module, originally designed for internal use in [NGN](http://github.com/thinkfirst/NGN). * However; it is capable of providing the same features for Node.JS scripts * independently of NGN. * * ### Getting node-linux * * `npm install node-linux` * * ### Using node-linux * * `var nm = require('node-linux');` * * @singleton * @author Corey Butler */ if (require('os').platform().indexOf('linux') < 0){ throw 'node-linux is only supported on Linux.'; } // Add daemon management capabilities module.exports.Service = require('./daemon');
/** * @class nodelinux * This is a standalone module, originally designed for internal use in [NGN](http://github.com/thinkfirst/NGN). * However; it is capable of providing the same features for Node.JS scripts * independently of NGN. * * ### Getting node-linux * * `npm install node-linux` * * ### Using node-linux * * `var nm = require('node-linux');` * * @singleton * @author Corey Butler */ // Add daemon management capabilities module.exports.Service = require('./daemon');
Remove exception on requiring module
Remove exception on requiring module
JavaScript
mit
zonetti/node-linux,zonetti/node-linux
--- +++ @@ -15,9 +15,6 @@ * @singleton * @author Corey Butler */ -if (require('os').platform().indexOf('linux') < 0){ - throw 'node-linux is only supported on Linux.'; -} // Add daemon management capabilities module.exports.Service = require('./daemon');
43f48c6fbe4d43d7f288d6169c612e8b6402e3b3
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { grunt.initConfig({ nodewebkit: { options: { platforms: ['osx'], buildDir: './build', macIcns: './app/icon/logo.icns' }, src: ['./app/**/*'] }, browserSync: { bsFiles: { src : 'app/css/*.css' }, options: { server: { baseDir: "./app" } } }, shell: { runApp: { command: '/Applications/node-webkit.app/Contents/MacOS/node-webkit ./app' } } }); require('load-grunt-tasks')(grunt); grunt.registerTask('build', ['nodewebkit']); grunt.registerTask('server', ['browserSync']); grunt.registerTask('run', ['shell:runApp']); }
module.exports = function(grunt) { grunt.initConfig({ nodewebkit: { options: { platforms: ['osx'], buildDir: './build', macIcns: './app/icon/logo.icns' }, src: ['./app/**/*'] }, browserSync: { bsFiles: { src : 'app/css/*.css' }, options: { server: { baseDir: "./app" } } }, shell: { runApp: { command: '/Applications/node-webkit.app/Contents/MacOS/node-webkit ./app --remote-debugging-port=9222' } } }); require('load-grunt-tasks')(grunt); grunt.registerTask('build', ['nodewebkit']); grunt.registerTask('server', ['browserSync']); grunt.registerTask('run', ['shell:runApp']); }
Enable remote debugging when running app.
Enable remote debugging when running app.
JavaScript
mit
ParinVachhani/chrome-devtools-app,ahmadassaf/Chrome-devtools-app,ParinVachhani/chrome-devtools-app,ahmadassaf/Chrome-devtools-app,ahmadassaf/Chrome-devtools-app,auchenberg/chrome-devtools-app,modulexcite/chrome-devtools-app,modulexcite/chrome-devtools-app,cjpearson/chrome-devtools-app,ahmadassaf/Chrome-devtools-app,modulexcite/chrome-devtools-app,modulexcite/chrome-devtools-app,monaca/chrome-devtools-app,ParinVachhani/chrome-devtools-app,auchenberg/chrome-devtools-app,monaca/chrome-devtools-app,ahmadassaf/Chrome-devtools-app,cjpearson/chrome-devtools-app,ParinVachhani/chrome-devtools-app,monaca/chrome-devtools-app,ParinVachhani/chrome-devtools-app,cjpearson/chrome-devtools-app,monaca/chrome-devtools-app,auchenberg/chrome-devtools-app,monaca/chrome-devtools-app,modulexcite/chrome-devtools-app,auchenberg/chrome-devtools-app,auchenberg/chrome-devtools-app
--- +++ @@ -24,7 +24,7 @@ shell: { runApp: { - command: '/Applications/node-webkit.app/Contents/MacOS/node-webkit ./app' + command: '/Applications/node-webkit.app/Contents/MacOS/node-webkit ./app --remote-debugging-port=9222' } }
f27626a82f7c2228182fca3b3d84171cf49b0ecb
Gruntfile.js
Gruntfile.js
require('js-yaml'); module.exports = function (grunt) { grunt.loadNpmTasks('grunt-mocha-test'); grunt.initConfig({ paths: require('paths.yml'), mochaTest: { jsbox_apps: { src: ['<%= paths.jsbox_apps.tests %>'], } } }); grunt.registerTask('test', [ 'mochaTest' ]); grunt.registerTask('default', [ 'test' ]); };
require('js-yaml'); module.exports = function (grunt) { grunt.loadNpmTasks('grunt-mocha-test'); grunt.initConfig({ paths: require('paths.yml'), mochaTest: { jsbox_apps: { src: ['<%= paths.jsbox_apps.tests %>'], } } }); grunt.registerTask('test:jsbox_apps', [ 'mochaTest:jsbox_apps' ]); grunt.registerTask('test', [ 'mochaTest' ]); grunt.registerTask('default', [ 'test' ]); };
Add a grunt task for only the jsbox_app js tests
Add a grunt task for only the jsbox_app js tests
JavaScript
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
--- +++ @@ -12,6 +12,10 @@ } }); + grunt.registerTask('test:jsbox_apps', [ + 'mochaTest:jsbox_apps' + ]); + grunt.registerTask('test', [ 'mochaTest' ]);
20c080c8f356f257d9c57dc761dd904280fabd4e
js/application.js
js/application.js
// load social sharing scripts if the page includes a Twitter "share" button var _jsLoader = _jsLoader || {}; // callback pattern _jsLoader.initTwitter = (function() { if (typeof (twttr) != 'undefined') { twttr.widgets.load(); } else { _jsLoader.getScript('http://platform.twitter.com/widgets.js'); } }); _jsLoader.initFacebook = (function() { if (typeof (FB) != 'undefined') { FB.init({ status: true, cookie: true, xfbml: true }); } else { _jsLoader.getScript("http://connect.facebook.net/en_US/all.js#xfbml=1", function () { FB.init({ status: true, cookie: true, xfbml: true }); }); } }); _jsLoader.initGooglePlusOne = (function() { if (typeof (gapi) != 'undefined') { $(".g-plusone").each(function () { gapi.plusone.render($(this).get(0)); }); } else { _jsLoader.getScript('https://apis.google.com/js/plusone.js'); } }); _jsLoader.loadSocial = (function() { _jsLoader.initTwitter(); _jsLoader.initFacebook(); _jsLoader.initGooglePlusOne(); });
// load social sharing scripts if the page includes a Twitter "share" button var _jsLoader = _jsLoader || {}; // callback pattern _jsLoader.initTwitter = (function() { if (typeof (twttr) != 'undefined') { twttr.widgets.load(); } else { _jsLoader.getScript('http://platform.twitter.com/widgets.js', function() { setTimeout(function() { _jsLoader.initTwitter(); }, _jsLoader.timeout); }); } }); _jsLoader.initFacebook = (function() { if (typeof (FB) != 'undefined') { FB.init({ status: true, cookie: true, xfbml: true }); } else { _jsLoader.getScript("http://connect.facebook.net/en_US/all.js#xfbml=1", function () { setTimeout(function() { _jsLoader.initFacebook(); }, _jsLoader.timeout); }); } }); _jsLoader.initGooglePlusOne = (function() { if (typeof (gapi) != 'undefined') { $(".g-plusone").each(function () { gapi.plusone.render($(this).get(0)); }); } else { _jsLoader.getScript('https://apis.google.com/js/plusone.js', function() { setTimeout(function() { _jsLoader.initGooglePlusOne(); }, _jsLoader.timeout); }); } }); _jsLoader.loadSocial = (function() { _jsLoader.initTwitter(); _jsLoader.initFacebook(); _jsLoader.initGooglePlusOne(); });
Add timeouts to social app loading
Add timeouts to social app loading
JavaScript
mit
bf4/bf4.github.com,bf4/bf4.github.com,bf4/bf4.github.com,bf4/bf4.github.com
--- +++ @@ -6,7 +6,11 @@ if (typeof (twttr) != 'undefined') { twttr.widgets.load(); } else { - _jsLoader.getScript('http://platform.twitter.com/widgets.js'); + _jsLoader.getScript('http://platform.twitter.com/widgets.js', function() { + setTimeout(function() { + _jsLoader.initTwitter(); + }, _jsLoader.timeout); + }); } }); @@ -15,7 +19,9 @@ FB.init({ status: true, cookie: true, xfbml: true }); } else { _jsLoader.getScript("http://connect.facebook.net/en_US/all.js#xfbml=1", function () { - FB.init({ status: true, cookie: true, xfbml: true }); + setTimeout(function() { + _jsLoader.initFacebook(); + }, _jsLoader.timeout); }); } }); @@ -26,7 +32,11 @@ gapi.plusone.render($(this).get(0)); }); } else { - _jsLoader.getScript('https://apis.google.com/js/plusone.js'); + _jsLoader.getScript('https://apis.google.com/js/plusone.js', function() { + setTimeout(function() { + _jsLoader.initGooglePlusOne(); + }, _jsLoader.timeout); + }); } });
e2bc229164dfcb37f3111950e536e3452bab646f
data/bootstrap.js
data/bootstrap.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; const { utils: Cu } = Components; const rootURI = __SCRIPT_URI_SPEC__.replace("bootstrap.js", ""); const COMMONJS_URI = "resource://gre/modules/commonjs"; const { require } = Cu.import(COMMONJS_URI + "/toolkit/require.js", {}); const { Bootstrap } = require(COMMONJS_URI + "/sdk/addon/bootstrap.js"); const { startup, shutdown, install, uninstall } = new Bootstrap(rootURI);
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; const { utils: Cu } = Components; const rootURI = __SCRIPT_URI_SPEC__.replace("bootstrap.js", ""); const COMMONJS_URI = "resource://gre/modules/commonjs"; const { require } = Cu.import(COMMONJS_URI + "/toolkit/require.js", {}); const { Bootstrap } = require(COMMONJS_URI + "/sdk/addon/bootstrap.js"); var { startup, shutdown, install, uninstall } = new Bootstrap(rootURI);
Fix fallout from global lexical scope changes.
Fix fallout from global lexical scope changes.
JavaScript
mpl-2.0
mozilla-jetpack/jpm-core,mozilla/jpm-core
--- +++ @@ -8,4 +8,4 @@ const COMMONJS_URI = "resource://gre/modules/commonjs"; const { require } = Cu.import(COMMONJS_URI + "/toolkit/require.js", {}); const { Bootstrap } = require(COMMONJS_URI + "/sdk/addon/bootstrap.js"); -const { startup, shutdown, install, uninstall } = new Bootstrap(rootURI); +var { startup, shutdown, install, uninstall } = new Bootstrap(rootURI);
67fc5a6d4365cc87ef7a07766594cae9431f1086
lib/app/js/directives/shadowDom.js
lib/app/js/directives/shadowDom.js
'use strict'; angular.module('sgApp') .directive('shadowDom', function(Styleguide, $templateCache) { var USER_STYLES_TEMPLATE = 'userStyles.html'; return { restrict: 'E', transclude: true, link: function(scope, element, attrs, controller, transclude) { if (typeof element[0].createShadowRoot === 'function' && !Styleguide.config.data.disableEncapsulation) { var root = angular.element(element[0].createShadowRoot()); root.append($templateCache.get(USER_STYLES_TEMPLATE)); transclude(function(clone) { root.append(clone); }); } else { transclude(function(clone) { element.append(clone); }); } } }; });
'use strict'; angular.module('sgApp') .directive('shadowDom', function(Styleguide, $templateCache) { var USER_STYLES_TEMPLATE = 'userStyles.html'; return { restrict: 'E', transclude: true, link: function(scope, element, attrs, controller, transclude) { scope.$watch(function() { return Styleguide.config; }, function() { if (typeof element[0].createShadowRoot === 'function' && (Styleguide.config && Styleguide.config.data && !Styleguide.config.data.disableEncapsulation)) { angular.element(element[0]).empty(); var root = angular.element(element[0].createShadowRoot()); root.append($templateCache.get(USER_STYLES_TEMPLATE)); transclude(function(clone) { root.append(clone); }); } else { transclude(function(clone) { var root = angular.element(element[0]); root.empty(); root.append(clone); }); } }, true); } }; });
Fix fullscreen mode when using disableEncapsulation option
Fix fullscreen mode when using disableEncapsulation option
JavaScript
mit
hence-io/sc5-styleguide,junaidrsd/sc5-styleguide,kraftner/sc5-styleguide,patriziosotgiu/sc5-styleguide,lewiscowper/sc5-styleguide,varya/sc5-styleguide,kraftner/sc5-styleguide,hence-io/sc5-styleguide,jkarttunen/sc5-styleguide,lewiscowper/sc5-styleguide,ifeelgoods/sc5-styleguide,jkarttunen/sc5-styleguide,SC5/sc5-styleguide,soulfresh/sc5-styleguide,SC5/sc5-styleguide,hannu/sc5-styleguide,varya/sc5-styleguide,ifeelgoods/sc5-styleguide,junaidrsd/sc5-styleguide,patriziosotgiu/sc5-styleguide,hannu/sc5-styleguide,soulfresh/sc5-styleguide
--- +++ @@ -9,17 +9,26 @@ restrict: 'E', transclude: true, link: function(scope, element, attrs, controller, transclude) { - if (typeof element[0].createShadowRoot === 'function' && !Styleguide.config.data.disableEncapsulation) { - var root = angular.element(element[0].createShadowRoot()); - root.append($templateCache.get(USER_STYLES_TEMPLATE)); - transclude(function(clone) { - root.append(clone); - }); - } else { - transclude(function(clone) { - element.append(clone); - }); - } + + scope.$watch(function() { + return Styleguide.config; + }, function() { + if (typeof element[0].createShadowRoot === 'function' && (Styleguide.config && Styleguide.config.data && !Styleguide.config.data.disableEncapsulation)) { + angular.element(element[0]).empty(); + var root = angular.element(element[0].createShadowRoot()); + root.append($templateCache.get(USER_STYLES_TEMPLATE)); + transclude(function(clone) { + root.append(clone); + }); + } else { + transclude(function(clone) { + var root = angular.element(element[0]); + root.empty(); + root.append(clone); + }); + } + }, true); + } }; });
8566a1dedb86a6941ef32822a424dbae327e646d
src/streams/hot-collection-to-collection.js
src/streams/hot-collection-to-collection.js
define(['streamhub-sdk/collection'], function (Collection) { 'use strict'; var HotCollectionToCollection = function () {}; /** * Transform an Object from StreamHub's Hot Collection endpoint into a * streamhub-sdk/collection model * @param hotCollection {object} */ HotCollectionToCollection.transform = function (hotCollection) { var collection = new Collection({ network: networkFromHotCollection(hotCollection), siteId: hotCollection.siteId, articleId: hotCollection.articleId, id: hotCollection.id, environment: environmentFromHotCollection(hotCollection) }); collection.heatIndex = hotCollection.heat; collection.title = hotCollection.title; return collection; }; var NETWORK_IN_INITURL = /([^.\/]+\.fyre\.co|livefyre\.com)\/\d+\//; function networkFromHotCollection(hotCollection) { var initUrl = hotCollection.initUrl; var match = initUrl.match(NETWORK_IN_INITURL); if ( ! match) { return; } return match[1]; } var ENVIRONMENT_IN_INITURL = /\/bs3\/([^\/]+)\/[^\/]+\/\d+\//; function environmentFromHotCollection(hotCollection) { var initUrl = hotCollection.initUrl; var match = initUrl.match(ENVIRONMENT_IN_INITURL); if ( ! match) { return; } return match[1]; } return HotCollectionToCollection; });
define(['streamhub-sdk/collection'], function (Collection) { 'use strict'; var HotCollectionToCollection = function () {}; /** * Transform an Object from StreamHub's Hot Collection endpoint into a * streamhub-sdk/collection model * @param hotCollection {object} */ HotCollectionToCollection.transform = function (hotCollection) { var collection = new Collection({ network: networkFromHotCollection(hotCollection), siteId: hotCollection.siteId, articleId: hotCollection.articleId, id: hotCollection.id, environment: environmentFromHotCollection(hotCollection) }); collection.heatIndex = hotCollection.heat; collection.title = hotCollection.title; collection.url = hotCollection.url; return collection; }; var NETWORK_IN_INITURL = /([^.\/]+\.fyre\.co|livefyre\.com)\/\d+\//; function networkFromHotCollection(hotCollection) { var initUrl = hotCollection.initUrl; var match = initUrl.match(NETWORK_IN_INITURL); if ( ! match) { return; } return match[1]; } var ENVIRONMENT_IN_INITURL = /\/bs3\/([^\/]+)\/[^\/]+\/\d+\//; function environmentFromHotCollection(hotCollection) { var initUrl = hotCollection.initUrl; var match = initUrl.match(ENVIRONMENT_IN_INITURL); if ( ! match) { return; } return match[1]; } return HotCollectionToCollection; });
Include url attribute in created Collection
Include url attribute in created Collection
JavaScript
mit
gobengo/streamhub-hot-collections
--- +++ @@ -20,6 +20,7 @@ }); collection.heatIndex = hotCollection.heat; collection.title = hotCollection.title; + collection.url = hotCollection.url; return collection; };
3f8a720bce6ea792be37fbf7a52ba7ea62d89c9f
lib/connection.js
lib/connection.js
var mongo = require('mongoskin'); var job = require('./job'); var Queue = require('./queue'); var Worker = require('./worker'); module.exports = Connection; function Connection(uri, options) { this.db = mongo.db(uri, options); } Connection.prototype.worker = function (queues, options) { var self = this; var queues = queues.map(function (queue) { if (typeof queue === 'string') { queue = self.queue(queue); } return queue; }); return new Worker(queues, options); }; Connection.prototype.queue = function (name, options) { return new Queue(this, name, options); }; Connection.prototype.close = function () { this.db.close(); };
var mongo = require('mongoskin'); var job = require('./job'); var Queue = require('./queue'); var Worker = require('./worker'); module.exports = Connection; function Connection(uri, options) { this.db = mongo.db(uri, options); } Connection.prototype.worker = function (queues, options) { var self = this; var queues = queues.map(function (queue) { if (typeof queue === 'string') { queue = self.queue(queue, options); } return queue; }); return new Worker(queues, options); }; Connection.prototype.queue = function (name, options) { return new Queue(this, name, options); }; Connection.prototype.close = function () { this.db.close(); };
Create worker queue with options
Create worker queue with options
JavaScript
mit
dioscouri/nodejs-monq
--- +++ @@ -14,7 +14,7 @@ var queues = queues.map(function (queue) { if (typeof queue === 'string') { - queue = self.queue(queue); + queue = self.queue(queue, options); } return queue;
403e11554bdd11ec3e521d4de244f22bdae437d0
src/components/Layout/HeaderNav.js
src/components/Layout/HeaderNav.js
import React from 'react' import PropTypes from 'prop-types' import { Menu, Icon, Popover } from 'antd' import { Link } from 'dva/router' import uri from 'utils/uri' import { l } from 'utils/localization' import styles from './Header.less' import { classnames } from 'utils' function createMenu(items, handleClick, mode = 'horizontal') { let current = uri.current().split('/')[1] return ( <Menu onClick={handleClick} selectedKeys={[current]} mode={mode}> {items.map(item => (<Menu.Item key={item.name}><Link to={item.path}><Icon type={item.icon || 'appstore-o'} /><span>{l(item.name)}</span></Link></Menu.Item>))} </Menu> ) } const HeaderNav = React.createClass({ getInitialState() { return { current: uri.current().split('/')[1], } }, handleClick(e) { this.setState({ current: e.key, }) }, render() { return (<div> <div className={styles.headerNavItems}> {createMenu(this.props.items, this.handleClick)} </div> <Popover content={createMenu(this.props.items, this.handleClick, 'inline')} trigger="click" overlayClassName={styles.headerNavMenus}> <div className={classnames(styles.headerNavDropdown, this.props.barClassName)}> <Icon type="bars" /> </div> </Popover> </div> ) }, }) export default HeaderNav
import React from 'react' import PropTypes from 'prop-types' import { Menu, Icon, Popover } from 'antd' import { Link } from 'dva/router' import uri from 'utils/uri' import { l } from 'utils/localization' import styles from './Header.less' import { classnames } from 'utils' function createMenu(items, handleClick, mode = 'horizontal') { let current = uri.current().split('/')[1] return ( <Menu onClick={handleClick} selectedKeys={[current]} mode={mode}> {items.map(item => (<Menu.Item key={item.path.split('/')[1]}><Link to={item.path}><Icon type={item.icon || 'appstore-o'} /><span>{l(item.name)}</span></Link></Menu.Item>))} </Menu> ) } const HeaderNav = React.createClass({ getInitialState() { return { current: uri.current().split('/')[1], } }, handleClick(e) { this.setState({ current: e.key, }) }, render() { return (<div> <div className={styles.headerNavItems}> {createMenu(this.props.items, this.handleClick)} </div> <Popover content={createMenu(this.props.items, this.handleClick, 'inline')} trigger="click" overlayClassName={styles.headerNavMenus}> <div className={classnames(styles.headerNavDropdown, this.props.barClassName)}> <Icon type="bars" /> </div> </Popover> </div> ) }, }) export default HeaderNav
Fix header nav selected key issue
Fix header nav selected key issue
JavaScript
mit
steem/qwp-antd,steem/qwp-antd
--- +++ @@ -11,7 +11,7 @@ let current = uri.current().split('/')[1] return ( <Menu onClick={handleClick} selectedKeys={[current]} mode={mode}> - {items.map(item => (<Menu.Item key={item.name}><Link to={item.path}><Icon type={item.icon || 'appstore-o'} /><span>{l(item.name)}</span></Link></Menu.Item>))} + {items.map(item => (<Menu.Item key={item.path.split('/')[1]}><Link to={item.path}><Icon type={item.icon || 'appstore-o'} /><span>{l(item.name)}</span></Link></Menu.Item>))} </Menu> ) }
9b491e8b0792917404e6a8af09b1f6bd367274d1
src/components/SubTabView/index.js
src/components/SubTabView/index.js
import React, {Component} from 'react' import {StyleSheet, View} from 'react-native' import TabButton from './TabButton' export default class extends Component { state = {activeTab: 0} render = () => ( <View style={{flex: 1}}> {this.props.tabs.length < 2 ? null : <View style={Styles.tabWrapper}> { this.props.tabs.map(({title}, key) => ( <TabButton key={key} index={key} text={title} activeTab={this.state.activeTab} changeTab={this.changeTab} /> )) } </View> } {this.renderTab()} </View> ) renderTab = () => ( this.props.tabs.map((tab, key) => { if (key == this.state.activeTab) { const ContentView = tab.content return <ContentView key={key}/> } }) ) changeTab = (key) => this.setState({activeTab: key}) } const Styles = StyleSheet.create({ tabWrapper: { flexDirection: 'row', alignSelf: 'stretch', alignContent: 'stretch', justifyContent: 'space-between', height: 40 } })
import React, {Component} from 'react' import {StyleSheet, View} from 'react-native' import TabButton from './TabButton' export default class extends Component { state = {activeTab: 0} render = () => ( <View style={{flex: 1}}> {this.props.tabs.length < 2 ? null : <View style={Styles.tabWrapper}> { this.props.tabs.sort(this.compareSortOrder).map(({title}, key) => ( <TabButton key={key} index={key} text={title} activeTab={this.state.activeTab} changeTab={this.changeTab} /> )) } </View> } {this.renderTab()} </View> ) renderTab = () => ( this.props.tabs.map((tab, key) => { if (key == this.state.activeTab) { const ContentView = tab.content return <ContentView key={key}/> } }) ) changeTab = (key) => this.setState({activeTab: key}) compareSortOrder = (element1, element2) => element1.sortOrder - element2.sortOrder } const Styles = StyleSheet.create({ tabWrapper: { flexDirection: 'row', alignSelf: 'stretch', alignContent: 'stretch', justifyContent: 'space-between', height: 40 } })
Implement sort ordering for SubTabView
Implement sort ordering for SubTabView
JavaScript
mit
Digitova/reactova-framework
--- +++ @@ -10,7 +10,7 @@ {this.props.tabs.length < 2 ? null : <View style={Styles.tabWrapper}> { - this.props.tabs.map(({title}, key) => ( + this.props.tabs.sort(this.compareSortOrder).map(({title}, key) => ( <TabButton key={key} index={key} @@ -36,6 +36,8 @@ ) changeTab = (key) => this.setState({activeTab: key}) + + compareSortOrder = (element1, element2) => element1.sortOrder - element2.sortOrder } const Styles = StyleSheet.create({
7aeca984f56841396a3d26120decc7b1b161f92a
scripts/_build-base-html.js
scripts/_build-base-html.js
const fs = require(`fs`); const glob = require(`glob`); const path = require(`path`); const buildHtml = require(`./_build-html.js`); const pages = glob.sync(path.join(process.cwd(), `pages`, `**`, `*.hbs`)); module.exports = (data) => { pages.forEach((page) => { const baseTemplate = fs.readFileSync(page, `utf8`); const outputFile = path.join(process.cwd(), `dist`, `${path.parse(page).name}.html`); buildHtml(baseTemplate, data, outputFile); }); };
const fs = require(`fs`); const glob = require(`glob`); const path = require(`path`); const buildHtml = require(`./_build-html.js`); const pages = glob.sync(path.join(process.cwd(), `pages`, `**`, `*.hbs`)); module.exports = (data) => { pages.forEach((page) => { const baseTemplate = fs.readFileSync(page, `utf8`); const pathName = path.parse(page).name; const subPath = path .parse(page.replace(path.join(process.cwd(), `pages`, path.sep), ``)) .dir.split(path.sep); const outputPath = [process.cwd(), `dist`, ...subPath]; if (pathName !== `index`) { outputPath.push(pathName); } const outputFile = path.join(...outputPath, `index.html`); buildHtml(baseTemplate, data, outputFile); }); };
Add support for nested pages
Add support for nested pages
JavaScript
mit
avalanchesass/avalanche-website,avalanchesass/avalanche-website
--- +++ @@ -9,7 +9,15 @@ module.exports = (data) => { pages.forEach((page) => { const baseTemplate = fs.readFileSync(page, `utf8`); - const outputFile = path.join(process.cwd(), `dist`, `${path.parse(page).name}.html`); + const pathName = path.parse(page).name; + const subPath = path + .parse(page.replace(path.join(process.cwd(), `pages`, path.sep), ``)) + .dir.split(path.sep); + const outputPath = [process.cwd(), `dist`, ...subPath]; + if (pathName !== `index`) { + outputPath.push(pathName); + } + const outputFile = path.join(...outputPath, `index.html`); buildHtml(baseTemplate, data, outputFile); }); };
78aa6e0fb40c58376105c801c1204b194bc926de
publishing/printview/main.js
publishing/printview/main.js
// convert current notebook to html by calling "ipython nbconvert" and open static html file in new tab define([ 'base/js/namespace', 'jquery', ], function(IPython, $) { "use strict"; if (IPython.version[0] < 3) { console.log("This extension requires IPython 3.x") return } /** * Call nbconvert using the current notebook server profile * */ var nbconvertPrintView = function () { var kernel = IPython.notebook.kernel; var name = IPython.notebook.notebook_name; var command = 'ip=get_ipython(); import os; os.system(\"ipython nbconvert --profile=%s --to html ' + name + '\" % ip.profile)'; function callback(out_type, out_data) { var url = name.split('.ipynb')[0] + '.html'; var win=window.open(url, '_blank'); win.focus(); } kernel.execute(command, { shell: { reply : callback } }); $('#doPrintView').blur() }; IPython.toolbar.add_buttons_group([ { id : 'doPrintView', label : 'Create static print view', icon : 'fa-print', callback : nbconvertPrintView } ]) })
// convert current notebook to html by calling "ipython nbconvert" and open static html file in new tab define([ 'base/js/namespace', 'jquery', ], function(IPython, $) { "use strict"; if (IPython.version[0] < 3) { console.log("This extension requires at least IPython 3.x") return } /** * Call nbconvert using the current notebook server profile * */ var nbconvertPrintView = function () { var name = IPython.notebook.notebook_name; var command = 'ip=get_ipython(); import os; os.system(\"jupyter nbconvert --profile=%s --to html ' + name + '\" % ip.profile)'; callbacks = { iopub : { output : function() { var url = name.split('.ipynb')[0] + '.html'; var win=window.open(url, '_blank'); win.focus(); } } }; IPython.notebook.kernel.execute(command, callbacks); //$('#doPrintView').blur(); }; var load_ipython_extension = function () { IPython.toolbar.add_buttons_group([ { id : 'doPrintView', label : 'Create static print view', icon : 'fa-print', callback : nbconvertPrintView } ]) } return { load_ipython_extension : load_ipython_extension } })
Make printview work with jupyter
Make printview work with jupyter
JavaScript
bsd-3-clause
Konubinix/IPython-notebook-extensions,Konubinix/IPython-notebook-extensions,Konubinix/IPython-notebook-extensions
--- +++ @@ -6,34 +6,42 @@ ], function(IPython, $) { "use strict"; if (IPython.version[0] < 3) { - console.log("This extension requires IPython 3.x") + console.log("This extension requires at least IPython 3.x") return } - + /** * Call nbconvert using the current notebook server profile * */ var nbconvertPrintView = function () { - var kernel = IPython.notebook.kernel; var name = IPython.notebook.notebook_name; - var command = 'ip=get_ipython(); import os; os.system(\"ipython nbconvert --profile=%s --to html ' + var command = 'ip=get_ipython(); import os; os.system(\"jupyter nbconvert --profile=%s --to html ' + name + '\" % ip.profile)'; - function callback(out_type, out_data) { - var url = name.split('.ipynb')[0] + '.html'; - var win=window.open(url, '_blank'); - win.focus(); - } - kernel.execute(command, { shell: { reply : callback } }); - $('#doPrintView').blur() + callbacks = { + iopub : { + output : function() { + var url = name.split('.ipynb')[0] + '.html'; + var win=window.open(url, '_blank'); + win.focus(); + } + } + }; + IPython.notebook.kernel.execute(command, callbacks); + //$('#doPrintView').blur(); }; - IPython.toolbar.add_buttons_group([ - { - id : 'doPrintView', - label : 'Create static print view', - icon : 'fa-print', - callback : nbconvertPrintView - } - ]) + var load_ipython_extension = function () { + IPython.toolbar.add_buttons_group([ + { + id : 'doPrintView', + label : 'Create static print view', + icon : 'fa-print', + callback : nbconvertPrintView + } + ]) + } + return { + load_ipython_extension : load_ipython_extension + } })
071ebfc41f71078432ad061488cb0b2175ab5668
src/index.js
src/index.js
require('./env'); module.exports = function(config) { config = Object.assign({}, config, { BUGS_TOKEN: process.env.BUGSNAG_TOKEN, LOGS_TOKEN: process.env.LOGENTRIES_TOKEN }); require('./bugsnag')(config.BUGS_TOKEN); require('./winston')(config.LOGS_TOKEN); };
require('./env'); module.exports = function(config) { config = Object.assign({ BUGS_TOKEN: process.env.BUGSNAG_TOKEN, LOGS_TOKEN: process.env.LOGENTRIES_TOKEN }, config); require('./bugsnag')(config.BUGS_TOKEN); require('./winston')(config.LOGS_TOKEN); };
Fix priority order in default config usage (env is not priority)
Fix priority order in default config usage (env is not priority)
JavaScript
mit
dial-once/node-microservice-boot
--- +++ @@ -1,10 +1,10 @@ require('./env'); module.exports = function(config) { - config = Object.assign({}, config, { + config = Object.assign({ BUGS_TOKEN: process.env.BUGSNAG_TOKEN, LOGS_TOKEN: process.env.LOGENTRIES_TOKEN - }); + }, config); require('./bugsnag')(config.BUGS_TOKEN); require('./winston')(config.LOGS_TOKEN);
1519fa8c1a2d92b5ab2f515f920bea3a691eca4f
src/index.js
src/index.js
import './css/app'; console.log('Initiated'); import {postMessage, getMessage} from './js/worker'; document.addEventListener('DOMContentLoaded', init); let workerBlob; require(['raw!../builds/worker'], (val) => { workerBlob = new Blob([val], {type: 'text/javascript'}); console.log(workerBlob); }); function init() { document.querySelector('.btn').addEventListener('click', (ev) => { ev.preventDefault(); console.log('Clicked'); if(!workerBlob) { return; } const workerURL = URL.createObjectURL(workerBlob); const worker = new Worker(workerURL); URL.revokeObjectURL(workerURL); worker.addEventListener('message', (msgEv) => { const data = getMessage(msgEv); console.log('Long Running Process result:', data); }); postMessage(worker, 'GO'); }, false); document.addEventListener('click', () => console.log('Doc clicked')); }
Create app entry main file
Create app entry main file
JavaScript
mit
abhisekp/WebWorker-demo,abhisekp/WebWorker-demo
--- +++ @@ -0,0 +1,33 @@ +import './css/app'; +console.log('Initiated'); +import {postMessage, getMessage} from './js/worker'; + +document.addEventListener('DOMContentLoaded', init); + +let workerBlob; +require(['raw!../builds/worker'], (val) => { + workerBlob = new Blob([val], {type: 'text/javascript'}); + console.log(workerBlob); +}); + +function init() { + document.querySelector('.btn').addEventListener('click', (ev) => { + ev.preventDefault(); + console.log('Clicked'); + + if(!workerBlob) { + return; + } + const workerURL = URL.createObjectURL(workerBlob); + const worker = new Worker(workerURL); + URL.revokeObjectURL(workerURL); + + worker.addEventListener('message', (msgEv) => { + const data = getMessage(msgEv); + console.log('Long Running Process result:', data); + }); + postMessage(worker, 'GO'); + }, false); + + document.addEventListener('click', () => console.log('Doc clicked')); +}
bc7f78fa11cfd51a4bcf28a3d1bc5aa384772224
api/index.js
api/index.js
const { Router } = require('express') const authRoutes = require('./authentication') const usersRoutes = require('./users') const authMiddleware = require('./../middlewares/authentication') const api = (app) => { let api = Router() api.use(authMiddleware) api.get('/', (req, res) => { res.status(200).send({ 'user': req.currentUser }) }) authRoutes(api) usersRoutes(api) return api } module.exports = api
const { Router } = require('express') const authRoutes = require('./authentication') const usersRoutes = require('./users') const customerRoutes = require('./customers') const authMiddleware = require('./../middlewares/authentication') const api = (app) => { let api = Router() api.use(authMiddleware) api.get('/', (req, res) => { res.status(200).send({ 'status': 'OK' }) }) authRoutes(api) usersRoutes(api) customerRoutes(api) return api } module.exports = api
Remove current user data from response and user customer routes
Remove current user data from response and user customer routes
JavaScript
mit
lucasrcdias/customer-mgmt
--- +++ @@ -1,6 +1,7 @@ const { Router } = require('express') const authRoutes = require('./authentication') const usersRoutes = require('./users') +const customerRoutes = require('./customers') const authMiddleware = require('./../middlewares/authentication') const api = (app) => { @@ -9,11 +10,12 @@ api.use(authMiddleware) api.get('/', (req, res) => { - res.status(200).send({ 'user': req.currentUser }) + res.status(200).send({ 'status': 'OK' }) }) authRoutes(api) usersRoutes(api) + customerRoutes(api) return api }
04035fb612629d88a73b04cdca02efc20833e819
cypress/integration/top-bar.spec.js
cypress/integration/top-bar.spec.js
context("Sage top bar UI", () => { beforeEach(() => { cy.visit("/") }) context("new node icon", () => { it("lets you drag a node onto canvas", () => { cy.getSageIframe().find('.proto-node') .trigger('mousedown', { which: 1 }) cy.getSageIframe().find('.ui-droppable') .trigger('mousemove') .trigger('mouseup', { force: true }) cy.getSageIframe().find(".ui-droppable").contains(".elm.ui-draggable", "Untitled") }) }) context("new image icon", () => { it("lets you drag a node onto canvas", () => { cy.getSageIframe().find('.palette-add-image').click() cy.getSageIframe().contains(".modal-dialog-title", "Add new image") }) }) })
context("Sage top bar UI", () => { beforeEach(() => { cy.visit("/") }) context("new node icon", () => { it("lets you drag a node onto canvas", () => { cy.getSageIframe().find('.proto-node') .trigger('mousedown', { which: 1 }) cy.getSageIframe().find('.ui-droppable') .trigger('mousemove') .trigger('mouseup', { force: true }) cy.getSageIframe().find(".ui-droppable").contains(".elm.ui-draggable", "Untitled") }) }) context("new image icon", () => { it("lets you drag a node onto canvas", () => { cy.getSageIframe().find('.palette-add-image').click() cy.getSageIframe().contains(".modal-dialog-title", "Add new image") }) }) context("About menu", () => { it("opens a menu displaying 'About' and 'Help'", () => { cy.getSageIframe().find('.icon-codap-help').click() cy.getSageIframe().contains(".menuItem", "About") cy.getSageIframe().contains(".menuItem", "Help") }) it ("Will display a splash screen when we click on about", () => { cy.getSageIframe().find('.icon-codap-help').click() cy.getSageIframe().contains(".menuItem", "About").click() cy.getSageIframe().contains("#splash-dialog", "Concord Consortium") }); }) })
Add Cypress test for About menu
Add Cypress test for About menu
JavaScript
mit
concord-consortium/building-models,concord-consortium/building-models,concord-consortium/building-models,concord-consortium/building-models,concord-consortium/building-models
--- +++ @@ -22,4 +22,17 @@ cy.getSageIframe().contains(".modal-dialog-title", "Add new image") }) }) + context("About menu", () => { + it("opens a menu displaying 'About' and 'Help'", () => { + cy.getSageIframe().find('.icon-codap-help').click() + cy.getSageIframe().contains(".menuItem", "About") + cy.getSageIframe().contains(".menuItem", "Help") + }) + it ("Will display a splash screen when we click on about", () => { + cy.getSageIframe().find('.icon-codap-help').click() + cy.getSageIframe().contains(".menuItem", "About").click() + cy.getSageIframe().contains("#splash-dialog", "Concord Consortium") + }); + }) + })
012db48868f1770b85925e52dce7628883f6867a
demo/src/index.js
demo/src/index.js
import 'normalize.css'; import React from 'react'; import { render } from 'react-dom'; import ButtonDemo from './components/ButtonDemo'; import './index.css'; render( <main> <ButtonDemo /> </main>, document.getElementById('root') );
import 'normalize.css'; import React from 'react'; import { render } from 'react-dom'; import ButtonDemo from './ButtonDemo'; import './index.css'; render( <main> <ButtonDemo /> </main>, document.getElementById('root') );
Fix access path of the button component
fix(demo): Fix access path of the button component
JavaScript
mit
kripod/material-components-react,kripod/material-components-react
--- +++ @@ -1,7 +1,7 @@ import 'normalize.css'; import React from 'react'; import { render } from 'react-dom'; -import ButtonDemo from './components/ButtonDemo'; +import ButtonDemo from './ButtonDemo'; import './index.css'; render(
d23efb0cd3380ea5a6b3384f4f2fa5ff72466f0b
playground/index.js
playground/index.js
'use strict'; import React, { Component } from 'react'; import Pic from '../lib/index.js'; export default class Playground extends Component { render() { return ( <html> <head> <meta charSet='UTF-8' /> <title>react-pic</title> </head> <body> <div id="root"> <Pic alt='winky face' images={[ { width: 40, url: 'http://placehold.it/40?text=😉' }, { width: 200, url: 'http://placehold.it/200?text=😉' }, { width: 400, url: 'http://placehold.it/400?text=😉' }, { width: 600, url: 'http://placehold.it/600?text=😉' }, { width: 800, url: 'http://placehold.it/800?text=😉' } ]} /> </div> <script src='//localhost:8080/build/react-pic.js' /> </body> </html> ); } }
'use strict'; import React, { Component } from 'react'; import Pic from '../lib/index.js'; export default class Playground extends Component { constructor(props) { super(props); this.state = { show: true }; this.clickHandler = this.clickHandler.bind(this); } clickHandler() { this.setState({show:!this.state.show}); } render() { return ( <html> <head> <meta charSet='UTF-8' /> <title>react-pic</title> </head> <body> <div id="root" style={{height:1500}}> <button onClick={this.clickHandler}> Toggle </button> { this.state.show && <Pic alt='winky face' images={[ { width: 40, url: 'http://placehold.it/40?text=😉' }, { width: 200, url: 'http://placehold.it/200?text=😉' }, { width: 400, url: 'http://placehold.it/400?text=😉' }, { width: 600, url: 'http://placehold.it/600?text=😉' }, { width: 800, url: 'http://placehold.it/800?text=😉' } ]} /> } </div> <script src='//localhost:8080/build/react-pic.js' /> </body> </html> ); } }
Add button that toggles `<Pic>` to make it easier to develop for unmount
Add button that toggles `<Pic>` to make it easier to develop for unmount
JavaScript
mit
benox3/react-pic
--- +++ @@ -4,6 +4,18 @@ import Pic from '../lib/index.js'; export default class Playground extends Component { + constructor(props) { + super(props); + this.state = { + show: true + }; + this.clickHandler = this.clickHandler.bind(this); + } + + clickHandler() { + this.setState({show:!this.state.show}); + } + render() { return ( <html> @@ -12,31 +24,37 @@ <title>react-pic</title> </head> <body> - <div id="root"> - <Pic - alt='winky face' - images={[ - { - width: 40, - url: 'http://placehold.it/40?text=😉' - }, - { - width: 200, - url: 'http://placehold.it/200?text=😉' - }, - { - width: 400, - url: 'http://placehold.it/400?text=😉' - }, - { - width: 600, - url: 'http://placehold.it/600?text=😉' - }, - { - width: 800, - url: 'http://placehold.it/800?text=😉' - } - ]} /> + <div id="root" style={{height:1500}}> + <button onClick={this.clickHandler}> + Toggle + </button> + { + this.state.show && + <Pic + alt='winky face' + images={[ + { + width: 40, + url: 'http://placehold.it/40?text=😉' + }, + { + width: 200, + url: 'http://placehold.it/200?text=😉' + }, + { + width: 400, + url: 'http://placehold.it/400?text=😉' + }, + { + width: 600, + url: 'http://placehold.it/600?text=😉' + }, + { + width: 800, + url: 'http://placehold.it/800?text=😉' + } + ]} /> + } </div> <script src='//localhost:8080/build/react-pic.js' /> </body>
dd80f254f407429aeaf5ca5c4fb414363836c267
src/karma.conf.js
src/karma.conf.js
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: require('path').join(__dirname, '../coverage'), reports: ['html', 'lcovonly'], fixWebpackSourcePaths: true }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }); };
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: require('path').join(__dirname, '../coverage'), reports: ['html', 'lcovonly'], fixWebpackSourcePaths: true }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox'] } }, singleRun: false }); };
Add custom launcher for karma
Add custom launcher for karma
JavaScript
mit
dzonatan/angular2-linky,dzonatan/angular2-linky
--- +++ @@ -26,6 +26,12 @@ logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], + customLaunchers: { + ChromeHeadlessNoSandbox: { + base: 'ChromeHeadless', + flags: ['--no-sandbox'] + } + }, singleRun: false }); };
f0b03d64e8e43781fe3fe97f6f6de4f4a1da1705
jobs/search-items.js
jobs/search-items.js
const WMASGSpider = require('../wmasg-spider'); class SearchItems { constructor(concurrency = 5) { this.title = 'search items'; this.concurrency = concurrency; } process(job, done) { const spider = new WMASGSpider(); spider.on('error', error => done(error)); spider.on('end', () => done()); spider.on('item', item => console.log(item)); spider.start(); } } module.exports = SearchItems;
const WMASGSpider = require('../wmasg-spider'); class SearchItems { constructor(concurrency = 5) { this.title = 'search items'; this.concurrency = concurrency; } match(item, expression) { return item.title.toLowerCase().match(expression) || item.description.toLowerCase().match(expression); } process(job, done) { const spider = new WMASGSpider(); const {keywords, price} = job.data; const expression = new RegExp(`(${keywords.join('|')})`, 'g'); const items = []; spider.on('error', error => done(error)); spider.on('end', () => done(null, items)); spider.on('item', item => { if ((!price || item.price <= price) && this.match(item, expression)) { items.push(item); } }); spider.start(); } } module.exports = SearchItems;
Implement filtering items by keywords and price and passing result back
Implement filtering items by keywords and price and passing result back
JavaScript
mit
adrianrutkowski/wmasg-crawler
--- +++ @@ -6,12 +6,23 @@ this.concurrency = concurrency; } + match(item, expression) { + return item.title.toLowerCase().match(expression) || item.description.toLowerCase().match(expression); + } + process(job, done) { const spider = new WMASGSpider(); + const {keywords, price} = job.data; + const expression = new RegExp(`(${keywords.join('|')})`, 'g'); + const items = []; spider.on('error', error => done(error)); - spider.on('end', () => done()); - spider.on('item', item => console.log(item)); + spider.on('end', () => done(null, items)); + spider.on('item', item => { + if ((!price || item.price <= price) && this.match(item, expression)) { + items.push(item); + } + }); spider.start(); }
f24a110d489a35705477ec1332fb9a148a26b609
api/models/user.js
api/models/user.js
'use strict' let mongoose = require('mongoose') mongoose.Promise = global.Promise let Schema = mongoose.Schema let UserSchema = new Schema({ email: String, password: String, CMDRs: { default: [], type: [{ type: Schema.Types.ObjectId, ref: 'Rat' }] }, nicknames: { default: [], type: [{ type: String }] }, drilled: { default: { dispatch: false, rescue: false }, type: { dispatch: { type: Boolean }, rescue: { type: Boolean } } }, resetToken: String, resetTokenExpire: Date }) let autopopulate = function (next) { this.populate('CMDRs') next() } UserSchema.pre('find', autopopulate) UserSchema.pre('findOne', autopopulate) UserSchema.methods.toJSON = function () { let obj = this.toObject() delete obj.hash delete obj.salt delete obj.resetToken delete obj.resetTokenExpire return obj } UserSchema.plugin(require('passport-local-mongoose'), { usernameField: 'email' }) module.exports = mongoose.model('User', UserSchema)
'use strict' let mongoose = require('mongoose') mongoose.Promise = global.Promise let Schema = mongoose.Schema let UserSchema = new Schema({ email: String, password: String, CMDRs: { default: [], type: [{ type: Schema.Types.ObjectId, ref: 'Rat' }] }, nicknames: { default: [], type: [{ type: String }] }, drilled: { default: { dispatch: false, rescue: false }, type: { dispatch: { type: Boolean }, rescue: { type: Boolean } } }, group: { default: 'normal', enum: [ 'normal', 'overseer', 'moderator', 'admin' ], type: String }, resetToken: String, resetTokenExpire: Date }) let autopopulate = function (next) { this.populate('CMDRs') next() } UserSchema.pre('find', autopopulate) UserSchema.pre('findOne', autopopulate) UserSchema.methods.toJSON = function () { let obj = this.toObject() delete obj.hash delete obj.salt delete obj.resetToken delete obj.resetTokenExpire return obj } UserSchema.plugin(require('passport-local-mongoose'), { usernameField: 'email' }) module.exports = mongoose.model('User', UserSchema)
Add permission group field to User object.
Add permission group field to User object. #25
JavaScript
bsd-3-clause
FuelRats/api.fuelrats.com,FuelRats/api.fuelrats.com,FuelRats/api.fuelrats.com
--- +++ @@ -35,6 +35,16 @@ } } }, + group: { + default: 'normal', + enum: [ + 'normal', + 'overseer', + 'moderator', + 'admin' + ], + type: String + }, resetToken: String, resetTokenExpire: Date })
30716f7acac0bf738d32b9c69aca84b59872a821
src/components/posts_new.js
src/components/posts_new.js
import React from 'react'; import { Field, reduxForm } from 'redux-form'; class PostsNew extends React.Component { renderField(field) { return ( <div className='form-group'> <label>{field.label}</label> <input className='form-control' type='text' {...field.input} /> </div> ); } render() { return ( <form className='posts-new'> <Field label='Title' name='title' component={this.renderField} /> <Field label='Categories' name='categories' component={this.renderField} /> <Field label='Post Content' name='content' component={this.renderField} /> </form> ); } } export default reduxForm({ form: 'PostsNewForm' })(PostsNew);
import React from 'react'; import { Field, reduxForm } from 'redux-form'; class PostsNew extends React.Component { renderField(field) { return ( <div className='form-group'> <label>{field.label}</label> <input className='form-control' type='text' {...field.input} /> </div> ); } render() { return ( <form className='posts-new'> <Field label='Title' name='title' component={this.renderField} /> <Field label='Categories' name='categories' component={this.renderField} /> <Field label='Post Content' name='content' component={this.renderField} /> </form> ); } } function validate(values) { const errors = {}; if (!values.title) { errors.title = "Enter a title"; } if (!values.categories) { errors.categories = "Enter categories"; } if (!values.content values.content.length < 10) { errors.content = "Enter content"; } return errors; } export default reduxForm({ validate: validate, form: 'PostsNewForm' })(PostsNew);
Add initial validations (using redux forms)
Add initial validations (using redux forms)
JavaScript
mit
monsteronfire/redux-learning-blog,monsteronfire/redux-learning-blog
--- +++ @@ -38,6 +38,25 @@ } } +function validate(values) { + const errors = {}; + + if (!values.title) { + errors.title = "Enter a title"; + } + + if (!values.categories) { + errors.categories = "Enter categories"; + } + + if (!values.content values.content.length < 10) { + errors.content = "Enter content"; + } + + return errors; +} + export default reduxForm({ + validate: validate, form: 'PostsNewForm' })(PostsNew);
d52129c5d915e260d4d86914326606f305ad4ed0
experiments/modern/src/maki-interpreter/interpreter.js
experiments/modern/src/maki-interpreter/interpreter.js
const parse = require("./parser"); const { getClass } = require("./objects"); const interpret = require("./virtualMachine"); function main({ runtime, data, system, log }) { const program = parse(data); // Set the System global program.variables[0].setValue(system); // Replace class hashes with actual JavaScript classes from the runtime program.classes = program.classes.map(hash => { const resolved = runtime[hash]; if (resolved == null && log) { const klass = getClass(hash); console.warn( `Class missing from runtime: ${hash} expected ${klass.name}` ); } return resolved; }); // Bind toplevel handlers. program.bindings.forEach(binding => { const handler = () => { return interpret(binding.commandOffset, program, { log }); }; // For now we only know how to handle System handlers. if (binding.variableOffset === 0) { const obj = program.variables[binding.variableOffset].getValue(); const method = program.methods[binding.methodOffset]; obj[method.name](handler); } else { console.warn( "Not Implemented: Not binding to non-system events", binding ); } }); system._start(); } module.exports = main;
const parse = require("./parser"); const { getClass, getFormattedId } = require("./objects"); const interpret = require("./virtualMachine"); function main({ runtime, data, system, log }) { const program = parse(data); // Set the System global program.variables[0].setValue(system); // Replace class hashes with actual JavaScript classes from the runtime program.classes = program.classes.map(hash => { const resolved = runtime[hash]; if (resolved == null && log) { const klass = getClass(hash); console.warn( `Class missing from runtime: ${hash}`, klass == null ? `(formatted ID: ${getFormattedId(hash)})` : `expected ${klass.name}` ); } return resolved; }); // Bind toplevel handlers. program.bindings.forEach(binding => { const handler = () => { return interpret(binding.commandOffset, program, { log }); }; // For now we only know how to handle System handlers. if (binding.variableOffset === 0) { const obj = program.variables[binding.variableOffset].getValue(); const method = program.methods[binding.methodOffset]; obj[method.name](handler); } else { console.warn( "Not Implemented: Not binding to non-system events", binding ); } }); system._start(); } module.exports = main;
Improve error message for missing classes
Improve error message for missing classes
JavaScript
mit
captbaritone/winamp2-js,captbaritone/winamp2-js,captbaritone/winamp2-js
--- +++ @@ -1,5 +1,5 @@ const parse = require("./parser"); -const { getClass } = require("./objects"); +const { getClass, getFormattedId } = require("./objects"); const interpret = require("./virtualMachine"); function main({ runtime, data, system, log }) { @@ -14,7 +14,10 @@ if (resolved == null && log) { const klass = getClass(hash); console.warn( - `Class missing from runtime: ${hash} expected ${klass.name}` + `Class missing from runtime: ${hash}`, + klass == null + ? `(formatted ID: ${getFormattedId(hash)})` + : `expected ${klass.name}` ); } return resolved;
20589a3fbfb61328a93a71eda4a90f07d6d0aa23
mac/resources/open_ATXT.js
mac/resources/open_ATXT.js
define(['mac/roman'], function(macRoman) { 'use strict'; function open(item) { return item.getBytes().then(function(bytes) { item.setDataObject(new TextView(bytes.buffer, bytes.byteOffset, bytes.byteLength)); }); }; function TextView(buffer, byteOffset, byteLength) { this.dataView = new DataView(buffer, byteOffset, byteLength); }; TextView.prototype = { toJSON: function() { return { top: this.top, left: this.left, bottom: this.bottom, right: this.right, fontType: this.fontType, fontSize: this.fontSize, text: this.text, }; }, get top() { return this.dataView.getInt16(0, false); }, get left() { return this.dataView.getInt16(2, false); }, get bottom() { return this.dataView.getInt16(4, false); }, get right() { return this.dataView.getInt16(6, false); }, get fontType() { return this.dataView.getUint16(8, false); }, get fontSize() { return this.dataView.getUint16(10, false); }, get text() { return macRoman(this.bytes, 12); }, }; return open; });
define(['mac/roman'], function(macRoman) { 'use strict'; function open(item) { return item.getBytes().then(function(bytes) { item.setDataObject(new TextView(bytes.buffer, bytes.byteOffset, bytes.byteLength)); }); }; function TextView(buffer, byteOffset, byteLength) { this.dataView = new DataView(buffer, byteOffset, byteLength); this.bytes = new Uint8Array(buffer, byteOffset, byteLength); }; TextView.prototype = { toJSON: function() { return { top: this.top, left: this.left, bottom: this.bottom, right: this.right, fontType: this.fontType, fontSize: this.fontSize, text: this.text, }; }, get top() { return this.dataView.getInt16(0, false); }, get left() { return this.dataView.getInt16(2, false); }, get bottom() { return this.dataView.getInt16(4, false); }, get right() { return this.dataView.getInt16(6, false); }, get fontType() { return this.dataView.getUint16(8, false); }, get fontSize() { return this.dataView.getUint16(10, false); }, get text() { return macRoman(this.bytes, 12); }, }; return open; });
Put in missing bytes field
Put in missing bytes field
JavaScript
mit
radishengine/drowsy,radishengine/drowsy
--- +++ @@ -10,6 +10,7 @@ function TextView(buffer, byteOffset, byteLength) { this.dataView = new DataView(buffer, byteOffset, byteLength); + this.bytes = new Uint8Array(buffer, byteOffset, byteLength); }; TextView.prototype = { toJSON: function() {
6143f9ef9701b92ec38aa12f4be2b1c94e4394cd
app/models/user.js
app/models/user.js
var Bcrypt = require('bcryptjs') var Mongoose = require('../../database').Mongoose var ObjectId = Mongoose.Schema.Types.ObjectId; var userSchema = new Mongoose.Schema({ username: { type : String, required: true }, password: { type : String, required: true }, email: { type : String, required: true }, token: { type : String, default: '_' }, registrationDate: { type : Date, default: Date.now }, channels: [Mongoose.Schema.Types.Mixed] }) userSchema.pre('save', function (next) { var user = this if (this.isModified('password') || this.isNew) { Bcrypt.genSalt(10, function (error, salt) { if (error) { return next(error) } Bcrypt.hash(user.password, salt, function (error, hash) { if (error) { return next(error) } user.password = hash next() }) }) } else { return next() } }) userSchema.methods.comparePassword = function (pwd, callback) { Bcrypt.compare(pwd, this.password, function (error, isMatch) { if (error) { return callback(error) } callback(null, isMatch) }) } exports.User = Mongoose.model('User', userSchema)
var Bcrypt = require('bcryptjs') var Mongoose = require('../../database').Mongoose var ObjectId = Mongoose.Schema.Types.ObjectId; var userSchema = new Mongoose.Schema({ username: { type : String, required: true }, password: { type : String, required: true }, email: { type : String, required: true }, token: { type : String, default: '_' }, registrationDate: { type : Date, default: Date.now }, channels: [{ type: ObjectId, ref: 'Channel' }] }) userSchema.pre('save', function (next) { var user = this if (this.isModified('password') || this.isNew) { Bcrypt.genSalt(10, function (error, salt) { if (error) { return next(error) } Bcrypt.hash(user.password, salt, function (error, hash) { if (error) { return next(error) } user.password = hash next() }) }) } else { return next() } }) userSchema.methods.comparePassword = function (pwd, callback) { Bcrypt.compare(pwd, this.password, function (error, isMatch) { if (error) { return callback(error) } callback(null, isMatch) }) } exports.User = Mongoose.model('User', userSchema)
Change mixed type to array json
Change mixed type to array json
JavaScript
mit
fitraditya/Obrel
--- +++ @@ -24,7 +24,10 @@ type : Date, default: Date.now }, - channels: [Mongoose.Schema.Types.Mixed] + channels: [{ + type: ObjectId, + ref: 'Channel' + }] }) userSchema.pre('save', function (next) {
f345e428c9d7766ee5945f1d1d2cbb6e64c24ce4
assets/js/index.js
assets/js/index.js
new Vue({ el: '#app', delimiters: ['[[', ']]'], data: { search: '', activeNote: window.location.href.split('#')[1] }, methods: { seeNote: function (note) { this.activeNote = note } }, updated: function () { var ulElem for (var refName in this.$refs) { ulElem = this.$refs[refName] if (ulElem.getElementsByTagName('a').length === 0) { ulElem.style.display = 'none' ulElem.previousElementSibling.style.display = 'none' } else { ulElem.style.display = '' ulElem.previousElementSibling.style.display = '' } } }, mounted: function () { window.addEventListener('keydown', function(e) { // Autofocus only on backspace and letters if (e.keyCode !== 8 && (e.keyCode < 65 || e.keyCode > 90)) { return; } if (document.activeElement.id !== 'search') { document.getElementById('search').focus() } }) } })
new Vue({ el: '#app', delimiters: ['[[', ']]'], data: { search: '', activeNote: window.location.href.split('#')[1] }, methods: { seeNote: function (note) { this.activeNote = note } }, updated: function () { var ulElem for (var refName in this.$refs) { ulElem = this.$refs[refName] if (ulElem.getElementsByTagName('a').length === 0) { ulElem.style.display = 'none' ulElem.previousElementSibling.style.display = 'none' } else { ulElem.style.display = '' ulElem.previousElementSibling.style.display = '' } } }, mounted: function () { window.addEventListener('keydown', function(e) { var ctrl = e.ctrlKey var backspace = e.keyCode === 8 var slash = e.keyCode === 191 var letter = e.keyCode >= 65 && e.keyCode <= 90 if (!ctrl && (backspace || slash || letter)) { document.getElementById('search').focus() } }) } })
Improve automatic focus to the search input
Improve automatic focus to the search input
JavaScript
mit
Yutsuten/Yutsuten.github.io,Yutsuten/Yutsuten.github.io,Yutsuten/Yutsuten.github.io
--- +++ @@ -25,11 +25,11 @@ }, mounted: function () { window.addEventListener('keydown', function(e) { - // Autofocus only on backspace and letters - if (e.keyCode !== 8 && (e.keyCode < 65 || e.keyCode > 90)) { - return; - } - if (document.activeElement.id !== 'search') { + var ctrl = e.ctrlKey + var backspace = e.keyCode === 8 + var slash = e.keyCode === 191 + var letter = e.keyCode >= 65 && e.keyCode <= 90 + if (!ctrl && (backspace || slash || letter)) { document.getElementById('search').focus() } })
561c08e0ccf70290b5c6c098b4a4b77fd5756b51
Resources/Plugins/.debug/browser.js
Resources/Plugins/.debug/browser.js
enabled(){ this.isDebugging = false; this.onKeyDown = (e) => { // ========================== // F4 key - toggle debug mode // ========================== if (e.keyCode === 115){ this.isDebugging = !this.isDebugging; $(".app-title").first().css("background-color", this.isDebugging ? "#5A6B75" : "#292F33"); } // Debug mode handling else if (this.isDebugging){ e.preventDefault(); // =================================== // N key - simulate popup notification // S key - simulate sound notification // =================================== if (e.keyCode === 78 || e.keyCode === 83){ var col = TD.controller.columnManager.getAllOrdered()[0]; var prevPopup = col.model.getHasNotification(); var prevSound = col.model.getHasSound(); col.model.setHasNotification(e.keyCode === 78); col.model.setHasSound(e.keyCode === 83); $.publish("/notifications/new",[{ column: col, items: [ col.updateArray[Math.floor(Math.random()*col.updateArray.length)] ] }]); setTimeout(function(){ col.model.setHasNotification(prevPopup); col.model.setHasSound(prevSound); }, 1); } } }; } ready(){ $(document).on("keydown", this.onKeyDown); } disabled(){ $(document).off("keydown", this.onKeyDown); }
enabled(){ this.isDebugging = false; this.onKeyDown = (e) => { // ========================== // F4 key - toggle debug mode // ========================== if (e.keyCode === 115){ this.isDebugging = !this.isDebugging; $(".nav-user-info").first().css("background-color", this.isDebugging ? "#5A6B75" : "#292F33"); } // Debug mode handling else if (this.isDebugging){ e.preventDefault(); // =================================== // N key - simulate popup notification // S key - simulate sound notification // =================================== if (e.keyCode === 78 || e.keyCode === 83){ var col = TD.controller.columnManager.getAllOrdered()[0]; var prevPopup = col.model.getHasNotification(); var prevSound = col.model.getHasSound(); col.model.setHasNotification(e.keyCode === 78); col.model.setHasSound(e.keyCode === 83); $.publish("/notifications/new",[{ column: col, items: [ col.updateArray[Math.floor(Math.random()*col.updateArray.length)] ] }]); setTimeout(function(){ col.model.setHasNotification(prevPopup); col.model.setHasSound(prevSound); }, 1); } } }; } ready(){ $(document).on("keydown", this.onKeyDown); } disabled(){ $(document).off("keydown", this.onKeyDown); }
Fix debug plugin after hiding app title
Fix debug plugin after hiding app title
JavaScript
mit
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
--- +++ @@ -8,7 +8,7 @@ if (e.keyCode === 115){ this.isDebugging = !this.isDebugging; - $(".app-title").first().css("background-color", this.isDebugging ? "#5A6B75" : "#292F33"); + $(".nav-user-info").first().css("background-color", this.isDebugging ? "#5A6B75" : "#292F33"); } // Debug mode handling
7249234061e8791ccbee5d0e3b8578d8595e43f8
tests/unit/classes/ModuleLoader.js
tests/unit/classes/ModuleLoader.js
var utils = require('utils') , env = utils.bootstrapEnv() , moduleLdr = env.moduleLoader , injector = require('injector') , ncp = require('ncp') , path = require('path') , async = require('async'); describe('ModuleLoader', function() { before(function(done) { var source = path.resolve(__dirname, '..', 'test-module') , dest = path.resolve(__dirname, '..', '..', '..', 'modules', 'test-module'); // Copy the test-module into the modules folder ncp(source, dest, done); }); it('should load modules', function(done) { this.timeout(20000); moduleLdr.on('modulesLoaded', function() { async.parallel( [ function ormDb(callback) { if (moduleLdr.moduleIsEnabled('clever-orm') === true) { injector .getInstance('sequelize') .sync({ force: true }) .then(function() { callback(null); }) .catch(callback); } else { callback(null); } }, function odmDb(callback) { callback(null); } ], function(err) { if (err !== undefined && err !== null) { console.dir(err); return done(err); } done(); } ); }); moduleLdr.loadModules(); }); it('should initialize all module routes', function(done) { moduleLdr.on('routesInitialized', function() { done(); }); moduleLdr.initializeRoutes(); }); });
var utils = require('utils') , env = utils.bootstrapEnv() , moduleLdr = env.moduleLoader , injector = require('injector') , ncp = require('ncp') , path = require('path') , async = require('async'); describe('ModuleLoader', function() { it('should load modules', function(done) { this.timeout(20000); moduleLdr.on('modulesLoaded', function() { async.parallel( [ function ormDb(callback) { if (moduleLdr.moduleIsEnabled('clever-orm') === true) { injector .getInstance('sequelize') .sync({ force: true }) .then(function() { callback(null); }) .catch(callback); } else { callback(null); } }, function odmDb(callback) { callback(null); } ], function(err) { if (err !== undefined && err !== null) { console.dir(err); return done(err); } done(); } ); }); moduleLdr.loadModules(); }); it('should initialize all module routes', function(done) { moduleLdr.on('routesInitialized', function() { done(); }); moduleLdr.initializeRoutes(); }); });
Remove old code for copying test-module
chore(cleanup): Remove old code for copying test-module
JavaScript
mit
CleverStack/node-seed
--- +++ @@ -7,14 +7,6 @@ , async = require('async'); describe('ModuleLoader', function() { - - before(function(done) { - var source = path.resolve(__dirname, '..', 'test-module') - , dest = path.resolve(__dirname, '..', '..', '..', 'modules', 'test-module'); - - // Copy the test-module into the modules folder - ncp(source, dest, done); - }); it('should load modules', function(done) { this.timeout(20000);
021c5e27be8e909bd7a56fc794e9a9d6c15cef9a
utilities/execution-environment.js
utilities/execution-environment.js
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */ /* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */ const canUseDOM = !!( typeof window !== 'undefined' && window.document && window.document.createElement ); const ExecutionEnvironment = { canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, }; export default ExecutionEnvironment;
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */ /* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */ const canUseDOM = !!( typeof window !== 'undefined' && window.document && window.document.createElement ); const canUseWorkers = typeof Worker !== 'undefined'; const canUseEventListeners = canUseDOM && !!(window.addEventListener || window.attachEvent); const canUseViewport = canUseDOM && !!window.screen; export { canUseDOM, canUseWorkers, canUseEventListeners, canUseViewport, };
Change exports for Execution Environment
Change exports for Execution Environment This reverts the export which is resulting in canUseDOM’s value equaling undefined.
JavaScript
bsd-3-clause
salesforce/design-system-react,salesforce/design-system-react,salesforce/design-system-react
--- +++ @@ -6,13 +6,13 @@ window.document && window.document.createElement ); +const canUseWorkers = typeof Worker !== 'undefined'; +const canUseEventListeners = canUseDOM && !!(window.addEventListener || window.attachEvent); +const canUseViewport = canUseDOM && !!window.screen; -const ExecutionEnvironment = { +export { canUseDOM, - canUseWorkers: typeof Worker !== 'undefined', - canUseEventListeners: - canUseDOM && !!(window.addEventListener || window.attachEvent), - canUseViewport: canUseDOM && !!window.screen, + canUseWorkers, + canUseEventListeners, + canUseViewport, }; - -export default ExecutionEnvironment;
2d3838b5391f65fd7abc4975eb0eb153f54386db
lib/sort_versions.js
lib/sort_versions.js
'use strict'; var Semvish = require('semvish'); module.exports = function(arr) { if(!arr) { return; } return arr.slice().sort(Semvish.compare).reverse(); };
'use strict'; var Semvish = require('semvish'); module.exports = function(arr) { if(!arr) { return; } return arr.slice().sort(Semvish.rcompare); };
Use rcomp instead of .reverse() in sort
Use rcomp instead of .reverse() in sort
JavaScript
mit
MartinKolarik/api-sync,jsdelivr/api-sync,MartinKolarik/api-sync,jsdelivr/api-sync
--- +++ @@ -8,5 +8,5 @@ return; } - return arr.slice().sort(Semvish.compare).reverse(); + return arr.slice().sort(Semvish.rcompare); };
4d04ef3b914405a29f42a07e8652967146fbefe6
static/js/main.js
static/js/main.js
require.config({ paths: { jquery: "/static/js/libs/jquery-min", underscore: "/static/js/libs/underscore-min", backbone: "/static/js/libs/backbone-min", mustache: "/static/js/libs/mustache", }, shim: { jquery: { exports: "$" }, underscore: { exports: "_" }, backbone: { deps: ["underscore", "jquery"], exports: "Backbone" } } }); require(["jquery", "underscore","backbone", "mustache"], function ($, _, Backbone, Mustache) { $(function () { // the search bar var SearchBar = Backbone.Model.extend({ initialize: function () { this.bind("change:position", function () { // TODO: change CSS class console.log("position changed!"); }); }, defaults: { position: "center" // the current location of the search bar/box } }); var SearchBarView = Backbone.View.extend({ id: "search-bar", className: "search-bar-position-center" }); // a suggestion below the search bar var AutocompleteSuggestion = Backbone.Model.extend({ defaults: { originator: null, text: "" } }); var AutocompleteSuggestionCollection = Backbone.Collection.extend({ model: AutocompleteSuggestion }); // ** END ** }); });
require.config({ paths: { jquery: "/static/js/libs/jquery-min", underscore: "/static/js/libs/underscore-min", backbone: "/static/js/libs/backbone-min", mustache: "/static/js/libs/mustache", }, shim: { jquery: { exports: "$" }, underscore: { exports: "_" }, backbone: { deps: ["underscore", "jquery"], exports: "Backbone" } }, // add dummy params to break caching urlArgs: "__nocache__=" + (new Date()).getTime() }); require(["jquery", "underscore","backbone", "mustache"], function ($, _, Backbone, Mustache) { $(function () { // the search bar var SearchBar = Backbone.Model.extend({ initialize: function () { this.bind("change:position", function () { // TODO: change CSS class console.log("position changed!"); }); }, defaults: { position: "center" // the current location of the search bar/box } }); var SearchBarView = Backbone.View.extend({ id: "search-bar", className: "search-bar-position-center" }); // a suggestion below the search bar var AutocompleteSuggestion = Backbone.Model.extend({ defaults: { originator: null, text: "" } }); var AutocompleteSuggestionCollection = Backbone.Collection.extend({ model: AutocompleteSuggestion }); // ** END ** }); });
Add dummy param to break caching
Add dummy param to break caching
JavaScript
mit
jasontbradshaw/multivid,jasontbradshaw/multivid
--- +++ @@ -16,7 +16,10 @@ deps: ["underscore", "jquery"], exports: "Backbone" } - } + }, + + // add dummy params to break caching + urlArgs: "__nocache__=" + (new Date()).getTime() }); require(["jquery", "underscore","backbone", "mustache"],
de03d876a5ddd7e82627441219d446e9f0d64275
server/controllers/students.js
server/controllers/students.js
//var Teachers = require('../models/teachers'); //var TeacherClasses = require('../models/Teacher_classes'); //var Classes = require('../models/classes'); //var ClassLessons = require('../models/class_lessons'); // var Lessons = require('../models/lessons'); //var RequestedResponses = require('../models/requested_responses'); module.exports = { readyStage : function(io, req, res, next) { //var studentInformation = req.body.studentData var pollResponse = { responseId: 1, type: 'thumbs', datetime: new Date(), lessonId: 13, }; io.on('connection', function(student){ student.emit('studentStandby', studentInformation); student.on('teacherConnect', function() { student.emit('teacherConnect'); }); student.on('newPoll', function(data) { student.emit(data); }); setTimeout(function(){ io.sockets.emit('responseFromStudent', pollResponse); }, 5000); }); res.status(200).send('Hello from the other side'); } };
//var Teachers = require('../models/teachers'); //var TeacherClasses = require('../models/Teacher_classes'); //var Classes = require('../models/classes'); //var ClassLessons = require('../models/class_lessons'); // var Lessons = require('../models/lessons'); //var RequestedResponses = require('../models/requested_responses'); module.exports = { readyStage : function(io, req, res, next) { //var studentInformation = req.body.studentData var pollResponse = { responseId: 1, type: 'thumbs', datetime: new Date(), lessonId: 13, }; io.on('connection', function(student){ student.emit('studentStandby', studentInformation); student.on('newPoll', function(data) { student.emit(data); }); setTimeout(function(){ io.sockets.emit('responseFromStudent', pollResponse); }, 5000); }); res.status(200).send('Hello from the student side'); } };
Remove teacherConnect socket event for frontend handling
Remove teacherConnect socket event for frontend handling
JavaScript
mit
shanemcgraw/thumbroll,Jakeyrob/thumbroll,absurdSquid/thumbroll,absurdSquid/thumbroll,Jakeyrob/thumbroll,Jakeyrob/thumbroll,shanemcgraw/thumbroll,shanemcgraw/thumbroll
--- +++ @@ -21,10 +21,6 @@ student.emit('studentStandby', studentInformation); - student.on('teacherConnect', function() { - student.emit('teacherConnect'); - }); - student.on('newPoll', function(data) { student.emit(data); }); @@ -34,6 +30,6 @@ }, 5000); }); - res.status(200).send('Hello from the other side'); + res.status(200).send('Hello from the student side'); } };
6d5ba4db94939c5f29451df363c9f6afd9740779
src/assets/dosamigos-ckeditor.widget.js
src/assets/dosamigos-ckeditor.widget.js
/** * @copyright Copyright (c) 2012-2015 2amigOS! Consulting Group LLC * @link http://2amigos.us * @license http://www.opensource.org/licenses/bsd-license.php New BSD License */ if (typeof dosamigos == "undefined" || !dosamigos) { var dosamigos = {}; } dosamigos.ckEditorWidget = (function ($) { var pub = { registerOnChangeHandler: function (id) { CKEDITOR && CKEDITOR.instances[id] && CKEDITOR.instances[id].on('change', function () { CKEDITOR.instances[id].updateElement(); $('#' + id).trigger('change'); return false; }); }, registerCsrfImageUploadHandler: function () { yii & $(document).off('click', '.cke_dialog_tabs a:eq(2)').on('click', '.cke_dialog_tabs a:eq(2)', function () { var $form = $('.cke_dialog_ui_input_file iframe').contents().find('form'); var csrfName = yii.getCsrfParam(); if (!$form.find('input[name=' + csrfName + ']').length) { var csrfTokenInput = $('<input/>').attr({ 'type': 'hidden', 'name': csrfName }).val(yii.getCsrfToken()); $form.append(csrfTokenInput); } }); } }; return pub; })(jQuery);
/** * @copyright Copyright (c) 2012-2015 2amigOS! Consulting Group LLC * @link http://2amigos.us * @license http://www.opensource.org/licenses/bsd-license.php New BSD License */ if (typeof dosamigos == "undefined" || !dosamigos) { var dosamigos = {}; } dosamigos.ckEditorWidget = (function ($) { var pub = { registerOnChangeHandler: function (id) { CKEDITOR && CKEDITOR.instances[id] && CKEDITOR.instances[id].on('change', function () { CKEDITOR.instances[id].updateElement(); $('#' + id).trigger('change'); return false; }); }, registerCsrfImageUploadHandler: function () { yii & $(document).off('click', '.cke_dialog_tabs a:eq(1), .cke_dialog_tabs a:eq(2)').on('click', '.cke_dialog_tabs a:eq(1), .cke_dialog_tabs a:eq(2)', function () { var $form = $('.cke_dialog_ui_input_file iframe').contents().find('form'); var csrfName = yii.getCsrfParam(); if (!$form.find('input[name=' + csrfName + ']').length) { var csrfTokenInput = $('<input/>').attr({ 'type': 'hidden', 'name': csrfName }).val(yii.getCsrfToken()); $form.append(csrfTokenInput); } }); } }; return pub; })(jQuery);
Fix bug with csrf token
Fix bug with csrf token
JavaScript
bsd-3-clause
yangtoude/yii2-ckeditor-widget,richardfan1126/yii2-ckeditor-widget,alexdin/yii2-ckeditor-widget,richardfan1126/yii2-ckeditor-widget,richardfan1126/yii2-ckeditor-widget,yangtoude/yii2-ckeditor-widget,alexdin/yii2-ckeditor-widget,yangtoude/yii2-ckeditor-widget
--- +++ @@ -18,7 +18,7 @@ }); }, registerCsrfImageUploadHandler: function () { - yii & $(document).off('click', '.cke_dialog_tabs a:eq(2)').on('click', '.cke_dialog_tabs a:eq(2)', function () { + yii & $(document).off('click', '.cke_dialog_tabs a:eq(1), .cke_dialog_tabs a:eq(2)').on('click', '.cke_dialog_tabs a:eq(1), .cke_dialog_tabs a:eq(2)', function () { var $form = $('.cke_dialog_ui_input_file iframe').contents().find('form'); var csrfName = yii.getCsrfParam(); if (!$form.find('input[name=' + csrfName + ']').length) {
55b2c19f6abe49e242a87853250d7da3dec26762
route-urls.js
route-urls.js
var m = angular.module("routeUrls", []); m.factory("urls", function($route) { var pathsByName = {}; angular.forEach($route.routes, function (route, path) { if (route.name) { pathsByName[route.name] = path; } }); var regexs = {}; var path = function (name, params) { var url = pathsByName[name] || "/"; angular.forEach(params || {}, function (value, key) { var regex = regexs[key]; if (regex === undefined) { regex = regexs[key] = new RegExp(":" + key + "(/|$)"); } url = url.replace(regex, value); }); return url; }; return { path: path, href: function (name, params) { return "#" + path(name, params); } }; });
var m = angular.module("routeUrls", []); m.factory("urls", function($route) { var pathsByName = {}; angular.forEach($route.routes, function (route, path) { if (route.name) { pathsByName[route.name] = path; } }); var regexs = {}; var path = function (name, params) { var url = pathsByName[name] || "/"; angular.forEach(params || {}, function (value, key) { var regex = regexs[key]; if (regex === undefined) { regex = regexs[key] = new RegExp(":" + key + "(?=/|$)"); } url = url.replace(regex, value); }); return url; }; return { path: path, href: function (name, params) { return "#" + path(name, params); } }; });
Resolve regex forward lookahead issue
Resolve regex forward lookahead issue
JavaScript
mit
emgee/angular-route-urls,emgee/angular-route-urls
--- +++ @@ -17,7 +17,7 @@ var regex = regexs[key]; if (regex === undefined) { - regex = regexs[key] = new RegExp(":" + key + "(/|$)"); + regex = regexs[key] = new RegExp(":" + key + "(?=/|$)"); } url = url.replace(regex, value); });
44200ed7deeb5ef12932b2f82f791643e16939a7
match-highlighter.js
match-highlighter.js
function MatchHighlighter() { 'use strict'; const mergeRanges = function(indexes) { return indexes.reduce(function(obj, index, pos) { const prevIndex = indexes[pos - 1] || 0; const currentIndex = indexes[pos]; const nextIndex = indexes[pos + 1] || 0; if (currentIndex === nextIndex - 1 || currentIndex === prevIndex + 1 || indexes.length === 1) { obj.ranges[obj.rangeIndex].push(currentIndex); } else if (currentIndex > 0 && indexes.length > 1) { obj.rangeIndex = obj.ranges.push([currentIndex]); } return obj; }, { ranges:[[]], rangeIndex: 0 }).ranges; }; const wrapHighlight = function(letter) { return '<b>' + letter + '</b>'; }; this.highlight = function(input, result) { const matched = FuzzaldrinPlus.match(result, input); const substrings = mergeRanges(matched).map(function(range) { return range.map(function(index) { return result.charAt(index); }).join(''); }); return substrings.reduce(function(res, substring) { return res.replace(substring, wrapHighlight(substring)); }, result); }; return this; }
function MatchHighlighter() { 'use strict'; const mergeRanges = function(indexes) { return indexes.reduce(function(obj, index, pos) { const prevIndex = indexes[pos - 1] || 0; const currentIndex = indexes[pos]; const nextIndex = indexes[pos + 1] || 0; if (currentIndex === nextIndex - 1 || currentIndex === prevIndex + 1 || indexes.length === 1) { obj.ranges[obj.rangeIndex].push(currentIndex); } else if (currentIndex > 0 && indexes.length > 1) { obj.rangeIndex = obj.ranges.push([currentIndex]) - 1; } return obj; }, { ranges:[[]], rangeIndex: 0 }).ranges; }; const wrapHighlight = function(letter) { return '<b>' + letter + '</b>'; }; this.highlight = function(input, result) { const matched = FuzzaldrinPlus.match(result, input); const substrings = mergeRanges(matched).map(function(range) { return range.map(function(index) { return result.charAt(index); }).join(''); }); return substrings.reduce(function(res, substring) { return res.replace(substring, wrapHighlight(substring)); }, result); }; return this; }
Fix off-by-one error in match highlighter
Fix off-by-one error in match highlighter
JavaScript
mit
YurySolovyov/fuzzymark,YurySolovyov/fuzzymark,YuriSolovyov/fuzzymark,YuriSolovyov/fuzzymark
--- +++ @@ -10,7 +10,7 @@ if (currentIndex === nextIndex - 1 || currentIndex === prevIndex + 1 || indexes.length === 1) { obj.ranges[obj.rangeIndex].push(currentIndex); } else if (currentIndex > 0 && indexes.length > 1) { - obj.rangeIndex = obj.ranges.push([currentIndex]); + obj.rangeIndex = obj.ranges.push([currentIndex]) - 1; } return obj; }, {
d213fa0c22440904b526a1793464dc3e5d69b980
src/components/video_list.js
src/components/video_list.js
import React from 'react'; import VideoListItem from './video_list_item'; const VideoList = (props) => { const videoItems = props.videos.map((video) => { return <VideoListItem video = {video} /> }); return ( <ul className="col-md-4 list-group"> {videoItems} </ul> ); } export default VideoList;
Add functionality to VideoList component
Add functionality to VideoList component
JavaScript
mit
izabelka/redux-simple-starter,izabelka/redux-simple-starter
--- +++ @@ -0,0 +1,16 @@ +import React from 'react'; +import VideoListItem from './video_list_item'; + +const VideoList = (props) => { + const videoItems = props.videos.map((video) => { + return <VideoListItem video = {video} /> + }); + + return ( + <ul className="col-md-4 list-group"> + {videoItems} + </ul> + ); +} + +export default VideoList;
28948b82be7d6da510d0afce5aa8d839df0ab1b0
test/main_spec.js
test/main_spec.js
let chai = require('chai') let chaiHttp = require('chai-http') let server = require('../src/main.js') import {expect} from 'chai' chai.use(chaiHttp) describe('server', () => { before( () => { server.listen(); }) after( () => { server.close(); }) describe('/', () => { it('should return 200', (done) => { chai.request(server) .get('/') .end((err, res) => { console.log(res); expect(res.status).to.equal(200); expect(res.text).to.equal('Node.js Server is running'); server.close(); done(); }) }) }) })
let chai = require('chai') let chaiHttp = require('chai-http') let server = require('../src/main.js') import {expect} from 'chai' chai.use(chaiHttp) describe('server', () => { before( () => { server.listen(); }) after( () => { server.close(); }) describe('/', () => { it('should return 200', (done) => { chai.request(server) .get('/') .end((err, res) => { expect(res.status).to.equal(200); expect(res.text).to.equal('Node.js Server is running'); server.close(); done(); }) }) }) })
Remove logging from server test
Remove logging from server test
JavaScript
mit
GLNRO/react-redux-threejs,GLNRO/react-redux-threejs
--- +++ @@ -18,7 +18,6 @@ chai.request(server) .get('/') .end((err, res) => { - console.log(res); expect(res.status).to.equal(200); expect(res.text).to.equal('Node.js Server is running'); server.close();
68eceecffb4ea457fe92d623f5722fd25c09e718
src/js/routers/app-router.js
src/js/routers/app-router.js
import * as Backbone from 'backbone'; import Items from '../collections/items'; import SearchBoxView from '../views/searchBox-view'; import SearchResultsView from '../views/searchResults-view'; import AppView from '../views/app-view'; import DocumentSet from '../helpers/search'; import dispatcher from '../helpers/dispatcher'; class AppRouter extends Backbone.Router { get routes() { return { '': 'loadDefault', 'search/(?*queryString)': 'showSearchResults' }; } initialize() { this.listenTo(dispatcher, 'router:go', this.go); } go(route) { this.navigate(route, {trigger: true}); } loadDefault() { new AppView(); } showSearchResults(queryString) { let q = queryString.substring(2); DocumentSet.search(q).then(function(result) { let currentDocuments = new DocumentSet(result).documents; let docCollection = new Items(currentDocuments); new SearchResultsView({collection: docCollection}).render(); }); } } export default AppRouter;
import * as Backbone from 'backbone'; import Items from '../collections/items'; import SearchBoxView from '../views/searchBox-view'; import SearchResultsView from '../views/searchResults-view'; import AppView from '../views/app-view'; import Events from '../helpers/backbone-events'; import DocumentSet from '../helpers/search'; class AppRouter extends Backbone.Router { get routes() { return { '': 'loadDefault', 'search/(?*queryString)': 'showSearchResults' }; } initialize() { this.listenTo(Events, 'router:go', this.go); } go(route) { this.navigate(route, {trigger: true}); } loadDefault() { new AppView(); } showSearchResults(queryString) { let q = queryString.substring(2); DocumentSet.search(q).then(function(result) { let currentDocuments = new DocumentSet(result).documents; let docCollection = new Items(currentDocuments); new SearchResultsView({collection: docCollection}).render(); }); } } export default AppRouter;
Use Events instead of custom dispatcher (more)
Use Events instead of custom dispatcher (more)
JavaScript
mit
trevormunoz/katherine-anne,trevormunoz/katherine-anne,trevormunoz/katherine-anne
--- +++ @@ -3,8 +3,8 @@ import SearchBoxView from '../views/searchBox-view'; import SearchResultsView from '../views/searchResults-view'; import AppView from '../views/app-view'; +import Events from '../helpers/backbone-events'; import DocumentSet from '../helpers/search'; -import dispatcher from '../helpers/dispatcher'; class AppRouter extends Backbone.Router { @@ -16,7 +16,7 @@ } initialize() { - this.listenTo(dispatcher, 'router:go', this.go); + this.listenTo(Events, 'router:go', this.go); } go(route) {
b4b22938c6feba84188859e522f1b44c274243db
src/modules/workshop/workshop.routes.js
src/modules/workshop/workshop.routes.js
// Imports import UserRoles from '../../core/auth/constants/userRoles'; import WorkshopController from './workshop.controller'; import WorkshopHeaderController from './workshop-header.controller'; import { workshop } from './workshop.resolve'; import { carBrands } from '../home/home.resolve'; /** * @ngInject * @param RouterHelper */ export default function routing(RouterHelper) { const states = [{ state: 'modules.workshop', config: { url: '/korjaamot/:id', title: 'Korjaamo', params: { id: null, selected: null, }, data: { access: UserRoles.ROLE_ANON, }, views: { 'content@': { template: require('./partials/workshop.html'), controller: WorkshopController, controllerAs: 'vm', resolve: { _workshop: workshop, _carBrands: carBrands, }, }, 'header@': { template: require('./partials/header.html'), controller: WorkshopHeaderController, controllerAs: 'vm', resolve: { _workshop: workshop, }, }, }, }, }]; RouterHelper.configureStates(states); }
// Imports import UserRoles from '../../core/auth/constants/userRoles'; import WorkshopController from './workshop.controller'; import WorkshopHeaderController from './workshop-header.controller'; import { workshop } from './workshop.resolve'; import { carBrands } from '../home/home.resolve'; /** * @ngInject * @param RouterHelper * @param WorkshopSharedDataService */ export default function routing(RouterHelper, WorkshopSharedDataService) { const states = [{ state: 'modules.workshop', config: { url: '/korjaamot/:id', title: 'Korjaamo', params: { id: null, selected: null, }, data: { access: UserRoles.ROLE_ANON, }, views: { 'content@': { template: require('./partials/workshop.html'), controller: WorkshopController, controllerAs: 'vm', resolve: { _workshop: workshop, _carBrands: carBrands, _sharedData() { // Set action to information when routing to workshop details WorkshopSharedDataService.action = 'information'; }, }, }, 'header@': { template: require('./partials/header.html'), controller: WorkshopHeaderController, controllerAs: 'vm', resolve: { _workshop: workshop, }, }, }, }, }]; RouterHelper.configureStates(states); }
Set action to information when routing to workshop details
Set action to information when routing to workshop details
JavaScript
mit
ProtaconSolutions/Poc24h-January2017-FrontEnd,ProtaconSolutions/Poc24h-January2017-FrontEnd
--- +++ @@ -8,8 +8,9 @@ /** * @ngInject * @param RouterHelper + * @param WorkshopSharedDataService */ -export default function routing(RouterHelper) { +export default function routing(RouterHelper, WorkshopSharedDataService) { const states = [{ state: 'modules.workshop', config: { @@ -30,6 +31,10 @@ resolve: { _workshop: workshop, _carBrands: carBrands, + _sharedData() { + // Set action to information when routing to workshop details + WorkshopSharedDataService.action = 'information'; + }, }, }, 'header@': {
f7dfb99616f47561d83f9609c8a32fd6275a053c
src/components/CategoryBody.js
src/components/CategoryBody.js
/** * Created by farid on 8/16/2017. */ import React, {Component} from "react"; import Post from "./Post"; import PropTypes from 'prop-types'; class CategoryBody extends Component { render() { return ( <div className="card-body"> <div className="row"> { this.props.posts.map((post, index) => ( <div className="col-md-4" key={index}> <Post post={post}/> <br/> </div> )) } </div> </div> ) } } CategoryBody.propTypes = { posts: PropTypes.array.isRequired }; export default CategoryBody;
/** * Created by farid on 8/16/2017. */ import React, {Component} from "react"; import Post from "./Post"; import PropTypes from 'prop-types'; class CategoryBody extends Component { render() { return ( <div className="card-body"> <div className="row"> { this.props.posts.map((post, index) => ( <div className="col-md-6" key={index} > <Post post={post} isEditEnabled={true} isDeleteEnabled={true}/> <br/> </div> )) } </div> </div> ) } } CategoryBody.propTypes = { posts: PropTypes.array.isRequired }; export default CategoryBody;
Enable delete and update post on home page
feat: Enable delete and update post on home page
JavaScript
mit
faridsaud/udacity-readable-project,faridsaud/udacity-readable-project
--- +++ @@ -14,8 +14,8 @@ <div className="row"> { this.props.posts.map((post, index) => ( - <div className="col-md-4" key={index}> - <Post post={post}/> + <div className="col-md-6" key={index} > + <Post post={post} isEditEnabled={true} isDeleteEnabled={true}/> <br/> </div> ))
f49ab42589462d519c4304f9c3014a8d5f04e1b3
native/components/safe-area-view.react.js
native/components/safe-area-view.react.js
// @flow import * as React from 'react'; import { SafeAreaView } from 'react-navigation'; const forceInset = { top: 'always', bottom: 'never' }; type Props = {| style?: $PropertyType<React.ElementConfig<typeof SafeAreaView>, 'style'>, children?: React.Node, |}; function InsetSafeAreaView(props: Props) { const { style, children } = props; return ( <SafeAreaView forceInset={forceInset} style={style}> {children} </SafeAreaView> ); } export default InsetSafeAreaView;
// @flow import type { ViewStyle } from '../types/styles'; import * as React from 'react'; import { View } from 'react-native'; import { useSafeArea } from 'react-native-safe-area-context'; type Props = {| style?: ViewStyle, children?: React.Node, |}; function InsetSafeAreaView(props: Props) { const insets = useSafeArea(); const style = [ { paddingTop: insets.top }, props.style, ]; return ( <View style={style}> {props.children} </View> ); } export default InsetSafeAreaView;
Update SafeAreaView for React Nav 5
[native] Update SafeAreaView for React Nav 5 Can't import directly from React Nav anymore, using `react-native-safe-area-context` now
JavaScript
bsd-3-clause
Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal
--- +++ @@ -1,20 +1,25 @@ // @flow +import type { ViewStyle } from '../types/styles'; + import * as React from 'react'; -import { SafeAreaView } from 'react-navigation'; - -const forceInset = { top: 'always', bottom: 'never' }; +import { View } from 'react-native'; +import { useSafeArea } from 'react-native-safe-area-context'; type Props = {| - style?: $PropertyType<React.ElementConfig<typeof SafeAreaView>, 'style'>, + style?: ViewStyle, children?: React.Node, |}; function InsetSafeAreaView(props: Props) { - const { style, children } = props; + const insets = useSafeArea(); + const style = [ + { paddingTop: insets.top }, + props.style, + ]; return ( - <SafeAreaView forceInset={forceInset} style={style}> - {children} - </SafeAreaView> + <View style={style}> + {props.children} + </View> ); }
7afb5342fb92ed902b962a3324f731833a1cdb00
client/userlist.js
client/userlist.js
var UserList = React.createClass({ componentDidMount: function() { socket.on('join', this._join); socket.on('part', this._part); }, render: function() { return ( <ul id='online-list'></ul> ); }, _join: function(username) { if (username != myUsername) { addOnlineUserToList(username); } }, _part: function(username) { $('#online-list li span').filter(function() { return $(this).text() == username; }).parent().remove(); } }); React.render(<UserList />, document.getElementsByClassName('nicklist')[0]);
var UserList = React.createClass({ componentDidMount: function() { socket.on('join', this._join); socket.on('part', this._part); }, render: function() { return ( <ul id='online-list'></ul> ); }, _join: function(username) { if (username != myUsername) { addOnlineUserToList(username); } }, _part: function(username) { $('#online-list li span').filter(function() { return $(this).text() == username; }).parent().remove(); } }); var User = React.createClass({ render: function() { return ( <li> </li> ) } }); React.render(<UserList />, document.getElementsByClassName('nicklist')[0]);
Create prototype react component for user in list
Create prototype react component for user in list
JavaScript
mit
mbalamat/ting,odyvarv/ting-1,gtklocker/ting,gtklocker/ting,mbalamat/ting,sirodoht/ting,dionyziz/ting,VitSalis/ting,gtklocker/ting,gtklocker/ting,odyvarv/ting-1,sirodoht/ting,sirodoht/ting,dionyziz/ting,dionyziz/ting,odyvarv/ting-1,mbalamat/ting,mbalamat/ting,dionyziz/ting,odyvarv/ting-1,VitSalis/ting,VitSalis/ting,VitSalis/ting,sirodoht/ting
--- +++ @@ -19,4 +19,14 @@ }).parent().remove(); } }); + +var User = React.createClass({ + render: function() { + return ( + <li> + </li> + ) + } +}); + React.render(<UserList />, document.getElementsByClassName('nicklist')[0]);
f26e7eb203948d7fff0d0c44a34a675d0631adcf
trace/snippets.js
trace/snippets.js
/** * Copyright 2017, Google, Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // [START trace_setup_explicit] require('@google-cloud/trace-agent').start({ projectId: 'your-project-id', keyFilename: '/path/to/key.json' }); // [END trace_setup_explicity]
/** * Copyright 2017, Google, Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // [START trace_setup_explicit] require('@google-cloud/trace-agent').start({ projectId: 'your-project-id', keyFilename: '/path/to/key.json' }); // [END trace_setup_explicit]
Fix type on region tag
Fix type on region tag
JavaScript
apache-2.0
JustinBeckwith/nodejs-docs-samples,thesandlord/nodejs-docs-samples,thesandlord/nodejs-docs-samples,JustinBeckwith/nodejs-docs-samples,GoogleCloudPlatform/nodejs-docs-samples,GoogleCloudPlatform/nodejs-docs-samples,GoogleCloudPlatform/nodejs-docs-samples,JustinBeckwith/nodejs-docs-samples,GoogleCloudPlatform/nodejs-docs-samples
--- +++ @@ -20,4 +20,4 @@ projectId: 'your-project-id', keyFilename: '/path/to/key.json' }); -// [END trace_setup_explicity] +// [END trace_setup_explicit]
0c2e8d75c01e8032adcde653a458528db0683c44
karma.conf.js
karma.conf.js
module.exports = function(config){ config.set({ basePath : './', files : [ 'app/bower_components/angular/angular.js', 'app/bower_components/angular-route/angular-route.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/components/**/*.js', 'app/view*/**/*.js' ], autoWatch : true, frameworks: ['jasmine'], browsers : ['Chrome'], plugins : [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
module.exports = function(config){ config.set({ basePath : './', files : [ 'app/bower_components/angular/angular.js', 'app/bower_components/angular-route/angular-route.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/components/**/*.js', 'app/view*/**/*.js' ], autoWatch : true, frameworks: ['jasmine'], browsers : ['Chrome', 'Firefox'], plugins : [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
Change karma to run both Firefox and Chrome.
Change karma to run both Firefox and Chrome. I have both, I care about both, so run both!
JavaScript
agpl-3.0
CCJ16/registration,CCJ16/registration,CCJ16/registration
--- +++ @@ -15,7 +15,7 @@ frameworks: ['jasmine'], - browsers : ['Chrome'], + browsers : ['Chrome', 'Firefox'], plugins : [ 'karma-chrome-launcher',
a783fbcd8bcff07672e64ada1f75c7290c9a765a
src/chrome/index.js
src/chrome/index.js
/* eslint-disable no-console */ import { CONFIG } from '../constants'; import { Socket } from 'phoenix'; import { startPlugin } from '..'; import listenAuth from './listenAuth'; import handleNotifications from './handleNotifications'; import handleWork from './handleWork'; import renderIcon from './renderIcon'; export const startChromePlugin = (auth, chrome, enhancer, socketConstructor = Socket) => { const reloader = () => window.location.reload(true); const plugin = startPlugin({ auth, enhancer, reloader, socketConstructor }); const store = plugin.getStore(); const getStore = () => store; listenAuth(store, chrome); handleNotifications(store, chrome); renderIcon(store, chrome); handleWork(store, chrome); if (CONFIG.env === 'dev') { // redux dev tools don't work with the plugin, so we have a dumb // replacement. store.subscribe(() => { const { worker, socket } = store.getState(); console.log('Worker:', worker.toJS(), 'Socket:', socket.toJS()); }); } return { getStore }; };
/* eslint-disable no-console */ import { CONFIG } from '../constants'; import { Socket } from 'phoenix'; import { startPlugin } from '..'; import listenAuth from './listenAuth'; import handleNotifications from './handleNotifications'; import handleWork from './handleWork'; import renderIcon from './renderIcon'; export const startChromePlugin = (auth, chrome, enhancer, socketConstructor = Socket) => { const reloader = () => window.location.reload(true); const plugin = startPlugin({ auth, enhancer, reloader, socketConstructor }); const store = plugin.getStore(); const getStore = () => store; listenAuth(store, chrome); handleNotifications(store, chrome); renderIcon(store, chrome); handleWork(store, chrome); if (CONFIG.env === 'dev') { // redux dev tools don't work with the plugin, so we have a dumb // replacement. store.subscribe(() => { const { worker, socket, plugin: pluginState } = store.getState(); console.log('Worker:', worker.toJS(), 'Socket:', socket.toJS(), 'Plugin:', pluginState.toJS()); }); } return { getStore }; };
Add plugin state to logging
Add plugin state to logging
JavaScript
mit
rainforestapp/tester-chrome-extension,rainforestapp/tester-chrome-extension,rainforestapp/tester-chrome-extension
--- +++ @@ -23,8 +23,10 @@ // redux dev tools don't work with the plugin, so we have a dumb // replacement. store.subscribe(() => { - const { worker, socket } = store.getState(); - console.log('Worker:', worker.toJS(), 'Socket:', socket.toJS()); + const { worker, socket, plugin: pluginState } = store.getState(); + console.log('Worker:', worker.toJS(), + 'Socket:', socket.toJS(), + 'Plugin:', pluginState.toJS()); }); }
51cebb77df8d4eec12da134b765d5fe046eefeda
karma.conf.js
karma.conf.js
var istanbul = require('browserify-istanbul'); var isparta = require('isparta'); module.exports = function (config) { 'use strict'; config.set({ browsers: [ 'Chrome', 'Firefox', 'Safari', 'Opera' ], reporters: ['progress', 'notify', 'coverage'], frameworks: ['browserify', 'mocha', 'chai-sinon', 'sinon'], // list of files / patterns to load in the browser files: ['./tests/spec/**/*.js'], preprocessors: { './tests/spec/**/*.js': ['browserify'] }, client: { mocha: {reporter: 'html'} // change Karma's debug.html to the mocha web reporter }, browserify: { debug: true, transform: [ //'babelify', istanbul({ instrumenter: isparta, ignore: ['**/node_modules/**', '**/test/**'], }) ], configure: function (bundle) { bundle.on('bundled', function (error) { if (error != null) console.error(error.message); }); } }, notifyReporter: { reportEachFailure: true, reportSuccess: true } }); };
var istanbul = require('browserify-istanbul'); var isparta = require('isparta'); module.exports = function (config) { 'use strict'; config.set({ browsers: [ //'PhantomJS', 'Chrome', 'Firefox', 'Safari', 'Opera' ], reporters: ['progress', 'notify', 'coverage'], frameworks: ['browserify', 'mocha', 'chai-sinon', 'sinon'], // list of files / patterns to load in the browser files: ['./tests/spec/**/*.js'], preprocessors: { './tests/spec/**/*.js': ['browserify'] }, client: { mocha: {reporter: 'html'} // change Karma's debug.html to the mocha web reporter }, browserify: { debug: true, transform: [ //'babelify', istanbul({ instrumenter: isparta, ignore: ['**/node_modules/**', '**/test/**'], }) ], configure: function (bundle) { bundle.on('bundled', function (error) { if (error != null) console.error(error.message); }); } }, notifyReporter: { reportEachFailure: true, reportSuccess: true }, logLevel: 'LOG_INFO', }); };
Set log level. PhantomJS off.
Set log level. PhantomJS off.
JavaScript
mit
ekazakov/dumpjs
--- +++ @@ -7,6 +7,7 @@ config.set({ browsers: [ + //'PhantomJS', 'Chrome', 'Firefox', 'Safari', @@ -46,6 +47,8 @@ notifyReporter: { reportEachFailure: true, reportSuccess: true - } + }, + + logLevel: 'LOG_INFO', }); };
b4cd7c829a7d17888902f5468d4ea0a0f1084c42
src/common/Popup.js
src/common/Popup.js
/* @flow */ import React, { PureComponent } from 'react'; import type { ChildrenArray } from 'react'; import { View, Dimensions, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ popup: { marginRight: 20, marginLeft: 20, marginBottom: 2, bottom: 0, borderRadius: 5, shadowOpacity: 0.25, elevation: 3, }, }); type Props = { children: ChildrenArray<*>, }; export default class Popup extends PureComponent<Props> { props: Props; static contextTypes = { styles: () => null, }; render() { const { height } = Dimensions.get('window'); return ( <View style={[this.context.styles.backgroundColor, styles.popup]} maxHeight={height / 4}> {this.props.children} </View> ); } }
/* @flow */ import React, { PureComponent } from 'react'; import type { ChildrenArray } from 'react'; import { View, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ popup: { marginRight: 20, marginLeft: 20, marginBottom: 2, bottom: 0, borderRadius: 5, shadowOpacity: 0.25, elevation: 3, }, }); type Props = { children: ChildrenArray<*>, }; export default class Popup extends PureComponent<Props> { props: Props; static contextTypes = { styles: () => null, }; render() { return ( <View style={[this.context.styles.backgroundColor, styles.popup]}>{this.props.children}</View> ); } }
Remove extraneous `maxHeight` prop on a `View`.
popup: Remove extraneous `maxHeight` prop on a `View`. This is not a prop that the `View` component supports. It has never had any effect, and the Flow 0.75 we'll pull in with RN 0.56 will register it as an error. This prop was added in commit ce0395cff when changing the component used here to a `ScrollView`, and 62ddf77a7 left it around when changing back to a `View`.
JavaScript
apache-2.0
vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile
--- +++ @@ -1,7 +1,7 @@ /* @flow */ import React, { PureComponent } from 'react'; import type { ChildrenArray } from 'react'; -import { View, Dimensions, StyleSheet } from 'react-native'; +import { View, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ popup: { @@ -27,12 +27,8 @@ }; render() { - const { height } = Dimensions.get('window'); - return ( - <View style={[this.context.styles.backgroundColor, styles.popup]} maxHeight={height / 4}> - {this.props.children} - </View> + <View style={[this.context.styles.backgroundColor, styles.popup]}>{this.props.children}</View> ); } }
c6d77a8570bbd3592acc1430672e57219f418072
Libraries/Utilities/PerformanceLoggerContext.js
Libraries/Utilities/PerformanceLoggerContext.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict-local * @format */ import * as React from 'react'; import {useContext} from 'react'; import GlobalPerformanceLogger from './GlobalPerformanceLogger'; import type {IPerformanceLogger} from './createPerformanceLogger'; /** * This is a React Context that provides a scoped instance of IPerformanceLogger. * We wrap every <AppContainer /> with a Provider for this context so the logger * should be available in every component. * See React docs about using Context: https://reactjs.org/docs/context.html */ const PerformanceLoggerContext: React.Context<IPerformanceLogger> = React.createContext( GlobalPerformanceLogger, ); if (__DEV__) { PerformanceLoggerContext.displayName = 'PerformanceLoggerContext'; } export function usePerformanceLogger(): IPerformanceLogger { return useContext(PerformanceLoggerContext); } export default PerformanceLoggerContext;
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict * @format */ import * as React from 'react'; import {useContext} from 'react'; import GlobalPerformanceLogger from './GlobalPerformanceLogger'; import type {IPerformanceLogger} from './createPerformanceLogger'; /** * This is a React Context that provides a scoped instance of IPerformanceLogger. * We wrap every <AppContainer /> with a Provider for this context so the logger * should be available in every component. * See React docs about using Context: https://reactjs.org/docs/context.html */ const PerformanceLoggerContext: React.Context<IPerformanceLogger> = React.createContext( GlobalPerformanceLogger, ); if (__DEV__) { PerformanceLoggerContext.displayName = 'PerformanceLoggerContext'; } export function usePerformanceLogger(): IPerformanceLogger { return useContext(PerformanceLoggerContext); } export default PerformanceLoggerContext;
Make some modules flow strict
Make some modules flow strict Summary: TSIA Changelog: [Internal] Reviewed By: mdvacca Differential Revision: D28412774 fbshipit-source-id: 899a78e573bb49633690275052d5e7cb069327fb
JavaScript
mit
facebook/react-native,myntra/react-native,facebook/react-native,pandiaraj44/react-native,myntra/react-native,janicduplessis/react-native,javache/react-native,myntra/react-native,javache/react-native,pandiaraj44/react-native,javache/react-native,javache/react-native,janicduplessis/react-native,janicduplessis/react-native,myntra/react-native,janicduplessis/react-native,pandiaraj44/react-native,janicduplessis/react-native,javache/react-native,facebook/react-native,javache/react-native,facebook/react-native,pandiaraj44/react-native,pandiaraj44/react-native,javache/react-native,facebook/react-native,janicduplessis/react-native,pandiaraj44/react-native,javache/react-native,facebook/react-native,facebook/react-native,facebook/react-native,myntra/react-native,myntra/react-native,janicduplessis/react-native,myntra/react-native,myntra/react-native,pandiaraj44/react-native,janicduplessis/react-native,myntra/react-native,facebook/react-native,pandiaraj44/react-native,javache/react-native
--- +++ @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @flow strict-local + * @flow strict * @format */
752c2c39790cf1ffb1e97850991d2f13c25f92b8
src/config/babel.js
src/config/babel.js
// External const mem = require('mem'); // Ours const { merge } = require('../utils/structures'); const { getProjectConfig } = require('./project'); const PROJECT_TYPES_CONFIG = { preact: { plugins: [ [ require.resolve('@babel/plugin-transform-react-jsx'), { pragma: 'h' } ] ] }, react: { presets: [require.resolve('@babel/preset-react')] } }; module.exports.getBabelConfig = mem(({ isModernJS } = {}) => { const { babel: projectBabelConfig, pkg, type } = getProjectConfig(); return merge( { presets: [ [ require.resolve('@babel/preset-env'), { targets: { browsers: isModernJS ? ['Chrome >= 76', 'Safari >= 12.1', 'iOS >= 12.3', 'Firefox >= 69', 'Edge >= 18'] : pkg.browserslist || ['> 1% in au', '> 5%', 'Firefox ESR'] }, useBuiltIns: 'entry', corejs: 3, modules: process.env.NODE_ENV === 'test' ? 'commonjs' : false } ] ], plugins: [ require.resolve('@babel/plugin-proposal-object-rest-spread'), require.resolve('@babel/plugin-syntax-dynamic-import'), require.resolve('@babel/plugin-proposal-class-properties') ] }, PROJECT_TYPES_CONFIG[type], projectBabelConfig ); });
// External const mem = require('mem'); // Ours const { merge } = require('../utils/structures'); const { getProjectConfig } = require('./project'); const PROJECT_TYPES_CONFIG = { preact: { plugins: [ [ require.resolve('@babel/plugin-transform-react-jsx'), { pragma: 'h' } ] ] }, react: { presets: [require.resolve('@babel/preset-react')] } }; module.exports.getBabelConfig = mem(({ isModernJS } = {}) => { const { babel: projectBabelConfig, pkg, type } = getProjectConfig(); return merge( { presets: [ [ require.resolve('@babel/preset-env'), { targets: { browsers: isModernJS ? ['Chrome >= 80', 'Safari >= 12.1', 'iOS >= 12.3', 'Firefox >= 72', 'Edge >= 18'] : pkg.browserslist || ['> 1% in AU', 'Firefox ESR', 'IE 11'] }, useBuiltIns: 'entry', corejs: 3, modules: process.env.NODE_ENV === 'test' ? 'commonjs' : false } ] ], plugins: [ require.resolve('@babel/plugin-proposal-object-rest-spread'), require.resolve('@babel/plugin-syntax-dynamic-import'), require.resolve('@babel/plugin-proposal-class-properties') ] }, PROJECT_TYPES_CONFIG[type], projectBabelConfig ); });
Update target browsers. IE 11 needs to be manually specified now becuase it's dropped below 1% in Australia, but is still supported by ABC.
Update target browsers. IE 11 needs to be manually specified now becuase it's dropped below 1% in Australia, but is still supported by ABC.
JavaScript
mit
abcnews/aunty,abcnews/aunty,abcnews/aunty
--- +++ @@ -32,8 +32,8 @@ { targets: { browsers: isModernJS - ? ['Chrome >= 76', 'Safari >= 12.1', 'iOS >= 12.3', 'Firefox >= 69', 'Edge >= 18'] - : pkg.browserslist || ['> 1% in au', '> 5%', 'Firefox ESR'] + ? ['Chrome >= 80', 'Safari >= 12.1', 'iOS >= 12.3', 'Firefox >= 72', 'Edge >= 18'] + : pkg.browserslist || ['> 1% in AU', 'Firefox ESR', 'IE 11'] }, useBuiltIns: 'entry', corejs: 3,
2525fe4097ff124239ed56956209d4d0ffefac27
test/unit/util/walk-tree.js
test/unit/util/walk-tree.js
import walkTree from '../../../src/util/walk-tree'; describe('utils/walk-tree', function () { it('should walk parents before walking descendants', function () { var order = []; var one = document.createElement('one'); one.innerHTML = '<two><three></three></two>'; walkTree(one, function (elem) { order.push(elem.tagName); }); expect(order[0]).to.equal('ONE'); expect(order[1]).to.equal('TWO'); expect(order[2]).to.equal('THREE'); }); });
import walkTree from '../../../src/util/walk-tree'; describe('utils/walk-tree', function () { var one, order; beforeEach(function () { order = []; one = document.createElement('one'); one.innerHTML = '<two><three></three></two>'; }); it('should walk parents before walking descendants', function () { walkTree(one, function (elem) { order.push(elem.tagName); }); expect(order.length).to.equal(3); expect(order[0]).to.equal('ONE'); expect(order[1]).to.equal('TWO'); expect(order[2]).to.equal('THREE'); }); it('should accept a filter that filters out a node removing it and its descendants', function () { walkTree(one, function (elem) { order.push(elem.tagName); }, function (elem) { return elem.tagName !== 'TWO'; }); expect(order.length).to.equal(1); expect(order[0]).to.equal('ONE'); }); });
Write test for walkTre() filter.
Write test for walkTre() filter.
JavaScript
mit
skatejs/skatejs,antitoxic/skatejs,chrisdarroch/skatejs,skatejs/skatejs,skatejs/skatejs,chrisdarroch/skatejs
--- +++ @@ -1,18 +1,33 @@ import walkTree from '../../../src/util/walk-tree'; describe('utils/walk-tree', function () { + var one, order; + + beforeEach(function () { + order = []; + one = document.createElement('one'); + one.innerHTML = '<two><three></three></two>'; + }); + it('should walk parents before walking descendants', function () { - var order = []; - var one = document.createElement('one'); - - one.innerHTML = '<two><three></three></two>'; - walkTree(one, function (elem) { order.push(elem.tagName); }); + expect(order.length).to.equal(3); expect(order[0]).to.equal('ONE'); expect(order[1]).to.equal('TWO'); expect(order[2]).to.equal('THREE'); }); + + it('should accept a filter that filters out a node removing it and its descendants', function () { + walkTree(one, function (elem) { + order.push(elem.tagName); + }, function (elem) { + return elem.tagName !== 'TWO'; + }); + + expect(order.length).to.equal(1); + expect(order[0]).to.equal('ONE'); + }); });
1a07a7c7900cc14582fdaf41a96933d221a439e0
tests/client/unit/s.Spec.js
tests/client/unit/s.Spec.js
describe('Satellite game', function () { beforeEach(function () { }); it('should exists', function () { expect(s).to.be.an('object'); expect(s).to.have.property('config'); expect(s).to.have.property('init'); }); it('should contains ship properties', function () { expect(s).to.have.deep.property('config.ship.hull'); expect(s).to.have.deep.property('config.ship.shields'); expect(s).to.have.deep.property('config.ship.maxSpeed'); }); it('should init the game', function () { var spy = sinon.spy(); s.init('init', spy); spy.called.should.equal.true; expect(s).to.have.property('projector').and.to.be.an('object'); expect(s).to.have.property('loader').and.to.be.an('object'); expect(s).to.have.property('game').and.to.be.an('object'); }); });
describe('Satellite game', function () { it('should exists', function () { expect(s).to.be.an('object'); expect(s).to.have.property('config'); expect(s).to.have.property('init'); }); it('should contains ship properties', function () { expect(s).to.have.deep.property('config.ship.hull'); expect(s).to.have.deep.property('config.ship.shields'); expect(s).to.have.deep.property('config.ship.maxSpeed'); }); it('should init the game', function () { var spy = sinon.spy(); s.init('init', spy); spy.called.should.equal.true; expect(s).to.have.property('projector').and.to.be.an('object'); expect(s).to.have.property('loader').and.to.be.an('object'); expect(s).to.have.property('game').and.to.be.an('object'); }); });
Remove unused before each call
Remove unused before each call
JavaScript
bsd-2-clause
satellite-game/Satellite,satellite-game/Satellite,satellite-game/Satellite
--- +++ @@ -1,8 +1,4 @@ describe('Satellite game', function () { - beforeEach(function () { - - }); - it('should exists', function () { expect(s).to.be.an('object'); expect(s).to.have.property('config');
3f934607b9404a5edca6b6a7f68c934d90c899ce
static/js/featured-projects.js
static/js/featured-projects.js
$('.project-toggle-featured').on('click', function() { const projectId = $(this).data("project-id"), featured = $(this).data("featured") === "True"; method = featured ? "DELETE" : "POST"; $.ajax({ type: method, url: `/admin/featured/${projectId}`, dataType: 'json' }).done(() => { const newStatus = featured ? "False" : "True"; $(this).data('featured', newStatus); $(this).html(newStatus); }); })
$('.project-toggle-featured').on('click', function() { const projectId = $(this).data("project-id"), featured = $(this).val() === "Remove"; method = featured ? "DELETE" : "POST"; $.ajax({ type: method, url: `/admin/featured/${projectId}`, dataType: 'json' }).done(() => { const newStatus = featured ? "Add" : "Remove"; $(this).html(newStatus); }); })
Update featured projects button text
Update featured projects button text
JavaScript
bsd-3-clause
LibCrowds/libcrowds-bs4-pybossa-theme,LibCrowds/libcrowds-bs4-pybossa-theme
--- +++ @@ -1,14 +1,13 @@ $('.project-toggle-featured').on('click', function() { const projectId = $(this).data("project-id"), - featured = $(this).data("featured") === "True"; + featured = $(this).val() === "Remove"; method = featured ? "DELETE" : "POST"; $.ajax({ type: method, url: `/admin/featured/${projectId}`, dataType: 'json' }).done(() => { - const newStatus = featured ? "False" : "True"; - $(this).data('featured', newStatus); + const newStatus = featured ? "Add" : "Remove"; $(this).html(newStatus); }); })
06e880b204d4b19edb42116d7a7fad85e8889de9
webpack.common.js
webpack.common.js
var webpack = require('webpack'), path = require('path'), CleanWebpackPlugin = require('clean-webpack-plugin'); var libraryName = 'webstompobs', dist = '/dist'; module.exports = { entry: __dirname + '/src/index.ts', context: path.resolve("./src"), output: { path: path.join(__dirname, dist), filename: libraryName + '.bundle.js', library: libraryName, libraryTarget: 'umd', umdNamedDefine: true }, resolve: { extensions: ['.js', '.ts', '.jsx', '.tsx' ] }, plugins: [ new CleanWebpackPlugin(['dist']) ], module: { rules: [ { test: /\.tsx?$/, loader: "awesome-typescript-loader" }, { enforce: "pre", test: /\.js$/, loader: "source-map-loader" } ] } };
var webpack = require('webpack'), path = require('path'), CleanWebpackPlugin = require('clean-webpack-plugin'); var libraryName = 'webstompobs', dist = '/dist'; module.exports = { target: 'node', entry: __dirname + '/src/index.ts', context: path.resolve("./src"), output: { path: path.join(__dirname, dist), filename: libraryName + '.bundle.js', library: libraryName, libraryTarget: 'umd', umdNamedDefine: true }, resolve: { extensions: ['.js', '.ts', '.jsx', '.tsx' ] }, plugins: [ new CleanWebpackPlugin(['dist']) ], module: { rules: [ { test: /\.tsx?$/, loader: "awesome-typescript-loader" }, { enforce: "pre", test: /\.js$/, loader: "source-map-loader" } ] } };
FIX : Version was not compatible with node
FIX : Version was not compatible with node Reason : webpack was using window
JavaScript
apache-2.0
fpozzobon/webstomp-obs,fpozzobon/webstomp-obs,fpozzobon/webstomp-obs
--- +++ @@ -6,6 +6,7 @@ dist = '/dist'; module.exports = { + target: 'node', entry: __dirname + '/src/index.ts', context: path.resolve("./src"), output: {
f75613d01d047cfbc5b8cc89154ad6eee64d6155
lib/Filter.js
lib/Filter.js
import React, { Component, PropTypes } from 'react'; import FormControl from 'react-bootstrap/lib/FormControl'; class Filter extends Component { constructor(props){ super(props); this.state = {filterValue : this.props.query}; this.inputChanged = this.inputChanged.bind(this); } componentWillUnmount(){ if(this.timeout){ window.clearTimeout(this.timeout); this.timeout = null; } } inputChanged(event){ this.setState({filterValue: event.target.value}); if (this.timeout){ window.clearTimeout(this.timeout); this.timeout = null; } this.timeout = window.setTimeout(()=>{ this.props.config.eventHandler( { type:'filter-change', id: this.props.config.id, column: this.props.column, query: this.state.filterValue } ); }, 300); } render(){ return( <FormControl id={'filter_for_'+this.props.column} type='search' key={this.props.column} value={this.state.filterValue} onChange={this.inputChanged} placeholder={"Filter..."} /> ); } } Filter.propTypes = { query: PropTypes.string, config: PropTypes.object, column: PropTypes.string.isRequired }; export default Filter;
import React, { Component, PropTypes } from 'react'; import FormControl from 'react-bootstrap/lib/FormControl'; class Filter extends Component { constructor(props){ super(props); this.state = {filterValue : this.props.query}; this.inputChanged = this.inputChanged.bind(this); } componentWillUnmount(){ if(this.timeout){ window.clearTimeout(this.timeout); this.timeout = null; } } inputChanged(event){ this.setState({filterValue: event.target.value}); if (this.timeout){ window.clearTimeout(this.timeout); this.timeout = null; } this.timeout = window.setTimeout(()=>{ this.props.config.eventHandler( { type:'filter-change', id: this.props.config.id, column: this.props.column, query: this.state.filterValue } ); }, 300); } render(){ return( <FormControl id={'filter_for_'+this.props.column} type='search' key={this.props.column} value={this.state.filterValue} onChange={this.inputChanged} placeholder={'Filter...'} /> ); } } Filter.propTypes = { query: PropTypes.string, config: PropTypes.object, column: PropTypes.string.isRequired }; export default Filter;
Use single quotes for strings
Use single quotes for strings
JavaScript
mit
eddyson-de/react-grid,eddyson-de/react-grid
--- +++ @@ -36,7 +36,7 @@ render(){ return( - <FormControl id={'filter_for_'+this.props.column} type='search' key={this.props.column} value={this.state.filterValue} onChange={this.inputChanged} placeholder={"Filter..."} /> + <FormControl id={'filter_for_'+this.props.column} type='search' key={this.props.column} value={this.state.filterValue} onChange={this.inputChanged} placeholder={'Filter...'} /> ); } }
4c141ac898f6a7bad42db55445bb5fecf99639bd
src/user/user-interceptor.js
src/user/user-interceptor.js
export default function userInterceptor($localStorage){ function request(config){ if(config.headers.Authorization){ return config; } if($localStorage.token){ config.headers.Authorization = 'bearer ' + $localStorage.token; } return config; } return {request}; } userInterceptor.$inject = ['$localStorage'];
export default function userInterceptor(user){ function request(config){ if(config.headers.Authorization){ return config; } if(user.token){ config.headers.Authorization = 'bearer ' + user.token; } return config; } return {request}; } userInterceptor.$inject = ['$localStorage'];
Use user service in interceptor
Use user service in interceptor
JavaScript
mit
tamaracha/wbt-framework,tamaracha/wbt-framework,tamaracha/wbt-framework
--- +++ @@ -1,10 +1,10 @@ -export default function userInterceptor($localStorage){ +export default function userInterceptor(user){ function request(config){ if(config.headers.Authorization){ return config; } - if($localStorage.token){ - config.headers.Authorization = 'bearer ' + $localStorage.token; + if(user.token){ + config.headers.Authorization = 'bearer ' + user.token; } return config; }
5841cf3eb49b17d5c851d8e7e2f6b4573b8fe620
src/components/nlp/template.js
src/components/nlp/template.js
/** * Created by Tomasz Gabrysiak @ Infermedica on 08/02/2017. */ import html from '../../templates/helpers'; const template = (context) => { return new Promise((resolve) => { resolve(html` <h5 class="card-title">Tell us how you feel.</h5> <div class="card-text"> <form> <div class="form-group"> <label for="input-feel">We will try to recognize your symptoms using Natural Language Processing algorithms.</label> <textarea placeholder="e.g. I got headache" class="form-control" id="input-feel" rows="4"></textarea> </div> </form> <p>Identified observations:</p> <ul class="list-unstyled" id="observations"> </ul> <p class="text-muted small"><i class="fa fa-info-circle"></i> This screen uses our NLP engine to find symptoms in a written text. Evidences found in text will be marked as initial which is important to our engine. Please read more about initial evidences <a target="_blank">here</a>. All of the identified symptoms will be added to your interview after clicking <span class="badge badge-primary">Next</span>.</p> </div> `); }); }; export default template;
/** * Created by Tomasz Gabrysiak @ Infermedica on 08/02/2017. */ import html from '../../templates/helpers'; const template = (context) => { return new Promise((resolve) => { resolve(html` <h5 class="card-title">Tell us how you feel.</h5> <div class="card-text"> <form> <div class="form-group"> <label for="input-feel">We will try to recognize your symptoms using Natural Language Processing algorithms.</label> <textarea placeholder="e.g. I got headache" class="form-control" id="input-feel" rows="4"></textarea> </div> </form> <p>Identified observations:</p> <ul class="list-unstyled" id="observations"> </ul> <p class="text-muted small"><i class="fa fa-info-circle"></i> This screen uses our NLP engine to find symptoms in a written text. Evidence found in text will be marked as initial which is important to our engine. Please read more about initial evidence <a target="_blank" href="https://developer.infermedica.com/docs/diagnosis#gathering-initial-evidence">here</a>. All of the identified symptoms will be added to your interview after clicking <span class="badge badge-primary">Next</span>.</p> </div> `); }); }; export default template;
Fix typos in text about NLP
Fix typos in text about NLP
JavaScript
mit
infermedica/js-symptom-checker-example,infermedica/js-symptom-checker-example
--- +++ @@ -18,7 +18,7 @@ <p>Identified observations:</p> <ul class="list-unstyled" id="observations"> </ul> - <p class="text-muted small"><i class="fa fa-info-circle"></i> This screen uses our NLP engine to find symptoms in a written text. Evidences found in text will be marked as initial which is important to our engine. Please read more about initial evidences <a target="_blank">here</a>. All of the identified symptoms will be added to your interview after clicking <span class="badge badge-primary">Next</span>.</p> + <p class="text-muted small"><i class="fa fa-info-circle"></i> This screen uses our NLP engine to find symptoms in a written text. Evidence found in text will be marked as initial which is important to our engine. Please read more about initial evidence <a target="_blank" href="https://developer.infermedica.com/docs/diagnosis#gathering-initial-evidence">here</a>. All of the identified symptoms will be added to your interview after clicking <span class="badge badge-primary">Next</span>.</p> </div> `); });
434fcc48ae69280d9295327ec6592c462ba55ab3
webpack.config.js
webpack.config.js
// Used to run webpack dev server to test the demo in local const webpack = require('webpack'); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = (env, options) => ({ mode: options.mode, devtool: 'source-map', entry: path.resolve(__dirname, 'demo/js/demo.js'), output: { path: path.resolve(__dirname, 'pages'), filename: '[name][chunkhash].js', }, module: { rules: [ { test: /\.js$/, exclude: [/node_modules/], use: [ { loader: 'babel-loader', }, ], }, { test: /\.css$/, loaders: ['style-loader', 'css-loader'], }, ], }, plugins: [ options.mode === 'development' ? new webpack.HotModuleReplacementPlugin() : () => {}, new HtmlWebpackPlugin({ template: path.resolve(__dirname, 'demo/index.html'), }), ], devServer: { contentBase: './demo', }, });
// Used to run webpack dev server to test the demo in local const webpack = require('webpack'); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = (env, options) => ({ mode: options.mode, devtool: 'source-map', entry: path.resolve(__dirname, 'demo/js/demo.js'), output: { path: path.resolve(__dirname, 'pages'), filename: options.mode === 'production' ? '[name][chunkhash].js' : '[name].js', }, module: { rules: [ { test: /\.js$/, exclude: [/node_modules/], use: [ { loader: 'babel-loader', }, ], }, { test: /\.css$/, loaders: ['style-loader', 'css-loader'], }, ], }, plugins: [ options.mode === 'development' ? new webpack.HotModuleReplacementPlugin() : () => {}, new HtmlWebpackPlugin({ template: path.resolve(__dirname, 'demo/index.html'), }), ], devServer: { contentBase: './demo', }, });
Fix chunkhash not allowed in development
Fix chunkhash not allowed in development
JavaScript
mit
springload/react-accessible-accordion,springload/react-accessible-accordion,springload/react-accessible-accordion
--- +++ @@ -9,7 +9,10 @@ entry: path.resolve(__dirname, 'demo/js/demo.js'), output: { path: path.resolve(__dirname, 'pages'), - filename: '[name][chunkhash].js', + filename: + options.mode === 'production' + ? '[name][chunkhash].js' + : '[name].js', }, module: { rules: [
458790663023230f78c75753bb2619bd437c1117
webpack.config.js
webpack.config.js
const path = require('path'); module.exports = { entry: { 'acrolinx-sidebar-integration': './src/acrolinx-sidebar-integration.ts', 'tests': './test/index.ts' }, module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ } ] }, resolve: { extensions: ['.tsx', '.ts', '.js'] }, output: { filename: '[name].js', publicPath: "/distrib/", path: path.resolve(__dirname, 'distrib') } };
const path = require('path'); module.exports = { entry: { 'acrolinx-sidebar-integration': './src/acrolinx-sidebar-integration.ts', 'tests': './test/index.ts' }, module: { rules: [ { test: /\.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, options: { transpileOnly: true } } ] }, resolve: { extensions: ['.tsx', '.ts', '.js'] }, output: { filename: '[name].js', publicPath: "/distrib/", path: path.resolve(__dirname, 'distrib') } };
Use webpack just for transpileOnly of ts to js.
Use webpack just for transpileOnly of ts to js. Type checking is done by IDE, npm run tscWatch or build anyway.
JavaScript
apache-2.0
acrolinx/acrolinx-sidebar-demo
--- +++ @@ -9,8 +9,11 @@ rules: [ { test: /\.tsx?$/, - use: 'ts-loader', - exclude: /node_modules/ + loader: 'ts-loader', + exclude: /node_modules/, + options: { + transpileOnly: true + } } ] },
3f2d406174bdeec38478bf1cb342266a0c1c6554
webpack.config.js
webpack.config.js
var webpack = require('webpack') module.exports = { entry: { ui: './lib/ui/main.js', vendor: ['react', 'debug'] }, output: { path: 'dist', filename: '[name].js' }, module: { loaders: [ {test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel'}, {test: /\.json$/, loader: 'json'} ] }, resolve: { alias: { bacon: "baconjs" } }, plugins: [ new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'), new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/) ] }
var webpack = require('webpack') module.exports = { entry: { ui: './lib/ui/main.js', vendor: ['react', 'debug', 'd3', 'react-bootstrap'] }, output: { path: 'dist', filename: '[name].js' }, module: { loaders: [ {test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel'}, {test: /\.json$/, loader: 'json'} ] }, resolve: { alias: { bacon: "baconjs" } }, plugins: [ new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'), new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/) ] }
Move stuff to vendor bundle
Move stuff to vendor bundle
JavaScript
apache-2.0
SignalK/instrumentpanel,SignalK/instrumentpanel
--- +++ @@ -3,7 +3,7 @@ module.exports = { entry: { ui: './lib/ui/main.js', - vendor: ['react', 'debug'] + vendor: ['react', 'debug', 'd3', 'react-bootstrap'] }, output: { path: 'dist',
a6854e7f88a94b09a0f15400463af8693249de09
lib/config.js
lib/config.js
'use strict' const path = require('path') const nconf = require('nconf') const defaults = { port: 5000, mongo: { url: 'mongodb://localhost/link-analyzer', }, redis: { host: 'localhost', port: 6379, }, kue: { prefix: 'q', }, } nconf .file({ file: path.join(__dirname, '..', 'config.json') }) .env({ separator: '_', lowerCase: true }) .defaults({ store: defaults }) module.exports = nconf
'use strict' const path = require('path') const nconf = require('nconf') const defaults = { port: 6000, mongo: { url: 'mongodb://localhost/link-analyzer', }, redis: { host: 'localhost', port: 6379, }, kue: { prefix: 'q', }, } nconf .file({ file: path.join(__dirname, '..', 'config.json') }) .env({ separator: '_', lowerCase: true }) .defaults({ store: defaults }) module.exports = nconf
Change default port to 6000 as specified in geogw
Change default port to 6000 as specified in geogw
JavaScript
mit
inspireteam/link-analyzer
--- +++ @@ -5,7 +5,7 @@ const defaults = { - port: 5000, + port: 6000, mongo: { url: 'mongodb://localhost/link-analyzer',
a752e6c1c2eadfaf2a278c7d5ee7f0494b8ed163
lib/batch/translator.js
lib/batch/translator.js
function Translator(domain) { this.domain = domain; this.init(); } Translator.prototype = { TYPE_ADD: 'add', MAPPED_FIELDS: { 'id': '_key' }, init: function() { this.table = this.getTableName(this.domain); }, getTableName: function(domain) { return domain; }, translate: function(batch) { }, translateOne: function(batch) { switch (batch.type) { case this.TYPE_ADD: return this.addToLoad(batch); default: throw new Error('batch type "' + batch.type + '" is not acceptable'); } }, addToLoad: function(batch) { var line = { _key: batch.id }; for (var field in batch.fields) { if (!batch.fields.hasOwnProperty(field)) continue; line[field] = batch.fields[field]; } var command = 'load --table ' + this.table + JSON.stringify([line]); return command; } }; exports.Translator = Translator;
function Translator(domain) { this.domain = domain; this.init(); } Translator.prototype = { TYPE_ADD: 'add', MAPPED_FIELDS: { 'id': '_key' }, init: function() { this.table = this.getTableName(this.domain); }, getTableName: function(domain) { return domain; }, translate: function(batch) { }, translateOne: function(batch) { switch (batch.type) { case this.TYPE_ADD: return this.addToLoad(batch); default: throw new Error('batch type "' + batch.type + '" is not acceptable'); } }, addToLoad: function(batch) { var line = { _key: batch.id }; for (var field in batch.fields) { if (!batch.fields.hasOwnProperty(field)) continue; line[field] = batch.fields[field]; } var command = 'load --table ' + this.table + ' ' + JSON.stringify([line]); return command; } }; exports.Translator = Translator;
Add padding space between table name and loaded data
Add padding space between table name and loaded data
JavaScript
mit
groonga/gcs,groonga/gcs
--- +++ @@ -35,7 +35,7 @@ continue; line[field] = batch.fields[field]; } - var command = 'load --table ' + this.table + JSON.stringify([line]); + var command = 'load --table ' + this.table + ' ' + JSON.stringify([line]); return command; } };
ed45aff0857eeac70aef4d339f6f97c805cadc82
src/model/settings.js
src/model/settings.js
import {Events} from 'tabris'; import {mixin} from './helpers'; const store = {}; class Settings { get serverUrl() { return store.serverUrl; } set serverUrl(url) { store.serverUrl = url; localStorage.setItem('serverUrl', url); this.trigger('change:serverUrl'); } load() { store.serverUrl = localStorage.getItem('serverUrl') || 'http://192.168.1.'; } } mixin(Settings, Events); export default new Settings();
import {Events} from 'tabris'; import {mixin} from './helpers'; const store = {}; class Settings { get serverUrl() { return store.serverUrl; } set serverUrl(url) { store.serverUrl = url; localStorage.setItem('serverUrl', url); this.trigger('change:serverUrl'); } load() { store.serverUrl = localStorage.getItem('serverUrl') || 'http://192.168.1.1'; } } mixin(Settings, Events); export default new Settings();
Use complete IP address as default
Use complete IP address as default Work around crash due to tabris-js issue 956
JavaScript
mit
ralfstx/kitchen-radio-app
--- +++ @@ -16,7 +16,7 @@ } load() { - store.serverUrl = localStorage.getItem('serverUrl') || 'http://192.168.1.'; + store.serverUrl = localStorage.getItem('serverUrl') || 'http://192.168.1.1'; } }
68b7afc956bf0dc2802f266183abb08e9930b3e9
lib/errors.js
lib/errors.js
var inherits = require('inherits'); var self = module.exports = { FieldValidationError: FieldValidationError, ModelValidationError: ModelValidationError, messages: { "en-us": { "generic": "Failed to validate field", "required": "The field is required", "wrong_type": "Field value is not of type {type}" } }, getMessage: function(type, params, lang) { lang = lang || "en-us"; return self.messages[lang][type].replace(/\${([\w:]+)}/g, function(match, varname) { return params[varname]; }); } }; function FieldValidationError(type, params) { this.type = type || 'generic'; this.params = params; this.message = self.getMessage(type, params); this.stack = new Error(this.message).stack; } inherits(FieldValidationError, Error); function ModelValidationError(errors) { this.errors = errors; this.message = "Error validating the model \n"+JSON.stringify(errors); this.stack = new Error(this.message).stack; } inherits(ModelValidationError, Error);
var inherits = require('inherits'); var self = module.exports = { FieldValidationError: FieldValidationError, ModelValidationError: ModelValidationError, messages: { "en-us": { "generic": "Failed to validate field", "required": "The field is required", "wrong_type": "Field value is not of type {type}" } }, getMessage: function(type, params, lang) { lang = lang || "en-us"; return self.messages[lang][type].replace(/\${([\w:]+)}/g, function(match, varname) { return params[varname]; }); } }; function FieldValidationError(type, params) { this.type = type || 'generic'; this.params = params; this.message = self.getMessage(type, params); this.stack = new Error(this.message).stack; } inherits(FieldValidationError, Error); function ModelValidationError(errors) { this.errors = errors; var message = "Error validating the model \n"; Object.keys(errors).forEach(function(field) { message += field + ": " + errors[field].message + "\n"; }); this.message = message; this.stack = new Error(this.message).stack; } inherits(ModelValidationError, Error);
Improve formatting of ModelValidationError toString()
Improve formatting of ModelValidationError toString()
JavaScript
mit
mariocasciaro/minimodel,D4H/minimodel
--- +++ @@ -20,9 +20,6 @@ } }; - - - function FieldValidationError(type, params) { this.type = type || 'generic'; this.params = params; @@ -33,10 +30,13 @@ inherits(FieldValidationError, Error); - function ModelValidationError(errors) { this.errors = errors; - this.message = "Error validating the model \n"+JSON.stringify(errors); + var message = "Error validating the model \n"; + Object.keys(errors).forEach(function(field) { + message += field + ": " + errors[field].message + "\n"; + }); + this.message = message; this.stack = new Error(this.message).stack; } inherits(ModelValidationError, Error);
b9129f100079a6bf96d086b95c8f65fa8f82d8d4
lib/memdash/server/public/charts.js
lib/memdash/server/public/charts.js
$(document).ready(function(){ $.jqplot('gets-sets', [$("#gets-sets").data("gets"), $("#gets-sets").data("sets")], { title: 'Gets & Sets', grid: { drawBorder: false, shadow: false, background: '#fefefe' }, axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer }, seriesDefaults: { rendererOptions: { smooth: true } } }); $.jqplot('hits-misses', [$("#hits-misses").data("hits"), $("#hits-misses").data("misses")], { title: 'Hits & Misses', grid: { drawBorder: false, shadow: false, background: '#fefefe' }, axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer }, seriesDefaults: { rendererOptions: { smooth: true } } }); });
$(document).ready(function(){ $.jqplot('gets-sets', [$("#gets-sets").data("gets"), $("#gets-sets").data("sets")], { title: 'Gets & Sets', grid: { drawBorder: false, shadow: false, background: '#fefefe' }, axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer }, seriesDefaults: { rendererOptions: { smooth: true } }, series: [ {label: 'Gets'}, {label: 'Sets'} ], legend: { show: true }, seriesColors: ["rgb(36, 173, 227)", "rgb(227, 36, 132)"] }); $.jqplot('hits-misses', [$("#hits-misses").data("hits"), $("#hits-misses").data("misses")], { title: 'Hits & Misses', grid: { drawBorder: false, shadow: false, background: '#fefefe' }, axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer }, seriesDefaults: { rendererOptions: { smooth: true } }, series: [ {label: 'Hits'}, {label: 'Misses'} ], legend: { show: true }, seriesColors: ["rgb(227, 36, 132)", "rgb(227, 193, 36)"] }); });
Set legends and colors of series
Set legends and colors of series
JavaScript
mit
bryckbost/memdash,bryckbost/memdash
--- +++ @@ -13,7 +13,15 @@ rendererOptions: { smooth: true } - } + }, + series: [ + {label: 'Gets'}, + {label: 'Sets'} + ], + legend: { + show: true + }, + seriesColors: ["rgb(36, 173, 227)", "rgb(227, 36, 132)"] }); $.jqplot('hits-misses', [$("#hits-misses").data("hits"), $("#hits-misses").data("misses")], { title: 'Hits & Misses', @@ -29,6 +37,14 @@ rendererOptions: { smooth: true } - } + }, + series: [ + {label: 'Hits'}, + {label: 'Misses'} + ], + legend: { + show: true + }, + seriesColors: ["rgb(227, 36, 132)", "rgb(227, 193, 36)"] }); });
bf2db67a14522f853bd0e898286947fdb0ed626b
src/js/constants.js
src/js/constants.js
/* eslint-disable max-len */ import dayjs from "dayjs"; export const GDQ_API_ENDPOINT = "https://api.gdqstat.us"; export const OFFLINE_MODE = true; const LIVE_STORAGE_ENDPOINT = "https://storage.api.gdqstat.us"; // Note: Keep this up-to-date with the most recent event export const EVENT_YEAR = 2019; export const EVENT_SHORT_NAME = "agdq"; export const EVENT_START_DATE = dayjs("01-05-20"); const OFFLINE_STORAGE_ENDPOINT = `/data/${EVENT_YEAR}/${EVENT_SHORT_NAME}_final`; export const GDQ_STORAGE_ENDPOINT = OFFLINE_MODE ? OFFLINE_STORAGE_ENDPOINT : LIVE_STORAGE_ENDPOINT; export const DONATION_TRACKER_URL = `https://gamesdonequick.com/tracker/index/${EVENT_SHORT_NAME}${EVENT_YEAR}`; export const SECONDARY_COLOR = "#F21847"; export const PRIMARY_COLOR = "#00AEEF"; export const PANEL_BACKGROUND_COLOR = "#EEEEEE"; export const LIGHT_FILL_COLOR = "#DDDDDD"; export const DARK_FILL_COLOR = "#333333";
/* eslint-disable max-len */ import dayjs from "dayjs"; export const GDQ_API_ENDPOINT = "https://api.gdqstat.us"; export const OFFLINE_MODE = true; const LIVE_STORAGE_ENDPOINT = "https://storage.api.gdqstat.us"; // Note: Keep this up-to-date with the most recent event export const EVENT_YEAR = 2020; export const EVENT_SHORT_NAME = "agdq"; export const EVENT_START_DATE = dayjs("01-05-20"); const OFFLINE_STORAGE_ENDPOINT = `/data/${EVENT_YEAR}/${EVENT_SHORT_NAME}_final`; export const GDQ_STORAGE_ENDPOINT = OFFLINE_MODE ? OFFLINE_STORAGE_ENDPOINT : LIVE_STORAGE_ENDPOINT; export const DONATION_TRACKER_URL = `https://gamesdonequick.com/tracker/index/${EVENT_SHORT_NAME}${EVENT_YEAR}`; export const SECONDARY_COLOR = "#F21847"; export const PRIMARY_COLOR = "#00AEEF"; export const PANEL_BACKGROUND_COLOR = "#EEEEEE"; export const LIGHT_FILL_COLOR = "#DDDDDD"; export const DARK_FILL_COLOR = "#333333";
Fix offline endpoint to point to 2020 instead of 2019
Fix offline endpoint to point to 2020 instead of 2019
JavaScript
mit
bcongdon/sgdq-stats,bcongdon/gdq-stats,bcongdon/sgdq-stats,bcongdon/gdq-stats,bcongdon/sgdq-stats
--- +++ @@ -8,7 +8,7 @@ const LIVE_STORAGE_ENDPOINT = "https://storage.api.gdqstat.us"; // Note: Keep this up-to-date with the most recent event -export const EVENT_YEAR = 2019; +export const EVENT_YEAR = 2020; export const EVENT_SHORT_NAME = "agdq"; export const EVENT_START_DATE = dayjs("01-05-20");
24c1af11a108aa8be55337f057b453cb1052cab6
test/components/Button_test.js
test/components/Button_test.js
// import { test, getRenderedComponent } from '../spec_helper' // import { default as subject } from '../../src/components/buttons/Button' // test('#render', (assert) => { // const button = getRenderedComponent(subject, {className: 'MyButton'}, 'Yo') // assert.equal(button.type, 'button') // assert.equal(button.props.className, 'MyButton Button') // assert.equal(button.props.classListName, 'Button') // assert.equal(button.props.children, 'Yo') // assert.end() // })
import { expect, getRenderedComponent } from '../spec_helper' import { default as subject } from '../../src/components/buttons/Button' describe('Button#render', () => { it('renders correctly', () => { const button = getRenderedComponent(subject, {className: 'MyButton'}, 'Yo') expect(button.type).to.equal('button') expect(button.props.className).to.equal('MyButton Button') expect(button.props.classListName).to.equal('Button') expect(button.props.children).to.equal('Yo') }) })
Add back in the button tests
Add back in the button tests
JavaScript
mit
ello/webapp,ello/webapp,ello/webapp
--- +++ @@ -1,12 +1,13 @@ -// import { test, getRenderedComponent } from '../spec_helper' -// import { default as subject } from '../../src/components/buttons/Button' +import { expect, getRenderedComponent } from '../spec_helper' +import { default as subject } from '../../src/components/buttons/Button' -// test('#render', (assert) => { -// const button = getRenderedComponent(subject, {className: 'MyButton'}, 'Yo') -// assert.equal(button.type, 'button') -// assert.equal(button.props.className, 'MyButton Button') -// assert.equal(button.props.classListName, 'Button') -// assert.equal(button.props.children, 'Yo') -// assert.end() -// }) +describe('Button#render', () => { + it('renders correctly', () => { + const button = getRenderedComponent(subject, {className: 'MyButton'}, 'Yo') + expect(button.type).to.equal('button') + expect(button.props.className).to.equal('MyButton Button') + expect(button.props.classListName).to.equal('Button') + expect(button.props.children).to.equal('Yo') + }) +})
0178ee1c94589270d78af013cf7ad493de04b637
src/reducers/index.js
src/reducers/index.js
import { combineReducers } from 'redux' import { RECEIVE_STOP_DATA } from '../actions' const cardsReducer = () => { return {cards: [{name: 'Fruängen', stopId: '9260', updating: false, error: false},{name: 'Slussen', stopId: '9192', updating: false, error: false}]} } const stopsReducer = (state, action) => { switch (action.type) { case RECEIVE_STOP_DATA: var s = Object.assign({}, state) s.stops[action.stop] = action.data.departures return s default: return state == undefined ? {stops: {}} : state } } const departuresApp = combineReducers({ cardsReducer, stopsReducer }) export default departuresApp
import { combineReducers } from 'redux' import { RECEIVE_STOP_DATA } from '../actions' const cardsReducer = () => { return {cards: [ { name: 'Fruängen', stopId: '9260', updating: false, error: false, lines: [{ line: '14', direction: 1 }] }, { name: 'Slussen', stopId: '9192', updating: false, error: false, lines: [{ line: '14', direction: 2 }] }]} } /* * Filter new stop information and add them to the new state */ const stopsReducer = (state, action) => { switch (action.type) { case RECEIVE_STOP_DATA: var newState = Object.assign({}, state) newState.stops[action.stop] = action.data.departures return newState default: return state == undefined ? {stops: {}} : state } } const departuresApp = combineReducers({ cardsReducer, stopsReducer }) export default departuresApp
Add direction information to cards
Add direction information to cards
JavaScript
apache-2.0
Ozzee/sl-departures,Ozzee/sl-departures
--- +++ @@ -2,15 +2,38 @@ import { RECEIVE_STOP_DATA } from '../actions' const cardsReducer = () => { - return {cards: [{name: 'Fruängen', stopId: '9260', updating: false, error: false},{name: 'Slussen', stopId: '9192', updating: false, error: false}]} + return {cards: [ + { + name: 'Fruängen', + stopId: '9260', + updating: false, + error: false, + lines: [{ + line: '14', + direction: 1 + }] + }, + { + name: 'Slussen', + stopId: '9192', + updating: false, + error: false, + lines: [{ + line: '14', + direction: 2 + }] + }]} } +/* + * Filter new stop information and add them to the new state + */ const stopsReducer = (state, action) => { switch (action.type) { case RECEIVE_STOP_DATA: - var s = Object.assign({}, state) - s.stops[action.stop] = action.data.departures - return s + var newState = Object.assign({}, state) + newState.stops[action.stop] = action.data.departures + return newState default: return state == undefined ? {stops: {}} : state
6648b1b1027a7fcc099f88339b312c7a03de1cd8
src/server/loggers.js
src/server/loggers.js
'use strict'; var winston = require('winston'); var expressWinston = require('express-winston'); var requestLogger = expressWinston.logger({ transports: [ new winston.transports.Console({ json: true, colorize: true }) ], meta: true, msg: 'HTTP {{req.method}} {{req.url}}', expressFormat: true, colorStatus: true }); var errorLogger = expressWinston.errorLogger({ transports: [ new winston.transports.Console({ json: true, colorize: true }) ] }); var logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ timestamp: function() { return Date.now(); }, formatter: function(options) { // Return string will be passed to logger. return options.timestamp() +' '+ options.level.toUpperCase() +' '+ (undefined !== options.message ? options.message : '') + (options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' ); } }) ] }); module.exports = { request: requestLogger, error: errorLogger, logger: logger };
'use strict'; var winston = require('winston'); var expressWinston = require('express-winston'); var requestLogger = expressWinston.logger({ transports: [ new winston.transports.Console({ json: true, colorize: true }) ], meta: true, msg: 'HTTP {{req.method}} {{req.url}}', expressFormat: true, colorStatus: true }); var errorLogger = expressWinston.errorLogger({ transports: [ new winston.transports.Console({ json: true, colorize: true }) ] }); var logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ timestamp: function() { return Date.now(); }, formatter: function(options) { // Return string will be passed to logger. return options.timestamp() +' '+ options.level.toLowerCase() + ': '+ (undefined !== options.message ? options.message : '') + (options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' ); } }) ] }); module.exports = { request: requestLogger, error: errorLogger, logger: logger };
Change log level to lowercase
Change log level to lowercase
JavaScript
mit
rangle/the-clusternator,rafkhan/the-clusternator,bennett000/the-clusternator,alanthai/the-clusternator,rangle/the-clusternator,bennett000/the-clusternator,bennett000/the-clusternator,rangle/the-clusternator,rafkhan/the-clusternator,alanthai/the-clusternator
--- +++ @@ -33,7 +33,7 @@ }, formatter: function(options) { // Return string will be passed to logger. - return options.timestamp() +' '+ options.level.toUpperCase() +' '+ (undefined !== options.message ? options.message : '') + + return options.timestamp() +' '+ options.level.toLowerCase() + ': '+ (undefined !== options.message ? options.message : '') + (options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' ); } })