commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
31663486624635748d6f2202504b0a187a102fcd
RcmBrightCoveLib/public/keep-aspect-ratio.js
RcmBrightCoveLib/public/keep-aspect-ratio.js
/** * This script keeps the height set on elements with regard to their * width for a given aspect ratio. Great for "display:block" elements * * Example usage: * * <div data-keep-aspect-ratio="16:9"> * * Author: Rod McNew * License: BSD */ new function () { var setHeights = function () { $.each($('[data-keep-aspect-ratio]'), function () { var ele = $(this); var ratioParts = ele.attr('data-keep-aspect-ratio').split(':'); var ratioWidth = ratioParts[0]; var ratioHeight = ratioParts[1]; var width = ele.width(); var newHeight = width * ratioHeight / ratioWidth; ele.css('height', newHeight); }) }; //Run onReady $(setHeights); //Run when window is resized $(window).resize(setHeights); //Run when target elements are resized without a window resize $('body').delegate('[data-keep-aspect-ratio]', 'resize', setHeights); };
/** * This script keeps the height set on elements with regard to their * width for a given aspect ratio. Great for "display:block" elements * * Example usage: * * <div data-keep-aspect-ratio="16:9"> * * Author: Rod McNew * License: BSD */ new function () { var setHeights = function () { $.each($('[data-keep-aspect-ratio]'), function () { var ele = $(this); var ratioParts = ele.attr('data-keep-aspect-ratio').split(':'); var ratioWidth = ratioParts[0]; var ratioHeight = ratioParts[1]; var width = ele.width(); var newHeight = width * ratioHeight / ratioWidth; ele.css('height', newHeight); }) }; //Run onReady $(setHeights); //Run when window is resized $(window).resize(setHeights); //Run when target elements are resized without a window resize $('body').on('resize', '[data-keep-aspect-ratio]', setHeights); $('body').on('orientationchange', '[data-keep-aspect-ratio]', setHeights); };
Fix for brightcove player when orintation is changed
Fix for brightcove player when orintation is changed
JavaScript
bsd-3-clause
jerv13/RcmPlugins,jerv13/RcmPlugins,bjanish/RcmPlugins,jerv13/RcmPlugins,innaDa/RcmPlugins,innaDa/RcmPlugins,innaDa/RcmPlugins,bjanish/RcmPlugins,bjanish/RcmPlugins
--- +++ @@ -26,5 +26,6 @@ //Run when window is resized $(window).resize(setHeights); //Run when target elements are resized without a window resize - $('body').delegate('[data-keep-aspect-ratio]', 'resize', setHeights); + $('body').on('resize', '[data-keep-aspect-ratio]', setHeights); + $('body').on('orientationchange', '[data-keep-aspect-ratio]', setHeights); };
c57a584a3bc781db629ae15dd2912f62992f98f3
Resources/private/js/sylius-auto-complete.js
Resources/private/js/sylius-auto-complete.js
/* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ (function ( $ ) { 'use strict'; $.fn.extend({ autoComplete: function () { var element = $(this); var criteriaType = $(this).data('criteria-type'); var criteriaName = $(this).data('criteria-name'); element.dropdown({ delay: { search: 250 }, apiSettings: { dataType: 'JSON', cache: false, data: { criteria: {} }, beforeSend: function(settings) { settings.data.criteria[criteriaName] = {type: criteriaType, value: ''}; settings.data.criteria[criteriaName].value = settings.urlData.query; return settings; }, onResponse: function (response) { var choiceName = element.data('choice-name'); var choiceValue = element.data('choice-value'); var myResults = []; $.each(response._embedded.items, function (index, item) { myResults.push({ name: item[choiceName], value: item[choiceValue] }); }); return { success: true, results: myResults }; } } }); } }); })( jQuery );
/* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ (function ( $ ) { 'use strict'; $.fn.extend({ autoComplete: function () { var element = $(this); var criteriaType = $(this).data('criteria-type'); var criteriaName = $(this).data('criteria-name'); element.dropdown({ delay: { search: 250 }, forceSelection: false, apiSettings: { dataType: 'JSON', cache: false, data: { criteria: {} }, beforeSend: function(settings) { settings.data.criteria[criteriaName] = {type: criteriaType, value: ''}; settings.data.criteria[criteriaName].value = settings.urlData.query; return settings; }, onResponse: function (response) { var choiceName = element.data('choice-name'); var choiceValue = element.data('choice-value'); var myResults = []; $.each(response._embedded.items, function (index, item) { myResults.push({ name: item[choiceName], value: item[choiceValue] }); }); return { success: true, results: myResults }; } } }); } }); })( jQuery );
Use collection instead of array in all transformers, also use map method
[Resource][Core] Use collection instead of array in all transformers, also use map method
JavaScript
mit
Sylius/SyliusUiBundle,Sylius/SyliusUiBundle
--- +++ @@ -20,6 +20,7 @@ delay: { search: 250 }, + forceSelection: false, apiSettings: { dataType: 'JSON', cache: false,
62b292ddf6a6fb71097c5cfa527b625366c46a3f
src/components/slide/index.js
src/components/slide/index.js
import React, { Component, PropTypes } from 'react'; require('./slide.scss'); class Slide extends Component { render() { return ( <div className="slide"> <header className="slide__header"> <h1 className="slide__title">{this.props.title}</h1> </header> <ul> {this.props.children} </ul> <footer className="slide__footer"> {this.props.order} / {this.props.total} </footer> </div> ); } } export default Slide;
import React, { Component, PropTypes } from 'react'; require('./slide.scss'); class Slide extends Component { constructor(props) { super(props); this.isViewable = this.isViewable.bind(this); } isViewable() { return this.props.current === +this.props.order; } render() { return ( this.isViewable() && <div className="slide"> <header className="slide__header"> <h1 className="slide__title">{this.props.title}</h1> </header> <ul> {this.props.children} </ul> <footer className="slide__footer"> {this.props.order} / {this.props.total} </footer> </div> ); } } export default Slide;
Make slide viewable based on current and order
feature: Make slide viewable based on current and order A slide will be viewable only if the current property matches the order property.
JavaScript
mit
leadiv/react-slides,leadiv/react-slides
--- +++ @@ -3,21 +3,32 @@ require('./slide.scss'); class Slide extends Component { + + constructor(props) { + super(props); + this.isViewable = this.isViewable.bind(this); + } + + isViewable() { + return this.props.current === +this.props.order; + } + render() { return ( - <div className="slide"> - <header className="slide__header"> - <h1 className="slide__title">{this.props.title}</h1> - </header> + this.isViewable() && + <div className="slide"> + <header className="slide__header"> + <h1 className="slide__title">{this.props.title}</h1> + </header> - <ul> - {this.props.children} - </ul> + <ul> + {this.props.children} + </ul> - <footer className="slide__footer"> - {this.props.order} / {this.props.total} - </footer> - </div> + <footer className="slide__footer"> + {this.props.order} / {this.props.total} + </footer> + </div> ); } }
daed42ff845baa2abf1e0fd180d7fb0eb2a13b3d
lib/cli/file-set-pipeline/log.js
lib/cli/file-set-pipeline/log.js
/** * @author Titus Wormer * @copyright 2015 Titus Wormer * @license MIT * @module mdast:cli:log * @fileoverview Log a file context on successful completion. */ 'use strict'; /* * Dependencies. */ var report = require('vfile-reporter'); /** * Output diagnostics to stdout(4) or stderr(4). * * @param {CLI} context - CLI engine. */ function log(context) { var files = context.files; var frail = context.frail; var applicables = files.filter(function (file) { return file.namespace('mdast:cli').providedByUser; }); var hasFailed = files.some(function (file) { return file.hasFailed() || (frail && file.messages.length); }); var diagnostics = report(applicables, { 'quiet': context.quiet, 'silent': context.silent }); if (diagnostics) { context[hasFailed ? 'stderr' : 'stdout'](diagnostics); } } /* * Expose. */ module.exports = log;
/** * @author Titus Wormer * @copyright 2015 Titus Wormer * @license MIT * @module mdast:cli:log * @fileoverview Log a file context on successful completion. */ 'use strict'; /* * Dependencies. */ var report = require('vfile-reporter'); /** * Output diagnostics to stdout(4) or stderr(4). * * @param {CLI} context - CLI engine. */ function log(context) { var files = context.files; var applicables = files.filter(function (file) { return file.namespace('mdast:cli').providedByUser; }); var diagnostics = report(applicables, { 'quiet': context.quiet, 'silent': context.silent }); if (diagnostics) { context.stderr(diagnostics); } } /* * Expose. */ module.exports = log;
Move all info output of mdast(1) to stderr(4)
Move all info output of mdast(1) to stderr(4) This changes moves all reporting output, even when not including failure messages, from stout(4) to stderr(4). Thus, when piping only stdout(4) from mdast(1) into a file, only the markdown is written. Closes GH-47.
JavaScript
mit
ulrikaugustsson/mdast,eush77/remark,chcokr/mdast,ulrikaugustsson/mdast,yukkurisinai/mdast,tanzania82/remarks,yukkurisinai/mdast,wooorm/remark,chcokr/mdast,eush77/remark
--- +++ @@ -21,12 +21,8 @@ */ function log(context) { var files = context.files; - var frail = context.frail; var applicables = files.filter(function (file) { return file.namespace('mdast:cli').providedByUser; - }); - var hasFailed = files.some(function (file) { - return file.hasFailed() || (frail && file.messages.length); }); var diagnostics = report(applicables, { 'quiet': context.quiet, @@ -34,7 +30,7 @@ }); if (diagnostics) { - context[hasFailed ? 'stderr' : 'stdout'](diagnostics); + context.stderr(diagnostics); } }
a7f6773184b6a08d6fcc62ed82e331e114f731b8
static/js/json_selector.js
static/js/json_selector.js
// =================================================== // DOM Outline with event handlers // =================================================== $(function(){ var $selector_box = $("#selector"); var selector_val = ""; var DomOutlineHandlers = { 'click': function(e){ selector_val = $(e).data('json-selector'); $selector_box.val(selector_val); }, 'mouseover': function(e){ $(".DomOutline").show(); }, 'mouseout': function(e){ $(".DomOutline").hide(); }, } var DOutline = DomOutline({ handlers: DomOutlineHandlers, filter: 'code span:not(.hljs-attribute)' }) DOutline.start() });
// =================================================== // DOM Outline with event handlers // =================================================== $(function(){ var $selector_box = $("#selector"); var selector_val = ""; var DomOutlineHandlers = { 'click': function(e){ selector_val = $(e).attr('data-json-selector'); $selector_box.val(selector_val); }, 'mouseover': function(e){ $(".DomOutline").show(); }, 'mouseout': function(e){ $(".DomOutline").hide(); }, } var DOutline = DomOutline({ handlers: DomOutlineHandlers, filter: 'code span:not(.hljs-attribute)' }) DOutline.start() });
Use .attr instead of .data to get json selector. Prevents evaluation of [x] as array
Use .attr instead of .data to get json selector. Prevents evaluation of [x] as array
JavaScript
mit
joequery/JSON-Selector-Generator,joequery/JSON-Selector-Generator,joequery/JSON-Selector-Generator
--- +++ @@ -7,7 +7,7 @@ var DomOutlineHandlers = { 'click': function(e){ - selector_val = $(e).data('json-selector'); + selector_val = $(e).attr('data-json-selector'); $selector_box.val(selector_val); }, 'mouseover': function(e){
38c8a46baee9cd61571cf26ba9c3942a98f3ce92
src/js/stores/ArrangeStore.js
src/js/stores/ArrangeStore.js
import { action, computed } from 'mobx' import { moveTabs, tabComparator } from '../libs' export default class ArrangeStore { constructor (store) { this.store = store } @computed get urlTabMap () { return this.store.windowStore.tabs.reduce((acc, tab) => { const { url } = tab acc[url] = acc[url] || [] acc[url].push(tab) return acc }, {}) } @computed get duplicatedTabs () { return Object.values(this.urlTabMap).filter(x => x.length > 1) } @action sortTabs = () => { this.store.windowStore.windows.map((win) => { const tabs = win.tabs.sort(tabComparator) moveTabs(tabs, win.id, 0) }) this.groupDuplicateTabs() } groupDuplicateTabs = () => { this.duplicatedTabs.map((tabs) => { moveTabs(tabs, tabs[0].windowId, -1) }) } }
import { action, computed } from 'mobx' import { moveTabs, tabComparator } from '../libs' const urlPattern = /.*:\/\/[^/]*/ const getDomain = (url) => { const matches = url.match(urlPattern) if (matches) { return matches[0] } return url } export default class ArrangeStore { constructor (store) { this.store = store } @computed get domainTabsMap () { return this.store.windowStore.tabs.reduce((acc, tab) => { const domain = getDomain(tab.url) acc[domain] = acc[domain] || [] acc[domain].push(tab) return acc }, {}) } @action sortTabs = async () => { await this.groupTabs() await this.sortInWindow() } groupTabs = async () => { await Promise.all( Object.entries(this.domainTabsMap).map( async ([ domain, tabs ]) => { if (tabs.length > 1) { const sortedTabs = tabs.sort(tabComparator) const { windowId, pinned } = sortedTabs[0] await moveTabs( sortedTabs.map(x => ({ ...x, pinned })), windowId ) } } ) ) } sortInWindow = async () => { const windows = await chrome.windows.getAll({ populate: true }) windows.map((win) => { const tabs = win.tabs.sort(tabComparator) moveTabs(tabs, win.id) }) } }
Update sortTabs to group tabs by domain then sort in window
Update sortTabs to group tabs by domain then sort in window
JavaScript
mit
xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2
--- +++ @@ -1,5 +1,14 @@ import { action, computed } from 'mobx' import { moveTabs, tabComparator } from '../libs' + +const urlPattern = /.*:\/\/[^/]*/ +const getDomain = (url) => { + const matches = url.match(urlPattern) + if (matches) { + return matches[0] + } + return url +} export default class ArrangeStore { constructor (store) { @@ -7,32 +16,43 @@ } @computed - get urlTabMap () { + get domainTabsMap () { return this.store.windowStore.tabs.reduce((acc, tab) => { - const { url } = tab - acc[url] = acc[url] || [] - acc[url].push(tab) + const domain = getDomain(tab.url) + acc[domain] = acc[domain] || [] + acc[domain].push(tab) return acc }, {}) } - @computed - get duplicatedTabs () { - return Object.values(this.urlTabMap).filter(x => x.length > 1) + @action + sortTabs = async () => { + await this.groupTabs() + await this.sortInWindow() } - @action - sortTabs = () => { - this.store.windowStore.windows.map((win) => { - const tabs = win.tabs.sort(tabComparator) - moveTabs(tabs, win.id, 0) - }) - this.groupDuplicateTabs() + groupTabs = async () => { + await Promise.all( + Object.entries(this.domainTabsMap).map( + async ([ domain, tabs ]) => { + if (tabs.length > 1) { + const sortedTabs = tabs.sort(tabComparator) + const { windowId, pinned } = sortedTabs[0] + await moveTabs( + sortedTabs.map(x => ({ ...x, pinned })), + windowId + ) + } + } + ) + ) } - groupDuplicateTabs = () => { - this.duplicatedTabs.map((tabs) => { - moveTabs(tabs, tabs[0].windowId, -1) + sortInWindow = async () => { + const windows = await chrome.windows.getAll({ populate: true }) + windows.map((win) => { + const tabs = win.tabs.sort(tabComparator) + moveTabs(tabs, win.id) }) } }
bdca4d4b6b04ad011a25fd913ec4c7ed2ed04b1d
react/components/Onboarding/components/UI/CTAButton/index.js
react/components/Onboarding/components/UI/CTAButton/index.js
import theme from 'react/styles/theme'; import GenericButton from 'react/components/UI/GenericButton'; import styled from 'styled-components'; const CTAButton = styled(GenericButton).attrs({ f: 6, })` margin-top: ${theme.space[6]} `; export default CTAButton;
import GenericButton from 'react/components/UI/GenericButton'; import styled from 'styled-components'; const CTAButton = styled(GenericButton).attrs({ f: 6 })` margin-top: ${x => x.theme.space[6]} `; export default CTAButton;
Use theme propeties in CTAButton styled component
Use theme propeties in CTAButton styled component
JavaScript
mit
aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell
--- +++ @@ -1,11 +1,10 @@ -import theme from 'react/styles/theme'; import GenericButton from 'react/components/UI/GenericButton'; import styled from 'styled-components'; const CTAButton = styled(GenericButton).attrs({ - f: 6, + f: 6 })` - margin-top: ${theme.space[6]} + margin-top: ${x => x.theme.space[6]} `; export default CTAButton;
07bffcd4d825b86dbd3386c2f3866f770671c6cb
src/lib/units/day-of-month.js
src/lib/units/day-of-month.js
import { makeGetSet } from '../moment/get-set'; import { addFormatToken } from '../format/format'; import { addUnitAlias } from './aliases'; import { addUnitPriority } from './priorities'; import { addRegexToken, match1to2, match2 } from '../parse/regex'; import { addParseToken } from '../parse/token'; import { DATE } from './constants'; import toInt from '../utils/to-int'; // FORMATTING addFormatToken('D', ['DD', 2], 'Do', 'date'); // ALIASES addUnitAlias('date', 'D'); // PRIOROITY addUnitPriority('date', 9); // PARSING addRegexToken('D', match1to2); addRegexToken('DD', match1to2, match2); addRegexToken('Do', function (isStrict, locale) { return isStrict ? locale._dayOfMonthOrdinalParse : locale._dayOfMonthOrdinalParseLenient; }); addParseToken(['D', 'DD'], DATE); addParseToken('Do', function (input, array) { array[DATE] = toInt(input.match(match1to2)[0], 10); }); // MOMENTS export var getSetDayOfMonth = makeGetSet('Date', true);
import { makeGetSet } from '../moment/get-set'; import { addFormatToken } from '../format/format'; import { addUnitAlias } from './aliases'; import { addUnitPriority } from './priorities'; import { addRegexToken, match1to2, match2 } from '../parse/regex'; import { addParseToken } from '../parse/token'; import { DATE } from './constants'; import toInt from '../utils/to-int'; // FORMATTING addFormatToken('D', ['DD', 2], 'Do', 'date'); // ALIASES addUnitAlias('date', 'D'); // PRIOROITY addUnitPriority('date', 9); // PARSING addRegexToken('D', match1to2); addRegexToken('DD', match1to2, match2); addRegexToken('Do', function (isStrict, locale) { // TODO: Remove "ordinalParse" fallback in next major release. return isStrict ? (locale._dayOfMonthOrdinalParse || locale._ordinalParse) : locale._dayOfMonthOrdinalParseLenient; }); addParseToken(['D', 'DD'], DATE); addParseToken('Do', function (input, array) { array[DATE] = toInt(input.match(match1to2)[0], 10); }); // MOMENTS export var getSetDayOfMonth = makeGetSet('Date', true);
Add fallback for old name ordinalParse
Add fallback for old name ordinalParse
JavaScript
mit
PKRoma/moment,Oire/moment,julionc/moment,OtkurBiz/moment,ze-pequeno/moment,julionc/moment,OtkurBiz/moment,moment/moment,joelmheim/moment,xkxx/moment,monoblaine/moment,ze-pequeno/moment,moment/moment,Oire/moment,OtkurBiz/moment,xkxx/moment,monoblaine/moment,xkxx/moment,PKRoma/moment,joelmheim/moment,calebcauthon/moment,julionc/moment,joelmheim/moment,ze-pequeno/moment,moment/moment,mj1856/moment,calebcauthon/moment,PKRoma/moment,mj1856/moment,calebcauthon/moment,Oire/moment,mj1856/moment
--- +++ @@ -23,7 +23,10 @@ addRegexToken('D', match1to2); addRegexToken('DD', match1to2, match2); addRegexToken('Do', function (isStrict, locale) { - return isStrict ? locale._dayOfMonthOrdinalParse : locale._dayOfMonthOrdinalParseLenient; + // TODO: Remove "ordinalParse" fallback in next major release. + return isStrict ? + (locale._dayOfMonthOrdinalParse || locale._ordinalParse) : + locale._dayOfMonthOrdinalParseLenient; }); addParseToken(['D', 'DD'], DATE);
06b9ff1d0759d289ae70fbd9717cf8129e3485bc
pages/home/index.js
pages/home/index.js
/** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { PropTypes } from 'react'; import Layout from '../../components/Layout'; import { title, html } from './index.md'; class HomePage extends React.Component { static propTypes = { articles: PropTypes.array.isRequired, }; componentDidMount() { document.title = title; } render() { return ( <Layout> <div dangerouslySetInnerHTML={{ __html: html }} /> <h4>Articles</h4> <ul> {this.props.articles.map(article => <li><a href={article.url}>{article.title}</a> by {article.author}</li> )} </ul> <p> <br /><br /> </p> </Layout> ); } } export default HomePage;
/** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { PropTypes } from 'react'; import Layout from '../../components/Layout'; import { title, html } from './index.md'; class HomePage extends React.Component { static propTypes = { articles: PropTypes.array.isRequired, }; componentDidMount() { document.title = title; } render() { return ( <Layout> <div dangerouslySetInnerHTML={{ __html: html }} /> <h4>Articles</h4> <ul> {this.props.articles.map((article, i) => <li key={i}><a href={article.url}>{article.title}</a> by {article.author}</li> )} </ul> <p> <br /><br /> </p> </Layout> ); } } export default HomePage;
Fix React warning on the home page (add key attribute to list items)
Fix React warning on the home page (add key attribute to list items)
JavaScript
mit
raffidil/garnanain,koistya/react-static-boilerplate,jamesrf/weddingwebsite,kyoyadmoon/fuzzy-hw1,gadflying/profileSite,RyanGosden/react-poll,srossross-tableau/hackathon,kyoyadmoon/fuzzy-hw1,leo60228/HouseRuler,jamesrf/weddingwebsite,gadflying/profileSite,leo60228/HouseRuler,RyanGosden/react-poll,kriasoft/react-static-boilerplate,koistya/react-static-boilerplate,lifeiscontent/OpenPoGoUI,willchertoff/planner,kriasoft/react-static-boilerplate,gmorel/me,zedd45/react-static-todos,raffidil/garnanain,zedd45/react-static-todos,gmorel/me,willchertoff/planner,lifeiscontent/OpenPoGoUI,srossross-tableau/hackathon
--- +++ @@ -28,8 +28,8 @@ <div dangerouslySetInnerHTML={{ __html: html }} /> <h4>Articles</h4> <ul> - {this.props.articles.map(article => - <li><a href={article.url}>{article.title}</a> by {article.author}</li> + {this.props.articles.map((article, i) => + <li key={i}><a href={article.url}>{article.title}</a> by {article.author}</li> )} </ul> <p>
5afa1a697da48fb473d0e19fe6e5dbfc6913ca75
src/common/analytics/index.js
src/common/analytics/index.js
/** * Dependencies. */ let NullAnalytics = require('./NullAnalytics'); let Tracker = require('./Tracker'); /** * Constants. */ const ANALYTICS_KEY = process.env.ANALYTICS_KEY; /** * Locals. */ let enableAnalytics = window.ProductHuntAnalytics && ANALYTICS_KEY; let ProductHuntAnalytics = enableAnalytics ? window.ProductHuntAnalytics : NullAnalytics; let analytics = new ProductHuntAnalytics(process.env.ANALYTICS_KEY); /** * Export a new `Tracker`. */ module.exports = new Tracker(analytics);
/** * Dependencies. */ let NullAnalytics = require('./NullAnalytics'); let Tracker = require('./Tracker'); /** * Constants. */ const ANALYTICS_KEY = process.env.ANALYTICS_KEY; /** * Locals. * * Note(andreasklinger): window.ProductHuntAnalytics gets set by a custom built of the analytics.js * To recreate this use their make script - it offers a options to set the variable name. */ let enableAnalytics = window.ProductHuntAnalytics && ANALYTICS_KEY; let ProductHuntAnalytics = enableAnalytics ? window.ProductHuntAnalytics : NullAnalytics; let analytics = new ProductHuntAnalytics(process.env.ANALYTICS_KEY); /** * Export a new `Tracker`. */ module.exports = new Tracker(analytics);
Add note to explain where the custom name comes from
Add note to explain where the custom name comes from
JavaScript
isc
producthunt/producthunt-chrome-extension,producthunt/producthunt-chrome-extension
--- +++ @@ -13,6 +13,9 @@ /** * Locals. + * + * Note(andreasklinger): window.ProductHuntAnalytics gets set by a custom built of the analytics.js + * To recreate this use their make script - it offers a options to set the variable name. */ let enableAnalytics = window.ProductHuntAnalytics && ANALYTICS_KEY;
998601c34ba9537fa6230232379c1efad84e17bb
routes/new.js
routes/new.js
// This route will save the given url into the database // returning its "shorter" version var router = require('express').Router(); var isValid = require('valid-url').isWebUri; router.get('/http://:url', function(req, res) { var json = {}; json.original = 'http://' + req.params.url; json.shorter = getShortUrl(req, random()); + req.originalUrl res.send(json); }); router.get('/https://:url', function(req, res) { var json = {}; json.original = 'https://' + req.params.url; json.shorter = getShortUrl(req, random()); + req.originalUrl res.send(json); }); var getShortUrl = function (req, id) { var baseUrl = req.protocol + '://' + req.get('host') + '/'; return baseUrl + id; } var random = function() { // Let the IDs be numbers with up to 5 digits return Math.ceil(Math.random() * 100000); } module.exports = router;
// This route will save the given url into the database // returning its "shorter" version var router = require('express').Router(); var isValid = require('valid-url').isWebUri; // Using GET parameters in place of something like "/:url", because // with this last solution the server is fooled by the "http" in the // middle of the whole url. router.get('/', function(req, res) { var json = {}; json.original = req.param('url'); if (!isValid(json.original)) { json.err = 'invalid url'; } else { json.shorter = getShortUrl(req, random()); + req.originalUrl } res.send(json); }); var random = function() { // Let the IDs be numbers with up to 5 digits return Math.ceil(Math.random() * 100000); } module.exports = router;
Reduce code duplication using GET params
Reduce code duplication using GET params Replaced the two routes, one for http and another one for https, using GET parameter ?url=
JavaScript
mit
clobrano/fcc-url-shortener-microservice,clobrano/fcc-url-shortener-microservice
--- +++ @@ -3,24 +3,19 @@ var router = require('express').Router(); var isValid = require('valid-url').isWebUri; -router.get('/http://:url', function(req, res) { +// Using GET parameters in place of something like "/:url", because +// with this last solution the server is fooled by the "http" in the +// middle of the whole url. +router.get('/', function(req, res) { var json = {}; - json.original = 'http://' + req.params.url; - json.shorter = getShortUrl(req, random()); + req.originalUrl + json.original = req.param('url'); + if (!isValid(json.original)) { + json.err = 'invalid url'; + } else { + json.shorter = getShortUrl(req, random()); + req.originalUrl + } res.send(json); }); - -router.get('/https://:url', function(req, res) { - var json = {}; - json.original = 'https://' + req.params.url; - json.shorter = getShortUrl(req, random()); + req.originalUrl - res.send(json); -}); - -var getShortUrl = function (req, id) { - var baseUrl = req.protocol + '://' + req.get('host') + '/'; - return baseUrl + id; -} var random = function() { // Let the IDs be numbers with up to 5 digits
ede5962c9926c8a852ccbc307e3a970ede4d6954
build/server.js
build/server.js
console.time('Starting server'); require('promise-helpers'); var fs = require('fs'); var path = require('path'); var express = require('express'); var app = express(); /** * Serve static files such as css, js, images */ app.use('/images', express.static('dist/assets/images')); app.use('/javascripts', express.static('dist/assets/javascripts')); app.use('/css', express.static('dist/assets/css')); // Individual routes pulled from the routes directory fs.readdir(path.join(__dirname, '/routes'), function(err, files) { if(err) { require('trace'); require('clarify'); console.trace(err); } files.forEach(function(file) { require(path.join(__dirname, '/routes/') + file)(app); }); }); // Go go go app.listen(process.env.PORT || 3000); console.log('listening on localhost:' + (process.env.npm_config_port || 3000)); // Export our server for testing purposes module.exports = app; console.timeEnd('Starting server');
console.time('Starting server'); require('promise-helpers'); var fs = require('fs'); var path = require('path'); var express = require('express'); var app = express(); /** * Serve static files such as css, js, images */ app.use('/images', express.static('dist/assets/images')); app.use('/javascripts', express.static('dist/assets/javascripts')); app.use('/stylesheets', express.static('dist/assets/stylesheets')); // Individual routes pulled from the routes directory fs.readdir(path.join(__dirname, '/routes'), function(err, files) { if(err) { require('trace'); require('clarify'); console.trace(err); } files.forEach(function(file) { require(path.join(__dirname, '/routes/') + file)(app); }); }); // Go go go app.listen(process.env.PORT || 3000); console.log('listening on localhost:' + (process.env.npm_config_port || 3000)); // Export our server for testing purposes module.exports = app; console.timeEnd('Starting server');
Fix broken path to css caused by previous commit
Fix broken path to css caused by previous commit
JavaScript
mit
LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements
--- +++ @@ -11,7 +11,7 @@ */ app.use('/images', express.static('dist/assets/images')); app.use('/javascripts', express.static('dist/assets/javascripts')); -app.use('/css', express.static('dist/assets/css')); +app.use('/stylesheets', express.static('dist/assets/stylesheets')); // Individual routes pulled from the routes directory fs.readdir(path.join(__dirname, '/routes'), function(err, files) {
92dfcaa6e03959bc6b88701d8f269c0e344bad76
src/actions.js
src/actions.js
import assign from 'object-assign'; import { store } from './helpers'; export const MENU_SHOW = 'REACT_CONTEXTMENU_SHOW'; export const MENU_HIDE = 'REACT_CONTEXTMENU_HIDE'; export function dispatchGlobalEvent(eventName, opts, target = window) { // Compatibale with IE // @see http://stackoverflow.com/questions/26596123/internet-explorer-9-10-11-event-constructor-doesnt-work let event; if (typeof window.CustomEvent === 'function') { event = new window.CustomEvent(eventName, { detail: opts }); } else { event = document.createEvent('Event'); event.initEvent(eventName, false, true, opts); } if (target) { target.dispatchEvent(event); assign(store, opts); } } export function showMenu(opts = {}, target) { dispatchGlobalEvent(MENU_SHOW, assign({}, opts, {type: MENU_SHOW}), target); } export function hideMenu(opts = {}, target) { dispatchGlobalEvent(MENU_HIDE, assign({}, opts, {type: MENU_HIDE}), target); }
import assign from 'object-assign'; import { store } from './helpers'; export const MENU_SHOW = 'REACT_CONTEXTMENU_SHOW'; export const MENU_HIDE = 'REACT_CONTEXTMENU_HIDE'; export function dispatchGlobalEvent(eventName, opts, target = window) { // Compatibale with IE // @see http://stackoverflow.com/questions/26596123/internet-explorer-9-10-11-event-constructor-doesnt-work let event; if (typeof window.CustomEvent === 'function') { event = new window.CustomEvent(eventName, { detail: opts }); } else { event = document.createEvent('Event'); event.initCustomEvent(eventName, false, true, opts); } if (target) { target.dispatchEvent(event); assign(store, opts); } } export function showMenu(opts = {}, target) { dispatchGlobalEvent(MENU_SHOW, assign({}, opts, {type: MENU_SHOW}), target); } export function hideMenu(opts = {}, target) { dispatchGlobalEvent(MENU_HIDE, assign({}, opts, {type: MENU_HIDE}), target); }
Fix for IE11 custom event
Fix for IE11 custom event
JavaScript
mit
codeart1st/react-contextmenu,vkbansal/react-contextmenu,vkbansal/react-contextmenu,codeart1st/react-contextmenu,danbovey/react-contextmenu,danbovey/react-contextmenu
--- +++ @@ -15,7 +15,7 @@ event = new window.CustomEvent(eventName, { detail: opts }); } else { event = document.createEvent('Event'); - event.initEvent(eventName, false, true, opts); + event.initCustomEvent(eventName, false, true, opts); } if (target) {
8712432a2c9d555ecdbae0b9c549f6554dd9be6d
assets/materialize/js/init.js
assets/materialize/js/init.js
(function($){ $(function(){ $('.button-collapse').sideNav(); }); // end of document ready })(jQuery); // end of jQuery name space // Keep one tab expanded while editing profile $('li div.collapsible-header').on('click',function(e){ if($(this).parents('li').hasClass('active')){ e.stopPropagation(); } }); // Expand "Home" upon loading Edit page $("document").ready(function() { setTimeout(function() { $("ul li:first-child div").trigger('click'); },10); }); $('#last_name').on('blur',function(e) { if( document.getElementById('username').value=='' && document.getElementById('first_name').value!='' && document.getElementById('last_name').value!='') { // combine firstname and lastname to create username var username = document.getElementById('first_name').value.substr(0,490) + document.getElementById('last_name').value.substr(0,49); username = username.replace(/\s+/g, ''); username = username.replace(/\'+/g, ''); username = username.replace(/-+/g, ''); username = username.toLowerCase(); document.getElementById('username').value = username; // username label should translate up var label = $('label[for="username"]'); label['addClass']('active'); // username underline should turn green document.getElementById('username').className = "validate valid"; } });
(function($){ $(function(){ $('.button-collapse').sideNav(); }); // end of document ready })(jQuery); // end of jQuery name space // Keep one tab expanded while editing profile /*$('li div.collapsible-header').on('click',function(e){ if($(this).parents('li').hasClass('active')){ e.stopPropagation(); } });*/ // Expand "Home" upon loading Edit page $("document").ready(function() { setTimeout(function() { $("ul li:first-child div").trigger('click'); },10); }); // Sign-up form: Auto generate username based on first name and llast name inputs $('#last_name').on('blur',function(e) { if( document.getElementById('username').value=='' && document.getElementById('first_name').value!='' && document.getElementById('last_name').value!='') { // combine firstname and lastname to create username var username = document.getElementById('first_name').value.substr(0,490) + document.getElementById('last_name').value.substr(0,49); username = username.replace(/\s+/g, ''); username = username.replace(/\'+/g, ''); username = username.replace(/-+/g, ''); username = username.toLowerCase(); document.getElementById('username').value = username; // username label should translate up var label = $('label[for="username"]'); label['addClass']('active'); // username underline should turn green document.getElementById('username').className = "validate valid"; } });
Allow collapse all accordion tabs in profileeditor
Allow collapse all accordion tabs in profileeditor
JavaScript
mit
VoodooWorks/profile-cms,VoodooWorks/profile-cms,VoodooWorks/profile-cms
--- +++ @@ -7,11 +7,11 @@ })(jQuery); // end of jQuery name space // Keep one tab expanded while editing profile -$('li div.collapsible-header').on('click',function(e){ +/*$('li div.collapsible-header').on('click',function(e){ if($(this).parents('li').hasClass('active')){ e.stopPropagation(); } -}); +});*/ // Expand "Home" upon loading Edit page $("document").ready(function() { @@ -20,6 +20,7 @@ },10); }); +// Sign-up form: Auto generate username based on first name and llast name inputs $('#last_name').on('blur',function(e) { if( document.getElementById('username').value=='' && document.getElementById('first_name').value!=''
4e7eaa000c897c36ed6cdbea6e5e53d49b2b2a76
src/components/pages/PatientsSummary/header/PTCustomCheckbox.js
src/components/pages/PatientsSummary/header/PTCustomCheckbox.js
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { Col } from 'react-bootstrap'; const PTCustomCheckbox = ({ title, name, isChecked, disabled = false, onChange }) => { const toggleCheckbox = () => !disabled && onChange(name); return <Col xs={6} sm={4}> <div className="wrap-fcustominp"> <div className={classNames('fcustominp-state', { disabled })} onClick={toggleCheckbox} > <div className="fcustominp"> <input type="checkbox" name={name} checked={isChecked} onChange={toggleCheckbox} /> <label htmlFor="patients-table-info-name" /> </div> <label htmlFor={name} className="fcustominp-label">{title}</label> </div> </div> </Col> } PTCustomCheckbox.propTypes = { title: PropTypes.string.isRequired, name: PropTypes.string.isRequired, isChecked: PropTypes.bool.isRequired, onChange: PropTypes.func, disabled: PropTypes.bool, }; export default PTCustomCheckbox
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { Col } from 'react-bootstrap'; const PTCustomCheckbox = ({ title, name, isChecked, disabled = false, onChange }) => { const toggleCheckbox = () => !disabled && onChange(name); return <Col xs={6} sm={4}> <div className="wrap-fcustominp"> <div className={classNames('fcustominp-state', { disabled })} onClick={toggleCheckbox} > <div className="fcustominp"> <input type="checkbox" id={`dashboard-${name}`} name={`dashboard-${name}`} checked={isChecked} onChange={toggleCheckbox} /> <label htmlFor={`dashboard-${name}`} /> </div> <label htmlFor={`dashboard-${name}`} className="fcustominp-label">{title}</label> </div> </div> </Col> } PTCustomCheckbox.propTypes = { title: PropTypes.string.isRequired, name: PropTypes.string.isRequired, isChecked: PropTypes.bool.isRequired, onChange: PropTypes.func, disabled: PropTypes.bool, }; export default PTCustomCheckbox
Fix checkboxes for Patient Summary.
Fix checkboxes for Patient Summary.
JavaScript
apache-2.0
PulseTile/PulseTile-React,PulseTile/PulseTile-React,PulseTile/PulseTile-React
--- +++ @@ -10,10 +10,10 @@ <div className="wrap-fcustominp"> <div className={classNames('fcustominp-state', { disabled })} onClick={toggleCheckbox} > <div className="fcustominp"> - <input type="checkbox" name={name} checked={isChecked} onChange={toggleCheckbox} /> - <label htmlFor="patients-table-info-name" /> + <input type="checkbox" id={`dashboard-${name}`} name={`dashboard-${name}`} checked={isChecked} onChange={toggleCheckbox} /> + <label htmlFor={`dashboard-${name}`} /> </div> - <label htmlFor={name} className="fcustominp-label">{title}</label> + <label htmlFor={`dashboard-${name}`} className="fcustominp-label">{title}</label> </div> </div> </Col>
f0e7098f88d7ceeae02ba60bb484f4cfa266bce7
src/plugins.js
src/plugins.js
/* @flow */ export const inMemory = (data : Object, transition : Function) => { let rootState = data; const read = () => rootState; const write = (fn : Function) => { const oldState = read(); const newState = fn(oldState); transition(oldState, newState); rootState = newState; return read(); }; return { read, write }; }; export const webStorage = ( { type, key } : Object, data : Object, transition : Function ) => { const store = window[`${type}Storage`]; const read = () => JSON.parse(store.getItem(key)); const write = (fn : Function) => { const oldState = read(); const newState = fn(oldState); transition(oldState, newState); store.setItem(key, JSON.stringify(newState)); return read(); }; return { read, write }; };
/* @flow */ export const inMemory = (initial : Object, transition : Function) => { let rootState = initial; const read = () => rootState; const write = (fn : Function) => { const oldState = read(); const newState = fn(oldState); transition(oldState, newState); rootState = newState; return read(); }; return { read, write }; }; export const webStorage = ( { type, key } : Object, initial : Object, transition : Function ) => { const store = window[`${type}Storage`]; const read = () => JSON.parse(store.getItem(key)); const write = (fn : Function) => { const oldState = read(); const newState = fn(oldState); transition(oldState, newState); store.setItem(key, JSON.stringify(newState)); return read(); }; return { read, write }; };
Rename data prop to initial
Rename data prop to initial
JavaScript
mit
jameshopkins/atom-store,jameshopkins/atom-store
--- +++ @@ -1,7 +1,7 @@ /* @flow */ -export const inMemory = (data : Object, transition : Function) => { - let rootState = data; +export const inMemory = (initial : Object, transition : Function) => { + let rootState = initial; const read = () => rootState; const write = (fn : Function) => { const oldState = read(); @@ -15,7 +15,7 @@ export const webStorage = ( { type, key } : Object, - data : Object, + initial : Object, transition : Function ) => { const store = window[`${type}Storage`];
6505b754bc31ce4062d1a4c2eecc172636dbba64
src/components/Node.js
src/components/Node.js
import React, { PropTypes } from 'react'; import { StyleSheet, css } from 'aphrodite'; const styles = StyleSheet.create({ node: { cursor: 'move', }, }); const renderState = (state, index) => ( <text key={state} x="5" y={37 + (18 * index)}> <tspan>{state}</tspan> <tspan x="155" textAnchor="end">99.9</tspan> </text> ); const Node = props => ( <g className={css(styles.node)} onMouseDown={props.onMouseDown} transform={`translate(${props.x} ${props.y})`} > <rect height={20 + (20 * props.states.length)} width="160" fill="#ff8" stroke="#333" ref={props.rectRef} /> <text x="5" y="15">{props.id}</text> <path d="M0,20 h160" stroke="#333" /> {props.states.map(renderState)} </g> ); Node.propTypes = { id: PropTypes.string.isRequired, states: PropTypes.arrayOf(PropTypes.string).isRequired, rectRef: PropTypes.func, onMouseDown: PropTypes.func, x: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired, y: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired, }; export default Node;
import React, { PropTypes } from 'react'; import { StyleSheet, css } from 'aphrodite'; const styles = StyleSheet.create({ node: { cursor: 'move', userSelect: 'none', }, }); const renderState = (state, index) => ( <text key={state} x="5" y={37 + (18 * index)}> <tspan>{state}</tspan> <tspan x="155" textAnchor="end">99.9</tspan> </text> ); const Node = props => ( <g className={css(styles.node)} onMouseDown={props.onMouseDown} transform={`translate(${props.x} ${props.y})`} > <rect height={20 + (20 * props.states.length)} width="160" fill="#ff8" stroke="#333" ref={props.rectRef} /> <text x="5" y="15">{props.id}</text> <path d="M0,20 h160" stroke="#333" /> {props.states.map(renderState)} </g> ); Node.propTypes = { id: PropTypes.string.isRequired, states: PropTypes.arrayOf(PropTypes.string).isRequired, rectRef: PropTypes.func, onMouseDown: PropTypes.func, x: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired, y: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired, }; export default Node;
Fix selecting node text when moving
Fix selecting node text when moving
JavaScript
mit
fhelwanger/bayesjs-editor,fhelwanger/bayesjs-editor
--- +++ @@ -4,6 +4,7 @@ const styles = StyleSheet.create({ node: { cursor: 'move', + userSelect: 'none', }, });
bbf64c4d45fc83b5143951f79f2a9c25d757cd65
addon/components/outside-click/component.js
addon/components/outside-click/component.js
import Ember from 'ember' import layout from './template' import PropTypeMixin, { PropTypes } from 'ember-prop-types' const { K } = Ember export default Ember.Component.extend(PropTypeMixin, { layout, propTypes: { onOutsideClick: PropTypes.func }, getDefaultProps() { return { onOutsideClick: K } }, init() { this._super(...arguments) this.handleDown = this.handleDown.bind(this) this.handleUp = this.handleUp.bind(this) }, didInsertElement() { this._super(...arguments) document.addEventListener('mousedown', this.handleDown, true) document.addEventListener('mouseup', this.handleUp, true) }, willDestroyElement() { this._super(...arguments) document.removeEventListener('mousedown', this.handleDown, true) document.removeEventListener('mouseup', this.handleUp, true) }, isOutside: false, handleDown(e) { if (this.isDestroyed || this.isDestroying) { return; } const el = this.$()[0]; if (!el.contains(e.target)) this.set('isOutside', true) }, handleUp(e) { if (this.isDestroyed || this.isDestroying) { return; } if (this.get('isOutside')) this.get('onOutsideClick')(e) this.set('isOutside', false) } })
import Ember from 'ember' import layout from './template' import PropTypeMixin, { PropTypes } from 'ember-prop-types' const { K } = Ember export default Ember.Component.extend(PropTypeMixin, { layout, propTypes: { onOutsideClick: PropTypes.func }, getDefaultProps() { return { onOutsideClick: K } }, init() { this._super(...arguments) this.handleDown = this.handleDown.bind(this) this.handleUp = this.handleUp.bind(this) }, didInsertElement() { this._super(...arguments) document.addEventListener('mousedown', this.handleDown, true) document.addEventListener('mouseup', this.handleUp, true) }, willDestroyElement() { this._super(...arguments) document.removeEventListener('mousedown', this.handleDown, true) document.removeEventListener('mouseup', this.handleUp, true) }, isOutside: false, handleDown(e) { const el = this.$()[0]; if (this.isDestroyed || this.isDestroying) return; if (!el.contains(e.target)) this.set('isOutside', true) }, handleUp(e) { if (this.get('isOutside')) this.get('onOutsideClick')(e) if (this.isDestroyed || this.isDestroying) return; this.set('isOutside', false) } })
Move destroy checks just before set
Move destroy checks just before set
JavaScript
mit
nucleartide/ember-outside-click,nucleartide/ember-outside-click
--- +++ @@ -37,18 +37,14 @@ isOutside: false, handleDown(e) { - if (this.isDestroyed || this.isDestroying) { - return; - } const el = this.$()[0]; + if (this.isDestroyed || this.isDestroying) return; if (!el.contains(e.target)) this.set('isOutside', true) }, handleUp(e) { - if (this.isDestroyed || this.isDestroying) { - return; - } if (this.get('isOutside')) this.get('onOutsideClick')(e) + if (this.isDestroyed || this.isDestroying) return; this.set('isOutside', false) } })
ec5e284f43cd890a2d24f775f77f0fc5f3810dfc
src/App.js
src/App.js
import React from 'react'; import './App.css'; import logo from './logo.png'; export default function App() { return ( <div> <h1> Welcome to <img src={logo} className="App--logo" alt="React logo" /> React </h1> <p> To get started, edit <code>src/App.js</code> and save the file to update. </p> </div> ); }
import React from 'react'; import './App.css'; import logo from './logo.png'; export default function App() { return ( <div> <h1> Welcome to <img src={logo} className="App--logo" alt="logo" /> React </h1> <p> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); }
Make it fit in one line
Make it fit in one line
JavaScript
bsd-3-clause
emvu/create-react-app,HelpfulHuman/helpful-react-scripts,Timer/create-react-app,christiantinauer/create-react-app,yosharepoint/react-scripts-ts-sp,powerreviews/create-react-app,CodingZeal/create-react-app,lolaent/create-react-app,xiaohu-developer/create-react-app,HelpfulHuman/helpful-react-scripts,andyeskridge/create-react-app,Clearcover/web-build,mikechau/create-react-app,brysgo/create-react-app,TondaHack/create-react-app,timlogemann/create-react-app,timlogemann/create-react-app,andyhite/create-react-app,peopleticker/create-react-app,ConnectedHomes/create-react-web-app,jdcrensh/create-react-app,scyankai/create-react-app,matart15/create-react-app,jayphelps/create-react-app,accurat/accurapp,andyhite/create-react-app,cr101/create-react-app,in2core/create-react-app,matart15/create-react-app,DivineGod/create-react-app,mangomint/create-react-app,Psychwire/create-react-app,kst404/e8e-react-scripts,Bogala/create-react-app-awesome-ts,reedsa/create-react-app,dsopel94/create-react-app,andrewmaudsley/create-react-app,lopezator/create-react-app,liamhu/create-react-app,stockspiking/create-react-app,prometheusresearch/create-react-app,Bogala/create-react-app-awesome-ts,ro-savage/create-react-app,xiaohu-developer/create-react-app,Sonu-sj/cardMatcher,ontruck/create-react-app,maletor/create-react-app,igetgames/spectacle-create-react-app,paweljedrzejczyk/create-react-app,digitalorigin/create-react-app,pdillon/create-react-app,g3r4n/create-esri-react-app,gutenye/create-react-app,Clearcover/web-build,Bogala/create-react-app-awesome-ts,andyhite/create-react-app,0xaio/create-react-app,vgmr/create-ts-app,johnslay/create-react-app,iamdoron/create-react-app,appier/create-react-app,gutenye/create-react-app,lolaent/create-react-app,pdillon/create-react-app,amido/create-react-app,johnslay/create-react-app,digitalorigin/create-react-app,tharakawj/create-react-app,svrcekmichal/react-scripts,powerreviews/create-react-app,andyeskridge/create-react-app,ontruck/create-react-app,romaindso/create-react-app,Exocortex/create-react-app,g3r4n/create-esri-react-app,ro-savage/create-react-app,sigmacomputing/create-react-app,Place1/create-react-app-typescript,pdillon/create-react-app,facebookincubator/create-react-app,iamdoron/create-react-app,HelpfulHuman/helpful-react-scripts,devex-web-frontend/create-react-app-dx,lolaent/create-react-app,Sonu-sj/cardMatcher,RobzDoom/frame_trap,infernojs/create-inferno-app,magic-FE/create-magic-component,romaindso/create-react-app,svrcekmichal/react-scripts,facebookincubator/create-react-app,Exocortex/create-react-app,infernojs/create-inferno-app,scyankai/create-react-app,liamhu/create-react-app,accurat/accurapp,maletor/create-react-app,dpoineau/create-react-app,viankakrisna/create-react-app,ConnectedHomes/create-react-web-app,1Body/prayer-app,viankakrisna/create-react-app,dpoineau/create-react-app,prometheusresearch/create-react-app,paweljedrzejczyk/create-react-app,Bogala/create-react-app-awesome-ts,IamJoseph/create-react-app,TryKickoff/create-kickoff-app,lopezator/create-react-app,gutenye/create-react-app,Psychwire/create-react-app,picter/create-react-app,tharakawj/create-react-app,CodingZeal/create-react-app,magic-FE/create-magic-component,igetgames/spectacle-create-react-app,in2core/create-react-app,accurat/accurapp,kst404/e8e-react-scripts,viankakrisna/create-react-app,bttf/create-react-app,tharakawj/create-react-app,RobzDoom/frame_trap,g3r4n/create-esri-react-app,shrynx/react-super-scripts,Place1/create-react-app-typescript,1Body/prayer-app,prontotools/create-react-app,jayphelps/create-react-app,mangomint/create-react-app,cr101/create-react-app,christiantinauer/create-react-app,sigmacomputing/create-react-app,Timer/create-react-app,1Body/prayer-app,bttf/create-react-app,johnslay/create-react-app,just-boris/create-preact-app,dsopel94/create-react-app,maletor/create-react-app,ConnectedHomes/create-react-web-app,ConnectedHomes/create-react-web-app,peopleticker/create-react-app,1Body/prayer-app,amido/create-react-app,yosharepoint/react-scripts-ts-sp,flybayer/create-react-webextension,josephfinlayson/create-react-app,bttf/create-react-app,mikechau/create-react-app,DivineGod/create-react-app,svrcekmichal/react-scripts,sigmacomputing/create-react-app,Exocortex/create-react-app,jdcrensh/create-react-app,dsopel94/create-react-app,GreenGremlin/create-react-app,xiaohu-developer/create-react-app,reedsa/create-react-app,andrewmaudsley/create-react-app,flybayer/create-react-webextension,Place1/create-react-app-typescript,stockspiking/create-react-app,d3ce1t/create-react-app,iamdoron/create-react-app,GreenGremlin/create-react-app,paweljedrzejczyk/create-react-app,Psychwire/create-react-app,vgmr/create-ts-app,andrewmaudsley/create-react-app,facebookincubator/create-react-app,emvu/create-react-app,jayphelps/create-react-app,prometheusresearch/create-react-app,ontruck/create-react-app,brysgo/create-react-app,TondaHack/create-react-app,josephfinlayson/create-react-app,digitalorigin/create-react-app,mangomint/create-react-app,DivineGod/create-react-app,in2core/create-react-app,magic-FE/create-magic-component,christiantinauer/create-react-app,andyeskridge/create-react-app,timlogemann/create-react-app,vgmr/create-ts-app,devex-web-frontend/create-react-app-dx,igetgames/spectacle-create-react-app,flybayer/create-react-webextension,jdcrensh/create-react-app,stockspiking/create-react-app,infernojs/create-inferno-app,shrynx/react-super-scripts,matart15/create-react-app,Timer/create-react-app,devex-web-frontend/create-react-app-dx,d3ce1t/create-react-app,picter/create-react-app,scyankai/create-react-app,romaindso/create-react-app,d3ce1t/create-react-app,mikechau/create-react-app,yosharepoint/react-scripts-ts-sp,IamJoseph/create-react-app,d3ce1t/create-react-app,ro-savage/create-react-app,liamhu/create-react-app,Sonu-sj/cardMatcher,GreenGremlin/create-react-app,vgmr/create-ts-app,Timer/create-react-app,yosharepoint/react-scripts-ts-sp,0xaio/create-react-app,appier/create-react-app,dpoineau/create-react-app,shrynx/react-super-scripts,prontotools/create-react-app,peopleticker/create-react-app,reedsa/create-react-app,just-boris/create-preact-app,jdcrensh/create-react-app,accurat/accurapp,GreenGremlin/create-react-app,whobutsb/create-redux-app,Place1/create-react-app-typescript,timlogemann/create-react-app,RobzDoom/frame_trap,amido/create-react-app,cr101/create-react-app,whobutsb/create-redux-app,TondaHack/create-react-app,mangomint/create-react-app,brysgo/create-react-app,kst404/e8e-react-scripts,TryKickoff/create-kickoff-app,Clearcover/web-build,CodingZeal/create-react-app,lopezator/create-react-app,0xaio/create-react-app,just-boris/create-preact-app,picter/create-react-app,powerreviews/create-react-app,christiantinauer/create-react-app,devex-web-frontend/create-react-app-dx,IamJoseph/create-react-app,appier/create-react-app,TryKickoff/create-kickoff-app,josephfinlayson/create-react-app,prontotools/create-react-app,emvu/create-react-app
--- +++ @@ -6,13 +6,10 @@ return ( <div> <h1> - Welcome to - <img src={logo} className="App--logo" alt="React logo" /> - React + Welcome to <img src={logo} className="App--logo" alt="logo" /> React </h1> <p> - To get started, edit <code>src/App.js</code> and - save the file to update. + To get started, edit <code>src/App.js</code> and save to reload. </p> </div> );
e96df96e13e47ab983fbdbcf58bd00ebd0ff9e5b
public/js/layout.js
public/js/layout.js
var fixedWidth = 220; var minWidth = 660; var fixedPadding = 100; function layoutWidth() { var wWidth = $(window).width(); var bodyPadding = Math.max(Math.floor(wWidth / fixedWidth)-3, 1) * 100; if ($(".container").length) { var width = wWidth - bodyPadding; var newWidth = Math.floor(width / fixedWidth) * fixedWidth; if (newWidth < minWidth) newWidth = minWidth; $(".container").width(newWidth); } } $(document).ready(function() { layoutWidth(); $(window).resize(function(){ layoutWidth(); }); });
var fixedWidth = 220; var minWidth = 660; var fixedPadding = 100; var delayResize = null; function layoutWidth() { var wWidth = $(window).width(); var bodyPadding = Math.max(Math.floor(wWidth / fixedWidth)-3, 1) * 100; if ($(".container").length) { var width = wWidth - bodyPadding; var newWidth = Math.floor(width / fixedWidth) * fixedWidth; if (newWidth < minWidth) newWidth = minWidth; $(".container").width(newWidth); } } function layoutResize() { clearTimeout(delayResize); delayResize = setTimeout(layoutWidth, 250); } $(document).ready(function() { layoutWidth(); $(window).resize(function(){ layoutResize(); }); });
Add timeout when resizing container (prevent close multicall that can cause performance issue)
Add timeout when resizing container (prevent close multicall that can cause performance issue)
JavaScript
mit
hernantas/MangaReader,hernantas/MangaReader,hernantas/MangaReader
--- +++ @@ -2,6 +2,7 @@ var fixedWidth = 220; var minWidth = 660; var fixedPadding = 100; +var delayResize = null; function layoutWidth() { @@ -16,10 +17,16 @@ } } +function layoutResize() +{ + clearTimeout(delayResize); + delayResize = setTimeout(layoutWidth, 250); +} + $(document).ready(function() { layoutWidth(); $(window).resize(function(){ - layoutWidth(); + layoutResize(); }); });
3fd410806d1f9cc2f922efde78539671306bd739
server/app.js
server/app.js
Meteor.startup(function () { Tiqs._ensureIndex({text: 1}); }); Meteor.methods({ associateTags: function(text, tags) { Tiqs.upsert({text: text}, {$addToSet: {tags: {$each: tags}}}); _.each(tags, function(tag) { Tiqs.upsert({text: tag}, {$addToSet: {tags: text}}); }); } });
Meteor.startup(function () { Tiqs._ensureIndex({text: 1}); }); Meteor.methods({ associateTags: function(text, tags) { Tiqs.upsert({text: text}, {$addToSet: {tags: {$each: tags}}, $setOnInsert: {createdAt: Date.now()} } ); _.each(tags, function(tag) { Tiqs.upsert({text: tag}, {$addToSet: {tags: text}, $setOnInsert: {createdAt: Date.now()}} ); }); } });
Add createdAt field to Tiqs collection
Add createdAt field to Tiqs collection
JavaScript
mit
imiric/tiq-web,imiric/tiq-web
--- +++ @@ -4,10 +4,16 @@ Meteor.methods({ associateTags: function(text, tags) { - Tiqs.upsert({text: text}, {$addToSet: {tags: {$each: tags}}}); + Tiqs.upsert({text: text}, + {$addToSet: {tags: {$each: tags}}, + $setOnInsert: {createdAt: Date.now()} + } + ); _.each(tags, function(tag) { - Tiqs.upsert({text: tag}, {$addToSet: {tags: text}}); + Tiqs.upsert({text: tag}, + {$addToSet: {tags: text}, $setOnInsert: {createdAt: Date.now()}} + ); }); } });
f0a2fefc7eced759ad5c639c85df44194c3a89f8
rules/temporary-hrdata.js
rules/temporary-hrdata.js
function (user, context, callback) { // This is a rule to specifically allow access to _HRData for specific ClientIDs // _HRData comes from WorkDay, through LDAP Connector // Ideally the RPs who need this data should request it directly from WorkDay, so this is a work-around. // Applications that are ALLOWED to see _HRData var ALLOWED_CLIENTIDS = [ 'IU80mVpKPtIZyUZtya9ZnSTs6fKLt3JO', //biztera.com 'R4djNlyXSl3i8N2KXWkfylghDa9kFQ84' //mozilla.tap.thinksmart.com ]; if (ALLOWED_CLIENTIDS.indexOf(context.clientID) >= 0) { var extend = require('extend'); context.samlConfiguration = context.samlConfiguration || {}; //Remap SAML attributes as SAML cannot show Javascript objects for(var value in user._HRData){ var nname = "http://schemas.security.allizom.org/claims/HRData/"+encodeURIComponent(value); var nvalue = "_HRData."+value; var obj = {}; obj[nname] = nvalue; context.samlConfiguration.mappings = extend(true, context.samlConfiguration.mappings, obj); } callback(null, user, context); } else { // Wipe _HRData (do use non-dot notation) user['_HRData'] = {"placeholder": "empty"}; callback(null, user, context); } }
function (user, context, callback) { // This is a rule to specifically allow access to _HRData for specific ClientIDs // _HRData comes from WorkDay, through LDAP Connector // Ideally the RPs who need this data should request it directly from WorkDay, so this is a work-around. // Applications that are ALLOWED to see _HRData var ALLOWED_CLIENTIDS = [ 'IU80mVpKPtIZyUZtya9ZnSTs6fKLt3JO', //biztera.com 'R4djNlyXSl3i8N2KXWkfylghDa9kFQ84', //mozilla.tap.thinksmart.com 'fNzzMG3XfkxQJcnUpgrGyH2deII3nFFM' //pto1.dmz.mdc1.mozilla.com ]; if (ALLOWED_CLIENTIDS.indexOf(context.clientID) >= 0) { var extend = require('extend'); context.samlConfiguration = context.samlConfiguration || {}; //Remap SAML attributes as SAML cannot show Javascript objects for(var value in user._HRData){ var nname = "http://schemas.security.allizom.org/claims/HRData/"+encodeURIComponent(value); var nvalue = "_HRData."+value; var obj = {}; obj[nname] = nvalue; context.samlConfiguration.mappings = extend(true, context.samlConfiguration.mappings, obj); } callback(null, user, context); } else { // Wipe _HRData (do use non-dot notation) user['_HRData'] = {"placeholder": "empty"}; callback(null, user, context); } }
Add pto app to hrdata rule
Add pto app to hrdata rule this will allow the pto app to get manager info and no longer need an LDAP connection
JavaScript
mpl-2.0
mozilla-iam/auth0-deploy,jdow/auth0-deploy,jdow/auth0-deploy,mozilla-iam/auth0-deploy
--- +++ @@ -6,7 +6,8 @@ // Applications that are ALLOWED to see _HRData var ALLOWED_CLIENTIDS = [ 'IU80mVpKPtIZyUZtya9ZnSTs6fKLt3JO', //biztera.com - 'R4djNlyXSl3i8N2KXWkfylghDa9kFQ84' //mozilla.tap.thinksmart.com + 'R4djNlyXSl3i8N2KXWkfylghDa9kFQ84', //mozilla.tap.thinksmart.com + 'fNzzMG3XfkxQJcnUpgrGyH2deII3nFFM' //pto1.dmz.mdc1.mozilla.com ]; if (ALLOWED_CLIENTIDS.indexOf(context.clientID) >= 0) {
2f61e76a50034cd06611bf0086d57deeaf61a2dd
schema/me/save_artwork.js
schema/me/save_artwork.js
import gravity from '../../lib/loaders/gravity'; import { GraphQLString, GraphQLBoolean } from 'graphql'; import { mutationWithClientMutationId } from 'graphql-relay'; import { artworkFields } from '../artwork/index'; export default mutationWithClientMutationId({ name: 'SaveArtwork', decription: 'Save (or remove) an artwork to (from) a users default collection.', inputFields: { artwork_id: { type: GraphQLString, }, remove: { type: GraphQLBoolean, }, }, outputFields: artworkFields(), mutateAndGetPayload: ({ artwork_id, remove, }, request, { rootValue: { accessToken, userID } }) => { if (!accessToken) return new Error('You need to be signed in to perform this action'); const saveMethod = remove ? 'DELETE' : 'POST'; return gravity.with(accessToken, { method: saveMethod, })(`/collection/saved-artwork/artwork/${artwork_id}`, { user_id: userID, }).then(() => gravity(`artwork/${artwork_id}`)); }, });
import gravity from '../../lib/loaders/gravity'; import { GraphQLString, GraphQLBoolean } from 'graphql'; import { mutationWithClientMutationId } from 'graphql-relay'; import { ArtworkType } from '../artwork/index'; export default mutationWithClientMutationId({ name: 'SaveArtwork', decription: 'Save (or remove) an artwork to (from) a users default collection.', inputFields: { artwork_id: { type: GraphQLString, }, remove: { type: GraphQLBoolean, }, }, outputFields: { artwork: { type: ArtworkType, resolve: ({ artwork_id }) => gravity(`artwork/${artwork_id}`), }, }, mutateAndGetPayload: ({ artwork_id, remove, }, request, { rootValue: { accessToken, userID } }) => { if (!accessToken) return new Error('You need to be signed in to perform this action'); const saveMethod = remove ? 'DELETE' : 'POST'; return gravity.with(accessToken, { method: saveMethod, })(`/collection/saved-artwork/artwork/${artwork_id}`, { user_id: userID, }).then(() => ({ artwork_id })); }, });
Return artwork node instead of fields
Return artwork node instead of fields
JavaScript
mit
mzikherman/metaphysics-1,craigspaeth/metaphysics,artsy/metaphysics,craigspaeth/metaphysics,artsy/metaphysics,mzikherman/metaphysics-1,artsy/metaphysics,mzikherman/metaphysics-1,broskoski/metaphysics,mzikherman/metaphysics-1
--- +++ @@ -1,7 +1,7 @@ import gravity from '../../lib/loaders/gravity'; import { GraphQLString, GraphQLBoolean } from 'graphql'; import { mutationWithClientMutationId } from 'graphql-relay'; -import { artworkFields } from '../artwork/index'; +import { ArtworkType } from '../artwork/index'; export default mutationWithClientMutationId({ name: 'SaveArtwork', @@ -14,7 +14,12 @@ type: GraphQLBoolean, }, }, - outputFields: artworkFields(), + outputFields: { + artwork: { + type: ArtworkType, + resolve: ({ artwork_id }) => gravity(`artwork/${artwork_id}`), + }, + }, mutateAndGetPayload: ({ artwork_id, remove, @@ -25,6 +30,6 @@ method: saveMethod, })(`/collection/saved-artwork/artwork/${artwork_id}`, { user_id: userID, - }).then(() => gravity(`artwork/${artwork_id}`)); + }).then(() => ({ artwork_id })); }, });
27e1d21c375b16697c4ca4eef0f6c14193262797
test/DropdownAlert-test.js
test/DropdownAlert-test.js
const React = require('react') const should = require('should') const { shallow } = require('enzyme') const { expect } = require('chai') import DropdownAlert from '../DropdownAlert' import { View, Text, StyleSheet, TouchableHighlight, Animated, Modal, StatusBar, Image } from "react-native" describe('DropdownAlert', () => { let dropdownAlert before(() => { dropdownAlert = shallow(<DropdownAlert />) }) it('should exist', () => { DropdownAlert.should.be.ok }) })
const React = require('react') const should = require('should') const { shallow } = require('enzyme') const { expect } = require('chai') import DropdownAlert from '../DropdownAlert' import { View, Text, StyleSheet, TouchableHighlight, Animated, Modal, StatusBar, Image } from "react-native" describe('DropdownAlert', () => { it('should exist', () => { let wrapper = shallow(<DropdownAlert />) should.exist(wrapper) }) it('should find custom sub components', () => { let wrapper = shallow(<DropdownAlert imageUri={'https://facebook.github.io/react/img/logo_og.png'} />) wrapper.instance().alert('custom', 'Title', 'Message') wrapper.update() expect(wrapper.find(Modal)).to.have.length(1) expect(wrapper.find(StatusBar)).to.have.length(1) expect(wrapper.find(View)).to.have.length(2) expect(wrapper.find(Animated.View)).to.have.length(1) expect(wrapper.find(TouchableHighlight)).to.have.length(1) expect(wrapper.find(Text)).to.have.length(2) expect(wrapper.find(Image)).to.have.length(1) }) it('should dismiss', () => { let wrapper = shallow(<DropdownAlert />) wrapper.instance().dismiss() wrapper.update() wrapper.instance().should.be.ok }) })
Add sub components test; Add dismiss test
Add sub components test; Add dismiss test
JavaScript
mit
testshallpass/react-native-dropdownalert,testshallpass/react-native-dropdownalert,shotozuro/react-native-dropdownalert,devBrian/react-native-dropdownalert,devBrian/react-native-dropdownalert,shotozuro/react-native-dropdownalert,shotozuro/react-native-dropdownalert,devBrian/react-native-dropdownalert,testshallpass/react-native-dropdownalert
--- +++ @@ -16,11 +16,26 @@ } from "react-native" describe('DropdownAlert', () => { - let dropdownAlert - before(() => { - dropdownAlert = shallow(<DropdownAlert />) + it('should exist', () => { + let wrapper = shallow(<DropdownAlert />) + should.exist(wrapper) }) - it('should exist', () => { - DropdownAlert.should.be.ok + it('should find custom sub components', () => { + let wrapper = shallow(<DropdownAlert imageUri={'https://facebook.github.io/react/img/logo_og.png'} />) + wrapper.instance().alert('custom', 'Title', 'Message') + wrapper.update() + expect(wrapper.find(Modal)).to.have.length(1) + expect(wrapper.find(StatusBar)).to.have.length(1) + expect(wrapper.find(View)).to.have.length(2) + expect(wrapper.find(Animated.View)).to.have.length(1) + expect(wrapper.find(TouchableHighlight)).to.have.length(1) + expect(wrapper.find(Text)).to.have.length(2) + expect(wrapper.find(Image)).to.have.length(1) + }) + it('should dismiss', () => { + let wrapper = shallow(<DropdownAlert />) + wrapper.instance().dismiss() + wrapper.update() + wrapper.instance().should.be.ok }) })
9f26f41123b6fcda8ade34325161d8d433f4ec61
test/unit/api/component.js
test/unit/api/component.js
import { Component } from '../../../src'; describe('api/Component', () => { if (!classStaticsInheritance()) { return; } describe('property getters', () => { it('observedAttributes', () => { class Test extends Component { static get observedAttributes() { return ['test']; } }; expect(Test.observedAttributes).to.deep.equal(['test']); }); it('props', () => { class Test extends Component { static get props() { return { test: { attribute: true } }; } }; expect(Test.props).to.deep.equal({ test: { attribute: true } }); }); }); describe('property initialisers', () => { it('observedAttributes', () => { class Test extends Component { static observedAttributes = ['test']; }; expect(Test.observedAttributes).to.deep.equal(['test']); }); it('props', () => { class Test extends Component { static props = { test: { attribute: true } }; }; expect(Test.props).to.deep.equal({ test: { attribute: true } }); }); }); });
import { Component } from '../../../src'; import { classStaticsInheritance } from '../lib/support'; describe('api/Component', () => { if (!classStaticsInheritance()) { return; } describe('property getters', () => { it('observedAttributes', () => { class Test extends Component { static get observedAttributes() { return ['test']; } }; expect(Test.observedAttributes).to.deep.equal(['test']); }); it('props', () => { class Test extends Component { static get props() { return { test: { attribute: true } }; } }; expect(Test.props).to.deep.equal({ test: { attribute: true } }); }); }); describe('property initialisers', () => { it('observedAttributes', () => { class Test extends Component { static observedAttributes = ['test']; }; expect(Test.observedAttributes).to.deep.equal(['test']); }); it('props', () => { class Test extends Component { static props = { test: { attribute: true } }; }; expect(Test.props).to.deep.equal({ test: { attribute: true } }); }); }); });
Fix test by adding a missing import.
test: Fix test by adding a missing import.
JavaScript
mit
skatejs/skatejs,skatejs/skatejs,skatejs/skatejs,chrisdarroch/skatejs,chrisdarroch/skatejs
--- +++ @@ -1,4 +1,5 @@ import { Component } from '../../../src'; +import { classStaticsInheritance } from '../lib/support'; describe('api/Component', () => { if (!classStaticsInheritance()) {
cb04c26b0819fe742c80bc8f05ce3af3c32823e3
lib/node_modules/@stdlib/fs/read-file/examples/index.js
lib/node_modules/@stdlib/fs/read-file/examples/index.js
'use strict'; var readFile = require( './../lib' ); // Sync // var file = readFile.sync( __filename, 'utf8' ); // returns <string> console.log( file instanceof Error ); // => false file = readFile.sync( 'beepboop', { 'encoding': 'utf8' }); // returns <Error> console.log( file instanceof Error ); // => true // Async // readFile( __filename, onFile ); readFile( 'beepboop', onFile ); function onFile( error, data ) { if ( error ) { if ( error.code === 'ENOENT' ) { console.error( 'File does not exist.' ); } else { throw error; } } else { console.log( data ); } }
'use strict'; var readFile = require( './../lib' ); // Sync // var file = readFile.sync( __filename, 'utf8' ); // returns <string> console.log( file instanceof Error ); // => false file = readFile.sync( 'beepboop', { 'encoding': 'utf8' }); // returns <Error> console.log( file instanceof Error ); // => true // Async // readFile( __filename, onFile ); readFile( 'beepboop', onFile ); function onFile( error, data ) { if ( error ) { if ( error.code === 'ENOENT' ) { console.error( 'File does not exist.' ); } else { throw error; } } else { console.log( data ); } }
Remove extra trailing empty lines
Remove extra trailing empty lines
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
--- +++ @@ -35,6 +35,3 @@ console.log( data ); } } - - -
ea22ee1596e2f9d93ce01349f06a3c99143f21bb
test/absUrl.js
test/absUrl.js
var should = require('chai').should(); var LocationUtil = require('../src/location-util.js').LocationUtil; describe('#absUrl', function () { it('should get full URL', function () { var l = new LocationUtil('http://example.com:8080/foo?bar=buz#frag'); l.absUrl().should.equal('http://example.com:8080/foo?bar=buz#frag'); }); });
var should = require('chai').should(); var LocationUtil = require('../src/location-util.js').LocationUtil; describe('#absUrl', function () { it('should get full URL', function () { var l = new LocationUtil('http://example.com:8080/foo?bar=buz#frag'); l.absUrl().should.equal('http://example.com:8080/foo?bar=buz#frag'); }); it('documents behavior', function () { var l = new LocationUtil('http://example.com:3000/foo?bar=buz#frag'); l.url('/user?id=123#name').absUrl().should.equal('http://example.com:3000/user?id=123#name'); l.path('/entry').absUrl().should.equal('http://example.com:3000/entry?id=123#name'); l.search('date', '20140401', 'id', null).absUrl().should.equal('http://example.com:3000/entry?date=20140401#name'); l.hash('').absUrl().should.equal('http://example.com:3000/entry?date=20140401'); }); });
Add some test cases that are in doc
Add some test cases that are in doc
JavaScript
mit
moznion/location-util
--- +++ @@ -8,5 +8,13 @@ var l = new LocationUtil('http://example.com:8080/foo?bar=buz#frag'); l.absUrl().should.equal('http://example.com:8080/foo?bar=buz#frag'); }); + + it('documents behavior', function () { + var l = new LocationUtil('http://example.com:3000/foo?bar=buz#frag'); + l.url('/user?id=123#name').absUrl().should.equal('http://example.com:3000/user?id=123#name'); + l.path('/entry').absUrl().should.equal('http://example.com:3000/entry?id=123#name'); + l.search('date', '20140401', 'id', null).absUrl().should.equal('http://example.com:3000/entry?date=20140401#name'); + l.hash('').absUrl().should.equal('http://example.com:3000/entry?date=20140401'); + }); });
56efaa7f095ffef29decbb0942f37f24851b4847
js/DataObjectPreviewer.js
js/DataObjectPreviewer.js
(function($) { $.entwine('ss', function($){ $('.ss-gridfield-orderable tbody .handle').entwine({ onmousedown: function () { this.closest('tbody').addClass('ss-gridfield-sorting'); }, onmouseup: function () { this.closest('tbody').removeClass('ss-gridfield-sorting'); } }); $('.dataobjectpreview').entwine({ onadd: function () { var $tr = this.closest('tr'); if ($tr.length && $tr.hasClass('ui-sortable-helper')) { return; } var $iframe = $('<iframe style="width: 100%; overflow: hidden" scrolling="no"></iframe>'); $iframe.bind('load', function () { var iframeWindow = $iframe.get(0).contentWindow, $iframeWindow = $(iframeWindow), iframeBody = iframeWindow.document.body, iframeHeight; $iframeWindow.resize(function () { var newHeight = iframeBody.offsetHeight; if (newHeight !== iframeHeight) { $iframe.height(newHeight + "px"); iframeHeight = newHeight; } }); if ($iframe.is(":visible")) { $iframeWindow.resize(); } }); $iframe.attr('src', this.data('src')); this.append($iframe); } }); }); }(jQuery));
(function($) { function getDocumentHeight(doc) { return Math.max( doc.documentElement.clientHeight, doc.body.scrollHeight, doc.documentElement.scrollHeight, doc.body.offsetHeight, doc.documentElement.offsetHeight); } $.entwine('ss', function($){ $('.ss-gridfield-orderable tbody .handle').entwine({ onmousedown: function () { this.closest('tbody').addClass('ss-gridfield-sorting'); }, onmouseup: function () { this.closest('tbody').removeClass('ss-gridfield-sorting'); } }); $('.dataobjectpreview').entwine({ onadd: function () { var $tr = this.closest('tr'); if ($tr.length && $tr.hasClass('ui-sortable-helper')) { return; } var $iframe = $('<iframe style="width: 100%; overflow: hidden" scrolling="no"></iframe>'); $iframe.bind('load', function () { var iframeWindow = $iframe.get(0).contentWindow, $iframeWindow = $(iframeWindow), iframeHeight; $iframeWindow.resize(function () { var newHeight = getDocumentHeight( iframeWindow.document ); if (newHeight !== iframeHeight) { $iframe.height(newHeight + "px"); iframeHeight = newHeight; } }); if ($iframe.is(":visible")) { $iframeWindow.resize(); } }); $iframe.attr('src', this.data('src')); this.append($iframe); } }); }); }(jQuery));
Use a cross-browser compatible method of determining document height
Use a cross-browser compatible method of determining document height The automatic setting of height for the preview iframe stopped working in Chrome. This change fixes this.
JavaScript
mit
heyday/silverstripe-dataobjectpreview,heyday/silverstripe-dataobjectpreview
--- +++ @@ -1,5 +1,13 @@ (function($) { + + function getDocumentHeight(doc) { + return Math.max( + doc.documentElement.clientHeight, + doc.body.scrollHeight, doc.documentElement.scrollHeight, + doc.body.offsetHeight, doc.documentElement.offsetHeight); + } + $.entwine('ss', function($){ $('.ss-gridfield-orderable tbody .handle').entwine({ onmousedown: function () { @@ -18,11 +26,11 @@ var $iframe = $('<iframe style="width: 100%; overflow: hidden" scrolling="no"></iframe>'); $iframe.bind('load', function () { var iframeWindow = $iframe.get(0).contentWindow, - $iframeWindow = $(iframeWindow), - iframeBody = iframeWindow.document.body, - iframeHeight; + $iframeWindow = $(iframeWindow), + iframeHeight; $iframeWindow.resize(function () { - var newHeight = iframeBody.offsetHeight; + var newHeight = getDocumentHeight( iframeWindow.document ); + if (newHeight !== iframeHeight) { $iframe.height(newHeight + "px"); iframeHeight = newHeight;
cadc76aaac836b8a13fd0c6da5b36b70d8c54ad7
example/examples/HLSSource.js
example/examples/HLSSource.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Hls from 'hls.js'; const propTypes = { src: PropTypes.string.isRequired, type: PropTypes.string, video: PropTypes.object, }; export default class HLSSource extends Component { constructor(props, context) { super(props, context); this.hls = new Hls(); } componentDidMount() { // `src` is the property get from this component // `video` is the property insert from `Video` component // `video` is the html5 video element const { src, video } = this.props; // load hls video source base on hls.js if (Hls.isSupported()) { this.hls.loadSource(src); this.hls.attachMedia(video); this.hls.on(Hls.Events.MANIFEST_PARSED, () => { video.play(); }); } } render() { return ( <source src={this.props.src} type={this.props.type || 'application/x-mpegURL'} /> ); } } HLSSource.propTypes = propTypes;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Hls from 'hls.js'; const propTypes = { src: PropTypes.string.isRequired, type: PropTypes.string, video: PropTypes.object, }; export default class HLSSource extends Component { constructor(props, context) { super(props, context); this.hls = new Hls(); } componentDidMount() { // `src` is the property get from this component // `video` is the property insert from `Video` component // `video` is the html5 video element const { src, video } = this.props; // load hls video source base on hls.js if (Hls.isSupported()) { this.hls.loadSource(src); this.hls.attachMedia(video); this.hls.on(Hls.Events.MANIFEST_PARSED, () => { video.play(); }); } } componentWillUnmount() { // destroy hls video source if (this.hls) { this.hls.destroy(); } } render() { return ( <source src={this.props.src} type={this.props.type || 'application/x-mpegURL'} /> ); } } HLSSource.propTypes = propTypes;
Destroy HLS source before component unmount
Destroy HLS source before component unmount
JavaScript
mit
video-react/video-react,video-react/video-react
--- +++ @@ -29,6 +29,13 @@ } } + componentWillUnmount() { + // destroy hls video source + if (this.hls) { + this.hls.destroy(); + } + } + render() { return ( <source
a60b407bf182c852b9d6e841e1f0511fb770411b
client/templates/course/sidebar/section/add-lesson/add-lesson.js
client/templates/course/sidebar/section/add-lesson/add-lesson.js
Template.sectionAddLesson.events({ 'click .add-lesson-button': function (event, template) { // Get lesson name var lessonName = template.find(".lesson-name").value; // Create temporary lesson object var lessonObject = {'name': lessonName}; // Add lesson to database, // getting lesson ID in return var lessonId = Lessons.insert(lessonObject); if (!this.lessonIDs) { this.lessonIDs = []; } // Add lesson ID to array this.lessonIDs.push(lessonId); // Get course sections array from parent template var courseSections = Template.parentData().sections; // Get course ID from parent template var courseID = Template.parentData()._id; // Save course.lessonIDs array to database Courses.update(courseID, {$set: {"sections": courseSections}}); } });
Template.sectionAddLesson.events({ 'click .add-lesson-button': function (event, template) { // Get lesson name var lessonName = template.find(".lesson-name").value; // Create temporary lesson object var lessonObject = {'name': lessonName}; // Add lesson to database, // getting lesson ID in return var lessonId = Lessons.insert(lessonObject); if (!this.lessonIDs) { this.lessonIDs = []; } // Add lesson ID to array this.lessonIDs.push(lessonId); // Get course sections array from parent template var courseSections = Template.parentData().sections; // Get course ID from parent template var courseID = Template.parentData()._id; // Save course.lessonIDs array to database Courses.update(courseID, {$set: {"sections": courseSections}}); // Clear the lesson name field $(".lesson-name").val(''); } });
Clear lesson field on add.
Clear lesson field on add.
JavaScript
agpl-3.0
Crowducate/crowducate-platform,Crowducate/crowducate-platform,Crowducate/crowducate-next,Crowducate/crowducate-next,KshirsagarNaidu/bodhiprocessor,KshirsagarNaidu/bodhiprocessor
--- +++ @@ -24,5 +24,8 @@ // Save course.lessonIDs array to database Courses.update(courseID, {$set: {"sections": courseSections}}); + + // Clear the lesson name field + $(".lesson-name").val(''); } });
ef773f16dbaf0d2ef922f061d50fb1462c98036b
tests/index.js
tests/index.js
/** * Check If Image Path Exists */ var http = require('http'), url = 'http://sirocco.accuweather.com/adc_images2/english/feature/400x300/worstwx.jpg' ; http.get(url, function(response) { if (response.statusCode == '200') return; throw new Error(response.statusCode); }).on('error', function(error) { throw error; });
/** * Check If Image Path Exists */ var http = require('http'), url = 'http://sirocco.accuweather.com/adc_images2/english/feature/400x300/worstwx.jpg' ; http.get(url, function(response) { if (response.statusCode == '200') process.exit(0); throw new Error(response.statusCode); }).on('error', function(error) { throw error; });
Use process.exit to make test faster
Use process.exit to make test faster
JavaScript
apache-2.0
matthewspencer/worstweather
--- +++ @@ -6,7 +6,7 @@ ; http.get(url, function(response) { - if (response.statusCode == '200') return; + if (response.statusCode == '200') process.exit(0); throw new Error(response.statusCode); }).on('error', function(error) { throw error;
995d2be6e56ba2b2f1b44e1e0f05c56d842da448
src/components/candidatethumbnail/CandidateThumbnail.js
src/components/candidatethumbnail/CandidateThumbnail.js
import React from 'react'; import { Image } from 'react-bootstrap' import CandidateCounter from './CandidateCounter' import styles from './candidatethumbnail.css' export default class CandidateThumbnail extends React.Component { render() { return ( <div className="col-lg-4 col-md-4 col-sm-12 col-xs-12"> <div className="card"> <div className="candidate-card-title"> <h3>{this.props.name}</h3> </div> <div className="candidate-card-divider"></div> <div className="candidate-card-image-link"> <Image className="candidate-card-image" src={this.props.img} responsive/> </div> <div className="candidate-card-counter"> <CandidateCounter counter={this.props.counter}/> </div> </div> </div> ); } }
import React from 'react'; import { Image } from 'react-bootstrap' import { Route } from 'react-router-dom' import CandidateCounter from './CandidateCounter' import styles from './candidatethumbnail.css' export default class CandidateThumbnail extends React.Component { render() { return ( <Route render={({ history}) => ( <div className="col-lg-4 col-md-4 col-sm-12 col-xs-12"> <div className="card" onClick = {() => { history.push('/election/dkijakarta/candidate/'+this.props.name) }}> <div className="candidate-card-title"> <h3>{this.props.name}</h3> </div> <div className="candidate-card-divider"></div> <div className="candidate-card-image-link" > <Image className="candidate-card-image" src={this.props.img} responsive/> </div> <div className="candidate-card-counter"> <CandidateCounter counter={this.props.counter}/> </div> </div> </div> )} /> ); } }
Add link from candidate thumbnail to candidate detail page
Add link from candidate thumbnail to candidate detail page
JavaScript
mit
imrenagi/rojak-web-frontend,imrenagi/rojak-web-frontend
--- +++ @@ -1,5 +1,6 @@ import React from 'react'; import { Image } from 'react-bootstrap' +import { Route } from 'react-router-dom' import CandidateCounter from './CandidateCounter' import styles from './candidatethumbnail.css' @@ -7,22 +8,25 @@ export default class CandidateThumbnail extends React.Component { render() { + return ( - <div className="col-lg-4 col-md-4 col-sm-12 col-xs-12"> - <div className="card"> - <div className="candidate-card-title"> - <h3>{this.props.name}</h3> - </div> - <div className="candidate-card-divider"></div> + <Route render={({ history}) => ( + <div className="col-lg-4 col-md-4 col-sm-12 col-xs-12"> + <div className="card" onClick = {() => { history.push('/election/dkijakarta/candidate/'+this.props.name) }}> + <div className="candidate-card-title"> + <h3>{this.props.name}</h3> + </div> + <div className="candidate-card-divider"></div> - <div className="candidate-card-image-link"> - <Image className="candidate-card-image" src={this.props.img} responsive/> - </div> - <div className="candidate-card-counter"> - <CandidateCounter counter={this.props.counter}/> - </div> + <div className="candidate-card-image-link" > + <Image className="candidate-card-image" src={this.props.img} responsive/> + </div> + <div className="candidate-card-counter"> + <CandidateCounter counter={this.props.counter}/> </div> </div> - ); + </div> + )} /> + ); } }
ed0df4c15952d3b00ca0de3b01cc4697ee6e9570
app/react/data/exclude_images.js
app/react/data/exclude_images.js
module.exports = [ 'https://upload.wikimedia.org/wikipedia/en/e/e7/Cscr-featured.svg', '.webm', 'https://upload.wikimedia.org/wikipedia/en/4/4a/Commons-logo.svg', 'https://upload.wikimedia.org/wikipedia/en/f/fd/Portal-puzzle.svg', 'https://upload.wikimedia.org/wikipedia/en/4/48/Folder_Hexagonal_Icon.svg', 'https://upload.wikimedia.org/wikipedia/commons/a/a8/Office-book.svg', '.tif', 'Commons-logo', 'assets/file-type-icons', '_Icon.svg', 'Question_book-new.svg', 'P_vip.svg', 'Cscr-featured.svg', 'Portal-puzzle.svg', 'Office-book.svg', 'commons/thumb/b/b4/Ambox_important.svg/600px-Ambox_important' ]
module.exports = [ 'https://upload.wikimedia.org/wikipedia/en/e/e7/Cscr-featured.svg', '.webm', 'https://upload.wikimedia.org/wikipedia/en/4/4a/Commons-logo.svg', 'https://upload.wikimedia.org/wikipedia/en/f/fd/Portal-puzzle.svg', 'https://upload.wikimedia.org/wikipedia/en/4/48/Folder_Hexagonal_Icon.svg', 'https://upload.wikimedia.org/wikipedia/commons/a/a8/Office-book.svg', '.tif', 'Commons-logo', 'assets/file-type-icons', '_Icon.svg', 'Question_book-new.svg', 'P_vip.svg', 'Cscr-featured.svg', 'Portal-puzzle.svg', 'Office-book.svg' ]
Revert "Added new exclude image"
Revert "Added new exclude image" This reverts commit cbc4520fcc0b6744113bee40ee21571eb787ea25.
JavaScript
mit
WikiEducationFoundation/Wiki-Playlist,WikiEducationFoundation/Wiki-Playlist,WikiEducationFoundation/Wiki-Playlist
--- +++ @@ -13,6 +13,5 @@ 'P_vip.svg', 'Cscr-featured.svg', 'Portal-puzzle.svg', - 'Office-book.svg', - 'commons/thumb/b/b4/Ambox_important.svg/600px-Ambox_important' + 'Office-book.svg' ]
317f7ca114f80cf2c4d995938b9f262b50fa02fb
app/scenes/SearchScreen/index.js
app/scenes/SearchScreen/index.js
import React, { Component } from 'react'; import { View } from 'react-native'; import RepoSearchBar from './components/RepoSearchBar'; import RepoSearchButton from './components/RepoSearchButton'; import RepoList from './components/RepoList'; export default class SearchScreen extends Component { constructor(props) { super(props); this.state = { username: '', repos: [] }; } render() { return ( <View style={{ flex: 1, flexDirection: 'column', }}> <RepoSearchBar /> <RepoSearchButton /> <RepoList /> </View> ); } }
import React, { Component } from 'react'; import { View } from 'react-native'; import RepoSearchBar from './components/RepoSearchBar'; import RepoSearchButton from './components/RepoSearchButton'; import RepoList from './components/RepoList'; export default class SearchScreen extends Component { constructor(props) { super(props); this.state = { username: '', repos: [] }; } render() { return ( <View style={{ flex: 1, flexDirection: 'column', }}> <RepoSearchBar /> <RepoSearchButton /> <RepoList /> </View> ); } changeUsername(newUsername) { this.setState({ username: newUsername }); } updateRepos(newRepos) { this.setSate({ repos: newRepos }); } }
Add helper functions to change screen states
Add helper functions to change screen states
JavaScript
mit
msanatan/GitHubProjects,msanatan/GitHubProjects,msanatan/GitHubProjects
--- +++ @@ -25,5 +25,17 @@ </View> ); } + + changeUsername(newUsername) { + this.setState({ + username: newUsername + }); + } + + updateRepos(newRepos) { + this.setSate({ + repos: newRepos + }); + } }
4036b9f7009c65aa1889b80ddbb81f2ad95dc873
src/handler_adaptor.js
src/handler_adaptor.js
define(['lib/def', 'handler'], function(Def, Handler) { var HandlerAdaptor = Def.type(Handler, function(handler) { Handler.call(this); this.def_prop('handler', handler); }); HandlerAdaptor.def_method(function on_message(msg, cont) { if (this.handler.match(msg)) return msg.respond(this.handler.execute(msg), cont); return cont(msg); }); return HandlerAdaptor; });
define(['lib/def', 'handler'], function(Def, Handler) { var HandlerAdaptor = Def.type(Handler, function(handler) { this.constructor.__super__.call(this); this.def_prop('handler', handler); }); HandlerAdaptor.def_method(function on_message(msg, cont) { if (this.handler.match(msg)) return msg.respond(this.handler.execute(msg), cont); return cont(msg); }); return HandlerAdaptor; });
Refactor constructor to take advantage of __super__ member.
Refactor constructor to take advantage of __super__ member.
JavaScript
mit
bassettmb/slack-bot-dev
--- +++ @@ -1,7 +1,7 @@ define(['lib/def', 'handler'], function(Def, Handler) { var HandlerAdaptor = Def.type(Handler, function(handler) { - Handler.call(this); + this.constructor.__super__.call(this); this.def_prop('handler', handler); });
2b82c65e398a66d3dc23f0fdf366549e5565219f
src/main/webapp/resources/js/utilities/url-utilities.js
src/main/webapp/resources/js/utilities/url-utilities.js
/** * Since IRIDA can be served within a container, all requests need to have * the correct base url. This will add, if required, the base url. * * NOTE: THIS ONLY NEEDS TO BE CALLED FOR LINKS, ASYNCHRONOUS REQUESTS WILL * BE AUTOMATICALLY HANDLED. * * @param {string} url * @return {string|*} */ export function setBaseUrl(url) { // Remove any leading slashes url = url.replace(/^\/+/, ""); /* Get the base url which is set via the thymeleaf template engine. */ const BASE_URL = window.TL?._BASE_URL || "/"; /* Check to make sure that the given url has not already been given the base url. */ if ( (BASE_URL !== "/" && url.startsWith(BASE_URL)) || url.startsWith("http") ) { return url; } /* Create the new url */ return `${BASE_URL}${url}`; }
/** * Since IRIDA can be served within a container, all requests need to have * the correct base url. This will add, if required, the base url. * * NOTE: THIS ONLY NEEDS TO BE CALLED FOR LINKS, ASYNCHRONOUS REQUESTS WILL * BE AUTOMATICALLY HANDLED. * * @param {string} url * @return {string|*} */ export function setBaseUrl(url) { /* Get the base url which is set via the thymeleaf template engine. */ const BASE_URL = window.TL?._BASE_URL || "/"; /* Check to make sure that the given url has not already been given the base url. */ if (url.startsWith(BASE_URL) || url.startsWith("http")) { return url; } // Remove any leading slashes url = url.replace(/^\/+/, ""); /* Create the new url */ return `${BASE_URL}${url}`; }
Check to see if the url has the context path first.
Check to see if the url has the context path first.
JavaScript
apache-2.0
phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida
--- +++ @@ -9,23 +9,22 @@ * @return {string|*} */ export function setBaseUrl(url) { - // Remove any leading slashes - url = url.replace(/^\/+/, ""); - /* Get the base url which is set via the thymeleaf template engine. */ const BASE_URL = window.TL?._BASE_URL || "/"; + /* Check to make sure that the given url has not already been given the base url. */ - if ( - (BASE_URL !== "/" && url.startsWith(BASE_URL)) || - url.startsWith("http") - ) { + if (url.startsWith(BASE_URL) || url.startsWith("http")) { return url; } + + // Remove any leading slashes + url = url.replace(/^\/+/, ""); + /* Create the new url */
ff2bb7a079a88eb9a60061de9f4481cee1141889
spec/specs.js
spec/specs.js
describe('pingPong', function() { it("is true for a number that is divisible by 3", function() { expect(pingPong(6)).to.equal(true); }); it("is true for a number that is divisible by 5", function() { expect(pingPong(10)).to.equal(true); }); });
describe('pingPong', function() { it("is true for a number that is divisible by 3", function() { expect(pingPong(6)).to.equal(true); }); it("is true for a number that is divisible by 5", function() { expect(pingPong(10)).to.equal(true); }); it("is true for a number that is divisible by 15", function() { expect(pingPong(30)).to.equal.(true); }); });
Add an additional spec test for userNumbers divisible by 15
Add an additional spec test for userNumbers divisible by 15
JavaScript
mit
kcmdouglas/pingpong,kcmdouglas/pingpong
--- +++ @@ -7,4 +7,8 @@ expect(pingPong(10)).to.equal(true); }); + it("is true for a number that is divisible by 15", function() { + expect(pingPong(30)).to.equal.(true); + }); + });
1dde5df3c6fdfe555f7258d1a697735bc6f3b7a8
src/App.js
src/App.js
import React from 'react'; import { HashRouter as Router, Switch, Route, Link } from "react-router-dom"; import ComponentsPage from './pages/Components'; import ContentPage from './pages/Content'; import UtilsPage from './pages/Utils'; function App() { return ( <Router> <div className="p-5"> <h1>Gateway</h1> <p>Gateway is Findaway's boilerplate for React sites/applications.</p> <p>This repository can be copied to start any react project.</p> <p>By default this repository contains CSS (SCSS), React Components, and utilities to help get any project up-and-running quickly with consistency to all other projects.</p> <ul className="list-inline"> <li><Link to="content">Content</Link></li> <li><Link to="components">Components</Link></li> <li><Link to="utils">Utils</Link></li> </ul> <Switch> <Route path="/components"> <ComponentsPage /> </Route> <Route path="/content"> <ContentPage /> </Route> <Route path="/utils"> <UtilsPage /> </Route> </Switch> </div> </Router> ); } export default App;
import React from 'react'; import { HashRouter as Router, Switch, Route, Link } from "react-router-dom"; import ComponentsPage from './pages/Components'; import ContentPage from './pages/Content'; import UtilsPage from './pages/Utils'; function App() { return ( <Router> <div className="p-5"> <h1>Gateway</h1> <p>Gateway is Findaway's boilerplate for React sites/applications.</p> <p>This repository can be copied to start any react project. Get the latest from <a href="https://github.com/FindawayWorld/gateway">https://github.com/FindawayWorld/gateway</a></p> <p>By default this repository contains CSS (SCSS), React Components, and utilities to help get any project up-and-running quickly with consistency to all other projects.</p> <p></p> <ul className="list-inline"> <li><Link to="content">Content</Link></li> <li><Link to="components">Components</Link></li> <li><Link to="utils">Utils</Link></li> </ul> <Switch> <Route path="/components"> <ComponentsPage /> </Route> <Route path="/content"> <ContentPage /> </Route> <Route path="/utils"> <UtilsPage /> </Route> </Switch> </div> </Router> ); } export default App;
Add link to GH repo
Add link to GH repo
JavaScript
mit
FindawayWorld/gateway,FindawayWorld/gateway
--- +++ @@ -16,8 +16,9 @@ <div className="p-5"> <h1>Gateway</h1> <p>Gateway is Findaway's boilerplate for React sites/applications.</p> - <p>This repository can be copied to start any react project.</p> + <p>This repository can be copied to start any react project. Get the latest from <a href="https://github.com/FindawayWorld/gateway">https://github.com/FindawayWorld/gateway</a></p> <p>By default this repository contains CSS (SCSS), React Components, and utilities to help get any project up-and-running quickly with consistency to all other projects.</p> + <p></p> <ul className="list-inline"> <li><Link to="content">Content</Link></li>
3a6dafd545da6f7ccb271915eb1b9a5f76cfe277
src/App.js
src/App.js
import React from 'react'; import { BrowserRouter, Match, Miss } from 'react-router' import Header from './components/Header'; import CTA from './components/CTA'; import Footer from './components/Footer'; import routes from './config/routes'; import FourOhFour from './components/404'; const App = () => ( // <BrowserRouter history={history}> <BrowserRouter> <div> <Header /> { routes.map((route, index) => ( // rendering `Match`s with different // components but the same pattern as before <Match // FIXME: index as key key={index} pattern={route.pattern} // component={route.main} render={matchProps => { const Component = route.main; // TODO: double check where to put scrolling window.scroll(0, 0); return ( <div className="content"> <Component {...matchProps} /> <CTA matchProps={matchProps} /> </div> ); }} exactly={route.exactly} /> )) } <Miss component={FourOhFour} /> <Footer /> </div> </BrowserRouter> ); export default App;
import React from 'react'; import { BrowserRouter, Match, Miss } from 'react-router' import Header from './components/Header'; import CTA from './components/CTA'; import Footer from './components/Footer'; import routes from './config/routes'; import FourOhFour from './components/404'; const App = () => ( // <BrowserRouter history={history}> <BrowserRouter> <div> <Header /> { routes.map((route, index) => ( // rendering `Match`s with different // components but the same pattern as before <Match key={route.pattern} pattern={route.pattern} // component={route.main} render={matchProps => { const Component = route.main; // TODO: double check where to put scrolling window.scroll(0, 0); return ( <div className="content"> <Component {...matchProps} /> <CTA matchProps={matchProps} /> </div> ); }} exactly={route.exactly} /> )) } <Miss component={FourOhFour} /> <Footer /> </div> </BrowserRouter> ); export default App;
Fix index as key anti pattern
Fix index as key anti pattern
JavaScript
mit
emyarod/afw,emyarod/afw
--- +++ @@ -16,8 +16,7 @@ // rendering `Match`s with different // components but the same pattern as before <Match - // FIXME: index as key - key={index} + key={route.pattern} pattern={route.pattern} // component={route.main} render={matchProps => {
1ebfc2f9d228811b45955e1d7ddd1f61407a3809
src/App.js
src/App.js
import React from 'react'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import Home from './Home'; const App = () => ( <React.Fragment> <Router> <Route exact path="/" component={Home} /> </Router> </React.Fragment> ); export default App;
import React from 'react'; import CssBaseline from '@material-ui/core/CssBaseline'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import Home from './Home'; const App = () => ( <React.Fragment> <CssBaseline /> <Router> <Route exact path="/" component={Home} /> </Router> </React.Fragment> ); export default App;
Use CssNormalize to normalize padding/margin for entire app
Use CssNormalize to normalize padding/margin for entire app
JavaScript
mit
jasongforbes/jforbes.io,jasongforbes/jforbes.io,jasongforbes/jforbes.io
--- +++ @@ -1,9 +1,11 @@ import React from 'react'; +import CssBaseline from '@material-ui/core/CssBaseline'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import Home from './Home'; const App = () => ( <React.Fragment> + <CssBaseline /> <Router> <Route exact path="/" component={Home} /> </Router>
22d63bf978e351a22515248600a8cd7a1d56a07d
src/pages/home/page.js
src/pages/home/page.js
import React from 'react'; import ReactDom from 'react-dom'; import { Link } from 'react-router'; import _ from 'lodash'; import client from '../../common/store/Contentful'; import marked from 'marked'; import styles from "./style.css"; export default class HomePage extends React.Component { constructor(props) { super(props); var self = this; this.state = { fonts: this.props.fontStore.fonts, content: '' }; client.getEntries({ 'content_type': 'page', 'fields.title': 'Home' }) .then(function (entries) { var content = _.get(entries, 'items[0].fields.content'); console.log(content) self.setState({ content }); }) .catch(function(error) { console.error(error); }); } render() { var fontItems = _.map(this.state.fonts, function(font, index) { var link = '/karaoke/' + font.name; return ( <li key={ index } style={{ backgroundColor: font.color }}> <Link to={ link }> <p>{ font.name }</p> </Link> </li> ); }); return ( <div id="content"> <ul className={ styles.directory }> { fontItems } </ul> <div className={ styles['page-content'] } dangerouslySetInnerHTML={{__html: marked(this.state.content)}}> </div> </div> ); } }
import React from 'react'; import ReactDom from 'react-dom'; import { Link } from 'react-router'; import _ from 'lodash'; import client from '../../common/store/Contentful'; import marked from 'marked'; import styles from "./style.css"; export default class HomePage extends React.Component { constructor(props) { super(props); var self = this; this.state = { fonts: this.props.fontStore.fonts, content: '' }; client.getEntries({ 'content_type': 'page', 'fields.title': 'Home' }) .then(function (entries) { var content = _.get(entries, 'items[0].fields.content'); self.setState({ content }); }) .catch(function(error) { console.error(error); }); } render() { var fontItems = _.map(this.state.fonts, function(font, index) { var link = '/karaoke/' + font.name; return ( <li key={ index } style={{ backgroundColor: font.color }}> <Link to={ link }> <p>{ font.name }</p> </Link> </li> ); }); return ( <div id="content"> <ul className={ styles.directory }> { fontItems } </ul> <div className={ styles['page-content'] } dangerouslySetInnerHTML={{__html: marked(this.state.content)}}> </div> </div> ); } }
Remove my dumb logging statement
Remove my dumb logging statement
JavaScript
mit
mhgbrown/typography-karaoke,mhgbrown/typography-karaoke
--- +++ @@ -23,9 +23,7 @@ 'fields.title': 'Home' }) .then(function (entries) { - var content = _.get(entries, 'items[0].fields.content'); - console.log(content) self.setState({ content }); }) .catch(function(error) {
1f79c994d96907273b45b36fe1cbf06340e71c41
src/cli.js
src/cli.js
#!/usr/bin/env node import yargs from 'yargs'; import path from 'path'; import fs from 'fs'; import * as pose from '.'; import actions from './actions'; const opts = yargs .usage('$ pose <action> [options]') .help('help') .epilog(actions.trim()) .options({ name: { alias: ['as'], default: path.basename(process.cwd()), desc: 'Name of template', }, entry: { alias: ['e'], default: process.cwd(), defaultDescription: 'cwd', desc: 'Entry of template', }, help: { alias: ['h'], }, }).argv; const action = opts._[0]; if (!action) { console.log('Type "pose help" to get started.'); process.exit(); } [ opts._pose = path.join(process.env.HOME, '.pose'), opts._templates = path.join(opts._pose, 'templates'), ].forEach(dir => { fs.mkdir(dir, () => null); }); if (typeof pose[action] === 'function') { pose[action](opts); } else { console.error(`Unknown action "${action}"`); } export { action, opts };
#!/usr/bin/env node import yargs from 'yargs'; import path from 'path'; import fs from 'fs'; import * as pose from '.'; import actions from './actions'; const opts = yargs .usage('$ pose <action> [options]') .help('help') .epilog(actions.trim()) .options({ name: { alias: ['as'], default: path.basename(process.cwd()), desc: 'Name of template', }, entry: { alias: ['from'], default: process.cwd(), defaultDescription: 'cwd', desc: 'Entry of template', }, help: { alias: ['h'], }, }).argv; const action = opts._[0]; if (!action) { console.log('Type "pose help" to get started.'); process.exit(); } [ opts._pose = path.join(process.env.HOME, '.pose'), opts._templates = path.join(opts._pose, 'templates'), ].forEach(dir => { fs.mkdir(dir, () => null); }); if (typeof pose[action] === 'function') { pose[action](opts); } else { console.error(`Unknown action "${action}"`); } export { action, opts };
Remove -e in favor of --from
Remove -e in favor of --from
JavaScript
mit
seanc/pose
--- +++ @@ -18,7 +18,7 @@ }, entry: { - alias: ['e'], + alias: ['from'], default: process.cwd(), defaultDescription: 'cwd', desc: 'Entry of template',
5d3474ab83dcf9931ee480fbe7d1119642e7355f
test/conf/karma-sauce.conf.js
test/conf/karma-sauce.conf.js
module.exports = function(config) { var commonConfig = (require("./karma-common.conf"))(config); var customLaunchers = { sl_chrome: { base: "SauceLabs", browserName: "chrome", platform: "Windows 8.1" }, sl_firefox: { base: "SauceLabs", browserName: "firefox", platform: "Windows 8.1" }, sl_safari: { base: "SauceLabs", browserName: "safari", platform: "OS X 10.10" }, sl_ie_11: { base: "SauceLabs", browserName: "internet explorer", platform: "Windows 8.1" } }; var options = { reporters: ["verbose", "saucelabs"], sauceLabs: { testName: "Vivliostyle.js", recordScreenshots: false, startConnect: false, // Sauce Connect is started by Travis CI tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER }, captureTimeout: 120000, customLaunchers: customLaunchers, browsers: Object.keys(customLaunchers), singleRun: true }; for (var key in commonConfig) { if (commonConfig.hasOwnProperty(key)) { options[key] = commonConfig[key]; } } config.set(options); };
module.exports = function(config) { var commonConfig = (require("./karma-common.conf"))(config); var customLaunchers = { sl_chrome: { base: "SauceLabs", browserName: "chrome", platform: "Windows 8.1" }, sl_firefox: { base: "SauceLabs", browserName: "firefox", platform: "Windows 8.1", version: "beta" }, sl_safari: { base: "SauceLabs", browserName: "safari", platform: "OS X 10.10" }, sl_ie_11: { base: "SauceLabs", browserName: "internet explorer", platform: "Windows 8.1" } }; var options = { reporters: ["verbose", "saucelabs"], sauceLabs: { testName: "Vivliostyle.js", recordScreenshots: false, startConnect: false, // Sauce Connect is started by Travis CI tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER }, captureTimeout: 120000, customLaunchers: customLaunchers, browsers: Object.keys(customLaunchers), singleRun: true }; for (var key in commonConfig) { if (commonConfig.hasOwnProperty(key)) { options[key] = commonConfig[key]; } } config.set(options); };
Use beta version of Firefox (supports vertical writing-mode) in tests on Sauce Labs
Use beta version of Firefox (supports vertical writing-mode) in tests on Sauce Labs
JavaScript
apache-2.0
kuad9/vivliostyle.js_study,vivliostyle/vivliostyle.js,nulltask/vivliostyle.js,vivliostyle/vivliostyle.js,kuad9/vivliostyle.js_study,vivliostyle/vivliostyle.js,nulltask/vivliostyle.js,kuad9/vivliostyle.js_study,nulltask/vivliostyle.js,vivliostyle/vivliostyle.js,kuad9/vivliostyle.js_study,nulltask/vivliostyle.js
--- +++ @@ -9,7 +9,8 @@ sl_firefox: { base: "SauceLabs", browserName: "firefox", - platform: "Windows 8.1" + platform: "Windows 8.1", + version: "beta" }, sl_safari: { base: "SauceLabs",
8e4e5ef743051f64d41e6e3e027faf6daaf10b89
test/showdir-href-encoding.js
test/showdir-href-encoding.js
var test = require('tap').test, ecstatic = require('../lib/ecstatic'), http = require('http'), request = require('request'), path = require('path'); var root = __dirname + '/public', baseDir = 'base'; test('url encoding in href', function (t) { var port = Math.floor(Math.random() * ((1<<16) - 1e4) + 1e4); var uri = 'http://localhost:' + port + path.join('/', baseDir, 'show-dir-href-encoding'); var server = http.createServer( ecstatic({ root: root, baseDir: baseDir, showDir: true, autoIndex: false }) ); server.listen(port, function () { request.get({ uri: uri }, function(err, res, body) { t.match(body, /href="\/base\/show\-dir\-href\-encoding\/aname\+aplus\.txt"/, 'We found the right href'); server.close(); t.end(); }); }); });
var test = require('tap').test, ecstatic = require('../lib/ecstatic'), http = require('http'), request = require('request'), path = require('path'); var root = __dirname + '/public', baseDir = 'base'; test('url encoding in href', function (t) { var port = Math.floor(Math.random() * ((1<<16) - 1e4) + 1e4); var uri = 'http://localhost:' + port + path.join('/', baseDir, 'show-dir-href-encoding'); var server = http.createServer( ecstatic({ root: root, baseDir: baseDir, showDir: true, autoIndex: false }) ); server.listen(port, function () { request.get({ uri: uri }, function(err, res, body) { t.match(body, /href="\/base\/show\-dir\-href\-encoding\/aname%2Baplus\.txt"/, 'We found the right href'); server.close(); t.end(); }); }); });
Fix test broken by encodeURIComponent change
Fix test broken by encodeURIComponent change
JavaScript
mit
mk-pmb/node-ecstatic,krikx/node-ecstatic,mk-pmb/node-ecstatic,jfhbrook/node-ecstatic,dotnetCarpenter/node-ecstatic,mk-pmb/node-ecstatic,dotnetCarpenter/node-ecstatic,krikx/node-ecstatic,dotnetCarpenter/node-ecstatic,ngs/node-ecstatic,jfhbrook/node-ecstatic,ngs/node-ecstatic,jfhbrook/node-ecstatic
--- +++ @@ -25,7 +25,7 @@ request.get({ uri: uri }, function(err, res, body) { - t.match(body, /href="\/base\/show\-dir\-href\-encoding\/aname\+aplus\.txt"/, 'We found the right href'); + t.match(body, /href="\/base\/show\-dir\-href\-encoding\/aname%2Baplus\.txt"/, 'We found the right href'); server.close(); t.end(); });
f4c10acf35c802049cb59fec2af813766821c83f
src/String.js
src/String.js
/** * Has Vowels * * hasVowel tests if the String calling the function has a vowels * * @param {void} * @return {Boolean} returns true or false indicating if the string * has a vowel or not */ String.prototype.hasVowels = function() { var inputString = this; return /[aeiou]/gi.test(inputString); }; /** * To Upper * * toUpper converts its calling string to all uppercase characters * * @param {void} * @return {String} returns an upperCase version of the calling string */ String.prototype.toUpper = function() { // the 'this' keyword represents the string calling the function return this.replace(/[a-z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)-32); }); }; String.prototype.toLower = function() { // the 'this' keyword represents the string calling the function return this.replace(/[A-Z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)+32); }); }; /** * Uc First * * ucFirst capitalises the first character of its calling string * * @param {void} * @return {String} returns the calling string with the first character * capitalised */ String.prototype.ucFirst = function() { return ''; };
/** * Has Vowels * * hasVowel tests if the String calling the function has a vowels * * @param {void} * @return {Boolean} returns true or false indicating if the string * has a vowel or not */ String.prototype.hasVowels = function() { var inputString = this; return /[aeiou]/gi.test(inputString); }; /** * To Upper * * toUpper converts its calling string to all uppercase characters * * @param {void} * @return {String} returns an upperCase version of the calling string */ String.prototype.toUpper = function() { // the 'this' keyword represents the string calling the function return this.replace(/[a-z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)-32); }); }; String.prototype.toLower = function() { // the 'this' keyword represents the string calling the function return this.replace(/[A-Z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)+32); }); }; /** * Uc First * * ucFirst capitalises the first character of its calling string * * @param {void} * @return {String} returns the calling string with the first character * capitalised */ String.prototype.ucFirst = function() { return this.replace(/^[a-z]/g, function(item, position, string) { return item.toUpper(); }); };
Implement ucFirst() to pass test
Implement ucFirst() to pass test
JavaScript
mit
andela-oolutola/string-class,andela-oolutola/string-class
--- +++ @@ -44,5 +44,7 @@ * capitalised */ String.prototype.ucFirst = function() { - return ''; + return this.replace(/^[a-z]/g, function(item, position, string) { + return item.toUpper(); + }); };
242dff01801b14ea10df218d0d967e9afef2b144
app/assets/javascripts/displayMap.js
app/assets/javascripts/displayMap.js
function initMap() { var map; var $business_object; var biz_loc_collection; var i; $business_object = $('#businesses').data('url'); biz_loc_collection = []; for (i = 0; i < $business_object.length; ++i) { biz_loc_collection.push({ lat: $business_object[i].latitude, lng: $business_object[i].longitude}); } map = new google.maps.Map(document.getElementById('map-canvas'), { center: {lat: 47.6062, lng: -122.3321}, // center: should be the lat and long of leading biz zoom: 12 }); for (i = 0; i < biz_loc_collection.length; ++i) { marker = new google.maps.Marker({ map: map, draggable: false, animation: google.maps.Animation.DROP, position: biz_loc_collection[i] }); marker.addListener('click', toggleBounce); } function toggleBounce() { if (marker.getAnimation() !== null) { marker.setAnimation(null); } else { marker.setAnimation(google.maps.Animation.BOUNCE); } } }
function initMap() { var map; var $business_object; var biz_loc_collection; var i; $business_object = $('#businesses').data('url'); biz_loc_collection = []; for (i = 0; i < $business_object.length; ++i) { biz_loc_collection.push({ lat: $business_object[i].latitude, lng: $business_object[i].longitude}); } map = new google.maps.Map(document.getElementById('map-canvas'), { center: {lat: 47.6062, lng: -122.3321}, // center: should be the lat and long of leading biz zoom: 12 }); biz_loc_collection.forEach(addMarker); function addMarker(business){ var marker; marker = new google.maps.Marker({ map: map, draggable: false, animation: google.maps.Animation.DROP, position: business }); marker.addListener('click', toggleBounce); } function toggleBounce() { var marker; marker = this; if (marker.getAnimation() !== null) { marker.setAnimation(null); } else { marker.setAnimation(google.maps.Animation.BOUNCE); setTimeout(function(){ marker.setAnimation(null); }, 750); } } }
Fix the marker bouncing function.
Fix the marker bouncing function.
JavaScript
mit
DBC-Huskies/flight-app,DBC-Huskies/flight-app,DBC-Huskies/flight-app
--- +++ @@ -16,21 +16,30 @@ zoom: 12 }); - for (i = 0; i < biz_loc_collection.length; ++i) { - marker = new google.maps.Marker({ + biz_loc_collection.forEach(addMarker); + + function addMarker(business){ + var marker; + marker = new google.maps.Marker({ map: map, draggable: false, animation: google.maps.Animation.DROP, - position: biz_loc_collection[i] + position: business }); + marker.addListener('click', toggleBounce); } function toggleBounce() { - if (marker.getAnimation() !== null) { - marker.setAnimation(null); - } else { - marker.setAnimation(google.maps.Animation.BOUNCE); - } - } + var marker; + marker = this; + + if (marker.getAnimation() !== null) { + marker.setAnimation(null); + } else { + marker.setAnimation(google.maps.Animation.BOUNCE); + setTimeout(function(){ marker.setAnimation(null); }, 750); + } + } + }
a59413dc688077d0f1c4d8ae26fce464b837faa6
src/scripts/scripts.js
src/scripts/scripts.js
$(document).foundation(); $('a.disabled').click(function(e) { e.preventDefault(); }); // Show shadow when content slides under the page header $(document).ready(function() { var $content = $('#site-body .content'); var $header = $('#page-head .inner'); if ($header.length > 0) { $content.css('margin-top', $header.outerHeight()); $(document).resize(function() { $content.css('margin-top', $header.outerHeight()); }); $(window).scroll(function() { if($(this).scrollTop() > 0) { $header.addClass('overlay'); } else { $header.removeClass('overlay'); } }); } });
$(document).foundation(); $('a.disabled').click(function(e) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); }); // Show shadow when content slides under the page header $(document).ready(function() { var $content = $('#site-body .content'); var $header = $('#page-head .inner'); if ($header.length > 0) { $content.css('margin-top', $header.outerHeight()); $(document).resize(function() { $content.css('margin-top', $header.outerHeight()); }); $(window).scroll(function() { if($(this).scrollTop() > 0) { $header.addClass('overlay'); } else { $header.removeClass('overlay'); } }); } // ================================================================ // Fake form submits and confirmation buttons. // // To create a confirmation button add ( data-confirm-action="message" ) // to the button. This will trigger a confirmation box. If the answer // is affirmative the button action will fire. // // For fake submit buttons add ( data-trigger-submit="id" ) and replace // id with the id of the submit button. // ================================================================ $('[data-confirm-action]').click(function(e) { var message = $(this).attr('data-confirm-action'); var confirm = window.confirm(message); if (!confirm) { e.preventDefault(); e.stopImmediatePropagation(); } }); $('[data-trigger-submit]').click(function(e) { e.preventDefault(); var id = $(this).attr('data-trigger-submit'); $('#' + id).click(); }); });
Implement fake form submits and confirmation buttons
Implement fake form submits and confirmation buttons
JavaScript
bsd-3-clause
flipside-org/aw-datacollection,flipside-org/aw-datacollection,flipside-org/aw-datacollection
--- +++ @@ -2,6 +2,8 @@ $('a.disabled').click(function(e) { e.preventDefault(); + e.stopPropagation(); + e.stopImmediatePropagation(); }); @@ -27,5 +29,29 @@ }); } + // ================================================================ + // Fake form submits and confirmation buttons. + // + // To create a confirmation button add ( data-confirm-action="message" ) + // to the button. This will trigger a confirmation box. If the answer + // is affirmative the button action will fire. + // + // For fake submit buttons add ( data-trigger-submit="id" ) and replace + // id with the id of the submit button. + // ================================================================ + + $('[data-confirm-action]').click(function(e) { + var message = $(this).attr('data-confirm-action'); + var confirm = window.confirm(message); + if (!confirm) { + e.preventDefault(); + e.stopImmediatePropagation(); + } + }); + + $('[data-trigger-submit]').click(function(e) { + e.preventDefault(); + var id = $(this).attr('data-trigger-submit'); + $('#' + id).click(); + }); }); -
8dc0bd8327a0acef05a611fa57a7b256951db69f
lib/util/spawn-promise.js
lib/util/spawn-promise.js
'use babel' import {getPath} from 'consistent-path' import {BufferedProcess} from 'atom' export default (command, args, cwd = null) => new Promise((resolve, reject) => { let output = null const stdout = (_output) => output = _output const exit = (code) => { if (code !== 0) { reject(new Error('Exit status ' + code)) } else { resolve(output) } } const env = Object.assign({}, {path: getPath()}, process.env) const options = {cwd, env} /* eslint no-new: 0 */ new BufferedProcess({command, args, options, stdout, exit}) })
'use babel' import getPath from 'consistent-path' import {BufferedProcess} from 'atom' export default (command, args, cwd = null) => new Promise((resolve, reject) => { let output = null const stdout = (_output) => output = _output const exit = (code) => { if (code !== 0) { reject(new Error('Exit status ' + code)) } else { resolve(output) } } const env = Object.assign({}, {path: getPath()}, process.env) const options = {cwd, env} /* eslint no-new: 0 */ new BufferedProcess({command, args, options, stdout, exit}) })
Update consistent-path import for 2.x
Update consistent-path import for 2.x
JavaScript
mit
timdp/atom-npm-helper
--- +++ @@ -1,6 +1,6 @@ 'use babel' -import {getPath} from 'consistent-path' +import getPath from 'consistent-path' import {BufferedProcess} from 'atom' export default (command, args, cwd = null) => new Promise((resolve, reject) => {
ba8371191ca468d1648e83324455d24a314725f8
src/portal.js
src/portal.js
import { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDom from 'react-dom'; class Portal extends Component { componentWillMount() { this.popup = document.createElement('div'); document.body.appendChild(this.popup); this.renderLayer(); } componentDidUpdate() { this.renderLayer(); } componentWillUnmount() { ReactDom.unmountComponentAtNode(this.popup); document.body.removeChild(this.popup); } renderLayer() { ReactDom.unstable_renderSubtreeIntoContainer(this, this.props.children, this.popup); } render() { return null; } } Portal.propTypes = { children: PropTypes.node, // eslint-disable-line }; export default Portal;
import { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDom from 'react-dom'; const useCreatePortal = typeof ReactDom.unstable_createPortal === 'function'; class Portal extends Component { componentWillMount() { this.popup = document.createElement('div'); document.body.appendChild(this.popup); this.renderLayer(); } componentDidUpdate() { this.renderLayer(); } componentWillUnmount() { if (!useCreatePortal) { ReactDom.unmountComponentAtNode(this.popup); } document.body.removeChild(this.popup); } renderLayer() { if (!useCreatePortal) { ReactDom.unstable_renderSubtreeIntoContainer(this, this.props.children, this.popup); } } render() { if (useCreatePortal) { return ReactDom.unstable_createPortal(this.props.children, this.popup); } return null; } } Portal.propTypes = { children: PropTypes.node, // eslint-disable-line }; export default Portal;
Add support for new React Core (v16)
Add support for new React Core (v16) Old react (v15) still working
JavaScript
mit
pradel/react-minimalist-portal
--- +++ @@ -1,6 +1,8 @@ import { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDom from 'react-dom'; + +const useCreatePortal = typeof ReactDom.unstable_createPortal === 'function'; class Portal extends Component { componentWillMount() { @@ -14,15 +16,22 @@ } componentWillUnmount() { - ReactDom.unmountComponentAtNode(this.popup); + if (!useCreatePortal) { + ReactDom.unmountComponentAtNode(this.popup); + } document.body.removeChild(this.popup); } renderLayer() { - ReactDom.unstable_renderSubtreeIntoContainer(this, this.props.children, this.popup); + if (!useCreatePortal) { + ReactDom.unstable_renderSubtreeIntoContainer(this, this.props.children, this.popup); + } } render() { + if (useCreatePortal) { + return ReactDom.unstable_createPortal(this.props.children, this.popup); + } return null; } }
9cadbca18e044b0b20b7a3316c7007eb1540711b
test/builder/graphql/query.js
test/builder/graphql/query.js
import {parse, Source} from 'graphql'; import {createSpecBuilderClass} from './base'; import {RepositoryBuilder} from './repository'; import {PullRequestBuilder} from './pr'; class SearchResultItemBuilder { static resolve() { return this; } constructor(...args) { this.args = args; this._value = null; } bePullRequest(block = () => {}) { const b = new PullRequestBuilder(...this.args); block(b); this._value = b.build(); } build() { return this._value; } } const SearchResultBuilder = createSpecBuilderClass('SearchResultItemConnection', { issueCount: {default: 0}, nodes: {linked: SearchResultItemBuilder, plural: true, singularName: 'node'}, }); const QueryBuilder = createSpecBuilderClass('Query', { repository: {linked: RepositoryBuilder}, search: {linked: SearchResultBuilder}, }); export function queryBuilder(...nodes) { return QueryBuilder.onFragmentQuery(nodes); } class RelayResponseBuilder extends QueryBuilder { static onOperation(op) { const doc = parse(new Source(op.text)); return this.onFullQuery(doc); } build() { return {data: super.build()}; } } export function relayResponseBuilder(op) { return RelayResponseBuilder.onOperation(op); }
import {parse, Source} from 'graphql'; import {createSpecBuilderClass} from './base'; import {RepositoryBuilder} from './repository'; import {PullRequestBuilder} from './pr'; class SearchResultItemBuilder { static resolve() { return this; } constructor(...args) { this.args = args; this._value = null; } bePullRequest(block = () => {}) { const b = new PullRequestBuilder(...this.args); block(b); this._value = b.build(); } build() { return this._value; } } const SearchResultBuilder = createSpecBuilderClass('SearchResultItemConnection', { issueCount: {default: 0}, nodes: {linked: SearchResultItemBuilder, plural: true, singularName: 'node'}, }); const QueryBuilder = createSpecBuilderClass('Query', { repository: {linked: RepositoryBuilder}, search: {linked: SearchResultBuilder}, }); export function queryBuilder(...nodes) { return QueryBuilder.onFragmentQuery(nodes); } class RelayResponseBuilder extends QueryBuilder { static onOperation(op) { const doc = parse(new Source(op.text)); return this.onFullQuery(doc); } constructor(...args) { super(...args); this._errors = []; } addError(string) { this._errors.push(string); return this; } build() { if (this._errors.length > 0) { return {data: null, errors: this._errors}; } return {data: super.build()}; } } export function relayResponseBuilder(op) { return RelayResponseBuilder.onOperation(op); }
Build a GraphQL response with errors reported
Build a GraphQL response with errors reported
JavaScript
mit
atom/github,atom/github,atom/github
--- +++ @@ -44,7 +44,22 @@ return this.onFullQuery(doc); } + constructor(...args) { + super(...args); + + this._errors = []; + } + + addError(string) { + this._errors.push(string); + return this; + } + build() { + if (this._errors.length > 0) { + return {data: null, errors: this._errors}; + } + return {data: super.build()}; } }
ab050e711d90495e23b8b887df2a3dc58dae6ba3
app/src/App.test.js
app/src/App.test.js
import React from 'react'; import { mount, shallow } from 'enzyme'; import App from './App'; import TimeTable from 'timetablescreen'; describe('App', () => { beforeEach( () => { Object.defineProperty(window.location, 'href', { writable: true, value: 'localhost:3000/kara' }); }); it('renders without crashing', () => { shallow(<App />); }); it('shows error when state is updated to error', () => { const component = mount(<App />); component.setState({data: { error: 'error' }}); expect(component.find('.cs-error')).toHaveLength(1); }); it('shows timetable when state is updated to valid state', () => { const component = shallow(<App />); component.setState({data: {lat: 0, lon:0}}); component.update(); expect(component.find(TimeTable)).toHaveLength(1); }); });
import React from 'react'; import { mount, shallow } from 'enzyme'; import App from './App'; import TimeTable from 'timetablescreen'; describe('App', () => { beforeEach( () => { Object.defineProperty(window.location, 'href', { writable: true, value: 'localhost:3000/kara' }); }); it('renders without crashing', () => { shallow(<App />); }); it('shows error when state is updated to error', () => { const component = mount(<App />); component.setState({data: { error: 'error' }}); expect(component.find('.cs-error')).toBeTruthy(); // TODO: Add error prefix and use toHaveLenght }); it('shows timetable when state is updated to valid state', () => { const component = shallow(<App />); component.setState({data: {lat: 0, lon:0}}); component.update(); expect(component.find(TimeTable)).toHaveLength(1); }); });
Test that there are errors instead of exact number
Test that there are errors instead of exact number
JavaScript
mit
kangasta/timetablescreen,kangasta/timetablescreen
--- +++ @@ -20,7 +20,7 @@ component.setState({data: { error: 'error' }}); - expect(component.find('.cs-error')).toHaveLength(1); + expect(component.find('.cs-error')).toBeTruthy(); // TODO: Add error prefix and use toHaveLenght }); it('shows timetable when state is updated to valid state', () => { const component = shallow(<App />);
2561471eea20a9d1ca762d402ba538661cfd2f64
module/Connector.js
module/Connector.js
const mysql = require('mysql') const qBuilder = require('./QueryBuilder') let query = '' let params = [] module.exports = (dbSetting) => { let connection = mysql.createConnection({ host: dbSetting.hostname, user: dbSetting.username, password: dbSetting.password, database: dbSetting.database }) connection.connect() return { makeQuery: () => { return qBuilder }, prepare: () => { query = qBuilder.prepare() }, setParameters: (params) => { qBuilder.setParameters(params) }, getParameters: () => { params = qBuilder.getParameters() }, execute: () => { // connection.query(query) }, get: () => { } } }
const mysql = require('mysql') const qBuilder = require('./QueryBuilder') let _query = '' let _params = [] module.exports = (dbSetting) => { let connection = mysql.createConnection({ host: dbSetting.hostname, user: dbSetting.username, password: dbSetting.password, database: dbSetting.database }) return { makeQuery: () => { return qBuilder }, prepare: () => { _query = qBuilder.prepare() }, setParameters: (params) => { _params = params qBuilder.setParameters(params) }, getParameters: () => { _params = qBuilder.getParameters() }, execute: () => { // connection.query(_query) }, get: () => { }, connectToDatabase: () => { connection.connect() }, endConnection: () => { connection.end() } } }
Add few functions and connect to query builder
Add few functions and connect to query builder
JavaScript
mit
evelikov92/mysql-qbuilder
--- +++ @@ -1,8 +1,8 @@ const mysql = require('mysql') const qBuilder = require('./QueryBuilder') -let query = '' -let params = [] +let _query = '' +let _params = [] module.exports = (dbSetting) => { let connection = mysql.createConnection({ @@ -12,26 +12,31 @@ database: dbSetting.database }) - connection.connect() - return { makeQuery: () => { return qBuilder }, prepare: () => { - query = qBuilder.prepare() + _query = qBuilder.prepare() }, setParameters: (params) => { + _params = params qBuilder.setParameters(params) }, getParameters: () => { - params = qBuilder.getParameters() + _params = qBuilder.getParameters() }, execute: () => { - // connection.query(query) + // connection.query(_query) }, get: () => { + }, + connectToDatabase: () => { + connection.connect() + }, + endConnection: () => { + connection.end() } } }
0f3c7f95b03b5e6b3b731158185ae12078c9b606
web/test/bootstrap.test.js
web/test/bootstrap.test.js
var Sails = require('sails'); before(function (done) { Sails.lift({ //config }, function (err, sails) { if (err) return done(err); // load fixtures, etc done (err, sails); }); }); after(function (done) { Sails.lower(done); });
var Sails = require('sails'); before(function (done) { this.timeout(5 * 1000); Sails.lift({ //config }, function (err, sails) { if (err) return done(err); // load fixtures, etc done (err, sails); }); }); after(function (done) { Sails.lower(done); });
Allow sails lift to take longer than 2 seconds
Allow sails lift to take longer than 2 seconds
JavaScript
apache-2.0
section-io-gists/vclfiddle,vclfiddle/vclfiddle,vclfiddle/vclfiddle,vclfiddle/vclfiddle,vclfiddle/vclfiddle,section-io-gists/vclfiddle,section-io-gists/vclfiddle,section-io-gists/vclfiddle
--- +++ @@ -1,6 +1,7 @@ var Sails = require('sails'); before(function (done) { + this.timeout(5 * 1000); Sails.lift({ //config }, function (err, sails) {
d2d68cb5ff8982f897b2805f57b73724def65208
feder/main/static/init_map.js
feder/main/static/init_map.js
(function($) { $("#pl_map path").on("click", function() { document.location.pathname = $(this).data("href") }); $('[data-toggle="tooltip"]').tooltip({'container': 'body'}); })(jQuery);
(function($) { $("#pl_map path").on("click", function() { document.location.pathname = $(this).data("href") }); })(jQuery);
Remove unused tooltip initialization code
Remove unused tooltip initialization code
JavaScript
mit
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
--- +++ @@ -2,5 +2,4 @@ $("#pl_map path").on("click", function() { document.location.pathname = $(this).data("href") }); - $('[data-toggle="tooltip"]').tooltip({'container': 'body'}); })(jQuery);
63d2829207a9968412fb332371774f3c1ca00601
src/config.js
src/config.js
var _ = require('underscore'); var fs = require('fs'); function Config(filePath) { var data = this.parse(filePath); this.validate(data); return Object.freeze(data); } Config.prototype.parse = function(filePath) { var content = fs.readFileSync(filePath, { encoding: 'utf8' }); return JSON.parse(content); }; Config.prototype.validate = function(data) { var pulsarApi = data.pulsarApi; if (!pulsarApi) { throw new Error('Define `pulsarApi` config options'); } this.validatePulsarApiInstance(pulsarApi, 'pulsarApi'); return _.each(pulsarApi.auxiliary, (function(_this) { return function(api, apiName) { if (!/^\w+\/\w+$/i.test(apiName)) { throw new Error("Wrong pulsarApi auxiliary API name: '" + apiName + "'. The acceptable format is: [{application}/{environment}]."); } return _this.validatePulsarApiInstance(api, apiName); }; })(this)); }; Config.prototype.validatePulsarApiInstance = function(api, apiName) { if (!api.url) { throw new Error("Define `" + apiName + ".url` in the config"); } }; module.exports = Config;
var _ = require('underscore'); var fs = require('fs'); /** * @param {String|Object} filePath. If param is a String then it is treated as a file path to a config file. * If param is an Object then it is treated as a parsed config file. * @constructor */ function Config(filePath) { var data; if (_.isObject(filePath)) { data = filePath; } else { data = this.parse(filePath); } this.validate(data); return Object.freeze(data); } Config.prototype.parse = function(filePath) { var content = fs.readFileSync(filePath, { encoding: 'utf8' }); return JSON.parse(content); }; Config.prototype.validate = function(data) { var pulsarApi = data.pulsarApi; if (!pulsarApi) { throw new Error('Define `pulsarApi` config options'); } this.validatePulsarApiInstance(pulsarApi, 'pulsarApi'); return _.each(pulsarApi.auxiliary, (function(_this) { return function(api, apiName) { if (!/^\w+\/\w+$/i.test(apiName)) { throw new Error("Wrong pulsarApi auxiliary API name: '" + apiName + "'. The acceptable format is: [{application}/{environment}]."); } return _this.validatePulsarApiInstance(api, apiName); }; })(this)); }; Config.prototype.validatePulsarApiInstance = function(api, apiName) { if (!api.url) { throw new Error("Define `" + apiName + ".url` in the config"); } }; module.exports = Config;
Allow to pass hash instead of filepath to Config.
Allow to pass hash instead of filepath to Config.
JavaScript
mit
vogdb/pulsar-rest-api-client-node,cargomedia/pulsar-rest-api-client-node
--- +++ @@ -1,8 +1,18 @@ var _ = require('underscore'); var fs = require('fs'); +/** + * @param {String|Object} filePath. If param is a String then it is treated as a file path to a config file. + * If param is an Object then it is treated as a parsed config file. + * @constructor + */ function Config(filePath) { - var data = this.parse(filePath); + var data; + if (_.isObject(filePath)) { + data = filePath; + } else { + data = this.parse(filePath); + } this.validate(data); return Object.freeze(data); }
5609d591ab892348b17f0bccef800dcd46ca431f
test/index.js
test/index.js
GLOBAL.projRequire = function (module) { return require('../' + module); };
GLOBAL.projRequire = function (module) { return require('../' + module); }; const log = projRequire('lib'); const tc = require('test-console'); const test = require('tape');
Add imports to test suite
Add imports to test suite
JavaScript
mit
cuvva/cuvva-log-sentry-node,TheTree/branch,TheTree/branch,TheTree/branch
--- +++ @@ -1,3 +1,7 @@ GLOBAL.projRequire = function (module) { return require('../' + module); }; + +const log = projRequire('lib'); +const tc = require('test-console'); +const test = require('tape');
c50035bb85a86aa7adb292ef74385388c391912c
test/index.js
test/index.js
require('./unit/index'); require('./test_multiple_payloads'); require('./test_misc'); require('./test_loop'); require('./test_capture'); require('./test_arrivals'); require('./test_reuse'); require('./test_loop'); require('./test_probability'); require('./test_if'); //require('./test_worker_http'); //require('./test_environments.js'); //require('./test_think'); //require('./test_tls');
require('./unit/index'); require('./test_multiple_payloads'); require('./test_misc'); require('./test_loop'); require('./test_capture'); require('./test_arrivals'); require('./test_reuse'); require('./test_loop'); require('./test_probability'); require('./test_if'); require('./ws/test_options'); //require('./test_worker_http'); //require('./test_environments.js'); //require('./test_think'); //require('./test_tls');
Include WS TLS test in the test suite
Include WS TLS test in the test suite
JavaScript
mpl-2.0
hassy/artillery,erikerikson/artillery-core,shoreditch-ops/artillery-core,shoreditch-ops/artillery,hassy/artillery-core,erikerikson/artillery-core,shoreditch-ops/artillery-core,shoreditch-ops/artillery,hassy/artillery,shoreditch-ops/artillery,hassy/artillery-core,hassy/artillery
--- +++ @@ -9,6 +9,8 @@ require('./test_probability'); require('./test_if'); +require('./ws/test_options'); + //require('./test_worker_http'); //require('./test_environments.js'); //require('./test_think');
58b4a325f06e178c398d96513f5ac7bd69ad0b1e
src/export.js
src/export.js
'use strict' /** * @class Elastic */ var Elastic = { klass : klass, domain: { Layout : LayoutDomain, View : ViewDomain, Compontnt: ComponentDomain }, exception: { Runtime : RuntimeException, Logic : LogicException }, util: { History : History, Router : Router, Storage : Storage, Validator: Validator }, trait: { AsyncCallback: AsyncCallbackTrait, Observable : ObservableTrait } }; // for RequireJS if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { window.define(function() { return Elastic; }); } // for Node.js & browserify else if (typeof module == 'object' && module && typeof exports == 'object' && exports && module.exports == exports ) { module.exports = Elastic; } // for Browser else { window.Elastic = Elastic; }
'use strict' /** * @class Elastic */ var Elastic = { // like OOP klass : klass, // shorthand Layout : LayoutDomain, View : ViewDomain, Component: ComponentDomain, // classes domain: { Layout : LayoutDomain, View : ViewDomain, Compontnt: ComponentDomain }, exception: { Runtime : RuntimeException, Logic : LogicException }, util: { History : History, Router : Router, Storage : Storage, Validator: Validator }, trait: { AsyncCallback: AsyncCallbackTrait, Observable : ObservableTrait } }; // for RequireJS if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { window.define(function() { return Elastic; }); } // for Node.js & browserify else if (typeof module == 'object' && module && typeof exports == 'object' && exports && module.exports == exports ) { module.exports = Elastic; } // for Browser else { window.Elastic = Elastic; }
Add Domain class's shorthand name
Add Domain class's shorthand name
JavaScript
mit
ahomu/Elastic
--- +++ @@ -4,7 +4,15 @@ * @class Elastic */ var Elastic = { + // like OOP klass : klass, + + // shorthand + Layout : LayoutDomain, + View : ViewDomain, + Component: ComponentDomain, + + // classes domain: { Layout : LayoutDomain, View : ViewDomain,
8b6b89e438c963ed0f3cb563cdfd60b6c0d0a7e0
shared/util/set-notifications.js
shared/util/set-notifications.js
/* @flow */ import engine from '../engine' import {notifyCtlSetNotificationsRpc} from '../constants/types/flow-types' type NotificationChannels = { session?: true, users?: true, kbfs?: true, tracking?: true, favorites?: true, paperkeys?: true, keyfamily?: true, service?: true, chat?: true, } let channelsSet = {} export default function (channels: NotificationChannels): Promise<void> { return new Promise((resolve, reject) => { channelsSet = {...channelsSet, ...channels} const toSend = { session: !!channelsSet.session, users: !!channelsSet.users, kbfs: !!channelsSet.kbfs, tracking: !!channelsSet.tracking, favorites: !!channelsSet.favorites, paperkeys: !!channelsSet.paperkeys, keyfamily: !!channelsSet.keyfamily, service: !!channelsSet.service, app: !!channelsSet.app, chat: !!channelsSet.chat, } engine.listenOnConnect('setNotifications', () => { notifyCtlSetNotificationsRpc({ param: {channels: toSend}, callback: (error, response) => { if (error != null) { console.warn('error in toggling notifications: ', error) reject(error) } else { resolve() } }, }) }) }) }
/* @flow */ import engine from '../engine' import {notifyCtlSetNotificationsRpc} from '../constants/types/flow-types' type NotificationChannels = { chat?: true, favorites?: true, kbfs?: true, keyfamily?: true, paperkeys?: true, pgp?: true, service?: true, session?: true, tracking?: true, users?: true, } let channelsSet = {} export default function (channels: NotificationChannels): Promise<void> { return new Promise((resolve, reject) => { channelsSet = {...channelsSet, ...channels} const toSend = { app: !!channelsSet.app, chat: !!channelsSet.chat, favorites: !!channelsSet.favorites, kbfs: !!channelsSet.kbfs, keyfamily: !!channelsSet.keyfamily, paperkeys: !!channelsSet.paperkeys, pgp: !!channelsSet.pgp, service: !!channelsSet.service, session: !!channelsSet.session, tracking: !!channelsSet.tracking, users: !!channelsSet.users, } engine.listenOnConnect('setNotifications', () => { notifyCtlSetNotificationsRpc({ param: {channels: toSend}, callback: (error, response) => { if (error != null) { console.warn('error in toggling notifications: ', error) reject(error) } else { resolve() } }, }) }) }) }
Add pgp to notification channels
Add pgp to notification channels
JavaScript
bsd-3-clause
keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client
--- +++ @@ -4,15 +4,16 @@ import {notifyCtlSetNotificationsRpc} from '../constants/types/flow-types' type NotificationChannels = { + chat?: true, + favorites?: true, + kbfs?: true, + keyfamily?: true, + paperkeys?: true, + pgp?: true, + service?: true, session?: true, + tracking?: true, users?: true, - kbfs?: true, - tracking?: true, - favorites?: true, - paperkeys?: true, - keyfamily?: true, - service?: true, - chat?: true, } let channelsSet = {} @@ -22,16 +23,17 @@ channelsSet = {...channelsSet, ...channels} const toSend = { - session: !!channelsSet.session, - users: !!channelsSet.users, - kbfs: !!channelsSet.kbfs, - tracking: !!channelsSet.tracking, - favorites: !!channelsSet.favorites, - paperkeys: !!channelsSet.paperkeys, - keyfamily: !!channelsSet.keyfamily, - service: !!channelsSet.service, app: !!channelsSet.app, chat: !!channelsSet.chat, + favorites: !!channelsSet.favorites, + kbfs: !!channelsSet.kbfs, + keyfamily: !!channelsSet.keyfamily, + paperkeys: !!channelsSet.paperkeys, + pgp: !!channelsSet.pgp, + service: !!channelsSet.service, + session: !!channelsSet.session, + tracking: !!channelsSet.tracking, + users: !!channelsSet.users, } engine.listenOnConnect('setNotifications', () => {
66b31b6659968968d3354fb5d114c77b72aac6af
test/mouse.js
test/mouse.js
var test = require('tape'); var robot = require('..'); var lastKnownPos, currentPos; test('Get the initial mouse position.', function(t) { t.plan(3); t.ok(lastKnownPos = robot.getMousePos(), 'successfully retrieved mouse position.'); t.ok(lastKnownPos.x !== undefined, 'mousepos.x is a valid value.'); t.ok(lastKnownPos.y !== undefined, 'mousepos.y is a valid value.'); }); test('Move the mouse.', function(t) { t.plan(3); lastKnownPos = robot.moveMouse(0, 0); t.ok(robot.moveMouse(100, 100), 'successfully moved the mouse.'); currentPos = robot.getMousePos(); t.ok(currentPos.x === 100, 'mousepos.x is correct.'); t.ok(currentPos.y === 100, 'mousepos.y is correct.'); });
var test = require('tape'); var robot = require('..'); var lastKnownPos, currentPos; //Increase delay to help test reliability. robot.setMouseDelay(100); test('Get the initial mouse position.', function(t) { t.plan(3); t.ok(lastKnownPos = robot.getMousePos(), 'successfully retrieved mouse position.'); t.ok(lastKnownPos.x !== undefined, 'mousepos.x is a valid value.'); t.ok(lastKnownPos.y !== undefined, 'mousepos.y is a valid value.'); }); test('Move the mouse.', function(t) { t.plan(3); lastKnownPos = robot.moveMouse(0, 0); t.ok(robot.moveMouse(100, 100), 'successfully moved the mouse.'); currentPos = robot.getMousePos(); t.ok(currentPos.x === 100, 'mousepos.x is correct.'); t.ok(currentPos.y === 100, 'mousepos.y is correct.'); });
Increase delay to help test reliability.
Increase delay to help test reliability.
JavaScript
mit
hristoterezov/robotjs,BHamrick1/robotjs,BHamrick1/robotjs,hristoterezov/robotjs,hristoterezov/robotjs,hristoterezov/robotjs,octalmage/robotjs,BHamrick1/robotjs,octalmage/robotjs,BHamrick1/robotjs,octalmage/robotjs,octalmage/robotjs
--- +++ @@ -1,6 +1,9 @@ var test = require('tape'); var robot = require('..'); var lastKnownPos, currentPos; + +//Increase delay to help test reliability. +robot.setMouseDelay(100); test('Get the initial mouse position.', function(t) {
6fad96e50890876712c69221a0cc372a2533a4ed
assets/js/googlesitekit/constants.js
assets/js/googlesitekit/constants.js
/** * Core constants. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export const VIEW_CONTEXT_DASHBOARD = 'dashboard'; export const VIEW_CONTEXT_PAGE_DASHBOARD = 'pageDashboard'; export const VIEW_CONTEXT_POSTS_LIST = 'postsList'; export const VIEW_CONTEXT_USER_INPUT = 'userInput'; export const VIEW_CONTEXT_ACTIVATION = 'activation'; export const VIEW_CONTEXT_DASHBOARD_SPLASH = 'splash'; export const VIEW_CONTEXT_ADMIN_BAR = 'adminBar'; export const VIEW_CONTEXT_SETTINGS = 'settings'; export const VIEW_CONTEXT_MODULE = 'module'; export const VIEW_CONTEXT_WP_DASHBOARD = 'WPDashboard';
/** * Core constants. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export const VIEW_CONTEXT_DASHBOARD = 'dashboard'; export const VIEW_CONTEXT_PAGE_DASHBOARD = 'pageDashboard'; export const VIEW_CONTEXT_POSTS_LIST = 'postsList'; export const VIEW_CONTEXT_USER_INPUT = 'userInput'; export const VIEW_CONTEXT_ACTIVATION = 'activation'; export const VIEW_CONTEXT_DASHBOARD_SPLASH = 'splash'; export const VIEW_CONTEXT_ADMIN_BAR = 'adminBar'; export const VIEW_CONTEXT_SETTINGS = 'settings'; export const VIEW_CONTEXT_MODULE = 'module'; export const VIEW_CONTEXT_WP_DASHBOARD = 'wpDashboard';
Change VIEW_CONTEXT_WP_DASHBOARD to camel case.
Change VIEW_CONTEXT_WP_DASHBOARD to camel case.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
--- +++ @@ -25,4 +25,4 @@ export const VIEW_CONTEXT_ADMIN_BAR = 'adminBar'; export const VIEW_CONTEXT_SETTINGS = 'settings'; export const VIEW_CONTEXT_MODULE = 'module'; -export const VIEW_CONTEXT_WP_DASHBOARD = 'WPDashboard'; +export const VIEW_CONTEXT_WP_DASHBOARD = 'wpDashboard';
932c3d27364eb4cfb09189f90afb92c8bfeaa07c
src/server.js
src/server.js
/* * Initialize the Restify server. */ var restify = require('restify'); var config = require('./config'); var routes = require('./routes'); var log = require('./logging').getLogger(); exports.create = function () { var server = restify.createServer(); server.pre(restify.pre.sanitizePath()); server.name = config.info.name; server.use(function (req, res, next) { log.verbose(req.method + ' ' + req.url); next(); }); server.use(restify.fullResponse()); server.on('uncaughtException', function (req, res, route, err) { log.error({ statusCode: err.statusCode || 500, requestURL: req.url, stack: err.stack, error: err.message, message: 'Uncaught exception' }); res.send(err); }); routes.loadRoutes(server); return server; };
/* * Initialize the Restify server. */ var restify = require('restify'); var config = require('./config'); var routes = require('./routes'); var log = require('./logging').getLogger(); exports.create = function () { var server = restify.createServer(); server.server.setTimeout(600000); server.pre(restify.pre.sanitizePath()); server.name = config.info.name; server.use(function (req, res, next) { log.verbose(req.method + ' ' + req.url); next(); }); server.use(restify.fullResponse()); server.on('uncaughtException', function (req, res, route, err) { log.error({ statusCode: err.statusCode || 500, requestURL: req.url, stack: err.stack, error: err.message, message: 'Uncaught exception' }); res.send(err); }); routes.loadRoutes(server); return server; };
Set a nice, generous timeout on requests.
Set a nice, generous timeout on requests.
JavaScript
mit
deconst/content-service,deconst/content-service
--- +++ @@ -9,6 +9,8 @@ exports.create = function () { var server = restify.createServer(); + + server.server.setTimeout(600000); server.pre(restify.pre.sanitizePath());
3bfcbc3ce266e873e43b8faf15d7b9ca87e6a094
src/server.js
src/server.js
import express from "express" import graphqlHTTP from "express-graphql" import { graphqlExpress, graphiqlExpress } from "graphql-server-express" import bodyParser from "body-parser" import mongoose, { Schema } from "mongoose" import schema from "./graphql" import Item from "./db/item" // Constants const CONFIG = require("./settings.yaml") const app = express() mongoose.Promise = global.Promise mongoose.connect( `mongodb://${CONFIG.mongodb.url}:${CONFIG.mongodb.port}/${CONFIG.mongodb.database}`, { useMongoClient: true } ) app.use( "/graphql", bodyParser.json({ limit: "15mb" }), graphqlExpress(() => ({ schema })) ) app.use( "/graphiql", graphiqlExpress({ endpointURL: "/graphql" }) ) export { app, CONFIG }
import bodyParser from "body-parser" import express from "express" import graphqlHTTP from "express-graphql" import { graphqlExpress, graphiqlExpress } from "graphql-server-express" import mongoose from "mongoose" import schema from "./graphql" import Item from "./db/item" import Update from "./db/update" // Constants const CONFIG = require("./settings.yaml") const app = express() mongoose.Promise = global.Promise mongoose.connect( `mongodb://${CONFIG.mongodb.url}:${CONFIG.mongodb.port}/${CONFIG.mongodb .database}`, { useMongoClient: true } ) mongoose.set("debug", true) app.use( "/graphql", bodyParser.json({ limit: "15mb" }), graphqlExpress(req => { return { schema, context: { loaders: {}, models: { items: Item, updates: Update } } } }) ) app.use( "/graphiql", graphiqlExpress({ endpointURL: "/graphql" }) ) export { app, CONFIG }
Add mongoose debugging and move models to context
Add mongoose debugging and move models to context
JavaScript
mit
DevNebulae/ads-pt-api
--- +++ @@ -1,10 +1,11 @@ +import bodyParser from "body-parser" import express from "express" import graphqlHTTP from "express-graphql" import { graphqlExpress, graphiqlExpress } from "graphql-server-express" -import bodyParser from "body-parser" -import mongoose, { Schema } from "mongoose" +import mongoose from "mongoose" import schema from "./graphql" import Item from "./db/item" +import Update from "./db/update" // Constants const CONFIG = require("./settings.yaml") @@ -13,20 +14,31 @@ mongoose.Promise = global.Promise mongoose.connect( - `mongodb://${CONFIG.mongodb.url}:${CONFIG.mongodb.port}/${CONFIG.mongodb.database}`, + `mongodb://${CONFIG.mongodb.url}:${CONFIG.mongodb.port}/${CONFIG.mongodb + .database}`, { useMongoClient: true } ) +mongoose.set("debug", true) app.use( "/graphql", bodyParser.json({ limit: "15mb" }), - graphqlExpress(() => ({ - schema - })) + graphqlExpress(req => { + return { + schema, + context: { + loaders: {}, + models: { + items: Item, + updates: Update + } + } + } + }) ) app.use(
b4dddaee7e2f449d65302009eb90c0ff608f6029
jasmine/src/inverted-index.js
jasmine/src/inverted-index.js
var fs = require('fs'); function Index(){ 'use strict' this.createIndex = function(filePath){ fs.readFile(filePath , function doneReading(err, fileContents){ console.log(fileContents.toString()); }) } } var indexObj =new Index(); indexObj.createIndex('../books.json');
Create an index object that points to a JSON file
Create an index object that points to a JSON file
JavaScript
mit
andela-jwarugu/checkpoint-1,andela-jwarugu/checkpoint-1
--- +++ @@ -0,0 +1,15 @@ +var fs = require('fs'); + +function Index(){ + 'use strict' + + this.createIndex = function(filePath){ + fs.readFile(filePath , function doneReading(err, fileContents){ + + console.log(fileContents.toString()); + }) + } +} + +var indexObj =new Index(); +indexObj.createIndex('../books.json');
86f7ec4efb24be276590df7c2304065a1b81027a
lib/response.js
lib/response.js
"use strict"; var Response = function(error, res) { res = res || {}; this.raw = res.body; this.headers = res.headers; this.status = res.statusCode || 500; if (error) { this._error = { error: (res.body || "Unknown error: empty response") }; } else { if (res.headers["content-type"].includes("application/json")) { try { this.json = res.body ? JSON.parse(res.body) : {}; } catch (ex) { this._error = { error: ex.toString() }; } } } }; Response.prototype.error = function() { if (!this._error && this.isError()) { this._error = this.json || {}; } return this._error; }; Response.prototype.isError = function() { return (this._error || this.isClientError() || this.isServerError()); }; Response.prototype.isSuccess = function() { return !this.isError(); }; Response.prototype.isClientError = function() { return this.status >= 400 && this.status < 500; }; Response.prototype.isServerError = function() { return this.status >= 500; }; module.exports = Response;
"use strict"; var Response = function(error, res) { res = res || {}; this.raw = res.body; this.headers = res.headers; this.status = res.statusCode || 500; if (error) { this._error = { error: (res.body || "Unknown error: empty response") }; } else { if (res.headers["content-type"].startsWith("application/json")) { try { this.json = res.body ? JSON.parse(res.body) : {}; } catch (ex) { this._error = { error: ex.toString() }; } } } }; Response.prototype.error = function() { if (!this._error && this.isError()) { this._error = this.json || {}; } return this._error; }; Response.prototype.isError = function() { return (this._error || this.isClientError() || this.isServerError()); }; Response.prototype.isSuccess = function() { return !this.isError(); }; Response.prototype.isClientError = function() { return this.status >= 400 && this.status < 500; }; Response.prototype.isServerError = function() { return this.status >= 500; }; module.exports = Response;
Use String.prototype.startsWith() instead of includes() for checking the content type
Use String.prototype.startsWith() instead of includes() for checking the content type
JavaScript
mit
skazska/m2x-nodejs,attm2x/m2x-nodejs
--- +++ @@ -9,7 +9,7 @@ if (error) { this._error = { error: (res.body || "Unknown error: empty response") }; } else { - if (res.headers["content-type"].includes("application/json")) { + if (res.headers["content-type"].startsWith("application/json")) { try { this.json = res.body ? JSON.parse(res.body) : {}; } catch (ex) {
578355c255e533622462c49d2a10b5e2fb5dc029
fetch-browser.js
fetch-browser.js
(function () { 'use strict'; function fetchPonyfill(options) { var Promise = options && options.Promise || self.Promise; var XMLHttpRequest = options && options.XMLHttpRequest || self.XMLHttpRequest; var global = self; return (function () { var self = Object.create(global, { fetch: { value: undefined, writable: true } }); // {{whatwgFetch}} return { fetch: self.fetch, Headers: self.Headers, Request: self.Request, Response: self.Response }; }()); } if (typeof define === 'function' && define.amd) { define(function () { return fetchPonyfill; }); } else if (typeof exports === 'object') { module.exports = fetchPonyfill; } else { self.fetchPonyfill = fetchPonyfill; } }());
(function (self) { 'use strict'; function fetchPonyfill(options) { var Promise = options && options.Promise || self.Promise; var XMLHttpRequest = options && options.XMLHttpRequest || self.XMLHttpRequest; var global = self; return (function () { var self = Object.create(global, { fetch: { value: undefined, writable: true } }); // {{whatwgFetch}} return { fetch: self.fetch, Headers: self.Headers, Request: self.Request, Response: self.Response }; }()); } if (typeof define === 'function' && define.amd) { define(function () { return fetchPonyfill; }); } else if (typeof exports === 'object') { module.exports = fetchPonyfill; } else { self.fetchPonyfill = fetchPonyfill; } }(typeof self === 'undefined' ? this : self));
Allow passing of self rather than just globally uses it
Allow passing of self rather than just globally uses it
JavaScript
mit
qubyte/fetch-ponyfill,qubyte/fetch-ponyfill
--- +++ @@ -1,4 +1,4 @@ -(function () { +(function (self) { 'use strict'; function fetchPonyfill(options) { @@ -34,4 +34,4 @@ } else { self.fetchPonyfill = fetchPonyfill; } -}()); +}(typeof self === 'undefined' ? this : self));
f36b511e9b9fc339a11c8c8acc758dc05009622c
lib/database.js
lib/database.js
var log4js = require('log4js'); var logger = log4js.getLogger('BOT-LOG'); function updateUserList(dyDb, userId){ } module.exports = { updateUserList:updateUserList }
var log4js = require('log4js'); var logger = log4js.getLogger('BOT-LOG'); function updateUserList(dyDb, userId, cb){ dydb.listTables({}, function(err, result){ if(err){ logger.error(err); cb(err, null); return; } }); } module.exports = { updateUserList:updateUserList }
Add listTables part into updateUserList
Add listTables part into updateUserList
JavaScript
mit
dollars0427/mtrupdate-bot
--- +++ @@ -1,8 +1,17 @@ var log4js = require('log4js'); var logger = log4js.getLogger('BOT-LOG'); -function updateUserList(dyDb, userId){ +function updateUserList(dyDb, userId, cb){ + dydb.listTables({}, function(err, result){ + + if(err){ + logger.error(err); + cb(err, null); + return; + } + + }); } module.exports = {
ce7d42edbf76e334eccc0897ed2283fbd0feb2d5
client/templates/posts/posts_list.js
client/templates/posts/posts_list.js
Template.postsList.helpers({ posts: function() { return Posts.find(); } });
Template.postsList.helpers({ posts: function() { return Posts.find({}, {sort: {submitted: -1}}); } });
Sort posts by submitted timestamp.
Sort posts by submitted timestamp.
JavaScript
mit
mtchllbrrn/microscope,mtchllbrrn/microscope
--- +++ @@ -1,5 +1,5 @@ Template.postsList.helpers({ posts: function() { - return Posts.find(); + return Posts.find({}, {sort: {submitted: -1}}); } });
5fd1908efa1add699d7a5169c8f05a64ec43f27b
src/global-components/info.js
src/global-components/info.js
let Vue = require('../../node_modules/vue/dist/vue.min'); let template = '<div style="border-radius: 4px; margin:5px; color: #31708f;background-color: #d9edf7; border: 1px solid #bce8f1;text-align: center">' + '<p>{{ message }}</p>' + '</div>'; Vue.component('info', { template: template, props: ['message'] });
let Vue = require('../../node_modules/vue/dist/vue.min'); let style = 'border-radius: 4px; margin:5px; color: #31708f;background-color: #d9edf7; border: 1px solid #bce8f1;text-align: center'; let template = ` <div style="${style}"> <p>{{ message }}</p> </div>`; Vue.component('info', { template: template, props: ['message'] });
Make use of ecma 6 template
Make use of ecma 6 template
JavaScript
mit
funcoding/vuetron-mail,funcoding/vuetron-mail
--- +++ @@ -1,8 +1,9 @@ let Vue = require('../../node_modules/vue/dist/vue.min'); - -let template = '<div style="border-radius: 4px; margin:5px; color: #31708f;background-color: #d9edf7; border: 1px solid #bce8f1;text-align: center">' + - '<p>{{ message }}</p>' + - '</div>'; +let style = 'border-radius: 4px; margin:5px; color: #31708f;background-color: #d9edf7; border: 1px solid #bce8f1;text-align: center'; +let template = ` + <div style="${style}"> + <p>{{ message }}</p> + </div>`; Vue.component('info', { template: template,
9a3be57d1ea6a2cd88a6e0f029405be65bb305e1
src/jsturbo-date.js
src/jsturbo-date.js
import str from '../src/jsturbo-string' function toStringDMY (date) { return [ str.pad(date.getDate().toString(), 2), str.pad((date.getMonth() + 1).toString(), 2), str.pad(date.getFullYear().toString(), 4) ].join('/') }; function isToday (date) { return toStringDMY(date) === toStringDMY(new Date()) }; function fromStringDMY (stringDdMmYyyy) { stringDdMmYyyy = stringDdMmYyyy.replace(/\D/g, '') var day = parseInt(stringDdMmYyyy.substr(0, 2)) var month = parseInt(stringDdMmYyyy.substr(2, 2)) - 1 var year = parseInt(stringDdMmYyyy.substr(4, 4)) return new Date(year, month, day, 0, 0, 0, 0) }; const mainExport = { toStringDMY: toStringDMY, isToday: isToday, fromStringDMY: fromStringDMY } export default mainExport module.exports = mainExport // for CommonJS compatibility
import str from '../src/jsturbo-string' /** * Converts a date to string in the format 'dd/MM/yyyy' * @param {Date} Date object * @return {string} */ function toStringDMY (date) { return [ str.pad(date.getDate().toString(), 2), str.pad((date.getMonth() + 1).toString(), 2), str.pad(date.getFullYear().toString(), 4) ].join('/') }; /** * Check if a date object represents the current day * @param {Date} * @return {Boolean} */ function isToday (date) { return toStringDMY(date) === toStringDMY(new Date()) }; /** * Create a Date object based on a string in the format 'dd/MM/yyyy' * @param {string} string with a date in the format 'dd/MM/yyyy' * @return {Date} */ function fromStringDMY (stringDdMmYyyy) { stringDdMmYyyy = stringDdMmYyyy.replace(/\D/g, '') var day = parseInt(stringDdMmYyyy.substr(0, 2)) var month = parseInt(stringDdMmYyyy.substr(2, 2)) - 1 var year = parseInt(stringDdMmYyyy.substr(4, 4)) return new Date(year, month, day, 0, 0, 0, 0) }; const mainExport = { toStringDMY: toStringDMY, isToday: isToday, fromStringDMY: fromStringDMY } export default mainExport module.exports = mainExport // for CommonJS compatibility
Add documentation to the date module
docs(date): Add documentation to the date module
JavaScript
mit
eduardoportilho/jsturbo
--- +++ @@ -1,5 +1,10 @@ import str from '../src/jsturbo-string' +/** + * Converts a date to string in the format 'dd/MM/yyyy' + * @param {Date} Date object + * @return {string} + */ function toStringDMY (date) { return [ str.pad(date.getDate().toString(), 2), @@ -8,10 +13,20 @@ ].join('/') }; +/** + * Check if a date object represents the current day + * @param {Date} + * @return {Boolean} + */ function isToday (date) { return toStringDMY(date) === toStringDMY(new Date()) }; +/** + * Create a Date object based on a string in the format 'dd/MM/yyyy' + * @param {string} string with a date in the format 'dd/MM/yyyy' + * @return {Date} + */ function fromStringDMY (stringDdMmYyyy) { stringDdMmYyyy = stringDdMmYyyy.replace(/\D/g, '') var day = parseInt(stringDdMmYyyy.substr(0, 2))
c82b074e557835334e50276a1f25e98b4567d7e8
src/locale/da_DK.js
src/locale/da_DK.js
export default { today: 'I dag', now: 'Nu', backToToday: 'Tilbage til i dag', ok: 'Ok', clear: 'Annuler', month: 'Måned', year: 'År', timeSelect: 'Vælg tidspunkt', dateSelect: 'Vælg dato', monthSelect: 'Vælg måned', yearSelect: 'Vælg år', decadeSelect: 'Vælg årti', yearFormat: 'YYYY', dateFormat: 'D/M/YYYY', dayFormat: 'D', dateTimeFormat: 'D/M/YYYY HH:mm:ss', monthFormat: 'MMMM', monthBeforeYear: true, previousMonth: 'Forrige måned(PageUp)', nextMonth: 'Næste måned (PageDown)', previousYear: 'Forrige år (Control + left)', nextYear: 'Næste r (Control + right)', previousDecade: 'Forrige årti', nextDecade: 'Næste årti', previousCentury: 'Forrige århundrede', nextCentury: 'Næste århundrede', };
export default { today: 'I dag', now: 'Nu', backToToday: 'Gå til i dag', ok: 'Ok', clear: 'Annuller', month: 'Måned', year: 'År', timeSelect: 'Vælg tidspunkt', dateSelect: 'Vælg dato', monthSelect: 'Vælg måned', yearSelect: 'Vælg år', decadeSelect: 'Vælg årti', yearFormat: 'YYYY', dateFormat: 'D/M/YYYY', dayFormat: 'D', dateTimeFormat: 'D/M/YYYY HH:mm:ss', monthFormat: 'MMMM', monthBeforeYear: true, previousMonth: 'Forrige måned(PageUp)', nextMonth: 'Næste måned (PageDown)', previousYear: 'Forrige år (Control + left)', nextYear: 'Næste r (Control + right)', previousDecade: 'Forrige årti', nextDecade: 'Næste årti', previousCentury: 'Forrige århundrede', nextCentury: 'Næste århundrede', };
Fix wrong wording and spelling
Fix wrong wording and spelling
JavaScript
mit
react-component/calendar,react-component/calendar
--- +++ @@ -1,9 +1,9 @@ export default { today: 'I dag', now: 'Nu', - backToToday: 'Tilbage til i dag', + backToToday: 'Gå til i dag', ok: 'Ok', - clear: 'Annuler', + clear: 'Annuller', month: 'Måned', year: 'År', timeSelect: 'Vælg tidspunkt',
fbeb60a6f9aefe23ae8c678b601c321166042bf8
src/main-browser.js
src/main-browser.js
import BiwaScheme from "./main.js"; BiwaScheme.on_node = false; import Console from "./platforms/browser/console.js" BiwaScheme.Console = Console; import { current_input, current_output, current_error } from "./platforms/browser/default_ports.js" BiwaScheme.Port.current_input = current_input; BiwaScheme.Port.current_output = current_output; BiwaScheme.Port.current_error = current_error; // // browser-specific code // import { jsonp_receiver } from "./library/webscheme_lib.js" BiwaScheme.jsonp_receiver = jsonp_receiver; import Dumper from "./platforms/browser/dumper.js" BiwaScheme.Dumper = Dumper; // TODO: ideally this should just be `window.BiwaScheme = BiwaScheme` but it will break test/spec.html (grep with `register_tests`) window.BiwaScheme = window.BiwaScheme || {}; Object.assign(window.BiwaScheme, BiwaScheme); import { execute_user_program } from "./platforms/browser/release_initializer.js" execute_user_program();
import BiwaScheme from "./main.js"; BiwaScheme.on_node = false; import Console from "./platforms/browser/console.js" BiwaScheme.Console = Console; import { current_input, current_output, current_error } from "./platforms/browser/default_ports.js" BiwaScheme.Port.current_input = current_input; BiwaScheme.Port.current_output = current_output; BiwaScheme.Port.current_error = current_error; // // browser-specific code // import { jsonp_receiver } from "./library/webscheme_lib.js" BiwaScheme.jsonp_receiver = jsonp_receiver; import Dumper from "./platforms/browser/dumper.js" BiwaScheme.Dumper = Dumper; // TODO: ideally this should just be `window.BiwaScheme = BiwaScheme` but it will break test/spec.html (grep with `register_tests`) window.BiwaScheme = window.BiwaScheme || {}; Object.assign(window.BiwaScheme, BiwaScheme); import { execute_user_program } from "./platforms/browser/release_initializer.js" execute_user_program(); module.exports = BiwaScheme;
Add BiwaScheme to browser module exports
Add BiwaScheme to browser module exports
JavaScript
mit
biwascheme/biwascheme,biwascheme/biwascheme,biwascheme/biwascheme
--- +++ @@ -25,3 +25,5 @@ import { execute_user_program } from "./platforms/browser/release_initializer.js" execute_user_program(); + +module.exports = BiwaScheme;
cf0542fe9895207d9ce9f68b458aba49fabfd9f0
app/assets/javascripts/application/codemirror-builder.js
app/assets/javascripts/application/codemirror-builder.js
var mumuki = mumuki || {}; (function (mumuki) { function CodeMirrorBuilder(textarea) { this.textarea = textarea; this.$textarea = $(textarea); } CodeMirrorBuilder.prototype = { setupEditor: function () { this.editor = CodeMirror.fromTextArea(this.textarea); }, setupLanguage: function () { var language = $(this.textarea).data('editor-language'); if (language === 'dynamic') { mumuki.page.dynamicEditors.push(this.editor); } else { mumuki.editor.setOption('mode', language); } }, setupPlaceholder: function (text) { this.editor.setOption('placeholder', text); }, setupOptions: function (minLines) { this.editor.setOption('tabSize', 2); this.editor.setOption('indentWithTabs', true); this.editor.setOption('lineWrapping', true); this.editor.setOption('lineNumbers', true); this.editor.setOption('showCursorWhenSelecting', true); this.editor.setOption('lineWiseCopyCut', true); this.editor.setOption('cursorHeight', 1); }, build: function () { return this.editor; } }; mumuki.editor = mumuki.editor || {}; mumuki.editor.CodeMirrorBuilder = CodeMirrorBuilder; }(mumuki));
var mumuki = mumuki || {}; (function (mumuki) { function CodeMirrorBuilder(textarea) { this.textarea = textarea; this.$textarea = $(textarea); } CodeMirrorBuilder.prototype = { setupEditor: function () { this.editor = CodeMirror.fromTextArea(this.textarea); }, setupLanguage: function () { var language = this.$textarea.data('editor-language'); if (language === 'dynamic') { mumuki.page.dynamicEditors.push(this.editor); } else { mumuki.editor.setOption('mode', language); } }, setupPlaceholder: function (text) { this.editor.setOption('placeholder', text); }, setupOptions: function (minLines) { this.editor.setOption('tabSize', 2); this.editor.setOption('lineWrapping', true); this.editor.setOption('lineNumbers', true); this.editor.setOption('showCursorWhenSelecting', true); this.editor.setOption('lineWiseCopyCut', true); this.editor.setOption('cursorHeight', 1); }, build: function () { return this.editor; } }; mumuki.editor = mumuki.editor || {}; mumuki.editor.CodeMirrorBuilder = CodeMirrorBuilder; }(mumuki));
Remove indent with spaces option
Remove indent with spaces option
JavaScript
agpl-3.0
mumuki/mumuki-laboratory,mumuki/mumuki-laboratory,mumuki/mumuki-laboratory,mumuki/mumuki-laboratory
--- +++ @@ -12,7 +12,7 @@ this.editor = CodeMirror.fromTextArea(this.textarea); }, setupLanguage: function () { - var language = $(this.textarea).data('editor-language'); + var language = this.$textarea.data('editor-language'); if (language === 'dynamic') { mumuki.page.dynamicEditors.push(this.editor); } else { @@ -25,7 +25,6 @@ setupOptions: function (minLines) { this.editor.setOption('tabSize', 2); - this.editor.setOption('indentWithTabs', true); this.editor.setOption('lineWrapping', true); this.editor.setOption('lineNumbers', true); this.editor.setOption('showCursorWhenSelecting', true);
3061897a2508c1226dcd1a153542539cdf17fdaa
src/routes/index.js
src/routes/index.js
import App from '../containers/App' function createRedirect(from, to) { return { path: from, onEnter(nextState, replaceState) { replaceState(nextState, to) }, } } const routes = [ createRedirect('/', '/explore'), { path: '/', component: App, // order matters, so less specific routes should go at the bottom childRoutes: [ require('./post_detail'), ...require('./authentication'), ...require('./discover'), ...require('./streams'), require('./notifications'), ...require('./settings'), ...require('./invitations'), createRedirect('onboarding', '/onboarding/communities'), require('./onboarding'), ...require('./search'), require('./user_detail'), ], }, ] export default routes
import App from '../containers/App' function createRedirect(from, to) { return { path: from, onEnter(nextState, replaceState) { replaceState(nextState, to) }, } } const routes = [ createRedirect('/', '/explore'), { path: '/', component: App, // order matters, so less specific routes should go at the bottom childRoutes: [ require('./post_detail'), ...require('./authentication'), ...require('./discover'), ...require('./streams'), require('./notifications'), ...require('./invitations'), createRedirect('onboarding', '/onboarding/communities'), require('./onboarding'), ...require('./search'), require('./user_detail'), ], }, ] export default routes
Remove settings from the routes for the moment
Remove settings from the routes for the moment
JavaScript
mit
ello/webapp,ello/webapp,ello/webapp
--- +++ @@ -21,7 +21,6 @@ ...require('./discover'), ...require('./streams'), require('./notifications'), - ...require('./settings'), ...require('./invitations'), createRedirect('onboarding', '/onboarding/communities'), require('./onboarding'),
3b850511df407a35f803118ca14c78b7e240cb8f
src/routes/index.js
src/routes/index.js
var express = require('express'); var os = require('os'); var router = express.Router(); var ifaces = os.networkInterfaces(); var localAddress = ''; var environment = process.env.NODE_ENV === 'production' ? 'production' : 'development'; var environmentNotice = environment === 'production' ? '' : environment + ' environment'; Object.keys(ifaces).forEach(function (ifname) { var alias = 0; ifaces[ifname].forEach(function (iface) { if ('IPv4' !== iface.family || iface.internal !== false) { // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses return; } localAddress = iface.address; }); }); /* GET home page. */ router.get('/', function (req, res, next) { res.render('index', { title: 'Accumulator', environment: environment, environmentNotice: environmentNotice, localAddress: localAddress }); }); module.exports = router;
var express = require('express'); var os = require('os'); var router = express.Router(); var ifaces = os.networkInterfaces(); var localAddress = ''; var environment = process.env.NODE_ENV === 'production' ? 'production' : 'development'; var environmentNotice = environment === 'production' ? '' : environment + ' environment'; Object.keys(ifaces).forEach(function (ifname) { var alias = 0; ifaces[ifname].forEach(function (iface) { if ('IPv4' !== iface.family || iface.internal !== false || localAddress !== '') { // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses return; } localAddress = iface.address; }); }); /* GET home page. */ router.get('/', function (req, res, next) { res.render('index', { title: 'Accumulator', environment: environment, environmentNotice: environmentNotice, localAddress: localAddress }); }); module.exports = router;
Select first network interface IP for localAddress display
Select first network interface IP for localAddress display
JavaScript
mit
lrakai/docker-software-delivery,lrakai/docker-software-delivery,lrakai/docker-software-delivery
--- +++ @@ -11,7 +11,7 @@ var alias = 0; ifaces[ifname].forEach(function (iface) { - if ('IPv4' !== iface.family || iface.internal !== false) { + if ('IPv4' !== iface.family || iface.internal !== false || localAddress !== '') { // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses return; }
daa5604ff4397caf02158634803d9a50e3b179a9
public/themes/lightweight/controllers/cart/checkout.as.guest.controller.js
public/themes/lightweight/controllers/cart/checkout.as.guest.controller.js
'use strict'; angular.module('lightweight').controller('CheckoutAsGuestController', ['$scope', '$rootScope', '$location', '$state', '$timeout', '$stateParams', '$window', 'Global', 'UserService','CartService', function($scope, $rootScope, $location, $state, $timeout, $stateParams, $window, Global, UserService, CartService) { $scope.global = Global; var returnState = $stateParams.returnUrl; $scope.userCredential = {}; $scope.items = []; CartService.getItemsWithoutPopulate() .$promise .then(function (items) { $scope.items = items; }); $scope.loginFromCheckout = function() { if($scope.items && $scope.items.length) { $scope.user.items = $scope.items; UserService.signInUserWithGuestUserItems($scope.user) .$promise .then(function(user) { $scope.global.user = user; //$window.location.reload(); $rootScope.$emit('cart:updated'); $timeout(function() { $state.go(returnState, {}, { reload: true }); }); }, function(error) { console.log('error== ',error); $scope.errorLogin = error.data.message; }); } }; $scope.checkoutAsGuest = function() { $state.go(returnState); }; } ]);
'use strict'; angular.module('lightweight').controller('CheckoutAsGuestController', ['$scope', '$rootScope', '$location', '$state', '$timeout', '$stateParams', '$window', 'Global', 'UserService','CartService', function($scope, $rootScope, $location, $state, $timeout, $stateParams, $window, Global, UserService, CartService) { $scope.global = Global; var returnState = $stateParams.returnUrl; $scope.userCredential = {}; $scope.items = []; CartService.getItemsWithoutPopulate() .$promise .then(function (items) { $scope.items = items; }); $scope.loginFromCheckout = function() { if($scope.items && $scope.items.length) { $scope.user.items = $scope.items; UserService.signInUserWithGuestUserItems($scope.user) .$promise .then(function(user) { $rootScope.$emit('cart:updated'); $timeout(function() { $scope.global.user = user; $scope.global.isRegistered = true; $state.go(returnState); }); }, function(error) { $scope.errorLogin = error.data.message; }); } }; $scope.checkoutAsGuest = function() { $state.go(returnState); }; } ]);
Update to set register user after logged in
Update to set register user after logged in
JavaScript
mit
shaishab/BS-Commerce,shaishab/BS-Commerce,shaishab/BS-Commerce
--- +++ @@ -20,17 +20,16 @@ UserService.signInUserWithGuestUserItems($scope.user) .$promise .then(function(user) { - $scope.global.user = user; - //$window.location.reload(); $rootScope.$emit('cart:updated'); $timeout(function() { - $state.go(returnState, {}, { reload: true }); + $scope.global.user = user; + $scope.global.isRegistered = true; + $state.go(returnState); }); - + }, function(error) { - console.log('error== ',error); $scope.errorLogin = error.data.message; }); }
6aea1d4c7d3f7ca44356bc8186fb662483580fa9
src/features/settingsWS/index.js
src/features/settingsWS/index.js
import { reaction, runInAction } from 'mobx'; import { SettingsWSStore } from './store'; import state, { resetState } from './state'; const debug = require('debug')('Franz:feature:settingsWS'); let store = null; export default function initAnnouncements(stores, actions) { const { features } = stores; // Toggle workspace feature reaction( () => ( features.features.isSettingsWSEnabled ), (isEnabled) => { if (isEnabled) { debug('Initializing `settingsWS` feature'); store = new SettingsWSStore(stores, null, actions, state); store.initialize(); runInAction(() => { state.isFeatureActive = true; }); } else if (store) { debug('Disabling `settingsWS` feature'); runInAction(() => { state.isFeatureActive = false; }); store.teardown(); store = null; resetState(); // Reset state to default } }, { fireImmediately: true, }, ); }
import { reaction, runInAction } from 'mobx'; import { SettingsWSStore } from './store'; import state, { resetState } from './state'; const debug = require('debug')('Franz:feature:settingsWS'); let store = null; export default function initSettingsWebSocket(stores, actions) { const { features } = stores; // Toggle SettingsWebSocket feature reaction( () => ( features.features.isSettingsWSEnabled ), (isEnabled) => { if (isEnabled) { debug('Initializing `settingsWS` feature'); store = new SettingsWSStore(stores, null, actions, state); store.initialize(); runInAction(() => { state.isFeatureActive = true; }); } else if (store) { debug('Disabling `settingsWS` feature'); runInAction(() => { state.isFeatureActive = false; }); store.teardown(); store = null; resetState(); // Reset state to default } }, { fireImmediately: true, }, ); }
Remove copy & paste issues
Remove copy & paste issues
JavaScript
apache-2.0
meetfranz/franz,meetfranz/franz,meetfranz/franz
--- +++ @@ -6,10 +6,10 @@ let store = null; -export default function initAnnouncements(stores, actions) { +export default function initSettingsWebSocket(stores, actions) { const { features } = stores; - // Toggle workspace feature + // Toggle SettingsWebSocket feature reaction( () => ( features.features.isSettingsWSEnabled
0c9680bfad90854bc47409466afd77c3f28f62d5
tests/docs.js
tests/docs.js
'use strict'; require('../examples/demo-only-stuff/docs'); var expect = require('chai').expect; var sinon = require('sinon'); var stub = sinon.stub; var utils = require('./helpers/utils'); var each = utils.each; var any = utils.any; var getContextStub = require('./helpers/get-context-stub'); var Canvas = require('../lib/index.js'); describe('docs', function () { var element = document.createElement('canvas'); stub(element, 'getContext', getContextStub); var canvas = new Canvas(element); var docs = window.docs; it('is a list of groups', function () { expect(docs.length).to.be.above(1); each(docs, function (value) { expect(value.name).to.exist; expect(value.methods).to.exist; }); }); it('should contain all of the canvasimo methods (or aliases)', function () { each(canvas, function (value, key) { var anyGroupContainsTheMethod = any(docs, function (group) { return any(group.methods, function (method) { return method.name === key || method.alias === key; }); }); expect(anyGroupContainsTheMethod).to.be.true; }); }); });
'use strict'; require('../examples/demo-only-stuff/docs'); var expect = require('chai').expect; var sinon = require('sinon'); var stub = sinon.stub; var utils = require('./helpers/utils'); var each = utils.each; var any = utils.any; var getContextStub = require('./helpers/get-context-stub'); var Canvas = require('../lib/index.js'); describe('docs', function () { var element = document.createElement('canvas'); stub(element, 'getContext', getContextStub); var canvas = new Canvas(element); var docs = window.docs; it('is a list of groups', function () { expect(docs.length).to.be.above(1); each(docs, function (value) { expect(value.name).to.exist; expect(value.methods).to.exist; }); }); it('should contain all of the canvasimo methods (or aliases)', function () { each(canvas, function (value, key) { var anyGroupContainsTheMethod = any(docs, function (group) { return any(group.methods, function (method) { return method.name === key || method.alias === key; }); }); expect(anyGroupContainsTheMethod).to.be.true; }); }); it('should have names and descriptions for all methods', function () { each(docs, function (group) { each(group.methods, function (method) { expect(method.name).to.exist; expect(method.description).to.exist; expect(method.name.length).to.be.above(5); expect(method.description.length).to.be.above(5); }); }); }); });
Test that all methods have a name and description
Test that all methods have a name and description
JavaScript
mit
JakeSidSmith/canvasimo,JakeSidSmith/sensible-canvas-interface,JakeSidSmith/canvasimo
--- +++ @@ -39,4 +39,15 @@ }); }); + it('should have names and descriptions for all methods', function () { + each(docs, function (group) { + each(group.methods, function (method) { + expect(method.name).to.exist; + expect(method.description).to.exist; + expect(method.name.length).to.be.above(5); + expect(method.description.length).to.be.above(5); + }); + }); + }); + });
86d78236569bda8954e157576be7cbdd3078ded2
src/server/index.js
src/server/index.js
const DB = require('./Persistence/database'); require('dotenv').config(); const App = require('./app'); DB.init().then((db) => { App(db).listen(3000); });
const DB = require('./Persistence/database'); require('dotenv').config(); const App = require('./app'); const port = process.env.PORT || 3000; DB.init().then((db) => { App(db).listen(port, () => { console.log(`Secure Drop running on port ${port}`); }); });
Add support for port changing
Add support for port changing
JavaScript
mit
RossCasey/SecureDrop,RossCasey/SecureDrop
--- +++ @@ -2,6 +2,10 @@ require('dotenv').config(); const App = require('./app'); +const port = process.env.PORT || 3000; + DB.init().then((db) => { - App(db).listen(3000); + App(db).listen(port, () => { + console.log(`Secure Drop running on port ${port}`); + }); });
84767a5bc800e03b6ff6acea4a2a76a585e65049
test/passwords-test.js
test/passwords-test.js
const Passwords = require('../passwords'); describe('Passwords', () => { let originalTimeout; beforeEach(() => { // Increase timeout because bcrypt is slow originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; }); it('should be able to generate and compare hashes', async () => { const pass = 'apple'; const passFake = 'orange'; const passHash = await Passwords.hash(pass); const passHashSync = Passwords.hashSync(pass); const passFakeHashSync = Passwords.hashSync(passFake); expect(Passwords.compareSync(pass, passHash)).toBeTruthy(); const compareAsync = await Passwords.compare(pass, passHash); expect(compareAsync).toBeTruthy(); expect(Passwords.compareSync(pass, passHashSync)).toBeTruthy(); expect(Passwords.compareSync(passFake, passHash)).toBeFalsy(); expect(Passwords.compareSync(pass, passFakeHashSync)).toBeFalsy(); }); afterEach(() => { jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); })
const Passwords = require('../passwords'); describe('Passwords', () => { let originalTimeout; beforeEach(() => { // Increase timeout because bcrypt is slow originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; }); it('should be able to generate and compare hashes', async () => { const pass = 'apple'; const passFake = 'orange'; const passHash = await Passwords.hash(pass); const passHashSync = Passwords.hashSync(pass); const passFakeHashSync = Passwords.hashSync(passFake); expect(Passwords.compareSync(pass, passHash)).toBeTruthy(); const compareAsync = await Passwords.compare(pass, passHash); expect(compareAsync).toBeTruthy(); expect(Passwords.compareSync(pass, passHashSync)).toBeTruthy(); expect(Passwords.compareSync(passFake, passHash)).toBeFalsy(); expect(Passwords.compareSync(pass, passFakeHashSync)).toBeFalsy(); }); afterEach(() => { jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); })
Increase test timeout further because bcrypt's entire purpose in life is to be slow
Increase test timeout further because bcrypt's entire purpose in life is to be slow
JavaScript
mpl-2.0
moziot/gateway,mozilla-iot/gateway,mozilla-iot/gateway,moziot/gateway,mozilla-iot/gateway,mozilla-iot/gateway,mozilla-iot/gateway,moziot/gateway
--- +++ @@ -5,7 +5,7 @@ beforeEach(() => { // Increase timeout because bcrypt is slow originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; - jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; + jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; }); it('should be able to generate and compare hashes', async () => {
5c23d7fc54a8f960340d2f8989a7e4a1da7c362b
app/assets/javascripts/angular_modules/module_toolbar.js
app/assets/javascripts/angular_modules/module_toolbar.js
miqHttpInject( angular.module('ManageIQ.toolbar', [ 'miqStaticAssets', 'ui.bootstrap' ]) .config(['$locationProvider', function ($locationProvider) { $locationProvider.html5Mode({ enabled: true, requireBase: false }) }]) );
miqHttpInject( angular.module('ManageIQ.toolbar', [ 'miqStaticAssets', 'ui.bootstrap' ]) .config(['$locationProvider', function ($locationProvider) { $locationProvider.html5Mode({ enabled: false, requireBase: false, }); }]) );
Disable html5 mode for the toolbar angular module
Disable html5 mode for the toolbar angular module When the current url contains a query string parameter with plus signs (like `?flash_msg=Edit+of+Cloud+Provider+"Amazon"+was+cancelled+by+the+user`), clicking on the toolbar would first mangle the url to use `%20` instead of `+`, and then clicking again would work. This is because in html5 mode, angular needs to controll the URL. However, there's no reason the toolbar should even be aware of the current URL, etc. Thus, disabling html5 mode in that module. Closes #11537
JavaScript
apache-2.0
kbrock/manageiq,ManageIQ/manageiq,branic/manageiq,mresti/manageiq,NaNi-Z/manageiq,andyvesel/manageiq,tinaafitz/manageiq,agrare/manageiq,billfitzgerald0120/manageiq,durandom/manageiq,jvlcek/manageiq,jrafanie/manageiq,jameswnl/manageiq,juliancheal/manageiq,mzazrivec/manageiq,mresti/manageiq,ailisp/manageiq,mfeifer/manageiq,gerikis/manageiq,d-m-u/manageiq,mkanoor/manageiq,tinaafitz/manageiq,josejulio/manageiq,israel-hdez/manageiq,gmcculloug/manageiq,tzumainn/manageiq,mfeifer/manageiq,d-m-u/manageiq,fbladilo/manageiq,ManageIQ/manageiq,NickLaMuro/manageiq,ilackarms/manageiq,juliancheal/manageiq,mkanoor/manageiq,fbladilo/manageiq,skateman/manageiq,chessbyte/manageiq,andyvesel/manageiq,aufi/manageiq,tzumainn/manageiq,ManageIQ/manageiq,djberg96/manageiq,yaacov/manageiq,kbrock/manageiq,aufi/manageiq,jntullo/manageiq,ilackarms/manageiq,ManageIQ/manageiq,mfeifer/manageiq,jvlcek/manageiq,tinaafitz/manageiq,pkomanek/manageiq,ilackarms/manageiq,fbladilo/manageiq,billfitzgerald0120/manageiq,mkanoor/manageiq,gerikis/manageiq,ailisp/manageiq,chessbyte/manageiq,pkomanek/manageiq,djberg96/manageiq,jrafanie/manageiq,pkomanek/manageiq,lpichler/manageiq,djberg96/manageiq,jvlcek/manageiq,aufi/manageiq,matobet/manageiq,jntullo/manageiq,d-m-u/manageiq,lpichler/manageiq,agrare/manageiq,mfeifer/manageiq,durandom/manageiq,andyvesel/manageiq,aufi/manageiq,ailisp/manageiq,agrare/manageiq,d-m-u/manageiq,kbrock/manageiq,skateman/manageiq,billfitzgerald0120/manageiq,borod108/manageiq,branic/manageiq,mkanoor/manageiq,jameswnl/manageiq,pkomanek/manageiq,romanblanco/manageiq,juliancheal/manageiq,romanblanco/manageiq,fbladilo/manageiq,gmcculloug/manageiq,skateman/manageiq,skateman/manageiq,ilackarms/manageiq,hstastna/manageiq,syncrou/manageiq,mzazrivec/manageiq,yaacov/manageiq,matobet/manageiq,yaacov/manageiq,NaNi-Z/manageiq,agrare/manageiq,djberg96/manageiq,NaNi-Z/manageiq,NickLaMuro/manageiq,tzumainn/manageiq,jrafanie/manageiq,tinaafitz/manageiq,gmcculloug/manageiq,yaacov/manageiq,syncrou/manageiq,mresti/manageiq,borod108/manageiq,matobet/manageiq,mzazrivec/manageiq,romanblanco/manageiq,josejulio/manageiq,ailisp/manageiq,durandom/manageiq,andyvesel/manageiq,NickLaMuro/manageiq,matobet/manageiq,israel-hdez/manageiq,mresti/manageiq,chessbyte/manageiq,borod108/manageiq,billfitzgerald0120/manageiq,chessbyte/manageiq,jameswnl/manageiq,israel-hdez/manageiq,syncrou/manageiq,kbrock/manageiq,syncrou/manageiq,durandom/manageiq,hstastna/manageiq,hstastna/manageiq,NickLaMuro/manageiq,josejulio/manageiq,jrafanie/manageiq,branic/manageiq,jameswnl/manageiq,juliancheal/manageiq,lpichler/manageiq,romanblanco/manageiq,hstastna/manageiq,israel-hdez/manageiq,tzumainn/manageiq,lpichler/manageiq,borod108/manageiq,mzazrivec/manageiq,jntullo/manageiq,jvlcek/manageiq,gerikis/manageiq,jntullo/manageiq,NaNi-Z/manageiq,gerikis/manageiq,branic/manageiq,gmcculloug/manageiq,josejulio/manageiq
--- +++ @@ -4,8 +4,8 @@ ]) .config(['$locationProvider', function ($locationProvider) { $locationProvider.html5Mode({ - enabled: true, - requireBase: false - }) + enabled: false, + requireBase: false, + }); }]) );
4a937b4779f1f8357a0da777846ce5e406222721
tasks/grunt-sass.js
tasks/grunt-sass.js
const path = require('path'); const fs = require('fs'); const sass = require('node-sass'); const { promisify } = require('util'); const mkdirp = require('mkdirp'); const renderAsPromised = promisify(sass.render); const writeFileAsPromised = promisify(fs.writeFile); const mkdirpAsPromised = promisify(mkdirp); module.exports = function (grunt) { grunt.registerMultiTask('sass', 'compile sass', function () { let done = this.async(), promises; mkdirpAsPromised(path.dirname(this.data.dest)) .then( Promise.all(this.filesSrc.map((file) => renderAsPromised({ file }) .then(({ css }) => writeFileAsPromised(this.data.dest, css))) )) .then(() => { grunt.log.ok(`Written ${this.data.dest}`); done(); }) .catch(error => { grunt.log.error(error); done(false); }); }); };
const path = require('path'); const fs = require('fs'); const sass = require('node-sass'); const { promisify } = require('util'); const mkdirp = require('mkdirp'); const renderAsPromised = promisify(sass.render); const writeFileAsPromised = promisify(fs.writeFile); const mkdirpAsPromised = promisify(mkdirp); module.exports = function (grunt) { grunt.registerMultiTask('sass', 'compile sass', function () { let done = this.async(), promises; mkdirpAsPromised(path.dirname(this.data.dest)) .then(() => Promise.all(this.filesSrc.map((file) => renderAsPromised({ file }) .then(({ css }) => writeFileAsPromised(this.data.dest, css)) .then(() => grunt.log.ok(`Written ${this.data.dest}`)) ))) .then(done) .catch(error => { grunt.log.error(error); done(false); }); }); };
Fix grunt task on watch
Fix grunt task on watch
JavaScript
apache-2.0
stryker-mutator/stryker-mutator.github.io,stryker-mutator/stryker-mutator.github.io,stryker-mutator/stryker-mutator.github.io,stryker-mutator/stryker-mutator.github.io
--- +++ @@ -11,17 +11,13 @@ grunt.registerMultiTask('sass', 'compile sass', function () { let done = this.async(), promises; - mkdirpAsPromised(path.dirname(this.data.dest)) - .then( - Promise.all(this.filesSrc.map((file) => - renderAsPromised({ file }) - .then(({ css }) => writeFileAsPromised(this.data.dest, css))) - )) - .then(() => { - grunt.log.ok(`Written ${this.data.dest}`); - done(); - }) + .then(() => Promise.all(this.filesSrc.map((file) => + renderAsPromised({ file }) + .then(({ css }) => writeFileAsPromised(this.data.dest, css)) + .then(() => grunt.log.ok(`Written ${this.data.dest}`)) + ))) + .then(done) .catch(error => { grunt.log.error(error); done(false);
a942a1e476879f298cb06b4fd14a213f212aa081
public/designs/templates/lefttopright/javascripts/template.js
public/designs/templates/lefttopright/javascripts/template.js
$(document).ready(function() { alert("Yup, i'm here !"); });
$(document).ready(function() { var box_4_height = $(".box-4").height(); // Make box-2(the most left one) stay align with box-4 $(".box-2").css("margin-top", "-"+box_4_height+"px"); });
Make box-2 stay align with box-4
Make box-2 stay align with box-4 Signed-off-by: Fabio Teixeira <a90b0aa793b4509973a022e6fee8cf8a263dd84e@gmail.com> Signed-off-by: Thiago Ribeiro <25630c3dd4509f5915a846461794b51273be2039@hotmail.com>
JavaScript
agpl-3.0
larissa/noosfero,coletivoEITA/noosfero,hebertdougl/noosfero,coletivoEITA/noosfero,arthurmde/noosfero,coletivoEITA/noosfero-ecosol,AlessandroCaetano/noosfero,evandrojr/noosferogov,abner/noosfero,uniteddiversity/noosfero,tallysmartins/noosfero,uniteddiversity/noosfero,samasti/noosfero,CIRANDAS/noosfero-ecosol,vfcosta/noosfero,uniteddiversity/noosfero,vfcosta/noosfero,AlessandroCaetano/noosfero,AlessandroCaetano/noosfero,abner/noosfero,alexandreab/noosfero,coletivoEITA/noosfero-ecosol,alexandreab/noosfero,tallysmartins/noosfero,blogoosfero/noosfero,EcoAlternative/noosfero-ecosol,LuisBelo/tccnoosfero,evandrojr/noosferogov,larissa/noosfero,coletivoEITA/noosfero-ecosol,LuisBelo/tccnoosfero,marcosronaldo/noosfero,coletivoEITA/noosfero,abner/noosfero,AlessandroCaetano/noosfero,larissa/noosfero,hebertdougl/noosfero,alexandreab/noosfero,vfcosta/noosfero,samasti/noosfero,samasti/noosfero,AlessandroCaetano/noosfero,hebertdougl/noosfero,blogoosfero/noosfero,EcoAlternative/noosfero-ecosol,arthurmde/noosfero,larissa/noosfero,evandrojr/noosfero,abner/noosfero,marcosronaldo/noosfero,EcoAlternative/noosfero-ecosol,evandrojr/noosfero,coletivoEITA/noosfero-ecosol,EcoAlternative/noosfero-ecosol,samasti/noosfero,evandrojr/noosfero,blogoosfero/noosfero,tallysmartins/noosfero,marcosronaldo/noosfero,AlessandroCaetano/noosfero,macartur/noosfero,tallysmartins/noosfero,EcoAlternative/noosfero-ecosol,AlessandroCaetano/noosfero,arthurmde/noosfero,arthurmde/noosfero,abner/noosfero,samasti/noosfero,uniteddiversity/noosfero,evandrojr/noosfero,coletivoEITA/noosfero-ecosol,larissa/noosfero,vfcosta/noosfero,arthurmde/noosfero,abner/noosfero,LuisBelo/tccnoosfero,coletivoEITA/noosfero-ecosol,alexandreab/noosfero,marcosronaldo/noosfero,uniteddiversity/noosfero,coletivoEITA/noosfero,coletivoEITA/noosfero,tallysmartins/noosfero,blogoosfero/noosfero,coletivoEITA/noosfero,arthurmde/noosfero,macartur/noosfero,evandrojr/noosfero,tallysmartins/noosfero,LuisBelo/tccnoosfero,CIRANDAS/noosfero-ecosol,samasti/noosfero,alexandreab/noosfero,LuisBelo/tccnoosfero,vfcosta/noosfero,uniteddiversity/noosfero,marcosronaldo/noosfero,marcosronaldo/noosfero,evandrojr/noosfero,blogoosfero/noosfero,marcosronaldo/noosfero,macartur/noosfero,EcoAlternative/noosfero-ecosol,hebertdougl/noosfero,vfcosta/noosfero,evandrojr/noosferogov,coletivoEITA/noosfero,hebertdougl/noosfero,hebertdougl/noosfero,LuisBelo/tccnoosfero,larissa/noosfero,evandrojr/noosferogov,uniteddiversity/noosfero,macartur/noosfero,alexandreab/noosfero,evandrojr/noosferogov,abner/noosfero,evandrojr/noosferogov,tallysmartins/noosfero,CIRANDAS/noosfero-ecosol,blogoosfero/noosfero,larissa/noosfero,CIRANDAS/noosfero-ecosol,EcoAlternative/noosfero-ecosol,arthurmde/noosfero,alexandreab/noosfero,evandrojr/noosfero,evandrojr/noosferogov,hebertdougl/noosfero,CIRANDAS/noosfero-ecosol,macartur/noosfero,blogoosfero/noosfero,macartur/noosfero,macartur/noosfero
--- +++ @@ -1,3 +1,6 @@ $(document).ready(function() { - alert("Yup, i'm here !"); + var box_4_height = $(".box-4").height(); + + // Make box-2(the most left one) stay align with box-4 + $(".box-2").css("margin-top", "-"+box_4_height+"px"); });
03a1b9af8f4fcaa85534e3889a61ea395e5aa19d
test/src/doors.spec.js
test/src/doors.spec.js
const expect = require('chai').expect; const Room = require('../../src/rooms').Room; const Doors = require('../../src/doors').Doors; const Mocks = require('../mocks/mocks.js'); const testRoom = new Room(Mocks.Room); describe('Doors & Locks', () => { it('Should find an exit given a direction', () => { const found = Doors.findExit(testRoom, 'out'); expect(found.length === 1).to.be.true; }); });
'use strict'; const expect = require('chai').expect; const Room = require('../../src/rooms').Room; const Doors = require('../../src/doors').Doors; const Mocks = require('../mocks/mocks.js'); const testRoom = new Room(Mocks.Room); describe('Doors & Locks', () => { describe('findExit', () => { it('Should find an exit given a direction', () => { const found = Doors.findExit(testRoom, 'out'); expect(found.length === 1).to.be.true; }); it('Should not find an exit if the direction doesn\'t exist', () => { const found = Doors.findExit(testRoom, 'wat'); expect(found.length === 0).to.be.true; }); }); describe('updateDestination', () => { const getLocation = () => '1'; const player = { getLocation }; const dest = { getExits: () => [{ location: '1' }] }; it('should call a callback if the exit exists', () => { let called = false; Doors.updateDestination(player, dest, () => { called = true; }); expect(called).to.be.true; }); }); });
Set up dests for helper funcs in doors.js
Set up dests for helper funcs in doors.js
JavaScript
mit
seanohue/ranviermud,shawncplus/ranviermud,seanohue/ranviermud
--- +++ @@ -1,3 +1,5 @@ +'use strict'; + const expect = require('chai').expect; const Room = require('../../src/rooms').Room; const Doors = require('../../src/doors').Doors; @@ -7,9 +9,42 @@ describe('Doors & Locks', () => { - it('Should find an exit given a direction', () => { - const found = Doors.findExit(testRoom, 'out'); - expect(found.length === 1).to.be.true; + + describe('findExit', () => { + + it('Should find an exit given a direction', () => { + const found = Doors.findExit(testRoom, 'out'); + expect(found.length === 1).to.be.true; + }); + + it('Should not find an exit if the direction doesn\'t exist', () => { + const found = Doors.findExit(testRoom, 'wat'); + expect(found.length === 0).to.be.true; + }); + }); + describe('updateDestination', () => { + const getLocation = () => '1'; + const player = { getLocation }; + const dest = { + getExits: () => [{ + location: '1' + }] + }; + + it('should call a callback if the exit exists', () => { + let called = false; + Doors.updateDestination(player, dest, () => { + called = true; + }); + + expect(called).to.be.true; + + }); + + + }); + + });
6a359323b5a4b3a4630f65bfb62e1ed531ac01c7
defaults/preferences/prefs.js
defaults/preferences/prefs.js
pref("extensions.torbirdy.protected", false); pref("extensions.torbirdy.proxy", 0); pref("extensions.torbirdy.first_run", true); pref("extensions.torbirdy.warn", true);
pref("extensions.torbirdy.protected", false); pref("extensions.torbirdy.proxy", 0); pref("extensions.torbirdy.first_run", true); pref("extensions.torbirdy.warn", true); pref("extensions.torbirdy.startup_folder", false);
Update the preferences to reflect the folder select state
Update the preferences to reflect the folder select state
JavaScript
bsd-2-clause
ioerror/torbirdy,viggyprabhu/torbirdy,kartikm/torbirdy,DigiThinkIT/TorBirdy,kartikm/torbirdy,u451f/torbirdy,infertux/torbirdy,u451f/torbirdy,ioerror/torbirdy,viggyprabhu/torbirdy,infertux/torbirdy,DigiThinkIT/TorBirdy
--- +++ @@ -2,3 +2,4 @@ pref("extensions.torbirdy.proxy", 0); pref("extensions.torbirdy.first_run", true); pref("extensions.torbirdy.warn", true); +pref("extensions.torbirdy.startup_folder", false);
5b9936a84f03a49585d8a5570936b15ed2cff387
tests/dummy/config/environment.js
tests/dummy/config/environment.js
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created }, contentSecurityPolicy: { "script-src": "'self' 'unsafe-inline'", "font-src": "'self'", "style-src": "'self' 'unsafe-inline'", "img-src": "'self' data:" } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created }, contentSecurityPolicy: { "script-src": "'self' 'unsafe-inline'", "font-src": "'self'", "style-src": "'self' 'unsafe-inline'", "img-src": "'self' data:" } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/gloit-component'; } return ENV; };
Set the base url of the dummy app
Set the base url of the dummy app
JavaScript
mit
gloit/gloit-component,gloit/gloit-component
--- +++ @@ -47,7 +47,7 @@ } if (environment === 'production') { - + ENV.baseURL = '/gloit-component'; } return ENV;
ed6107f6bcf6dd0bbf917947d67d35a0a58e85c0
models/Users.js
models/Users.js
var mongoose = require('mongoose'); var UserSchema = new mongoose.Schema({ fname: String, lname: String, username: String, password: String, salt: String }); mongoose.model('User', UserSchema);
var mongoose = require('mongoose'); var crypto = require('crypto'); var jwt = require('jsonwebtoken'); var UserSchema = new mongoose.Schema({ fname: String, lname: String, username: String, password: String, salt: String }); UserSchema.methods.setPassword = function(password) { this.salt = crypto.randomBytes(16).toString('hex'); this.password = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex'); }; UserSchema.methods.validPassword = function(password) { var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex'); return this.password === hash; }; UserSchema.methods.generateJWT = function() { var today = new Date(); var exp = new Date(today); exp.setDate(today.getDate() + 60); return jwt.sign({ _id: this._id, username: this.username, exp: parseInt(exp.getTime() / 1000) }, 'SECRET'); }; mongoose.model('User', UserSchema);
Create setPassword validPassword and generateJWT methods on User model
Create setPassword validPassword and generateJWT methods on User model
JavaScript
mit
zachloubier/stocks,zachloubier/stocks
--- +++ @@ -1,4 +1,6 @@ var mongoose = require('mongoose'); +var crypto = require('crypto'); +var jwt = require('jsonwebtoken'); var UserSchema = new mongoose.Schema({ fname: String, @@ -8,4 +10,28 @@ salt: String }); +UserSchema.methods.setPassword = function(password) { + this.salt = crypto.randomBytes(16).toString('hex'); + + this.password = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex'); +}; + +UserSchema.methods.validPassword = function(password) { + var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex'); + + return this.password === hash; +}; + +UserSchema.methods.generateJWT = function() { + var today = new Date(); + var exp = new Date(today); + exp.setDate(today.getDate() + 60); + + return jwt.sign({ + _id: this._id, + username: this.username, + exp: parseInt(exp.getTime() / 1000) + }, 'SECRET'); +}; + mongoose.model('User', UserSchema);
9ccff0afcc20c515804a38e8828317451b15e1bd
lib/controllers/geo-tagging.js
lib/controllers/geo-tagging.js
'use strict'; var request = require('request'); var Q = require('q'); var config = require('../config'); const plugins = require('../../plugins'); const geoTagController = plugins.getFirst('geo-tag-controller'); if(!geoTagController) { throw new Error('Missing a geo-tag-controller plugin!'); } function deg(w) { w = w % 360; return w < 0 ? w + 360 : w; } exports.save = function(req, res, next) { // Check with the CIP to ensure that the asset has not already been geotagged. var collection = req.params.collection; var id = req.params.id; var latitude = parseFloat(req.body.latitude); var longitude = parseFloat(req.body.longitude); // Checking if heading is a key in the body, as a valid heading can be 0. // Heading is also converted to a degree between 0 and 360 var heading = 'heading' in req.body ? deg(parseFloat(req.body.heading)) : null; if (!config.features.geoTagging) { throw new Error('Geotagging is disabled.'); } // Save the new coordinates to the CIP. geoTagController.save({ collection, id, latitude, longitude, heading }) .then(geoTagController.updateIndex) .then(function(result) { res.json(result); }, next); };
'use strict'; var request = require('request'); var Q = require('q'); var config = require('../config'); const plugins = require('../../plugins'); const geoTagController = plugins.getFirst('geo-tag-controller'); if(!geoTagController) { throw new Error('Missing a geo-tag-controller plugin!'); } function deg(w) { w = w % 360; return w < 0 ? w + 360 : w; } exports.save = function(req, res, next) { // Check with the CIP to ensure that the asset has not already been geotagged. var collection = req.params.collection; var id = req.params.id; var latitude = parseFloat(req.body.latitude); var longitude = parseFloat(req.body.longitude); const userId = req.user.id; // Checking if heading is a key in the body, as a valid heading can be 0. // Heading is also converted to a degree between 0 and 360 var heading = 'heading' in req.body ? deg(parseFloat(req.body.heading)) : null; if (!config.features.geoTagging) { throw new Error('Geotagging is disabled.'); } // Save the new coordinates to the CIP. geoTagController.save({ collection, id, latitude, longitude, heading, userId, }) .then(geoTagController.updateIndex) .then(function(result) { res.json(result); }, next); };
Add userid to geotagging callback
Add userid to geotagging callback
JavaScript
mit
CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder
--- +++ @@ -21,6 +21,7 @@ var id = req.params.id; var latitude = parseFloat(req.body.latitude); var longitude = parseFloat(req.body.longitude); + const userId = req.user.id; // Checking if heading is a key in the body, as a valid heading can be 0. // Heading is also converted to a degree between 0 and 360 var heading = 'heading' in req.body ? @@ -37,7 +38,8 @@ id, latitude, longitude, - heading + heading, + userId, }) .then(geoTagController.updateIndex) .then(function(result) {
8fe68b5a70a10d742d39992714f3b80ca620f88e
tests/requests/home.js
tests/requests/home.js
'use strict'; var app = require('../../app'); var should = require('should'); var request = require('supertest')(app); describe('No controller home', function() { it('Must return status 200 when doing GET', function(done) { request.get('/') .end(function(err, res) { res.status.should.eql(200); }); }); });
'use strict'; var server = require('../../server'); var should = require('should'); var request = require('supertest')(server); describe('The home controller', function() { it('Must return status 200 when doing GET', function(done) { request.get('/') .end(function(err, res) { res.status.should.eql(200); done(); }); }); it('Must to go for route / when doing GET /exit', function(done) { request.get('/exit') .end(function(err, res) { res.headers.location.should.eql('/'); done(); }); }); });
Add other test: Must to go for route / when doing GET /exit
Add other test: Must to go for route / when doing GET /exit
JavaScript
mit
brenopolanski/coffee-club,brenopolanski/coffee-club
--- +++ @@ -1,14 +1,23 @@ 'use strict'; -var app = require('../../app'); +var server = require('../../server'); var should = require('should'); -var request = require('supertest')(app); +var request = require('supertest')(server); -describe('No controller home', function() { +describe('The home controller', function() { it('Must return status 200 when doing GET', function(done) { request.get('/') - .end(function(err, res) { - res.status.should.eql(200); + .end(function(err, res) { + res.status.should.eql(200); + done(); + }); + }); + + it('Must to go for route / when doing GET /exit', function(done) { + request.get('/exit') + .end(function(err, res) { + res.headers.location.should.eql('/'); + done(); }); }); });
7f076bd1b43cc53b172c353cf24ee274ea7b5db3
lib/helpers/metadata.js
lib/helpers/metadata.js
'use strict'; var WM = require('es6-weak-map'); var hasNativeWeakMap = require('es6-weak-map/is-native-implemented'); // WeakMap for storing metadata var metadata = hasNativeWeakMap ? new WeakMap() : new WM(); module.exports = metadata;
'use strict'; // WeakMap for storing metadata var WM = require('es6-weak-map'); var metadata = new WM(); module.exports = metadata;
Remove conditional use of es6-weak-map
Fix: Remove conditional use of es6-weak-map
JavaScript
mit
phated/undertaker,gulpjs/undertaker
--- +++ @@ -1,9 +1,7 @@ 'use strict'; +// WeakMap for storing metadata var WM = require('es6-weak-map'); -var hasNativeWeakMap = require('es6-weak-map/is-native-implemented'); - -// WeakMap for storing metadata -var metadata = hasNativeWeakMap ? new WeakMap() : new WM(); +var metadata = new WM(); module.exports = metadata;
d962869bf6059568f39d4c8b5af801cfdcf30d0b
js/templates.js
js/templates.js
var Templates = {}; Templates.ItemListingTemplate = _.template('\ <div class="item media">\ <img class="pull-left" src="<%= imageUrl %>" />\ <div class="media-body">\ <h3 class="media-heading"><%= name %></h3>\ <div class="item-location"><span class="glyphicon glyphicon-globe"></span> <%= location %></div>\ <div class="item-price"><span class="glyphicon glyphicon-usd"></span><%= price %></div>\ <div class="item-buyers"><%= buyers.length %></div>\ </div>\ </div>');
var Templates = {}; Templates.ItemListingTemplate = _.template('\ <div class="item media">\ <img class="pull-left" src="<%= imageUrl %>" />\ <div class="media-body">\ <h3 class="media-heading"><%= name %></h3>\ <div class="item-location"><span class="glyphicon glyphicon-globe"></span> <%= location %></div>\ <div class="item-price"><span class="glyphicon glyphicon-usd"></span><%= price %></div>\ <div class="item-buyers"><span class="glyphicon glyphicon-user"></span><%= buyers.length %></div>\ </div>\ </div>');
Add icon for amount of buyers.
Add icon for amount of buyers.
JavaScript
mit
burnflare/CrowdBuy,burnflare/CrowdBuy
--- +++ @@ -7,6 +7,6 @@ <h3 class="media-heading"><%= name %></h3>\ <div class="item-location"><span class="glyphicon glyphicon-globe"></span> <%= location %></div>\ <div class="item-price"><span class="glyphicon glyphicon-usd"></span><%= price %></div>\ - <div class="item-buyers"><%= buyers.length %></div>\ + <div class="item-buyers"><span class="glyphicon glyphicon-user"></span><%= buyers.length %></div>\ </div>\ </div>');
9d7b781e57e885233eb5a16e6809ed528d0abe87
examples/blog/thinky.js
examples/blog/thinky.js
//var thinky = require('thinky'); var thinky = require('/home/michel/projects/thinky/lib/index.js'); var config = require('./config'); // Initialize thinky // The most important thing is to initialize the pool of connection thinky.init({ host: config.host, port: config.port, db: config.db }); exports.thinky = thinky;
var thinky = require('thinky'); var config = require('./config'); // Initialize thinky // The most important thing is to initialize the pool of connection thinky.init({ host: config.host, port: config.port, db: config.db }); exports.thinky = thinky;
Switch to the npm library
Switch to the npm library
JavaScript
mit
gutenye/thinky-websocket,JohnyDays/thinky,soplakanets/thinky,rasapetter/thinky,mbroadst/thinky,bprymicz/thinky,JohnyDays/thinky,gutenye/thinky-websocket,davewasmer/thinky,gjuchault/thinky,soplakanets/thinky,davewasmer/thinky,gutenye/thinky-websocket,rasapetter/thinky
--- +++ @@ -1,5 +1,4 @@ -//var thinky = require('thinky'); -var thinky = require('/home/michel/projects/thinky/lib/index.js'); +var thinky = require('thinky'); var config = require('./config'); // Initialize thinky
157f5524db00970c99cb91e5e1f65e0be31fb245
website/app/js/controllers.js
website/app/js/controllers.js
function HomeController($scope) { } function ProjectsController($scope, Restangular) { var allProjects = Restangular.all('projects'); allProjects.getList().then(function(projects) { $scope.projects = projects; }); Restangular.one("projects", "a").customGET("tree").then(function(tree) { console.dir(tree); $scope.projectTree = tree; }); // Restangular.oneUrl("datadirs", "http://localhost:5000/datadirs/tree?apikey=4a3ec8f43cc511e3ba368851fb4688d4") // .get().then(function(tree) { // console.dir(tree); // }) } function ChangesController($scope) { } function ProvenanceController($scope) { } function AboutController($scope) { } function ContactController($scope) { } function EventController($scope) { }
function HomeController($scope) { } function ProjectsController($scope, Restangular, $http) { var allProjects = Restangular.all('projects'); allProjects.getList().then(function(projects) { $scope.projects = projects; }); Restangular.one("projects", "a").customGET("tree").then(function(tree) { $scope.projectTree = tree; }); } function ChangesController($scope) { } function ProvenanceController($scope) { } function AboutController($scope) { } function ContactController($scope) { } function EventController($scope) { }
Remove testing code for going to materials commons.
Remove testing code for going to materials commons.
JavaScript
mit
materials-commons/materials,materials-commons/materials
--- +++ @@ -3,21 +3,15 @@ } -function ProjectsController($scope, Restangular) { +function ProjectsController($scope, Restangular, $http) { var allProjects = Restangular.all('projects'); allProjects.getList().then(function(projects) { $scope.projects = projects; }); Restangular.one("projects", "a").customGET("tree").then(function(tree) { - console.dir(tree); $scope.projectTree = tree; }); - -// Restangular.oneUrl("datadirs", "http://localhost:5000/datadirs/tree?apikey=4a3ec8f43cc511e3ba368851fb4688d4") -// .get().then(function(tree) { -// console.dir(tree); -// }) } function ChangesController($scope) {
224c56ed7da455e9ec8105e6efd088a4cd8eade2
portal/js/controllers/ChartEditController.js
portal/js/controllers/ChartEditController.js
App.ChartEditController = App.AuthenticationController.extend({ actions: { registerQuery: function() { console.log('registering a query'); var chart = this.get('model'); chart.save(); } } });
App.ChartEditController = App.AuthenticationController.extend({ actions: { registerQuery: function() { console.log('registering a query'); var chart = this.get('model'); // Put a dummy chartdata in the chart to trigger the async loading of the chart data // Since the request will be fulfilled by the query api, don't need to save the record. var chartdata = this.store.createRecord('chartdata'); chartdata.set('id', chart.id); chart.get('chartdata').then(function(chartdatas){ chartdatas.pushObject(chartdata); chart.save(); }) } } });
Create a dummy chart data object so the chart data loads async
Create a dummy chart data object so the chart data loads async
JavaScript
apache-2.0
with-regard/regard-website
--- +++ @@ -3,7 +3,16 @@ registerQuery: function() { console.log('registering a query'); var chart = this.get('model'); - chart.save(); + + // Put a dummy chartdata in the chart to trigger the async loading of the chart data + // Since the request will be fulfilled by the query api, don't need to save the record. + var chartdata = this.store.createRecord('chartdata'); + chartdata.set('id', chart.id); + + chart.get('chartdata').then(function(chartdatas){ + chartdatas.pushObject(chartdata); + chart.save(); + }) } } });
6caba9f16599101ddf710aa4f322865341582c11
lib/foodlogiq-client/users.js
lib/foodlogiq-client/users.js
module.exports = function(conn) { return { list: function(businessId, callback) { conn.get('/users?businessId=' + businessId, callback); } } };
module.exports = function(conn) { return { show: function(callback) {conn.get('/user', callback);}, list: function(businessId, callback) { conn.get('/users?businessId=' + businessId, callback); } } };
Add a wrapper method for retrieving the current API user
Add a wrapper method for retrieving the current API user The API route for this already existed, but there was no wrapper method.
JavaScript
mit
ventres/foodlogiq-node,FoodLogiQ/foodlogiq-node
--- +++ @@ -1,5 +1,6 @@ module.exports = function(conn) { return { + show: function(callback) {conn.get('/user', callback);}, list: function(businessId, callback) { conn.get('/users?businessId=' + businessId, callback); }
3a136a01d0e66bf5a0697fe031c0eb9eab0b81c9
app/server/methods/permissions.js
app/server/methods/permissions.js
Meteor.methods({ addSingleUserPermissions(userId, groupIds) { if (groupIds.length > 0) { groupIds.forEach(groupId => { Permissions.insert({ userId, groupId }); }); } return true; } });
Meteor.methods({ addSingleUserPermissions(userId, groupIds) { // Remove existing user permissions Permissions.remove({ userId }); // add new permissions, if any group IDs provided if (groupIds.length > 0) { groupIds.forEach(groupId => { Permissions.insert({ userId, groupId }); }); } return true; } });
Delete existing permission prior to inserting new set
Delete existing permission prior to inserting new set
JavaScript
agpl-3.0
brylie/juhani-wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing
--- +++ @@ -1,5 +1,9 @@ Meteor.methods({ addSingleUserPermissions(userId, groupIds) { + // Remove existing user permissions + Permissions.remove({ userId }); + + // add new permissions, if any group IDs provided if (groupIds.length > 0) { groupIds.forEach(groupId => { Permissions.insert({ userId, groupId });
28415ab520751159162e15d42b205352c6ce1e73
src/js/components/form.js
src/js/components/form.js
import React from 'react' import ReactDOM from 'react-dom' import DefaultProps from '../default_props.js' export default class Form extends React.Component { static displayName = 'FriggingBootstrap.Form' static defaultProps = { layout: DefaultProps.layout, } static propTypes = { formHtml: React.PropTypes.shape({ className: React.PropTypes.string, }), layout: React.PropTypes.string, children: React.PropTypes.any.isRequired, } _formHtml() { const className = this.props.layout ? `form-${this.props.layout}` : '' return Object.assign({}, this.props.formHtml, { ref: 'form', className: `${this.props.formHtml.className || ''} ${className}`.trim(), }) } formData() { const formElement = ReactDOM.findDOMNode(this.refs.form) return new FormData(formElement) } render() { return ( <form {...this._formHtml()}> {this.props.children} </form> ) } }
import React from 'react' import ReactDOM from 'react-dom' export default class Form extends React.Component { static displayName = 'FriggingBootstrap.Form' static defaultProps = { layout: 'vertical', } static propTypes = { formHtml: React.PropTypes.shape({ className: React.PropTypes.string, }), layout: React.PropTypes.string, children: React.PropTypes.any.isRequired, } _formHtml() { const className = this.props.layout ? `form-${this.props.layout}` : '' return Object.assign({}, this.props.formHtml, { ref: 'form', className: `${this.props.formHtml.className || ''} ${className}`.trim(), }) } formData() { const formElement = ReactDOM.findDOMNode(this.refs.form) return new FormData(formElement) } render() { return ( <form {...this._formHtml()}> {this.props.children} </form> ) } }
Remove DefaultProps.js From Form Component
Remove DefaultProps.js From Form Component Remove defaultProps.js from Form component layout prop as it is no longer in defaultProps.js
JavaScript
mit
frig-js/frigging-bootstrap,frig-js/frigging-bootstrap
--- +++ @@ -1,12 +1,11 @@ import React from 'react' import ReactDOM from 'react-dom' -import DefaultProps from '../default_props.js' export default class Form extends React.Component { static displayName = 'FriggingBootstrap.Form' static defaultProps = { - layout: DefaultProps.layout, + layout: 'vertical', } static propTypes = {
13752fc80af365ae8c80effd323c8ea2e9bb637f
assets/javascripts/application.js
assets/javascripts/application.js
//= require "lib/moment.min" //= require "lib/jquery-2.0.3" //= require "lib/handlebars-v1.1.2" //= require "lib/ember" //= require "lib/ember-data" //= require_self //= require "models" //= require "views" //= require "helpers" //= require "./routes/authenticated_route" //= require_tree "./controllers" //= require_tree "./routes" window.App = Em.Application.create({LOG_TRANSITIONS: true}) App.ApplicationSerializer = DS.ActiveModelSerializer.extend({}) App.ApplicationAdapter = DS.RESTAdapter.reopen({namespace: "api"}) App.ApplicationView = Em.View.extend({classNames: ["container"]}) App.Router.map(function() { // login this.route("login"); // rooms this.resource("rooms", function() { this.route("new"); this.resource("room", {path: "/:room_id"}, function() { this.route("edit"); }); }); // users // users/new // users/:user_id this.resource("users", function() { this.route("new"); this.resource("user", {path: "/:user_id"}, function() { this.route("edit"); }); }); });
//= require "lib/moment.min" //= require "lib/jquery-2.0.3" //= require "lib/handlebars-v1.1.2" //= require "lib/ember" //= require "lib/ember-data" //= require_self //= require "models" //= require "views" //= require "helpers" //= require "./routes/authenticated_route" //= require_tree "./controllers" //= require_tree "./routes" window.App = Em.Application.create({LOG_TRANSITIONS: true}) App.ApplicationSerializer = DS.ActiveModelSerializer.extend({}) App.ApplicationAdapter = DS.ActiveModelAdapter.reopen({namespace: "api"}) App.ApplicationView = Em.View.extend({classNames: ["container"]}) App.Router.map(function() { // login this.route("login"); // rooms this.resource("rooms", function() { this.route("new"); this.resource("room", {path: "/:room_id"}, function() { this.route("edit"); }); }); // users // users/new // users/:user_id this.resource("users", function() { this.route("new"); this.resource("user", {path: "/:user_id"}, function() { this.route("edit"); }); }); });
Use ActiveModelAdapter instead of RESTAdapter
Use ActiveModelAdapter instead of RESTAdapter
JavaScript
mit
louishawkins/mogo-chat,HashNuke/mogo-chat,sashafklein/bloc-mogo,di-stars/mogo-chat,louishawkins/mogo-chat,sashafklein/bloc-mogo,di-stars/mogo-chat,HashNuke/mogo-chat,HashNuke/mogo-chat,sashafklein/bloc-mogo,di-stars/mogo-chat,louishawkins/mogo-chat
--- +++ @@ -15,7 +15,7 @@ window.App = Em.Application.create({LOG_TRANSITIONS: true}) App.ApplicationSerializer = DS.ActiveModelSerializer.extend({}) -App.ApplicationAdapter = DS.RESTAdapter.reopen({namespace: "api"}) +App.ApplicationAdapter = DS.ActiveModelAdapter.reopen({namespace: "api"}) App.ApplicationView = Em.View.extend({classNames: ["container"]})
ad76d7022d388e7b7a0e4f24c224dc29e4fa03ee
webpack/webpack-dev-server.js
webpack/webpack-dev-server.js
var Express = require('express'); var webpack = require('webpack'); var config = require('../src/config'); var webpackConfig = require('./dev.config'); var compiler = webpack(webpackConfig); var host = process.env.HOST || 'localhost'; var port = parseInt(config.port, 10) + 1 || 3001; var serverOptions = { contentBase: 'http://' + host + ':' + port, quiet: true, noInfo: true, hot: true, inline: true, lazy: false, publicPath: webpackConfig.output.publicPath, headers: {'Access-Control-Allow-Origin': '*'}, stats: {colors: true} }; var app = new Express(); app.use(require('webpack-dev-middleware')(compiler, serverOptions)); app.use(require('webpack-hot-middleware')(compiler)); app.listen(port, function onAppListening(err) { if (err) { console.error(err); } else { console.info('==> 🚧 Webpack development server listening on port %s', port); } });
var Express = require('express'); var webpack = require('webpack'); var config = require('../src/config'); var webpackConfig = require('./dev.config'); var compiler = webpack(webpackConfig); var host = config.host || 'localhost'; var port = (config.port + 1) || 3001; var serverOptions = { contentBase: 'http://' + host + ':' + port, quiet: true, noInfo: true, hot: true, inline: true, lazy: false, publicPath: webpackConfig.output.publicPath, headers: {'Access-Control-Allow-Origin': '*'}, stats: {colors: true} }; var app = new Express(); app.use(require('webpack-dev-middleware')(compiler, serverOptions)); app.use(require('webpack-hot-middleware')(compiler)); app.listen(port, function onAppListening(err) { if (err) { console.error(err); } else { console.info('==> 🚧 Webpack development server listening on port %s', port); } });
Use host + port from config
Use host + port from config
JavaScript
mit
hitripod/react-redux-universal-hot-example,thomastanhb/ericras,user512/teacher_dashboard,erikras/react-redux-universal-hot-example,mscienski/stpauls,ThatCheck/AutoLib,mull/require_hacker_error_reproduction,ames89/keystone-react-redux,hldzlk/wuhao,bertho-zero/react-redux-universal-hot-example,huangc28/palestine-2,tonykung06/realtime-exchange-rates,ercangursoy/react-dev,CalebEverett/soulpurpose,mscienski/stpauls,Trippstan/elephonky,elbstack/elbstack-hackreact-web-3,ThatCheck/AutoLib,avantcontra/react-redux-custom-starter,sfarthin/youtube-search,tanvip/hackPrinceton,bdefore/universal-redux,sseppola/react-redux-universal-hot-example,frankleng/react-redux-universal-hot-example,sunh11373/t648,RomanovRoman/react-redux-universal-hot-example,TracklistMe/client-react,Widcket/sia,eastonqiu/frontend,trueter/react-redux-universal-hot-example,hldzlk/wuhao,runnables/react-redux-universal-hot-example,Widcket/sia,tpphu/react-pwa,sanyamagrawal/royalgeni,PhilNorfleet/pBot,twomoonsfactory/custom-poll,quicksnap/react-redux-universal-hot-example,TracklistMe/client-web,delwiv/saphir,Kronenberg/WebLabsTutorials,kiyonish/kiyonishimura,lordakshaya/pages,Druddigon/react-redux-learn,Widcket/sia,prgits/react-product,delwiv/tactill-techtest,gihrig/react-redux-universal-hot-example,fiTTrail/fiTTrail,thekevinscott/react-redux-universal-starter-kit,ames89/keystone-react-redux,ipbrennan90/movesort-app,hank7444/react-redux-universal-hot-example,dumbNickname/oasp4js-goes-react,yomolify/cc_material,svsool/react-redux-universal-hot-example,fforres/coworks,guymorita/creditTiger,nathanielks/universal-redux,codejunkienick/katakana,jeremiahrhall/react-redux-universal-hot-example,dieface/react-redux-universal-hot-example,TonyJen/react-redux-universal-hot-example,TribeMedia/react-redux-universal-hot-example,robertSahm/port,Xvakin/quiz,PhilNorfleet/pBot,thingswesaid/seed,EnrikoLabriko/react-redux-universal-hot-example,jairoandre/lance-web-hot,delwiv/saphir,chrisslater/snapperfish,DelvarWorld/some-game,bdefore/react-redux-universal-hot-example,vidaaudrey/avanta,tpphu/react-pwa,danieloliveira079/healthy-life-app,Dengo/bacon-bacon,micooz/react-redux-universal-hot-example,Widcket/react-boilerplate,bazanowsky/react-ssr-exercise,AndriyShepitsen/svredux,MarkPhillips7/happy-holidays,bdefore/universal-redux,codejunkienick/katakana,nathanielks/universal-redux,sars/appetini-front,hokustalkshow/friend-landing-page,andbet39/reactPress,ptim/react-redux-universal-hot-example
--- +++ @@ -5,8 +5,8 @@ var webpackConfig = require('./dev.config'); var compiler = webpack(webpackConfig); -var host = process.env.HOST || 'localhost'; -var port = parseInt(config.port, 10) + 1 || 3001; +var host = config.host || 'localhost'; +var port = (config.port + 1) || 3001; var serverOptions = { contentBase: 'http://' + host + ':' + port, quiet: true,
d1e7f6719926b94cef11f276e1c13ec04adf59c4
themes/janeswalk/js/components/pages/Walk/Team/ConnectionLinks.js
themes/janeswalk/js/components/pages/Walk/Team/ConnectionLinks.js
import { createElement as ce } from 'react'; const connectTypes = require('../../../../json/ConnectionTypes.json'); const ConnectionLinks = ({ name: memberName, connections }) => ( ce('div', { className: 'btn-toolbar' }, connectTypes .filter(c => connections[c.name]) .map(({ prefix, match, name, style }, i) => ( ce('a', { key: `connect${name}${i}`, className: 'btn', href: `${memberName.match(match) ? '' : prefix}${memberName}`, target: '_blank', }, ce('i', { className: style }), ) ) )) ); export default ConnectionLinks;
import { createElement as ce } from 'react'; const connectTypes = [{ name: 'twitter', prefix: 'http://twitter.com/', match: '^(https?://(www.)?twitter.com|@)?(.*)$', style: 'fa fa-twitter', }, { name: 'facebook', prefix: 'http://facebook.com/', match: '^(https?://)?((www.)?(facebook.com)/?)?(.*)$', style: 'fa fa-facebook', }, { name: 'email', prefix: 'mailto:', match: '(mailto:)?(.*)$', style: 'fa fa-envelope-o', }, { name: 'website', prefix: '//', match: '^(https?://)?(.*)$', style: 'fa fa-globe', }]; function getLink({ connections, match, name, prefix }) { const matches = (connections[name] || '').match(match); if (matches) { const unprefix = matches[matches.length - 1]; return `${prefix}${unprefix}`; } return ''; } const ConnectionLinks = ({ name: memberName, connections }) => { debugger; return ( ce('div', { className: 'btn-toolbar' }, connectTypes .filter(c => connections[c.name]) .map(({ prefix, match, name, style }, i) => ( ce('a', { key: `connect${name}${i}`, className: 'btn', href: getLink({ connections, name, prefix, match }), target: '_blank', }, ce('i', { className: style }), ) ) )) ); }; export default ConnectionLinks;
Fix the social connection links
Fix the social connection links
JavaScript
mit
jkoudys/janeswalk-web,jkoudys/janeswalk-web,jkoudys/janeswalk-web
--- +++ @@ -1,8 +1,37 @@ import { createElement as ce } from 'react'; -const connectTypes = require('../../../../json/ConnectionTypes.json'); +const connectTypes = [{ + name: 'twitter', + prefix: 'http://twitter.com/', + match: '^(https?://(www.)?twitter.com|@)?(.*)$', + style: 'fa fa-twitter', +}, { + name: 'facebook', + prefix: 'http://facebook.com/', + match: '^(https?://)?((www.)?(facebook.com)/?)?(.*)$', + style: 'fa fa-facebook', +}, { + name: 'email', + prefix: 'mailto:', + match: '(mailto:)?(.*)$', + style: 'fa fa-envelope-o', +}, { + name: 'website', + prefix: '//', + match: '^(https?://)?(.*)$', + style: 'fa fa-globe', +}]; -const ConnectionLinks = ({ name: memberName, connections }) => ( +function getLink({ connections, match, name, prefix }) { + const matches = (connections[name] || '').match(match); + if (matches) { + const unprefix = matches[matches.length - 1]; + return `${prefix}${unprefix}`; + } + return ''; +} + +const ConnectionLinks = ({ name: memberName, connections }) => { debugger; return ( ce('div', { className: 'btn-toolbar' }, connectTypes .filter(c => connections[c.name]) @@ -10,13 +39,13 @@ ce('a', { key: `connect${name}${i}`, className: 'btn', - href: `${memberName.match(match) ? '' : prefix}${memberName}`, + href: getLink({ connections, name, prefix, match }), target: '_blank', }, ce('i', { className: style }), ) ) )) -); +); }; export default ConnectionLinks;