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
ccc01b4599b586651bab6a60df91517bced9e4d4
src/social-icon.js
src/social-icon.js
import React, { PropTypes } from 'react'; import cx from 'classnames'; import Background from './background'; import Icon from './icon'; import Mask from './mask'; import { keyFor } from './networks'; import { socialIcon, socialContainer, socialSvg } from './styles'; function getNetworkKey(props) { return props.network || keyFor(props.url); } function SocialIcon(props) { const { url, network, color, className, ...rest } = props; const networkKey = getNetworkKey({ url, network }); return ( <a {...rest} href={url} target="_blank" rel="noopener" className={cx('social-icon', className)} style={{ ...socialIcon, ...props.style }}> <div className="social-container" style={socialContainer} > <svg className="social-svg" style={socialSvg} viewBox="0 0 64 64"> <Background /> <Icon networkKey={networkKey} /> <Mask networkKey={networkKey} color={color} /> </svg> </div> </a> ); } SocialIcon.propTypes = { className: PropTypes.string, color: PropTypes.string, network: PropTypes.string, url: PropTypes.string, }; export default SocialIcon;
import React, { PropTypes } from 'react'; import cx from 'classnames'; import Background from './background'; import Icon from './icon'; import Mask from './mask'; import { keyFor } from './networks'; import { socialIcon, socialContainer, socialSvg } from './styles'; function getNetworkKey(props) { return props.network || keyFor(props.url); } function SocialIcon(props) { const { url, network, color, className, label, ...rest } = props; const networkKey = getNetworkKey({ url, network }); return ( <a {...rest} href={url} target="_blank" rel="noopener" className={cx('social-icon', className)} style={{ ...socialIcon, ...props.style }} aria-label={label}> <div className="social-container" style={socialContainer} > <svg className="social-svg" style={socialSvg} viewBox="0 0 64 64"> <Background /> <Icon networkKey={networkKey} /> <Mask networkKey={networkKey} color={color} /> </svg> </div> </a> ); } SocialIcon.propTypes = { className: PropTypes.string, color: PropTypes.string, label: PropTypes.string, network: PropTypes.string, url: PropTypes.string, }; export default SocialIcon;
Add support for label prop
Add support for label prop
JavaScript
mit
jaketrent/react-social-icons,jaketrent/react-social-icons
--- +++ @@ -11,7 +11,7 @@ } function SocialIcon(props) { - const { url, network, color, className, ...rest } = props; + const { url, network, color, className, label, ...rest } = props; const networkKey = getNetworkKey({ url, network }); return ( @@ -20,7 +20,8 @@ target="_blank" rel="noopener" className={cx('social-icon', className)} - style={{ ...socialIcon, ...props.style }}> + style={{ ...socialIcon, ...props.style }} + aria-label={label}> <div className="social-container" style={socialContainer} > <svg className="social-svg" style={socialSvg} viewBox="0 0 64 64"> <Background /> @@ -35,6 +36,7 @@ SocialIcon.propTypes = { className: PropTypes.string, color: PropTypes.string, + label: PropTypes.string, network: PropTypes.string, url: PropTypes.string, };
f8787b6bccd15d8850a10ea66a9d13bb059437cc
src/store/store.js
src/store/store.js
import { createStore, applyMiddleware, compose } from 'redux'; import createHistory from 'history/createHashHistory'; import { routerMiddleware } from 'connected-react-router'; import createRootReducer from 'reducers/root'; import gitHubAPIMiddleware from 'middlewares/gitHubAPI'; export const history = createHistory(); const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const middlewares = [routerMiddleware(history), gitHubAPIMiddleware]; if (process.env.NODE_ENV === 'development') { const freeze = require('redux-freeze'); // const { createLogger } = require('redux-logger'); // const logger = createLogger({ collapsed: true }); const middlewaresToAdd = [ freeze // logger ]; middlewares.push(...middlewaresToAdd); } const store = createStore( createRootReducer(history), composeEnhancers(applyMiddleware(...middlewares)) ); export default store;
import { createStore, applyMiddleware, compose } from 'redux'; import { createHashHistory } from 'history'; import { routerMiddleware } from 'connected-react-router'; import createRootReducer from 'reducers/root'; import gitHubAPIMiddleware from 'middlewares/gitHubAPI'; export const history = createHashHistory(); const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const middlewares = [routerMiddleware(history), gitHubAPIMiddleware]; if (process.env.NODE_ENV === 'development') { const freeze = require('redux-freeze'); // const { createLogger } = require('redux-logger'); // const logger = createLogger({ collapsed: true }); const middlewaresToAdd = [ freeze // logger ]; middlewares.push(...middlewaresToAdd); } const store = createStore( createRootReducer(history), composeEnhancers(applyMiddleware(...middlewares)) ); export default store;
FIX (router): use proper import instead of depricated
FIX (router): use proper import instead of depricated
JavaScript
mit
Gisto/Gisto,Gisto/Gisto,Gisto/Gisto,Gisto/Gisto
--- +++ @@ -1,10 +1,10 @@ import { createStore, applyMiddleware, compose } from 'redux'; -import createHistory from 'history/createHashHistory'; +import { createHashHistory } from 'history'; import { routerMiddleware } from 'connected-react-router'; import createRootReducer from 'reducers/root'; import gitHubAPIMiddleware from 'middlewares/gitHubAPI'; -export const history = createHistory(); +export const history = createHashHistory(); const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const middlewares = [routerMiddleware(history), gitHubAPIMiddleware];
a04c89d7251148fdc298828535fdfd4977893135
app/services/data/get-team-caseload.js
app/services/data/get-team-caseload.js
const config = require('../../../knexfile').web const knex = require('knex')(config) module.exports = function (id, type) { var table = "team_caseload_overview" var whereObject = {} if (id !== undefined) { whereObject.id = id } return knex(table) .where(whereObject) .select('name', 'gradeCode', 'untiered', 'd2', 'd1', 'c2', 'c1', 'b2', 'b1', 'a', 'totalCases') .then(function (results) { return results }) }
const config = require('../../../knexfile').web const knex = require('knex')(config) module.exports = function (id, type) { var table = "team_caseload_overview" var whereObject = {} if (id !== undefined) { whereObject.id = id } return knex(table) .where(whereObject) .select('name', 'grade_code as gradeCode', 'untiered', 'd2', 'd1', 'c2', 'c1', 'b2', 'b1', 'a', 'total_cases as totalCases') .then(function (results) { return results }) }
Change the column name to follow the standard naming convention.
784: Change the column name to follow the standard naming convention.
JavaScript
mit
ministryofjustice/wmt-web,ministryofjustice/wmt-web
--- +++ @@ -10,7 +10,7 @@ return knex(table) .where(whereObject) .select('name', - 'gradeCode', + 'grade_code as gradeCode', 'untiered', 'd2', 'd1', @@ -19,7 +19,7 @@ 'b2', 'b1', 'a', - 'totalCases') + 'total_cases as totalCases') .then(function (results) { return results })
5754f8e24f47a86f442e5833bff15661a45c6a30
scripts.js
scripts.js
var markup = null; $(function() { var markupTools = MarkupTools('.button-bar > div'); markup = Markup('#pdf-markup', markupTools); $(markup).on('update add', function() { $('#result').text(JSON.stringify(markup.Serialize())); }); $(markupTools).on('browse', function(e, settings) { new Browser(settings); }); $('.button-bar > ul').find('a').each(function() { var pluginName = $(this).data('plugin'); var plugin = window[pluginName]; markup.AddPlugin(plugin); $(this).on('click', function(){ window[$(this).data('plugin')].New(markup); }); }); });
var markup = null; $(function() { var markupTools = MarkupTools('.button-bar > div'); markup = Markup('#pdf-markup', markupTools); $(markup).on('update add', function() { $('#result').text(JSON.stringify(markup.Serialize())); }); $(markupTools).on('browse', function(e, settings) { new Browser(settings); }); $('.button-bar > ul').find('a').each(function() { var pluginName = $(this).data('plugin'); var plugin = window[pluginName]; markup.AddPlugin(plugin); $(this).on('click', function(){ window[$(this).data('plugin')].New(markup); }); }); markup.Load([{"type":"text","text":"Invoice","x":94,"y":2,"color":"#00000","size":"20","bold":"1"},{"type":"image","source":"example.png","x":47,"y":50,"width":"129"}]); });
Add example of using the Load method on the Markup object
Add example of using the Load method on the Markup object
JavaScript
mit
Soneritics/pdf-markup,Soneritics/pdf-markup
--- +++ @@ -18,4 +18,6 @@ markup.AddPlugin(plugin); $(this).on('click', function(){ window[$(this).data('plugin')].New(markup); }); }); + + markup.Load([{"type":"text","text":"Invoice","x":94,"y":2,"color":"#00000","size":"20","bold":"1"},{"type":"image","source":"example.png","x":47,"y":50,"width":"129"}]); });
4fb0b46888829fb6b325dfa666cad5763eacdfeb
src/client.js
src/client.js
import React from 'react' import { applyMiddleware, createStore, compose } from 'redux' import { render } from 'react-dom' import { Provider } from 'react-redux' import { applyRouterMiddleware, browserHistory, Router } from 'react-router' import { ReduxAsyncConnect } from 'redux-connect' import { persistState } from 'redux-devtools' import { routerMiddleware, syncHistoryWithStore } from 'react-router-redux' import useScroll from 'react-router-scroll' import PromiseMiddleware from './middlewares/PromiseMiddleware' import reducers from './reducers' import routes from './routes' const initialState = decodeURIComponent(window.__INITIAL_STATE__) const store = createStore( reducers, initialState, compose( applyMiddleware( PromiseMiddleware, routerMiddleware(browserHistory) ), window.devToolsExtension && window.devToolsExtension(), persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)) ), ) const history = syncHistoryWithStore(browserHistory, store) render( <Provider store={ store }> <Router render={ (renderProps) => { return ( <ReduxAsyncConnect { ...renderProps } render={ applyRouterMiddleware(useScroll()) } /> ) } } history={ history }> { routes(store) } </Router> </Provider>, document.getElementById('root') )
import React from 'react' import { applyMiddleware, createStore, compose } from 'redux' import { render } from 'react-dom' import { Provider } from 'react-redux' import { applyRouterMiddleware, browserHistory, Router } from 'react-router' import { ReduxAsyncConnect } from 'redux-connect' import { persistState } from 'redux-devtools' import { routerMiddleware, syncHistoryWithStore } from 'react-router-redux' import useScroll from 'react-router-scroll' import PromiseMiddleware from './middlewares/PromiseMiddleware' import reducers from './reducers' import routes from './routes' const initialState = decodeURIComponent(window.__INITIAL_STATE__) const store = createStore( reducers, initialState, // compose( applyMiddleware( PromiseMiddleware, routerMiddleware(browserHistory) ), // (window.devToolsExtension // ? window.devToolsExtension() // : null), // persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)) // ), ) const history = syncHistoryWithStore(browserHistory, store) render( <Provider store={ store }> <Router render={ (renderProps) => { return ( <ReduxAsyncConnect { ...renderProps } render={ applyRouterMiddleware(useScroll()) } /> ) } } history={ history }> { routes(store) } </Router> </Provider>, document.getElementById('root') )
Disable redux devtools for fixing invalid object on mobile browser
Disable redux devtools for fixing invalid object on mobile browser
JavaScript
mit
nomkhonwaan/nomkhonwaan.github.io
--- +++ @@ -16,14 +16,16 @@ const store = createStore( reducers, initialState, - compose( + // compose( applyMiddleware( PromiseMiddleware, routerMiddleware(browserHistory) ), - window.devToolsExtension && window.devToolsExtension(), - persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)) - ), + // (window.devToolsExtension + // ? window.devToolsExtension() + // : null), + // persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)) + // ), ) const history = syncHistoryWithStore(browserHistory, store)
0e0e931c759a1ed3589481eaa2e6b82511519bba
examples/whack/js/common.js
examples/whack/js/common.js
var hits = 0; function setup() { hits = 0; } function hit() { hits++; console.log(hits); } function showAll() { $('.hole').flip(true); } function hideAll() { $('.hole').flip({ trigger: 'manual' }); } function randomTimeout() { return Math.random() * 5000 + 2500; } function won() { console.log('You won!'); } function lost() { console.log('You lost!'); }
var hits = 0; function setup() { hits = 0; } function hit() { hits++; } function showAll() { $('.hole').flip(true); } function hideAll() { $('.hole').flip({ trigger: 'manual' }); } function randomTimeout() { return Math.random() * 5000 + 2500; } function won() { alert('You won!'); } function lost() { alert('You lost!'); }
Remove debugging statements from example.
Remove debugging statements from example.
JavaScript
mit
efritz/arrows,JoshuaSCochrane/arrows
--- +++ @@ -6,7 +6,6 @@ function hit() { hits++; - console.log(hits); } function showAll() { @@ -24,9 +23,9 @@ } function won() { - console.log('You won!'); + alert('You won!'); } function lost() { - console.log('You lost!'); + alert('You lost!'); }
28e6e967eac14e0d4196e45dcdea9c06cd5562b4
lib/dsl.js
lib/dsl.js
(function (define) { 'use strict'; define(function (require) { var _ = require('lodash'); function DSL() { this.matches = []; } _.extend(DSL.prototype, { route: function (name, options, callback) { if (arguments.length === 2 && typeof options === 'function') { callback = options; options = {}; } if (arguments.length === 1) { options = {}; } if (typeof options.path !== 'string') { var parts = name.split("."); options.path = parts[parts.length - 1]; } if (callback) { var routes = DSL.map(callback); this.push(options.path, name, routes); } else { this.push(options.path, name, null); } }, push: function (url, name, routes) { this.matches.push({ path: url, name: name, routes: routes }); }, generate: function () { return this.matches; } }); DSL.map = function (callback) { var dsl = new DSL(); callback.call(dsl); return dsl.generate(); }; return DSL; }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
(function (define) { 'use strict'; define(function (require) { var _ = require('lodash'); function DSL(ancestors) { this.ancestors = ancestors; this.matches = []; } _.extend(DSL.prototype, { route: function (name, options, callback) { if (arguments.length === 2 && typeof options === 'function') { callback = options; options = {}; } if (arguments.length === 1) { options = {}; } if (typeof options.path !== 'string') { var parts = name.split("."); options.path = parts[parts.length - 1]; } if (callback) { var routes = DSL.map(callback, this.ancestors.concat(name)); this.push(options.path, name, routes); } else { this.push(options.path, name, null); } }, push: function (url, name, routes) { this.matches.push({ path: url, name: name, routes: routes, ancestors: this.ancestors }); }, generate: function () { return this.matches; } }); DSL.map = function (callback, ancestors) { var dsl = new DSL(ancestors || []); callback.call(dsl); return dsl.generate(); }; return DSL; }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
Add information about the ancestors to each route descriptor
Add information about the ancestors to each route descriptor
JavaScript
mit
QubitProducts/cherrytree,QubitProducts/cherrytree,nathanboktae/cherrytree,nathanboktae/cherrytree
--- +++ @@ -3,7 +3,8 @@ var _ = require('lodash'); - function DSL() { + function DSL(ancestors) { + this.ancestors = ancestors; this.matches = []; } @@ -24,7 +25,7 @@ } if (callback) { - var routes = DSL.map(callback); + var routes = DSL.map(callback, this.ancestors.concat(name)); this.push(options.path, name, routes); } else { this.push(options.path, name, null); @@ -35,7 +36,8 @@ this.matches.push({ path: url, name: name, - routes: routes + routes: routes, + ancestors: this.ancestors }); }, @@ -44,8 +46,8 @@ } }); - DSL.map = function (callback) { - var dsl = new DSL(); + DSL.map = function (callback, ancestors) { + var dsl = new DSL(ancestors || []); callback.call(dsl); return dsl.generate(); };
6eabbb5565d5b529835cd36ac5d7d3c380416105
spec/buster.js
spec/buster.js
var config = module.exports; config["specs"] = { rootPath: "../", environment: "browser", sources: [ "lib/*.js" ], tests: [ "spec/*.spec.js" ], }
/*global module: true */ var config = module.exports; config.specs = { rootPath: "../", environment: "browser", sources: [ // lib/helpers.js needs to be loaded first "lib/helpers.js", "lib/EnglishParser.js", "lib/interpreters.js" ], specs: [ "spec/*.spec.js" ] };
Fix loading error of helpers.js
Fix loading error of helpers.js
JavaScript
mit
jmdeldin/content-usability,jmdeldin/content-usability
--- +++ @@ -1,12 +1,16 @@ +/*global module: true */ var config = module.exports; -config["specs"] = { - rootPath: "../", - environment: "browser", - sources: [ - "lib/*.js" - ], - tests: [ - "spec/*.spec.js" - ], -} +config.specs = { + rootPath: "../", + environment: "browser", + sources: [ + // lib/helpers.js needs to be loaded first + "lib/helpers.js", + "lib/EnglishParser.js", + "lib/interpreters.js" + ], + specs: [ + "spec/*.spec.js" + ] +};
dd634ae9873d1dddb44a20396e0d8ee8f764c429
src/Context.js
src/Context.js
import React from "react/addons"; import Resolver from "./Resolver"; class ResolverContext extends React.Component { getChildContext() { const resolver = this.props.resolver || this.context.resolver; return { resolver }; } render() { return React.addons.cloneWithProps(this.props.element, this.props); } } ResolverContext.childContextTypes = { resolver: React.PropTypes.any, }; ResolverContext.contextTypes = { resolver: React.PropTypes.any, }; ResolverContext.propTypes = { resolver: React.PropTypes.any, }; export default ResolverContext;
import React from "react"; import Resolver from "./Resolver"; class ResolverContext extends React.Component { getChildContext() { const resolver = this.props.resolver || this.context.resolver; return { resolver }; } render() { return React.cloneElement(this.props.element); } } ResolverContext.childContextTypes = { resolver: React.PropTypes.any, }; ResolverContext.contextTypes = { resolver: React.PropTypes.any, }; ResolverContext.propTypes = { resolver: React.PropTypes.any, }; export default ResolverContext;
Switch from React.addons.cloneWithProps to React.cloneElement
Switch from React.addons.cloneWithProps to React.cloneElement
JavaScript
isc
matthiasak/react-resolver,iamdustan/react-resolver,gilesbradshaw/react-resolver-csp,iamdustan/react-resolver,kwangkim/react-resolver,goatslacker/react-resolver,Daniel15/react-resolver,shaunstanislaus/react-resolver,gilesbradshaw/react-resolver-csp,eiriklv/react-resolver,donabrams/react-resolver
--- +++ @@ -1,4 +1,4 @@ -import React from "react/addons"; +import React from "react"; import Resolver from "./Resolver"; @@ -10,7 +10,7 @@ } render() { - return React.addons.cloneWithProps(this.props.element, this.props); + return React.cloneElement(this.props.element); } }
1b8b28bad82576de80b8066ccd4d23663a11598b
test-loader.js
test-loader.js
/* globals requirejs, require */ (function() { define("ember-cli/test-loader", [], function() { "use strict"; var TestLoader = function() { }; TestLoader.prototype = { shouldLoadModule: function(moduleName) { return (moduleName.match(/[-_]test$/)); }, loadModules: function() { var moduleName; for (moduleName in requirejs.entries) { if (this.shouldLoadModule(moduleName)) { this.require(moduleName); } } } }; TestLoader.prototype.require = function(moduleName) { try { require(moduleName); } catch(e) { this.moduleLoadFailure(moduleName, e); } }; TestLoader.prototype.moduleLoadFailure = function(moduleName, error) { console.error('Error loading: ' + moduleName, error.stack); }; TestLoader.load = function() { new TestLoader().loadModules(); }; return { 'default': TestLoader } } ); })();
/* globals requirejs, require */ (function() { define("ember-cli/test-loader", [], function() { "use strict"; var TestLoader = function() { }; TestLoader.prototype = { shouldLoadModule: function(moduleName) { return moduleName.match(/\/.*[-_]test$/); }, loadModules: function() { var moduleName; for (moduleName in requirejs.entries) { if (this.shouldLoadModule(moduleName)) { this.require(moduleName); } } } }; TestLoader.prototype.require = function(moduleName) { try { require(moduleName); } catch(e) { this.moduleLoadFailure(moduleName, e); } }; TestLoader.prototype.moduleLoadFailure = function(moduleName, error) { console.error('Error loading: ' + moduleName, error.stack); }; TestLoader.load = function() { new TestLoader().loadModules(); }; return { 'default': TestLoader } } ); })();
Exclude the project name when requiring files
Exclude the project name when requiring files
JavaScript
mit
ember-cli/ember-cli-test-loader
--- +++ @@ -10,7 +10,7 @@ TestLoader.prototype = { shouldLoadModule: function(moduleName) { - return (moduleName.match(/[-_]test$/)); + return moduleName.match(/\/.*[-_]test$/); }, loadModules: function() {
fd5251c0a047cf100ce051e2a6d4bfb4184d5131
test/unit/utils-test.js
test/unit/utils-test.js
'use strict'; var utils = require('../../').utils; var assert = require('chai').assert; suite('Utils', () => { test('create a random hex string', () => { const test1 = utils.getRandomHexString(); assert.isString(test1); assert.equal(test1, test1.match(/^[0-9A-F]{8}$/)[0]); const test2 = utils.getRandomHexString(16); assert.isString(test2); assert.equal(test2, test2.match(/^[0-9A-F]{16}$/)[0]); }); });
'use strict'; var utils = require('../../').utils; var assert = require('chai').assert; suite('Utils', () => { test('create a random hex string', () => { const test1 = utils.getRandomHexString(); assert.isString(test1); assert.equal(test1, test1.match(/^[0-9A-F]{8}$/)[0]); const test2 = utils.getRandomHexString(16); assert.isString(test2); assert.equal(test2, test2.match(/^[0-9A-F]{16}$/)[0]); }); test('getting host ips', () => { const hostIPs = utils.getHostIPs(); assert.isArray(hostIPs); hostIPs.forEach((ip) => { assert.isString(ip, 'IPs are given as'); assert.isTrue(ip.indexOf('.') >= 0 || ip.indexOf(':') >= 0, 'IP format'); }); }); });
Enhance test coverage of util helpers
Enhance test coverage of util helpers
JavaScript
mit
MariusRumpf/node-lifx
--- +++ @@ -13,4 +13,13 @@ assert.isString(test2); assert.equal(test2, test2.match(/^[0-9A-F]{16}$/)[0]); }); + + test('getting host ips', () => { + const hostIPs = utils.getHostIPs(); + assert.isArray(hostIPs); + hostIPs.forEach((ip) => { + assert.isString(ip, 'IPs are given as'); + assert.isTrue(ip.indexOf('.') >= 0 || ip.indexOf(':') >= 0, 'IP format'); + }); + }); });
109b89e89845eaa7371d74ab603ba993be0fb504
app/services/Admin/Admin.js
app/services/Admin/Admin.js
'use strict'; angular .module('lmServices') .constant('Admin', (/((; )|^)admin=true(;|$)/).test(document.cookie));
'use strict'; // This "admin" cookie is not intended to be secure. All it does is display a few convenience // buttons for quick access to the admin interface. Access to the admin interface is unrestricted; // the admin interface merely displays the same data as the normal web interface, but in an // editable manner. Authentication happens server-side when the user attempts to save changes. angular .module('lmServices') .constant('Admin', (/((; )|^)admin=true(;|$)/).test(document.cookie));
Add comments explaining how the admin interface works
Add comments explaining how the admin interface works
JavaScript
mit
peferron/lilymandarin-web,peferron/lilymandarin-web,peferron/lilymandarin-v1-web,peferron/lilymandarin-v1-web
--- +++ @@ -1,5 +1,9 @@ 'use strict'; +// This "admin" cookie is not intended to be secure. All it does is display a few convenience +// buttons for quick access to the admin interface. Access to the admin interface is unrestricted; +// the admin interface merely displays the same data as the normal web interface, but in an +// editable manner. Authentication happens server-side when the user attempts to save changes. angular .module('lmServices') .constant('Admin', (/((; )|^)admin=true(;|$)/).test(document.cookie));
c29f89a08b83fe3d907978d0ff38e0094a390b92
tests/DOM/CreateSpec.js
tests/DOM/CreateSpec.js
describe("$.create", function() { it("creates an element and sets properties on it", function() { var element = $.create("article", { className: "wide" }); expect(element).to.be.an.instanceOf(Element); expect(element.className).to.be.equal("wide"); expect(element.tagName).to.be.equal("ARTICLE"); }); it("returns a text node when called with only a string", function() { var text = $.create("Lorem Ipsom dolor sit amet"); expect(text).to.be.an.instanceOf(Text); }); describe("passed only an object", function() { it("creates an element and sets the properties on it", function() { var element = $.create({ tag: "span" }); expect(element).to.be.an.instanceOf(Element); expect(element.tagName).to.be.equal("SPAN"); }); it("creates a div by default", function() { var element = $.create({}); expect(element.tagName).to.be.equal("DIV"); }); }); });
describe("$.create", function() { it("creates an element and sets properties on it", function() { var element = $.create("article", { className: "wide" }); expect(element).to.be.an.instanceOf(Element); expect(element.className).to.be.equal("wide"); expect(element.tagName).to.be.equal("ARTICLE"); }); it("returns a text node when called with only a string", function() { var text = $.create("Lorem Ipsom dolor sit amet"); expect(text).to.be.an.instanceOf(Text); }); describe("passed only an object", function() { it("creates an element and sets the properties on it", function() { var element = $.create({ tag: "span" }); expect(element).to.be.an.instanceOf(Element); expect(element.tagName).to.be.equal("SPAN"); }); it("creates a div by default", function() { var element = $.create({}); expect(element.tagName).to.be.equal("DIV"); }); }); it("creates a div when there are no arguments", function() { var element = $.create(); expect(element.tagName).to.be.equal("DIV"); }); });
Test that $.create makes a div by default
Test that $.create makes a div by default Adds a test for #13
JavaScript
mit
LeaVerou/bliss,zdfs/bliss,LeaVerou/bliss,dperrymorrow/bliss,zdfs/bliss,dperrymorrow/bliss
--- +++ @@ -29,4 +29,10 @@ expect(element.tagName).to.be.equal("DIV"); }); }); + + it("creates a div when there are no arguments", function() { + var element = $.create(); + + expect(element.tagName).to.be.equal("DIV"); + }); });
f4fb9da3a005a95126cff182659d9415a0fe7b28
src/Spinner.js
src/Spinner.js
const React = require('react'); const classNames = require('classnames'); const SIZES = require('./SIZES'); const Spinner = React.createClass({ propTypes: { centered: React.PropTypes.bool, size: React.PropTypes.oneOf(SIZES) }, getDefaultProps: function() { return { centered: true, size: 'md' }; }, render: function() { let className = classNames('gb-spinner', 'spinner-' + this.props.size, { 'spinner-inverse': this.props.inverse, 'spinner-centered': this.props.centered }); return <div className={className}></div>; } }); /** * Block div representing a loading area */ const SpinnerSlate = React.createClass({ render: function() { return <div className="gb-spinner-slate"> <Spinner {...this.props} /> </div>; } }); module.exports = Spinner; module.exports.Slate = SpinnerSlate;
const React = require('react'); const classNames = require('classnames'); const SIZES = require('./SIZES'); const Spinner = React.createClass({ propTypes: { centered: React.PropTypes.bool, inverse: React.PropTypes.bool, size: React.PropTypes.oneOf(SIZES) }, getDefaultProps: function() { return { centered: true, size: 'md' }; }, render: function() { let className = classNames('gb-spinner', 'spinner-' + this.props.size, { 'spinner-inverse': this.props.inverse, 'spinner-centered': this.props.centered }); return <div className={className}></div>; } }); /** * Block div representing a loading area */ const SpinnerSlate = React.createClass({ render: function() { return <div className="gb-spinner-slate"> <Spinner {...this.props} /> </div>; } }); module.exports = Spinner; module.exports.Slate = SpinnerSlate;
Add prop inverse for spinner
Add prop inverse for spinner
JavaScript
apache-2.0
rlugojr/styleguide,GitbookIO/styleguide,GitbookIO/styleguide,rlugojr/styleguide
--- +++ @@ -6,6 +6,7 @@ const Spinner = React.createClass({ propTypes: { centered: React.PropTypes.bool, + inverse: React.PropTypes.bool, size: React.PropTypes.oneOf(SIZES) },
5368611171153c0abdd37e65b654415d6314e9ca
packages/inline-node/InsertInlineNodeCommand.js
packages/inline-node/InsertInlineNodeCommand.js
import Command from '../../ui/Command' import insertInlineNode from '../../model/transform/insertInlineNode' class InsertInlineNodeCommand extends Command { constructor(...args) { super(...args) if (!this.params.nodeType) { throw new Error('Every AnnotationCommand must have a nodeType') } } getCommandState(props, context) { let sel = context.documentSession.getSelection() let newState = { disabled: !sel.isPropertySelection(), active: false } return newState } execute(props, context) { let state = this.getCommandState(props, context) if (state.disabled) return let surface = context.surface || context.surfaceManager.getFocusedSurface() if (surface) { surface.transaction(function(tx, args) { return this.insertInlineNode(tx, args) }.bind(this)) } return true } insertInlineNode(tx, args) { args.node = this.createNodeData(tx, args) return insertInlineNode(tx, args) } createNodeData(tx, args) { // eslint-disable-line return { type: this.constructor.type } } _getAnnotationsForSelection(props) { return props.selectionState.getAnnotationsForType(this.params.nodeType) } } export default InsertInlineNodeCommand
import Command from '../../ui/Command' import insertInlineNode from '../../model/transform/insertInlineNode' class InsertInlineNodeCommand extends Command { constructor(...args) { super(...args) if (!this.params.nodeType) { throw new Error('Every AnnotationCommand must have a nodeType') } } getCommandState(props, context) { let sel = context.documentSession.getSelection() let newState = { disabled: !sel.isPropertySelection(), active: false } return newState } execute(props, context) { let state = this.getCommandState(props, context) if (state.disabled) return let surface = context.surface || context.surfaceManager.getFocusedSurface() if (surface) { surface.transaction(function(tx, args) { return this.insertInlineNode(tx, args) }.bind(this)) } return true } insertInlineNode(tx, args) { args.node = this.createNodeData(tx, args) return insertInlineNode(tx, args) } createNodeData(tx, args) { // eslint-disable-line return { type: this.params.nodeType } } _getAnnotationsForSelection(props) { return props.selectionState.getAnnotationsForType(this.params.nodeType) } } export default InsertInlineNodeCommand
Use nodeType from params instead of static prop.
Use nodeType from params instead of static prop.
JavaScript
mit
stencila/substance,andene/substance,podviaznikov/substance,substance/substance,michael/substance-1,substance/substance,podviaznikov/substance,michael/substance-1,andene/substance
--- +++ @@ -38,7 +38,7 @@ createNodeData(tx, args) { // eslint-disable-line return { - type: this.constructor.type + type: this.params.nodeType } }
057fde01ab9527d3a48d053d17b356d0fb6f6428
test/writer.js
test/writer.js
var fs = require('fs') var assert = require('assert') var rmrf = require('rimraf') var Writer = require('../src/writer') describe('Writer', function() { this.timeout(5000) var tempPath = __dirname + '/../tmp' var filePath = tempPath + '/../tmp/test.txt' beforeEach(function() { rmrf.sync(tempPath) fs.mkdirSync(tempPath) }) it('always writes data from the latest call', function(done) { var writer = new Writer(filePath) // 1M characters var data = '' for (var i = 0; i <= 1000 * 1000; i++) { data += 'x' } for (var i = 0; i <= 1000 * 1000; i++) { writer.write(data + i) } setTimeout(function() { assert.equal(fs.readFileSync(filePath, 'utf-8'), data + (i - 1)) done() }, 1000) }) })
var fs = require('fs') var assert = require('assert') var rmrf = require('rimraf') var Writer = require('../src/writer') describe('Writer', function() { this.timeout(10000) var tempPath = __dirname + '/../tmp' var filePath = tempPath + '/../tmp/test.txt' beforeEach(function() { rmrf.sync(tempPath) fs.mkdirSync(tempPath) }) it('always writes data from the latest call', function(done) { var writer = new Writer(filePath) // 1M characters var data = '' for (var i = 0; i <= 1000 * 1000; i++) { data += 'x' } for (var i = 0; i <= 1000 * 1000; i++) { writer.write(data + i) } setTimeout(function() { assert.equal(fs.readFileSync(filePath, 'utf-8'), data + (i - 1)) done() }, 1000) }) })
Update test (trying to fix Travis error)
Update test (trying to fix Travis error)
JavaScript
mit
typicode/lowdb,etiktin/lowdb,CreaturePhil/lowdb,beni55/lowdb,typicode/lowdb
--- +++ @@ -5,7 +5,7 @@ describe('Writer', function() { - this.timeout(5000) + this.timeout(10000) var tempPath = __dirname + '/../tmp' var filePath = tempPath + '/../tmp/test.txt'
4c2bfe4fa16e2fdca974fe3abe8890313bc00500
tests/index.js
tests/index.js
/* eslint-env mocha */ 'use strict'; import plugin from '../src'; import assert from 'assert'; import fs from 'fs'; import path from 'path'; const rules = fs.readdirSync(path.resolve(__dirname, '../src/rules/')) .map(f => path.basename(f, '.js')); describe('all rule files should be exported by the plugin', () => { rules.forEach(ruleName => { it(`should export ${ruleName}`, () => { assert.equal( plugin.rules[ruleName], require(path.join('../src/rules', ruleName)) ); }); }); }); describe('configurations', function() { it('should export a \'recommended\' configuration', function() { assert(plugin.configs.recommended); }); });
/* eslint-env mocha */ 'use strict'; import plugin from '../src'; import assert from 'assert'; import fs from 'fs'; import path from 'path'; const rules = fs.readdirSync(path.resolve(__dirname, '../src/rules/')) .map(f => path.basename(f, '.js')); describe('all rule files should be exported by the plugin', () => { rules.forEach(ruleName => { it(`should export ${ruleName}`, () => { assert.equal( plugin.rules[ruleName], require(path.join('../src/rules', ruleName)) ); }); }); }); describe('configurations', () => { it('should export a \'recommended\' configuration', () => { assert(plugin.configs.recommended); }); });
Fix test to pass lint.
Fix test to pass lint.
JavaScript
mit
jessebeach/eslint-plugin-jsx-a11y,evcohen/eslint-plugin-jsx-a11y
--- +++ @@ -21,8 +21,8 @@ }); }); -describe('configurations', function() { - it('should export a \'recommended\' configuration', function() { +describe('configurations', () => { + it('should export a \'recommended\' configuration', () => { assert(plugin.configs.recommended); }); });
cb2e70635a77d1b503d9c9f4c313c6e29eae4f0a
test/karma.conf.js
test/karma.conf.js
// karma.conf.js module.exports = function(config) { config.set({ basePath : '../', frameworks: ['jasmine'], files : [ 'public/bower_components/jquery/dist/jquery.js', 'public/bower_components/angular/angular.js', 'public/bower_components/angular-cookies/angular-cookies.js', 'public/bower_components/angular-route/angular-route.js', 'public/bower_components/angular-mocks/angular-mocks.js', 'public/bower_components/angular-socket.io-mock/angular-socket.io-mock.js', 'public/bower_components/toastr/toastr.min.js', 'public/js/**/*.js', 'test/unit/**/*.js' ], reporters: ['junit', 'coverage'], coverageReporter: { type: 'html', dir: 'build/coverage/' }, preprocessors: { 'public/js/**/*.js': ['coverage'] }, junitReporter: { outputFile: 'build/unit/test-results.xml' }, port: 8876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['PhantomJS'], captureTimeout: 60000, singleRun: true }); };
// karma.conf.js module.exports = function(config) { config.set({ basePath : '../', frameworks: ['jasmine'], files : [ 'public/bower_components/jquery/dist/jquery.js', 'public/bower_components/angular/angular.js', 'public/bower_components/angular-cookies/angular-cookies.js', 'public/bower_components/angular-route/angular-route.js', 'public/bower_components/angular-mocks/angular-mocks.js', 'public/bower_components/angular-socket.io-mock/angular-socket.io-mock.js', 'public/bower_components/toastr/toastr.min.js', 'public/js/**/*.js', 'test/unit/**/*.js' ], reporters: ['junit', 'coverage', 'dots'], coverageReporter: { type: 'html', dir: 'build/coverage/' }, preprocessors: { 'public/js/**/*.js': ['coverage'] }, junitReporter: { outputFile: 'build/unit/test-results.xml' }, port: 8876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['PhantomJS'], captureTimeout: 60000, singleRun: true }); };
Add dots reporting to karma
Add dots reporting to karma
JavaScript
mit
solarkennedy/uchiwa,pantheon-systems/uchiwa,pauloconnor/uchiwa,sensu/uchiwa,pantheon-systems/uchiwa,palourde/uchiwa,palourde/uchiwa,palourde/uchiwa,solarkennedy/uchiwa,Contegix/uchiwa,pgporada/uchiwa,palourde/uchiwa,upfluence/uchiwa,sensu/uchiwa,palourde/uchiwa,ransoni/uchiwa,jsoriano/uchiwa,pgporada/uchiwa,jsoriano/uchiwa,pauloconnor/uchiwa,upfluence/uchiwa,Contegix/uchiwa,pgporada/uchiwa,solarkennedy/uchiwa,jsoriano/uchiwa,upfluence/uchiwa,ransoni/uchiwa,sensu/uchiwa,ransoni/uchiwa,Contegix/uchiwa,pauloconnor/uchiwa,sensu/uchiwa,sensu/uchiwa
--- +++ @@ -14,7 +14,7 @@ 'public/js/**/*.js', 'test/unit/**/*.js' ], - reporters: ['junit', 'coverage'], + reporters: ['junit', 'coverage', 'dots'], coverageReporter: { type: 'html', dir: 'build/coverage/'
e3ec369f409c759573b64f44ce904acfcc8a87a6
test/pages-test.js
test/pages-test.js
const { expect } = require('chai'); const cheerio = require('cheerio'); const request = require('supertest'); const app = require('../app'); describe('Pages', function() { let req; describe('/', function() { beforeEach(function() { req = request(app).get('/') }); it('returns 200 OK', function(done) { req.expect(200, done); }); it('renders template', function (done) { req.expect('Content-Type', /text\/html/, done); }); it('has valid title', function (done) { req .expect((res) => { const content = res.text; const $ = cheerio.load(content); expect($('title').text()).to.eq('Slava Pavlutin'); }) .end(done); }); }); describe('/contact', function() { beforeEach(function() { req = request(app).get('/contact'); }); it('returns 200 OK', function (done) { req.expect(200, done); }); it('renders template', function (done) { req.expect('Content-Type', /text\/html/, done); }); it('has valid title', function (done) { req .expect((res) => { const content = res.text; const $ = cheerio.load(content); expect($('title').text()).to.eq('Slava Pavlutin | Contact'); }) .end(done); }); }); });
const { expect } = require('chai'); const cheerio = require('cheerio'); const request = require('supertest'); const app = require('../app'); describe('Pages', function() { let req; describe('/', function() { beforeEach(function() { req = request(app).get('/'); }); it('returns 200 OK', function(done) { req.expect(200, done); }); it('renders template', function (done) { req.expect('Content-Type', /text\/html/, done); }); it('has valid title', function (done) { req .expect((res) => { const content = res.text; const $ = cheerio.load(content); expect($('title').text()).to.eq('Slava Pavlutin'); }) .end(done); }); }); describe('/contact', function() { beforeEach(function() { req = request(app).get('/contact'); }); it('returns 200 OK', function (done) { req.expect(200, done); }); it('renders template', function (done) { req.expect('Content-Type', /text\/html/, done); }); it('has valid title', function (done) { req .expect((res) => { const content = res.text; const $ = cheerio.load(content); expect($('title').text()).to.eq('Slava Pavlutin | Contact'); }) .end(done); }); }); });
Add semicolon in test file
Add semicolon in test file
JavaScript
mit
slavapavlutin/pavlutin-node,slavapavlutin/pavlutin-node
--- +++ @@ -9,7 +9,7 @@ describe('/', function() { beforeEach(function() { - req = request(app).get('/') + req = request(app).get('/'); }); it('returns 200 OK', function(done) {
bd2ea150c6922e686b12c5f7a658b802bfafb3b7
src/routes.js
src/routes.js
import React from 'react'; import { Route, IndexRoute } from 'react-router'; /* containers */ import { App } from 'components/App'; import { Home } from 'components/Home'; import { DataDisplay } from 'components/DataDisplay'; // import { List } from 'containers/List'; export default ( <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="/chat" component={DataDisplay} /> <Route status={404} path="*" component={Home} /> </Route> );
import React from 'react'; import { Route, IndexRoute } from 'react-router'; /* containers */ import { App } from 'components/App'; import { Home } from 'components/Home'; import { About } from 'components/About'; import { DataDisplay } from 'components/DataDisplay'; // import { List } from 'containers/List'; export default ( <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="/chat" component={DataDisplay} /> <Route path="/about" component={About} /> <Route status={404} path="*" component={Home} /> </Route> );
Add route path for About page
Add route path for About page
JavaScript
mit
TerryCapan/twitchBot,badT/Chatson,badT/Chatson,TerryCapan/twitchBot,badT/twitchBot,dramich/twitchBot,dramich/Chatson,dramich/Chatson,badT/twitchBot,dramich/twitchBot
--- +++ @@ -4,6 +4,7 @@ /* containers */ import { App } from 'components/App'; import { Home } from 'components/Home'; +import { About } from 'components/About'; import { DataDisplay } from 'components/DataDisplay'; // import { List } from 'containers/List'; @@ -11,6 +12,7 @@ <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="/chat" component={DataDisplay} /> + <Route path="/about" component={About} /> <Route status={404} path="*" component={Home} /> </Route> );
85e242dd7e5293a92f124fb1976dfd51fbda6f6e
src/server.js
src/server.js
import bodyParser from "body-parser" import cors from "cors" import express from "express" import graphqlHTTP from "express-graphql" import { graphqlExpress, graphiqlExpress } from "graphql-server-express" import models from "./db" import schema from "./graphql" // Constants const CONFIG = require("./settings.yaml") const app = express() app.use(cors()) app.use( "/graphql", bodyParser.json({ limit: CONFIG.max_api_call_size }), graphqlExpress(req => { return { schema, context: { loaders: {}, models } } }) ) app.use( "/graphiql", graphiqlExpress({ endpointURL: "/graphql" }) ) export { app, CONFIG }
import bodyParser from "body-parser" import cors from "cors" import express from "express" import graphqlHTTP from "express-graphql" import { graphqlExpress, graphiqlExpress } from "graphql-server-express" import models, { sequelize } from "./db" import schema from "./graphql" // Constants const CONFIG = require("./settings.yaml") const app = express() app.use(cors()) app.use( "/graphql", bodyParser.json({ limit: CONFIG.max_api_call_size }), graphqlExpress(req => { return { schema, context: { loaders: {}, models, sequelize } } }) ) app.use( "/graphiql", graphiqlExpress({ endpointURL: "/graphql" }) ) export { app, CONFIG }
Add sequelize to context of GraphQL queries
Add sequelize to context of GraphQL queries
JavaScript
mit
DevNebulae/ads-pt-api
--- +++ @@ -3,7 +3,7 @@ import express from "express" import graphqlHTTP from "express-graphql" import { graphqlExpress, graphiqlExpress } from "graphql-server-express" -import models from "./db" +import models, { sequelize } from "./db" import schema from "./graphql" // Constants @@ -21,7 +21,8 @@ schema, context: { loaders: {}, - models + models, + sequelize } } })
01db3107f6f7d6b4edddd1375b8096810099adff
test/index.js
test/index.js
import test from 'ava'; import plugin from '../postcss-rem-phi-units' import postcss from 'postcss'; import { readFileSync } from 'fs'; test('Settingless units', async t => { postcss(plugin) .process(readFileSync('in.css')) .then(result => t.same(result.css, readFileSync('expected.css', 'utf8')) ); });
import test from 'ava'; import plugin from '../postcss-rem-phi-units'; import postcss from 'postcss'; import { readFileSync } from 'fs'; test('Settingless units', async t => { postcss(plugin) .process(readFileSync('in.css')) .then(result => t.same(result.css, readFileSync('expected.css', 'utf8')); ); });
Convert test js to happiness
Convert test js to happiness It’d be a PITA to lint these differently so we should either convert this back to ES5 or convert postcss-rem-phi-units.js to ES2015.
JavaScript
mit
posthumans/postcss-rem-phi-units
--- +++ @@ -1,5 +1,5 @@ import test from 'ava'; -import plugin from '../postcss-rem-phi-units' +import plugin from '../postcss-rem-phi-units'; import postcss from 'postcss'; import { readFileSync } from 'fs'; @@ -7,6 +7,6 @@ postcss(plugin) .process(readFileSync('in.css')) .then(result => - t.same(result.css, readFileSync('expected.css', 'utf8')) + t.same(result.css, readFileSync('expected.css', 'utf8')); ); });
52f11529a145f849f3db58a85c35c124c53ac4a5
package.js
package.js
Package.describe({ summary: 'Web tracing framework wrapper for Meteor', version: "0.0.2", git: 'git@github.com:eluck/meteor-web-tracing-framework.git' }); Npm.depends({ "tracing-framework": "2014.8.18-1" }); Package.on_use(function (api) { api.add_files('import.js', ['server']); api.add_files('web-tracing-framework-shim.js', ['client', 'server']); api.add_files('export.js', ['client', 'server']); api.export('WTF', ['client', 'server']); });
Package.describe({ summary: 'Web tracing framework wrapper for Meteor', version: "0.0.2", git: 'https://github.com/eluck/meteor-web-tracing-framework.git' }); Npm.depends({ "tracing-framework": "2014.8.18-1" }); Package.on_use(function (api) { api.add_files('import.js', ['server']); api.add_files('web-tracing-framework-shim.js', ['client', 'server']); api.add_files('export.js', ['client', 'server']); api.export('WTF', ['client', 'server']); });
Update path to the repository
Update path to the repository
JavaScript
mit
eluck/meteor-web-tracing-framework
--- +++ @@ -1,7 +1,7 @@ Package.describe({ summary: 'Web tracing framework wrapper for Meteor', version: "0.0.2", - git: 'git@github.com:eluck/meteor-web-tracing-framework.git' + git: 'https://github.com/eluck/meteor-web-tracing-framework.git' }); Npm.depends({
3235e1e88f357be9172b45edf32a276065b7c291
src/server/config.js
src/server/config.js
var nconf = require('nconf'); // Specifying an env delimiter allows you to override below config when shipping to production server // by e.g. defining piping__ignore or version variables. nconf.env('__'); var config = { appLocales: ['en', 'fr'], defaultLocale: 'en', googleAnalyticsId: 'UA-XXXXXXX-X', isProduction: process.env.NODE_ENV === 'production', piping: { // Ignore webpack custom loaders on server. TODO: Reuse index.js config. ignore: /(\/\.|~$|\.(css|less|sass|scss|styl))/, // Hook ensures server restart on all required deps, even client side. // Server restarting invalidates require cache, no more stale html. hook: true }, port: process.env.PORT || 8000, version: require('../../package').version, webpackStylesExtensions: ['css', 'less', 'sass', 'scss', 'styl'] }; // Use above config as a default one // Multiple other providers are available like loading config from json and more // Check out nconf docs for fancier examples nconf.defaults(config); module.exports = nconf.get();
var nconf = require('nconf'); // Specifying an env delimiter allows you to override below config when shipping to production server // by e.g. defining piping__ignore or version variables. nconf.env('__'); var config = { appLocales: ['en', 'fr'], defaultLocale: 'en', googleAnalyticsId: 'UA-XXXXXXX-X', isProduction: process.env.NODE_ENV === 'production', piping: { // Ignore webpack custom loaders on server. TODO: Reuse index.js config. ignore: /(\/\.|~$|\.(css|less|sass|scss|styl))/, // Hook ensures always fresh server response even for client file change. hook: true }, port: process.env.PORT || 8000, version: require('../../package').version, webpackStylesExtensions: ['css', 'less', 'sass', 'scss', 'styl'] }; // Use above config as a default one // Multiple other providers are available like loading config from json and more // Check out nconf docs for fancier examples nconf.defaults(config); module.exports = nconf.get();
Update comment about piping hook.
Update comment about piping hook.
JavaScript
mit
puzzfuzz/othello-redux,XeeD/test,laxplaer/este,este/este,puzzfuzz/othello-redux,skyuplam/debt_mgmt,gaurav-/este,TheoMer/Gyms-Of-The-World,grabbou/este,neozhangthe1/framedrop-web,amrsekilly/updatedEste,steida/este,ViliamKopecky/este,XeeD/este,TheoMer/este,este/este,sikhote/davidsinclair,obimod/este,AugustinLF/este,cazacugmihai/este,christophediprima/este,TheoMer/Gyms-Of-The-World,sljuka/portfulio,TheoMer/este,sljuka/portfolio-este,XeeD/este,amrsekilly/updatedEste,robinpokorny/este,estaub/my-este,sikhote/davidsinclair,este/este,langpavel/este,abelaska/este,jaeh/este,syroegkin/mikora.eu,syroegkin/mikora.eu,steida/este,glaserp/Maturita-Project,vacuumlabs/este,neozhangthe1/framedrop-web,glaserp/Maturita-Project,zanj2006/este,blueberryapps/este,AlesJiranek/este,langpavel/este,robinpokorny/este,skallet/este,christophediprima/este,zanj2006/este,TheoMer/Gyms-Of-The-World,Tzitzian/Oppex,SidhNor/este-cordova-starter-kit,amrsekilly/updatedEste,cjk/smart-home-app,christophediprima/este,sljuka/portfolio-este,hsrob/league-este,sikhote/davidsinclair,abelaska/este,TheoMer/este,AugustinLF/este,skallet/este,sljuka/portfulio,neozhangthe1/framedrop-web,christophediprima/este,GarrettSmith/schizophrenia,neozhangthe1/framedrop-web,MartinPavlik/este,skaldo/este,GarrettSmith/schizophrenia,Brainfock/este,este/este,blueberryapps/este,sljuka/bucka-portfolio,shawn-dsz/este,syroegkin/mikora.eu,aindre/este-example,vacuumlabs/este,GarrettSmith/schizophrenia,robinpokorny/este,srhmgn/markdowner,youprofit/este,neozhangthe1/framedrop-web,estaub/my-este,abelaska/este,aindre/este-example,skyuplam/debt_mgmt,estaub/my-este,XeeD/test,AlesJiranek/este,skallet/este,nezaidu/este,nason/este
--- +++ @@ -12,8 +12,7 @@ piping: { // Ignore webpack custom loaders on server. TODO: Reuse index.js config. ignore: /(\/\.|~$|\.(css|less|sass|scss|styl))/, - // Hook ensures server restart on all required deps, even client side. - // Server restarting invalidates require cache, no more stale html. + // Hook ensures always fresh server response even for client file change. hook: true }, port: process.env.PORT || 8000,
50036eab17d4ead74316e2023bed1a4a55b256a7
modules/phenyl-api-explorer-client/src/components/OperationResult/Response.js
modules/phenyl-api-explorer-client/src/components/OperationResult/Response.js
import React from 'react' import { Segment, Message } from 'semantic-ui-react' import JSONTree from 'react-json-tree' type Props = { loading: boolean, expanded: boolean, response: any, error: ?Error, } const Response = ({ loading, expanded, response, error }: Props) => { if (loading) { return ( <Segment loading className='result' /> ) } else if (error != null) { return ( <Segment className='result'> <Message negative> <Message.Header>{error.message}</Message.Header> <pre>{error.stack}</pre> </Message> </Segment> ) } else if (response != null) { return ( <Segment className='result'> <JSONTree hideRoot shouldExpandNode={() => expanded} data={response} /> </Segment> ) } return null } export default Response
import React from 'react' import { Segment, Tab, Message } from 'semantic-ui-react' import JSONTree from 'react-json-tree' type Props = { loading: boolean, expanded: boolean, response: any, error: ?Error, } const Response = ({ loading, expanded, response, error }: Props) => { if (loading) { return ( <Segment loading className='result' /> ) } else if (error != null) { return ( <Segment className='result'> <Message negative> <Message.Header>{error.message}</Message.Header> <pre>{error.stack}</pre> </Message> </Segment> ) } else if (response != null) { return ( <Tab className='result' panes={[ { menuItem: 'Tree view', // eslint-disable-next-line react/display-name render: () => ( <Tab.Pane> <JSONTree hideRoot shouldExpandNode={() => expanded} data={response} /> </Tab.Pane> ) }, { menuItem: 'Raw JSON', // eslint-disable-next-line react/display-name render: () => ( <Tab.Pane> <pre>{JSON.stringify(response, null, 2)}</pre> </Tab.Pane> ) }, ]} /> ) } return null } export default Response
Add `Raw JSON` pane to response
Add `Raw JSON` pane to response
JavaScript
apache-2.0
phenyl-js/phenyl,phenyl-js/phenyl,phenyl-js/phenyl,phenyl-js/phenyl
--- +++ @@ -1,5 +1,5 @@ import React from 'react' -import { Segment, Message } from 'semantic-ui-react' +import { Segment, Tab, Message } from 'semantic-ui-react' import JSONTree from 'react-json-tree' type Props = { @@ -25,13 +25,33 @@ ) } else if (response != null) { return ( - <Segment className='result'> - <JSONTree - hideRoot - shouldExpandNode={() => expanded} - data={response} - /> - </Segment> + <Tab + className='result' + panes={[ + { + menuItem: 'Tree view', + // eslint-disable-next-line react/display-name + render: () => ( + <Tab.Pane> + <JSONTree + hideRoot + shouldExpandNode={() => expanded} + data={response} + /> + </Tab.Pane> + ) + }, + { + menuItem: 'Raw JSON', + // eslint-disable-next-line react/display-name + render: () => ( + <Tab.Pane> + <pre>{JSON.stringify(response, null, 2)}</pre> + </Tab.Pane> + ) + }, + ]} + /> ) }
77f0b638cbb12224871700129b6885abea6ff2e4
packages/react-hot-boilerplate/webpack.config.js
packages/react-hot-boilerplate/webpack.config.js
var webpack = require('webpack'); module.exports = { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './scripts/index' ], output: { path: __dirname + '/scripts/', filename: 'bundle.js', publicPath: '/scripts/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], resolve: { extensions: ['', '.js'] }, module: { loaders: [ { test: /\.js$/, loaders: ['react-hot', 'jsx?harmony'], exclude: /node_modules/ }, ] } };
var webpack = require('webpack'); module.exports = { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './scripts/index' ], output: { path: __dirname + '/scripts/', filename: 'bundle.js', publicPath: '/scripts/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], resolve: { extensions: ['', '.js', '.jsx'] }, module: { loaders: [ { test: /\.jsx?$/, loaders: ['react-hot', 'jsx?harmony'], exclude: /node_modules/ } ] } };
Allow jsx extension as some people prefer it
Allow jsx extension as some people prefer it
JavaScript
mit
gaearon/react-hot-loader,gaearon/react-hot-loader
--- +++ @@ -17,11 +17,11 @@ new webpack.NoErrorsPlugin() ], resolve: { - extensions: ['', '.js'] + extensions: ['', '.js', '.jsx'] }, module: { loaders: [ - { test: /\.js$/, loaders: ['react-hot', 'jsx?harmony'], exclude: /node_modules/ }, + { test: /\.jsx?$/, loaders: ['react-hot', 'jsx?harmony'], exclude: /node_modules/ } ] } };
3f31666935ca6a7c3bf48aabd393112542ebbba7
app/client/templates/modals/project/activity_discuss/activity_discuss.js
app/client/templates/modals/project/activity_discuss/activity_discuss.js
/*****************************************************************************/ /* ActivityDiscuss: Event Handlers */ /*****************************************************************************/ Template.ActivityDiscuss.events({ }); /*****************************************************************************/ /* ActivityDiscuss: Helpers */ /*****************************************************************************/ Template.ActivityDiscuss.helpers({ thisRoomId: function() { return this.project + '-' + thisActivity.id; }, thisUsername: function() { return Meteor.user().username; }, thisName: function() { var name = Meteor.user().profile.firstName + ' ' + Meteor.user().profile.lastName; return name; }, thisGravatar: function() { var url = Gravatar.imageUrl(Meteor.user().emails[0].address, { size: 34, default: 'mm' }); return url; } }); /*****************************************************************************/ /* ActivityDiscuss: Lifecycle Hooks */ /*****************************************************************************/ Template.ActivityDiscuss.onCreated(function () { }); Template.ActivityDiscuss.onRendered(function () { }); Template.ActivityDiscuss.onDestroyed(function () { });
/*****************************************************************************/ /* ActivityDiscuss: Event Handlers */ /*****************************************************************************/ Template.ActivityDiscuss.events({ }); /*****************************************************************************/ /* ActivityDiscuss: Helpers */ /*****************************************************************************/ Template.ActivityDiscuss.helpers({ thisRoomId: function() { return thisProject._id + '-' + thisActivity.id; }, thisUsername: function() { return Meteor.user().username; }, thisName: function() { var name = Meteor.user().profile.firstName + ' ' + Meteor.user().profile.lastName; return name; }, thisGravatar: function() { var url = Gravatar.imageUrl(Meteor.user().emails[0].address, { size: 34, default: 'mm' }); return url; } }); /*****************************************************************************/ /* ActivityDiscuss: Lifecycle Hooks */ /*****************************************************************************/ Template.ActivityDiscuss.onCreated(function () { }); Template.ActivityDiscuss.onRendered(function () { }); Template.ActivityDiscuss.onDestroyed(function () { });
Fix missing id of project in discussion of activities
Fix missing id of project in discussion of activities
JavaScript
agpl-3.0
openp2pdesign/OpenMetaDesign,openp2pdesign/OpenMetaDesign,openp2pdesign/OpenMetaDesign
--- +++ @@ -9,7 +9,7 @@ /*****************************************************************************/ Template.ActivityDiscuss.helpers({ thisRoomId: function() { - return this.project + '-' + thisActivity.id; + return thisProject._id + '-' + thisActivity.id; }, thisUsername: function() { return Meteor.user().username;
0d9dd06d48773c1caeb130265f0f5d0e2d9b4f8f
lib/board.js
lib/board.js
const Block = require('./block'); const typeToConfig = require('./type-to-config'); class Board { constructor() { this.height = 3; this.width = 3; this.blocks = [ [null, null, null], [null, null, null], [null, null, null], ]; } getBlock(x, y) { return this.blocks[y][x]; } placeBlock(x, y, type) { const config = typeToConfig[type]; config.x = x; config.y = y; const block = new Block(config); this.blocks[y][x] = block; } } module.exports = Board;
const Block = require('./block'); const typeToConfig = require('./type-to-config'); class Board { constructor() { this.height = 3; this.width = 3; this.blocks = [ [null, null, null], [null, null, null], [null, null, null], ]; this.inputBlockX = 1; this.inputBlockY = 0; this.outputBlockX = 1; this.outputBlockY = 2; } get inputBlock() { return this.blocks[this.inputBlockY][this.inputBlockX]; } get outputBlock() { return this.blocks[this.outputBlockY][this.outputBlockX]; } getBlock(x, y) { return this.blocks[y][x]; } placeBlock(x, y, type) { const config = typeToConfig[type]; config.x = x; config.y = y; const block = new Block(config); this.blocks[y][x] = block; } } module.exports = Board;
Define input and output block information
Define input and output block information
JavaScript
mit
tsg-ut/mnemo,tsg-ut/mnemo
--- +++ @@ -10,6 +10,18 @@ [null, null, null], [null, null, null], ]; + this.inputBlockX = 1; + this.inputBlockY = 0; + this.outputBlockX = 1; + this.outputBlockY = 2; + } + + get inputBlock() { + return this.blocks[this.inputBlockY][this.inputBlockX]; + } + + get outputBlock() { + return this.blocks[this.outputBlockY][this.outputBlockX]; } getBlock(x, y) {
182621443c609d145f8185e97611bf53d6337607
Brocfile.js
Brocfile.js
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); var app = new EmberApp({ 'ember-cli-jquery-ui': { 'theme': 'redmond' }, vendorFiles: { 'handlebars.js': { production: 'bower_components/handlebars/handlebars.js' } } }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. app.import('vendor/js/jquery-knob/jquery.knob.js'); module.exports = app.toTree();
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); var app = new EmberApp({ 'ember-cli-jquery-ui': { 'theme': 'redmond' }, 'ember-cli-bootstrap-sass': { 'importBootstrapJS': true }, vendorFiles: { 'handlebars.js': { production: 'bower_components/handlebars/handlebars.js' } } }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. app.import('vendor/js/jquery-knob/jquery.knob.js'); module.exports = app.toTree();
Add Bootstrap JavaScript to build
Add Bootstrap JavaScript to build
JavaScript
mit
liveband/liveband
--- +++ @@ -5,6 +5,9 @@ var app = new EmberApp({ 'ember-cli-jquery-ui': { 'theme': 'redmond' + }, + 'ember-cli-bootstrap-sass': { + 'importBootstrapJS': true }, vendorFiles: { 'handlebars.js': {
e29fc0a4f15bd33237ecf8465a4eacebb1461b6f
server/game/cards/06-CotE/MagnificentTriumph.js
server/game/cards/06-CotE/MagnificentTriumph.js
const DrawCard = require('../../drawcard.js'); const EventRegistrar = require('../../eventregistrar.js'); const { CardTypes, Players } = require('../../Constants'); class MagnificentTriumph extends DrawCard { setupCardAbilities(ability) { this.duelWinnersThisConflict = []; this.eventRegistrar = new EventRegistrar(this.game, this); this.eventRegistrar.register(['onConflictFinished', 'afterDuel']); this.action({ title: 'Give a character +2/+2', condition: () => this.game.isDuringConflict(), target: { cardType: CardTypes.Character, controller: Players.Any, cardCondition: card => this.duelWinnersThisConflict.includes(card), gameAction: ability.actions.cardLastingEffect({ effect: [ ability.effects.modifyBothSkills(2), ability.effects.cardCannot({ cannot: 'target', restricts: 'opponentsCardEffects' }) ] }) }, effect: 'give {0} +2{1}, +2{2}, and prevent them from being targeted by opponent\'s abilities', effectArgs: () => ['military', 'political'] }); } onConflictFinished() { this.duelWinnersThisConflict = []; } afterDuel(event) { if(event.duel.winner) { this.duelWinnersThisConflict.push(event.duel.winner); } } } MagnificentTriumph.id = 'magnificent-triumph'; module.exports = MagnificentTriumph;
const DrawCard = require('../../drawcard.js'); const EventRegistrar = require('../../eventregistrar.js'); const { CardTypes, Players } = require('../../Constants'); class MagnificentTriumph extends DrawCard { setupCardAbilities(ability) { this.duelWinnersThisConflict = []; this.eventRegistrar = new EventRegistrar(this.game, this); this.eventRegistrar.register(['onConflictFinished', 'afterDuel']); this.action({ title: 'Give a character +2/+2', condition: () => this.game.isDuringConflict(), target: { cardType: CardTypes.Character, controller: Players.Any, cardCondition: card => this.duelWinnersThisConflict.includes(card), gameAction: ability.actions.cardLastingEffect({ effect: [ ability.effects.modifyBothSkills(2), ability.effects.cardCannot({ cannot: 'target', restricts: 'opponentsEvents' }) ] }) }, effect: 'give {0} +2{1}, +2{2}, and prevent them from being targeted by opponent\'s events', effectArgs: () => ['military', 'political'] }); } onConflictFinished() { this.duelWinnersThisConflict = []; } afterDuel(event) { if(event.duel.winner) { this.duelWinnersThisConflict.push(event.duel.winner); } } } MagnificentTriumph.id = 'magnificent-triumph'; module.exports = MagnificentTriumph;
Fix to target events (not all card effects)
Fix to target events (not all card effects)
JavaScript
mit
gryffon/ringteki,gryffon/ringteki,jeremylarner/ringteki,jeremylarner/ringteki,gryffon/ringteki,jeremylarner/ringteki
--- +++ @@ -19,12 +19,12 @@ ability.effects.modifyBothSkills(2), ability.effects.cardCannot({ cannot: 'target', - restricts: 'opponentsCardEffects' + restricts: 'opponentsEvents' }) ] }) }, - effect: 'give {0} +2{1}, +2{2}, and prevent them from being targeted by opponent\'s abilities', + effect: 'give {0} +2{1}, +2{2}, and prevent them from being targeted by opponent\'s events', effectArgs: () => ['military', 'political'] }); }
d56023c3b7beb44184aaee799cd5448e76acef1d
lib/hooks/responder/rpc/rpc_serialize.js
lib/hooks/responder/rpc/rpc_serialize.js
// RPC reply serializer, that should heppen in the end, // because we pass errors in serialized form too // 'use strict'; //////////////////////////////////////////////////////////////////////////////// module.exports = function (N) { N.wire.after('responder:rpc', { priority: 90 }, function rpc_serialize(env) { // // Set Content-Type and charset (override existing) // env.headers['Content-Type'] = 'application/json; charset=UTF-8'; // // Status is always ok - errors are embedded into payload // env.status = N.io.OK; // // HEAD requested - no need for real rendering // if ('HEAD' === env.origin.req.method) { env.body = null; return; } // // Replace body with serialized payload // env.body = JSON.stringify({ version: N.runtime.version, error: env.err, response: env.err ? null : env.response }); }); };
// RPC reply serializer, that should heppen in the end, // because we pass errors in serialized form too // 'use strict'; //////////////////////////////////////////////////////////////////////////////// module.exports = function (N) { N.wire.after('responder:rpc', { priority: 90 }, function rpc_serialize(env) { // Set Content-Type and charset (override existing) env.headers['Content-Type'] = 'application/json; charset=UTF-8'; // Status is always ok - errors are embedded into payload env.status = N.io.OK; // Expose API path of the executed server method, e.g. 'forum.index' env.response.data.head.apiPath = env.method; // HEAD requested - no need for real rendering if ('HEAD' === env.origin.req.method) { env.body = null; return; } // Replace body with serialized payload env.body = JSON.stringify({ version: N.runtime.version, error: env.err, response: env.err ? null : env.response }); }); };
Fix pagination links on the RPC page navigation.
Fix pagination links on the RPC page navigation.
JavaScript
mit
nodeca/nodeca.core,nodeca/nodeca.core
--- +++ @@ -13,31 +13,22 @@ N.wire.after('responder:rpc', { priority: 90 }, function rpc_serialize(env) { - // // Set Content-Type and charset (override existing) - // - env.headers['Content-Type'] = 'application/json; charset=UTF-8'; - // // Status is always ok - errors are embedded into payload - // - env.status = N.io.OK; - // + // Expose API path of the executed server method, e.g. 'forum.index' + env.response.data.head.apiPath = env.method; + // HEAD requested - no need for real rendering - // - if ('HEAD' === env.origin.req.method) { env.body = null; return; } - // // Replace body with serialized payload - // - env.body = JSON.stringify({ version: N.runtime.version, error: env.err,
80736399737e0c3e5d7b203d2d3234cb32805aae
client/src/bg/background.js
client/src/bg/background.js
// if you checked "fancy-settings" in extensionizr.com, uncomment this lines // var settings = new Store("settings", { // "sample_setting": "This is how you use Store.js to remember values" // }); function generateUUID() { let id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { let r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8); return v.toString(16); }); return id; } const defaults = { id: generateUUID(), username: "test-user", }; class StorageService { constructor() { this.storage = chrome.storage.local; this.storage.get(defaults, (items) => { this.storage.set(items); }) } reset() { this.storage.clear(() => { defaults.id = generateUUID(); this.set(defaults); }); } get(key) { return new Promise((resolve) => { this.storage.get(key, (item) => { resolve(item[key]); }); }); } set(key, value) { let data = {}; data[key] = value; this.storage.set(data); } remove(key) { this.storage.remove(key); } } window.BackgroundStorageService = new StorageService();
// if you checked "fancy-settings" in extensionizr.com, uncomment this lines // var settings = new Store("settings", { // "sample_setting": "This is how you use Store.js to remember values" // }); function generateUUID() { let id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { let r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8); return v.toString(16); }); return id; } const defaults = { id: generateUUID(), username: "test-user", }; class StorageService { constructor() { this.storage = chrome.storage.sync; this.storage.get(defaults, (items) => { this.storage.set(items); }) } reset() { this.storage.clear(() => { defaults.id = generateUUID(); this.set(defaults); }); } get(key) { return new Promise((resolve) => { this.storage.get(key, (item) => { resolve(item[key]); }); }); } set(key, value) { let data = {}; data[key] = value; this.storage.set(data); } remove(key) { this.storage.remove(key); } } window.BackgroundStorageService = new StorageService();
Use sync storage instead of local storage
Use sync storage instead of local storage
JavaScript
mit
zhoutwo/url_connect,zhoutwo/url_connect,zhoutwo/url_connect
--- +++ @@ -19,7 +19,7 @@ class StorageService { constructor() { - this.storage = chrome.storage.local; + this.storage = chrome.storage.sync; this.storage.get(defaults, (items) => { this.storage.set(items); })
63d2478dd04fb1287232a59225cb11fe567e3dcd
test_apps/test_app/test/simple_storage_deploy_spec.js
test_apps/test_app/test/simple_storage_deploy_spec.js
/*global contract, it, embark, assert, before*/ const SimpleStorage = embark.require('Embark/contracts/SimpleStorage'); contract("SimpleStorage Deploy", function () { let SimpleStorageInstance; before(async function() { SimpleStorageInstance = await SimpleStorage.deploy({arguments: [150]}).send(); }); it("should set constructor value", async function () { let result = await SimpleStorageInstance.methods.storedData().call(); assert.strictEqual(parseInt(result, 10), 150); }); it("set storage value", async function () { await SimpleStorageInstance.methods.set(150).send(); let result = await SimpleStorageInstance.methods.get().call(); assert.strictEqual(parseInt(result, 10), 150); }); });
/*global contract, it, embark, assert, before, web3*/ const SimpleStorage = embark.require('Embark/contracts/SimpleStorage'); const Utils = require('embarkjs').Utils; contract("SimpleStorage Deploy", function () { let simpleStorageInstance; before(function(done) { Utils.secureSend(web3, SimpleStorage.deploy({arguments: [150]}), {}, true, function(err, receipt) { if(err) { return done(err); } simpleStorageInstance = SimpleStorage; simpleStorageInstance.options.address = receipt.contractAddress; done(); }); }); it("should set constructor value", async function () { let result = await simpleStorageInstance.methods.storedData().call(); assert.strictEqual(parseInt(result, 10), 150); }); it("set storage value", function (done) { Utils.secureSend(web3, simpleStorageInstance.methods.set(200), {}, false, async function(err) { if (err) { return done(err); } let result = await simpleStorageInstance.methods.get().call(); assert.strictEqual(parseInt(result, 10), 200); done(); }); }); });
Fix embark test using node option
Fix embark test using node option
JavaScript
mit
iurimatias/embark-framework,iurimatias/embark-framework
--- +++ @@ -1,22 +1,34 @@ -/*global contract, it, embark, assert, before*/ +/*global contract, it, embark, assert, before, web3*/ const SimpleStorage = embark.require('Embark/contracts/SimpleStorage'); +const Utils = require('embarkjs').Utils; contract("SimpleStorage Deploy", function () { - let SimpleStorageInstance; - - before(async function() { - SimpleStorageInstance = await SimpleStorage.deploy({arguments: [150]}).send(); + let simpleStorageInstance; + before(function(done) { + Utils.secureSend(web3, SimpleStorage.deploy({arguments: [150]}), {}, true, function(err, receipt) { + if(err) { + return done(err); + } + simpleStorageInstance = SimpleStorage; + simpleStorageInstance.options.address = receipt.contractAddress; + done(); + }); }); it("should set constructor value", async function () { - let result = await SimpleStorageInstance.methods.storedData().call(); + let result = await simpleStorageInstance.methods.storedData().call(); assert.strictEqual(parseInt(result, 10), 150); }); - it("set storage value", async function () { - await SimpleStorageInstance.methods.set(150).send(); - let result = await SimpleStorageInstance.methods.get().call(); - assert.strictEqual(parseInt(result, 10), 150); + it("set storage value", function (done) { + Utils.secureSend(web3, simpleStorageInstance.methods.set(200), {}, false, async function(err) { + if (err) { + return done(err); + } + let result = await simpleStorageInstance.methods.get().call(); + assert.strictEqual(parseInt(result, 10), 200); + done(); + }); }); });
09fe7ea33c4037b47d3128a95ae76ebddf836fc7
tests/main.js
tests/main.js
var allTestFiles = []; var TEST_REGEXP = /(spec|test)\.js$/i; var pathToModule = function(path) { return path.replace(/^\/base\//, '').replace(/\.js$/, ''); }; Object.keys(window.__karma__.files).forEach(function(file) { if (TEST_REGEXP.test(file)) { allTestFiles.push(pathToModule(file)); } }); require.config({ baseUrl: "/base", paths: { // Libraries "jquery": "libraries/jquery/jquery", // /Libraries // Application "app": "app/scripts/app", // /Application // Fixtures "app-fixture": "tests/fixtures/app-fixture" // /Fixtures }, shim: { }, deps: allTestFiles, callback: window.__karma__.start });
var allTestFiles = []; var TEST_REGEXP = /(spec|test)\.js$/i; var pathToModule = function(path) { return path.replace(/^\/base\//, '').replace(/\.js$/, ''); }; Object.keys(window.__karma__.files).forEach(function(file) { if (TEST_REGEXP.test(file)) { allTestFiles.push(pathToModule(file)); } }); require.config({ baseUrl: "/base", paths: { // Libraries "jquery": "libraries/jquery/jquery", // /Libraries // Application "app": "app/scripts/app", "components/example": "app/scripts/components/example", // /Application // Fixtures "app-fixture": "tests/fixtures/app-fixture" // /Fixtures }, shim: { }, deps: allTestFiles, callback: window.__karma__.start });
Define component path in the test RequireJS config.
Define component path in the test RequireJS config.
JavaScript
mit
rishabhsrao/voxel-hologram,rishabhsrao/voxel-hologram,rishabhsrao/voxel-hologram
--- +++ @@ -21,6 +21,7 @@ // Application "app": "app/scripts/app", + "components/example": "app/scripts/components/example", // /Application // Fixtures
56979c9b70008adb38cd04294924e7611b838098
mehuge-chat/chat-config.js
mehuge-chat/chat-config.js
ChatConfig = { join: ["uidev"], leave: [], hideDeathSpam: false, autoexec: [ "/closeui perfhud", "jumpdelay 0", "/sleep 1000", "/openui mehuge-lb", "/openui mehuge-heatmap", "/openui mehuge-perf", "/openui mehuge-pop", "/openui mehuge-bct", "/openui mehuge-announcer", "/openui mehuge-deathspam", "/openui mehuge-loc", "/openui mehuge-group", "/openui mehuge-combatlog", "/openui castbar", "/openui ortu-compass" ] };
ChatConfig = { join: ["uidev"], leave: [], hideDeathSpam: false, autoexec: [ "/closeui perfhud", "jumpdelay 0", "/sleep 1000", "/openui mehuge-lb", "/openui mehuge-heatmap", "/openui mehuge-perf", "/openui mehuge-pop", "/openui mehuge-bct", "/openui mehuge-announcer", "/openui mehuge-deathspam", "/openui mehuge-loc", "/openui mehuge-group", "/openui mehuge-combatlog", "/openui castbar", "/openui ortu-compass", "/join _modsquad", ] };
Join _modsquad channel (my personal config)
Join _modsquad channel (my personal config)
JavaScript
mpl-2.0
Mehuge/cu-ui-legacy,Mehuge/cu-ui-legacy,Mehuge/cu-ui-legacy,Mehuge/cu-ui-legacy,Mehuge/cu-ui-legacy
--- +++ @@ -17,6 +17,7 @@ "/openui mehuge-group", "/openui mehuge-combatlog", "/openui castbar", - "/openui ortu-compass" + "/openui ortu-compass", + "/join _modsquad", ] };
20e426730539d3df99e3999926ce670b2fd3cee0
js/models/levels/level_1.js
js/models/levels/level_1.js
var LevelOne = function(){ this.bricks = [new Brick(), new Brick(140), new Brick(230), new Brick(320), new Brick(410), new Brick(500), new Brick(590), new Brick(680), new Brick(50, 80),new Brick(140, 80), new Brick(230, 80), new Brick(320, 80), new Brick(410, 80), new Brick(500, 80), new Brick(590, 80), new Brick(680, 80)] }
var LevelOne = function(){ this.bricks = [ new Brick(), new Brick(140), new Brick(230), new Brick(320), new Brick(410), new Brick(500), new Brick(590), new Brick(680), new Brick(50, 80), new Brick(140, 80), new Brick(230, 80), new Brick(320, 80), new Brick(410, 80), new Brick(500, 80), new Brick(590, 80), new Brick(680, 80) ] }
Tidy up ogranisation of Brick objects in a level
Tidy up ogranisation of Brick objects in a level
JavaScript
mit
theomarkkuspaul/Brick-Breaker,theomarkkuspaul/Brick-Breaker
--- +++ @@ -1,3 +1,20 @@ var LevelOne = function(){ - this.bricks = [new Brick(), new Brick(140), new Brick(230), new Brick(320), new Brick(410), new Brick(500), new Brick(590), new Brick(680), new Brick(50, 80),new Brick(140, 80), new Brick(230, 80), new Brick(320, 80), new Brick(410, 80), new Brick(500, 80), new Brick(590, 80), new Brick(680, 80)] + this.bricks = [ + new Brick(), + new Brick(140), + new Brick(230), + new Brick(320), + new Brick(410), + new Brick(500), + new Brick(590), + new Brick(680), + new Brick(50, 80), + new Brick(140, 80), + new Brick(230, 80), + new Brick(320, 80), + new Brick(410, 80), + new Brick(500, 80), + new Brick(590, 80), + new Brick(680, 80) + ] }
bc2108c68406a22f2b339942336a292c85935a21
build/postcss.config.js
build/postcss.config.js
'use strict' module.exports = (ctx) => ({ map: ctx.file.dirname.includes('examples') ? false : { inline: false, annotation: true, sourcesContent: true }, plugins: { autoprefixer: {} } })
'use strict' module.exports = (ctx) => ({ map: ctx.file.dirname.includes('examples') ? false : { inline: false, annotation: true, sourcesContent: true }, plugins: { autoprefixer: { cascade: false } } })
Set autoprefixer's cascade option to false.
Set autoprefixer's cascade option to false. BS4 commits: c70eaa156f5fc0b7f7019593390ebac1650967e2
JavaScript
mit
todc/todc-bootstrap,todc/todc-bootstrap,todc/todc-bootstrap
--- +++ @@ -7,6 +7,6 @@ sourcesContent: true }, plugins: { - autoprefixer: {} + autoprefixer: { cascade: false } } })
55f0f4ab81f18cf33ff62389752ee7571623c27f
backend/dynamic-web-apps/voting-app/src/tests/integrated/database.spec.js
backend/dynamic-web-apps/voting-app/src/tests/integrated/database.spec.js
const test = require('tape'); const User = require('../../../models/User'); const { connect, add, remove } = require('../../database'); test('connection to database', async (assert) => { const res = await connect(); assert.equal(res, 0, 'It should connect to the database without errors'); assert.end(); }); test('adding to database', async (assert) => { const res = await add(User, 'sample', 'secret'); // try { await remove(User, 'sample'); // } catch (e) { assert.fail(e); } assert.equal(res, 0, 'It should add documents to the database without errors'); assert.end(); }); test('adding duplicates to database', async (assert) => { await add(User, 'sample', 'secret'); const res = await add(User, 'sample', 'secret'); // try { await remove(User, 'sample'); // } catch (e) {} assert.equal(res, 2, 'It should not add duplicate documents to the database'); assert.end(); });
const test = require('tape'); const User = require('../../../models/User'); const { connect, add, remove } = require('../../database'); test('connection to database', async (assert) => { const actual = await connect(); const expected = 0; assert.equal(actual, expected, 'It should connect to the database without errors'); assert.end(); }); test('adding to database', async (assert) => { const actual = await add(User, 'sample', 'secret'); const expected = 0; await remove(User, 'sample'); assert.equal(actual, expected, 'It should add documents to the database without errors'); assert.end(); }); test('adding duplicates to database', async (assert) => { await add(User, 'sample', 'secret'); const actual = await add(User, 'sample', 'secret'); const expected = 2; await remove(User, 'sample'); assert.equal(actual, expected, 'It should not add duplicate documents to the database'); assert.end(); });
Update test file variable names
Update test file variable names
JavaScript
mit
mkermani144/freecodecamp-projects,mkermani144/freecodecamp-projects
--- +++ @@ -3,26 +3,25 @@ const { connect, add, remove } = require('../../database'); test('connection to database', async (assert) => { - const res = await connect(); - assert.equal(res, 0, 'It should connect to the database without errors'); + const actual = await connect(); + const expected = 0; + assert.equal(actual, expected, 'It should connect to the database without errors'); assert.end(); }); test('adding to database', async (assert) => { - const res = await add(User, 'sample', 'secret'); - // try { - await remove(User, 'sample'); - // } catch (e) { assert.fail(e); } - assert.equal(res, 0, 'It should add documents to the database without errors'); + const actual = await add(User, 'sample', 'secret'); + const expected = 0; + await remove(User, 'sample'); + assert.equal(actual, expected, 'It should add documents to the database without errors'); assert.end(); }); test('adding duplicates to database', async (assert) => { await add(User, 'sample', 'secret'); - const res = await add(User, 'sample', 'secret'); - // try { - await remove(User, 'sample'); - // } catch (e) {} - assert.equal(res, 2, 'It should not add duplicate documents to the database'); + const actual = await add(User, 'sample', 'secret'); + const expected = 2; + await remove(User, 'sample'); + assert.equal(actual, expected, 'It should not add duplicate documents to the database'); assert.end(); });
da5deec709e4f2f1635ad72e26dd69740f20cd02
rules/base.js
rules/base.js
module.exports = { rules: { 'quote-props': [2, 'as-needed'], 'array-bracket-spacing': [2, 'never'], 'vars-on-top': 0, 'no-param-reassign': 0, 'max-len': [ 1, 110, 2, { "ignoreComments": true, "ignoreUrls": true } ], 'comma-dangle': [2, 'never'], 'no-use-before-define': [2, 'nofunc'], 'no-lonely-if': 2, 'handle-callback-err': 2, 'no-extra-parens': 2, 'no-path-concat': 1, 'func-style': [ 1, 'declaration' ], 'space-unary-ops': 2, 'no-mixed-requires': [ 2, true ], 'space-in-parens': [ 2, 'never' ], 'no-var': 0, 'prefer-const': 0, strict: [2, 'global'], 'object-curly-spacing': [2, 'never'], 'computed-property-spacing': [2, 'never'], 'func-names': 0, 'valid-jsdoc': [2, {requireReturnDescription: false}], 'id-length': 0 } };
module.exports = { rules: { 'quote-props': [2, 'as-needed', {keywords: true}], 'array-bracket-spacing': [2, 'never'], 'vars-on-top': 0, 'no-param-reassign': 0, 'max-len': [ 1, 110, 2, { "ignoreComments": true, "ignoreUrls": true } ], 'comma-dangle': [2, 'never'], 'no-use-before-define': [2, 'nofunc'], 'no-lonely-if': 2, 'handle-callback-err': 2, 'no-extra-parens': 2, 'no-path-concat': 1, 'func-style': [ 1, 'declaration' ], 'space-unary-ops': 2, 'no-mixed-requires': [ 2, true ], 'space-in-parens': [ 2, 'never' ], 'no-var': 0, 'prefer-const': 0, strict: [2, 'global'], 'object-curly-spacing': [2, 'never'], 'computed-property-spacing': [2, 'never'], 'func-names': 0, 'valid-jsdoc': [2, {requireReturnDescription: false}], 'id-length': 0 } };
Add the `keywords: true` option
feat(quote-props): Add the `keywords: true` option Without it `{ 'boolean': 'xxx' }` fails. However, this is not valid JS.
JavaScript
mit
algolia/eslint-config-algolia,algolia/eslint-config-algolia,algolia/eslint-config-algolia
--- +++ @@ -1,6 +1,6 @@ module.exports = { rules: { - 'quote-props': [2, 'as-needed'], + 'quote-props': [2, 'as-needed', {keywords: true}], 'array-bracket-spacing': [2, 'never'], 'vars-on-top': 0, 'no-param-reassign': 0,
4a4686e98d33d5eda9df4d5d21884254c6c11fa7
src/app/components/Can.js
src/app/components/Can.js
import React, { Component, PropTypes } from 'react'; function can(permissionsData, permission) { const permissions = JSON.parse(permissionsData); return permissions[permission]; } class Can extends Component { render() { if (can(this.props.permissions, this.props.permission)) { return (this.props.children); } else { return null; } } } export { Can as default, can };
import React, { Component, PropTypes } from 'react'; function can(permissionsData, permission) { try { const permissions = JSON.parse(permissionsData); return permissions[permission]; } catch (e) { throw `Error parsing permissions data: ${permissionsData}` } } class Can extends Component { render() { if (can(this.props.permissions, this.props.permission)) { return (this.props.children); } else { return null; } } } export { Can as default, can };
Throw more descriptive permissions parse errors
Throw more descriptive permissions parse errors
JavaScript
mit
meedan/check-web,meedan/check-web,meedan/check-web
--- +++ @@ -1,8 +1,12 @@ import React, { Component, PropTypes } from 'react'; function can(permissionsData, permission) { - const permissions = JSON.parse(permissionsData); - return permissions[permission]; + try { + const permissions = JSON.parse(permissionsData); + return permissions[permission]; + } catch (e) { + throw `Error parsing permissions data: ${permissionsData}` + } } class Can extends Component {
2a37fa9601da2277042e9a2485daae545337e9e8
lib/Pluggable/Pluggable.js
lib/Pluggable/Pluggable.js
// We have to remove node_modules/react to avoid having multiple copies loaded. // eslint-disable-next-line import/no-unresolved import React, { PropTypes } from 'react'; import { modules } from 'stripes-loader'; // eslint-disable-line const Pluggable = props => { const plugins = modules.plugin || []; let best; for (name of Object.keys(plugins)) { const m = plugins[name]; if (m.pluginType === props.type) { best = m; if (m.module === props.stripes.plugins[props.type]) break; } } if (best) { const Child = props.stripes.connect(best.getModule()); return <Child {...props} /> } return props.children; }; Pluggable.propTypes = { type: PropTypes.string.isRequired, }; export default Pluggable;
// We have to remove node_modules/react to avoid having multiple copies loaded. // eslint-disable-next-line import/no-unresolved import React, { PropTypes } from 'react'; import { modules } from 'stripes-loader'; // eslint-disable-line const Pluggable = (props, context) => { const plugins = modules.plugin || []; let best; for (name of Object.keys(plugins)) { const m = plugins[name]; if (m.pluginType === props.type) { best = m; if (m.module === context.stripes.plugins[props.type]) break; } } if (best) { const Child = context.stripes.connect(best.getModule()); return <Child {...props} /> } return props.children; }; Pluggable.contextTypes = { stripes: PropTypes.shape({ hasPerm: PropTypes.func.isRequired, }).isRequired, }; Pluggable.propTypes = { type: PropTypes.string.isRequired, }; export default Pluggable;
Use Stripes object from context, not from prop
Use Stripes object from context, not from prop Part of STRIPES-395.
JavaScript
apache-2.0
folio-org/stripes-components,folio-org/stripes-components
--- +++ @@ -3,7 +3,7 @@ import React, { PropTypes } from 'react'; import { modules } from 'stripes-loader'; // eslint-disable-line -const Pluggable = props => { +const Pluggable = (props, context) => { const plugins = modules.plugin || []; let best; @@ -11,16 +11,22 @@ const m = plugins[name]; if (m.pluginType === props.type) { best = m; - if (m.module === props.stripes.plugins[props.type]) break; + if (m.module === context.stripes.plugins[props.type]) break; } } if (best) { - const Child = props.stripes.connect(best.getModule()); + const Child = context.stripes.connect(best.getModule()); return <Child {...props} /> } return props.children; +}; + +Pluggable.contextTypes = { + stripes: PropTypes.shape({ + hasPerm: PropTypes.func.isRequired, + }).isRequired, }; Pluggable.propTypes = {
351594b202b9fe655a380031d2dce7d7a797f29e
lib/control/v1/conqueso.js
lib/control/v1/conqueso.js
'use strict'; const HTTP_OK = 200; const HTTP_METHOD_NOT_ALLOWED = 405; /** * Conqueso compatible API * * @param {Express.App} app */ function Conqueso(app) { app.get('/v1/conqueso*', (req, res) => { res.set('Content-Type', 'text/plain') res.status(HTTP_OK); res.end(); }); app.post('/v1/conqueso*', (req, res) => { res.status(HTTP_OK).end(); }); app.put('/v1/conqueso*', (req, res) => { res.status(HTTP_OK).end(); }); app.options('/v1/conqueso*', (req, res) => { res.set('Allow', 'POST,PUT,OPTIONS'); res.status(HTTP_OK); res.end(); }); app.all('/v1/conqueso*', (req, res) => { res.set('Allow', 'POST,PUT,OPTIONS'); res.status(HTTP_METHOD_NOT_ALLOWED); res.end(); }); } exports.attach = Conqueso;
'use strict'; const HTTP_OK = 200; const HTTP_METHOD_NOT_ALLOWED = 405; /** * Conqueso compatible API * * @param {Express.App} app */ function Conqueso(app) { function methodNotAllowed(req, res) { res.set('Allow', 'POST,PUT,OPTIONS'); res.status(HTTP_METHOD_NOT_ALLOWED); res.end(); } const route = app.route('/v1/conqueso*'); route.get((req, res) => { res.set('Content-Type', 'text/plain') res.status(HTTP_OK); res.end(); }); route.post((req, res) => { res.status(HTTP_OK).end(); }); route.put((req, res) => { res.status(HTTP_OK).end(); }); route.options((req, res) => { res.set('Allow', 'POST,PUT,OPTIONS'); res.status(HTTP_OK); res.end(); }); route.head(methodNotAllowed); route.all(methodNotAllowed); } exports.attach = Conqueso;
Refactor to use a route instead of pretty handlers.
Refactor to use a route instead of pretty handlers.
JavaScript
mit
rapid7/propsd,rapid7/propsd,rapid7/propsd
--- +++ @@ -9,31 +9,36 @@ * @param {Express.App} app */ function Conqueso(app) { - app.get('/v1/conqueso*', (req, res) => { + function methodNotAllowed(req, res) { + res.set('Allow', 'POST,PUT,OPTIONS'); + res.status(HTTP_METHOD_NOT_ALLOWED); + res.end(); + } + + const route = app.route('/v1/conqueso*'); + + route.get((req, res) => { res.set('Content-Type', 'text/plain') res.status(HTTP_OK); res.end(); }); - app.post('/v1/conqueso*', (req, res) => { + route.post((req, res) => { res.status(HTTP_OK).end(); }); - app.put('/v1/conqueso*', (req, res) => { + route.put((req, res) => { res.status(HTTP_OK).end(); }); - app.options('/v1/conqueso*', (req, res) => { + route.options((req, res) => { res.set('Allow', 'POST,PUT,OPTIONS'); res.status(HTTP_OK); res.end(); }); - app.all('/v1/conqueso*', (req, res) => { - res.set('Allow', 'POST,PUT,OPTIONS'); - res.status(HTTP_METHOD_NOT_ALLOWED); - res.end(); - }); + route.head(methodNotAllowed); + route.all(methodNotAllowed); } exports.attach = Conqueso;
44f9a70d53832e467aafba3a87c6fb06215a2a28
test/plugin.js
test/plugin.js
const expect = require('expect'); const proxyquire = require('proxyquire'); const ContextMock = require('./mocks/context'); const GitHubMock = require('./mocks/github'); const RobotMock = require('./mocks/robot'); function arrange(handleEventSpy) { const Plugin = proxyquire('../lib/plugin', { './handle-event': handleEventSpy }); return { plugin: new Plugin(), robotMock: new RobotMock(new GitHubMock()), contextMock: new ContextMock(), event: { action: 'test' } }; } describe('plugin', () => { it('should load correctly', async () => { // Arrange const handleEventSpy = expect.createSpy(); const { plugin, robotMock, contextMock, event } = arrange(handleEventSpy); // Act plugin.load(robotMock); await plugin.acceptEvent(event, contextMock); // Assert expect(handleEventSpy).toHaveBeenCalledWith(robotMock, event, contextMock); }); it('should emit event-handled event when event is handled successfully'); it('should emit error event when event handler fails'); it('should throw if loaded more than once'); it('should throw if events are given before loading'); it('should throw if `load` is called with incorrect execution context'); it('should throw if `acceptEvent` is called with incorrect execution context'); });
const expect = require('expect'); const proxyquire = require('proxyquire'); const ContextMock = require('./mocks/context'); const GitHubMock = require('./mocks/github'); const RobotMock = require('./mocks/robot'); function arrange(handleEventSpy) { const Plugin = proxyquire('../lib/plugin', { './handle-event': handleEventSpy }); return { plugin: new Plugin(), robotMock: new RobotMock(new GitHubMock()), contextMock: new ContextMock(), event: { action: 'test' } }; } describe('plugin', () => { it('should load correctly', async () => { // Arrange const handleEventSpy = expect.createSpy(); const { plugin, robotMock, contextMock, event } = arrange(handleEventSpy); // Act plugin.load(robotMock); await plugin.acceptEvent(event, contextMock); // Assert expect(handleEventSpy).toHaveBeenCalledWith(robotMock, event, contextMock); }); it('should emit event-handled event when event is handled successfully', async () => { // Arrange const { plugin, robotMock, contextMock, event } = arrange(expect.createSpy()); plugin.load(robotMock); const finishedEventSpy = expect.createSpy(); plugin.on('event-handled', finishedEventSpy); // Act await plugin.acceptEvent(event, contextMock); // Assert expect(finishedEventSpy).toHaveBeenCalled(); }); it('should emit error event when event handler fails'); it('should throw if loaded more than once'); it('should throw if events are given before loading'); it('should throw if `load` is called with incorrect execution context'); it('should throw if `acceptEvent` is called with incorrect execution context'); });
Implement `Plugin` test for `event-handled` event
Implement `Plugin` test for `event-handled` event
JavaScript
mit
jarrodldavis/probot-gpg
--- +++ @@ -31,7 +31,21 @@ expect(handleEventSpy).toHaveBeenCalledWith(robotMock, event, contextMock); }); - it('should emit event-handled event when event is handled successfully'); + it('should emit event-handled event when event is handled successfully', async () => { + // Arrange + const { plugin, robotMock, contextMock, event } = arrange(expect.createSpy()); + + plugin.load(robotMock); + + const finishedEventSpy = expect.createSpy(); + plugin.on('event-handled', finishedEventSpy); + + // Act + await plugin.acceptEvent(event, contextMock); + + // Assert + expect(finishedEventSpy).toHaveBeenCalled(); + }); it('should emit error event when event handler fails');
04d1cd56b942f5830e8be4f50c5603d0fed23fed
test/shared.js
test/shared.js
import React from 'react'; import { mount } from 'enzyme'; import { createStore } from 'redux'; import Phone from '../dev-server/Phone'; import App from '../dev-server/containers/App'; import brandConfig from '../dev-server/brandConfig'; import version from '../dev-server/version'; import prefix from '../dev-server/prefix'; import state from './state.json'; const apiConfig = { appKey: process.env.appKey, appSecret: process.env.appSecret, server: process.env.server, }; const getPhone = async () => { const phone = new Phone({ apiConfig, brandConfig, prefix, appVersion: version, }); if (window.authData === null) { await phone.client.service.platform().login({ username: process.env.username, extension: process.env.extension, password: process.env.password }); window.authData = phone.client.service.platform().auth().data(); } else { phone.client.service.platform().auth().setData(window.authData); } state.storage.status = 'module-initializing'; const store = createStore(phone.reducer, state); phone.setStore(store); return phone; }; export const getWrapper = async () => { const phone = await getPhone(); return mount(<App phone={phone} />); };
import React from 'react'; import { mount } from 'enzyme'; import { createStore } from 'redux'; import getIntlDateTimeFormatter from 'ringcentral-integration/lib/getIntlDateTimeFormatter'; import Phone from '../dev-server/Phone'; import App from '../dev-server/containers/App'; import brandConfig from '../dev-server/brandConfig'; import version from '../dev-server/version'; import prefix from '../dev-server/prefix'; import state from './state.json'; const apiConfig = { appKey: process.env.appKey, appSecret: process.env.appSecret, server: process.env.server, }; const getPhone = async () => { const phone = new Phone({ apiConfig, brandConfig, prefix, appVersion: version, }); if (window.authData === null) { await phone.client.service.platform().login({ username: process.env.username, extension: process.env.extension, password: process.env.password }); window.authData = phone.client.service.platform().auth().data(); } else { phone.client.service.platform().auth().setData(window.authData); } state.storage.status = 'module-initializing'; const store = createStore(phone.reducer, state); phone.setStore(store); phone.dateTimeFormat._defaultFormatter = getIntlDateTimeFormatter(); return phone; }; export const getWrapper = async () => { const phone = await getPhone(); return mount(<App phone={phone} />); };
Fix _defaultFormatter undefined issue in tests
Fix _defaultFormatter undefined issue in tests
JavaScript
mit
u9520107/ringcentral-js-widget,ringcentral/ringcentral-js-widget,u9520107/ringcentral-js-widget,ringcentral/ringcentral-js-widget,u9520107/ringcentral-js-widget,ringcentral/ringcentral-js-widget
--- +++ @@ -1,6 +1,7 @@ import React from 'react'; import { mount } from 'enzyme'; import { createStore } from 'redux'; +import getIntlDateTimeFormatter from 'ringcentral-integration/lib/getIntlDateTimeFormatter'; import Phone from '../dev-server/Phone'; import App from '../dev-server/containers/App'; @@ -35,6 +36,7 @@ state.storage.status = 'module-initializing'; const store = createStore(phone.reducer, state); phone.setStore(store); + phone.dateTimeFormat._defaultFormatter = getIntlDateTimeFormatter(); return phone; };
fbb9efc5ac0c7b7e673ade6fbfb214c51024fdf3
common/models/city.js
common/models/city.js
module.exports = function(City) { City.search = function(query, callback) { // TODO: sanitize query City.find( { where: { name: { like: '%' + query + '%' } } }, function (err, results) { callback(null, results); } ); }; City.remoteMethod( 'search', { http: { verb: 'get' }, accepts: { arg: 'query', type: 'string' }, returns: { arg: 'results', type: [ 'object' ] } } ); };
module.exports = function(City) { City.search = function(query, callback) { // TODO: sanitize query City.find( { where: { name: { like: '%' + query + '%' } }, include: [ 'region' ] }, function (err, results) { callback(null, results); } ); }; City.remoteMethod( 'search', { http: { verb: 'get' }, accepts: { arg: 'query', type: 'string' }, returns: { arg: 'results', type: [ 'object' ] } } ); };
Include region model on City search
Include region model on City search
JavaScript
bsd-3-clause
craigcabrey/ratemycoop,dkgramming/ratemycoop,craigcabrey/ratemycoop,dkgramming/ratemycoop
--- +++ @@ -7,7 +7,10 @@ name: { like: '%' + query + '%' } - } + }, + include: [ + 'region' + ] }, function (err, results) { callback(null, results); }
821f61f3d1c4df9ca4d9710b9f5c57b0b5b27795
lib/methods/competencies.js
lib/methods/competencies.js
Meteor.methods({ 'competencies.insert': function(params) { Nodes.insert({ name: params.name, type: 'C' }); } });
Meteor.methods({ 'competencies.insert': function(params) { Nodes.insert({ name: params.name, description: params.description, type: 'C' }); }, 'competencies.node.add': function(params) { Nodes.findAndModify({ query: { _id: params.competency._id }, update: { $push: { 'elements.nodes': Nodes.graph.createNode(params.node), 'elements.edges': { $each: Nodes.graph.createEdges(Lazy(params.parents).pluck('_id'), params.node._id) } } } }); } });
Add node to competency method
Add node to competency method
JavaScript
apache-2.0
ExtensionEngine/talc,ExtensionEngine/talc
--- +++ @@ -3,7 +3,21 @@ 'competencies.insert': function(params) { Nodes.insert({ name: params.name, + description: params.description, type: 'C' + }); + }, + 'competencies.node.add': function(params) { + Nodes.findAndModify({ + query: { _id: params.competency._id }, + update: { + $push: { + 'elements.nodes': Nodes.graph.createNode(params.node), + 'elements.edges': { + $each: Nodes.graph.createEdges(Lazy(params.parents).pluck('_id'), params.node._id) + } + } + } }); } });
badc42261d76c1437f949ac260f6b82cb1628de4
js/tilemapper.js
js/tilemapper.js
$(document).ready(function() { var canvas = document.getElementById('canvas'); canvas.width = $('#tileset').width(); canvas.height = $('#tileset').height(); });
function tilesetClip(tileset, number) { var index = number - 1; var row = Math.floor((index * tileset.tilewidth) / tileset.imagewidth); return { x: (index * tileset.tilewidth) % tileset.imagewidth, y: (row * tileset.tileheight) % tileset.imageheight, width: tileset.tilewidth, height: tileset.tileheight, } } $(document).ready(function() { var canvas = document.getElementById('canvas'); canvas.width = $('#tileset').width(); canvas.height = $('#tileset').height(); });
Add clip number resolving function
Add clip number resolving function
JavaScript
mit
nihey/tilemapper,nihey/tilemapper
--- +++ @@ -1,3 +1,15 @@ +function tilesetClip(tileset, number) { + var index = number - 1; + var row = Math.floor((index * tileset.tilewidth) / tileset.imagewidth); + + return { + x: (index * tileset.tilewidth) % tileset.imagewidth, + y: (row * tileset.tileheight) % tileset.imageheight, + width: tileset.tilewidth, + height: tileset.tileheight, + } +} + $(document).ready(function() { var canvas = document.getElementById('canvas'); canvas.width = $('#tileset').width();
4c9c3ded30c71caa797cee69190d09bf936f6da5
app/assets/javascripts/application.js
app/assets/javascripts/application.js
var socket = window.socket = new WebSocket("ws://localhost:8080/"); socket.onmessage = function(event) { var message = $.parseJSON(event.data); $("#events table") .append("<tr><td>" + message.name + " has entered the room.</td></tr>"); };
window.socket = new WebSocket("ws://localhost:8080/"); window.socket.addEventListener("message", function(event) { var message = $.parseJSON(event.data); $("#events table") .append( $("<tr>").append( $("<td>", { text: message.name + " has entered the room." }) ) ); }, false);
Clean up the example JavaScript.
Clean up the example JavaScript.
JavaScript
mit
tristandunn/cucumber-websocket-example,tristandunn/cucumber-websocket-example
--- +++ @@ -1,8 +1,11 @@ -var -socket = window.socket = new WebSocket("ws://localhost:8080/"); -socket.onmessage = function(event) { +window.socket = new WebSocket("ws://localhost:8080/"); +window.socket.addEventListener("message", function(event) { var message = $.parseJSON(event.data); $("#events table") - .append("<tr><td>" + message.name + " has entered the room.</td></tr>"); -}; + .append( + $("<tr>").append( + $("<td>", { text: message.name + " has entered the room." }) + ) + ); +}, false);
0bf440d7214159c76d5aa57ea44dd3e431984be2
.babelrc.js
.babelrc.js
const env = process.env.BABEL_ENV || process.env.NODE_ENV || 'development'; const browsers = process.env.BROWSERSLIST; const targets = {}; if (browsers) { targets.browsers = browsers; } if (env === 'production') { targets.uglify = true; } if (env === 'testing') { targets.node = 'current'; } const preset = { presets: [ ['env', { modules: false, loose: env === 'production', targets }], 'react' ], plugins: [ 'syntax-dynamic-import', 'transform-object-rest-spread', 'transform-class-properties', 'transform-export-extensions', ['transform-runtime', { polyfill: false }] ] }; if (env === 'development') { preset.plugins.push('react-hot-loader/babel'); } if (env === 'production') { preset.plugins.push( 'transform-react-constant-elements', 'transform-react-inline-elements', ['transform-react-remove-prop-types', { mode: 'wrap' }] ); } if (env === 'testing') { preset.plugins.push('istanbul'); } module.exports = preset;
module.exports = () => { const env = process.env.BABEL_ENV || process.env.NODE_ENV || 'development'; const browsers = process.env.BROWSERSLIST; const targets = {}; if (browsers) { targets.browsers = browsers; } if (env === 'production') { targets.uglify = true; } if (env === 'testing') { targets.node = 'current'; } const preset = { presets: [ ['env', { modules: false, loose: env === 'production', targets }], 'react' ], plugins: [ 'syntax-dynamic-import', 'transform-object-rest-spread', 'transform-class-properties', 'transform-export-extensions', ['transform-runtime', { polyfill: false }] ] }; if (env === 'development') { preset.plugins.push('react-hot-loader/babel'); } if (env === 'production') { preset.plugins.push( 'transform-react-constant-elements', 'transform-react-inline-elements', ['transform-react-remove-prop-types', { mode: 'wrap' }] ); } if (env === 'testing') { preset.plugins.push('istanbul'); } return preset; };
Fix Babel config env being shared.
Fix Babel config env being shared.
JavaScript
mit
u-wave/web,welovekpop/uwave-web-welovekpop.club,welovekpop/uwave-web-welovekpop.club,u-wave/web
--- +++ @@ -1,49 +1,51 @@ -const env = process.env.BABEL_ENV || process.env.NODE_ENV || 'development'; -const browsers = process.env.BROWSERSLIST; +module.exports = () => { + const env = process.env.BABEL_ENV || process.env.NODE_ENV || 'development'; + const browsers = process.env.BROWSERSLIST; -const targets = {}; -if (browsers) { - targets.browsers = browsers; -} -if (env === 'production') { - targets.uglify = true; -} -if (env === 'testing') { - targets.node = 'current'; -} + const targets = {}; + if (browsers) { + targets.browsers = browsers; + } + if (env === 'production') { + targets.uglify = true; + } + if (env === 'testing') { + targets.node = 'current'; + } -const preset = { - presets: [ - ['env', { - modules: false, - loose: env === 'production', - targets - }], - 'react' - ], - plugins: [ - 'syntax-dynamic-import', - 'transform-object-rest-spread', - 'transform-class-properties', - 'transform-export-extensions', - ['transform-runtime', { polyfill: false }] - ] + const preset = { + presets: [ + ['env', { + modules: false, + loose: env === 'production', + targets + }], + 'react' + ], + plugins: [ + 'syntax-dynamic-import', + 'transform-object-rest-spread', + 'transform-class-properties', + 'transform-export-extensions', + ['transform-runtime', { polyfill: false }] + ] + }; + + if (env === 'development') { + preset.plugins.push('react-hot-loader/babel'); + } + + if (env === 'production') { + preset.plugins.push( + 'transform-react-constant-elements', + 'transform-react-inline-elements', + ['transform-react-remove-prop-types', { mode: 'wrap' }] + ); + } + + if (env === 'testing') { + preset.plugins.push('istanbul'); + } + + return preset; }; - -if (env === 'development') { - preset.plugins.push('react-hot-loader/babel'); -} - -if (env === 'production') { - preset.plugins.push( - 'transform-react-constant-elements', - 'transform-react-inline-elements', - ['transform-react-remove-prop-types', { mode: 'wrap' }] - ); -} - -if (env === 'testing') { - preset.plugins.push('istanbul'); -} - -module.exports = preset;
d9792a52a49efcf3ad1c4e343d2782a68002719c
app/initializer/layout-initializer.js
app/initializer/layout-initializer.js
import React from 'react'; import FocusCore from 'focus-core'; import FocusComponents from 'focus-components'; import render from 'focus-core/application/render'; import Layout from 'focus-components/components/layout'; import ConfirmWrapper from 'focus-components/components/confirm'; import DemoMenuLeft from '../views/menu/menu-left'; render(()=> <div><Layout MenuLeft={DemoMenuLeft}></Layout><ConfirmWrapper /></div>, '[data-focus="application"]', { props: {} });
import React from 'react'; import FocusCore from 'focus-core'; import FocusComponents from 'focus-components'; import render from 'focus-core/application/render'; import Layout from 'focus-components/components/layout'; import ConfirmWrapper from 'focus-components/components/confirm'; import DemoMenuLeft from '../views/menu/menu-left'; render(Layout, '[data-focus="application"]', { props: {MenuLeft: DemoMenuLeft} });
Remove function because it is now included in the layour
[initializer] Remove function because it is now included in the layour
JavaScript
mit
KleeGroup/focus-demo-app,get-focus/focus-demo-app,KleeGroup/focus-demo-app,KleeGroup/focus-starter-kit,KleeGroup/focus-starter-kit
--- +++ @@ -6,6 +6,6 @@ import ConfirmWrapper from 'focus-components/components/confirm'; import DemoMenuLeft from '../views/menu/menu-left'; -render(()=> <div><Layout MenuLeft={DemoMenuLeft}></Layout><ConfirmWrapper /></div>, '[data-focus="application"]', { - props: {} +render(Layout, '[data-focus="application"]', { + props: {MenuLeft: DemoMenuLeft} });
a1a087d2db9b67895ee7ac6220e3dc39d969f82a
lib/npmalerts.js
lib/npmalerts.js
'use strict'; var github = require('./github'); var npm = require('./npm'); var db = require('./db'); var email = require('./email'); var _ = require('underscore'); var cache = {}; var yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); npm.getLatestPackages(yesterday, function(error, packages) { if (error) { return console.error(error); } cache = packages; console.info('There are ' + cache.length + ' package updates.'); db.readSubscriptions(function(error, subscriptions) { if (error) { return console.error(error); } _.each(subscriptions, function(subscription) { var user = github.getUserFromUrl(subscription.repourl); var repo = github.getRepoFromUrl(subscription.repourl); github.getPackageJson(user, repo, processPackageJson(subscription)); }); }); }); function processPackageJson(subscription) { return function(error, json) { if (error) { return console.error(error); } var packages = _.filter(_.extend(json.dependencies, json.devDependencies), isPackageInCache); _.each(packages, function(packageName) { var cached = cache[packageName]; var versionRange = packages[packageName]; email.send(subscription.email, subscription.repourl, packageName, versionRange, cached.version); }); }; } function isPackageInCache(dependency) { return !!cache[dependency]; }
'use strict'; var github = require('./github'); var npm = require('./npm'); var db = require('./db'); var email = require('./email'); var _ = require('underscore'); var cache = {}; var yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); npm.getLatestPackages(yesterday, function(error, packages) { if (error) { return console.error(error); } cache = packages; console.info('There are ' + cache.length + ' package updates.'); db.readSubscriptions(function(error, subscriptions) { if (error) { return console.error(error); } _.each(subscriptions, function(subscription) { var user = github.getUserFromUrl(subscription.repourl); var repo = github.getRepoFromUrl(subscription.repourl); github.getPackageJson(user, repo, processPackageJson(subscription)); }); }); }); function processPackageJson(subscription) { return function(error, json) { if (error) { return console.error(error); } var packages = _.filter(_.extend(json.dependencies || {}, json.devDependencies || {}), isPackageInCache); _.each(packages, function(packageName) { var cached = cache[packageName]; var versionRange = packages[packageName]; email.send(subscription.email, subscription.repourl, packageName, versionRange, cached.version); }); }; } function isPackageInCache(dependency) { return !!cache[dependency]; }
Add fallback for empty dependencies and devDependencies
Add fallback for empty dependencies and devDependencies
JavaScript
mit
seriema/npmalerts,creationix/npmalerts
--- +++ @@ -40,7 +40,7 @@ return console.error(error); } - var packages = _.filter(_.extend(json.dependencies, json.devDependencies), isPackageInCache); + var packages = _.filter(_.extend(json.dependencies || {}, json.devDependencies || {}), isPackageInCache); _.each(packages, function(packageName) { var cached = cache[packageName];
f66815b189260d66090e1f3de5a0967a23fb5155
configure.js
configure.js
var webpack = require('webpack'); var path = require('path'); var fs = require('fs'); var assignDeep = require('assign-deep'); var values = require('object-values'); var configureCommon = require('./configureCommon'); var configureDevelopment = require('./configureDevelopment'); module.exports = function(port, entryFile, config) { var env = process.env.NODE_ENV || 'development'; var rootDir = path.dirname(entryFile); var packagePath = path.resolve(rootDir, './package.json'); var options = { globals: { __DEV__: (env === 'development'), 'process.env.NODE_ENV': JSON.stringify(env) }, package: fs.existsSync(packagePath) ? require(packagePath) : {name: 'packup-app', title: 'Packup-App', version: '0.0.0', description: '', dependencies: {}}, root: rootDir, entry: config.entry || entryFile, port: port } var packupConfig = assignDeep(configureCommon(options), configureDevelopment(options)); var webpackConfig = assignDeep(packupConfig, { module: { loaders: values(packupConfig.loaders) } }); return webpackConfig; }
var webpack = require('webpack'); var path = require('path'); var fs = require('fs'); var assignDeep = require('assign-deep'); var values = require('object-values'); var configureCommon = require('./configureCommon'); var configureDevelopment = require('./configureDevelopment'); module.exports = function(port, entryFile, config) { var env = process.env.NODE_ENV || 'development'; var rootDir = path.dirname(entryFile); var packagePath = path.resolve(rootDir, './package.json'); var options = { globals: { __DEV__: (env === 'development'), 'process.env.NODE_ENV': JSON.stringify(env) }, package: fs.existsSync(packagePath) ? require(packagePath) : {name: path.basename(rootDir), title: 'Packup-App', version: '0.0.0', description: '', dependencies: {}}, root: rootDir, entry: config.entry || entryFile, port: port } var packupConfig = assignDeep(configureCommon(options), configureDevelopment(options)); var webpackConfig = assignDeep(packupConfig, { module: { loaders: values(packupConfig.loaders) } }); return webpackConfig; }
Use base name as default package name
Use base name as default package name
JavaScript
bsd-3-clause
interactivethings/packup,interactivethings/packup
--- +++ @@ -16,7 +16,7 @@ __DEV__: (env === 'development'), 'process.env.NODE_ENV': JSON.stringify(env) }, - package: fs.existsSync(packagePath) ? require(packagePath) : {name: 'packup-app', title: 'Packup-App', version: '0.0.0', description: '', dependencies: {}}, + package: fs.existsSync(packagePath) ? require(packagePath) : {name: path.basename(rootDir), title: 'Packup-App', version: '0.0.0', description: '', dependencies: {}}, root: rootDir, entry: config.entry || entryFile, port: port
57b0d056e3ecd7676edc641f75d69e93b06f54c9
lib/util/wrap.js
lib/util/wrap.js
'use strict' module.exports = wrap wrap.needed = needed var phrasing = require('mdast-util-phrasing') /* Wrap all inline runs of MDAST content in `paragraph` nodes. */ function wrap(nodes) { var result = [] var length = nodes.length var index = -1 var node var queue while (++index < length) { node = nodes[index] if (phrasing(node)) { if (queue === undefined) { queue = [] } queue.push(node) } else { if (queue !== undefined) { result.push({type: 'paragraph', children: queue}) queue = undefined } result.push(node) } } if (queue !== undefined) { result.push({type: 'paragraph', children: queue}) } return result } /* Check if there are non-inline MDAST nodes returned. * This is needed if a fragment is given, which could just be * a sentence, and doesn’t need a wrapper paragraph. */ function needed(nodes) { var length = nodes.length var index = -1 while (++index < length) { if (!phrasing(nodes[index])) { return true } } return false }
'use strict' module.exports = wrap wrap.needed = needed var phrasing = require('mdast-util-phrasing') /* Wrap all inline runs of MDAST content in `paragraph` nodes. */ function wrap(nodes) { var result = [] var length = nodes.length var index = -1 var node var queue while (++index < length) { node = nodes[index] if (phrasing(node)) { if (queue === undefined) { queue = [] } queue.push(node) } else { flush() result.push(node) } } flush() return result function flush() { if (queue !== undefined) { if ( queue.length !== 1 || queue[0].type !== 'text' || (queue[0].value !== ' ' && queue[0].value !== '\n') ) { result.push({type: 'paragraph', children: queue}) } } queue = undefined } } /* Check if there are non-inline MDAST nodes returned. * This is needed if a fragment is given, which could just be * a sentence, and doesn’t need a wrapper paragraph. */ function needed(nodes) { var length = nodes.length var index = -1 while (++index < length) { if (!phrasing(nodes[index])) { return true } } return false }
Fix bug where white space only paragraphs showed
Fix bug where white space only paragraphs showed
JavaScript
mit
syntax-tree/hast-util-to-mdast
--- +++ @@ -24,20 +24,28 @@ queue.push(node) } else { - if (queue !== undefined) { - result.push({type: 'paragraph', children: queue}) - queue = undefined - } - + flush() result.push(node) } } - if (queue !== undefined) { - result.push({type: 'paragraph', children: queue}) - } + flush() return result + + function flush() { + if (queue !== undefined) { + if ( + queue.length !== 1 || + queue[0].type !== 'text' || + (queue[0].value !== ' ' && queue[0].value !== '\n') + ) { + result.push({type: 'paragraph', children: queue}) + } + } + + queue = undefined + } } /* Check if there are non-inline MDAST nodes returned.
7a65f45051fbede11859fd2c044d35982cd9a51a
source/sw.js
source/sw.js
importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js'); workbox.core.skipWaiting(); workbox.precaching.precacheAndRoute([]); // NOTE: All HTML pages should be dynamically cached, and also constantly // revalidated to make sure that the cache is always up-to-date. const staticUrlRegex = /\/static\//; const notStaticUrl = ({url}) => !staticUrlRegex.test(url); workbox.routing.registerRoute( notStaticUrl, new workbox.strategies.StaleWhileRevalidate({ plugins: [ new workbox.broadcastUpdate.Plugin({ channelName: 'page-updated' }) ] }) );
importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js'); workbox.core.skipWaiting(); workbox.precaching.precacheAndRoute([]); const persistentPages = ['/', '/blog/', '/events/', '/projects/']; const persistentPagesStrategy = new workbox.strategies.StaleWhileRevalidate({ cacheName: 'persistent-pages', plugins: [ new workbox.broadcastUpdate.Plugin({ channelName: 'page-updated' }) ] }); persistentPages.forEach(path => { workbox.routing.registerRoute(path, persistentPagesStrategy); });
Store persistent pages in separate cache
Store persistent pages in separate cache
JavaScript
mit
arnellebalane/arnellebalane.com,arnellebalane/arnellebalane.com,arnellebalane/arnellebalane.com
--- +++ @@ -3,19 +3,16 @@ workbox.core.skipWaiting(); workbox.precaching.precacheAndRoute([]); -// NOTE: All HTML pages should be dynamically cached, and also constantly -// revalidated to make sure that the cache is always up-to-date. +const persistentPages = ['/', '/blog/', '/events/', '/projects/']; +const persistentPagesStrategy = new workbox.strategies.StaleWhileRevalidate({ + cacheName: 'persistent-pages', + plugins: [ + new workbox.broadcastUpdate.Plugin({ + channelName: 'page-updated' + }) + ] +}); -const staticUrlRegex = /\/static\//; -const notStaticUrl = ({url}) => !staticUrlRegex.test(url); - -workbox.routing.registerRoute( - notStaticUrl, - new workbox.strategies.StaleWhileRevalidate({ - plugins: [ - new workbox.broadcastUpdate.Plugin({ - channelName: 'page-updated' - }) - ] - }) -); +persistentPages.forEach(path => { + workbox.routing.registerRoute(path, persistentPagesStrategy); +});
50ff39933815985cd7bcc8df3cbe25a2b5f4a543
js/scratch-pad.js
js/scratch-pad.js
(function (context) { var Sample = {}; Sample.switchCase = function (x) { var returnValue; switch(val) { case 2: returnValue = 'A' break; case 6: returnValue = 'B' break; case 9: returnValue = 'C' break; default: returnValue = null; } return returnValue; }; Sample.forEachArray = [1, 3, 5, 9, 6, 19, 10, 11]; Sample.forEach = function (x) { var sum = 0; for (var index in Sample.forEachArray) { sum += Sample.forEachArray[index]; } return sum; }; Sample.twoDigits = function (x) { var z = x * 10; return function (y) { return z + y; } }; return context.Sample = Sample; var val = 2; Sample.hash = {2: 'A', 6: 'B', 9: 'C', '2': 'D'}; Sample.hashAccess1 = {2: 'A', 6: 'B', 9: 'C', '2': 'D'}[val]; Sample.hashAccess2 = Sample.hash[val]; })(this)
(function (context) { var Sample = {}; Sample.switchCase = function (x) { var returnValue; switch(val) { case 2: returnValue = 'A' break; case 6: returnValue = 'B' break; case 9: returnValue = 'C' break; default: returnValue = null; } return returnValue; }; Sample.forEachArray = [1, 3, 5, 9, 6, 19, 10, 11]; Sample.forEach = function (x) { var sum = 0; for (var index in Sample.forEachArray) { sum += Sample.forEachArray[index]; } return sum; }; Sample.twoDigits = function (x) { var z = x * 10; return function (y) { return z + y; } }; Sample.whatTheFunc = function (bar) { return function (baz) { return function (derp) { return bar.callback(baz, derp, bar.value); }; }; }; Sample.whatTheFuncData = { callback: function (x, y, z) { return [x, y, z].join(' '); }, value: 'func?!' }; Sample.whatTheFuncOut = Sample.whatTheFunc(Sample.whatTheFuncData)('What')('the'); return context.Sample = Sample; var val = 2; Sample.hash = {2: 'A', 6: 'B', 9: 'C', '2': 'D'}; Sample.hashAccess1 = {2: 'A', 6: 'B', 9: 'C', '2': 'D'}[val]; Sample.hashAccess2 = Sample.hash[val]; })(this)
Add whatTheFunc to scratch pad.
Add whatTheFunc to scratch pad.
JavaScript
unlicense
CWDG/Functional-JavaScript-Talk
--- +++ @@ -35,6 +35,21 @@ } }; + Sample.whatTheFunc = function (bar) { + return function (baz) { + return function (derp) { + return bar.callback(baz, derp, bar.value); + }; + }; + }; + + Sample.whatTheFuncData = { + callback: function (x, y, z) { return [x, y, z].join(' '); }, + value: 'func?!' + }; + + Sample.whatTheFuncOut = Sample.whatTheFunc(Sample.whatTheFuncData)('What')('the'); + return context.Sample = Sample; var val = 2;
2db577b84eb075b0183bc3744fd60464e6ed6465
src/index.js
src/index.js
export { Diory as default, Diory } from './Diory' export { default as DioryText } from './DioryText' export { default as DioryImage } from './DioryImage'
export { Diory as default, Diory } from './Diory' export { DioryText } from './DioryText' export { DioryImage } from './DioryImage'
Fix export of the components
Fix export of the components
JavaScript
mit
DioryMe/diory-react-components,DioryMe/diory-react-components
--- +++ @@ -1,3 +1,3 @@ export { Diory as default, Diory } from './Diory' -export { default as DioryText } from './DioryText' -export { default as DioryImage } from './DioryImage' +export { DioryText } from './DioryText' +export { DioryImage } from './DioryImage'
691f9ecf58861fec54d299d3d1f9b14d123f0d14
lib/plugins/body_parser.js
lib/plugins/body_parser.js
// Copyright 2012 Mark Cavage, Inc. All rights reserved. var jsonParser = require('./json_body_parser'); var formParser = require('./form_body_parser'); var multipartParser = require('./multipart_parser'); var errors = require('../errors'); var UnsupportedMediaTypeError = errors.UnsupportedMediaTypeError; function bodyParser(options) { var parseForm = formParser(options); var parseJson = jsonParser(options); var parseMultipart = multipartParser(options); return function parseBody(req, res, next) { if (req.method !== 'POST' && req.method !== 'PUT') return next(); if (req.contentLength === 0 && !req.chunked) return next(); if (req.contentType === 'application/json') { return parseJson(req, res, next); } else if (req.contentType === 'application/x-www-form-urlencoded') { return parseForm(req, res, next); } else if (req.contentType === 'multipart/form-data') { return parseMultipart(req, res, next); } else if (options.rejectUnknown !== false) { return next(new UnsupportedMediaTypeError('Unsupported Content-Type: ' + req.contentType)); } return next(); }; } module.exports = bodyParser;
// Copyright 2012 Mark Cavage, Inc. All rights reserved. var jsonParser = require('./json_body_parser'); var formParser = require('./form_body_parser'); var multipartParser = require('./multipart_parser'); var errors = require('../errors'); var UnsupportedMediaTypeError = errors.UnsupportedMediaTypeError; function bodyParser(options) { var parseForm = formParser(options); var parseJson = jsonParser(options); var parseMultipart = multipartParser(options); return function parseBody(req, res, next) { if (req.method !== 'POST' && req.method !== 'PUT' && req.method !== 'PATCH') return next(); if (req.contentLength === 0 && !req.chunked) return next(); if (req.contentType === 'application/json') { return parseJson(req, res, next); } else if (req.contentType === 'application/x-www-form-urlencoded') { return parseForm(req, res, next); } else if (req.contentType === 'multipart/form-data') { return parseMultipart(req, res, next); } else if (options.rejectUnknown !== false) { return next(new UnsupportedMediaTypeError('Unsupported Content-Type: ' + req.contentType)); } return next(); }; } module.exports = bodyParser;
Make bodyParser play well with PATCH too.
Make bodyParser play well with PATCH too.
JavaScript
mit
rborn/node-restify,msaffitz/node-restify,jclulow/node-restify,kevinykchan/node-restify,TheDeveloper/node-restify,chaordic/node-restify,adunkman/node-restify,prasmussen/node-restify,ferhatsb/node-restify,uWhisp/node-restify
--- +++ @@ -16,7 +16,7 @@ var parseMultipart = multipartParser(options); return function parseBody(req, res, next) { - if (req.method !== 'POST' && req.method !== 'PUT') + if (req.method !== 'POST' && req.method !== 'PUT' && req.method !== 'PATCH') return next(); if (req.contentLength === 0 && !req.chunked)
4a95ed75556c4922653a14c8db7a0e480eba1b28
src/sketch.js
src/sketch.js
function setup() { createCanvas(640, 480); } function draw() { ellipse(50, 50, 80, 80); } /** * Boid class */ function Boid(x_pos, y_pos, mass) { this.position= createVector(x_pos, y_pos); this.velocity = createVector(0, 0); this.acceleration = createVector(0, 0); this.mass = mass; } Boid.prototype = { constructor: Boid, update:function () { // TODO }, display:function () { // TODO }, checkEdges:function () { // TODO } }
var boids = []; /** * P5js initialization */ function setup() { createCanvas(640, 480); for (var i = 0; i < 10; i++) { boids.push(new Boid(10*i, 10*i, 10)); } } /** * P5js render loop */ function draw() { boids.forEach( Boid.prototype.display ); } /** * Boid class */ function Boid(x_pos, y_pos, mass) { this.position= createVector(x_pos, y_pos); this.velocity = createVector(0, 0); this.acceleration = createVector(0, 0); this.mass = mass; } Boid.prototype = { constructor: Boid, update:function () { // TODO }, display:function (self) { ellipse(self.position.x, self.position.y, 80, 80); }, checkEdges:function () { // TODO } }
Implement Boid display method, uses arbitrary radius
Implement Boid display method, uses arbitrary radius
JavaScript
mit
dkgramming/rgw,dkgramming/rgw
--- +++ @@ -1,9 +1,27 @@ +var boids = []; + +/** + * P5js initialization + */ function setup() { + createCanvas(640, 480); + + for (var i = 0; i < 10; i++) { + boids.push(new Boid(10*i, 10*i, 10)); + } + } +/** + * P5js render loop + */ function draw() { - ellipse(50, 50, 80, 80); + + boids.forEach( + Boid.prototype.display + ); + } /** @@ -21,8 +39,8 @@ update:function () { // TODO }, - display:function () { - // TODO + display:function (self) { + ellipse(self.position.x, self.position.y, 80, 80); }, checkEdges:function () { // TODO
0cd2a9e4571986dfe951805f33d9dcfe369e64db
tasks/build.js
tasks/build.js
// imports var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var uglify = require('gulp-uglify'); var buffer = require('vinyl-buffer'); // build src gulp.task('browserify', function(cb){ return browserify('./src/app.js', { debug: true }) .bundle() .pipe(source('bundle.js')) .pipe(gulp.dest('./www/')); cb(); }); // build in release mode gulp.task('browserify:release', function(cb){ return browserify('./src/app.js') .bundle() .pipe(source('bundle.js')) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest('./www/')); cb(); }); // copy fonts gulp.task('fonts', function(cb){ return gulp.src('node_modules/ionic-framework/release/fonts/**') .pipe(gulp.dest('./www/fonts/')); cb(); }); // copy assets gulp.task('assets', function(cb){ return gulp.src('./assets/**') .pipe(gulp.dest('./www/')); cb(); }); // copy templates gulp.task('templates', function(cb){ return gulp.src('./src/**/*.html') .pipe(gulp.dest('./www/')); cb(); });
// imports var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var uglify = require('gulp-uglify'); var buffer = require('vinyl-buffer'); // build src gulp.task('browserify', function(cb){ return browserify('./src/app.js', { debug: true }) .bundle() .pipe(source('bundle.js')) .pipe(gulp.dest('./www/')); cb(); }); // build in release mode gulp.task('browserify:release', function(cb){ return browserify('./src/app.js') .bundle() .pipe(source('bundle.js')) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest('./www/')); cb(); }); // copy fonts gulp.task('fonts', function(cb){ return gulp.src('node_modules/ionic-npm/fonts/**') .pipe(gulp.dest('./www/fonts/')); cb(); }); // copy assets gulp.task('assets', function(cb){ return gulp.src('./assets/**') .pipe(gulp.dest('./www/')); cb(); }); // copy templates gulp.task('templates', function(cb){ return gulp.src('./src/**/*.html') .pipe(gulp.dest('./www/')); cb(); });
Update path fonts gulp task
Update path fonts gulp task
JavaScript
mit
microscope-mobile/ionic-tabs,microscope-mobile/ionic-tabs,microscope-mobile/ionic-tabs,microscope-mobile/ionic-tabs,microscope-mobile/ionic-tabs
--- +++ @@ -32,7 +32,7 @@ // copy fonts gulp.task('fonts', function(cb){ - return gulp.src('node_modules/ionic-framework/release/fonts/**') + return gulp.src('node_modules/ionic-npm/fonts/**') .pipe(gulp.dest('./www/fonts/')); cb(); });
c90559b246ed418c54ddc9c64cdb864dbab3ef6d
prompts.js
prompts.js
'use strict'; var _ = require('lodash'); var prompts = [ { type: 'input', name: 'projectName', message: 'Machine-name of your project?', // Name of the parent directory. default: _.last(process.cwd().split('/')), validate: function (input) { return (input.search(' ') === -1) ? true : 'No spaces allowed.'; } }, { type: 'list', name: 'webserver', message: 'Choose your webserver:', choices: [ 'apache', 'nginx', 'custom' ], default: 'apache' }, { name: 'webImage', message: 'Specify your webserver Docker image:', default: 'phase2/apache24php55', when: function(answers) { return answers.webserver == 'custom'; }, validate: function(input) { if (_.isString(input)) { return true; } return 'A validate docker image identifier is required.'; } }, { type: 'list', name: 'cacheInternal', message: 'Choose a cache backend:', default: 'memcache', choices: [ 'memcache', 'database' ] } ]; module.exports = prompts;
'use strict'; var _ = require('lodash'); var prompts = [ { type: 'input', name: 'projectName', message: 'Machine-name of your project?', // Name of the parent directory. default: _.last(process.cwd().split('/')), validate: function (input) { return (input.search(' ') === -1) ? true : 'No spaces allowed.'; } }, { type: 'list', name: 'webserver', message: 'Choose your webserver:', choices: [ 'apache', 'custom' ], default: 'apache' }, { name: 'webImage', message: 'Specify your webserver Docker image:', default: 'phase2/apache24php55', when: function(answers) { return answers.webserver == 'custom'; }, validate: function(input) { if (_.isString(input)) { return true; } return 'A validate docker image identifier is required.'; } }, { type: 'list', name: 'cacheInternal', message: 'Choose a cache backend:', default: 'memcache', choices: [ 'memcache', 'database' ] } ]; module.exports = prompts;
Remove nginx as a directly supported option.
Remove nginx as a directly supported option.
JavaScript
mit
phase2/generator-outrigger-drupal,phase2/generator-outrigger-drupal,phase2/generator-outrigger-drupal
--- +++ @@ -19,7 +19,6 @@ message: 'Choose your webserver:', choices: [ 'apache', - 'nginx', 'custom' ], default: 'apache'
10af81baad62584ef31a497b21479ca8db31fb5a
statistics.js
statistics.js
var config = require('./config'); var rdb = config.rdb; var rdbLogger = config.rdbLogger; module.exports = function statistics() { return function (req, res, next) { rdb.sismember( 'stats:ip', req.connection.remoteAddress, function (err, reply) { if (err || typeof reply === 'undefined') { console.log('[Statistics] No reply from redis.'); } else { if (!reply) { rdb.sadd('stats:ip', req.connection.remoteAddress, rdbLogger); rdb.incr('stats:visit:total', rdbLogger); } } } ); rdb.incr('stats:hit:total', rdbLogger); next(); }; }
var config = require('./config'); var rdb = config.rdb; var rdbLogger = config.rdbLogger; module.exports = function statistics() { return function (req, res, next) { var ip = ''; if (req.headers['x-nginx-proxy'] == 'true') { ip = req.headers['x-real-ip']; } else { ip = req.connection.remoteAddress; } rdb.sismember( 'stats:ip', ip, function (err, reply) { if (err || typeof reply === 'undefined') { console.log('[Statistics] No reply from redis.'); } else { if (!reply) { rdb.sadd('stats:ip', ip, rdbLogger); rdb.incr('stats:visit:total', rdbLogger); } } } ); rdb.incr('stats:hit:total', rdbLogger); next(); }; }
Fix nginx forwarding issue with remote address.
Fix nginx forwarding issue with remote address.
JavaScript
mit
s1na/talkie
--- +++ @@ -4,15 +4,21 @@ module.exports = function statistics() { return function (req, res, next) { + var ip = ''; + if (req.headers['x-nginx-proxy'] == 'true') { + ip = req.headers['x-real-ip']; + } else { + ip = req.connection.remoteAddress; + } rdb.sismember( 'stats:ip', - req.connection.remoteAddress, + ip, function (err, reply) { if (err || typeof reply === 'undefined') { console.log('[Statistics] No reply from redis.'); } else { if (!reply) { - rdb.sadd('stats:ip', req.connection.remoteAddress, rdbLogger); + rdb.sadd('stats:ip', ip, rdbLogger); rdb.incr('stats:visit:total', rdbLogger); } }
56ffe01657459d41dc62b187903afbad2348e587
app/assets/javascripts/title_onload.js
app/assets/javascripts/title_onload.js
window.onload = function(){ var headerText = "WriteNow".split("") animateHeader(headerText); }; animateHeader = function(text){ current = 0; header = $(".main_header"); setInterval(function() { if(current < text.length) { header.text(header.text() + text[current++]); } }, 120); }
TitleLoader = { animateHeader: function(text){ current = 0; header = $(".main_header"); setInterval(function() { if (current < text.length) { header.text(header.text() + text[current++]); } }, 120); }, displayTagline: function() { $(".tagline").fadeIn(4700); } } $(document).ready(function() { var headerText = "WriteNow".split(""); TitleLoader.animateHeader(headerText); TitleLoader.displayTagline(); });
Add TitleLoader namespace for onload functionality.
Add TitleLoader namespace for onload functionality.
JavaScript
mit
tiger-swallowtails-2014/write-now,tiger-swallowtails-2014/write-now
--- +++ @@ -1,14 +1,20 @@ -window.onload = function(){ - var headerText = "WriteNow".split("") - animateHeader(headerText); -}; +TitleLoader = { + animateHeader: function(text){ + current = 0; + header = $(".main_header"); + setInterval(function() { + if (current < text.length) { + header.text(header.text() + text[current++]); + } + }, 120); + }, + displayTagline: function() { + $(".tagline").fadeIn(4700); + } +} -animateHeader = function(text){ - current = 0; - header = $(".main_header"); - setInterval(function() { - if(current < text.length) { - header.text(header.text() + text[current++]); - } - }, 120); -} +$(document).ready(function() { + var headerText = "WriteNow".split(""); + TitleLoader.animateHeader(headerText); + TitleLoader.displayTagline(); +});
e9a71f62a6d88a13d8be3435e970814b6087bd3e
app/components/layer-info/component.js
app/components/layer-info/component.js
import Ember from 'ember'; import loadAll from 'ember-osf/utils/load-relationship'; export default Ember.Component.extend({ users: Ember.A(), bibliographicUsers: Ember.A(), institutions: Ember.A(), getAuthors: function() { // Cannot be called until node has loaded! const node = this.get('node'); if (!node) { return }; if(this.get('users').length > 0 || this.get('bibliographicUsers').length > 0) { return; } const contributors = Ember.A(); loadAll(node, 'contributors', contributors).then(() => { contributors.forEach((item) => { this.get('users').pushObject(item.get('users')); if(item.get('bibliographic')){ this.get('bibliographicUsers').pushObject(item.get('users')); } }) }); }, getAffiliatedInst: function (){ const node = this.get('node'); if (!node) { return }; const institutions = Ember.A(); loadAll(node, 'affiliatedInstitutions', institutions).then(() => { institutions.forEach((item) => { this.get('institutions').pushObject(item); }) }); }, didReceiveAttrs() { this._super(...arguments); this.getAuthors(); this.getAffiliatedInst(); } });
import Ember from 'ember'; import loadAll from 'ember-osf/utils/load-relationship'; export default Ember.Component.extend({ users: Ember.A(), bibliographicUsers: Ember.A(), institutions: Ember.A(), getAuthors: function() { // Cannot be called until node has loaded! const node = this.get('node'); if (!node) { return }; if(this.get('users').length > 0 || this.get('bibliographicUsers').length > 0) { return; } const contributors = Ember.A(); loadAll(node, 'contributors', contributors).then(() => { contributors.forEach((item) => { this.get('users').pushObject(item.get('users')); if(item.get('bibliographic')){ this.get('bibliographicUsers').pushObject(item.get('users')); } }) }); }, getAffiliatedInst: function (){ const node = this.get('node'); if (!node) { return }; if(this.get('institutions').length > 0) { return; } const institutions = Ember.A(); loadAll(node, 'affiliatedInstitutions', institutions).then(() => { institutions.forEach((item) => { this.get('institutions').pushObject(item); }) }); }, didReceiveAttrs() { this._super(...arguments); this.getAuthors(); this.getAffiliatedInst(); } });
Fix affiliated institutions multiplying at every render
Fix affiliated institutions multiplying at every render
JavaScript
apache-2.0
Rytiggy/osfpages,caneruguz/osfpages,caneruguz/osfpages,Rytiggy/osfpages
--- +++ @@ -23,6 +23,7 @@ getAffiliatedInst: function (){ const node = this.get('node'); if (!node) { return }; + if(this.get('institutions').length > 0) { return; } const institutions = Ember.A(); loadAll(node, 'affiliatedInstitutions', institutions).then(() => { institutions.forEach((item) => {
031233307e0a4892ad4ff80372873a44d11d6fa9
tasks/serve.js
tasks/serve.js
const gulp = require('gulp'); const webpack = require('webpack'); const webpackDevMiddleware = require('webpack-dev-middleware'); const compress = require('compression'); const browserSync = require('browser-sync'); const config = require('../config'); const webpackConfig = require('../config/webpack.config'); module.exports = function serve(done) { const tasks = require('../utils/getTasks'); // eslint-disable-line global-require const compiler = webpack(webpackConfig); compiler.plugin('done', () => { browserSync.reload(); }); const middleware = [compress()]; if (config.publicPath) { middleware.push(webpackDevMiddleware(compiler, { publicPath: webpackConfig.output.publicPath, logLevel: 'silent', noInfo: true, })); } browserSync({ ...config.browserSync, middleware }); if (!config.publicPath) { gulp.watch(`${config.source}/${config.scripts.path}/**`, tasks.scripts); } gulp.watch(`${config.source}/${config.styles.path}/**`, tasks.styles); gulp.watch(`${config.source}/${config.icons.path}/**`, tasks.icons); gulp.watch(`${config.source}/${config.images.path}/**`, tasks.images); gulp.watch(config.files(config), tasks.static); done(); };
const gulp = require('gulp'); const webpack = require('webpack'); const webpackDevMiddleware = require('webpack-dev-middleware'); const compress = require('compression'); const browserSync = require('browser-sync'); const config = require('../config'); const webpackConfig = require('../config/webpack.config'); module.exports = function serve(done) { const tasks = require('../utils/getTasks'); // eslint-disable-line global-require const compiler = webpack(webpackConfig); compiler.hooks.done.tap({ name: 'BrowserSync' }, () => { browserSync.reload(); }); const middleware = [compress()]; if (config.publicPath) { middleware.push(webpackDevMiddleware(compiler, { publicPath: webpackConfig.output.publicPath, logLevel: 'silent', noInfo: true, })); } browserSync({ ...config.browserSync, middleware }); if (!config.publicPath) { gulp.watch(`${config.source}/${config.scripts.path}/**`, tasks.scripts); } gulp.watch(`${config.source}/${config.styles.path}/**`, tasks.styles); gulp.watch(`${config.source}/${config.icons.path}/**`, tasks.icons); gulp.watch(`${config.source}/${config.images.path}/**`, tasks.images); gulp.watch(config.files(config), tasks.static); done(); };
Fix Webpack Tapable deprecation warning
Fix Webpack Tapable deprecation warning
JavaScript
mit
strt/bricks
--- +++ @@ -10,7 +10,7 @@ const tasks = require('../utils/getTasks'); // eslint-disable-line global-require const compiler = webpack(webpackConfig); - compiler.plugin('done', () => { + compiler.hooks.done.tap({ name: 'BrowserSync' }, () => { browserSync.reload(); });
fb1d25a1135f41b4be2cb18f73f14b94dfc47bbf
models/ticket.js
models/ticket.js
var mongoose = require('mongoose'); var Ticket = new mongoose.Schema({ name:String, phoneNumber: String, description: String, createdAt : Date }); var ticket = mongoose.model('ticket', Ticket); module.exports = ticket;
var mongoose = require('mongoose'); var Ticket = new mongoose.Schema({ name:String, phoneNumber: String, description: String, createdAt : Date }); // Delete model definition in case it is already defined delete mongoose.models.ticket; var ticket = mongoose.model('ticket', Ticket); module.exports = ticket;
Delete cached model definition Everytime the Ticket model is defined
Delete cached model definition Everytime the Ticket model is defined
JavaScript
mit
TwilioDevEd/browser-calls-node,TwilioDevEd/browser-calls-node
--- +++ @@ -7,5 +7,8 @@ createdAt : Date }); +// Delete model definition in case it is already defined +delete mongoose.models.ticket; + var ticket = mongoose.model('ticket', Ticket); module.exports = ticket;
7e4320b1bb12ed9ada7c758ff2c9401b1149f7ae
modules/lists/list-empty.js
modules/lists/list-empty.js
// @flow import * as React from 'react' import {View, Text} from 'react-native' type Props = { mode: 'bug' | 'normal', } export class ListEmpty extends React.PureComponent<Props> { render() { return ( <View> <Text>List is empty</Text> </View> ) } }
// @flow import * as React from 'react' import {NoticeView} from '@frogpond/notice' type Props = { mode: 'bug' | 'normal', } export class ListEmpty extends React.PureComponent<Props> { render() { return <NoticeView text="List is empty" /> } }
Change the listempty component to be a noticeview
Change the listempty component to be a noticeview
JavaScript
agpl-3.0
StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native
--- +++ @@ -1,6 +1,6 @@ // @flow import * as React from 'react' -import {View, Text} from 'react-native' +import {NoticeView} from '@frogpond/notice' type Props = { mode: 'bug' | 'normal', @@ -8,10 +8,6 @@ export class ListEmpty extends React.PureComponent<Props> { render() { - return ( - <View> - <Text>List is empty</Text> - </View> - ) + return <NoticeView text="List is empty" /> } }
d13b0473314ff148146f00b60c8a3fa4dd3b26f7
tabcounter.js
tabcounter.js
'use strict'; var tabRemoved = false; browser.browserAction.setBadgeBackgroundColor({color: "gray"}); browser.tabs.onActivated.addListener(refreshCounter); browser.tabs.onCreated.addListener(refreshCounter); browser.tabs.onAttached.addListener(refreshCounter); browser.tabs.onRemoved.addListener(() => tabRemoved = true); refreshCounter(); function refreshCounter() { browser.tabs.query({currentWindow: true}).then(updateCounter, onError); } function updateCounter(tabs) { var tabCount = tabs.length; // XXX because a removed tab is still part of the "tabs" array at this time, we have to adjust the counter if (tabRemoved) { tabCount -= 1; tabRemoved = false; } browser.browserAction.setBadgeText({text: tabCount.toString(), tabId: getActiveTabId(tabs)}); } function getActiveTabId(tabs) { return tabs.filter((tab) => tab.active)[0].id; } function onError(error) { console.log(`Error: ${error}`); }
'use strict'; var tabRemoved = false; browser.browserAction.setBadgeBackgroundColor({color: "gray"}); browser.tabs.onActivated.addListener(refreshCounter); browser.tabs.onRemoved.addListener(() => tabRemoved = true); initCounter(); function initCounter() { browser.tabs.query({currentWindow: true}).then(tabs => updateCounter(getActiveTabId(tabs), tabs), onError); } function refreshCounter(tabInfo) { browser.tabs.query({windowId: tabInfo.windowId}).then(tabs => updateCounter(tabInfo.tabId, tabs), onError); } function updateCounter(tabId, tabs) { var tabCount = tabs.length; // XXX because a removed tab is still part of the "tabs" array at this time, we have to adjust the counter if (tabRemoved) { tabCount -= 1; tabRemoved = false; } browser.browserAction.setBadgeText({text: tabCount.toString(), tabId: tabId}); } function getActiveTabId(tabs) { return tabs.filter(tab => tab.active)[0].id; } function onError(error) { console.log(`Error: ${error}`); }
Fix tab counting when moving tab between windows
Fix tab counting when moving tab between windows
JavaScript
mit
cakebaker/yet-another-tab-counter
--- +++ @@ -4,17 +4,19 @@ browser.browserAction.setBadgeBackgroundColor({color: "gray"}); browser.tabs.onActivated.addListener(refreshCounter); -browser.tabs.onCreated.addListener(refreshCounter); -browser.tabs.onAttached.addListener(refreshCounter); browser.tabs.onRemoved.addListener(() => tabRemoved = true); -refreshCounter(); +initCounter(); -function refreshCounter() { - browser.tabs.query({currentWindow: true}).then(updateCounter, onError); +function initCounter() { + browser.tabs.query({currentWindow: true}).then(tabs => updateCounter(getActiveTabId(tabs), tabs), onError); } -function updateCounter(tabs) { +function refreshCounter(tabInfo) { + browser.tabs.query({windowId: tabInfo.windowId}).then(tabs => updateCounter(tabInfo.tabId, tabs), onError); +} + +function updateCounter(tabId, tabs) { var tabCount = tabs.length; // XXX because a removed tab is still part of the "tabs" array at this time, we have to adjust the counter @@ -23,11 +25,11 @@ tabRemoved = false; } - browser.browserAction.setBadgeText({text: tabCount.toString(), tabId: getActiveTabId(tabs)}); + browser.browserAction.setBadgeText({text: tabCount.toString(), tabId: tabId}); } function getActiveTabId(tabs) { - return tabs.filter((tab) => tab.active)[0].id; + return tabs.filter(tab => tab.active)[0].id; } function onError(error) {
db884e3373d9ad0440473e292dd41d41ccf93c99
test/vendor.js
test/vendor.js
;(function() { var MODULES_PATH = 'https://a.alipayobjects.com/static/arale/' if (location.href.indexOf('/~lifesinger/') > 0) { MODULES_PATH = 'http://' + location.host + '/~lifesinger/seajs/spm/modules/' } // Ref: https://github.com/miohtama/detectmobile.js function isMobile() { return Math.max(screen.availWidth || screen.availHeight) < 970 } function root(path) { return MODULES_PATH + path; } var hash = { '$': root(isMobile() ? 'zepto/0.8.0/zepto.js' : 'jquery/1.7.2/jquery.js'), 'coffee': root('coffee/1.3.3/coffee-script.js'), 'less': root('less/1.3.0/less.js') } seajs.config({ alias: hash }) define({ isMobile: isMobile() }) })()
;(function() { var MODULES_PATH = 'https://a.alipayobjects.com/static/arale/' if (location.href.indexOf('/~lifesinger/') > 0) { MODULES_PATH = 'http://' + location.host + '/~lifesinger/seajs/spm/modules/' } // Ref: https://github.com/miohtama/detectmobile.js function isMobile() { return Math.max(screen.availWidth || screen.availHeight) <= 480 } function root(path) { return MODULES_PATH + path } var hash = { '$': root(isMobile() ? 'zepto/0.8.0/zepto.js' : 'jquery/1.7.2/jquery.js'), 'coffee': root('coffee/1.3.3/coffee-script.js'), 'less': root('less/1.3.0/less.js') } seajs.config({ alias: hash }) define({ isMobile: isMobile() }) })()
Exclude pad from mobile device
Exclude pad from mobile device
JavaScript
mit
kaijiemo/seajs,miusuncle/seajs,miusuncle/seajs,LzhElite/seajs,yuhualingfeng/seajs,121595113/seajs,sheldonzf/seajs,FrankElean/SeaJS,13693100472/seajs,PUSEN/seajs,LzhElite/seajs,treejames/seajs,kuier/seajs,judastree/seajs,lianggaolin/seajs,FrankElean/SeaJS,moccen/seajs,sheldonzf/seajs,seajs/seajs,liupeng110112/seajs,imcys/seajs,121595113/seajs,hbdrawn/seajs,yern/seajs,mosoft521/seajs,tonny-zhang/seajs,zwh6611/seajs,13693100472/seajs,ysxlinux/seajs,treejames/seajs,zaoli/seajs,yern/seajs,judastree/seajs,PUSEN/seajs,angelLYK/seajs,eleanors/SeaJS,MrZhengliang/seajs,moccen/seajs,longze/seajs,jishichang/seajs,yuhualingfeng/seajs,twoubt/seajs,longze/seajs,zwh6611/seajs,kaijiemo/seajs,evilemon/seajs,evilemon/seajs,yuhualingfeng/seajs,liupeng110112/seajs,jishichang/seajs,ysxlinux/seajs,tonny-zhang/seajs,imcys/seajs,sheldonzf/seajs,eleanors/SeaJS,chinakids/seajs,chinakids/seajs,coolyhx/seajs,FrankElean/SeaJS,lianggaolin/seajs,lovelykobe/seajs,Lyfme/seajs,Lyfme/seajs,baiduoduo/seajs,zaoli/seajs,treejames/seajs,liupeng110112/seajs,ysxlinux/seajs,coolyhx/seajs,wenber/seajs,MrZhengliang/seajs,AlvinWei1024/seajs,AlvinWei1024/seajs,zaoli/seajs,uestcNaldo/seajs,seajs/seajs,JeffLi1993/seajs,twoubt/seajs,MrZhengliang/seajs,kaijiemo/seajs,Gatsbyy/seajs,moccen/seajs,longze/seajs,Lyfme/seajs,imcys/seajs,zwh6611/seajs,seajs/seajs,lee-my/seajs,miusuncle/seajs,Gatsbyy/seajs,uestcNaldo/seajs,judastree/seajs,lee-my/seajs,hbdrawn/seajs,wenber/seajs,JeffLi1993/seajs,mosoft521/seajs,mosoft521/seajs,JeffLi1993/seajs,lianggaolin/seajs,angelLYK/seajs,LzhElite/seajs,angelLYK/seajs,baiduoduo/seajs,twoubt/seajs,lovelykobe/seajs,lovelykobe/seajs,evilemon/seajs,uestcNaldo/seajs,kuier/seajs,tonny-zhang/seajs,eleanors/SeaJS,jishichang/seajs,PUSEN/seajs,AlvinWei1024/seajs,yern/seajs,lee-my/seajs,coolyhx/seajs,wenber/seajs,Gatsbyy/seajs,kuier/seajs,baiduoduo/seajs
--- +++ @@ -10,12 +10,12 @@ // Ref: https://github.com/miohtama/detectmobile.js function isMobile() { - return Math.max(screen.availWidth || screen.availHeight) < 970 + return Math.max(screen.availWidth || screen.availHeight) <= 480 } function root(path) { - return MODULES_PATH + path; + return MODULES_PATH + path }
7a933da519e0cd556ea2e79b380978b8df9787e1
node-tests/blueprints/test-helper-test.js
node-tests/blueprints/test-helper-test.js
'use strict'; var setupTestHooks = require('ember-cli-blueprint-test-helpers/lib/helpers/setup'); var BlueprintHelpers = require('ember-cli-blueprint-test-helpers/lib/helpers/blueprint-helper'); var generateAndDestroy = BlueprintHelpers.generateAndDestroy; describe('Acceptance: ember generate and destroy test-helper', function() { setupTestHooks(this); it('test-helper foo', function() { return generateAndDestroy(['test-helper', 'foo'], { files: [ { file: 'tests/helpers/foo.js', contains: [ "import Ember from 'ember';", 'export default Ember.Test.registerAsyncHelper(\'foo\', function(app) {\n\n}' ] } ] }); }); });
'use strict'; var blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers'); var setupTestHooks = blueprintHelpers.setupTestHooks; var emberNew = blueprintHelpers.emberNew; var emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy; var chai = require('ember-cli-blueprint-test-helpers/chai'); var expect = chai.expect; describe('Acceptance: ember generate and destroy test-helper', function() { setupTestHooks(this); it('test-helper foo', function() { var args = ['test-helper', 'foo']; return emberNew() .then(() => emberGenerateDestroy(args, _file => { expect(_file('tests/helpers/foo.js')) .to.contain("import Ember from 'ember';") .to.contain('export default Ember.Test.registerAsyncHelper(\'foo\', function(app) {\n\n}'); })); }); });
Use alternative blueprint test helpers
tests/test-helper: Use alternative blueprint test helpers
JavaScript
mit
ember-cli/ember-cli-legacy-blueprints,ember-cli/ember-cli-legacy-blueprints
--- +++ @@ -1,23 +1,24 @@ 'use strict'; -var setupTestHooks = require('ember-cli-blueprint-test-helpers/lib/helpers/setup'); -var BlueprintHelpers = require('ember-cli-blueprint-test-helpers/lib/helpers/blueprint-helper'); -var generateAndDestroy = BlueprintHelpers.generateAndDestroy; +var blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers'); +var setupTestHooks = blueprintHelpers.setupTestHooks; +var emberNew = blueprintHelpers.emberNew; +var emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy; + +var chai = require('ember-cli-blueprint-test-helpers/chai'); +var expect = chai.expect; describe('Acceptance: ember generate and destroy test-helper', function() { setupTestHooks(this); it('test-helper foo', function() { - return generateAndDestroy(['test-helper', 'foo'], { - files: [ - { - file: 'tests/helpers/foo.js', - contains: [ - "import Ember from 'ember';", - 'export default Ember.Test.registerAsyncHelper(\'foo\', function(app) {\n\n}' - ] - } - ] - }); + var args = ['test-helper', 'foo']; + + return emberNew() + .then(() => emberGenerateDestroy(args, _file => { + expect(_file('tests/helpers/foo.js')) + .to.contain("import Ember from 'ember';") + .to.contain('export default Ember.Test.registerAsyncHelper(\'foo\', function(app) {\n\n}'); + })); }); });
bb400919494f2805e6a4d6087602a47866d362d4
pages/article.js
pages/article.js
import React from 'react' import { connect } from 'react-redux'; import { compose } from 'redux'; import Link from 'next/link'; import app from '../components/App'; import { load } from '../redux/articleDetail'; export default compose( app((dispatch, {query: {id}}) => dispatch(load(id))), connect(({articleDetail}) => ({ isLoading: articleDetail.getIn(['state', 'isLoading']), article: articleDetail.get('data'), })), )(function Index({ isLoading = false, article = null }) { if(isLoading && article === null) { return <div>Loading...</div> } return ( <div> <Link href="/"><a>Back to list</a></Link> <pre>{JSON.stringify(article.toJS(), null, ' ')}</pre> </div> ); })
import React from 'react' import { connect } from 'react-redux'; import { compose } from 'redux'; import Link from 'next/link'; import app from '../components/App'; import { load } from '../redux/articleDetail'; export default compose( app((dispatch, {query: {id}}) => dispatch(load(id))), connect(({articleDetail}) => ({ isLoading: articleDetail.getIn(['state', 'isLoading']), article: articleDetail.get('data'), })), )(function Index({ isLoading = false, article = null }) { if(isLoading && article === null) { return <div>Loading...</div> } return ( <div> <pre>{JSON.stringify(article.toJS(), null, ' ')}</pre> </div> ); })
Remove “back to list” link because it is not accurately “back to list”
Remove “back to list” link because it is not accurately “back to list”
JavaScript
mit
cofacts/rumors-site,cofacts/rumors-site
--- +++ @@ -22,7 +22,6 @@ return ( <div> - <Link href="/"><a>Back to list</a></Link> <pre>{JSON.stringify(article.toJS(), null, ' ')}</pre> </div> );
8cea0ec1551b4b51123a6e9c25ab6fe1823c8d1e
database/seeds/users.js
database/seeds/users.js
const bcrypt = require('bcryptjs') const users = [ { username: 'kudakwashe', password: hashedPassword('kp') }, { username: 'garikai', password: hashedPassword('gg') } ] function hashedPassword (password) { return bcrypt.hashSync(password, 10) } exports.seed = (knex, Promise) => knex('users').del() .then(() => knex('users').insert(users))
const bcrypt = require('bcryptjs') const users = [ { username: 'kudakwashe', password: hashedPassword('paradzayi') }, { username: 'garikai', password: hashedPassword('rodneygg') } ] function hashedPassword (password) { return bcrypt.hashSync(password, 10) } exports.seed = (knex, Promise) => knex('users').del() .then(() => knex('users').insert(users))
Increase the length of passwords to be consistent with the vaalidation rules
Increase the length of passwords to be consistent with the vaalidation rules
JavaScript
mit
byteBridge/transcriptus-api
--- +++ @@ -3,11 +3,11 @@ const users = [ { username: 'kudakwashe', - password: hashedPassword('kp') + password: hashedPassword('paradzayi') }, { username: 'garikai', - password: hashedPassword('gg') + password: hashedPassword('rodneygg') } ]
29abdb6ceff6038cce37e9e5761513b204a08ea0
module/json_api_request.js
module/json_api_request.js
/*! * apiai * Copyright(c) 2015 http://api.ai/ * Apache 2.0 Licensed */ 'use strict'; var Request = require('./request').Request; var util = require('util'); var ServerError = require('./exceptions').ServerError; exports.JSONApiRequest = module.exports.JSONApiRequest = JSONApiRequest; util.inherits(JSONApiRequest, Request); function JSONApiRequest () { JSONApiRequest.super_.apply(this, arguments); } JSONApiRequest.prototype._handleResponse = function(response) { var self = this; var body = ''; response.on('data', function(chunk) { body += chunk; }); response.on('end', function() { if (response.statusCode >= 200 && response.statusCode <= 299) { try { var json_body = JSON.parse(body); self.emit('response', json_body); } catch (error) { // JSON.parse can throw only one exception, SyntaxError // All another exceptions throwing from user function, // because it just rethrowing for better error handling. if (error instanceof SyntaxError) { self.emit('error', error); } else { throw error; } } } else { var error = new ServerError(response.statusCode, body, 'Wrong response status code.'); self.emit('error', error); } }); };
/*! * apiai * Copyright(c) 2015 http://api.ai/ * Apache 2.0 Licensed */ 'use strict'; var Request = require('./request').Request; var util = require('util'); var ServerError = require('./exceptions').ServerError; exports.JSONApiRequest = module.exports.JSONApiRequest = JSONApiRequest; util.inherits(JSONApiRequest, Request); function JSONApiRequest () { JSONApiRequest.super_.apply(this, arguments); } JSONApiRequest.prototype._handleResponse = function(response) { var self = this; var body = ''; var buffers = []; var bufferLength = 0; response.on('data', function(chunk) { bufferLength += chunk.length; buffers.push(chunk); }); response.on('end', function() { if (bufferLength) { body = Buffer.concat(buffers, bufferLength).toString('utf8'); } buffers = []; bufferLength = 0; if (response.statusCode >= 200 && response.statusCode <= 299) { try { var json_body = JSON.parse(body); self.emit('response', json_body); } catch (error) { // JSON.parse can throw only one exception, SyntaxError // All another exceptions throwing from user function, // because it just rethrowing for better error handling. if (error instanceof SyntaxError) { self.emit('error', error); } else { throw error; } } } else { var error = new ServerError(response.statusCode, body, 'Wrong response status code.'); self.emit('error', error); } }); };
Fix issue with wrong data in response
Fix issue with wrong data in response
JavaScript
apache-2.0
dialogflow/dialogflow-nodejs-client,api-ai/api-ai-node-js,api-ai/apiai-nodejs-client,api-ai/api-ai-node-js,api-ai/apiai-nodejs-client,dialogflow/dialogflow-nodejs-client
--- +++ @@ -24,11 +24,22 @@ var body = ''; + var buffers = []; + var bufferLength = 0; + response.on('data', function(chunk) { - body += chunk; + bufferLength += chunk.length; + buffers.push(chunk); }); response.on('end', function() { + if (bufferLength) { + body = Buffer.concat(buffers, bufferLength).toString('utf8'); + } + + buffers = []; + bufferLength = 0; + if (response.statusCode >= 200 && response.statusCode <= 299) { try { var json_body = JSON.parse(body);
74b9cebd9c43e4a281ba642c9bcc20f24411a801
src/runner/install/package-json.js
src/runner/install/package-json.js
import path from 'path' import json from '../../util/json' const saguiScripts = { 'build': 'sagui build', 'develop': 'sagui develop --port 3000', 'dist': 'NODE_ENV=production sagui build --optimize', 'start': 'npm run develop', 'test': 'npm run test:lint && npm run test:unit', 'test:lint': 'sagui lint', 'test:unit': 'NODE_ENV=test sagui test', 'test:coverage': 'npm run test:unit -- --coverage', 'test:unit:watch': 'npm run test -- --watch' } export default function (projectPath) { const packagePath = path.join(projectPath, 'package.json') const packageJSON = json.read(packagePath) json.write(packagePath, { ...packageJSON, scripts: { ...saguiScripts, ...withoutDefaults(packageJSON.scripts) } }) } /** * Remove default configurations generated by NPM that can be overwriten * We don't want to overwrite any user configured scripts */ function withoutDefaults (scripts = {}) { const defaultScripts = { 'test': 'echo "Error: no test specified" && exit 1' } return Object.keys(scripts) .filter((key) => !scripts[key] !== '' && scripts[key] !== defaultScripts[key]) .reduce((filtered, key) => { return { ...filtered, [key]: scripts[key] } }, {}) }
import path from 'path' import json from '../../util/json' const saguiScripts = { 'build': 'sagui build', 'develop': 'sagui develop --port 3000', 'dist': 'NODE_ENV=production sagui build --optimize', 'start': 'npm run develop', 'test': 'npm run test:lint && npm run test:unit', 'test:coverage': 'npm run test:unit -- --coverage', 'test:lint': 'sagui lint', 'test:unit': 'NODE_ENV=test sagui test', 'test:unit:watch': 'npm run test:unit -- --watch' } export default function (projectPath) { const packagePath = path.join(projectPath, 'package.json') const packageJSON = json.read(packagePath) json.write(packagePath, { ...packageJSON, scripts: { ...saguiScripts, ...withoutDefaults(packageJSON.scripts) } }) } /** * Remove default configurations generated by NPM that can be overwriten * We don't want to overwrite any user configured scripts */ function withoutDefaults (scripts = {}) { const defaultScripts = { 'test': 'echo "Error: no test specified" && exit 1' } return Object.keys(scripts) .filter((key) => !scripts[key] !== '' && scripts[key] !== defaultScripts[key]) .reduce((filtered, key) => { return { ...filtered, [key]: scripts[key] } }, {}) }
Fix bootstrapped `test:unit:watch` npm script 🐛
Fix bootstrapped `test:unit:watch` npm script 🐛
JavaScript
mit
saguijs/sagui,saguijs/sagui
--- +++ @@ -7,10 +7,10 @@ 'dist': 'NODE_ENV=production sagui build --optimize', 'start': 'npm run develop', 'test': 'npm run test:lint && npm run test:unit', + 'test:coverage': 'npm run test:unit -- --coverage', 'test:lint': 'sagui lint', 'test:unit': 'NODE_ENV=test sagui test', - 'test:coverage': 'npm run test:unit -- --coverage', - 'test:unit:watch': 'npm run test -- --watch' + 'test:unit:watch': 'npm run test:unit -- --watch' } export default function (projectPath) {
00216ffd2ba8907d5c70ff067f4bf9fa051027f8
server/controllers/Book.js
server/controllers/Book.js
import omit from 'lodash/omit'; import db from '../models'; const { User } = db; export default { create(req, res) { return User .create(req.userInput) .then((user) => { const data = omit(user.dataValues, [ 'password' ]); return res.status(201).send({ message: 'Book Uploaded Successfully!', data }) .catch(error => res.status(400).send(error)); }, };
import db from '../models'; const { Book } = db; export default { create(req, res) { return Book .create(req.userInput) .then(() => { return res.status(201).send({ success: true, message: 'Book uploaded successfully', }); }) .catch(error => res.status(400).send(error)); }, };
Add book route and creator
Add book route and creator
JavaScript
mit
nosisky/Hello-Books,nosisky/Hello-Books
--- +++ @@ -1,19 +1,16 @@ -import omit from 'lodash/omit'; import db from '../models'; -const { User } = db; +const { Book } = db; export default { create(req, res) { - return User + return Book .create(req.userInput) - .then((user) => { - const data = omit(user.dataValues, [ - 'password' - ]); + .then(() => { return res.status(201).send({ - message: 'Book Uploaded Successfully!', - data - }) + success: true, + message: 'Book uploaded successfully', + }); + }) .catch(error => res.status(400).send(error)); }, };
b4c5139d53430ae26bb869d621cfbdfa9f3124ec
src/testUtils/warningFreeBasics.js
src/testUtils/warningFreeBasics.js
/** * Test for a few basic patterns that usually should * case no warnings. * * This should not be used by rules that intentionally * warn for these cases. */ export default function (tr) { tr.ok("", "empty stylesheet") tr.ok("a {}", "empty rule set") tr.ok("@import \"foo.css\";", "blockless statement") }
/** * Test for a few basic patterns that usually should * case no warnings. * * This should not be used by rules that intentionally * warn for these cases. */ export default function (tr) { tr.ok("", "empty stylesheet") tr.ok("a {}", "empty rule set") tr.ok (":global {}", "CSS Modules global empty rule set") tr.ok("@import \"foo.css\";", "blockless statement") }
Add :global to basic tests
Add :global to basic tests
JavaScript
mit
gaidarenko/stylelint,gucong3000/stylelint,stylelint/stylelint,stylelint/stylelint,hudochenkov/stylelint,gucong3000/stylelint,heatwaveo8/stylelint,hudochenkov/stylelint,heatwaveo8/stylelint,heatwaveo8/stylelint,stylelint/stylelint,m-allanson/stylelint,gucong3000/stylelint,gaidarenko/stylelint,evilebottnawi/stylelint,stylelint/stylelint,evilebottnawi/stylelint,gaidarenko/stylelint,hudochenkov/stylelint
--- +++ @@ -8,5 +8,6 @@ export default function (tr) { tr.ok("", "empty stylesheet") tr.ok("a {}", "empty rule set") + tr.ok (":global {}", "CSS Modules global empty rule set") tr.ok("@import \"foo.css\";", "blockless statement") }
c062c2af8e43790759194633fe6bff6b098d4933
src/adhocracy_frontend/adhocracy_frontend/tests/acceptance/EmbeddedSharePage.js
src/adhocracy_frontend/adhocracy_frontend/tests/acceptance/EmbeddedSharePage.js
"use strict"; var shared = require("./shared.js"); var EmbeddedSharePage = function() { this.url = "/embed/social-share"; this.dummyTweetButton = element(by.css(".tweet.dummy_btn")); this.dummyFacebookLikeButton = element(by.css(".fb_like.dummy_btn")); this.get = function() { browser.get(this.url); return this; } this.clickDummyTweetButton = function() { this.dummyTweetButton.click(); }; this.getTwitterIframe = function() { return this.dummyTweetButton.element(by.css("iframe")); }; this.clickDummyFacebookLikeButton = function() { this.dummyFacebookLikeButton.click(); }; this.getFacebookIframe = function() { return this.dummyFacebookLikeButton.element(by.css("iframe")); }; }; module.exports = EmbeddedSharePage;
"use strict"; var shared = require("./shared.js"); var EmbeddedSharePage = function() { this.url = "/embed/social-share"; this.dummyTweetButton = element(by.css(".tweet.dummy_btn")); this.dummyFacebookLikeButton = element(by.css(".fb_like.dummy_btn")); this.get = function() { browser.get(this.url); return this; } this.clickDummyTweetButton = function() { this.dummyTweetButton.click(); browser.waitForAngular(); }; this.getTwitterIframe = function() { return this.dummyTweetButton.element(by.css("iframe")); }; this.clickDummyFacebookLikeButton = function() { this.dummyFacebookLikeButton.click(); }; this.getFacebookIframe = function() { return this.dummyFacebookLikeButton.element(by.css("iframe")); }; }; module.exports = EmbeddedSharePage;
Fix Twitter share test not deterministic
Fix Twitter share test not deterministic
JavaScript
agpl-3.0
xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator
--- +++ @@ -14,6 +14,7 @@ this.clickDummyTweetButton = function() { this.dummyTweetButton.click(); + browser.waitForAngular(); }; this.getTwitterIframe = function() {
c80bd1e6459211f35f3f7676c11e62e132f91c27
src/main/web/florence/js/functions/_makeEditSections.js
src/main/web/florence/js/functions/_makeEditSections.js
function makeEditSections(collectionName, response) { if (response.type === 'bulletin') { bulletinEditor(collectionName, response); } else { $('.fl-editor__sections').hide(); $("#addSection").remove(); $('.fl-editor__headline').show().val(JSON.stringify(response, null, 2)); $('.fl-panel--editor__nav__save').unbind("click").click(function () { pageData = $('.fl-editor__headline').val(); updateContent(collectionName, getPathName(), pageData); }); // complete $('.fl-panel--editor__nav__complete').unbind("click").click(function () { pageData = $('.fl-editor__headline').val(); saveAndCompleteContent(collectionName, getPathName(), pageData); }); } }
function makeEditSections(collectionName, response, path) { if (response.type === 'bulletin') { bulletinEditor(collectionName, response); } else { $('.fl-editor__sections').hide(); $("#addSection").remove(); $('.fl-editor__headline').show().val(JSON.stringify(response, null, 2)); $('.fl-panel--editor__nav__save').unbind("click").click(function () { pageData = $('.fl-editor__headline').val(); updateContent(collectionName, path, pageData); }); $('.fl-panel--editor__nav__complete').unbind("click").click(function () { pageData = $('.fl-editor__headline').val(); saveAndCompleteContent(collectionName, path, pageData); }); } $('.fl-panel--editor__nav__review').unbind("click").click(function () { postReview(collectionName, path); }); }
Attach click handler to submit for review button to call API.
Attach click handler to submit for review button to call API.
JavaScript
mit
ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence
--- +++ @@ -1,4 +1,5 @@ -function makeEditSections(collectionName, response) { +function makeEditSections(collectionName, response, path) { + if (response.type === 'bulletin') { bulletinEditor(collectionName, response); } else { @@ -8,15 +9,16 @@ $('.fl-panel--editor__nav__save').unbind("click").click(function () { pageData = $('.fl-editor__headline').val(); - updateContent(collectionName, getPathName(), pageData); + updateContent(collectionName, path, pageData); }); - // complete $('.fl-panel--editor__nav__complete').unbind("click").click(function () { pageData = $('.fl-editor__headline').val(); - saveAndCompleteContent(collectionName, getPathName(), pageData); + saveAndCompleteContent(collectionName, path, pageData); }); } - + $('.fl-panel--editor__nav__review').unbind("click").click(function () { + postReview(collectionName, path); + }); }
e130009deb5af19ae8de099dc38d81ae076f12f7
djplaces/static/js/djplaces.js
djplaces/static/js/djplaces.js
$(document).ready(function() { $("#id_place") .geocomplete({ map: "#map_location", mapOptions: { zoom: 10 }, markerOptions: { draggable: true } }) .bind("geocode:result", function(event, result) { var coordinates = result.geometry.location.lat() + ',' + result.geometry.location.lng(); $('#id_location').val(coordinates); }) .bind("geocode:error", function(event, status){ console.log("ERROR: " + status); }) .bind("geocode:multiple", function(event, results){ console.log("Multiple: " + results.length + " results found"); }); });
$(document).ready(function() { $("#id_place") .geocomplete({ map: "#map_location", mapOptions: { zoom: 10 }, markerOptions: { draggable: true } }) .bind("geocode:result", function(event, result) { $('#id_location').val(result.geometry.location.lat() + ',' + result.geometry.location.lng()); }) .bind("geocode:error", function(event, status){ console.log("ERROR: " + status); }) .bind("geocode:multiple", function(event, results){ console.log("Multiple: " + results.length + " results found"); }) .bind("geocode:dragged", function(event, latLng){ $('#id_location').val(latLng.lat() + ',' + latLng.lng()); }); });
Update lat and lng on marker dragged
Update lat and lng on marker dragged
JavaScript
mit
oscarmcm/django-places,oscarmcm/django-places,oscarmcm/django-places
--- +++ @@ -3,22 +3,20 @@ $("#id_place") .geocomplete({ map: "#map_location", - mapOptions: { - zoom: 10 - }, - markerOptions: { - draggable: true - } + mapOptions: { zoom: 10 }, + markerOptions: { draggable: true } }) .bind("geocode:result", function(event, result) { - var coordinates = result.geometry.location.lat() + ',' + result.geometry.location.lng(); - $('#id_location').val(coordinates); + $('#id_location').val(result.geometry.location.lat() + ',' + result.geometry.location.lng()); }) .bind("geocode:error", function(event, status){ console.log("ERROR: " + status); }) .bind("geocode:multiple", function(event, results){ console.log("Multiple: " + results.length + " results found"); + }) + .bind("geocode:dragged", function(event, latLng){ + $('#id_location').val(latLng.lat() + ',' + latLng.lng()); }); });
71a1c4a3fe010a3f79ea83a4271b6240f5c9c0a8
app/models/post.js
app/models/post.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var safeOpts = { j: 1, w: "majority", wtimeout: 10000 }; var postSchema = new Schema({ saved_at: { type: Date, default: Date.now, required: true}, created_at: { type: Date, required: true}, created_at_i: { type: Number, required: true}, url: String, title: String, story_title: String, author: String, num_comments: Number }, { safe: safeOpts }); module.exports = postSchema;
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var safeOpts = { j: 1, w: "majority", wtimeout: 10000 }; var postSchema = new Schema({ saved_at: { type: Date, default: Date.now, required: true}, created_at: { type: Date, required: true}, created_at_i: { type: Number, required: true}, url: String, title: String, story_title: String, author: String, num_comments: Number }, { safe: safeOpts }); var Post = mongoose.model('Post', postSchema); module.exports = Post;
Add model, not only the schema
Add model, not only the schema
JavaScript
mit
dburgos/HN-feed,dburgos/HN-feed
--- +++ @@ -17,4 +17,6 @@ num_comments: Number }, { safe: safeOpts }); -module.exports = postSchema; +var Post = mongoose.model('Post', postSchema); + +module.exports = Post;
7f511555f48096c94aeaefd0254d43f8bcf672fc
app/models/task.js
app/models/task.js
import DS from "ember-data"; import Ember from "ember"; import config from '../config/environment'; export default DS.Model.extend( { prerequisities: DS.attr("prerequisite"), state: DS.attr("string"), active: Ember.computed("state", function() { return ["base", "correcting", "done"].indexOf(this.get("state")) > -1; }), title: DS.attr("string"), author: DS.belongsTo("user", { async: true }), co_author: DS.belongsTo("user", { async: true }), intro: DS.attr("string"), max_score: DS.attr("number"), time_deadline: DS.attr("date"), time_published: DS.attr("date"), wave: DS.belongsTo("wave", { async: true }), picture_base: DS.attr("string"), picture_suffix: DS.attr("string"), picture: Ember.computed("picture_base", "picture_suffix", "active", "state", function() { if(!this.get("active")) { return config.API_LOC + this.get("picture_base") + "locked" + this.get("picture_suffix"); } return config.API_LOC + this.get("picture_base") + this.get("state") + this.get("picture_suffix"); }), details: DS.belongsTo("task-detail", {async: true}) });
import DS from "ember-data"; import Ember from "ember"; import config from '../config/environment'; export default DS.Model.extend( { prerequisities: DS.attr("prerequisite"), state: DS.attr("string"), active: Ember.computed("state", function() { return ["base", "correcting", "done"].indexOf(this.get("state")) > -1; }), title: DS.attr("string"), author: DS.belongsTo("user", { async: true }), co_author: DS.belongsTo("user", { async: true }), intro: DS.attr("string"), max_score: DS.attr("number"), time_deadline: DS.attr("date"), time_published: DS.attr("date"), wave: DS.belongsTo("wave", { async: true }), picture_base: DS.attr("string"), picture_suffix: DS.attr("string"), picture: Ember.computed("picture_base", "picture_suffix", "active", "state", function() { if(!this.get("picture_base")) { return undefined; } if(!this.get("active")) { return config.API_LOC + this.get("picture_base") + "locked" + this.get("picture_suffix"); } return config.API_LOC + this.get("picture_base") + this.get("state") + this.get("picture_suffix"); }), details: DS.belongsTo("task-detail", {async: true}) });
Fix CSP violation on profile.
Fix CSP violation on profile.
JavaScript
mit
fi-ksi/web-frontend,fi-ksi/web-frontend,fi-ksi/web-frontend
--- +++ @@ -26,6 +26,9 @@ picture: Ember.computed("picture_base", "picture_suffix", "active", "state", function() { + if(!this.get("picture_base")) { + return undefined; + } if(!this.get("active")) { return config.API_LOC + this.get("picture_base") + "locked" + this.get("picture_suffix"); }
e6ef64968bc99b6f8ed30fb0f1a581bc78763a97
tests/configs/modules/weather/currentweather_options.js
tests/configs/modules/weather/currentweather_options.js
/* Magic Mirror Test config default weather * * By fewieden https://github.com/fewieden * * MIT Licensed. */ let config = { port: 8080, ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"], language: "en", timeFormat: 24, units: "metric", electronOptions: { webPreferences: { nodeIntegration: true } }, modules: [ { module: "weather", position: "bottom_bar", config: { location: "Munich", apiKey: "fake key", initialLoadDelay: 3000, useBeaufort: false, showWindDirectionAsArrow: true, showHumidity: true, roundTemp: true, degreeLabel: true } } ] }; /*************** DO NOT EDIT THE LINE BELOW ***************/ if (typeof module !== "undefined") { module.exports = config; }
/* Magic Mirror Test config default weather * * By fewieden https://github.com/fewieden * * MIT Licensed. */ let config = { port: 8080, ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"], language: "en", timeFormat: 24, units: "metric", electronOptions: { webPreferences: { nodeIntegration: true } }, modules: [ { module: "weather", position: "bottom_bar", config: { location: "Munich", apiKey: "fake key", initialLoadDelay: 3000, useBeaufort: false, showWindDirectionAsArrow: true, showSun: false, showHumidity: true, roundTemp: true, degreeLabel: true } } ] }; /*************** DO NOT EDIT THE LINE BELOW ***************/ if (typeof module !== "undefined") { module.exports = config; }
Disable Sunrise/Sunset in Config option
Disable Sunrise/Sunset in Config option
JavaScript
mit
MichMich/MagicMirror,MichMich/MagicMirror,Tyvonne/MagicMirror,MichMich/MagicMirror,Tyvonne/MagicMirror,Tyvonne/MagicMirror,MichMich/MagicMirror,Tyvonne/MagicMirror
--- +++ @@ -28,6 +28,7 @@ initialLoadDelay: 3000, useBeaufort: false, showWindDirectionAsArrow: true, + showSun: false, showHumidity: true, roundTemp: true, degreeLabel: true
11e185860f52757c013f64221927f0b605805cd1
.htmlhintrc.js
.htmlhintrc.js
const htmlHintConfig = require('kolibri-tools/.htmlhintrc'); htmlHintConfig['--vue-component-conventions'] = false; module.exports = htmlHintConfig;
const htmlHintConfig = require('kolibri-tools/.htmlhintrc'); htmlHintConfig['id-class-value'] = false; htmlHintConfig['--vue-component-conventions'] = false; module.exports = htmlHintConfig;
Disable html hint class value check
Disable html hint class value check Vuetify helper classes contain double dashes, e.g. grey--text.
JavaScript
mit
DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation
--- +++ @@ -1,3 +1,4 @@ const htmlHintConfig = require('kolibri-tools/.htmlhintrc'); +htmlHintConfig['id-class-value'] = false; htmlHintConfig['--vue-component-conventions'] = false; module.exports = htmlHintConfig;
144874d96097be560057901149af29fe65bf57ba
packages/test/testserver.js
packages/test/testserver.js
#!/usr/bin/env node /** * Minimal server for local, manual web page testing. */ 'use strict'; // eslint-disable-line const portfinder = require('portfinder'); const http = require('http'); const path = require('path'); const nodeStatic = require('node-static'); const webroot = path.resolve(process.argv[2]); portfinder.basePort = Number(process.env.PORT) || 1234; const fileServer = new nodeStatic.Server(webroot, { cache: false }); const server = http.createServer((req, res) => { req.on('end', () => { fileServer.serve(req, res, (err) => { if (err) { console.error(`Error serving ${req.url} - ${err.message}`); res.writeHead(err.status, err.headers); res.end(); } }); }).resume(); }); portfinder .getPortPromise() .then((port) => { server.listen(port, () => { console.log(`\nTesting server running on http://localhost:${port}`); }); }) .catch((err) => { throw err; }); process.on('SIGINT', () => { console.log('\nServer terminated'); try { server.close(() => { process.exit(0); }); } catch (err) { console.error(err); process.exit(1); } });
#!/usr/bin/env node /** * Minimal server for local, manual web page testing. */ /* eslint-disable strict, no-console *//* tslint:disable no-console */ 'use strict'; const portfinder = require('portfinder'); const http = require('http'); const path = require('path'); const nodeStatic = require('node-static'); const webroot = path.resolve(process.argv[2]); portfinder.basePort = Number(process.env.PORT) || 1234; const fileServer = new nodeStatic.Server(webroot, { cache: false }); const server = http.createServer((req, res) => { req.on('end', () => { fileServer.serve(req, res, (err) => { if (err) { console.error(`Error serving ${req.url} - ${err.message}`); res.writeHead(err.status, err.headers); res.end(); } }); }).resume(); }); portfinder .getPortPromise() .then((port) => { server.listen(port, () => { console.log(`\nTesting server running on http://localhost:${port}`); }); }) .catch((err) => { throw err; }); process.on('SIGINT', () => { console.log('\nServer terminated'); try { server.close(() => { process.exit(0); }); } catch (err) { console.error(err); process.exit(1); } });
Fix lint errors in test server
Fix lint errors in test server
JavaScript
isc
WeAreGenki/wag-ui
--- +++ @@ -4,7 +4,9 @@ * Minimal server for local, manual web page testing. */ -'use strict'; // eslint-disable-line +/* eslint-disable strict, no-console *//* tslint:disable no-console */ + +'use strict'; const portfinder = require('portfinder'); const http = require('http');
5c4981122946fbbe8c8bcece6ebc959dd942aa76
client.js
client.js
var configUtils = _altboilerScope.configUtils /* Wait until the client-side configuration has been done */ addEventListener('load', function () { var showLoader = altboiler.getConfig('showLoader') /* Clear the object */ altboiler.tmpConf = {} /* Don't do anything if the loader should be shown */ if(configUtils.isTruthy(showLoader)) return /* Load the static CSS defined for the altboiler */ document.head.innerHTML += ['<link rel="stylesheet" type="text/css" href="', '">'] .join(altboiler.getConfig('routes').css) })
var configUtils = _altboilerScope.configUtils /* Wait until the client-side configuration has been done */ addEventListener('load', function () { var showLoader = altboiler.getConfig('showLoader') var styles /* Clear the object */ altboiler.tmpConf = {} /* Don't do anything if the loader should be shown */ if(configUtils.isTruthy(showLoader)) return /* Load the static CSS defined for the altboiler */ styles = document.createElement('link') styles.rel = 'stylesheet' styles.type = 'text/css' styles.href = altboiler.getConfig('routes').styles document.head.appendChild(styles) })
Fix the path to the linked loader css
Fix the path to the linked loader css
JavaScript
mit
Kriegslustig/meteor-altboiler,Kriegslustig/meteor-altboiler
--- +++ @@ -3,13 +3,16 @@ /* Wait until the client-side configuration has been done */ addEventListener('load', function () { var showLoader = altboiler.getConfig('showLoader') + var styles /* Clear the object */ altboiler.tmpConf = {} /* Don't do anything if the loader should be shown */ if(configUtils.isTruthy(showLoader)) return /* Load the static CSS defined for the altboiler */ - document.head.innerHTML += - ['<link rel="stylesheet" type="text/css" href="', '">'] - .join(altboiler.getConfig('routes').css) + styles = document.createElement('link') + styles.rel = 'stylesheet' + styles.type = 'text/css' + styles.href = altboiler.getConfig('routes').styles + document.head.appendChild(styles) })
a288ab32b8b5c5e6e545739cbb480b16cc00da22
src/main/web/florence/js/functions/_viewTeams.js
src/main/web/florence/js/functions/_viewTeams.js
function viewTeams() { getTeams( success = function (data) { populateTeamsTable(data.teams); }, error = function (jqxhr) { handleApiError(jqxhr); } ); function populateTeamsTable(data) { var teams = _.sortBy(data, function (d) { return d.name.toLowerCase() }); var teamsHtml = templates.teamList(teams); $('.section').html(teamsHtml); $('.js-selectable-table tbody tr').click(function () { var teamId = $(this).attr('data-id'); viewTeamDetails(teamId, $(this)); }); $('.form-create-team').submit(function (e) { e.preventDefault(); var teamName = $('#create-team-name').val(); if (teamName.length < 1) { sweetAlert("Please enter a user name."); return; } teamName = teamName.trim(); postTeam(teamName); }); } }
function viewTeams() { getTeams( success = function (data) { populateTeamsTable(data.teams); }, error = function (jqxhr) { handleApiError(jqxhr); } ); function populateTeamsTable(data) { var teamsHtml = templates.teamList(teams); $('.section').html(teamsHtml); $('.js-selectable-table tbody tr').click(function () { var teamId = $(this).attr('data-id'); viewTeamDetails(teamId, $(this)); }); $('.form-create-team').submit(function (e) { e.preventDefault(); var teamName = $('#create-team-name').val(); if (teamName.length < 1) { sweetAlert("Please enter a user name."); return; } teamName = teamName.trim(); postTeam(teamName); }); } }
Remove client side ordering of teams list (fixed in zebedee now)
Remove client side ordering of teams list (fixed in zebedee now)
JavaScript
mit
ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence
--- +++ @@ -10,9 +10,6 @@ ); function populateTeamsTable(data) { - var teams = _.sortBy(data, function (d) { - return d.name.toLowerCase() - }); var teamsHtml = templates.teamList(teams); $('.section').html(teamsHtml);
16737528b47ed1b7e91e06cf9927f5acb0465e6a
demos/events/06-musical-data/script.js
demos/events/06-musical-data/script.js
var pianoKeys = document.querySelectorAll('.piano-key'); for (var i = 0; i < pianoKeys.length; i++) { pianoKeys[i].addEventListener('click', function (event) { var note = this.getAttribute('data-piano-key'); playNote(note); }); }
// Write an event listener for each key that looks at the data-piano-key of the // element that was clicked and passes that note to the playNote global function
Remove solution code for data-attributes demo
Remove solution code for data-attributes demo
JavaScript
mpl-2.0
joshcass/advanced-js-fundamentals-ck,mdn/advanced-js-fundamentals-ck,mdn/advanced-js-fundamentals-ck,joshcass/advanced-js-fundamentals-ck
--- +++ @@ -1,10 +1,2 @@ -var pianoKeys = document.querySelectorAll('.piano-key'); - -for (var i = 0; i < pianoKeys.length; i++) { - - pianoKeys[i].addEventListener('click', function (event) { - var note = this.getAttribute('data-piano-key'); - playNote(note); - }); - -} +// Write an event listener for each key that looks at the data-piano-key of the +// element that was clicked and passes that note to the playNote global function
010fc67d6558cb35f6810d00ac4fcb62092c75fa
lib/node_modules/@stdlib/math/base/dist/betaprime/lib/index.js
lib/node_modules/@stdlib/math/base/dist/betaprime/lib/index.js
'use strict'; /* * When adding modules to the namespace, ensure that they are added in alphabetical order according to module name. */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); // MAIN // /** * Top-level namespace. * * @namespace betaprime */ var betaprime = {}; /** * @name mean * @memberof betaprime * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/dist/betaprime/mean} */ setReadOnly( betaprime, 'mean', require( '@stdlib/math/base/dist/betaprime/mean' ) ); // EXPORTS // module.exports = betaprime;
'use strict'; /* * When adding modules to the namespace, ensure that they are added in alphabetical order according to module name. */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); // MAIN // /** * Top-level namespace. * * @namespace betaprime */ var betaprime = {}; /** * @name mean * @memberof betaprime * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/dist/betaprime/mean} */ setReadOnly( betaprime, 'mean', require( '@stdlib/math/base/dist/betaprime/mean' ) ); /** * @name variance * @memberof betaprime * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/dist/betaprime/variance} */ setReadOnly( betaprime, 'variance', require( '@stdlib/math/base/dist/betaprime/variance' ) ); // EXPORTS // module.exports = betaprime;
Add variance to beta prime namespace
Add variance to beta prime namespace
JavaScript
apache-2.0
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
--- +++ @@ -27,6 +27,15 @@ */ setReadOnly( betaprime, 'mean', require( '@stdlib/math/base/dist/betaprime/mean' ) ); +/** +* @name variance +* @memberof betaprime +* @readonly +* @type {Function} +* @see {@link module:@stdlib/math/base/dist/betaprime/variance} +*/ +setReadOnly( betaprime, 'variance', require( '@stdlib/math/base/dist/betaprime/variance' ) ); + // EXPORTS //
094b42ab7dd77ead37bb8160d0001343c4347972
imports/startup/client/index.js
imports/startup/client/index.js
// PhantomJS does not support web fonts if (Meteor.isTest == false) { WebFontConfig = { google: { families: [ 'Oswald:300,400' ] } }; (function() { var wf = document.createElement('script'); wf.src = '//ajax.googleapis.com/ajax/libs/webfont/1.6.16/webfont.js'; wf.type = 'text/javascript'; wf.async = 'true'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(wf, s); })(); }
// PhantomJS does not support web fonts WebFontConfig = { google: { families: [ 'Oswald:300,400' ] } }; (function() { var wf = document.createElement('script'); wf.src = '//ajax.googleapis.com/ajax/libs/webfont/1.6.16/webfont.js'; wf.type = 'text/javascript'; wf.async = 'true'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(wf, s); })();
Remove the clause around the font loader since it wasn't working anyway.
Remove the clause around the font loader since it wasn't working anyway.
JavaScript
mit
howlround/worldtheatremap,howlround/worldtheatremap
--- +++ @@ -1,14 +1,12 @@ // PhantomJS does not support web fonts -if (Meteor.isTest == false) { - WebFontConfig = { - google: { families: [ 'Oswald:300,400' ] } - }; - (function() { - var wf = document.createElement('script'); - wf.src = '//ajax.googleapis.com/ajax/libs/webfont/1.6.16/webfont.js'; - wf.type = 'text/javascript'; - wf.async = 'true'; - var s = document.getElementsByTagName('script')[0]; - s.parentNode.insertBefore(wf, s); - })(); -} +WebFontConfig = { + google: { families: [ 'Oswald:300,400' ] } +}; +(function() { + var wf = document.createElement('script'); + wf.src = '//ajax.googleapis.com/ajax/libs/webfont/1.6.16/webfont.js'; + wf.type = 'text/javascript'; + wf.async = 'true'; + var s = document.getElementsByTagName('script')[0]; + s.parentNode.insertBefore(wf, s); +})();
cc5410b3b4860862d41da79a569ae8eeb268d23e
client/js/controllers/auth.js
client/js/controllers/auth.js
angular .module('app') .controller('AuthLoginController', ['$scope', 'AuthService', '$state', function ($scope, AuthService, $state) { $scope.login = function () { AuthService.login($scope.user.username, $scope.user.email, $scope.user.password) .then(function () { $state.go('area-clienti-inizio'); }); }; }]) .controller('AuthLogoutController', ['$scope', 'AuthService', '$state', function ($scope, AuthService, $state) { AuthService.logout() .then(function () { $state.go('home'); }); }]) .controller('SignUpController', ['$scope', 'AuthService', '$state', function ($scope, AuthService, $state) { $scope.register = function () { AuthService.register($scope.user.username, $scope.user.email, $scope.user.password) .then(function () { $state.transitionTo('sign-up-success'); }); }; }]);
angular .module('app') .controller('AuthLoginController', ['$scope', 'AuthService', '$state', function ($scope, AuthService, $state) { $scope.login = function () { AuthService.login($scope.user.username, $scope.user.email, $scope.user.password) .then(function () { $state.go('area-clienti'); }); }; }]) .controller('AuthLogoutController', ['$scope', 'AuthService', '$state', function ($scope, AuthService, $state) { AuthService.logout() .then(function () { $state.go('home'); }); }]) .controller('SignUpController', ['$scope', 'AuthService', '$state', function ($scope, AuthService, $state) { $scope.register = function () { AuthService.register($scope.user.username, $scope.user.email, $scope.user.password) .then(function () { $state.transitionTo('sign-up-success'); }); }; }]);
Fix an error on login
Fix an error on login
JavaScript
mit
dev-augmenta/vrseum-backend,dev-augmenta/vrseum-backend
--- +++ @@ -5,7 +5,7 @@ $scope.login = function () { AuthService.login($scope.user.username, $scope.user.email, $scope.user.password) .then(function () { - $state.go('area-clienti-inizio'); + $state.go('area-clienti'); }); }; }])
d93d4dd2b4300641505509191956b42c8a132a87
static/js/drop_points.js
static/js/drop_points.js
/* vim: set expandtab ts=4 sw=4: */
var last_update = Date.now()/1000; function refresh_drop_points() { return $.ajax({ type: "POST", url: apiurl, data: { action: "dp_json", ts: last_update }, success: function (response) { last_update = Date.now() / 1000; drop_points = $.extend(drop_points, response); if (typeof map != "undefined") { for (var num in response) { redraw_marker(num, response[num].last_state); } } }, complete: function () { setTimeout(function() { refresh_drop_points() }, 120000); }, dataType: "json" }); } setTimeout(function() { refresh_drop_points() }, 120000); /* vim: set expandtab ts=4 sw=4: */
Add stupid polling for changes via API
Add stupid polling for changes via API
JavaScript
mit
der-michik/c3bottles,der-michik/c3bottles,der-michik/c3bottles,der-michik/c3bottles
--- +++ @@ -1 +1,29 @@ +var last_update = Date.now()/1000; + +function refresh_drop_points() { + return $.ajax({ + type: "POST", + url: apiurl, + data: { + action: "dp_json", + ts: last_update + }, + success: function (response) { + last_update = Date.now() / 1000; + drop_points = $.extend(drop_points, response); + if (typeof map != "undefined") { + for (var num in response) { + redraw_marker(num, response[num].last_state); + } + } + }, + complete: function () { + setTimeout(function() { refresh_drop_points() }, 120000); + }, + dataType: "json" + }); +} + +setTimeout(function() { refresh_drop_points() }, 120000); + /* vim: set expandtab ts=4 sw=4: */
55230781219ec63c6e95c0fd94a632b4c9677180
stories/setup.stories.js
stories/setup.stories.js
/** * External dependencies */ import { storiesOf } from '@storybook/react'; /** * Internal dependencies */ import Setup from '../assets/js/components/setup'; storiesOf( 'Setup', module ) .add( 'Step one', () => { global.googlesitekit.setup.isSiteKitConnected = false; global.googlesitekit.setup.authenticated = false; global.googlesitekit.setup.isVerified = false; global.googlesitekit.setup.hasSearchConsoleProperty = false; global.googlesitekit.permissions.canSetup = true; return ( <Setup /> ); } );
/** * External dependencies */ import { storiesOf } from '@storybook/react'; /** * Internal dependencies */ import Setup from '../assets/js/components/setup'; storiesOf( 'Setup', module ) .add( 'Step one', () => { global.googlesitekit.setup.isSiteKitConnected = false; global.googlesitekit.setup.isAuthenticated = false; global.googlesitekit.setup.isVerified = false; global.googlesitekit.setup.hasSearchConsoleProperty = false; global.googlesitekit.permissions.canSetup = true; return ( <Setup /> ); } );
Revert change to global name.
Revert change to global name.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
--- +++ @@ -11,7 +11,7 @@ storiesOf( 'Setup', module ) .add( 'Step one', () => { global.googlesitekit.setup.isSiteKitConnected = false; - global.googlesitekit.setup.authenticated = false; + global.googlesitekit.setup.isAuthenticated = false; global.googlesitekit.setup.isVerified = false; global.googlesitekit.setup.hasSearchConsoleProperty = false; global.googlesitekit.permissions.canSetup = true;
415bf090411644dc2844b4a86a7d38b3fae6667a
packages/pg/lib/index.js
packages/pg/lib/index.js
'use strict' var Client = require('./client') var defaults = require('./defaults') var Connection = require('./connection') var Pool = require('pg-pool') const poolFactory = (Client) => { return class BoundPool extends Pool { constructor(options) { super(options, Client) } } } var PG = function (clientConstructor) { this.defaults = defaults this.Client = clientConstructor this.Query = this.Client.Query this.Pool = poolFactory(this.Client) this._pools = [] this.Connection = Connection this.types = require('pg-types') } if (typeof process.env.NODE_PG_FORCE_NATIVE !== 'undefined') { module.exports = new PG(require('./native')) } else { module.exports = new PG(Client) // lazy require native module...the native module may not have installed Object.defineProperty(module.exports, 'native', { configurable: true, enumerable: false, get() { var native = null try { native = new PG(require('./native')) } catch (err) { if (err.code !== 'MODULE_NOT_FOUND') { throw err } /* eslint-disable no-console */ console.error(err.message) /* eslint-enable no-console */ } // overwrite module.exports.native so that getter is never called again Object.defineProperty(module.exports, 'native', { value: native, }) return native }, }) }
'use strict' var Client = require('./client') var defaults = require('./defaults') var Connection = require('./connection') var Pool = require('pg-pool') const poolFactory = (Client) => { return class BoundPool extends Pool { constructor(options) { super(options, Client) } } } var PG = function (clientConstructor) { this.defaults = defaults this.Client = clientConstructor this.Query = this.Client.Query this.Pool = poolFactory(this.Client) this._pools = [] this.Connection = Connection this.types = require('pg-types') } if (typeof process.env.NODE_PG_FORCE_NATIVE !== 'undefined') { module.exports = new PG(require('./native')) } else { module.exports = new PG(Client) // lazy require native module...the native module may not have installed Object.defineProperty(module.exports, 'native', { configurable: true, enumerable: false, get() { var native = null try { native = new PG(require('./native')) } catch (err) { if (err.code !== 'MODULE_NOT_FOUND') { throw err } } // overwrite module.exports.native so that getter is never called again Object.defineProperty(module.exports, 'native', { value: native, }) return native }, }) }
Remove console.error on pg-native module not found
Remove console.error on pg-native module not found
JavaScript
mit
brianc/node-postgres,brianc/node-postgres
--- +++ @@ -40,9 +40,6 @@ if (err.code !== 'MODULE_NOT_FOUND') { throw err } - /* eslint-disable no-console */ - console.error(err.message) - /* eslint-enable no-console */ } // overwrite module.exports.native so that getter is never called again
2094436175c4a3c2482b974700ac2202a1a4b6a8
errors.js
errors.js
(function(root) { if (typeof exports !== 'undefined') { var _ = require('underscore'); var util = require('./util') } else { var util = Substance.util; } var errors = {}; SubstanceError = function(name, code, message) { this.message = message; this.name = name; this.code = code; this.stack = util.callstack(1); }; SubstanceError.prototype = { toString: function() { return this.name+":"+this.message; }, toJSON: function() { return { name: this.name, message: this.message, code: this.code, stack: this.stack }; }, printStackTrace: function() { for (var idx = 0; idx < this.stack.length; idx++) { var s = this.stack[idx]; console.log(s.file+":"+s.line+":"+s.col, "("+s.func+")"); } } } errors.define = function(className, code) { errors[className] = SubstanceError.bind(null, className, code); errors[className].prototype = SubstanceError.prototype; } if (typeof exports === 'undefined') { if (!root.Substance) root.Substance = {}; root.Substance.errors = errors; } else { module.exports = errors; } })(this);
(function(root) { if (typeof exports !== 'undefined') { var _ = require('underscore'); var util = require('./util') } else { var util = Substance.util; } var errors = {}; SubstanceError = function(name, code, message) { this.message = message; this.name = name; this.code = code; this.stack = util.callstack(1); }; SubstanceError.prototype = { toString: function() { return this.name+":"+this.message; }, toJSON: function() { return { name: this.name, message: this.message, code: this.code, stack: this.stack }; }, printStackTrace: function() { for (var idx = 0; idx < this.stack.length; idx++) { var s = this.stack[idx]; console.log(s.file+":"+s.line+":"+s.col, "("+s.func+")"); } } } errors.define = function(className, code) { errors[className] = SubstanceError.bind(null, className, code); errors[className].prototype = SubstanceError.prototype; return errors[className]; } if (typeof exports === 'undefined') { if (!root.Substance) root.Substance = {}; root.Substance.errors = errors; } else { module.exports = errors; } })(this);
Return a freshly defined error class.
Return a freshly defined error class.
JavaScript
mit
substance/util
--- +++ @@ -40,6 +40,8 @@ errors.define = function(className, code) { errors[className] = SubstanceError.bind(null, className, code); errors[className].prototype = SubstanceError.prototype; + + return errors[className]; } if (typeof exports === 'undefined') {
75bbb60783f5decc00ece0cf80cb590b5dfbafef
test/scripts/preview.js
test/scripts/preview.js
const mocha = require('mocha'); const assert = require('assert'); const path = require('path'); const fs = require('fs'); const describe = mocha.describe; const it = mocha.it; const allResumes = require('./allResumes'); describe('npm run preview', () => { it('should have generated the png files', () => { const resumes = allResumes(); resumes.forEach(resume => { const p = path.join(__dirname, '../../src/assets/preview/resume-' + resume.path + '.png'); assert.ok(fs.existsSync(p)); }); }); });
const mocha = require('mocha'); const assert = require('assert'); const path = require('path'); const fs = require('fs'); const describe = mocha.describe; const it = mocha.it; const allResumes = require('./allResumes'); describe('npm run preview', () => { it('should have generated the png files', () => { setTimeout(() => { const resumes = allResumes(); resumes.forEach(resume => { const p = path.join(__dirname, '../../src/assets/preview/resume-' + resume.path + '.png'); assert.ok(fs.existsSync(p)); }); }, 20000); }); });
ADD sleep before running test
ADD sleep before running test
JavaScript
mit
salomonelli/best-resume-ever,salomonelli/best-resume-ever
--- +++ @@ -8,10 +8,12 @@ describe('npm run preview', () => { it('should have generated the png files', () => { - const resumes = allResumes(); - resumes.forEach(resume => { - const p = path.join(__dirname, '../../src/assets/preview/resume-' + resume.path + '.png'); - assert.ok(fs.existsSync(p)); - }); + setTimeout(() => { + const resumes = allResumes(); + resumes.forEach(resume => { + const p = path.join(__dirname, '../../src/assets/preview/resume-' + resume.path + '.png'); + assert.ok(fs.existsSync(p)); + }); + }, 20000); }); });
d6f57a39a457e800a87fec02d3c5cc6800cdd6d0
test/svg-test-helper.js
test/svg-test-helper.js
import $ from "cheerio"; const SvgTestHelper = { RECTANGULAR_SEQUENCE: ["M", "L", "L", "L", "L"], expectIsRectangular(wrapper) { expect(exhibitsRectangularDirectionSequence(wrapper)).to.be.true; } }; function exhibitsRectangularDirectionSequence(wrapper) { const commands = getPathCommandsFromWrapper(wrapper); return commands.every((command, index) => { return command.name === SvgTestHelper.RECTANGULAR_SEQUENCE[index]; }); } function getPathCommandsFromWrapper(wrapper) { const commandStr = $(wrapper.html()).attr("d"); return parseSvgPathCommands(commandStr); } function parseSvgPathCommands(commandStr) { const matches = commandStr.match( /[MmLlHhVvCcSsQqTtAaZz]+[^MmLlHhVvCcSsQqTtAaZz]*/g ); return matches.map(match => { const name = match.charAt(0); const args = match.substring(1).split(",").map(arg => parseFloat(arg, 10)); return { raw: match, name, args } }); } export default SvgTestHelper;
import $ from "cheerio"; const RECTANGULAR_SEQUENCE = ["M", "L", "L", "L", "L"]; const CIRCULAR_SEQUENCE = ["M", "m", "a", "a"]; const SvgTestHelper = { expectIsRectangular(wrapper) { expect(exhibitsShapeSequence(wrapper, RECTANGULAR_SEQUENCE)).to.be.true; }, expectIsCircular(wrapper) { expect(exhibitsShapeSequence(wrapper, CIRCULAR_SEQUENCE)).to.be.true; } }; function exhibitsShapeSequence(wrapper, shapeSequence) { const commands = getPathCommandsFromWrapper(wrapper); return commands.every((command, index) => { return command.name === shapeSequence[index]; }); } function getPathCommandsFromWrapper(wrapper) { const commandStr = $(wrapper.html()).attr("d"); return parseSvgPathCommands(commandStr); } function parseSvgPathCommands(commandStr) { const matches = commandStr.match( /[MmLlHhVvCcSsQqTtAaZz]+[^MmLlHhVvCcSsQqTtAaZz]*/g ); return matches.map(match => { const name = match.charAt(0); const args = match.substring(1).split(",").map(arg => parseFloat(arg, 10)); return { raw: match, name, args } }); } export default SvgTestHelper;
Refactor and add circular shape helper
Refactor and add circular shape helper
JavaScript
mit
FormidableLabs/victory-chart,GreenGremlin/victory-chart,FormidableLabs/victory-chart,GreenGremlin/victory-chart
--- +++ @@ -1,17 +1,22 @@ import $ from "cheerio"; +const RECTANGULAR_SEQUENCE = ["M", "L", "L", "L", "L"]; +const CIRCULAR_SEQUENCE = ["M", "m", "a", "a"]; + const SvgTestHelper = { - RECTANGULAR_SEQUENCE: ["M", "L", "L", "L", "L"], + expectIsRectangular(wrapper) { + expect(exhibitsShapeSequence(wrapper, RECTANGULAR_SEQUENCE)).to.be.true; + }, - expectIsRectangular(wrapper) { - expect(exhibitsRectangularDirectionSequence(wrapper)).to.be.true; + expectIsCircular(wrapper) { + expect(exhibitsShapeSequence(wrapper, CIRCULAR_SEQUENCE)).to.be.true; } }; -function exhibitsRectangularDirectionSequence(wrapper) { +function exhibitsShapeSequence(wrapper, shapeSequence) { const commands = getPathCommandsFromWrapper(wrapper); return commands.every((command, index) => { - return command.name === SvgTestHelper.RECTANGULAR_SEQUENCE[index]; + return command.name === shapeSequence[index]; }); }
afdf568adcb412eb2c37bb9a516696f12f381000
karma.conf.js
karma.conf.js
module.exports = function(config) { config.set({ basePath: '', frameworks: ['mocha'], webpack: { mode: 'development', module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/env'], plugins: ['@babel/plugin-proposal-export-default-from'] } } }, { test: /\.html$/, use: { loader: 'raw-loader' } } ] } }, files: [ 'app/bootstrap/css/bootstrap.min.css', 'app/fontawesome/css/font-awesome.min.css', 'dist/formio.full.min.css', { pattern: 'dist/fonts/*', watched: false, included: false, served: true, nocache: false }, { pattern: 'dist/icons/*', watched: false, included: false, served: true, nocache: false }, 'src/**/*.spec.js' ], exclude: [ ], preprocessors: { 'src/**/*.spec.js': ['webpack'] }, browserNoActivityTimeout: 30000, reporters: ['mocha'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, concurrency: Infinity }); };
module.exports = function(config) { const { KARMA_FILE = 'src/**/*.spec.js' } = process.env; const FILE = KARMA_FILE || 'src/**/*.spec.js'; config.set({ basePath: '', frameworks: ['mocha'], webpack: { mode: 'development', module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/env'], plugins: ['@babel/plugin-proposal-export-default-from'] } } }, { test: /\.html$/, use: { loader: 'raw-loader' } } ] } }, files: [ 'app/bootstrap/css/bootstrap.min.css', 'app/fontawesome/css/font-awesome.min.css', 'dist/formio.full.min.css', { pattern: 'dist/fonts/*', watched: false, included: false, served: true, nocache: false }, { pattern: 'dist/icons/*', watched: false, included: false, served: true, nocache: false }, FILE ], exclude: [ ], preprocessors: { [FILE]: ['webpack'] }, browserNoActivityTimeout: 30000, reporters: ['mocha'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, concurrency: Infinity }); };
Add ability to set karma file through env
Add ability to set karma file through env
JavaScript
mit
formio/formio.js,formio/formio.js,formio/formio.js
--- +++ @@ -1,4 +1,6 @@ module.exports = function(config) { + const { KARMA_FILE = 'src/**/*.spec.js' } = process.env; + const FILE = KARMA_FILE || 'src/**/*.spec.js'; config.set({ basePath: '', frameworks: ['mocha'], @@ -44,12 +46,12 @@ served: true, nocache: false }, - 'src/**/*.spec.js' + FILE ], exclude: [ ], preprocessors: { - 'src/**/*.spec.js': ['webpack'] + [FILE]: ['webpack'] }, browserNoActivityTimeout: 30000, reporters: ['mocha'],
d2d0a8a4f911d6a46cf4def218dabc9ca2c50ed4
workshop/www/js/recipe.js
workshop/www/js/recipe.js
recipe.js
var Recipe = function(data){ this.title = data.Title; this.ingredients = []; this.instructions = data.Instructions; this.prepTime = data.TotalMinutes; this.yieldNumber = data.YieldNumber; this.yieldUnit = data.YieldUnit; this.stars = data.StarRating; this.instructions = data.Instructions; this.imageUrl = data.ImageURL } function BigOvenGetRecipeJson(recipeId) { var apiKey = APIKEY; var url = "https://api.bigoven.com/recipe/" + recipeId + "?api_key="+apiKey; $.ajax({ type: "GET", dataType: 'json', cache: false, url: url }).then(function(data) { var currentRecipe = new Recipe(data); }); }; $(document).ready(function(){ BigOvenGetRecipeJson(100); });
Create Recipe class to wrap desired JSON data from 2nd API call
Create Recipe class to wrap desired JSON data from 2nd API call All attributes for Recipe object, created on invocation of BigOvenGetRecipeJson function, are functional except for ingredients, which requires creation of new JS constructors.
JavaScript
mit
danasselin/line-cook,nyc-rock-doves-2015/line-cook,nyc-rock-doves-2015/line-cook,nyc-rock-doves-2015/line-cook,danasselin/line-cook,danasselin/line-cook,danasselin/line-cook,nyc-rock-doves-2015/line-cook,nyc-rock-doves-2015/line-cook,danasselin/line-cook,danasselin/line-cook,nyc-rock-doves-2015/line-cook,danasselin/line-cook,nyc-rock-doves-2015/line-cook,danasselin/line-cook,nyc-rock-doves-2015/line-cook
--- +++ @@ -1 +1,29 @@ -recipe.js +var Recipe = function(data){ + this.title = data.Title; + this.ingredients = []; + this.instructions = data.Instructions; + this.prepTime = data.TotalMinutes; + this.yieldNumber = data.YieldNumber; + this.yieldUnit = data.YieldUnit; + this.stars = data.StarRating; + this.instructions = data.Instructions; + this.imageUrl = data.ImageURL +} + +function BigOvenGetRecipeJson(recipeId) { + var apiKey = APIKEY; + var url = "https://api.bigoven.com/recipe/" + recipeId + "?api_key="+apiKey; + + $.ajax({ + type: "GET", + dataType: 'json', + cache: false, + url: url + }).then(function(data) { + var currentRecipe = new Recipe(data); + }); +}; + +$(document).ready(function(){ + BigOvenGetRecipeJson(100); +});
a164d5fdd4ab443abd63042737d91706e7559350
js/map.js
js/map.js
var atlas = {}; function initMap() { atlas = L.map('atlas').setView([40, -100], 4); L.tileLayer('//stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.png').addTo(atlas); } function buildMap() { console.log(data.maps); _.each(data.maps, function(map) { var options = { className: 'atlas--map-area', fill: false }; var rect = L.rectangle([ [map.bottom, map.left], [map.top, map.right] ]).toGeoJSON(); L.geoJson(rect, { style: function(f) { return { fill: false, className: 'atlas--map-area' } }, onEachFeature: function(f, l) { l.on({ click: function() { $(document).trigger('select:', this) }, mouseover: function() { $(document).trigger('highlight:', this) } }); } }).addTo(atlas); }); }
var atlas = {}; function initMap() { atlas = L.map('atlas').setView([40, -100], 4); L.tileLayer('//stamen-tiles-{s}.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}.png').addTo(atlas); } function buildMap() { console.log(data.maps); _.each(data.maps, function(map) { var options = { className: 'atlas--map-area', fill: false }; var rect = L.rectangle([ [map.bottom, map.left], [map.top, map.right] ]).toGeoJSON(); rect.properties = { number: parseInt(map.number) } L.geoJson(rect, { style: function(f) { return { fill: false, className: 'atlas--map-area' } }, onEachFeature: function(f, l) { l.on({ click: function() { $(document).trigger('select:', f.properties.number) }, mouseover: function() { $(document).trigger('highlight:', f.properties.number) } }); } }).addTo(atlas); }); }
Send correct number to highlight and select functions
Send correct number to highlight and select functions
JavaScript
mit
axismaps/tile-browser,axismaps/tile-browser
--- +++ @@ -18,7 +18,11 @@ [map.bottom, map.left], [map.top, map.right] ]).toGeoJSON(); - + + rect.properties = { + number: parseInt(map.number) + } + L.geoJson(rect, { style: function(f) { return { @@ -28,8 +32,8 @@ }, onEachFeature: function(f, l) { l.on({ - click: function() { $(document).trigger('select:', this) }, - mouseover: function() { $(document).trigger('highlight:', this) } + click: function() { $(document).trigger('select:', f.properties.number) }, + mouseover: function() { $(document).trigger('highlight:', f.properties.number) } }); } }).addTo(atlas);
0154b921fa55444bb09dffb5e2f09382cc780def
exercises/buffer_concat/solution/solution.js
exercises/buffer_concat/solution/solution.js
var buffers = []; process.stdin.on('readable', function(chunk) { var chunk = process.stdin.read(); if (chunk !== null) { buffers.push(chunk); } }); process.stdin.on('end', function() { console.log(Buffer.concat(buffers)); });
var buffers = []; process.stdin.on('readable', function() { var chunk = process.stdin.read(); if (chunk !== null) { buffers.push(chunk); } }); process.stdin.on('end', function() { console.log(Buffer.concat(buffers)); });
Remove unnecessary argument to 'readable' callback
Remove unnecessary argument to 'readable' callback
JavaScript
bsd-2-clause
karissa/bytewiser,karissa/bytewiser,maxogden/bytewiser,maxogden/bytewiser
--- +++ @@ -1,6 +1,6 @@ var buffers = []; -process.stdin.on('readable', function(chunk) { +process.stdin.on('readable', function() { var chunk = process.stdin.read(); if (chunk !== null) { buffers.push(chunk);
670580b52e520b42698ab80f02fe9fb8df6c8b50
external/amber-cli/tests/amberVersionTest.js
external/amber-cli/tests/amberVersionTest.js
// Tests if the `amber version` command returns the expected amber version number, according to the configuration file `package.json` // Displays 'ok' in green if test succeeds, else 'not ok' in red. require('shelljs/global'); require('colors'); var JSON_PACKAGE_PATH = '../package.json'; // {amber directory}/external/amber-cli/package.json var AMBER_VERSION_COMMAND = './support/amber-cli.js version'; var amberResult = exec("node " + AMBER_VERSION_COMMAND, {silent: true}).output; var expectedAmberVersion = require(JSON_PACKAGE_PATH).version; // tests if expected amber version is in the result of `amber version` command if (amberResult.indexOf(expectedAmberVersion) > -1) { console.log("ok 1 - amber version".green); exit(0); } else { console.log(amberResult.red); console.log(("not ok 1 - amber version\n\texpected : " + expectedAmberVersion).red); exit(1); }
// Tests if the `amber version` command returns the expected amber version number, according to the configuration file `package.json` // Displays 'ok' in green if test succeeds, else 'not ok' in red. require('shelljs/global'); require('colors'); var AMBER_VERSION_COMMAND = './support/amber-cli.js version'; var amberResult = exec("node " + AMBER_VERSION_COMMAND, {silent: true}).output; if (amberResult.match(/[Aa]mber/) && amberResult.match(/version/)) { console.log("ok 1 - amber version".green); exit(0); } else { console.log(amberResult.red); console.log(("not ok 1 - amber version".red); exit(1); }
Fix amber version smoke test - cannot test actual version
Fix amber version smoke test - cannot test actual version Version presented by amber cli is the version of amber it was compiled with, not version of amber-cli itself.
JavaScript
mit
adrian-castravete/amber,adrian-castravete/amber,amber-smalltalk/amber,adrian-castravete/amber,amber-smalltalk/amber,amber-smalltalk/amber
--- +++ @@ -4,18 +4,15 @@ require('shelljs/global'); require('colors'); -var JSON_PACKAGE_PATH = '../package.json'; // {amber directory}/external/amber-cli/package.json var AMBER_VERSION_COMMAND = './support/amber-cli.js version'; var amberResult = exec("node " + AMBER_VERSION_COMMAND, {silent: true}).output; -var expectedAmberVersion = require(JSON_PACKAGE_PATH).version; -// tests if expected amber version is in the result of `amber version` command -if (amberResult.indexOf(expectedAmberVersion) > -1) { +if (amberResult.match(/[Aa]mber/) && amberResult.match(/version/)) { console.log("ok 1 - amber version".green); exit(0); } else { console.log(amberResult.red); - console.log(("not ok 1 - amber version\n\texpected : " + expectedAmberVersion).red); + console.log(("not ok 1 - amber version".red); exit(1); }