commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
c21d52d96ec21d9a43da3467ee66364619e1e3f4
app/containers/FlagView.js
app/containers/FlagView.js
import React from 'react'; import { connect } from 'react-redux'; import admin from '../utils/admin'; import Concept from '../components/Concept'; const FlagView = React.createClass({ componentWillMount() { this.props.fetchFlags(); }, render() { const { flags } = this.props; return ( <div className="FlagView"> {flags.map((flag) => <div style={{ borderBottom: '1px solid #ccc' }}> <Concept concept={flag.origin}/> {flag.type} ({flag.value}) <Concept concept={flag.target}/> </div> )} </div> ); }, }); export default connect( (state) => { const { data: { flags } } = state; return { flags: flags.data, }; }, { fetchFlags: admin.actions.flags, } )(FlagView);
import React from 'react'; import { connect } from 'react-redux'; import admin from '../utils/admin'; import Concept from '../components/Concept'; const FlagView = React.createClass({ componentWillMount() { this.props.fetchFlags(); }, render() { const { flags } = this.props; return ( <div className="FlagView"> {flags.map((flag) => <div style={{ borderBottom: '1px solid #ccc' }} key={flag.id}> <Concept concept={flag.origin}/> {flag.type} ({flag.value}) <Concept concept={flag.target}/> </div> )} </div> ); }, }); export default connect( (state) => { const { data: { flags } } = state; return { flags: flags.data, }; }, { fetchFlags: admin.actions.flags, } )(FlagView);
Add missing key to flags view to remove warning
Add missing key to flags view to remove warning
JavaScript
mit
transparantnederland/relationizer,transparantnederland/relationizer,waagsociety/tnl-relationizer,transparantnederland/browser,transparantnederland/browser,waagsociety/tnl-relationizer
9730bfb3db49d210d496e2289bf90154ab497612
scripts/components/Footer.js
scripts/components/Footer.js
import { format } from 'date-fns'; import React from 'react' import { Navigation } from './blocks/Navigation' import styles from './Main.css' const socialLinks = [ { to: 'https://stackoverflow.com/story/usehotkey', title: 'StackOverflow' }, // { // to: 'https://yadi.sk/d/QzyQ04br3HXrmU', // title: 'CV' // }, { to: 'https://www.linkedin.com/in/igor-golopolosov-98382012a/', title: 'LinkedIn' }, { to: 'https://github.com/usehotkey', title: 'GitHub' }, // { // to: 'https://soundcloud.com/hotkeymusic', // title: 'SoundCloud' // }, ] export const Footer = () => { return ( <footer className={styles.footer}> <div className={styles.socialNav}> <Navigation links={socialLinks} external /> </div> <div> <small> {`Igor Golopolosov, 2016-${format(new Date(), 'YYYY')} ♥️`} <b>[email protected]</b> </small> </div> </footer> ) }
import { format } from 'date-fns'; import React from 'react' import { Navigation } from './blocks/Navigation' import styles from './Main.css' const socialLinks = [ { to: 'https://stackoverflow.com/story/usehotkey', title: 'StackOverflow' }, // { // to: 'https://yadi.sk/d/QzyQ04br3HXrmU', // title: 'CV' // }, { to: 'https://www.linkedin.com/in/igor-golopolosov-98382012a/', title: 'LinkedIn' }, { to: 'https://github.com/usehotkey', title: 'GitHub' }, // { // to: 'https://soundcloud.com/hotkeymusic', // title: 'SoundCloud' // }, ] export const Footer = () => { return ( <footer className={styles.footer}> <div className={styles.socialNav}> <Navigation links={socialLinks} external /> </div> <small> {`Igor Golopolosov, ${format(new Date(), 'YYYY')} ♥️`} <b>[email protected]</b> </small> </footer> ) }
Remove first year from footer
[change] Remove first year from footer
JavaScript
mit
usehotkey/my-personal-page,usehotkey/my-personal-page,usehotkey/my-personal-page,usehotkey/my-personal-page
ad207a87639cef156201b8e2a208f38c51e93c50
src/js/math.js
src/js/math.js
import THREE from 'three'; export function randomPointOnSphere( vector = new THREE.Vector3() ) { const theta = 2 * Math.PI * Math.random(); const u = 2 * Math.random() - 1; const v = Math.sqrt( 1 - u * u ); return vector.set( v * Math.cos( theta ), v * Math.sin( theta ), u ); }
import THREE from 'three'; export function randomPointOnSphere( vector = new THREE.Vector3() ) { const theta = 2 * Math.PI * Math.random(); const u = 2 * Math.random() - 1; const v = Math.sqrt( 1 - u * u ); return vector.set( v * Math.cos( theta ), v * Math.sin( theta ), u ); } export function lerp( a, b, t ) { return a + t * ( b - a ); } export function inverseLerp( a, b, x ) { return ( x - a ) / ( b - a ); } export function map( x, a, b, c, d ) { return lerp( c, d, inverseLerp( a, b, x ) ); }
Add 1D lerp(), inverseLerp(), and map().
Add 1D lerp(), inverseLerp(), and map().
JavaScript
mit
razh/flying-machines,razh/flying-machines
20c0f4d04aa9581a717741bb1be7f73167e358b0
optional.js
optional.js
module.exports = function(module, options){ try{ if(module[0] in {".":1}){ module = process.cwd() + module.substr(1); } return require(module); }catch(e){ if (err.code !== "MODULE_NOT_FOUND" && options && options.rethrow) { throw err; } } return null; };
module.exports = function(module, options){ try{ if(module[0] in {".":1}){ module = process.cwd() + module.substr(1); } return require(module); }catch(err){ if (err.code !== "MODULE_NOT_FOUND" && options && options.rethrow) { throw err; } } return null; };
Fix a typo (`e` -> `err`)
Fix a typo (`e` -> `err`)
JavaScript
mit
tony-o/node-optional,peerbelt/node-optional
e057cdfb71ccd2f7d70157ccac728736fbcad450
tests/plugins/front-matter.js
tests/plugins/front-matter.js
import test from 'ava'; import {fromString, fromNull, fromStream} from '../helpers/pipe'; import fm from '../../lib/plugins/front-matter'; test('No Compile - null', t => { return fromNull(fm) .then(output => { t.is(output, '', 'No output'); }); }); test('Error - is stream', t => { t.throws(fromStream(fm)); });
import test from 'ava'; import {fromString} from '../helpers/pipe'; import plugin from '../helpers/plugin'; import fm from '../../lib/plugins/front-matter'; test('Extracts Front Matter', t => { const input = `--- foo: bar baz: - qux - where - waldo more: good: stuff: - lives: here - and: here --- # Hello World`; const expectedMeta = { foo: 'bar', baz: [ 'qux', 'where', 'waldo', ], more: { good: { stuff: [ { lives: 'here', }, { and: 'here', }, ], }, }, }; const expectedBody = '# Hello World'; return fromString(input, 'markdown/hello.md', fm) .then(output => { expectedMeta.today = output.meta.today; t.true(output.meta.hasOwnProperty('today'), 'Contains the time'); t.deepEqual(output.meta, expectedMeta, 'Front matter transformed in to usable object'); t.is(output.contents.toString(), expectedBody); }); }); test('No Front Matter', t => { const input = `# Hello World`; const expected = '# Hello World'; return fromString(input, 'markdown/hello.md', fm) .then(output => { t.true(output.meta.hasOwnProperty('today'), 'Contains the time'); t.is(output.contents.toString(), expected); }); }); plugin(fm, test);
Add tests for actual FM
:white_check_mark: Add tests for actual FM
JavaScript
mit
Snugug/gulp-armadillo,kellychurchill/gulp-armadillo
2aec558cb2518426284b0a6bca79ab87178a5ccb
TrackedViews.js
TrackedViews.js
/** * @flow */ import React, { Component, Text, View, } from 'react-native'; import {registerView, unregisterView} from './ViewTracker' /** * Higher-order component that turns a built-in View component into a component * that is tracked with the key specified in the viewKey prop. If the viewKey * prop is not specified, then no tracking is done. */ const createTrackedView = (ViewComponent: any) => class TrackedComponent extends Component { componentDidMount() { const {viewKey} = this.props; if (viewKey) { registerView(viewKey, this.refs.viewRef); } } componentWillUnmount() { const {viewKey} = this.props; if (viewKey) { unregisterView(viewKey, this.refs.viewRef); } } render() { const {viewKey, ...childProps} = this.props; return <ViewComponent ref="viewRef" {...childProps} /> } }; export const TrackedView = createTrackedView(View); export const TrackedText = createTrackedView(Text);
/** * @flow */ import React, { Component, Text, View, } from 'react-native'; import {registerView, unregisterView} from './ViewTracker' /** * Higher-order component that turns a built-in View component into a component * that is tracked with the key specified in the viewKey prop. If the viewKey * prop is not specified, then no tracking is done. */ const createTrackedView = (ViewComponent: any) => class TrackedComponent extends Component { componentDidMount() { const {viewKey} = this.props; if (viewKey) { registerView(viewKey, this.refs.viewRef); } } componentWillUpdate(nextProps: any) { const {viewKey} = this.props; if (viewKey && !viewKey.equals(nextProps.viewKey)) { unregisterView(viewKey, this.refs.viewRef); } } componentDidUpdate(prevProps: any) { const {viewKey} = this.props; if (viewKey && !viewKey.equals(prevProps.viewKey)) { registerView(viewKey, this.refs.viewRef); } } componentWillUnmount() { const {viewKey} = this.props; if (viewKey) { unregisterView(viewKey, this.refs.viewRef); } } render() { const {viewKey, ...childProps} = this.props; return <ViewComponent ref="viewRef" {...childProps} /> } }; export const TrackedView = createTrackedView(View); export const TrackedText = createTrackedView(Text);
Fix crash when dragging definitions
Fix crash when dragging definitions I was accidentally updating the view key for a view, and the tracked view code couldn't handle prop changes.
JavaScript
mit
alangpierce/LambdaCalculusPlayground,alangpierce/LambdaCalculusPlayground,alangpierce/LambdaCalculusPlayground
11215560382e5c0b4484019dbf8541351337f7fb
src/mixins/size.js
src/mixins/size.js
draft.mixins.size = { // Get/set the element's width & height size(width, height) { return this.prop({ width: draft.types.length(width), height: draft.types.length(height) // depth: draft.types.length(depth) }); } };
draft.mixins.size = { // Get/set the element's width & height size(width, height) { return this.prop({ width: draft.types.length(width), height: draft.types.length(height) // depth: draft.types.length(depth) }); }, scale(width, height) { return this.prop({ width: this.prop('width') * width || undefined, height: this.prop('height') * height || undefined // depth: this.prop('depth') * depth || undefined }); } };
Add scale() function for relative sizing
Add scale() function for relative sizing
JavaScript
mit
D1SC0tech/draft.js,D1SC0tech/draft.js
b24cd5018185dc2ef35598a7cae863322d89c8c7
app/scripts/fixBackground.js
app/scripts/fixBackground.js
'use strict'; var fixBackground = function(){ var backgroundImage = document.getElementById('page-background-img'); if(window.innerHeight >= backgroundImage.height) { backgroundImage.style.height = '100%'; backgroundImage.style.width = null; } if(window.innerWidth >= backgroundImage.width) { backgroundImage.style.width = '100%'; backgroundImage.style.height = null; } }; window.onresize = fixBackground; window.onload = fixBackground;
'use strict'; var fixBackground = function(){ var backgroundImage = document.getElementById('page-background-img'); if(window.innerHeight >= backgroundImage.height) { backgroundImage.style.height = '100%'; backgroundImage.style.width = null; } if(window.innerWidth >= backgroundImage.width) { backgroundImage.style.width = '100%'; backgroundImage.style.height = null; } }; document.getElementById('page-background-img').ondragstart = function() { return false; }; window.onresize = fixBackground; window.onload = fixBackground;
Disable image grab event for background
Disable image grab event for background
JavaScript
mit
Pozo/elvira-redesign
31fe75787678465efcfd10dafbb9c368f72d9758
hbs-builder.js
hbs-builder.js
define(["handlebars-compiler"], function (Handlebars) { var buildMap = {}, templateExtension = ".hbs"; return { // http://requirejs.org/docs/plugins.html#apiload load: function (name, parentRequire, onload, config) { // Get the template extension. var ext = (config.hbs && config.hbs.templateExtension ? config.hbs.templateExtension : templateExtension); // Use node.js file system module to load the template. // Sorry, no Rhino support. var fs = nodeRequire("fs"); var fsPath = config.dirBaseUrl + "/" + name + ext; buildMap[name] = fs.readFileSync(fsPath).toString(); onload(); }, // http://requirejs.org/docs/plugins.html#apiwrite write: function (pluginName, name, write) { var compiled = Handlebars.precompile(buildMap[name]); // Write out precompiled version of the template function as AMD // definition. write( "define('hbs!" + name + "', ['handlebars'], function(Handlebars){ \n" + "return Handlebars.template(" + compiled.toString() + ");\n" + "});\n" ); } }; });
define(["handlebars-compiler"], function (Handlebars) { var buildMap = {}, templateExtension = ".hbs"; return { // http://requirejs.org/docs/plugins.html#apiload load: function (name, parentRequire, onload, config) { // Get the template extension. var ext = (config.hbs && config.hbs.templateExtension ? config.hbs.templateExtension : templateExtension); // Use node.js file system module to load the template. // Sorry, no Rhino support. var fs = nodeRequire("fs"); var fsPath = config.dirBaseUrl + "/" + name + ext; buildMap[name] = fs.readFileSync(fsPath).toString(); parentRequire(["handlebars"], function () { onload(); }); }, // http://requirejs.org/docs/plugins.html#apiwrite write: function (pluginName, name, write) { var compiled = Handlebars.precompile(buildMap[name]); // Write out precompiled version of the template function as AMD // definition. write( "define('hbs!" + name + "', ['handlebars'], function(Handlebars){ \n" + "return Handlebars.template(" + compiled.toString() + ");\n" + "});\n" ); } }; });
Include handlebars module in build process
Include handlebars module in build process
JavaScript
mit
designeng/requirejs-hbs,designeng/requirejs-hbs,designeng/requirejs-hbs
695f3c5607fae90b13fe6c85ffd6412afcaff0bf
packages/react-app-rewired/index.js
packages/react-app-rewired/index.js
const babelLoaderMatcher = function(rule) { return rule.loader && rule.loader.indexOf("/babel-loader/") != -1; } const getLoader = function(rules, matcher) { var loader; rules.some(rule => { return loader = matcher(rule) ? rule : getLoader(rule.use || rule.oneOf || [], matcher); }); return loader; }; const getBabelLoader = function(rules) { return getLoader(rules, babelLoaderMatcher); } const injectBabelPlugin = function(pluginName, config) { const loader = getBabelLoader(config.module.rules); if (!loader) { console.log("babel-loader not found"); return config; } loader.options.plugins = [pluginName].concat(loader.options.plugins || []); return config; }; module.exports = { getLoader, getBabelLoader, injectBabelPlugin };
const babelLoaderMatcher = function(rule) { return rule.loader && rule.loader.indexOf("babel-loader/") != -1; } const getLoader = function(rules, matcher) { var loader; rules.some(rule => { return loader = matcher(rule) ? rule : getLoader(rule.use || rule.oneOf || [], matcher); }); return loader; }; const getBabelLoader = function(rules) { return getLoader(rules, babelLoaderMatcher); } const injectBabelPlugin = function(pluginName, config) { const loader = getBabelLoader(config.module.rules); if (!loader) { console.log("babel-loader not found"); return config; } loader.options.plugins = [pluginName].concat(loader.options.plugins || []); return config; }; module.exports = { getLoader, getBabelLoader, injectBabelPlugin };
Fix babelLoaderMatcher for other npm install tool
Fix babelLoaderMatcher for other npm install tool like https://github.com/cnpm/npminstall
JavaScript
mit
timarney/react-app-rewired,timarney/react-app-rewired
38080adc1302b88af2c5d19d70720b53d4f464a7
jest.config.js
jest.config.js
/* @flow */ module.exports = { coverageDirectory: 'reports/coverage', coveragePathIgnorePatterns: [ '/node_modules/', '/packages/mineral-ui-icons', '/website/' ], moduleNameMapper: { '.*react-docgen-loader.*': '<rootDir>/utils/emptyObject.js', '.(md|svg)$': '<rootDir>/utils/emptyString.js' }, setupFiles: ['raf/polyfill'], setupTestFrameworkScriptFile: '<rootDir>/utils/setupTestFrameworkScript.js', snapshotSerializers: [ 'enzyme-to-json/serializer', '<rootDir>/utils/snapshotSerializer' ] };
/* @flow */ module.exports = { coverageDirectory: 'reports/coverage', coveragePathIgnorePatterns: [ '/node_modules/', '/packages/mineral-ui-icons', '/website/' ], moduleNameMapper: { '.*react-docgen-loader.*': '<rootDir>/utils/emptyObject.js', '.(md|svg)$': '<rootDir>/utils/emptyString.js' }, setupFiles: ['raf/polyfill'], setupTestFrameworkScriptFile: '<rootDir>/utils/setupTestFrameworkScript.js', snapshotSerializers: [ 'enzyme-to-json/serializer', '<rootDir>/utils/snapshotSerializer' ], testURL: 'http://localhost/' };
Update testURL to accommodate JSDOM update
chore(jest): Update testURL to accommodate JSDOM update - See https://github.com/jsdom/jsdom/issues/2304
JavaScript
apache-2.0
mineral-ui/mineral-ui,mineral-ui/mineral-ui
f9b3837c53bb0572c95f2f48b6855250870ea2f1
js/Landing.js
js/Landing.js
import React from 'react' const Landing = React.createClass({ render () { return ( <div className='landing'> <h1>svideo</h1> <input type='text' placeholder='Search' /> <a>or Browse All</a> </div> ) } }) export default Landing
import React from 'react' import { Link } from 'react-router' const Landing = React.createClass({ render () { return ( <div className='landing'> <h1>svideo</h1> <input type='text' placeholder='Search' /> <Link to='/search'>or Browse All</Link> </div> ) } }) export default Landing
Make the "or Browse All" button a link that takes you to /search route
Make the "or Browse All" button a link that takes you to /search route
JavaScript
mit
galaxode/ubiquitous-eureka,galaxode/ubiquitous-eureka
680debc53973355b553155bdfae857907af0a259
app/assets/javascripts/edsn.js
app/assets/javascripts/edsn.js
var EDSN_THRESHOLD = 30; var EdsnSwitch = (function(){ var editing; var validBaseLoads = /^(base_load|base_load_edsn)$/; EdsnSwitch.prototype = { enable: function(){ if(editing){ swapEdsnBaseLoadSelectBoxes(); } }, isEdsn: function(){ return validBaseLoads.test($(this).val()); }, cloneAndAppendProfileSelect: function(){ swapSelectBox.call(this); } }; function swapEdsnBaseLoadSelectBoxes(){ $("tr.base_load_edsn select.name").each(swapSelectBox); }; function swapSelectBox(){ var technology = 'base_load' var self = this; var unitSelector = $(this).parents("tr").find(".units input"); var units = parseInt(unitSelector.val()); var actual = (units > EDSN_THRESHOLD ? "base_load_edsn" : "base_load"); var select = $(".hidden select." + actual).clone(true, true); $(this).val(technology); $(this).parent().next().html(select); $(this).find("option[value='" + technology + "']").attr('value', actual); $(this).val(actual); unitSelector.off('change').on('change', swapSelectBox.bind(self)); }; function EdsnSwitch(_editing){ editing = _editing; }; return EdsnSwitch; })();
var EDSN_THRESHOLD = 30; var EdsnSwitch = (function(){ var editing; var validBaseLoads = /^(base_load|base_load_edsn)$/; EdsnSwitch.prototype = { enable: function(){ if(editing){ swapEdsnBaseLoadSelectBoxes(); } }, isEdsn: function(){ return validBaseLoads.test($(this).data('type')); }, cloneAndAppendProfileSelect: function(){ swapSelectBox.call(this); } }; function swapEdsnBaseLoadSelectBoxes(){ $("tr.base_load_edsn select.name").each(swapSelectBox); }; function swapSelectBox(){ var technology = 'base_load' var self = this; var unitSelector = $(this).parents("tr").find(".units input"); var units = parseInt(unitSelector.val()); var actual = (units > EDSN_THRESHOLD ? "base_load_edsn" : "base_load"); var select = $(".hidden select." + actual).clone(true, true); $(this).val(technology); $(this).parent().next().html(select); $(this).find("option[value='" + technology + "']").attr('value', actual); $(this).val(actual); unitSelector.off('change').on('change', swapSelectBox.bind(self)); }; function EdsnSwitch(_editing){ editing = _editing; }; return EdsnSwitch; })();
Use data attribute instead of val()
Use data attribute instead of val()
JavaScript
mit
quintel/etmoses,quintel/etmoses,quintel/etmoses,quintel/etmoses,quintel/etmoses
6321dc80f757cb1d83c4c06e277e0efcba5b853a
site/remark.js
site/remark.js
const visit = require('unist-util-visit'); const { kebabCase } = require('lodash'); const IGNORES = [ 'https://raw.githubusercontent.com/styleguidist/react-styleguidist/master/templates/DefaultExample.md', 'https://github.com/styleguidist/react-styleguidist/blob/master/.github/Contributing.md', ]; const REPLACEMENTS = { 'https://github.com/styleguidist/react-styleguidist': 'https://react-styleguidist.js.org/', }; const getDocUrl = url => url.replace(/(\w+)(?:\.md)/, (_, $1) => `/${kebabCase($1)}`); /* * Fix links: * GettingStarted.md -> /docs/getting-started */ function link() { return ast => visit(ast, 'link', node => { if (IGNORES.includes(node.url)) { return; } if (REPLACEMENTS[node.url]) { node.url = REPLACEMENTS[node.url]; } else if (node.url.endsWith('.md') || node.url.includes('.md#')) { node.url = getDocUrl(node.url); } }); } module.exports = [link];
const visit = require('unist-util-visit'); const { kebabCase } = require('lodash'); const IGNORES = [ 'https://raw.githubusercontent.com/styleguidist/react-styleguidist/master/templates/DefaultExample.md', 'https://github.com/styleguidist/react-styleguidist/blob/master/.github/Contributing.md', ]; const REPLACEMENTS = { 'https://github.com/styleguidist/react-styleguidist': 'https://react-styleguidist.js.org/', }; const getDocUrl = url => url.replace(/(\w+)(?:\.md)/, (_, $1) => `/docs/${kebabCase($1)}`); /* * Fix links: * GettingStarted.md -> /docs/getting-started */ function link() { return ast => visit(ast, 'link', node => { if (IGNORES.includes(node.url)) { return; } if (REPLACEMENTS[node.url]) { node.url = REPLACEMENTS[node.url]; } else if (node.url.endsWith('.md') || node.url.includes('.md#')) { node.url = getDocUrl(node.url); } }); } module.exports = [link];
Fix links on the site, again 🦐
docs: Fix links on the site, again 🦐 Closes #1650
JavaScript
mit
styleguidist/react-styleguidist,sapegin/react-styleguidist,styleguidist/react-styleguidist,styleguidist/react-styleguidist,sapegin/react-styleguidist
24d6b502081b81eff9ce1775002015f59ee3ccba
blueprints/component/index.js
blueprints/component/index.js
'use strict' module.exports = { description: "A basic React component", generateReplacements(args) { let propTypes = ""; let defaultProps = ""; if(args.length) { propTypes = "__name__.propTypes = {"; defaultProps = "\n getDefaultProps: function() {"; for(let index in args) { let prop = args[index]; let parts = prop.split(':'); propTypes += `\n ${parts[0]}: ${this.reactPropTypeFrom(parts[1])},`; defaultProps += `\n ${parts[0]}: ${this.reactDefaultPropFrom(parts[1])},`; } propTypes += "\n}\n"; defaultProps += "\n },\n"; } return {'__proptypes__': propTypes, '__defaultprops__': defaultProps }; }, reactPropTypeFrom(prop) { return 'React.PropTypes.' + prop; }, reactDefaultPropFrom(prop) { switch(prop) { case 'number': return '0'; case 'string': return "''"; case 'array': return '[]'; case 'bool': return 'false'; case 'func': case 'object': case 'shape': return 'null'; default: throw new Error(`Unsupported propType ${prop}`); } } }
'use strict' module.exports = { description: "A basic React component", generateReplacements(args) { let propTypes = ""; let defaultProps = ""; if(args.length) { propTypes = "__name__.propTypes = {"; defaultProps = "\n getDefaultProps: function() {"; for(let index in args) { let prop = args[index]; let parts = prop.split(':'); if(parts.length != 2) { throw new Error(`Prop ${prop} is formatted incorrectly`); } propTypes += `\n ${parts[0]}: ${this.reactPropTypeFrom(parts[1])},`; defaultProps += `\n ${parts[0]}: ${this.reactDefaultPropFrom(parts[1])},`; } propTypes += "\n}\n"; defaultProps += "\n },\n"; } return {'__proptypes__': propTypes, '__defaultprops__': defaultProps }; }, reactPropTypeFrom(prop) { return 'React.PropTypes.' + prop; }, reactDefaultPropFrom(prop) { switch(prop) { case 'number': return '0'; case 'string': return "''"; case 'array': return '[]'; case 'bool': return 'false'; case 'func': case 'object': case 'shape': return 'null'; default: throw new Error(`Unsupported propType ${prop}`); } } }
Check for badly formatted props
Check for badly formatted props
JavaScript
mit
reactcli/react-cli,reactcli/react-cli
3063e971479ca50e3e7d96d89db26688f5f74375
hobbes/vava.js
hobbes/vava.js
var vavaClass = require('./vava/class'); var vavaMethod = require('./vava/method'); var vavaType = require('./vava/type'); exports.scope = require('./vava/scope'); // TODO automate env assembly exports.env = { VavaClass : vavaClass.VavaClass, VavaMethod : vavaMethod.VavaMethod, TypedVariable : vavaType.TypedVariable, BooleanValue : vavaType.BooleanValue, IntValue : vavaType.IntValue, FloatValue : vavaType.FloatValue, DoubleValue : vavaType.DoubleValue, StringValue : vavaType.StringValue }
var utils = (typeof hobbes !== 'undefined' && hobbes.utils) || require('./utils'); var vavaClass = require('./vava/class'); var vavaMethod = require('./vava/method'); var vavaType = require('./vava/type'); exports.scope = require('./vava/scope'); exports.env = utils.merge( vavaClass, vavaMethod, vavaType );
Add automatic assembly of env
Add automatic assembly of env
JavaScript
mit
knuton/hobbes,knuton/hobbes,knuton/hobbes,knuton/hobbes
b1a4e4275743dd30a19eb7005af386596c752eb9
src/kb/widget/legacy/helpers.js
src/kb/widget/legacy/helpers.js
/*global define*/ /*jslint browser:true,white:true*/ define([ 'jquery', 'kb_common/html' ], function ($, html) { 'use strict'; // jQuery plugins that you can use to add and remove a // loading giff to a dom element. $.fn.rmLoading = function () { $(this).find('.loader').remove(); }; $.fn.loading = function (text, big) { var div = html.tag('div'); $(this).rmLoading(); // TODO: handle "big" $(this).append(div({ class: 'loader' }, html.loading(text))); // if (big) { // if (text !== undefined) { // $(this).append('<p class="text-center text-muted loader"><br>'+ // '<img src="assets/img/ajax-loader-big.gif"> '+text+'</p>'); // } else { // $(this).append('<p class="text-center text-muted loader"><br>'+ // '<img src="assets/img/ajax-loader-big.gif"> loading...</p>'); // } // } else { // if (text !== 'undefined') { // $(this).append('<p class="text-muted loader">'+ // '<img src="assets/img/ajax-loader.gif"> '+text+'</p>'); // } else { // $(this).append('<p class="text-muted loader">'+ // '<img src="assets/img/ajax-loader.gif"> loading...</p>'); // } // // } return this; }; });
define([ 'jquery', 'kb_common/html' ], function ( $, html ) { 'use strict'; // jQuery plugins that you can use to add and remove a // loading giff to a dom element. $.fn.rmLoading = function () { $(this).find('.loader').remove(); }; $.fn.loading = function (text, big) { var div = html.tag('div'); $(this).rmLoading(); // TODO: handle "big" $(this).append(div({ class: 'loader' }, html.loading(text))); return this; }; });
Remove commented out code that was upsetting uglify
Remove commented out code that was upsetting uglify
JavaScript
mit
eapearson/kbase-ui-widget
2e99a372b401cdfb8ecaaccffd3f8546c83c7da5
api/question.js
api/question.js
var bodyParser = require('body-parser'); var express = require('express'); var database = require('../database'); var router = express.Router(); router.get('/', function(req, res) { database.Question.find({}, function(err, questions) { if (err) { res.sendStatus(500); } else { res.sendStatus(200).json(questions); } }); }); router.put('/', bodyParser.json(), function(req, res) { var question = new database.Question(req.body); question.save(function(err) { if (err) { res.sendStatus(500); } else { res.sendStatus(200); } }); }); module.exports = router;
var bodyParser = require('body-parser'); var express = require('express'); var database = require('../database'); var router = express.Router(); router.get('/', function(req, res) { database.Question.find({}, function(err, questions) { if (err) { res.status(500); } else { res.status(200).json(questions); } }); }); router.put('/', bodyParser.json(), function(req, res) { var question = new database.Question(req.body); question.save(function(err) { if (err) { res.status(500); } else { res.status(200); } }); }); module.exports = router;
Fix error with resending response.
Fix error with resending response.
JavaScript
apache-2.0
skalmadka/TierUp,skalmadka/TierUp
33e775c0e0e025847297c138261689dd5354a7d8
api/resolver.js
api/resolver.js
var key = require('../utils/key'); var sync = require('synchronize'); var request = require('request'); var _ = require('underscore'); // The API that returns the in-email representation. module.exports = function(req, res) { var url = req.query.url.trim(); // Giphy image urls are in the format: // http://giphy.com/gifs/<seo-text>-<alphanumeric id> var matches = url.match(/\-([a-zA-Z0-9]+)$/); if (!matches) { res.status(400).send('Invalid URL format'); return; } var id = matches[1]; var response; try { response = sync.await(request({ url: 'http://api.giphy.com/v1/gifs/' + encodeURIComponent(id), qs: { api_key: key }, gzip: true, json: true, timeout: 15 * 1000 }, sync.defer())); } catch (e) { res.status(500).send('Error'); return; } var image = response.body.data.images.original; var width = image.width > 600 ? 600 : image.width; var html = '<p><img style="max-width:100%;" src="' + image.url + '" width="' + width + '"/></p>'; res.json({ body: html }); };
var key = require('../utils/key'); var sync = require('synchronize'); var request = require('request'); var _ = require('underscore'); // The API that returns the in-email representation. module.exports = function(req, res) { var url = req.query.url.trim(); // Giphy image urls are in the format: // http://giphy.com/gifs/<seo-text>-<alphanumeric id> var matches = url.match(/\-([a-zA-Z0-9]+)$/); if (!matches) { res.status(400).send('Invalid URL format'); return; } var id = matches[1]; var response; try { response = sync.await(request({ url: 'http://api.giphy.com/v1/gifs/' + encodeURIComponent(id), qs: { api_key: key }, gzip: true, json: true, timeout: 15 * 1000 }, sync.defer())); } catch (e) { res.status(500).send('Error'); return; } var image = response.body.data.images.original; var width = image.width > 600 ? 600 : image.width; var html = '<img style="max-width:100%;" src="' + image.url + '" width="' + width + '"/>'; res.json({ body: html }); };
Remove paragraphs since they add unnecessary vertical padding.
Remove paragraphs since they add unnecessary vertical padding.
JavaScript
mit
kigster/wanelo-mixmax-link-resolver,kigster/wanelo-mixmax-link-resolver,mixmaxhq/giphy-example-link-resolver,germy/mixmax-metaweather
8d27f66f4b4c61ddeb95e5107a616b937eb06dff
app/core/app.js
app/core/app.js
'use strict'; var bowlingApp = angular.module('bowling', ['ngRoute']); bowlingApp.config(['$routeProvider', function($routeProvider) { $routeProvider.otherwise({ redirectTo: '/main' }); }]); bowlingApp.factory("dataProvider", ['$q', function ($q) { var dataLoaded = false; var currentPromise = null; return { getData: function () { if (currentPromise == null) { if (!dataLoaded) { var result = bowling.initialize({"root": "polarbowler"}, $q); currentPromise = result.then(function (league) { dataLoaded = true; currentPromise = null; return league; }); } else { return $q(function (resolve, reject) { resolve(bowling.currentLeague); }); } } return currentPromise; } } }]);
'use strict'; var bowlingApp = angular.module('bowling', ['ngRoute']); bowlingApp.config(['$routeProvider', function($routeProvider) { $routeProvider.otherwise({ redirectTo: '/main' }); }]); bowlingApp.factory("dataProvider", ['$q', function ($q) { var dataLoaded = false; var currentPromise = null; return { getData: function () { if (currentPromise == null) { if (!dataLoaded) { var result = bowling.initialize({"root": "testdata"}, $q); currentPromise = result.then(function (league) { dataLoaded = true; currentPromise = null; return league; }); } else { return $q(function (resolve, reject) { resolve(bowling.currentLeague); }); } } return currentPromise; } } }]);
Change data directory back to test data.
Change data directory back to test data.
JavaScript
mit
MeerkatLabs/bowling-visualization
4f429972826a4a1892969f11bef49f4bae147ac3
webpack.config.base.js
webpack.config.base.js
'use strict' var webpack = require('webpack') var reactExternal = { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' } module.exports = { externals: { 'react': reactExternal }, module: { loaders: [ { test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/ } ] }, output: { library: 'ReduxForm', libraryTarget: 'umd' }, resolve: { extensions: ['', '.js'] } }
'use strict' var webpack = require('webpack') var reactExternal = { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' } var reduxExternal = { root: 'Redux', commonjs2: 'redux', commonjs: 'redux', amd: 'redux' } var reactReduxExternal = { root: 'ReactRedux', commonjs2: 'react-redux', commonjs: 'react-redux', amd: 'react-redux' } module.exports = { externals: { 'react': reactExternal, 'redux': reduxExternal, 'react-redux': reactReduxExternal }, module: { loaders: [ { test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/ } ] }, output: { library: 'ReduxForm', libraryTarget: 'umd' }, resolve: { extensions: ['', '.js'] } }
Add Redux and React Redux as external dependencies
Add Redux and React Redux as external dependencies
JavaScript
mit
erikras/redux-form,erikras/redux-form
849ae9172c21704c61ae6a84affdef0a309fcb4b
app/controllers/application.js
app/controllers/application.js
import Ember from 'ember'; export default Ember.Controller.extend({ sitemap: { nodes: [ { link: 'index', title: 'Home', children: null }, { link: null, title: 'Admin panel', children: [ { link: 'suggestionTypes', title: 'Suggestion Types', children: null }, { link: 'users', title: 'Application Users', children: null } ] }, { link: 'suggestions.new', title: 'Добавить предложение', children: null } ] } });
import Ember from "ember"; export default Ember.Controller.extend({ sitemap: { nodes: [ { link: "index", title: "Home" }, { title: "Admin panel", children: [ { link: "suggestionTypes", title: "Suggestion Types" }, { link: "users", title: "Application Users" } ] }, { link: "suggestions.new", title: "Добавить предложение" }, { title: "Разное", children: [ { link: "geolocation", title: "Геолокация" } ] } ] } });
Add link to geolocation example into sitemap
Add link to geolocation example into sitemap
JavaScript
mit
Flexberry/flexberry-ember-demo,Flexberry/flexberry-ember-demo,Flexberry/flexberry-ember-demo
421aba98815a8f3d99fa78daf1d6ec9315712966
zombie/proxy/server.js
zombie/proxy/server.js
var net = require('net'); var zombie = require('zombie'); // Defaults var ping = 'pong' var browser = null; var ELEMENTS = []; // // Store global client states indexed by ZombieProxyClient (memory address): // // { // 'CLIENTID': [X, Y] // } // // ...where X is some zombie.Browser instance... // // ...and Y is a per-browser cache (a list) used to store NodeList results. // Subsequent TCP API calls will reference indexes to retrieve DOM // attributes/properties accumulated in previous browser.querySelectorAll() // calls. // // var CLIENTS = {}; // // Simple proxy server implementation // for proxying streamed (Javascript) content via HTTP // to a running Zombie.js // // Borrowed (heavily) from the Capybara-Zombie project // https://github.com/plataformatec/capybara-zombie // // function ctx_switch(id){ if(!CLIENTS[id]) CLIENTS[id] = [new zombie.Browser(), []]; return CLIENTS[id]; } net.createServer(function (stream){ stream.setEncoding('utf8'); stream.on('data', function (data){ eval(data); }); }).listen(process.argv[2], function(){ console.log('Zombie.js server running on ' + process.argv[2] + '...'); });
var net = require('net'); var Browser = require('zombie'); // Defaults var ping = 'pong' var browser = null; var ELEMENTS = []; // // Store global client states indexed by ZombieProxyClient (memory address): // // { // 'CLIENTID': [X, Y] // } // // ...where X is some zombie.Browser instance... // // ...and Y is a per-browser cache (a list) used to store NodeList results. // Subsequent TCP API calls will reference indexes to retrieve DOM // attributes/properties accumulated in previous browser.querySelectorAll() // calls. // // var CLIENTS = {}; // // Simple proxy server implementation // for proxying streamed (Javascript) content via HTTP // to a running Zombie.js // // Borrowed (heavily) from the Capybara-Zombie project // https://github.com/plataformatec/capybara-zombie // // function ctx_switch(id){ if(!CLIENTS[id]) CLIENTS[id] = [new Browser(), []]; return CLIENTS[id]; } net.createServer(function (stream){ stream.setEncoding('utf8'); stream.on('data', function (data){ eval(data); }); }).listen(process.argv[2], function(){ console.log('Zombie.js server running on ' + process.argv[2] + '...'); });
Make the sever.js work with zombie 2
Make the sever.js work with zombie 2
JavaScript
mit
ryanpetrello/python-zombie,ryanpetrello/python-zombie
fe6247d1ade209f1ebb6ba537652569810c4d77a
lib/adapter.js
lib/adapter.js
/** * Request adapter. * * @package cork * @author Andrew Sliwinski <[email protected]> */ /** * Dependencies */ var _ = require('lodash'), async = require('async'), request = require('request'); /** * Executes a task from the adapter queue. * * @param {Object} Task * * @return {Object} */ var execute = function (task, callback) { request(task, function (err, response, body) { callback(err, body); }); } /** * Constructor */ function Adapter (args) { var self = this; // Setup instance _.extend(self, args); _.defaults(self, { base: null, throttle: 0 }); // Throttled request method var limiter = _.throttle(execute, self.throttle); // Create queue self.queue = async.queue(function (obj, callback) { // Assemble task var task = Object.create(null); _.extend(task, self, obj); if (self.base !== null) task.uri = self.base + task.uri; // Clean-up delete task.base; delete task.throttle; // Process task through the limiter method limiter(task, callback); }, 1); }; /** * Export */ module.exports = Adapter;
/** * Request adapter. * * @package cork * @author Andrew Sliwinski <[email protected]> */ /** * Dependencies */ var _ = require('lodash'), async = require('async'), request = require('request'); /** * Executes a task from the adapter queue. * * @param {Object} Task * * @return {Object} */ var execute = function (task, callback) { request(task, function (err, response, body) { callback(err, body); }); } /** * Constructor */ function Adapter (args) { var self = this; // Setup instance _.extend(self, args); _.defaults(self, { base: null, throttle: 0 }); // Throttle the request execution method var limiter = _.throttle(execute, self.throttle); // Create queue self.queue = async.queue(function (obj, callback) { // Assemble task var task = Object.create(null); _.extend(task, self, obj); if (self.base !== null) task.uri = self.base + task.uri; // Clean-up delete task.queue; delete task.base; delete task.throttle; // Process task through the limiter method limiter(task, callback); }, 1); }; /** * Export */ module.exports = Adapter;
Remove queue object from the task
Remove queue object from the task
JavaScript
mit
thisandagain/cork
fcab433c54faeffbc59d0609a6f503e3a3237d6f
lib/bemhint.js
lib/bemhint.js
/** * The core of BEM hint * ==================== */ var vow = require('vow'), _ = require('lodash'), scan = require('./walk'), loadRules = require('./load-rules'), Configuration = require('./configuration'), utils = require('./utils'); /** * Loads the BEM entities and checks them * @param {Object} [loadedConfig] * @param {String} [loadedConfig.configPath] * @param {Array} [loadedConfig.levels] * @param {Array} [loadedCinfig.excludeFiles] * @param {Array} targets * @returns {Promise * Array} - the list of BEM errors */ module.exports = function (loadedConfig, targets) { var config = new Configuration(loadedConfig); return vow.all([scan(targets, config), loadRules()]) .spread(function (entities, rules) { return vow.all(_.keys(rules).map(function (rule) { var _rule = new rules[rule](); return _rule.check(entities); })); }) .then(function (res) { var bemErros = []; _(res).keys().forEach(function (item) { bemErros = bemErros.concat(res[item]); }); return utils.sortByFullpath(bemErros); }); };
/** * The core of BEM hint * ==================== */ var vow = require('vow'), _ = require('lodash'), scan = require('./walk'), loadRules = require('./load-rules'), Configuration = require('./configuration'), utils = require('./utils'); /** * Loads the BEM entities and checks them * @param {Object} [loadedConfig] * @param {String} [loadedConfig.configPath] * @param {Array} [loadedConfig.levels] * @param {Array} [loadedCinfig.excludeFiles] * @param {Array} targets * @returns {Promise * Array} - the list of BEM errors */ module.exports = function (loadedConfig, targets) { var config = new Configuration(loadedConfig); return vow.all([scan(targets, config), loadRules()]) .spread(function (entities, rules) { return vow.all(_.keys(rules).map(function (rule) { var _rule = new rules[rule](config); return _rule.check(entities); })); }) .then(function (res) { var bemErros = []; _(res).keys().forEach(function (item) { bemErros = bemErros.concat(res[item]); }); return utils.sortByFullpath(bemErros); }); };
Add 'config' as argument to rules' constructors
Add 'config' as argument to rules' constructors
JavaScript
mit
bemhint/bemhint,bemhint/bemhint,bem/bemhint,bem/bemhint
7b6d8f66fd1c2130d10ba7013136ecc3f25d6c3b
src/main/webapp/scripts/main.js
src/main/webapp/scripts/main.js
$().ready(() => { loadContentSection().then(() =>{ $("#loader").addClass("hide"); $("#real-body").removeClass("hide"); $("#real-body").addClass("body"); $(".keyword").click(function() { $(this).addClass("active"); $(".base").hide(200); $("#real-body").addClass("focus"); }); $(".close").click(function(event) { event.stopPropagation(); $(this).parent().removeClass("active"); $(".base").show(200); $("#real-body").removeClass("focus"); }); }); });
$().ready(() => { loadContentSection().then(() =>{ $("#loader").addClass("hide"); $("#real-body").removeClass("hide"); $("#real-body").addClass("body"); $(".keyword").click(function() { $(this).addClass("active"); $(".base").hide(200); $("#real-body").addClass("focus"); }); $(".close").click(function(event) { event.stopPropagation(); $(this).parent().removeClass("active"); $(".base").show(200); $("#real-body").removeClass("focus"); }); $(".active .item").click(function() { $(".item").off("click"); const url = $(this).attr("data-url"); window.location.replace(url); }); }); });
Add js to perform url replacement
Add js to perform url replacement
JavaScript
apache-2.0
googleinterns/step36-2020,googleinterns/step36-2020,googleinterns/step36-2020
2de06af9887b6941f73a6610a5485d98cf7f353f
lib/mongoat.js
lib/mongoat.js
'use strict'; var Mongoat = require('mongodb'); var utilsHelper = require('../helpers/utils-helper'); var connect = Mongoat.MongoClient.connect; var hooks = { before: {}, after: {} }; Mongoat.Collection.prototype.before = function(opName, callback) { hooks = utilsHelper.beforeAfter('before', opName, hooks, callback); }; Mongoat.Collection.prototype.after = function(opName, callback) { hooks = utilsHelper.beforeAfter('after', opName, hooks, callback); }; Mongoat.Collection.prototype.insertTo = Mongoat.Collection.prototype.insert; Mongoat.Collection.prototype.insert = function(document, options) { var promises = []; var _this = this; options = options || {}; promises = utilsHelper.promisify(hooks.before.insert, document); return Promise.all(promises).then(function (docToInsert) { return _this.insertTo(docToInsert[0], options).then(function (mongoObject) { promises = []; promises = utilsHelper.promisify(hooks.after.insert, docToInsert[0]); Promise.all(promises); return mongoObject; }); }); }; module.exports = Mongoat;
'use strict'; var Mongoat = require('mongodb'); var utilsHelper = require('../helpers/utils-helper'); var connect = Mongoat.MongoClient.connect; var hooks = { before: {}, after: {} }; (function(){ var opArray = ['insert', 'update', 'remove']; var colPrototype = Mongoat.Collection.prototype; for (var i = 0; i < opArray.length; ++i) { colPrototype[opArray[i] + 'Method'] = colPrototype[opArray[i]]; } })(); Mongoat.Collection.prototype.before = function(opName, callback) { hooks = utilsHelper.beforeAfter('before', opName, hooks, callback); }; Mongoat.Collection.prototype.after = function(opName, callback) { hooks = utilsHelper.beforeAfter('after', opName, hooks, callback); }; Mongoat.Collection.prototype.insert = function(document, options) { var promises = []; var _this = this; options = options || {}; promises = utilsHelper.promisify(hooks.before.insert, document); return Promise.all(promises).then(function (docToInsert) { return _this.insertMethod(docToInsert[0], options) .then(function (mongoObject) { promises = []; promises = utilsHelper.promisify(hooks.after.insert, docToInsert[0]); Promise.all(promises); return mongoObject; }); }); }; module.exports = Mongoat;
Update save methods strategy - Use anonymous function to save collection methods before overwrite
Update save methods strategy - Use anonymous function to save collection methods before overwrite
JavaScript
mit
dial-once/node-mongoat
7bb5536b35b5f1bb90fde60abeb2f6cd7e410139
lib/version.js
lib/version.js
var clone = require('clone'), mongoose = require('mongoose'), ObjectId = mongoose.Schema.Types.ObjectId; module.exports = function(schema, options) { options = options || {}; options.collection = options.collection || 'versions'; var versionedSchema = clone(schema); // Fix for callQueue arguments versionedSchema.callQueue.forEach(function(queueEntry) { var args = []; for(var key in queueEntry[1]) { args.push(queueEntry[1][key]); } queueEntry[1] = args; }); for(var key in options) { if (options.hasOwnProperty(key)) { versionedSchema.set(key, options[key]); } } versionedSchema.add({ refId : ObjectId, refVersion : Number }); // Add reference to model to original schema schema.statics.VersionedModel = mongoose.model(options.collection, versionedSchema); schema.pre('save', function(next) { this.increment(); // Increment origins version var versionedModel = new versionedSchema.statics.VersionedModel(this); versionedModel.refVersion = this._doc.__v; // Saves current document version versionedModel.refId = this._id; // Sets origins document id as a reference versionedModel._id = undefined; versionedModel.save(function(err) { next(); }); }); };
var clone = require('clone'), mongoose = require('mongoose'), ObjectId = mongoose.Schema.Types.ObjectId; module.exports = function(schema, options) { options = options || {}; options.collection = options.collection || 'versions'; var versionedSchema = clone(schema); // Fix for callQueue arguments versionedSchema.callQueue.forEach(function(queueEntry) { var args = []; for(var key in queueEntry[1]) { args.push(queueEntry[1][key]); } queueEntry[1] = args; }); for(var key in options) { if (options.hasOwnProperty(key)) { versionedSchema.set(key, options[key]); } } versionedSchema.add({ refId : ObjectId, refVersion : Number }); // Add reference to model to original schema schema.statics.VersionedModel = mongoose.model(options.collection, versionedSchema); schema.pre('save', function(next) { this.increment(); // Increment origins version var versionedModel = new schema.statics.VersionedModel(this); versionedModel.refVersion = this._doc.__v; // Saves current document version versionedModel.refId = this._id; // Sets origins document id as a reference versionedModel._id = undefined; versionedModel.save(function(err) { next(); }); }); };
Fix bug accessing wrong schema instance
Fix bug accessing wrong schema instance
JavaScript
bsd-2-clause
jeresig/mongoose-version,saintedlama/mongoose-version
c31d392e1972d6eaca952c21ba9349d30b31b012
js/defaults.js
js/defaults.js
/* exported defaults */ /* Magic Mirror * Config Defauls * * By Michael Teeuw http://michaelteeuw.nl * MIT Licensed. */ var defaults = { port: 8080, language: "en", timeFormat: 24, modules: [ { module: "helloworld", position: "upper_third", config: { text: "Magic Mirror V2", classes: "large thin" } }, { module: "helloworld", position: "middle_center", config: { text: "Please create a config file." } }, { module: "helloworld", position: "middle_center", config: { text: "See README for more information.", classes: "small dimmed" } }, { module: "helloworld", position: "bottom_bar", config: { text: "www.michaelteeuw.nl", classes: "xsmall dimmed" } }, ], paths: { modules: "modules", vendor: "vendor" }, }; /*************** DO NOT EDIT THE LINE BELOW ***************/ if (typeof module !== "undefined") {module.exports = defaults;}
/* exported defaults */ /* Magic Mirror * Config Defauls * * By Michael Teeuw http://michaelteeuw.nl * MIT Licensed. */ var defaults = { port: 8080, language: "en", timeFormat: 24, modules: [ { module: "helloworld", position: "upper_third", config: { text: "Magic Mirror<sup>2</sup>", classes: "large thin" } }, { module: "helloworld", position: "middle_center", config: { text: "Please create a config file." } }, { module: "helloworld", position: "middle_center", config: { text: "See README for more information.", classes: "small dimmed" } }, { module: "helloworld", position: "bottom_bar", config: { text: "www.michaelteeuw.nl", classes: "xsmall dimmed" } }, ], paths: { modules: "modules", vendor: "vendor" }, }; /*************** DO NOT EDIT THE LINE BELOW ***************/ if (typeof module !== "undefined") {module.exports = defaults;}
Change branding on default config.
Change branding on default config.
JavaScript
mit
kthorri/MagicMirror,enith2478/spegel,aschulz90/MagicMirror,morozgrafix/MagicMirror,morozgrafix/MagicMirror,marcroga/sMirror,aghth/MagicMirror,ShivamShrivastava/Smart-Mirror,ConnorChristie/MagicMirror,berlincount/MagicMirror,wszgxa/magic-mirror,heyheyhexi/MagicMirror,gndimitro/MagicMirror,vyazadji/MagicMirror,ryanlawler/MagicMirror,aschulz90/MagicMirror,ConnorChristie/MagicMirror,thunderseethe/MagicMirror,cmwalshWVU/smartMirror,Leniox/MagicMirror,parakrama1995/Majic-Mirror,cs499Mirror/MagicMirror,cameronediger/MagicMirror,vyazadji/MagicMirror,cmwalshWVU/smartMirror,phareim/magic-mirror,aghth/MagicMirror,kevinatown/MM,n8many/MagicMirror,prasanthsasikumar/MagicMirror,thobach/MagicMirror,JimmyBoyle/MagicMirror,wszgxa/magic-mirror,aghth/MagicMirror,NoroffNIS/MagicMirror,cameronediger/MagicMirror,n8many/MagicMirror,cameronediger/MagicMirror,heyheyhexi/MagicMirror,Rimap47/MagicMirror,thunderseethe/MagicMirror,jamessalvatore/MagicMirror,denalove/MM2,soapdx/MagicMirror,cs499Mirror/MagicMirror,kevinatown/MM,kthorri/MagicMirror,parakrama1995/Majic-Mirror,mbalfour/MagicMirror,Makerspace-IDI/magic-mirror,Devan0369/AI-Project,gndimitro/MagicMirror,Leniox/MagicMirror,kevinatown/MM,Rimap47/MagicMirror,marc-86/MagicMirror,JimmyBoyle/MagicMirror,Tyvonne/MagicMirror,berlincount/MagicMirror,n8many/MagicMirror,roramirez/MagicMirror,OniDotun123/MirrorMirror,mbalfour/MagicMirror,thunderseethe/MagicMirror,Makerspace-IDI/magic-mirror,thobach/MagicMirror,vyazadji/MagicMirror,jodybrewster/hkthon,marc-86/MagicMirror,cameronediger/MagicMirror,fullbright/MagicMirror,MichMich/MagicMirror,JimmyBoyle/MagicMirror,wszgxa/magic-mirror,prasanthsasikumar/MagicMirror,phareim/magic-mirror,heyheyhexi/MagicMirror,kthorri/MagicMirror,berlincount/MagicMirror,morozgrafix/MagicMirror,marcroga/sMirror,denalove/MM2,Makerspace-IDI/magic-mirror,huntersiniard/MagicMirror,marcroga/sMirror,OniDotun123/MirrorMirror,kevinatown/MM,MichMich/MagicMirror,soapdx/MagicMirror,cs499Mirror/MagicMirror,he3/MagicMirror,thobach/MagicMirror,skippengs/MagicMirror,enith2478/spegel,mbalfour/MagicMirror,Tyvonne/MagicMirror,MichMich/MagicMirror,Tyvonne/MagicMirror,marc-86/MagicMirror,ShivamShrivastava/Smart-Mirror,NoroffNIS/MagicMirror,fullbright/MagicMirror,NoroffNIS/MagicMirror,Devan0369/AI-Project,gndimitro/MagicMirror,skippengs/MagicMirror,n8many/MagicMirror,jamessalvatore/MagicMirror,thobach/MagicMirror,roramirez/MagicMirror,huntersiniard/MagicMirror,ryanlawler/MagicMirror,jodybrewster/hkthon,MichMich/MagicMirror,ConnorChristie/MagicMirror,he3/MagicMirror,parakrama1995/Majic-Mirror,Leniox/MagicMirror,marcroga/sMirror,roramirez/MagicMirror,prasanthsasikumar/MagicMirror,denalove/MM2,OniDotun123/MirrorMirror,huntersiniard/MagicMirror,roramirez/MagicMirror,Rimap47/MagicMirror,jamessalvatore/MagicMirror,ryanlawler/MagicMirror,cmwalshWVU/smartMirror,soapdx/MagicMirror,marc-86/MagicMirror,n8many/MagicMirror,heyheyhexi/MagicMirror,Devan0369/AI-Project,ShivamShrivastava/Smart-Mirror,Tyvonne/MagicMirror,fullbright/MagicMirror,prasanthsasikumar/MagicMirror,berlincount/MagicMirror,jodybrewster/hkthon,morozgrafix/MagicMirror,he3/MagicMirror,aschulz90/MagicMirror,phareim/magic-mirror,enith2478/spegel,skippengs/MagicMirror
fce51a7f4c2991773fff8d8070130a726f73879a
nin/frontend/app/scripts/directives/demo.js
nin/frontend/app/scripts/directives/demo.js
function demo($interval, demo) { return { restrict: 'E', template: '<div class=demo-container></div>', link: function(scope, element) { demo.setContainer(element[0].children[0]); setTimeout(function() { demo.resize(); }); scope.$watch(() => scope.main.fullscreen, function (toFullscreen){ if (toFullscreen) { // go to fullscreen document.body.classList.add('fullscreen'); } else { // exit fullscreen document.body.classList.remove('fullscreen'); } demo.resize(); }); scope.$watch(() => scope.main.mute, function (toMute) { if (toMute) { demo.music.setVolume(0); } else { demo.music.setVolume(scope.main.volume); } }); scope.$watch(() => scope.main.volume, volume => { if (scope.mute) return; demo.music.setVolume(volume); }); $interval(function() { scope.main.currentFrame = demo.getCurrentFrame(); scope.main.duration = demo.music.getDuration() * 60; }, 1000 / 60); setTimeout(function(){ demo.start(); demo.music.pause(); demo.jumpToFrame(0); }, 0); } }; } module.exports = demo;
function demo($interval, demo) { return { restrict: 'E', template: '<div class=demo-container></div>', link: function(scope, element) { demo.setContainer(element[0].children[0]); setTimeout(function() { demo.resize(); }); scope.$watch(() => scope.main.fullscreen, function (toFullscreen){ if (toFullscreen) { // go to fullscreen document.body.classList.add('fullscreen'); } else { // exit fullscreen document.body.classList.remove('fullscreen'); } demo.resize(); }); scope.$watch(() => scope.main.mute, function (toMute) { if (toMute) { demo.music.setVolume(0); } else { demo.music.setVolume(scope.main.volume); } }); scope.$watch(() => scope.main.volume, volume => { if (scope.main.mute) return; demo.music.setVolume(volume); }); $interval(function() { scope.main.currentFrame = demo.getCurrentFrame(); scope.main.duration = demo.music.getDuration() * 60; }, 1000 / 60); setTimeout(function(){ demo.start(); demo.music.pause(); demo.jumpToFrame(0); }, 0); } }; } module.exports = demo;
Fix mute on initial load
Fix mute on initial load
JavaScript
apache-2.0
ninjadev/nin,ninjadev/nin,ninjadev/nin
85afadbe75bce0fd7069224c8065d99d6a663a2f
src/adapter.js
src/adapter.js
/* * Copyright 2014 Workiva, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(karma, System) { // Prevent immediately starting tests. window.__karma__.loaded = function() {}; function extractModuleName(fileName){ return fileName.replace(/\.js$/, ""); } var promises = []; if(!System){ throw new Error("SystemJS was not found. Please make sure you have " + "initialized jspm via installing a dependency with jspm, " + "or by running 'jspm dl-loader'."); } // Configure SystemJS baseURL System.config({ baseURL: 'base' }); // Load everything specified in loadFiles karma.config.jspm.expandedFiles.map(function(modulePath){ promises.push(System.import(extractModuleName(modulePath))); }); // Promise comes from the es6_module_loader Promise.all(promises).then(function(){ karma.start(); }); })(window.__karma__, window.System);
/* * Copyright 2014 Workiva, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(karma, System) { // Prevent immediately starting tests. window.__karma__.loaded = function() {}; function extractModuleName(fileName){ return fileName.replace(/\.js$/, ""); } var promises = []; if(!System){ throw new Error("SystemJS was not found. Please make sure you have " + "initialized jspm via installing a dependency with jspm, " + "or by running 'jspm dl-loader'."); } // Configure SystemJS baseURL System.config({ baseURL: 'base' }); // Load everything specified in loadFiles karma.config.jspm.expandedFiles.map(function(modulePath){ var promise = System.import(extractModuleName(modulePath)) .catch(function(e){ setTimeout(function() { throw e; }); }); promises.push(promise); }); // Promise comes from the es6_module_loader Promise.all(promises).then(function(){ karma.start(); }); })(window.__karma__, window.System);
Add error handler to System.import promises
Add error handler to System.import promises
JavaScript
apache-2.0
rich-nguyen/karma-jspm
4aa3e40ae4a9b998025a010749be69da428cb9bb
src/jupyter_contrib_nbextensions/nbextensions/hide_input_all/main.js
src/jupyter_contrib_nbextensions/nbextensions/hide_input_all/main.js
// toggle display of all code cells' inputs define([ 'jquery', 'base/js/namespace' ], function( $, IPython ) { "use strict"; function set_input_visible(show) { IPython.notebook.metadata.hide_input = !show; if (show) $('div.input').show('slow'); else $('div.input').hide('slow'); var btn = $('#toggle_codecells'); btn.toggleClass('active', !show); var icon = btn.find('i'); icon.toggleClass('fa-eye', show); icon.toggleClass('fa-eye-slash', !show); $('#toggle_codecells').attr( 'title', (show ? 'Hide' : 'Show') + ' codecell inputs'); } function toggle() { set_input_visible($('#toggle_codecells').hasClass('active')); } var load_ipython_extension = function() { IPython.toolbar.add_buttons_group([{ id : 'toggle_codecells', label : 'Hide codecell inputs', icon : 'fa-eye', callback : function() { toggle(); setTimeout(function() { $('#toggle_codecells').blur(); }, 500); } }]); set_input_visible(IPython.notebook.metadata.hide_input !== true); }; return { load_ipython_extension : load_ipython_extension }; });
// toggle display of all code cells' inputs define([ 'jquery', 'base/js/namespace', 'base/js/events' ], function( $, Jupyter, events ) { "use strict"; function set_input_visible(show) { Jupyter.notebook.metadata.hide_input = !show; if (show) $('div.input').show('slow'); else $('div.input').hide('slow'); var btn = $('#toggle_codecells'); btn.toggleClass('active', !show); var icon = btn.find('i'); icon.toggleClass('fa-eye', show); icon.toggleClass('fa-eye-slash', !show); $('#toggle_codecells').attr( 'title', (show ? 'Hide' : 'Show') + ' codecell inputs'); } function toggle() { set_input_visible($('#toggle_codecells').hasClass('active')); } function initialize () { set_input_visible(Jupyter.notebook.metadata.hide_input !== true); } var load_ipython_extension = function() { Jupyter.toolbar.add_buttons_group([{ id : 'toggle_codecells', label : 'Hide codecell inputs', icon : 'fa-eye', callback : function() { toggle(); setTimeout(function() { $('#toggle_codecells').blur(); }, 500); } }]); if (Jupyter.notebook !== undefined && Jupyter.notebook._fully_loaded) { // notebook_loaded.Notebook event has already happened initialize(); } events.on('notebook_loaded.Notebook', initialize); }; return { load_ipython_extension : load_ipython_extension }; });
Fix loading for either before or after notebook loads.
[hide_input_all] Fix loading for either before or after notebook loads.
JavaScript
bsd-3-clause
ipython-contrib/IPython-notebook-extensions,ipython-contrib/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,juhasch/IPython-notebook-extensions,ipython-contrib/IPython-notebook-extensions,juhasch/IPython-notebook-extensions,juhasch/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,ipython-contrib/IPython-notebook-extensions
0c0878ac06febc05dd34f617c6a874e3a5d2ee49
lib/node_modules/@stdlib/utils/move-property/lib/index.js
lib/node_modules/@stdlib/utils/move-property/lib/index.js
'use strict'; /** * FUNCTION: moveProperty( source, prop, target ) * Moves a property from one object to another object. * * @param {Object} source - source object * @param {String} prop - property to move * @param {Object} target - target object * @returns {Boolean} boolean indicating whether operation was successful */ function moveProperty( source, prop, target ) { var desc; if ( typeof source !== 'object' || source === null ) { throw new TypeError( 'invalid input argument. Source argument must be an object. Value: `' + source + '`.' ); } if ( typeof target !== 'object' || target === null ) { throw new TypeError( 'invalid input argument. Target argument must be an object. Value: `' + target + '`.' ); } desc = Object.getOwnPropertyDescriptor( source, prop ); if ( desc === void 0 ) { return false; } delete source[ prop ]; Object.defineProperty( target, prop, desc ); return true; } // end FUNCTION moveProperty() // EXPORTS // module.exports = moveProperty;
'use strict'; /** * FUNCTION: moveProperty( source, prop, target ) * Moves a property from one object to another object. * * @param {Object} source - source object * @param {String} prop - property to move * @param {Object} target - target object * @returns {Boolean} boolean indicating whether operation was successful */ function moveProperty( source, prop, target ) { var desc; if ( typeof source !== 'object' || source === null ) { throw new TypeError( 'invalid input argument. Source argument must be an object. Value: `' + source + '`.' ); } if ( typeof target !== 'object' || target === null ) { throw new TypeError( 'invalid input argument. Target argument must be an object. Value: `' + target + '`.' ); } // TODO: handle case where gOPD is not supported desc = Object.getOwnPropertyDescriptor( source, prop ); if ( desc === void 0 ) { return false; } delete source[ prop ]; Object.defineProperty( target, prop, desc ); return true; } // end FUNCTION moveProperty() // EXPORTS // module.exports = moveProperty;
Add TODO for handling getOwnPropertyDescriptor support
Add TODO for handling getOwnPropertyDescriptor support
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
65294019c1d29baaa548e483e93c8c55bf4bbabb
static/site.js
static/site.js
jQuery( document ).ready( function( $ ) { // Your JavaScript goes here jQuery('#content').fitVids(); });
jQuery( document ).ready( function( $ ) { // Your JavaScript goes here jQuery('#content').fitVids({customSelector: ".fitvids-responsive-iframe"}); });
Add .fitvids-responsive-iframe class for making iframes responsive
Add .fitvids-responsive-iframe class for making iframes responsive
JavaScript
mit
CoderDojo/cd-theme,CoderDojo/cd-theme,CoderDojo/cd-theme,CoderDojo/cd-theme
9af98fed472b4dabeb7c713f44c0b5b80da8fe4a
website/src/app/project/experiments/experiment/experiment.model.js
website/src/app/project/experiments/experiment/experiment.model.js
export class ExperimentStep { constructor(title, _type) { this.id = ''; this.title = title; this._type = _type; this.steps = []; this.description = ''; this.flags = { important: false, review: false, error: false, done: false }; this.displayState = { details: { showTitle: true, showStatus: true, showNotes: true, showFiles: false, showSamples: false, currentFilesTab: 0, currentSamplesTab: 0 }, editTitle: true, open: false, maximize: false }; this.node = null; } addStep(step) { this.steps.push(step); } } export class Experiment { constructor(name) { this.name = name; this.goal = ''; this.description = 'Look at grain size as it relates to hardness'; this.aim = ''; this.done = false; this.steps = []; } addStep(title, _type) { let s = new ExperimentStep(title, _type); this.steps.push(s); } }
export class ExperimentStep { constructor(title, _type) { this.id = ''; this.title = title; this._type = _type; this.steps = []; this.description = ''; this.flags = { important: false, review: false, error: false, done: false }; this.displayState = { details: { showTitle: true, showStatus: true, showNotes: true, showFiles: false, showSamples: false, currentFilesTab: 0, currentSamplesTab: 0 }, editTitle: true, open: false, maximize: false }; this.node = null; } addStep(step) { this.steps.push(step); } } export class Experiment { constructor(name) { this.name = name; this.goal = ''; this.description = ''; this.aim = ''; this.status = 'in-progress'; this.steps = []; } addStep(title, _type) { let s = new ExperimentStep(title, _type); this.steps.push(s); } }
Remove hard coded experiment description. Remove done field and add status field since that is what we get from the backend.
Remove hard coded experiment description. Remove done field and add status field since that is what we get from the backend.
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
c316a0757defcde769be70b5d8af5c51ef0ccb75
task/import.js
task/import.js
var geonames = require('geonames-stream'); var peliasConfig = require( 'pelias-config' ).generate(); var peliasAdminLookup = require( 'pelias-admin-lookup' ); var dbclient = require('pelias-dbclient'); var model = require( 'pelias-model' ); var resolvers = require('./resolvers'); var adminLookupMetaStream = require('../lib/streams/adminLookupMetaStream'); var peliasDocGenerator = require( '../lib/streams/peliasDocGenerator'); module.exports = function( filename ){ var pipeline = resolvers.selectSource( filename ) .pipe( geonames.pipeline ) .pipe( peliasDocGenerator.createPeliasDocGenerator() ); if( peliasConfig.imports.geonames.adminLookup ){ pipeline = pipeline .pipe( adminLookupMetaStream.create() ) .pipe( peliasAdminLookup.stream() ); } pipeline .pipe(model.createDocumentMapperStream()) .pipe( dbclient() ); };
var geonames = require('geonames-stream'); var peliasConfig = require( 'pelias-config' ).generate(); var peliasAdminLookup = require( 'pelias-admin-lookup' ); var dbclient = require('pelias-dbclient'); var model = require( 'pelias-model' ); var resolvers = require('./resolvers'); var adminLookupMetaStream = require('../lib/streams/adminLookupMetaStream'); var peliasDocGenerator = require( '../lib/streams/peliasDocGenerator'); module.exports = function( filename ){ var pipeline = resolvers.selectSource( filename ) .pipe( geonames.pipeline ) .pipe( peliasDocGenerator.create() ); if( peliasConfig.imports.geonames.adminLookup ){ pipeline = pipeline .pipe( adminLookupMetaStream.create() ) .pipe( peliasAdminLookup.stream() ); } pipeline .pipe(model.createDocumentMapperStream()) .pipe( dbclient() ); };
Use new function name for doc generator
Use new function name for doc generator
JavaScript
mit
pelias/geonames,pelias/geonames
6bb0842748a92359d383445e1046bb622a6649e4
tasks/build.js
tasks/build.js
/* Copyright (c) 2013, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://yuilibrary.com/license/ */ module.exports = function(grunt) { // The `artifacts` directory will usually only ever in YUI's CI system. // If you're in CI, and `build-npm` exists (meaning YUI's already built), skip the build. if ((grunt.file.exists('artifacts') && grunt.file.exists('build-npm')) || 'GRUNT_SKIP_BUILD' in process.env) { grunt.registerTask('build', 'Building YUI', function() { grunt.log.ok('Found GRUNT_SKIP_BUILD in environment, skipping build.'); }); } else { grunt.registerTask('build', 'Building YUI', ['yogi-build', 'npm']); } grunt.registerTask('build-test', 'Building and testing YUI', ['yogi-build', 'npm', 'test']); grunt.registerTask('all', 'Building and testing YUI', ['build-test']); };
/* Copyright (c) 2013, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://yuilibrary.com/license/ */ module.exports = function(grunt) { // The `artifacts` directory will usually only ever in YUI's CI system. // If you're in CI, `build-npm` exists, and this task was called in // response to the `postinstall` hook; skip the build. if ((process.env.npm_lifecycle_event === "postinstall" && grunt.file.exists('artifacts') && grunt.file.exists('build-npm')) || 'GRUNT_SKIP_BUILD' in process.env) { grunt.registerTask('build', 'Building YUI', function() { grunt.log.ok('Found GRUNT_SKIP_BUILD in environment, skipping build.'); }); } else { grunt.registerTask('build', 'Building YUI', ['yogi-build', 'npm']); } grunt.registerTask('build-test', 'Building and testing YUI', ['yogi-build', 'npm', 'test']); grunt.registerTask('all', 'Building and testing YUI', ['build-test']); };
Add more specificity to the CI "check."
Add more specificity to the CI "check."
JavaScript
bsd-3-clause
yui/grunt-yui-contrib
261149bf0046fda82bb80dbe50fcc2f6233fe779
modules/core/client/config/core-admin.client.routes.js
modules/core/client/config/core-admin.client.routes.js
'use strict'; // Setting up route angular.module('core.admin.routes').config(['$stateProvider', function ($stateProvider) { $stateProvider .state('admin', { abstract: true, url: '/admin', template: '<ui-view/>', data: { adminOnly: true } }) .state('admin.index', { url: '', templateUrl: 'modules/core/client/views/admin/list.client.view.html' }); } ]);
'use strict'; // Setting up route angular.module('core.admin.routes').config(['$stateProvider', function ($stateProvider) { $stateProvider .state('admin', { abstract: true, url: '/admin', template: '<ui-view/>', data: { adminOnly: true } }) .state('admin.index', { url: '', templateUrl: 'modules/core/client/views/admin/index.client.view.html' }); } ]);
Add event category descriptions + update style
Add event category descriptions + update style
JavaScript
mit
CEN3031GroupA/US-Hackathon,CEN3031GroupA/US-Hackathon,CEN3031GroupA/US-Hackathon
7c3f65c9492218d91d2213e9c5d5ae88d5ae2772
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' ) ); /** * @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;
'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 skewness * @memberof betaprime * @readonly * @type {Function} * @see {@link module:@stdlib/math/base/dist/betaprime/skewness} */ setReadOnly( betaprime, 'skewness', require( '@stdlib/math/base/dist/betaprime/skewness' ) ); /** * @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 skewness to beta prime namespace
Add skewness 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
40a96dbb0681ff912a64f8fdc3f542256dab1fd4
src/main/js/components/views/builder/SponsorAffinities.js
src/main/js/components/views/builder/SponsorAffinities.js
import React from 'react'; import { List, ListSubHeader, ListCheckbox } from 'react-toolbox/lib/list'; const SponsorAffinities = () => { return ( <div> <List selectable ripple> <ListSubHeader caption='list_a' /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> </List> <List selectable ripple> <ListSubHeader caption='list_b' /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> </List> </div> ); }; export default SponsorAffinities;
import React from 'react'; import { List, ListSubHeader, ListCheckbox } from 'react-toolbox/lib/list'; const SponsorAffinities = () => { return ( <div className="horizontal"> <List selectable ripple className="horizontalChild"> <ListSubHeader caption='list_a' /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> </List> <List selectable ripple className="horizontalChild"> <ListSubHeader caption='list_b' /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> <ListCheckbox caption='affinity' checked={false} /> </List> </div> ); }; export default SponsorAffinities;
Set classes for showing the lists horizontally
Set classes for showing the lists horizontally
JavaScript
apache-2.0
Bernardo-MG/dreadball-toolkit-webpage,Bernardo-MG/dreadball-toolkit-webpage,Bernardo-MG/dreadball-toolkit-webpage,Bernardo-MG/dreadball-toolkit-webpage
873e2e8a92b286e73375a0f3505615d63dde3d9e
server/graphql/queries/entries/multiple.js
server/graphql/queries/entries/multiple.js
const { GraphQLList, GraphQLString } = require('graphql'); const mongoose = require('mongoose'); const { outputType } = require('../../types/Entries'); const getProjection = require('../../get-projection'); const getUserPermissions = require('../../../utils/getUserPermissions'); const Entry = mongoose.model('Entry'); module.exports = { type: new GraphQLList(outputType), args: { status: { name: 'status', type: GraphQLString, }, }, async resolve(root, args, ctx, ast) { const projection = getProjection(ast); const perms = await getUserPermissions(ctx.user._id); if (!perms.canSeeDrafts) { return Entry .find({ status: 'live' }) .select(projection) .exec(); } return Entry .find(args) .select(projection) .exec(); }, };
const { GraphQLList, GraphQLString } = require('graphql'); const mongoose = require('mongoose'); const { outputType } = require('../../types/Entries'); const getProjection = require('../../get-projection'); const getUserPermissions = require('../../../utils/getUserPermissions'); const Entry = mongoose.model('Entry'); module.exports = { type: new GraphQLList(outputType), args: { status: { name: 'status', type: GraphQLString, }, }, async resolve(root, args, ctx, ast) { const projection = getProjection(ast); if (ctx.user) { const perms = await getUserPermissions(ctx.user._id); if (!perms.canSeeDrafts) { return Entry .find({ status: 'live' }) .select(projection) .exec(); } } return Entry .find(args) .select(projection) .exec(); }, };
Fix permissions check in Entries query
:lock: Fix permissions check in Entries query
JavaScript
mit
JasonEtco/flintcms,JasonEtco/flintcms
e67f17f3430c9509f4d1ff07ddefc6baf05780ff
client/actions/profile.js
client/actions/profile.js
import axios from 'axios'; import { FETCHING_PROFILE, PROFILE_SUCCESS, PROFILE_FAILURE } from './types'; import { apiURL } from './userSignUp'; import setHeader from '../helpers/setheader'; const fetchingProfile = () => ({ type: FETCHING_PROFILE, }); const profileSuccess = profile => ({ type: PROFILE_SUCCESS, profile, }); const profileFailure = error => ({ type: PROFILE_FAILURE, error, }); const getUserProfile = userId => (dispatch) => { dispatch(fetchingProfile()); setHeader(); return axios.get(`${apiURL}/users/${userId}`) .then((response) => { console.log(response.data); dispatch(profileSuccess(response.data)); }) .catch((error) => { if (error.response) { let errorMessage = ''; errorMessage = error.response.msg; dispatch(profileFailure(errorMessage)); } else { dispatch(profileFailure(error.message)); } }); }; export default getUserProfile;
import axios from 'axios'; import { FETCHING_PROFILE, PROFILE_SUCCESS, PROFILE_FAILURE, RETURN_BOOK_SUCCESS, RETURN_BOOK_REQUEST, RETURN_BOOK_FAILURE, } from './types'; import { apiURL } from './userSignUp'; import setHeader from '../helpers/setheader'; const fetchingProfile = () => ({ type: FETCHING_PROFILE, }); const profileSuccess = profile => ({ type: PROFILE_SUCCESS, profile, }); const profileFailure = error => ({ type: PROFILE_FAILURE, error, }); export const getUserProfile = userId => (dispatch) => { dispatch(fetchingProfile()); setHeader(); return axios.get(`${apiURL}/users/${userId}`) .then((response) => { console.log(response.data); dispatch(profileSuccess(response.data.user)); }) .catch((error) => { if (error.response) { let errorMessage = ''; errorMessage = error.response.msg; dispatch(profileFailure(errorMessage)); } else { dispatch(profileFailure(error.message)); } }); }; const returningBook = () => ({ type: RETURN_BOOK_REQUEST, }); const returnBookSuccess = returnRequest => ({ type: RETURN_BOOK_SUCCESS, returnRequest, }); const returnBookFailure = error => ({ type: RETURN_BOOK_FAILURE, error, }); export const returnBook = (userId, bookId) => (dispatch) => { dispatch(returningBook()); setHeader(); return axios.post(`${apiURL}/users/${userId}/return/${bookId}`) .then((response) => { console.log(response.data); dispatch(returnBookSuccess(response.data.returnRequest)); }) .catch((error) => { if (error.response) { let errorMessage = ''; errorMessage = error.response.msg; console.log(errorMessage); dispatch(returnBookFailure(errorMessage)); } else { dispatch(returnBookFailure(error.message)); } }); };
Add actions for returning a book
Add actions for returning a book
JavaScript
mit
amarachukwu-agbo/hello-books,amarachukwu-agbo/hello-books
a4e2361908ff921fa0033a4fecbf4abf2d5766da
client/app/docs/module.js
client/app/docs/module.js
/** * This file is part of Superdesk. * * Copyright 2013, 2014 Sourcefabric z.u. and contributors. * * For the full copyright and license information, please see the * AUTHORS and LICENSE files distributed with this source code, or * at https://www.sourcefabric.org/superdesk/license */ (function() { 'use strict'; var app = angular.module('superdesk.docs', []); MainDocsView.$inject = ['$location', '$anchorScroll']; function MainDocsView($location, $anchorScroll) { return { templateUrl: 'docs/views/main.html', link: function(scope, elem, attrs) { scope.scrollTo = function(id) { $location.hash(id); $anchorScroll(); }; } }; } app.directive('sdDocs', MainDocsView); app.directive('prettyprint', function() { return { restrict: 'C', link: function postLink(scope, element, attrs) { var langExtension = attrs['class'].match(/\blang(?:uage)?-([\w.]+)(?!\S)/); if (langExtension) { langExtension = langExtension[1]; } element.html(window.prettyPrintOne(_.escape(element.html()), langExtension, true)); } }; }); return app; })();
/** * This file is part of Superdesk. * * Copyright 2013, 2014 Sourcefabric z.u. and contributors. * * For the full copyright and license information, please see the * AUTHORS and LICENSE files distributed with this source code, or * at https://www.sourcefabric.org/superdesk/license */ (function() { 'use strict'; var app = angular.module('superdesk.docs', []); MainDocsView.$inject = ['$location', '$anchorScroll']; function MainDocsView($location, $anchorScroll) { return { templateUrl: '/docs/views/main.html', link: function(scope, elem, attrs) { scope.scrollTo = function(id) { $location.hash(id); $anchorScroll(); }; } }; } app.directive('sdDocs', MainDocsView); app.directive('prettyprint', function() { return { restrict: 'C', link: function postLink(scope, element, attrs) { var langExtension = attrs['class'].match(/\blang(?:uage)?-([\w.]+)(?!\S)/); if (langExtension) { langExtension = langExtension[1]; } element.html(window.prettyPrintOne(_.escape(element.html()), langExtension, true)); } }; }); return app; })();
Fix template url for UI docs
fix(docs): Fix template url for UI docs
JavaScript
agpl-3.0
mdhaman/superdesk-aap,sivakuna-aap/superdesk,thnkloud9/superdesk,pavlovicnemanja92/superdesk,ancafarcas/superdesk,hlmnrmr/superdesk,pavlovicnemanja92/superdesk,plamut/superdesk,superdesk/superdesk-ntb,marwoodandrew/superdesk-aap,verifiedpixel/superdesk,fritzSF/superdesk,superdesk/superdesk,verifiedpixel/superdesk,sivakuna-aap/superdesk,akintolga/superdesk,sivakuna-aap/superdesk,pavlovicnemanja92/superdesk,mugurrus/superdesk,plamut/superdesk,Aca-jov/superdesk,pavlovicnemanja/superdesk,mugurrus/superdesk,akintolga/superdesk-aap,petrjasek/superdesk,ancafarcas/superdesk,liveblog/superdesk,mdhaman/superdesk,superdesk/superdesk,superdesk/superdesk,thnkloud9/superdesk,Aca-jov/superdesk,superdesk/superdesk-ntb,vied12/superdesk,petrjasek/superdesk-ntb,petrjasek/superdesk,gbbr/superdesk,Aca-jov/superdesk,liveblog/superdesk,pavlovicnemanja/superdesk,mdhaman/superdesk-aap,darconny/superdesk,amagdas/superdesk,plamut/superdesk,marwoodandrew/superdesk,verifiedpixel/superdesk,pavlovicnemanja/superdesk,amagdas/superdesk,marwoodandrew/superdesk,sjunaid/superdesk,gbbr/superdesk,superdesk/superdesk-aap,verifiedpixel/superdesk,hlmnrmr/superdesk,vied12/superdesk,sivakuna-aap/superdesk,mdhaman/superdesk-aap,akintolga/superdesk-aap,marwoodandrew/superdesk-aap,fritzSF/superdesk,mdhaman/superdesk-aap,ancafarcas/superdesk,thnkloud9/superdesk,superdesk/superdesk,superdesk/superdesk-aap,fritzSF/superdesk,gbbr/superdesk,mdhaman/superdesk,ioanpocol/superdesk,petrjasek/superdesk,akintolga/superdesk,ioanpocol/superdesk,petrjasek/superdesk-ntb,ioanpocol/superdesk-ntb,amagdas/superdesk,petrjasek/superdesk-ntb,superdesk/superdesk-aap,darconny/superdesk,marwoodandrew/superdesk-aap,pavlovicnemanja92/superdesk,akintolga/superdesk,superdesk/superdesk-ntb,plamut/superdesk,superdesk/superdesk-ntb,verifiedpixel/superdesk,plamut/superdesk,hlmnrmr/superdesk,mdhaman/superdesk,ioanpocol/superdesk,vied12/superdesk,pavlovicnemanja/superdesk,ioanpocol/superdesk-ntb,sivakuna-aap/superdesk,mugurrus/superdesk,sjunaid/superdesk,marwoodandrew/superdesk,liveblog/superdesk,amagdas/superdesk,vied12/superdesk,amagdas/superdesk,akintolga/superdesk-aap,marwoodandrew/superdesk,ioanpocol/superdesk-ntb,akintolga/superdesk,darconny/superdesk,petrjasek/superdesk-ntb,marwoodandrew/superdesk,fritzSF/superdesk,liveblog/superdesk,fritzSF/superdesk,akintolga/superdesk-aap,superdesk/superdesk-aap,pavlovicnemanja92/superdesk,petrjasek/superdesk,akintolga/superdesk,marwoodandrew/superdesk-aap,vied12/superdesk,sjunaid/superdesk,liveblog/superdesk
8e8a784f1318f367f2a633395429abff30566c64
updates/0.1.0-fr-settings.js
updates/0.1.0-fr-settings.js
exports.create = { Settings: [{ "site": { "name": "EStore Demo" }, "payment.cod.active": true }] };
exports.create = { Settings: [{ "site": { "name": "EStore Demo" }, "payments.cod.active": true }] };
Fix no payment set by default error.
Fix no payment set by default error.
JavaScript
mit
stunjiturner/estorejs,quenktechnologies/estorejs,stunjiturner/estorejs
52fbbe3c5e4be1ad9be58fe862185a577a0e6c1f
packages/vega-parser/index.js
packages/vega-parser/index.js
// setup transform definition aliases import {definition} from 'vega-dataflow'; definition('Sort', definition('Collect')); definition('Formula', definition('Apply')); export {default as parse} from './src/parse'; export {default as selector} from './src/parsers/event-selector'; export {default as signal} from './src/parsers/signal'; export {default as signalUpdates} from './src/parsers/signal-updates'; export {default as stream} from './src/parsers/stream'; export { MarkRole, FrameRole, ScopeRole, AxisRole, AxisDomainRole, AxisGridRole, AxisLabelRole, AxisTickRole, AxisTitleRole, LegendRole, LegendEntryRole, LegendLabelRole, LegendSymbolRole, LegendTitleRole } from './src/parsers/marks/roles'; export {marktypes, isMarkType} from './src/parsers/marks/marktypes'; export {default as Scope} from './src/Scope'; export {default as DataScope} from './src/DataScope';
// setup transform definition aliases import {definition} from 'vega-dataflow'; definition('Formula', definition('Apply')); export {default as parse} from './src/parse'; export {default as selector} from './src/parsers/event-selector'; export {default as signal} from './src/parsers/signal'; export {default as signalUpdates} from './src/parsers/signal-updates'; export {default as stream} from './src/parsers/stream'; export { MarkRole, FrameRole, ScopeRole, AxisRole, AxisDomainRole, AxisGridRole, AxisLabelRole, AxisTickRole, AxisTitleRole, LegendRole, LegendEntryRole, LegendLabelRole, LegendSymbolRole, LegendTitleRole } from './src/parsers/marks/roles'; export {marktypes, isMarkType} from './src/parsers/marks/marktypes'; export {default as Scope} from './src/Scope'; export {default as DataScope} from './src/DataScope';
Drop Sort alias for Collect.
Drop Sort alias for Collect.
JavaScript
bsd-3-clause
lgrammel/vega,vega/vega,vega/vega,vega/vega,vega/vega
e569c4f2081979947e7b948de870978e9bde719a
app/elements/sidebar.js
app/elements/sidebar.js
import * as React from 'react' import {State} from 'react-router' import SearchButton from 'elements/searchButton' import GraduationStatus from 'elements/graduationStatus' let Sidebar = React.createClass({ mixins: [State], render() { let isSearching = this.getQuery().search let sidebar = isSearching ? React.createElement(SearchButton, {search: isSearching}) : React.createElement(GraduationStatus, {student: this.props.student, sections: this.getQuery().sections}) return sidebar }, }) export default Sidebar
import * as React from 'react' import {State} from 'react-router' import SearchButton from 'elements/searchButton' import GraduationStatus from 'elements/graduationStatus' let Sidebar = React.createClass({ mixins: [State], render() { let isSearching = 'search' in this.getQuery() let sidebar = isSearching ? React.createElement(SearchButton, {search: isSearching}) : React.createElement(GraduationStatus, {student: this.props.student, sections: this.getQuery().sections}) return sidebar }, }) export default Sidebar
Use `in` to detect if the query param has "search"
Use `in` to detect if the query param has "search"
JavaScript
agpl-3.0
hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook
1c3042481b75e305e993316256dc19f51fd41cf6
SPAWithAngularJS/module2/customServices/js/app.shoppingListService.js
SPAWithAngularJS/module2/customServices/js/app.shoppingListService.js
// app.shoppingListService.js (function() { "use strict"; angular.module("MyApp") .service("ShoppingListService", ShoppingListService); function ShoppingListService() { let service = this; // List of Shopping items let items = []; service.addItem = addItem; function addItem(itemName, itemQuantity) { console.log("ShoppingListService", itemName, itemQuantity); let item = { name: itemName, quantity: itemQuantity }; items.push(item); } service.getItems = getItems; function getItems() { return items; } } })();
// app.shoppingListService.js (function() { "use strict"; angular.module("MyApp") .service("ShoppingListService", ShoppingListService); function ShoppingListService() { let service = this; // List of Shopping items let items = []; service.addItem = addItem; service.getItems = getItems; service.removeItem = removeItem; function addItem(itemName, itemQuantity) { let item = { name: itemName, quantity: itemQuantity }; items.push(item); } function getItems() { return items; } function removeItem(itemIndex) { items.splice(itemIndex, 1); } } })();
Delete useless code. Added removeItem method
Delete useless code. Added removeItem method
JavaScript
mit
var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training
47b9aba68050230eeff0754f4076b7596cbe9eb9
api/throttle.js
api/throttle.js
"use strict" module.exports = function(callback) { //60fps translates to 16.6ms, round it down since setTimeout requires int var time = 16 var last = 0, pending = null var timeout = typeof requestAnimationFrame === "function" ? requestAnimationFrame : setTimeout return function(synchronous) { var now = new Date().getTime() if (synchronous === true || last === 0 || now - last >= time) { last = now callback() } else if (pending === null) { pending = timeout(function() { pending = null callback() last = new Date().getTime() }, time - (now - last)) } } }
"use strict" var ts = Date.now || function() { return new Date().getTime() } module.exports = function(callback) { //60fps translates to 16.6ms, round it down since setTimeout requires int var time = 16 var last = 0, pending = null var timeout = typeof requestAnimationFrame === "function" ? requestAnimationFrame : setTimeout return function(synchronous) { var now = ts() if (synchronous === true || last === 0 || now - last >= time) { last = now callback() } else if (pending === null) { pending = timeout(function() { pending = null callback() last = ts() }, time - (now - last)) } } }
Use Date.now() if available since it's faster
Use Date.now() if available since it's faster
JavaScript
mit
pygy/mithril.js,impinball/mithril.js,tivac/mithril.js,MithrilJS/mithril.js,barneycarroll/mithril.js,barneycarroll/mithril.js,tivac/mithril.js,impinball/mithril.js,pygy/mithril.js,lhorie/mithril.js,lhorie/mithril.js,MithrilJS/mithril.js
a5add8048b2548c5f216d7afd9e0ebcb097f4fcc
lib/dom/accessibility/sections.js
lib/dom/accessibility/sections.js
(function() { 'use strict'; var headings = ['h6', 'h5', 'h4', 'h3', 'h2', 'h1']; var score = 0; var message = ''; var sections = Array.prototype.slice.call(window.document.getElementsByTagName('section')); var totalSections = sections.length; if (totalSections === 0) { message = 'The page doesn\'t use sections. You could possible use them to get a better structure of your content.'; score = 100; } else { sections.forEach(function(section) { var hasHeading = false; headings.forEach(function(heading) { var tags = Array.prototype.slice.call(section.getElementsByTagName(heading)); if (tags.length > 0) { hasHeading = true; } }, this); if (!hasHeading) { score += 10; message += ' The page is missing a heading within a section tag on the page.'; } }) } return { id: 'sections', title: 'Use headings tags within section tags to better structure your page', description: 'Section tags should have at least one heading element as a direct descendant.', advice: message, score: Math.max(0, 100 - score), weight: 0, offending: [], tags: ['accessibility', 'html'] }; })();
(function() { 'use strict'; var headings = ['h6', 'h5', 'h4', 'h3', 'h2', 'h1']; var score = 0; var message = ''; var sections = Array.prototype.slice.call(window.document.getElementsByTagName('section')); var totalSections = sections.length; if (totalSections === 0) { message = 'The page doesn\'t use sections. You could possible use them to get a better structure of your content.'; score = 100; } else { sections.forEach(function(section) { var hasHeading = false; headings.forEach(function(heading) { var tags = Array.prototype.slice.call(section.getElementsByTagName(heading)); if (tags.length > 0) { hasHeading = true; } }); if (!hasHeading) { score += 10; message = 'The page is missing a heading within a section tag on the page.'; } }) } return { id: 'sections', title: 'Use headings tags within section tags to better structure your page', description: 'Section tags should have at least one heading element as a direct descendant.', advice: message, score: Math.max(0, 100 - score), weight: 0, offending: [], tags: ['accessibility', 'html'] }; })();
Remove extra space in message.
Remove extra space in message.
JavaScript
mit
sitespeedio/coach,sitespeedio/coach
18ac5c64a7da29e5bf25bc274c61ad6078bace86
config/environments.config.js
config/environments.config.js
// Here is where you can define configuration overrides based on the execution environment. // Supply a key to the default export matching the NODE_ENV that you wish to target, and // the base configuration will apply your overrides before exporting itself. module.exports = { // ====================================================== // Overrides when NODE_ENV === 'development' // ====================================================== // NOTE: In development, we use an explicit public path when the assets // are served webpack by to fix this issue: // http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809 development : (config) => ({ compiler_public_path : `http://${config.server_host}:${config.server_port}/` }), // ====================================================== // Overrides when NODE_ENV === 'production' // ====================================================== production : (config) => ({ compiler_public_path : '/', compiler_fail_on_warning : false, compiler_hash_type : 'chunkhash', compiler_devtool : null, compiler_stats : { chunks : true, chunkModules : true, colors : true } }) }
// Here is where you can define configuration overrides based on the execution environment. // Supply a key to the default export matching the NODE_ENV that you wish to target, and // the base configuration will apply your overrides before exporting itself. module.exports = { // ====================================================== // Overrides when NODE_ENV === 'development' // ====================================================== // NOTE: In development, we use an explicit public path when the assets // are served webpack by to fix this issue: // http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809 development : (config) => ({ compiler_public_path : `http://${config.server_host}:${config.server_port}/` }), // ====================================================== // Overrides when NODE_ENV === 'production' // ====================================================== production : (config) => ({ compiler_public_path : '/', compiler_fail_on_warning : false, compiler_hash_type : 'chunkhash', compiler_devtool : 'source-map', compiler_stats : { chunks : true, chunkModules : true, colors : true } }) }
Enable sourcemaps on production builds
Enable sourcemaps on production builds
JavaScript
mit
matthisk/es6console,matthisk/es6console
a095b3f6f17687fb769670f236f4224556254edd
js/game.js
js/game.js
// Game define([ 'stage', 'models/ui', 'utility' ], function(Stage, UI, Utility) { console.log("game.js loaded"); var Game = (function() { // Game canvas var stage; var gameUI; return { // Initialize the game init: function() { stage = new Stage('game-canvas'); gameUI = new UI(stage); gameUI.init(); stage.addChild(gameUI); } } })(); return Game; });
// Game define([ 'stage', 'models/ui', 'utility' ], function(Stage, UI, Utility) { console.log("game.js loaded"); var Game = (function() { // Game canvas var stage; var gameUI; return { // Initialize the game init: function() { try { stage = new Stage('game-canvas'); } catch(e) { alert('Cannot obtain the canvas context.'); return; } gameUI = new UI(stage); gameUI.init(); stage.addChild(gameUI); } } })(); return Game; });
Add try-catch block for obtaining canvas context
Add try-catch block for obtaining canvas context
JavaScript
mit
vicksonzero/TyphoonTycoon,vicksonzero/TyphoonTycoon,ericksli/TyphoonTycoon,jasonycw/TyphoonTycoon,ericksli/TyphoonTycoon,jasonycw/TyphoonTycoon
1802e997a2d682ec3fc05d292e95fd64f3258b1b
src/components/fields/Text/index.js
src/components/fields/Text/index.js
import React from 'react' export default class Text extends React.Component { static propTypes = { onChange: React.PropTypes.func, value: React.PropTypes.string, fieldType: React.PropTypes.string, passProps: React.PropTypes.object, placeholder: React.PropTypes.node, errorMessage: React.PropTypes.node } static defaultProps = { fieldType: 'text', value: '' } render () { return ( <div> <div className='os-input-container'> <input ref='input' className='os-input-text' type={this.props.fieldType} value={this.props.value} placeholder={this.props.placeholder} onChange={event => this.props.onChange(event.target.value)} {...this.props.passProps} /> </div> <div className='os-input-error'>{this.props.errorMessage}</div> </div> ) } }
import React from 'react' export default class Text extends React.Component { static propTypes = { onChange: React.PropTypes.func, value: React.PropTypes.string, fieldType: React.PropTypes.string, passProps: React.PropTypes.object, placeholder: React.PropTypes.node, errorMessage: React.PropTypes.node, disabled: React.PropTypes.boolean } static defaultProps = { fieldType: 'text', value: '' } render () { return ( <div> <div className='os-input-container'> <input ref='input' className='os-input-text' type={this.props.fieldType} value={this.props.value} placeholder={this.props.placeholder} onChange={event => this.props.onChange(event.target.value)} disabled={this.props.disabled} {...this.props.passProps} /> </div> <div className='os-input-error'>{this.props.errorMessage}</div> </div> ) } }
Add disabled to text input
Add disabled to text input
JavaScript
mit
orionsoft/parts
82a4e6147a20b6583df43375e70b593a73cf0396
lib/transport/ssh.spec.js
lib/transport/ssh.spec.js
'use strict'; const { expect } = require('chai'); const SshTransport = require('./ssh'); describe('SshTransport', () => { it('should not use a private key if password is specified', () => { const options = getTransportOptions({ password: 'pass' }); expect(options.usePrivateKey).to.be.false; expect(options.privateKeyPath).to.be.undefined; }); it('should use a private key if password is not specified', () => { const options = getTransportOptions(); expect(options.usePrivateKey).to.be.true; expect(options.privateKeyPath).not.to.be.undefined; }); }); function getTransportOptions(config) { const options = Object.assign({ remoteUrl: '/', remotePath: '/' }, config); const ssh = new SshTransport({ transport: options }); return ssh.options; }
'use strict'; const { expect } = require('chai'); const SshTransport = require('./ssh'); class NoExceptionSshTransport extends SshTransport { normalizeOptions() { try { super.normalizeOptions(); } catch (e) { this.error = e; } } } describe('SshTransport', () => { it('should not use a private key if password is specified', () => { const options = getTransportOptions({ password: 'pass' }); expect(options.usePrivateKey).to.be.false; expect(options.privateKeyPath).to.be.undefined; }); it('should use a private key if password is not specified', () => { const options = getTransportOptions(); expect(options.usePrivateKey).to.be.true; expect(options.privateKeyPath).not.to.be.undefined; }); }); function getTransportOptions(config) { const options = Object.assign({ remoteUrl: '/', remotePath: '/' }, config); const ssh = new NoExceptionSshTransport({ transport: options }); return ssh.options; }
Fix a test on travis
Fix a test on travis
JavaScript
mit
megahertz/electron-simple-publisher
a08a2e797d2783defdd2551bf2ca203e54a3702b
js/main.js
js/main.js
// Github API call according to their json-p dox function callGHAPI(url, callback) { var apiRoot = "https://api.github.com/"; var script = document.createElement("script"); script.src = apiRoot + url + "?callback=" + callback; document.getElementsByTagName("head")[0].appendChild(script); } // validate the user input function validateInput() { if ($("#username").val().length > 0 && $("#repository").val().length > 0) { $("#get-stats-button").prop("disabled", false); } else { $("#get-stats-button").prop("disabled", true); } } // Callback function for getting user repositories function getUserReposCB(response) { var data = response.data; var repoNames = []; $.each(data, function(index, item) { repoNames.push(data[index].name); }); $("#repository").typeahead({source: repoNames}); } // The main function $(function() { validateInput(); $("#username, #repository").keyup(validateInput); $("#username").change(function() { var user = $("#username").val(); callGHAPI("users/" + user + "/repos", "getUserReposCB"); }); });
// Github API call according to their json-p dox function callGHAPI(url, callback) { var apiRoot = "https://api.github.com/"; var script = document.createElement("script"); script.src = apiRoot + url + "?callback=" + callback; document.getElementsByTagName("head")[0].appendChild(script); } // validate the user input function validateInput() { if ($("#username").val().length > 0 && $("#repository").val().length > 0) { $("#get-stats-button").prop("disabled", false); } else { $("#get-stats-button").prop("disabled", true); } } // Callback function for getting user repositories function getUserReposCB(response) { var data = response.data; var repoNames = []; $.each(data, function(index, item) { repoNames.push(data[index].name); }); var autoComplete = $('#repository').typeahead(); autoComplete.data('typeahead').source = repoNames; } // The main function $(function() { validateInput(); $("#username, #repository").keyup(validateInput); $("#username").change(function() { var user = $("#username").val(); callGHAPI("users/" + user + "/repos", "getUserReposCB"); }); });
Update typeahead source when different user entered
Update typeahead source when different user entered
JavaScript
mit
Somsubhra/github-release-stats,Somsubhra/github-release-stats
a1b98bb9dad8a3a82fe750dc09d470e14fe233ec
js/main.js
js/main.js
--- layout: null --- $(document).ready(function () { $('a.events-button').click(function (e) { if ($('.panel-cover').hasClass('panel-cover--collapsed')) return currentWidth = $('.panel-cover').width() if (currentWidth < 960) { $('.panel-cover').addClass('panel-cover--collapsed') $('.content-wrapper').addClass('animated slideInRight') } else { $('.panel-cover').css('max-width', currentWidth) $('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {}) } }) if (window.location.hash && window.location.hash == '#events') { $('.panel-cover').addClass('panel-cover--collapsed') } if (window.location.pathname !== '{{ site.baseurl }}' && window.location.pathname !== '{{ site.baseurl }}index.html') { $('.panel-cover').addClass('panel-cover--collapsed') } $('.btn-mobile-menu').click(function () { $('.navigation-wrapper').toggleClass('visible animated bounceInDown') $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn') }) $('.navigation-wrapper .events-button').click(function () { $('.navigation-wrapper').toggleClass('visible') $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn') }) })
--- layout: null --- $(document).ready(function () { $('a.events-button').click(function (e) { if ($('.panel-cover').hasClass('panel-cover--collapsed')) return currentWidth = $('.panel-cover').width() if (currentWidth < 960) { $('.panel-cover').addClass('panel-cover--collapsed') $('.content-wrapper').addClass('animated slideInRight') } else { $('.panel-cover').css('max-width', currentWidth) $('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {}) } }) if (window.location.hash && window.location.hash == '#events') { $('.panel-cover').addClass('panel-cover--collapsed') } if (window.location.pathname !== '{{ site.baseurl }}') { $('.panel-cover').addClass('panel-cover--collapsed') } $('.btn-mobile-menu').click(function () { $('.navigation-wrapper').toggleClass('visible animated bounceInDown') $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn') }) $('.navigation-wrapper .events-button').click(function () { $('.navigation-wrapper').toggleClass('visible') $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn') }) })
Fix defaulting to events page, maybe....
Fix defaulting to events page, maybe....
JavaScript
mit
GRPosh/GRPosh.github.io,GRPosh/GRPosh.github.io,GRPosh/GRPosh.github.io
86773197f53aeb163de92fbd9f339d53903dd4c3
lib/viewer/DataSetView.js
lib/viewer/DataSetView.js
import React from 'react'; export default React.createClass({ displayName: 'DataSetViewer', propTypes: { base: React.PropTypes.string, item: React.PropTypes.object, }, openDataSet() { ArcticViewer.load('http://' + location.host + this.props.base + this.props.item.path, document.querySelector('.react-content')); }, render() { return ( <div className='DataSetView'> <div className='DataSetView__thumbnail' onClick={ this.openDataSet } style={{ backgroundImage: 'url(' + this.props.base + this.props.item.thumbnail + ')' }}> <i className={this.props.item.thumbnail ? '' : 'fa fa-question' }></i> </div> <div className='DataSetView__titleBar'> <strong>{ this.props.item.name }</strong> <span className='DataSetView__size'>{ this.props.item.size }</span> </div> <div className='DataSetView__description'> { this.props.item.description } </div> </div> ); }, });
import React from 'react'; export default React.createClass({ displayName: 'DataSetViewer', propTypes: { base: React.PropTypes.string, item: React.PropTypes.object, }, openDataSet() { ArcticViewer.load('http://' + location.host + this.props.base + this.props.item.path, document.querySelector('.react-content')); // eslint-disable-line }, render() { return ( <div className='DataSetView'> <div className='DataSetView__thumbnail' onClick={ this.openDataSet } style={{ backgroundImage: 'url(' + this.props.base + this.props.item.thumbnail + ')' }}> <i className={this.props.item.thumbnail ? '' : 'fa fa-question' }></i> </div> <div className='DataSetView__titleBar'> <strong>{ this.props.item.name }</strong> <span className='DataSetView__size'>{ this.props.item.size }</span> </div> <div className='DataSetView__description'> { this.props.item.description } </div> </div> ); }, });
Update code formatting to comply with our ESLint specification
style(ESLint): Update code formatting to comply with our ESLint specification
JavaScript
bsd-3-clause
Kitware/arctic-viewer,Kitware/in-situ-data-viewer,Kitware/in-situ-data-viewer,Kitware/arctic-viewer,Kitware/arctic-viewer
97889608f3e80095e139d3da69be2b24df6eacd7
components/guestbookCapture.js
components/guestbookCapture.js
/** @jsxImportSource theme-ui */ import { Box, Button } from 'theme-ui' import Link from 'next/link' import Sparkle from './sparkle' import Spicy from './spicy' // email export default function GuestbookCapture({ props }) { return ( <Box sx={{ position: 'relative', p: [3, 3, 4], bg: 'elevated', height: 'fit-content', borderRadius: '4px', maxWidth: ['100%', '50%'], }} > <h3> <Spicy>Sign the web3 guestbook!</Spicy> </h3> <p> Connect with your favorite wallet, and sign the Web3 Guestbook with a gasless meta-transaction. </p> <Link href="/guestbook"> <Button title="Discuss on Twitter"> <Sparkle>Guestbook</Sparkle> </Button> </Link> </Box> ) }
/** @jsxImportSource theme-ui */ import { Box, Button } from 'theme-ui' import Link from 'next/link' import Sparkle from './sparkle' import Spicy from './spicy' // email export default function GuestbookCapture({ props }) { return ( <Box sx={{ position: 'relative', p: [3, 3, 4], bg: 'elevated', height: 'fit-content', borderRadius: '4px', }} > <h3> <Spicy>Sign the web3 guestbook!</Spicy> </h3> <p> Connect with your favorite wallet, and sign the Web3 Guestbook with a gasless meta-transaction. </p> <Link href="/guestbook"> <Button title="Discuss on Twitter"> <Sparkle>Guestbook</Sparkle> </Button> </Link> </Box> ) }
Remove max-width from guestbook capture
Remove max-width from guestbook capture
JavaScript
mit
iammatthias/.com,iammatthias/.com,iammatthias/.com
783a18b1ed4e3053861315eccfee5bf55a467c02
services/frontend/src/components/elements/account/follow.js
services/frontend/src/components/elements/account/follow.js
import React from 'react'; import steem from 'steem' import { Button } from 'semantic-ui-react' export default class AccountFollow extends React.Component { constructor(props) { super(props) this.state = { processing: false, following: props.account.following || [] } } componentWillReceiveProps(nextProps) { if(this.state.processing && nextProps.length !== this.state.following.length) { this.setState({processing: false}) } } follow = (e) => { this.setState({processing: true}) this.props.actions.follow({ account: this.props.account, action: "follow", who: this.props.who }) } unfollow = (e) => { this.setState({processing: true}) this.props.actions.follow({ account: this.props.account, action: "unfollow", who: this.props.who }) } render() { const loading = (this.state.processing || !this.props.account || !this.props.account.following) const following = (this.props.account.following && this.props.account.following.indexOf(this.props.who) !== -1) return ( <Button color={(loading) ? 'grey' : (following) ? 'orange' : 'green' } content={(following) ? 'Unfollow' : 'Follow'} loading={loading} onClick={(loading) ? () => {} : (following) ? this.unfollow : this.follow} /> ) } }
import React from 'react'; import steem from 'steem' import { Button } from 'semantic-ui-react' export default class AccountFollow extends React.Component { constructor(props) { super(props) this.state = { processing: false, following: props.account.following || [] } } componentWillReceiveProps(nextProps) { if(this.state.processing && nextProps.length !== this.state.following.length) { this.setState({processing: false}) } } follow = (e) => { this.setState({processing: true}) this.props.actions.follow({ account: this.props.account, action: "follow", who: this.props.who }) } unfollow = (e) => { this.setState({processing: true}) this.props.actions.follow({ account: this.props.account, action: "unfollow", who: this.props.who }) } render() { if(this.props.account.name === this.props.who) return false const loading = (this.state.processing || !this.props.account || !this.props.account.following) const following = (this.props.account.following && this.props.account.following.indexOf(this.props.who) !== -1) return ( <Button color={(loading) ? 'grey' : (following) ? 'orange' : 'green' } content={(following) ? 'Unfollow' : 'Follow'} loading={loading} onClick={(loading) ? () => {} : (following) ? this.unfollow : this.follow} /> ) } }
Hide for your own account.
Hide for your own account.
JavaScript
mit
aaroncox/chainbb,aaroncox/chainbb
6b00187f384c2078cb06c5d8dab4d5ef48ca8953
src/web_loaders/ember-app-loader/get-module-exports.js
src/web_loaders/ember-app-loader/get-module-exports.js
const HarmonyExportExpressionDependency = require( "webpack/lib/dependencies/HarmonyExportExpressionDependency" ); const HarmonyExportSpecifierDependency = require( "webpack/lib/dependencies/HarmonyExportSpecifierDependency" ); const HarmonyExportImportedSpecifierDependency = require( "webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency" ); module.exports = function getModuleExportsFactory( loaderContext ) { return path => new Promise( ( resolve, reject ) => { loaderContext.loadModule( path, ( error, source, sourceMap, { dependencies } ) => { if ( error || !dependencies ) { return reject( error ); } // does the module have a default export? const exports = dependencies.find( d => d instanceof HarmonyExportExpressionDependency ) // just resolve with the default export name ? [ "default" ] // get the list of all export names instead : dependencies .filter( d => d instanceof HarmonyExportSpecifierDependency || d instanceof HarmonyExportImportedSpecifierDependency ) .map( dependency => dependency.name ); resolve( exports ); }); }); };
const HarmonyExportExpressionDependency = require( "webpack/lib/dependencies/HarmonyExportExpressionDependency" ); const HarmonyExportSpecifierDependency = require( "webpack/lib/dependencies/HarmonyExportSpecifierDependency" ); const HarmonyExportImportedSpecifierDependency = require( "webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency" ); module.exports = function getModuleExportsFactory( loaderContext ) { return path => new Promise( ( resolve, reject ) => { loaderContext.loadModule( path, ( error, source, sourceMap, { dependencies } = {} ) => { if ( error || !dependencies ) { return reject( error ); } // does the module have a default export? const exports = dependencies.find( d => d instanceof HarmonyExportExpressionDependency ) // just resolve with the default export name ? [ "default" ] // get the list of all export names instead : dependencies .filter( d => d instanceof HarmonyExportSpecifierDependency || d instanceof HarmonyExportImportedSpecifierDependency ) .map( dependency => dependency.name ); resolve( exports ); }); }); };
Fix ember-app-loader error on invalid modules
Fix ember-app-loader error on invalid modules
JavaScript
mit
chhe/livestreamer-twitch-gui,streamlink/streamlink-twitch-gui,bastimeyer/livestreamer-twitch-gui,chhe/livestreamer-twitch-gui,bastimeyer/livestreamer-twitch-gui,streamlink/streamlink-twitch-gui,streamlink/streamlink-twitch-gui,chhe/livestreamer-twitch-gui,bastimeyer/livestreamer-twitch-gui
cc63c5d48f48294163b1e9d01efa8b8fc00fce06
client/index.js
client/index.js
import 'babel-polyfill'; require('normalize.css'); require('reveal.js/css/reveal.css'); require('reveal.js/css/theme/black.css'); require('./index.css'); import reveal from 'reveal.js'; import setupMedimapWidgets from './medimap-widget.js'; reveal.initialize({ controls: false, progress: false, loop: true, shuffle: true, autoSlide: 20 * 1000, autoSlideStoppable: false, transition: 'slide', transitionSpeed: 'default', backgroundTransition: 'slide', }); // Setup all medimap widgets setupMedimapWidgets();
import 'babel-polyfill'; require('normalize.css'); require('reveal.js/css/reveal.css'); require('reveal.js/css/theme/black.css'); require('./index.css'); import reveal from 'reveal.js'; import setupMedimapWidgets from './medimap-widget.js'; reveal.initialize({ controls: false, progress: false, loop: true, shuffle: true, autoSlide: 20 * 1000, autoSlideStoppable: false, transition: 'fade', transitionSpeed: 'default', backgroundTransition: 'fade', }); // Setup all medimap widgets setupMedimapWidgets();
Switch to fade transition (performance issues)
Switch to fade transition (performance issues)
JavaScript
mit
jo12bar/medimap-viewer,jo12bar/medimap-viewer,jo12bar/medimap-viewer,jo12bar/medimap-viewer,jo12bar/medimap-viewer
908c305b901b73e92cd0e1ef4fd0f76d1aa2ea72
lib/config.js
lib/config.js
var fs = require('fs'); var mkdirp = require('mkdirp'); var existsSync = fs.existsSync || path.existsSync; // to support older nodes than 0.8 var CONFIG_FILE_NAME = 'config.json'; var Config = function(home) { this.home = home; this.load(); }; Config.prototype = { home: null, data: {}, configFilePath: function() { return this.home + '/' + CONFIG_FILE_NAME; }, load: function() { if (existsSync(this.configFilePath())) { this.data = JSON.parse(fs.readFileSync(this.configFilePath())); } }, save: function() { var json = JSON.stringify(this.data); mkdirp.sync(this.home); fs.writeFileSync(this.configFilePath(), json); } }; module.exports.Config = Config;
var fs = require('fs'); var mkdirp = require('mkdirp'); var existsSync = fs.existsSync || require('path').existsSync; // to support older nodes than 0.8 var CONFIG_FILE_NAME = 'config.json'; var Config = function(home) { this.home = home; this.load(); }; Config.prototype = { home: null, data: {}, configFilePath: function() { return this.home + '/' + CONFIG_FILE_NAME; }, load: function() { if (existsSync(this.configFilePath())) { this.data = JSON.parse(fs.readFileSync(this.configFilePath())); } }, save: function() { var json = JSON.stringify(this.data); mkdirp.sync(this.home); fs.writeFileSync(this.configFilePath(), json); } }; module.exports.Config = Config;
Add the missing require for path module
Add the missing require for path module
JavaScript
mit
groonga/gcs-console
8262f90630783eb9329613aaf676b2b43c960dff
lib/CarbonClient.js
lib/CarbonClient.js
var RestClient = require('carbon-client') var util = require('util') var fibrous = require('fibrous'); /**************************************************************************************************** * monkey patch the endpoint class to support sync get/post/put/delete/head/patch */ var Endpoint = RestClient.super_ /**************************************************************************************************** * syncifyClassMethod * * @param clazz the class * @param methodName name of the method to syncify */ function syncifyClassMethod(clazz, methodName){ var asyncMethod = clazz.prototype[methodName] clazz.prototype[methodName] = function() { // if last argument is a callback then run async if(arguments && (typeof(arguments[arguments.length-1]) === 'function') ) { asyncMethod.apply(this, arguments); } else { // sync call! return asyncMethod.sync.apply(this, arguments); } } } // syncify all Endpoint methods Endpoint.ALL_METHODS.forEach(function(m) { syncifyClassMethod(Endpoint, m) }) // syncify Collection methods var Collection = Endpoint.collectionClass Collection.ALL_METHODS.forEach(function(m) { syncifyClassMethod(Collection, m) }) /**************************************************************************************************** * exports */ module.exports = RestClient
var RestClient = require('carbon-client') var util = require('util') var fibrous = require('fibrous'); /**************************************************************************************************** * monkey patch the endpoint class to support sync get/post/put/delete/head/patch */ var Endpoint = RestClient.super_ /**************************************************************************************************** * syncifyClassMethod * * @param clazz the class * @param methodName name of the method to syncify */ function syncifyClassMethod(clazz, methodName){ var asyncMethod = clazz.prototype[methodName] clazz.prototype[methodName] = function() { // if last argument is a callback then run async if(arguments && (typeof(arguments[arguments.length-1]) === 'function') ) { asyncMethod.apply(this, arguments); } else { // sync call! return asyncMethod.sync.apply(this, arguments); } } } // syncify all Endpoint methods var ENDPOINT_METHODS = [ "get", "post", "head", "put", "delete", "patch" ] ENDPOINT_METHODS.forEach(function(m) { syncifyClassMethod(Endpoint, m) }) // syncify Collection methods var COLLECTION_METHODS = [ "find", "insert", "update", "remove" ] var Collection = Endpoint.collectionClass COLLECTION_METHODS.forEach(function(m) { syncifyClassMethod(Collection, m) }) /**************************************************************************************************** * exports */ module.exports = RestClient
Move method list to node client
Move method list to node client
JavaScript
mit
carbon-io/carbon-client-node,carbon-io/carbon-client-node
4855e94ed7492a333597b4715a9d606cb74ab086
plugins/services/src/js/pages/task-details/ServiceTaskDetailPage.js
plugins/services/src/js/pages/task-details/ServiceTaskDetailPage.js
import React from 'react'; import TaskDetail from './TaskDetail'; import MesosStateStore from '../../../../../../src/js/stores/MesosStateStore'; import ServiceBreadcrumbs from '../../components/ServiceBreadcrumbs'; import Page from '../../../../../../src/js/components/Page'; class ServiceTaskDetailPage extends React.Component { render() { const {params, routes} = this.props; const {id, taskID} = params; let routePrefix = `/services/overview/${encodeURIComponent(id)}/tasks/${encodeURIComponent(taskID)}`; const tabs = [ {label: 'Details', routePath: routePrefix + '/details'}, {label: 'Files', routePath: routePrefix + '/files'}, {label: 'Logs', routePath: routePrefix + '/logs'} ]; let task = MesosStateStore.getTaskFromTaskID(taskID); if (task == null) { return this.getNotFound('task', taskID); } const breadcrumbs = ( <ServiceBreadcrumbs serviceID={id} taskID={task.getId()} taskName={task.getName()} /> ); return ( <Page> <Page.Header breadcrumbs={breadcrumbs} tabs={tabs} iconID="services" /> <TaskDetail params={params} routes={routes}> {this.props.children} </TaskDetail> </Page> ); } } TaskDetail.propTypes = { params: React.PropTypes.object, routes: React.PropTypes.array }; module.exports = ServiceTaskDetailPage;
import React from 'react'; import TaskDetail from './TaskDetail'; import MesosStateStore from '../../../../../../src/js/stores/MesosStateStore'; import ServiceBreadcrumbs from '../../components/ServiceBreadcrumbs'; import Page from '../../../../../../src/js/components/Page'; class ServiceTaskDetailPage extends React.Component { render() { const {params, routes} = this.props; const {id, taskID} = params; let routePrefix = `/services/overview/${encodeURIComponent(id)}/tasks/${encodeURIComponent(taskID)}`; const tabs = [ {label: 'Details', routePath: routePrefix + '/details'}, {label: 'Files', routePath: routePrefix + '/files'}, {label: 'Logs', routePath: routePrefix + '/view'} ]; let task = MesosStateStore.getTaskFromTaskID(taskID); if (task == null) { return this.getNotFound('task', taskID); } const breadcrumbs = ( <ServiceBreadcrumbs serviceID={id} taskID={task.getId()} taskName={task.getName()} /> ); return ( <Page> <Page.Header breadcrumbs={breadcrumbs} tabs={tabs} iconID="services" /> <TaskDetail params={params} routes={routes}> {this.props.children} </TaskDetail> </Page> ); } } TaskDetail.propTypes = { params: React.PropTypes.object, routes: React.PropTypes.array }; module.exports = ServiceTaskDetailPage;
Fix up route to logs tab
Fix up route to logs tab
JavaScript
apache-2.0
dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui
0f2fc159b5c0622b20f34d9eed915c7563237a7a
lib/cfn.js
lib/cfn.js
exports.init = function(genericAWSClient) { // Creates a CloudFormation API client var createCFNClient = function (accessKeyId, secretAccessKey, options) { options = options || {}; var client = cfnClient({ host: options.host || "cloudformation.us-east-1.amazonaws.com", path: options.path || "/", accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, secure: options.secure, version: options.version }); return client; } // Amazon CloudFormation API handler which is wrapped around the genericAWSClient var cfnClient = function(obj) { var aws = genericAWSClient({ host: obj.host, path: obj.path, accessKeyId: obj.accessKeyId, secretAccessKey: obj.secretAccessKey, secure: obj.secure }); obj.call = function(action, query, callback) { query["Action"] = action query["Version"] = obj.version || '2010-08-01' query["SignatureMethod"] = "HmacSHA256" query["SignatureVersion"] = "2" return aws.call(action, query, callback); } return obj; } return createCFNClient; }
exports.init = function(genericAWSClient) { // Creates a CloudFormation API client var createCFNClient = function (accessKeyId, secretAccessKey, options) { options = options || {}; var client = cfnClient({ host: options.host || "cloudformation.us-east-1.amazonaws.com", path: options.path || "/", accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, secure: options.secure, version: options.version }); return client; } // Amazon CloudFormation API handler which is wrapped around the genericAWSClient var cfnClient = function(obj) { var aws = genericAWSClient({ host: obj.host, path: obj.path, accessKeyId: obj.accessKeyId, secretAccessKey: obj.secretAccessKey, secure: obj.secure }); obj.call = function(action, query, callback) { query["Action"] = action query["Version"] = obj.version || '2010-05-15' query["SignatureMethod"] = "HmacSHA256" query["SignatureVersion"] = "2" return aws.call(action, query, callback); } return obj; } return createCFNClient; }
Use advertised API version for CFN.
Use advertised API version for CFN.
JavaScript
mit
mirkokiefer/aws-lib,livelycode/aws-lib,pnedunuri/aws-lib
370857a2c3d321b2fb1e7177de266b8422112425
app/assets/javascripts/alchemy/alchemy.jquery_loader.js
app/assets/javascripts/alchemy/alchemy.jquery_loader.js
if (typeof(Alchemy) === 'undefined') { var Alchemy = {}; } // Load jQuery on demand. Use this if jQuery is not present. // Found on http://css-tricks.com/snippets/jquery/load-jquery-only-if-not-present/ Alchemy.loadjQuery = function(callback) { var thisPageUsingOtherJSLibrary = false; if (typeof($) === 'function') { thisPageUsingOtherJSLibrary = true; } function getScript(url, success) { var script = document.createElement('script'); var head = document.getElementsByTagName('head')[0], done = false; script.src = url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if (!done && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete')) { done = true; // callback function provided as param success(); script.onload = script.onreadystatechange = null; head.removeChild(script); }; }; head.appendChild(script); } getScript('/assets/jquery.min.js', function() { if (typeof(jQuery) !== 'undefined') { if (thisPageUsingOtherJSLibrary) { jQuery.noConflict(); } callback(jQuery); } }); }
if (typeof(Alchemy) === 'undefined') { var Alchemy = {}; } // Load jQuery on demand. Use this if jQuery is not present. // Found on http://css-tricks.com/snippets/jquery/load-jquery-only-if-not-present/ Alchemy.loadjQuery = function(callback) { var thisPageUsingOtherJSLibrary = false; if (typeof($) === 'function') { thisPageUsingOtherJSLibrary = true; } function getScript(url, success) { var script = document.createElement('script'); var head = document.getElementsByTagName('head')[0], done = false; script.src = url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if (!done && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete')) { done = true; // callback function provided as param success(); script.onload = script.onreadystatechange = null; head.removeChild(script); }; }; head.appendChild(script); } getScript('//code.jquery.com/jquery.min.js', function() { if (typeof(jQuery) !== 'undefined') { if (thisPageUsingOtherJSLibrary) { jQuery.noConflict(); } callback(jQuery); } }); }
Load jquery from cdn instead of locally for menubar.
Load jquery from cdn instead of locally for menubar.
JavaScript
bsd-3-clause
clst/alchemy_cms,mtomov/alchemy_cms,nielspetersen/alchemy_cms,mamhoff/alchemy_cms,thomasjachmann/alchemy_cms,heisam/alchemy_cms,Domenoth/alchemy_cms,kinsomicrote/alchemy_cms,mamhoff/alchemy_cms,thomasjachmann/alchemy_cms,cygnus6/alchemy_cms,IngoAlbers/alchemy_cms,robinboening/alchemy_cms,AlchemyCMS/alchemy_cms,cygnus6/alchemy_cms,paperculture/alchemy_cms,Domenoth/alchemy_cms,akra/alchemy_cms,mtomov/alchemy_cms,thomasjachmann/alchemy_cms,heisam/alchemy_cms,getkiwicom/alchemy_cms,jsqu99/alchemy_cms,mamhoff/alchemy_cms,IngoAlbers/alchemy_cms,AlchemyCMS/alchemy_cms,phaedryx/alchemy_cms,heisam/alchemy_cms,watg/alchemy_cms,chalmagean/alchemy_cms,phaedryx/alchemy_cms,IngoAlbers/alchemy_cms,chalmagean/alchemy_cms,Domenoth/alchemy_cms,akra/alchemy_cms,akra/alchemy_cms,phaedryx/alchemy_cms,cygnus6/alchemy_cms,clst/alchemy_cms,mixandgo/alchemy_cms,mixandgo/alchemy_cms,mtomov/alchemy_cms,thomasjachmann/alchemy_cms,watg/alchemy_cms,getkiwicom/alchemy_cms,mixandgo/alchemy_cms,watg/alchemy_cms,paperculture/alchemy_cms,nielspetersen/alchemy_cms,cygnus6/alchemy_cms,akra/alchemy_cms,chalmagean/alchemy_cms,getkiwicom/alchemy_cms,IngoAlbers/alchemy_cms,heisam/alchemy_cms,phaedryx/alchemy_cms,chalmagean/alchemy_cms,getkiwicom/alchemy_cms,jsqu99/alchemy_cms,kinsomicrote/alchemy_cms,nielspetersen/alchemy_cms,watg/alchemy_cms,paperculture/alchemy_cms,AlchemyCMS/alchemy_cms,robinboening/alchemy_cms,clst/alchemy_cms,robinboening/alchemy_cms,jsqu99/alchemy_cms,paperculture/alchemy_cms,jsqu99/alchemy_cms,mtomov/alchemy_cms,kinsomicrote/alchemy_cms,nielspetersen/alchemy_cms,Domenoth/alchemy_cms,mixandgo/alchemy_cms,kinsomicrote/alchemy_cms,clst/alchemy_cms
2d1dd9b1bbfd7b07bdcae40613899eab31c75f9a
lib/wee.js
lib/wee.js
#! /usr/bin/env node /* global require, process */ var program = require('commander'), fs = require('fs'), cwd = process.cwd(), cliPath = cwd + '/node_modules/wee-core/cli.js'; // Register version and init command program .version(require('../package').version) .usage('<command> [options]') .command('init [name]', 'create a new project'); fs.stat(cliPath, function(err) { if (err !== null) { fs.stat('./package.json', function(err) { if (err !== null) { console.log('Wee package.json not found in current directory'); return; } fs.readFile('./package.json', function(err, data) { if (err) { console.log(err); return; } // Check for valid Wee installation var config = JSON.parse(data); if (config.name == 'wee-framework' || config.name == 'wee') { console.log('Run "npm install" to install Wee core'); } else { console.log('The package.json is not compatible with Wee'); } }); }); return; } // Register all other commands from specific project require(cliPath)(cwd, program); // Process cli input and execute command program.parse(process.argv); });
#! /usr/bin/env node /* global require, process */ var program = require('commander'), fs = require('fs'), cwd = process.cwd(), cliPath = cwd + '/node_modules/wee-core/cli.js'; // Register version and init command program .version(require('../package').version) .usage('<command> [options]') .command('init [name]', 'create a new project'); // TODO: Finish init command // Set help as default command if nothing found program .on('*', () => { program.outputHelp(); }); fs.stat(cliPath, function(err) { if (err !== null) { fs.stat('./package.json', function(err) { if (err !== null) { console.log('Wee package.json not found in current directory'); return; } fs.readFile('./package.json', function(err, data) { if (err) { console.log(err); return; } // Check for valid Wee installation var config = JSON.parse(data); if (config.name == 'wee-framework' || config.name == 'wee') { console.log('Run "npm install" to install Wee core'); } else { console.log('The package.json is not compatible with Wee'); } }); }); return; } // Register all other commands from specific project require(cliPath)(cwd, program); // Process cli input and execute command program.parse(process.argv); });
Print out help menu when incorrect argument is given
Print out help menu when incorrect argument is given
JavaScript
apache-2.0
weepower/wee-cli
63284bdb3177e678208650e0b738dc9876afa643
app/components/Todo.js
app/components/Todo.js
import React, { PropTypes } from 'react' import ListItem from 'material-ui/lib/lists/list-item' import Checkbox from 'material-ui/lib/checkbox' import ActionDelete from 'material-ui/lib/svg-icons/action/delete' const Todo = ({ onClick, onDelete, completed, text }) => ( <ListItem onClick={onClick} primaryText={text} leftCheckbox={<Checkbox checked={completed} />} rightIcon={<ActionDelete onClick={onDelete} />} /> ) Todo.propTypes = { onClick: PropTypes.func.isRequired, onDelete: PropTypes.func.isRequired, completed: PropTypes.bool.isRequired, text: PropTypes.string.isRequired } export default Todo
import React, { PropTypes } from 'react' import ListItem from 'material-ui/lib/lists/list-item' import Checkbox from 'material-ui/lib/checkbox' import ActionDelete from 'material-ui/lib/svg-icons/action/delete' const Todo = ({ onClick, onDelete, completed, text }) => ( <ListItem onClick={onClick} primaryText={text} leftCheckbox={<Checkbox checked={completed} />} rightIcon={<ActionDelete onClick={onDelete} />} style={completed ? {textDecoration: 'line-through'} : {}} /> ) Todo.propTypes = { onClick: PropTypes.func.isRequired, onDelete: PropTypes.func.isRequired, completed: PropTypes.bool.isRequired, text: PropTypes.string.isRequired } export default Todo
Add strike-through for completed tasks
Add strike-through for completed tasks
JavaScript
mit
rxlabs/tasty-todos,rxlabs/tasty-todos,rxlabs/tasty-todos
ad03ed2e56b56f22fc0f148dd6e6027eab718591
specs/server/ServerSpec.js
specs/server/ServerSpec.js
/* global require, describe, it */ 'use strict'; var expect = require('chai').expect; var request = require('request'); var url = function(path) { return 'http://localhost:8000' + path; }; describe('GET /', function() { it('responds', function(done){ request(url('/'), function(error, res) { expect(res.statusCode).to.equal(200); done(); }); }); }); describe('GET /index.html', function() { it('responds', function(done){ request(url('/indexs.html'), function(error, res) { expect(res.headers['content-type'].indexOf('html')).to.not.equal(-1); done(); }); }); }); describe('GET /no-such-file.html', function() { it('responds', function(done){ request(url('/no-such-file.html'), function(error, res) { expect(res.statusCode).to.equal(404); done(); }); }); });
/* global require, describe, it */ 'use strict'; var expect = require('chai').expect; var request = require('request'); var url = function(path) { return 'http://localhost:8000' + path; }; describe("MongoDB", function() { it("is there a server running", function(next) { var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://127.0.0.1:27017/brainstormer', function(err, db) { expect(err).to.equal(null); next(); }); }); }); describe('GET /', function() { it('responds', function(done){ request(url('/'), function(error, res) { expect(res.statusCode).to.equal(200); done(); }); }); }); describe('GET /index.html', function() { it('responds', function(done){ request(url('/indexs.html'), function(error, res) { expect(res.headers['content-type'].indexOf('html')).to.not.equal(-1); done(); }); }); }); describe('GET /no-such-file.html', function() { it('responds', function(done){ request(url('/no-such-file.html'), function(error, res) { expect(res.statusCode).to.equal(404); done(); }); }); });
Add test to ensure mongodb is running.
Add test to ensure mongodb is running.
JavaScript
mit
JulieMarie/Brainstorm,HRR2-Brainstorm/Brainstorm,JulieMarie/Brainstorm,ekeric13/Brainstorm,EJJ-Brainstorm/Brainstorm,EJJ-Brainstorm/Brainstorm,ekeric13/Brainstorm,plauer/Brainstorm,drabinowitz/Brainstorm
7f08b0b8950ee9e4123b2d5332f2fcfe8616d771
lib/daemon-setup.js
lib/daemon-setup.js
(function() { 'use strict'; exports.init = function(params) { var fs = require('fs'); var path = require('path'); var service = params['service']; var shell = require('shelljs'); if (!service) { throw new Error('missing required parameter "service"'); } createUser(); enableLogging(); writeUpstart(); enableDaemon(); function createUser() { console.log('creating user ' + service); } function writeUpstart() { var srcFile = path.join(__dirname, 'template.upstart'); console.log('upstart contents:'); fs.readFile(srcFile, 'utf8', function(err, data) { if (err) { return console.log(err); } console.log(data); }); } function enableLogging() { var logPath = path.join(process.env.npm_config_quichean_logging_path, service); console.log('log path: ' + logPath); } function enableDaemon() { console.log('enabling daemon'); } }; })();
(function() { 'use strict'; exports.init = function(params) { var fs = require('fs'); var path = require('path'); var service = params['service']; var shell = require('shelljs'); if (!service) { throw new Error('missing required parameter "service"'); } createUser(); enableLogging(); writeUpstart(); enableDaemon(); function createUser() { console.log('creating user ' + service); } function writeUpstart() { //var srcFile = path.join(__dirname, 'template.upstart'); var srcFile = path.join(__dirname, 'foo.upstart'); console.log('upstart contents:'); fs.readFile(srcFile, 'utf8', function(err, data) { if (err) { throw new Error(err); } console.log(data); }); } function enableLogging() { var logPath = path.join(process.env.npm_config_quichean_logging_path, service); console.log('log path: ' + logPath); } function enableDaemon() { console.log('enabling daemon'); } }; })();
Verify that exception is raised if appropriate.
Verify that exception is raised if appropriate.
JavaScript
mit
optbot/daemon-setup,optbot/daemon-setup
788c0adabe8a1501e8032e5b9d90afcc5c4927ab
lib/delve-client.js
lib/delve-client.js
/** DelveClient @description creates a singleton Delve client **/ 'use babel'; const DelveClient = require('delvejs'); var delveClient; const connManager = { connect: function connect(host, port) { delveClient = new DelveClient(host, port); return delveClient.establishSocketConn(); }, endConnection: function endConnection() { delveClient.endSession(); delveClient = null; } }; export { connManager as DelveConnMgr }; export default delveClient;
/** DelveClient @description creates a singleton Delve client **/ 'use babel'; const DelveClient = require('delvejs'); var delveClient; const connManager = { isConnected: false, connect: function connect(host, port) { delveClient = new DelveClient(host, port); return delveClient.establishSocketConn() .then(() => this.isConnected = true); }, endConnection: function endConnection() { if (this.isConnected) { delveClient.endSession(); delveClient = null; } } }; export { connManager as DelveConnMgr }; export default delveClient;
Check for is connected before ending
Check for is connected before ending
JavaScript
mit
tylerFowler/atom-delve
31fde45536d569f6629b4896d61b4f6093059f2c
source/@lacqueristas/signals/refreshResources/index.js
source/@lacqueristas/signals/refreshResources/index.js
import {map} from "ramda" import mergeResource from "../mergeResource" export default function refreshResources (): Function { return function thunk (dispatch: ReduxDispatchType, getState: GetStateType, {client}: {client: HSDKClientType}): Promise<SignalType> { const state = getState() map((collection: Array<any>) => { map((member: any): any => { const {id} = member const {type} = member const {meta} = member const {version} = meta // TODO: Check for staleness instead of always refreshing if (id && type && version && client[type][version].show) { return client[type][version] .show({id}) .then(({data}: {data: any}): SignalType => dispatch(mergeResource(data))) } return member }, collection) }, state.resources) } }
import {ok} from "httpstatuses" import {forEach} from "ramda" import {omit} from "ramda" import * as resources from "@lacqueristas/resources" import mergeResource from "../mergeResource" const MAPPING = { accounts: "account", sessions: "session", projects: "project", } export default function refreshResources (): Function { return function thunk (dispatch: ReduxDispatchType, getState: GetStateType, {client}: {client: HSDKClientType}): Promise<SignalType> { const state = getState() forEach((collection: Array<Promise<ResourceType>>) => { forEach((member: ResourceType) => { const {id} = member const {type} = member const {meta} = member const {version} = meta // TODO: Check for staleness instead of always refreshing if (id && type && version && client[type][version].show) { client[type][version] .show({id}) .then(({data, status}: {data: JSONAPIResponse, status: number}): ResourceType => { const resource = resources[MAPPING[type]] switch (status) { case ok: { return omit(["__abstraction__"], resource(data.data)) } default: { return Promise.reject(new Error("We received an unexpected status code from the server")) } } }) .then((resource: ResourceType): SignalType => dispatch(mergeResource(resource))) .catch(console.error.bind(console)) } }, collection) }, state.resources) return dispatch({type: "refreshResources"}) } }
Refactor for abstractions and better control flow
Refactor for abstractions and better control flow
JavaScript
mit
lacqueristas/www,lacqueristas/www
4893fe0778f0e6a3876d0c634d5437c3f7e6911d
lib/controllers/api/v1/users.js
lib/controllers/api/v1/users.js
'use strict'; var mongoose = require('mongoose'), utils = require('../utils'), User = mongoose.model('User'), Application = mongoose.model('Application'), SimpleApiKey = mongoose.model('SimpleApiKey'), OauthConsumer = mongoose.model('OauthConsumer'), Event = mongoose.model('Event'), middleware = require('../../../middleware'), devsite = require('../../../clients/devsite'); module.exports = function(app, cacher) { }
'use strict'; var mongoose = require('mongoose'), utils = require('../utils'), User = mongoose.model('User'), Application = mongoose.model('Application'), SimpleApiKey = mongoose.model('SimpleApiKey'), OauthConsumer = mongoose.model('OauthConsumer'), Event = mongoose.model('Event'), User = mongoose.model('User'), Chapter = mongoose.model('Chapter'), middleware = require('../../../middleware'), devsite = require('../../../clients/devsite'); module.exports = function(app, cacher) { app.route("get", "/organizer/:gplusId", {}, cacher.cache('hours', 24), function(req, res) { Chapter.find({organizers: req.params.gplusId}, function(err, chapters) { if (err) { console.log(err); return res.send(500, "Internal Error"); } var response = { msg: "ok", user: req.params.gplusId, chapters: [] }; for(var i = 0; i < chapters.length; i++) { response.chapters.push({ id: chapters[i]._id, name: chapters[i].name }); } return res.send(200, response); } ); }); }
Add organizer Endpoint to API
Add organizer Endpoint to API
JavaScript
apache-2.0
Splaktar/hub,gdg-x/hub,gdg-x/hub,nassor/hub,fchuks/hub,nassor/hub,fchuks/hub,Splaktar/hub
a4187de0cd7c54363cc6225f72fe9093b8a8b4c8
src/javascripts/ng-admin/Main/component/directive/maDashboardPanel.js
src/javascripts/ng-admin/Main/component/directive/maDashboardPanel.js
function maDashboardPanel($state) { return { restrict: 'E', scope: { collection: '&', entries: '&' }, link: function(scope) { scope.gotoList = function () { $state.go($state.get('list'), { entity: scope.collection().entity.name() }); }; }, template: '<div class="panel-heading">' + '<a ng-click="gotoList()">{{ collection().title() || collection().entity().label() }}</a>' + '</div>' + '<ma-datagrid name="{{ collection().name() }}"' + ' entries="entries()"' + ' fields="::collection().fields()"' + ' entity="::collection().entity"' + ' list-actions="::collection().listActions()">' + '</ma-datagrid>' }; } maDashboardPanel.$inject = ['$state']; module.exports = maDashboardPanel;
function maDashboardPanel($state) { return { restrict: 'E', scope: { collection: '&', entries: '&' }, link: function(scope) { scope.gotoList = function () { $state.go($state.get('list'), { entity: scope.collection().entity.name() }); }; }, template: '<div class="panel-heading">' + '<a ng-click="gotoList()">{{ collection().title() || collection().entity.label() }}</a>' + '</div>' + '<ma-datagrid name="{{ collection().name() }}"' + ' entries="entries()"' + ' fields="::collection().fields()"' + ' entity="::collection().entity"' + ' list-actions="::collection().listActions()">' + '</ma-datagrid>' }; } maDashboardPanel.$inject = ['$state']; module.exports = maDashboardPanel;
Fix dashboard panel title when dashboard is undefined
Fix dashboard panel title when dashboard is undefined
JavaScript
mit
Benew/ng-admin,LuckeyHomes/ng-admin,ulrobix/ng-admin,maninga/ng-admin,manuelnaranjo/ng-admin,ronal2do/ng-admin,jainpiyush111/ng-admin,baytelman/ng-admin,manekinekko/ng-admin,eBoutik/ng-admin,marmelab/ng-admin,rifer/ng-admin,baytelman/ng-admin,rifer/ng-admin,bericonsulting/ng-admin,SebLours/ng-admin,SebLours/ng-admin,ahgittin/ng-admin,thachp/ng-admin,thachp/ng-admin,rao1219/ng-admin,jainpiyush111/ng-admin,jainpiyush111/ng-admin,LuckeyHomes/ng-admin,manekinekko/ng-admin,bericonsulting/ng-admin,ulrobix/ng-admin,eBoutik/ng-admin,janusnic/ng-admin,LuckeyHomes/ng-admin,zealot09/ng-admin,vasiakorobkin/ng-admin,vasiakorobkin/ng-admin,Benew/ng-admin,VincentBel/ng-admin,eBoutik/ng-admin,shekhardesigner/ng-admin,gxr1028/ng-admin,marmelab/ng-admin,janusnic/ng-admin,marmelab/ng-admin,manuelnaranjo/ng-admin,AgustinCroce/ng-admin,AgustinCroce/ng-admin,VincentBel/ng-admin,spfjr/ng-admin,ahgittin/ng-admin,jainpiyush111/ng-admin,rao1219/ng-admin,zealot09/ng-admin,shekhardesigner/ng-admin,ronal2do/ng-admin,heliodor/ng-admin,arturbrasil/ng-admin,spfjr/ng-admin,arturbrasil/ng-admin,gxr1028/ng-admin,heliodor/ng-admin,ulrobix/ng-admin,maninga/ng-admin
d4a57ac1e7516a75a3770e23a06241366a90dbcb
spec/lib/repository-mappers/figshare/parseL1ArticlePresenters-spec.js
spec/lib/repository-mappers/figshare/parseL1ArticlePresenters-spec.js
import parseL1ArticlePresenters from '../../../../lib/repository-mappers/figshare/parseL1ArticlePresenters'; const figshareL1Articles = require('./resources/figshareL1Articles.json'); const convertedArticles = parseL1ArticlePresenters(figshareL1Articles); it('parses all articles figshare returns', () => expect(convertedArticles.length).toBe(2) ); it('converts Figshare article DOIs to codemeta identifier', () => { expect(convertedArticles[0].identifier).toBe(figshareL1Articles[0].doi); expect(convertedArticles[1].identifier).toBe(figshareL1Articles[1].doi); }); it('converts Figshare article titles to codemeta titles', () => { expect(convertedArticles[0].title).toBe(convertedArticles[0].title); expect(convertedArticles[1].title).toBe(convertedArticles[1].title); }); it('converts Figshare article published date to codemeta date published', () => { expect(convertedArticles[0].datePublished).toBe(figshareL1Articles[0].published_date); expect(convertedArticles[1].datePublished).toBe(figshareL1Articles[1].published_date); });
import parseL1ArticlePresenters from '../../../../lib/repository-mappers/figshare/parseL1ArticlePresenters'; const figshareL1Articles = require('./resources/figshareL1Articles.json'); const convertedArticles = parseL1ArticlePresenters(figshareL1Articles); it('parses all articles figshare returns', () => expect(convertedArticles.length).toBe(2) ); it('parses Figshare article IDs', () => { expect(convertedArticles[0].id).toBe(figshareL1Articles[0].id); expect(convertedArticles[1].id).toBe(figshareL1Articles[1].id); }); it('converts Figshare article DOIs to codemeta identifier', () => { expect(convertedArticles[0].identifier).toBe(figshareL1Articles[0].doi); expect(convertedArticles[1].identifier).toBe(figshareL1Articles[1].doi); }); it('converts Figshare article titles to codemeta titles', () => { expect(convertedArticles[0].title).toBe(convertedArticles[0].title); expect(convertedArticles[1].title).toBe(convertedArticles[1].title); }); it('converts Figshare article published date to codemeta date published', () => { expect(convertedArticles[0].datePublished).toBe(figshareL1Articles[0].published_date); expect(convertedArticles[1].datePublished).toBe(figshareL1Articles[1].published_date); });
Add unit test for Figshare ID in L1 presenter
Add unit test for Figshare ID in L1 presenter
JavaScript
mit
mozillascience/software-discovery-dashboard,mozillascience/software-discovery-dashboard
5df003b17e805ea3c649330bd72fe3d0d7ad085d
app/src/store/index.js
app/src/store/index.js
import Vue from "vue"; import Vuex, {Store} from "vuex"; import state from "./state"; import * as mutations from "./mutations"; import * as getters from "./getters"; import * as actions from "./actions"; import {persistencePlugin, i18nPlugin} from "./plugins"; Vue.use(Vuex); export default new Store({ strict: process.env.NODE_ENV !== "production", state, mutations, getters, actions, plugins: [ persistencePlugin({ prefix: "sulcalc", saveOn: { addCustomSets: "sets.custom", setSmogonSets: "enabledSets.smogon", setPokemonPerfectSets: "enabledSets.pokemonPerfect", setCustomSets: "enabledSets.custom", setLongRolls: "longRolls", setFractions: "fractions" } }), i18nPlugin() ] });
import Vue from "vue"; import Vuex, {Store} from "vuex"; import state from "./state"; import * as mutations from "./mutations"; import * as getters from "./getters"; import * as actions from "./actions"; import {persistencePlugin, i18nPlugin} from "./plugins"; Vue.use(Vuex); export default new Store({ strict: process.env.NODE_ENV !== "production", state, mutations, getters, actions, plugins: [ persistencePlugin({ prefix: "sulcalc", saveOn: { importPokemon: "sets.custom", toggleSmogonSets: "enabledSets.smogon", togglePokemonPerfectSets: "enabledSets.pokemonPerfect", toggleCustomSets: "enabledSets.custom", toggleLongRolls: "longRolls", toggleFractions: "fractions" } }), i18nPlugin() ] });
Fix persistence issues not tracking the correct mutations
Fix persistence issues not tracking the correct mutations
JavaScript
mit
sulcata/sulcalc,sulcata/sulcalc,sulcata/sulcalc
1d894193ceebc30520ef2d18a6c15452f52a2e30
tests/dummy/app/controllers/collapsible.js
tests/dummy/app/controllers/collapsible.js
export default Ember.Controller.extend({ actions: { collapseLeft: function() { this.get('leftChild').collapse(); }, collapseRight: function() { this.get('rightChild').collapse(); } } });
import Ember from 'ember'; export default Ember.Controller.extend({ actions: { collapseLeft: function() { this.get('leftChild').collapse(); }, collapseRight: function() { this.get('rightChild').collapse(); } } });
Add missing import ember to dummy app
Add missing import ember to dummy app
JavaScript
mit
BryanCrotaz/ember-split-view,BryanHunt/ember-split-view,BryanCrotaz/ember-split-view,BryanHunt/ember-split-view
d0f443c0b9c32a72faa67de95da03a01025c2ad0
config/nconf.js
config/nconf.js
var nconf = require('nconf'); nconf .env(); nconf.defaults({ 'RIPPLE_REST_API': 'http://localhost:5990', 'DATABASE_URL': 'postgres://postgres:password@localhost:5432/ripple_gateway', 'RIPPLE_DATAMODEL_ADAPTER': 'ripple-gateway-data-sequelize-adapter', 'RIPPLE_EXPRESS_GATEWAY': 'ripple-gateway-express', 'SSL': true, 'PORT': 5000 }); module.exports = nconf;
var nconf = require('nconf'); nconf .file({ file: './config/config.json' }) .env(); nconf.defaults({ 'RIPPLE_REST_API': 'http://localhost:5990', 'DATABASE_URL': 'postgres://postgres:password@localhost:5432/ripple_gateway', 'RIPPLE_DATAMODEL_ADAPTER': 'ripple-gateway-data-sequelize-adapter', 'RIPPLE_EXPRESS_GATEWAY': 'ripple-gateway-express', 'SSL': true, 'PORT': 5000 }); module.exports = nconf;
Load base config from file.
[FEATURE] Load base config from file.
JavaScript
isc
zealord/gatewayd,Parkjeahwan/awegeeks,xdv/gatewayd,Parkjeahwan/awegeeks,whotooktwarden/gatewayd,xdv/gatewayd,crazyquark/gatewayd,zealord/gatewayd,whotooktwarden/gatewayd,crazyquark/gatewayd
e9d0001580fcd7178334071d6ea9040da9df49a9
jest.setup.js
jest.setup.js
/* eslint-disable import/no-unassigned-import */ import 'raf/polyfill' import 'mock-local-storage' import {configure} from 'enzyme' import Adapter from 'enzyme-adapter-react-16' configure({adapter: new Adapter()})
/* eslint-disable import/no-unassigned-import */ import 'raf/polyfill' import 'mock-local-storage' import {configure} from 'enzyme' import Adapter from 'enzyme-adapter-react-16' import {setConfig} from 'next/config' configure({adapter: new Adapter()}) // Initialize Next.js configuration with empty values. setConfig({ publicRuntimeConfig: {}, secretRuntimeConfig: {} })
Set default configuration for tests
Set default configuration for tests
JavaScript
mit
sgmap/inspire,sgmap/inspire
e6bfa9f7036d4ad51af84a9205616b4782a5db91
geoportal/geoportailv3_geoportal/static-ngeo/js/backgroundselector/BackgroundselectorDirective.js
geoportal/geoportailv3_geoportal/static-ngeo/js/backgroundselector/BackgroundselectorDirective.js
import appModule from '../module.js'; /** * @param {string} appBackgroundselectorTemplateUrl Url to backgroundselector template. * @return {angular.IDirective} * @ngInject */ const exports = function(appBackgroundselectorTemplateUrl) { return { restrict: 'E', scope: { 'map': '=appBackgroundselectorMap' }, controller: 'AppBackgroundselectorController', controllerAs: 'ctrl', bindToController: true, templateUrl: appBackgroundselectorTemplateUrl } } appModule.directive('appBackgroundselector', exports); export default exports;
import appModule from '../module.js'; /** * @param {string} appBackgroundselectorTemplateUrl Url to backgroundselector template. * @return {angular.IDirective} * @ngInject */ const exports = function(appBackgroundselectorTemplateUrl) { return { restrict: 'E', scope: { 'map': '=appBackgroundselectorMap' }, controller: 'AppBackgroundselectorController', controllerAs: 'ctrl', bindToController: true, templateUrl: appBackgroundselectorTemplateUrl } } // Custom directive for the "vector tiles style" upload button appModule.directive('customOnChange', function() { return { restrict: 'A', link: function (scope, element, attrs) { var onChangeHandler = scope.$eval(attrs.customOnChange); element.on('change', onChangeHandler); element.on('$destroy', function() { element.off(); }); } }; }); appModule.directive('appBackgroundselector', exports); export default exports;
Add missing customOnChange directive for the new background selector component
Add missing customOnChange directive for the new background selector component
JavaScript
mit
Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3
067d0b0d647385559f5008aa62c89b18688431c0
karma.conf.js
karma.conf.js
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html const path = require('path'); process.env.CHROME_BIN = require('puppeteer').executablePath(); module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: path.join(__dirname, 'coverage/app'), reports: ['html'], fixWebpackSourcePaths: true }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['ChromeHeadless'], singleRun: false, restartOnFileChange: true }); };
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html const path = require('path'); process.env.CHROME_BIN = require('puppeteer').executablePath(); module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client:{ captureConsole: false, clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: path.join(__dirname, 'coverage/app'), reports: ['html'], fixWebpackSourcePaths: true }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['ChromeHeadless'], singleRun: false, restartOnFileChange: true }); };
Disable unit test console logging
Disable unit test console logging
JavaScript
mit
kiswa/TaskBoard,kiswa/TaskBoard,kiswa/TaskBoard,kiswa/TaskBoard,kiswa/TaskBoard
6cbd9e5ade62b19781fce3263aa8890242aa2804
contentcuration/contentcuration/frontend/shared/vuex/snackbar/index.js
contentcuration/contentcuration/frontend/shared/vuex/snackbar/index.js
export default { state: { isVisible: false, options: { text: '', autoDismiss: true, }, }, getters: { snackbarIsVisible(state) { return state.isVisible; }, snackbarOptions(state) { return state.options; }, }, mutations: { CORE_CREATE_SNACKBAR(state, snackbarOptions = {}) { // reset state.isVisible = false; state.options = {}; // set new options state.isVisible = true; // options include text, autoDismiss, duration, actionText, actionCallback, // hideCallback, bottomPosition state.options = snackbarOptions; }, CORE_CLEAR_SNACKBAR(state) { state.isVisible = false; state.options = {}; }, CORE_SET_SNACKBAR_TEXT(state, text) { state.options.text = text; }, }, };
export default { state: { isVisible: false, options: { text: '', // duration in ms, 0 indicates it should not automatically dismiss duration: 6000, actionText: '', actionCallback: null, }, }, getters: { snackbarIsVisible(state) { return state.isVisible; }, snackbarOptions(state) { return state.options; }, }, actions: { showSnackbar({ commit }, { text, duration, actionText, actionCallback }) { commit('CORE_CREATE_SNACKBAR', { text, duration, actionText, actionCallback }); }, clearSnackbar({ commit }) { commit('CORE_CLEAR_SNACKBAR'); } }, mutations: { CORE_CREATE_SNACKBAR(state, snackbarOptions = {}) { // reset state.isVisible = false; state.options = {}; // set new options state.isVisible = true; // options include text, duration, actionText, actionCallback, // hideCallback, bottomPosition state.options = snackbarOptions; }, CORE_CLEAR_SNACKBAR(state) { state.isVisible = false; state.options = {}; }, CORE_SET_SNACKBAR_TEXT(state, text) { state.options.text = text; }, }, };
Remove `autoDismiss` and add actions
Remove `autoDismiss` and add actions - `autoDismiss: false` can be done by making duration `null` in this case the snackbar won't dismiss until the button is clicked on the snackbar item - Now we can dispatch actions rather than commit mutations directly. Per Vue 'best practices'
JavaScript
mit
DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation
a003149c2d98a236c320bd84c0e484a6cf62f370
packages/rekit-studio/src/features/common/monaco/setupLinter.js
packages/rekit-studio/src/features/common/monaco/setupLinter.js
/* eslint no-use-before-define: 0 */ import _ from 'lodash'; import axios from 'axios'; let editor; let monaco; // Worker always run and will never terminate // There is only one global editor instance never disposed in Rekit Studio. function setupLintWorker(_editor, _monaco) { editor = _editor; monaco = _monaco; editor.onDidChangeModelContent(doLint); requestAnimationFrame(doLint); // For first time load } const doLint = _.debounce(() => { if (/javascript/i.test(editor.getModel().getModeId())) { const code = editor.getValue(); axios .post('/rekit/api/lint', { content: code, file: editor._editingFile // eslint-disable-line }) .then(res => { if (code === editor.getValue()) { updateLintWarnings(res.data); } }) .catch(() => {}); } }, 500); function updateLintWarnings(validations) { const markers = validations.map(error => ({ severity: Math.min(error.severity + 1, 3), startColumn: error.column, startLineNumber: error.line, endColumn: error.endColumn, endLineNumber: error.endLine, message: `${error.message} (${error.ruleId})`, source: 'eslint' })); monaco.editor.setModelMarkers(editor.getModel(), 'eslint', markers); } export default setupLintWorker;
/* eslint no-use-before-define: 0 */ import _ from 'lodash'; import axios from 'axios'; let editor; let monaco; // Worker always run and will never terminate // There is only one global editor instance never disposed in Rekit Studio. function setupLintWorker(_editor, _monaco) { editor = _editor; monaco = _monaco; editor.onDidChangeModelContent(doLint); requestAnimationFrame(doLint); // For first time load } const doLint = _.debounce(() => { if (/javascript/i.test(editor.getModel().getModeId())) { const code = editor.getValue(); axios .post('/rekit/api/lint', { content: code, file: editor._editingFile // eslint-disable-line }) .then(res => { if (code === editor.getValue()) { updateLintWarnings(res.data); } }) .catch(() => {}); } else { updateLintWarnings([]); } }, 500); function updateLintWarnings(validations) { const markers = validations.map(error => ({ severity: Math.min(error.severity + 1, 3), startColumn: error.column, startLineNumber: error.line, endColumn: error.endColumn, endLineNumber: error.endLine, message: `${error.message} (${error.ruleId})`, source: 'eslint' })); monaco.editor.setModelMarkers(editor.getModel(), 'eslint', markers); } export default setupLintWorker;
Clear eslint error for non-js files.
Clear eslint error for non-js files.
JavaScript
mit
supnate/rekit
5cf5083c97d2189a75c1124581c40c30cf3921dc
lib/global.js
lib/global.js
global.WRTC = require('wrtc') global.WEBTORRENT_ANNOUNCE = [ 'wss://tracker.webtorrent.io' ]
global.WRTC = require('wrtc') global.WEBTORRENT_ANNOUNCE = [ 'wss://tracker.webtorrent.io/' ]
Fix error "connection error to wss://tracker.webtorrent.io?1fe16837ed"
Fix error "connection error to wss://tracker.webtorrent.io?1fe16837ed"
JavaScript
mit
feross/webtorrent-hybrid,yciabaud/webtorrent-hybrid,feross/webtorrent-hybrid
751c2642026e2e6aabd62e1661d7ee01dfb82b4c
app/assets/javascripts/app.js
app/assets/javascripts/app.js
angular .module('fitnessTracker', ['ui.router', 'templates', 'Devise']) .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('signup', { url: '/signup', templateUrl: 'auth/_signup.html', controller: 'AuthenticationController as AuthCtrl' }) .state('signin', { url: '/signin', templateUrl: 'auth/_signin.html', controller: 'AuthenticationController as AuthCtrl' }) .state('profile', { url: '/user', template: 'user/_user.html', controller: 'UserController as UserCtrl' }); $urlRouterProvider.otherwise('/signin'); });
angular .module('fitnessTracker', ['ui.router', 'templates', 'Devise']) .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('signup', { url: '/signup', templateUrl: 'auth/_signup.html', controller: 'AuthenticationController as AuthCtrl' }) .state('signin', { url: '/signin', templateUrl: 'auth/_signin.html', controller: 'AuthenticationController as AuthCtrl' }) .state('user', { url: '/user', template: 'user/_user.html', controller: 'UserController as UserCtrl' }); $urlRouterProvider.otherwise('/signin'); });
Change state name from 'profile' to 'user'
Change state name from 'profile' to 'user'
JavaScript
mit
viparthasarathy/fitness-tracker,viparthasarathy/fitness-tracker,viparthasarathy/fitness-tracker
06309a28546f22db3ada5c67a363e7062914c701
lib/loader.js
lib/loader.js
/*jshint node: true */ var Promise = require("bluebird"); var fs = require("fs"); /** * Maps file paths to their contents. Filled in by readTemplate() if the * disableCache argument is not set to true. */ var cache = {}; /** * Reads the template file at the given path and returns its contents as a * Promise. The second parameter is optional; if it is set to true, the string * that was read will not be cached for another access in the future. */ module.exports = function load(path, disableCache) { var prom; if (!disableCache && cache[path]) { // load from cache prom = Promise.resolve(cache[path]); } else { // read file prom = read(path); } if (!disableCache) { // store in cache prom = prom.then(function (template) { cache[path] = template; return template; }); } return prom; }; /** * Reads the file at the given path and returns its contents as a string. */ function read(path) { return new Promise(function (fulfill, reject) { fs.readFile(path, "utf8", function (err, template) { if (err) reject(err); else fulfill(template); }); }); }
/*jshint node: true */ var Promise = require("bluebird"); var fs = require("fs"); /** * Maps file paths to their contents */ var cache = {}; /** * Reads the template file at the given path and returns its contents as a * Promise. The second parameter is optional; if it is set to true, the string * that was read will not be cached for another access in the future. */ module.exports = function load(path, disableCache) { var prom; if (!disableCache && cache[path]) { // load from cache prom = Promise.resolve(cache[path]); } else { // read file prom = read(path); } if (!disableCache) { // store in cache prom = prom.then(function (template) { cache[path] = template; return template; }); } return prom; }; /** * Reads the file at the given path and returns its contents as a string. */ function read(path) { return new Promise(function (fulfill, reject) { fs.readFile(path, "utf8", function (err, template) { if (err) reject(err); else fulfill(template); }); }); }
Fix 'cache' variable doc comment
Fix 'cache' variable doc comment The comment referenced a non-existing function from during the development; the affected sentence is removed.
JavaScript
mit
JangoBrick/teval,JangoBrick/teval
672d4b454e02fe0cb894fdca00f6a151f7e522e4
src/data/ui/breakpoints/reducers.js
src/data/ui/breakpoints/reducers.js
//@flow import { updateObject } from "../../reducers/utils"; export default ( state: { breakpoints: { main: string } }, action: { type: string, newLayout: string, component: string } ) => updateObject(state, { breakpoints: updateObject(state.breakpoints, { [action.component]: action.newLayout }) });
//@flow import { updateObject } from "../../reducers/utils"; export default ( state: { breakpoints: { main: string } }, action: { type: string, component: string, query: { [string]: string } } ) => updateObject(state, { breakpoints: updateObject(state.breakpoints, { [action.component]: updateObject( state.breakpoints[action.component], action.query ) }) });
Update breakpoint reducer to assign deeper queries object
Update breakpoint reducer to assign deeper queries object
JavaScript
mit
slightly-askew/portfolio-2017,slightly-askew/portfolio-2017
b90abb59cc56d6ec0f0adf381e73f4901d5cfbee
lib/assert.js
lib/assert.js
'use strict'; var Assert = require('test/assert').Assert , bindMethods = require('es5-ext/lib/Object/bind-methods').call , merge = require('es5-ext/lib/Object/plain/merge').call , never, neverBind; never = function (message) { this.fail({ message: message, operator: "never" }); }; neverBind = function (message) { return never.bind(this, message); }; module.exports = function (logger) { var assert = new Assert({ pass: logger.pass.bind(logger), fail: logger.fail.bind(logger), error: logger.error.bind(logger) }); assert = bindMethods(assert.strictEqual.bind(assert), assert, Assert.prototype); assert.not = assert.notStrictEqual; assert.deep = assert.deepEqual; assert.notDeep = assert.notDeepEqual; assert.never = never.bind(assert); assert.never.bind = neverBind.bind(assert); return assert; };
'use strict'; var Assert = require('test/assert').Assert , bindMethods = require('es5-ext/lib/Object/plain/bind-methods').call , merge = require('es5-ext/lib/Object/plain/merge').call , never, neverBind; never = function (message) { this.fail({ message: message, operator: "never" }); }; neverBind = function (message) { return never.bind(this, message); }; module.exports = function (logger) { var assert = new Assert({ pass: logger.pass.bind(logger), fail: logger.fail.bind(logger), error: logger.error.bind(logger) }); assert = bindMethods(assert.strictEqual.bind(assert), assert, Assert.prototype); assert.not = assert.notStrictEqual; assert.deep = assert.deepEqual; assert.notDeep = assert.notDeepEqual; assert.never = never.bind(assert); assert.never.bind = neverBind.bind(assert); return assert; };
Update up to changes in es5-ext
Update up to changes in es5-ext
JavaScript
isc
medikoo/tad
96e722264b46887d4127cf23d3e472783fba777e
js/main.js
js/main.js
var updatePreviewTarget = function(data, status) { $('.spinner').hide(); $('#preview-target').html(data); renderLatexExpressions(); } var renderLatexExpressions = function() { $('.latex-container').each( function(index) { katex.render( this.innerText, this, { displayMode: $(this).data('displaymode') == 'block' } ); } ); } var main = function() { $('div code').each(function(i, block) { hljs.highlightBlock(block); }); $('button#preview').click( function() { $('#preview-target').html(''); $('.spinner').show(); $('h1.preview').text($('input[name=title]').val()) $.post('/note_preview', {text: $('#note-txt').val()}, updatePreviewTarget); } ); renderLatexExpressions(); }; function searchRedirect(searchpage) { event.preventDefault(); var term = (arguments.length == 1) ? document.getElementById('mainsearch').value : document.getElementById('searchbox').value; window.location = '/search/' + term + '/'; } $(main);
var updatePreviewTarget = function(data, status) { $('.spinner').hide(); $('#preview-target').html(data); renderLatexExpressions(); } var renderLatexExpressions = function() { $('.latex-container').each( function(index) { katex.render( this.textContent, this, { displayMode: $(this).data('displaymode') == 'block' } ); } ); } var main = function() { $('div code').each(function(i, block) { hljs.highlightBlock(block); }); $('button#preview').click( function() { $('#preview-target').html(''); $('.spinner').show(); $('h1.preview').text($('input[name=title]').val()) $.post('/note_preview', {text: $('#note-txt').val()}, updatePreviewTarget); } ); renderLatexExpressions(); }; function searchRedirect(searchpage) { event.preventDefault(); var term = (arguments.length == 1) ? document.getElementById('mainsearch').value : document.getElementById('searchbox').value; window.location = '/search/' + term + '/'; } $(main);
Fix katex rendering on firefox
Fix katex rendering on firefox
JavaScript
mit
erettsegik/erettsegik.hu,erettsegik/erettsegik.hu,erettsegik/erettsegik.hu
f070ba58f9d8fe367284a9c82fd9e8ec75829584
src/components/Projects.js
src/components/Projects.js
import React from 'react' import { Project } from './Project' const Projects = ({ projects = [], feature }) => { if (!projects.length) return null const featuredProjects = projects.filter((project) => project.feature) const nonFeaturedProjects = projects.filter((project) => !project.feature) return ( <> {feature ? ( <ul className="divide-y divide-gray-200"> {featuredProjects.map((project) => ( <li key={project.id} className="flex py-12 space-x-6"> <Project project={project} /> </li> ))} </ul> ) : ( <ul className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-12"> {nonFeaturedProjects.map((project) => ( <li key={project.id} className="p-4 border rounded-sm"> <Project project={{ ...project, image: undefined }} /> </li> ))} </ul> )} </> ) } export { Projects }
import React from 'react' import { Project } from './Project' const Projects = ({ projects = [], feature }) => { if (!projects.length) return null const featuredProjects = projects.filter((project) => project.feature) const nonFeaturedProjects = projects.filter((project) => !project.feature) return ( <> {feature ? ( <ul className="divide-y divide-gray-200"> {featuredProjects.map((project) => ( <li key={project.id} className="flex py-12 space-x-6"> <Project project={project} /> </li> ))} </ul> ) : ( <ul className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-12"> {nonFeaturedProjects.map((project) => ( <li key={project.id} className="p-4 border rounded-lg shadow-md"> <Project project={{ ...project, image: undefined }} /> </li> ))} </ul> )} </> ) } export { Projects }
Add shadow to non-feature project container
Add shadow to non-feature project container
JavaScript
mit
dtjv/dtjv.github.io
0f874d8c12778c07c93526a84a8e0a43d4d27e3b
js/main.js
js/main.js
$(function() { yourCollection = new Models.ItemListings(); friendCollection = new Models.ItemListings(); featuredCollection = new Models.ItemListings(); publicCollection = new Models.ItemListings(); yourView = new Views.ListingView({ collection: yourCollection, el: $('#you-listing')[0] }); friendView = new Views.ListingView({ collection: friendCollection, el: $('#friend-listing')[0] }); featuredView = new Views.ListingView({ collection: featuredCollection, el: $('#featured-listing')[0] }); publicView = new Views.ListingView({ collection: publicCollection, el: $('#public-listing')[0] }) yourCollection.add({ id: 0, name: "Test Item", price: "(USD) $5", location: "Singapore", buyers: [0], owner: 0, imageUrl: 'http://placehold.it/96x96' }); friendCollection.add({ id: 1, name: "Another Item", price: "(USD) $25", location: "Singapore", buyers: [0, 1, 2], owner: 1, imageUrl: 'http://placehold.it/96x96' }); });
$(function() { yourCollection = new Models.ItemListings(); friendCollection = new Models.ItemListings(); featuredCollection = new Models.ItemListings(); publicCollection = new Models.ItemListings(); yourView = new Views.ListingView({ collection: yourCollection, el: $('#you-listing')[0] }); friendView = new Views.ListingView({ collection: friendCollection, el: $('#friend-listing')[0] }); featuredView = new Views.ListingView({ collection: featuredCollection, el: $('#featured-listing')[0] }); publicView = new Views.ListingView({ collection: publicCollection, el: $('#public-listing')[0] }); yourCollection.add({ id: 0, name: "Test Item", price: "(USD) $5", location: "Singapore", buyers: [0], owner: 0, imageUrl: 'http://placehold.it/96x96' }); friendCollection.add({ id: 1, name: "Another Item", price: "(USD) $25", location: "Singapore", buyers: [0, 1, 2], owner: 1, imageUrl: 'http://placehold.it/96x96' }); });
Add missing semicolon, remove trailing whitespace.
Add missing semicolon, remove trailing whitespace.
JavaScript
mit
burnflare/CrowdBuy,burnflare/CrowdBuy
db55033e85b3c87ba45b1d5fdb28120cbc526208
src/manager/components/CommentList/index.js
src/manager/components/CommentList/index.js
import React, { Component } from 'react'; import style from './style'; import CommentItem from '../CommentItem'; export default class CommentList extends Component { componentDidMount() { this.wrapper.scrollTop = this.wrapper.scrollHeight; } componentDidUpdate(prev) { if (this.props.comments.length !== prev.comments.length) { this.wrapper.scrollTop = this.wrapper.scrollHeight; } } render() { const { comments } = this.props; if (comments.length === 0) { return ( <div ref={(el) => { this.wrapper = el; }} style={style.wrapper}> <div style={style.noComments}>No Comments Yet!</div> </div> ); } return ( <div ref={(el) => { this.wrapper = el; }} style={style.wrapper}> {comments.map((comment, idx) => ( <CommentItem key={`comment_${idx}`} comment={comment} ownComment={comment.userId === this.props.user && this.props.user.id} deleteComment={() => this.props.deleteComment(comment.id)} /> ))} </div> ); } } CommentList.propTypes = { comments: React.PropTypes.array, user: React.PropTypes.object, deleteComment: React.PropTypes.func, };
import React, { Component } from 'react'; import style from './style'; import CommentItem from '../CommentItem'; export default class CommentList extends Component { componentDidMount() { this.wrapper.scrollTop = this.wrapper.scrollHeight; } componentDidUpdate(prev) { if (this.props.comments.length !== prev.comments.length) { this.wrapper.scrollTop = this.wrapper.scrollHeight; } } render() { const { comments } = this.props; if (comments.length === 0) { return ( <div ref={(el) => { this.wrapper = el; }} style={style.wrapper}> <div style={style.noComments}>No Comments Yet!</div> </div> ); } return ( <div ref={(el) => { this.wrapper = el; }} style={style.wrapper}> {comments.map((comment, idx) => ( <CommentItem key={`comment_${idx}`} comment={comment} ownComment={comment.userId === (this.props.user && this.props.user.id)} deleteComment={() => this.props.deleteComment(comment.id)} /> ))} </div> ); } } CommentList.propTypes = { comments: React.PropTypes.array, user: React.PropTypes.object, deleteComment: React.PropTypes.func, };
Fix boolean logic related to showing delete button
Fix boolean logic related to showing delete button
JavaScript
mit
kadirahq/react-storybook,nfl/react-storybook,shilman/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,jribeiro/storybook,enjoylife/storybook,storybooks/storybook,rhalff/storybook,rhalff/storybook,rhalff/storybook,bigassdragon/storybook,jribeiro/storybook,storybooks/storybook,storybooks/react-storybook,enjoylife/storybook,nfl/react-storybook,rhalff/storybook,jribeiro/storybook,jribeiro/storybook,bigassdragon/storybook,storybooks/storybook,storybooks/react-storybook,shilman/storybook,shilman/storybook,enjoylife/storybook,kadirahq/react-storybook,storybooks/storybook,nfl/react-storybook,rhalff/storybook,storybooks/react-storybook,rhalff/storybook,enjoylife/storybook,shilman/storybook,bigassdragon/storybook,bigassdragon/storybook,nfl/react-storybook
42af1e835e8ffd80e6772a8dc7694ad81b425dc5
test/test-api-ping-plugins-route.js
test/test-api-ping-plugins-route.js
var request = require('supertest'); var assert = require('assert'); var storageFactory = require('../lib/storage/storage-factory'); var storage = storageFactory.getStorageInstance('test'); var app = require('../webserver/app')(storage); describe('ping plugins route', function () { var server; var PORT = 3355; var API_ROOT = '/api/plugins'; var agent = request.agent(app); before(function (done) { server = app.listen(PORT, function () { if (server.address()) { console.log('starting server in port ' + PORT); done(); } else { console.log('something went wrong... couldn\'t listen to that port.'); process.exit(1); } }); }); after(function () { server.close(); }); describe('plugin list', function () { describe('with an anonymous user ', function () { it('should return list of plugins', function (done) { agent .get(API_ROOT + '/') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .send() .end(function (err, res) { assert.equal(res.body.length, 2); assert.equal(res.body[0].name, 'http-head'); done(err); }); }); }); }); });
var request = require('supertest'); var assert = require('assert'); var storageFactory = require('../lib/storage/storage-factory'); var storage = storageFactory.getStorageInstance('test'); var app = require('../webserver/app')(storage); describe('ping plugins route', function () { var server; var PORT = 3355; var API_ROOT = '/api/plugins'; var agent = request.agent(app); before(function (done) { server = app.listen(PORT, function () { if (server.address()) { console.log('starting server in port ' + PORT); done(); } else { console.log('something went wrong... couldn\'t listen to that port.'); process.exit(1); } }); }); after(function () { server.close(); }); describe('plugin list', function () { describe('with an anonymous user ', function () { it('should return list of plugins', function (done) { agent .get(API_ROOT + '/') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .send() .end(function (err, res) { assert.equal(res.body.length, 2); var plugins = res.body.sort(function(a, b){ return a.name > b.name; }); assert.equal(plugins[0].name, 'http-contains'); assert.equal(plugins[1].name, 'http-head'); done(err); }); }); }); }); });
Sort to get determinist ordering
Sort to get determinist ordering
JavaScript
mit
corinis/watchmen,corinis/watchmen,ravi/watchmen,iloire/WatchMen,Cellington1/Status,iloire/WatchMen,Cellington1/Status,iloire/WatchMen,Cellington1/Status,NotyIm/WatchMen,ravi/watchmen,corinis/watchmen,NotyIm/WatchMen,NotyIm/WatchMen,plyo/watchmen,plyo/watchmen,labianchin/WatchMen,labianchin/WatchMen,ravi/watchmen,labianchin/WatchMen,plyo/watchmen
81a144daaf912e9e9692f558b1ce0fb521575db1
package.js
package.js
Package.describe({ name: "practicalmeteor:loglevel", summary: "Simple logger with app and per-package log levels and line number preserving output.", version: "1.2.0_2", git: "https://github.com/practicalmeteor/meteor-loglevel.git" }); Package.onUse(function (api) { api.versionsFrom('0.9.3'); api.use(['meteor', 'coffeescript']); api.use(['practicalmeteor:[email protected]_1']); api.addFiles('loglevel-1.2.0.js'); api.addFiles('LoggerFactory.coffee'); api.addFiles('ObjectLogger.coffee'); api.export(['loglevel', 'ObjectLogger']); }); Package.onTest(function(api) { api.use(['coffeescript', 'practicalmeteor:[email protected]_2', 'practicalmeteor:[email protected]']); api.addFiles('tests/LoggerFactoryTest.coffee'); api.addFiles('tests/ObjectLoggerTest.coffee'); });
Package.describe({ name: "practicalmeteor:loglevel", summary: "Simple logger with app and per-package log levels and line number preserving output.", version: "1.2.0_2", git: "https://github.com/practicalmeteor/meteor-loglevel.git" }); Package.onUse(function (api) { api.versionsFrom('0.9.3'); api.use(['meteor', 'coffeescript']); api.use(['practicalmeteor:[email protected]_1']); api.addFiles('loglevel-1.2.0.js'); api.addFiles('LoggerFactory.coffee'); api.addFiles('ObjectLogger.coffee'); api.export(['loglevel', 'ObjectLogger']); }); Package.onTest(function(api) { api.use(['coffeescript', 'practicalmeteor:[email protected]_2', 'practicalmeteor:[email protected]']); api.addFiles('tests/LoggerFactoryTest.coffee'); api.addFiles('tests/ObjectLoggerTest.coffee'); });
Update munit dependency to 2.1.4
Update munit dependency to 2.1.4
JavaScript
mit
practicalmeteor/meteor-loglevel,solderzzc/meteor-loglevel
d0d62e6e7bcf78e7955ac693b36084d3dc94b725
lib/workers/repository/onboarding/branch/index.js
lib/workers/repository/onboarding/branch/index.js
const { detectPackageFiles } = require('../../../../manager'); const { createOnboardingBranch } = require('./create'); const { rebaseOnboardingBranch } = require('./rebase'); const { isOnboarded, onboardingPrExists } = require('./check'); async function checkOnboardingBranch(config) { logger.debug('checkOnboarding()'); logger.trace({ config }); const repoIsOnboarded = await isOnboarded(config); if (repoIsOnboarded) { logger.debug('Repo is onboarded'); return { ...config, repoIsOnboarded }; } if (config.isFork) { throw new Error('fork'); } logger.info('Repo is not onboarded'); if (await onboardingPrExists(config)) { logger.debug('Onboarding PR already exists'); await rebaseOnboardingBranch(config); } else { logger.debug('Onboarding PR does not exist'); if ((await detectPackageFiles(config)).length === 0) { throw new Error('no-package-files'); } logger.info('Need to create onboarding PR'); await createOnboardingBranch(config); } await platform.setBaseBranch(`renovate/configure`); const branchList = [`renovate/configure`]; return { ...config, repoIsOnboarded, branchList }; } module.exports = { checkOnboardingBranch, };
const { detectPackageFiles } = require('../../../../manager'); const { createOnboardingBranch } = require('./create'); const { rebaseOnboardingBranch } = require('./rebase'); const { isOnboarded, onboardingPrExists } = require('./check'); async function checkOnboardingBranch(config) { logger.debug('checkOnboarding()'); logger.trace({ config }); const repoIsOnboarded = await isOnboarded(config); if (repoIsOnboarded) { logger.debug('Repo is onboarded'); return { ...config, repoIsOnboarded }; } if (config.isFork && !config.renovateFork) { throw new Error('fork'); } logger.info('Repo is not onboarded'); if (await onboardingPrExists(config)) { logger.debug('Onboarding PR already exists'); await rebaseOnboardingBranch(config); } else { logger.debug('Onboarding PR does not exist'); if ((await detectPackageFiles(config)).length === 0) { throw new Error('no-package-files'); } logger.info('Need to create onboarding PR'); await createOnboardingBranch(config); } await platform.setBaseBranch(`renovate/configure`); const branchList = [`renovate/configure`]; return { ...config, repoIsOnboarded, branchList }; } module.exports = { checkOnboardingBranch, };
Allow --renovate-fork Cli flag for onboarding.
Allow --renovate-fork Cli flag for onboarding. Fixes https://github.com/renovateapp/renovate/issues/1371.
JavaScript
mit
singapore/renovate,singapore/renovate,singapore/renovate
e1693cbc3e8f27a15109e128d17b675845f16166
assets/mathjaxhelper.js
assets/mathjaxhelper.js
MathJax.Hub.Config({ "tex2jax": { inlineMath: [['$','$'], ['\\(','\\)']], processEscapes: true } }); MathJax.Hub.Config({ config: ["MMLorHTML.js"], jax: ["input/TeX", "output/HTML-CSS", "output/NativeMML"], extensions: ["MathMenu.js", "MathZoom.js", "AMSmath.js", "AMSsymbols.js", "autobold.js", "autoload-all.js"] }); MathJax.Hub.Config({ TeX: { equationNumbers: { autoNumber: "AMS" } } });
MathJax.Hub.Config({ "tex2jax": { inlineMath: [['$','$'], ['\\(','\\)']], processEscapes: true } }); MathJax.Hub.Config({ config: ["MMLorHTML.js"], jax: [ "input/TeX", "output/HTML-CSS", "output/NativeMML" ], extensions: [ "MathMenu.js", "MathZoom.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js", "TeX/autobold.js", "TeX/autoload-all.js" ] }); MathJax.Hub.Config({ TeX: { equationNumbers: { autoNumber: "AMS" } } });
Fix paths for some mathjax extensions.
Fix paths for some mathjax extensions.
JavaScript
mit
mortenpi/Documenter.jl,MichaelHatherly/Documenter.jl,MichaelHatherly/Lapidary.jl,JuliaDocs/Documenter.jl
2aed51e0cddadbf600421ae56587a2b1fceb6198
config/index.js
config/index.js
import defaults from 'defaults' const API_GLOBAL = '_IMDIKATOR' const env = process.env.NODE_ENV || 'development' const DEFAULTS = { port: 3000, reduxDevTools: false } const globalConfig = (typeof window !== 'undefined' && window[API_GLOBAL] || {}) export default defaults({ env, port: process.env.PORT, // nodeApiHost: 'localhost:8080', nodeApiHost: 'http://atindikatornode.azurewebsites.net', apiHost: globalConfig.apiHost, contentApiHost: globalConfig.contentApiHost, reduxDevTools: env == 'development' && !['0', 'false'].includes(process.env.REDUX_DEVTOOLS), showDebug: process.env.DEBUG }, DEFAULTS)
import defaults from 'defaults' const API_GLOBAL = '_IMDIKATOR' const env = process.env.NODE_ENV || 'development' const DEFAULTS = { port: 3000, reduxDevTools: false } const globalConfig = (typeof window !== 'undefined' && window[API_GLOBAL] || {}) export default defaults({ env, port: process.env.PORT, // nodeApiHost: 'localhost:8080', nodeApiHost: 'https://atindikatornode.azurewebsites.net', apiHost: globalConfig.apiHost, contentApiHost: globalConfig.contentApiHost, reduxDevTools: env == 'development' && !['0', 'false'].includes(process.env.REDUX_DEVTOOLS), showDebug: process.env.DEBUG }, DEFAULTS)
FIX - changed node api to https
FIX - changed node api to https
JavaScript
mit
bengler/imdikator,bengler/imdikator
fdce895bbaa4c08431d173edd286cb9b6670f2c2
tools/cli/dev-bundle-bin-helpers.js
tools/cli/dev-bundle-bin-helpers.js
var path = require("path"); var devBundleDir = path.resolve(__dirname, "..", "..", "dev_bundle"); var binDir = path.join(devBundleDir, "bin"); exports.getCommandPath = function (command) { return path.join(binDir, command); }; exports.getEnv = function () { var env = Object.create(process.env); env.PATH = [ // When npm looks for node, it must find dev_bundle/bin/node. binDir, // Also make available any scripts installed by packages in // dev_bundle/lib/node_modules, such as node-gyp. path.join(devBundleDir, "lib", "node_modules", ".bin"), env.PATH ].join(path.delimiter); if (process.platform === "win32") { // On Windows we provide a reliable version of python.exe for use by // node-gyp (the tool that rebuilds binary node modules). #WinPy env.PYTHON = env.PYTHON || path.join( devBundleDir, "python", "python.exe"); // We don't try to install a compiler toolchain on the developer's // behalf, but setting GYP_MSVS_VERSION helps select the right one. env.GYP_MSVS_VERSION = env.GYP_MSVS_VERSION || "2015"; } return env; };
var path = require("path"); var devBundleDir = path.resolve(__dirname, "..", "..", "dev_bundle"); var binDir = path.join(devBundleDir, "bin"); exports.getCommandPath = function (command) { return path.join(binDir, command); }; exports.getEnv = function () { var env = Object.create(process.env); var paths = [ // When npm looks for node, it must find dev_bundle/bin/node. binDir, // Also make available any scripts installed by packages in // dev_bundle/lib/node_modules, such as node-gyp. path.join(devBundleDir, "lib", "node_modules", ".bin"), ]; var PATH = env.PATH || env.Path; if (PATH) { paths.push(PATH); } env.PATH = paths.join(path.delimiter); if (process.platform === "win32") { // On Windows we provide a reliable version of python.exe for use by // node-gyp (the tool that rebuilds binary node modules). #WinPy env.PYTHON = env.PYTHON || path.join( devBundleDir, "python", "python.exe"); // We don't try to install a compiler toolchain on the developer's // behalf, but setting GYP_MSVS_VERSION helps select the right one. env.GYP_MSVS_VERSION = env.GYP_MSVS_VERSION || "2015"; // While the original process.env object allows for case insensitive // access on Windows, Object.create interferes with that behavior, so // here we ensure env.PATH === env.Path on Windows. env.Path = env.PATH; } return env; };
Make sure env.Path === env.PATH on Windows.
Make sure env.Path === env.PATH on Windows.
JavaScript
mit
Hansoft/meteor,Hansoft/meteor,4commerce-technologies-AG/meteor,jdivy/meteor,mjmasn/meteor,Hansoft/meteor,4commerce-technologies-AG/meteor,chasertech/meteor,chasertech/meteor,4commerce-technologies-AG/meteor,chasertech/meteor,chasertech/meteor,4commerce-technologies-AG/meteor,Hansoft/meteor,4commerce-technologies-AG/meteor,jdivy/meteor,mjmasn/meteor,4commerce-technologies-AG/meteor,mjmasn/meteor,Hansoft/meteor,chasertech/meteor,mjmasn/meteor,chasertech/meteor,jdivy/meteor,mjmasn/meteor,Hansoft/meteor,mjmasn/meteor,4commerce-technologies-AG/meteor,chasertech/meteor,Hansoft/meteor,jdivy/meteor,jdivy/meteor,jdivy/meteor,mjmasn/meteor,jdivy/meteor
7e6697514f6f2596ebcc9227c730effc72783c06
test/visual/cypress/specs/home-page-spec.js
test/visual/cypress/specs/home-page-spec.js
describe('home page', () => { before(() => { cy.visit('/') }) it('content', () => { cy.get('.dashboard-section__info-feed-date').hideElement() cy.get('.grid-row').compareSnapshot('homePageContent') }) it('header', () => { cy.get('.datahub-header').compareSnapshot('homePageHeader') }) it('search bar', () => { cy.get('.govuk-grid-column-full') .first() .compareSnapshot('homePageSearchBar') }) })
describe('home page', () => { before(() => { cy.visit('/') }) it('content', () => { cy.get('.dashboard-section__info-feed-date').hideElement() cy.get('[for="company-name"]').should('be.visible') cy.get('.grid-row').compareSnapshot('homePageContent') }) it('header', () => { cy.get('.datahub-header').compareSnapshot('homePageHeader') }) it('search bar', () => { cy.get('.govuk-grid-column-full') .first() .compareSnapshot('homePageSearchBar') }) })
Add assertion to test to wait for component to load
Add assertion to test to wait for component to load
JavaScript
mit
uktrade/data-hub-fe-beta2,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-frontend,uktrade/data-hub-frontend
2c1660c07e516d96dbdf8000a766fd6b63f3ef73
packages/ember-data/lib/system/application_ext.js
packages/ember-data/lib/system/application_ext.js
var set = Ember.set; Ember.onLoad('Ember.Application', function(Application) { Application.registerInjection({ name: "store", before: "controllers", injection: function(app, stateManager, property) { if (!stateManager) { return; } if (property === 'Store') { set(stateManager, 'store', app[property].create()); } } }); Application.registerInjection({ name: "giveStoreToControllers", after: ['store','controllers'], injection: function(app, stateManager, property) { if (!stateManager) { return; } if (/^[A-Z].*Controller$/.test(property)) { var controllerName = property.charAt(0).toLowerCase() + property.substr(1); var store = stateManager.get('store'); var controller = stateManager.get(controllerName); if(!controller) { return; } controller.set('store', store); } } }); });
var set = Ember.set; /** This code registers an injection for Ember.Application. If an Ember.js developer defines a subclass of DS.Store on their application, this code will automatically instantiate it and make it available on the router. Additionally, after an application's controllers have been injected, they will each have the store made available to them. For example, imagine an Ember.js application with the following classes: App.Store = DS.Store.extend({ adapter: 'App.MyCustomAdapter' }); App.PostsController = Ember.ArrayController.extend({ // ... }); When the application is initialized, `App.Store` will automatically be instantiated, and the instance of `App.PostsController` will have its `store` property set to that instance. Note that this code will only be run if the `ember-application` package is loaded. If Ember Data is being used in an environment other than a typical application (e.g., node.js where only `ember-runtime` is available), this code will be ignored. */ Ember.onLoad('Ember.Application', function(Application) { Application.registerInjection({ name: "store", before: "controllers", // If a store subclass is defined, like App.Store, // instantiate it and inject it into the router. injection: function(app, stateManager, property) { if (!stateManager) { return; } if (property === 'Store') { set(stateManager, 'store', app[property].create()); } } }); Application.registerInjection({ name: "giveStoreToControllers", after: ['store','controllers'], // For each controller, set its `store` property // to the DS.Store instance we created above. injection: function(app, stateManager, property) { if (!stateManager) { return; } if (/^[A-Z].*Controller$/.test(property)) { var controllerName = property.charAt(0).toLowerCase() + property.substr(1); var store = stateManager.get('store'); var controller = stateManager.get(controllerName); if(!controller) { return; } controller.set('store', store); } } }); });
Add inline docs to injection code
Add inline docs to injection code
JavaScript
mit
BookingSync/data,EmberSherpa/data,Eric-Guo/data,funtusov/data,sebastianseilund/data,topaxi/data,courajs/data,tarzan/data,sammcgrail/data,Turbo87/ember-data,kimroen/data,courajs/data,greyhwndz/data,sebastianseilund/data,gniquil/data,hibariya/data,Robdel12/data,fpauser/data,lostinpatterns/data,yaymukund/data,gabriel-letarte/data,arenoir/data,fsmanuel/data,Kuzirashi/data,simaob/data,topaxi/data,webPapaya/data,tarzan/data,jgwhite/data,Turbo87/ember-data,bf4/data,PrecisionNutrition/data,thaume/data,eriktrom/data,minasmart/data,andrejunges/data,H1D/data,stefanpenner/data,Robdel12/data,andrejunges/data,nickiaconis/data,slindberg/data,k-fish/data,danmcclain/data,nickiaconis/data,bcardarella/data,webPapaya/data,bcardarella/data,intuitivepixel/data,rtablada/data,pdud/data,martndemus/data,jmurphyau/data,heathharrelson/data,gkaran/data,hjdivad/data,slindberg/data,workmanw/data,BBLN/data,hibariya/data,tstirrat/ember-data,jgwhite/data,intuitivepixel/data,martndemus/data,sammcgrail/data,eriktrom/data,greyhwndz/data,danmcclain/data,bf4/data,acburdine/data,gniquil/data,rtablada/data,funtusov/data,BBLN/data,EmberSherpa/data,sammcgrail/data,faizaanshamsi/data,duggiefresh/data,in4mates/ember-data,fpauser/data,BookingSync/data,intuitivepixel/data,Turbo87/ember-data,heathharrelson/data,zoeesilcock/data,tonywok/data,heathharrelson/data,fsmanuel/data,zoeesilcock/data,H1D/data,workmanw/data,simaob/data,zoeesilcock/data,jgwhite/data,knownasilya/data,wecc/data,hibariya/data,ryanpatrickcook/data,hibariya/data,davidpett/data,trisrael/em-data,sandstrom/ember-data,simaob/data,BookingSync/data,XrXr/data,wecc/data,nickiaconis/data,offirgolan/data,dustinfarris/data,radiumsoftware/data,greyhwndz/data,Addepar/ember-data,EmberSherpa/data,Globegitter/ember-data-evolution,basho/ember-data,topaxi/data,usecanvas/data,gabriel-letarte/data,usecanvas/data,dustinfarris/data,basho/ember-data,XrXr/data,martndemus/data,lostinpatterns/data,kappiah/data,Eric-Guo/data,radiumsoftware/data,Globegitter/ember-data-evolution,ryanpatrickcook/data,arenoir/data,flowjzh/data,in4mates/ember-data,seanpdoyle/data,vikram7/data,teddyzeenny/data,topaxi/data,HeroicEric/data,usecanvas/data,yaymukund/data,funtusov/data,sebweaver/data,eriktrom/data,flowjzh/data,gkaran/data,trisrael/em-data,workmanw/data,lostinpatterns/data,swarmbox/data,InboxHealth/data,BBLN/data,bcardarella/data,minasmart/data,faizaanshamsi/data,eriktrom/data,arenoir/data,splattne/data,slindberg/data,tarzan/data,wecc/data,martndemus/data,tarzan/data,sebastianseilund/data,yaymukund/data,acburdine/data,H1D/data,usecanvas/data,dustinfarris/data,PrecisionNutrition/data,acburdine/data,knownasilya/data,offirgolan/data,gniquil/data,gabriel-letarte/data,funtusov/data,sebweaver/data,duggiefresh/data,stefanpenner/data,davidpett/data,fpauser/data,davidpett/data,faizaanshamsi/data,InboxHealth/data,fpauser/data,rwjblue/data,vikram7/data,HeroicEric/data,kappiah/data,sebweaver/data,arenoir/data,tstirrat/ember-data,rwjblue/data,bf4/data,fsmanuel/data,simaob/data,duggiefresh/data,heathharrelson/data,k-fish/data,flowjzh/data,FinSync/ember-data,in4mates/ember-data,seanpdoyle/data,k-fish/data,vikram7/data,fsmanuel/data,EmberSherpa/data,seanpdoyle/data,yaymukund/data,kappiah/data,BBLN/data,InboxHealth/data,splattne/data,ryanpatrickcook/data,gkaran/data,wecc/data,Kuzirashi/data,swarmbox/data,davidpett/data,kappiah/data,splattne/data,dustinfarris/data,Kuzirashi/data,jmurphyau/data,offirgolan/data,jmurphyau/data,Eric-Guo/data,sandstrom/ember-data,FinSync/ember-data,InboxHealth/data,danmcclain/data,H1D/data,rtablada/data,mphasize/data,gabriel-letarte/data,swarmbox/data,danmcclain/data,ryanpatrickcook/data,bf4/data,k-fish/data,intuitivepixel/data,mphasize/data,pdud/data,duggiefresh/data,pdud/data,HeroicEric/data,pdud/data,kimroen/data,XrXr/data,sammcgrail/data,whatthewhat/data,Turbo87/ember-data,kimroen/data,whatthewhat/data,teddyzeenny/data,nickiaconis/data,gkaran/data,acburdine/data,thaume/data,bcardarella/data,FinSync/ember-data,tstirrat/ember-data,sebastianseilund/data,knownasilya/data,andrejunges/data,faizaanshamsi/data,greyhwndz/data,stefanpenner/data,seanpdoyle/data,sebweaver/data,zoeesilcock/data,jmurphyau/data,PrecisionNutrition/data,Addepar/ember-data,webPapaya/data,XrXr/data,splattne/data,mphasize/data,swarmbox/data,offirgolan/data,Kuzirashi/data,Robdel12/data,tonywok/data,minasmart/data,courajs/data,rtablada/data,BookingSync/data,mphasize/data,flowjzh/data,FinSync/ember-data,tonywok/data,stefanpenner/data,webPapaya/data,andrejunges/data,gniquil/data,minasmart/data,workmanw/data,vikram7/data,thaume/data,hjdivad/data,Addepar/ember-data,lostinpatterns/data,Eric-Guo/data,trisrael/em-data,Robdel12/data,thaume/data,HeroicEric/data,tonywok/data,whatthewhat/data,whatthewhat/data,PrecisionNutrition/data,jgwhite/data,courajs/data,tstirrat/ember-data
26d55a74b3f302f3803f8e87d05866bab81cb5ed
src/components/svg-icon/svg-icon.js
src/components/svg-icon/svg-icon.js
// Aurelia import { bindable, bindingMode } from 'aurelia-framework'; import icons from 'configs/icons'; export class SvgIcon { @bindable({ defaultBindingMode: bindingMode.oneWay }) iconId; attached () { const id = this.iconId.toUpperCase().replace('-', '_'); this.icon = icons[id] ? icons[id] : icons.WARNING; } }
// Aurelia import { bindable, bindingMode } from 'aurelia-framework'; import icons from 'configs/icons'; export class SvgIcon { @bindable({ defaultBindingMode: bindingMode.oneWay }) iconId; constructor () { this.icon = { viewBox: '0 0 16 16', svg: '' }; } attached () { const id = this.iconId.toUpperCase().replace('-', '_'); this.icon = icons[id] ? icons[id] : icons.WARNING; } }
Set default values to avoid initial binding errors.
Set default values to avoid initial binding errors.
JavaScript
mit
flekschas/hipiler,flekschas/hipiler,flekschas/hipiler