commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
02ee190d7383336953c7dde6d3e4f50285a7d113
src/interface/common/Ad.js
src/interface/common/Ad.js
import React from 'react'; import PropTypes from 'prop-types'; class Ad extends React.PureComponent { static propTypes = { style: PropTypes.object, }; componentDidMount() { (window.adsbygoogle = window.adsbygoogle || []).push({}); } render() { const { style, ...others } = this.props; const props = {}; if (!others['data-ad-slot']) { // Default to responsive props['data-ad-slot'] = '5976455458'; props['data-ad-format'] = 'auto'; props['data-full-width-responsive'] = 'true'; } return ( <ins className="adsbygoogle" style={style ? { display: 'block', ...style } : { display: 'block' }} data-ad-client="ca-pub-8048055232081854" {...props} {...others} /> ); } } export default Ad;
import React from 'react'; import PropTypes from 'prop-types'; class Ad extends React.PureComponent { static propTypes = { style: PropTypes.object, }; componentDidMount() { try { (window.adsbygoogle = window.adsbygoogle || []).push({}); } catch (err) { // "adsbygoogle.push() error: No slot size for availableWidth=0" error that I can't explain console.error(err); } } render() { const { style, ...others } = this.props; const props = {}; if (!others['data-ad-slot']) { // Default to responsive props['data-ad-slot'] = '5976455458'; props['data-ad-format'] = 'auto'; props['data-full-width-responsive'] = 'true'; } return ( <ins className="adsbygoogle" style={style ? { display: 'block', ...style } : { display: 'block' }} data-ad-client="ca-pub-8048055232081854" {...props} {...others} /> ); } } export default Ad;
Fix crash caused by google adsense
Fix crash caused by google adsense
JavaScript
agpl-3.0
WoWAnalyzer/WoWAnalyzer,anom0ly/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,fyruna/WoWAnalyzer,fyruna/WoWAnalyzer,ronaldpereira/WoWAnalyzer,anom0ly/WoWAnalyzer,sMteX/WoWAnalyzer,anom0ly/WoWAnalyzer,Juko8/WoWAnalyzer,ronaldpereira/WoWAnalyzer,yajinni/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,Juko8/WoWAnalyzer,ronaldpereira/WoWAnalyzer,sMteX/WoWAnalyzer,fyruna/WoWAnalyzer,yajinni/WoWAnalyzer,sMteX/WoWAnalyzer,yajinni/WoWAnalyzer,anom0ly/WoWAnalyzer,yajinni/WoWAnalyzer,Juko8/WoWAnalyzer
a96f3a13dc3a80d18ca7bc2fec5268c453c24533
src/react-chayns-personfinder/utils/normalizeOutput.js
src/react-chayns-personfinder/utils/normalizeOutput.js
export default function normalizeOutput(type, value) { return { type, name: value.name, firstName: value.firstName, lastName: value.lastName, personId: value.personId, userId: value.userId, siteId: value.siteId, locationId: value.locationId, isFriend: value.isFriend, }; }
import { FRIEND_RELATION, LOCATION_RELATION, PERSON_RELATION, PERSON_UNRELATED, } from '../constants/relationTypes'; export default function normalizeOutput(type, value) { const newType = (type === PERSON_RELATION || type === PERSON_UNRELATED || type === FRIEND_RELATION) ? PERSON_RELATION : LOCATION_RELATION; return { type: newType, name: value.name, firstName: value.firstName, lastName: value.lastName, personId: value.personId, userId: value.userId, siteId: value.siteId, locationId: value.locationId, isFriend: value.isFriend, }; }
Add normalization of type to prevent wrong types
:bug: Add normalization of type to prevent wrong types
JavaScript
mit
TobitSoftware/chayns-components,TobitSoftware/chayns-components,TobitSoftware/chayns-components
046b77894ef1df26a411ae2ca808936d920632c9
to.etc.domui/src/resources/themes/domui/style.props.js
to.etc.domui/src/resources/themes/domui/style.props.js
/* * "domui" stylesheet properties. */ font_family='Verdana, Geneva, "DejaVu Sans", sans-serif'; font_size="11px"; hdr_font_size="14px"; fixed_font_family='Courier New, Courier, monospace'; fixed_font_size="11px"; defaultbutton_height=23; window_title_font_size='15px';
/* * "blue" stylesheet properties. */ font_family='Verdana, Geneva, "DejaVu Sans", sans-serif'; //font_family='Verdana, Tahoma, helvetica, sans-serif'; font_size="11px"; hdr_font_size="14px"; fixed_font_family='Courier New, Courier, monospace'; fixed_font_size="11px"; //special_font = "Verdana, Tahoma, helvetica, sans-serif"; special_font = "Arial, Helvetica, sans-serif"; //special_font = "Biolinum2, Courier, serif"; special_font_size = "13px"; button_font_family='Verdana, Geneva, "DejaVu Sans", sans-serif'; button_font_size="11px"; defaultbutton_height=23; window_title_font_size='15px';
Make both style properties equal
Make both style properties equal
JavaScript
lgpl-2.1
fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui
f5484310a9e52d1c7786d111486882dd94959a98
src/website/app/demos/Flex/components/Flex.js
src/website/app/demos/Flex/components/Flex.js
/* @flow */ import { createStyledComponent, pxToEm } from '../../../../../library/styles'; import _Flex from '../../../../../library/Flex'; type Props = { gutterWidth?: number | string, theme: Object }; export const containerStyles = ({ gutterWidth: propGutterSize, theme }: Props) => { const gutterWidth = propGutterSize === undefined ? 'md' : propGutterSize; const gutter = typeof gutterWidth === 'number' ? pxToEm(gutterWidth / 2) : `${parseFloat(theme[`space_inline_${gutterWidth}`] || gutterWidth) / 2}em`; const offset = gutterWidth ? `calc(${gutter} - 4px)` : -4; return { position: 'relative', '&::before': { border: `1px dotted ${theme.color_theme_30}`, bottom: -4, content: '""', left: offset, position: 'absolute', right: offset, top: -4, zIndex: -1 } }; }; export default createStyledComponent(_Flex, (props) => ({ ...containerStyles(props) }));
/* @flow */ import { createStyledComponent, pxToEm } from '../../../../../library/styles'; import _Flex from '../../../../../library/Flex'; type Props = { gutterWidth?: number | string, theme: Object }; export const containerStyles = ({ gutterWidth: propGutterSize, theme }: Props) => { const gutterWidth = propGutterSize === undefined ? 'md' : propGutterSize; const gutter = typeof gutterWidth === 'number' ? pxToEm(gutterWidth / 2) : `${parseFloat(theme[`space_inline_${gutterWidth}`] || gutterWidth) / 2}em`; const offset = gutterWidth ? `calc(${gutter} - 4px)` : -4; return { position: 'relative', zIndex: 1, '&::before': { border: `1px dotted ${theme.color_theme_30}`, bottom: -4, content: '""', left: offset, position: 'absolute', right: offset, top: -4, zIndex: -1 } }; }; export default createStyledComponent(_Flex, (props) => ({ ...containerStyles(props) }));
Fix display issue with Layout examples
chore(website): Fix display issue with Layout examples
JavaScript
apache-2.0
mineral-ui/mineral-ui,mineral-ui/mineral-ui
979bf24a28e95f6975fde020b002426eafe5f3e6
static/js/activity-23andme-complete-import.js
static/js/activity-23andme-complete-import.js
$(function () { var params = {'data_type': '23andme_names'}; $.ajax({ 'type': 'GET', 'url': '/json-data/', 'data': params, 'success': function(data) { if (data.profiles && data.profiles.length > 0) { for (var i = 0; i < data.profiles.length; i++) { var radioElem = $('<input />'); radioElem.attr({'type' : 'radio', 'name' : 'profile_id', 'value' : data.profiles[i].id}); if (data.profiles.length == 1) { radioElem.attr('checked', true); } var labelElem = $('<label></label>'); labelElem.append(radioElem); labelElem.append(data.profiles[i].first_name + ' ' + data.profiles[i].last_name); var divElem = $('<div></div>'); divElem.attr('class', 'radio'); divElem.append(labelElem); $("#23andme-list-profiles").append(divElem); } $("#load-23andme-waiting").hide(); $("#23andme-complete-submit").css('visibility', 'visible'); } } }); });
$(function () { var params = {'data_type': '23andme_names'}; $.ajax({ 'type': 'GET', 'url': '/json-data/', 'data': params, 'success': function(data) { if (data.profiles && data.profiles.length > 0) { for (var i = 0; i < data.profiles.length; i++) { var radioElem = $('<input />'); radioElem.attr({'type' : 'radio', 'name' : 'profile_id', 'value' : data.profiles[i].id}); if (data.profiles.length == 1) { radioElem.attr('checked', true); } var labelElem = $('<label></label>'); labelElem.append(radioElem); labelElem.append(data.profiles[i].first_name + ' ' + data.profiles[i].last_name); var divElem = $('<div></div>'); divElem.attr('class', 'radio'); divElem.append(labelElem); $("#23andme-list-profiles").append(divElem); } $("#load-23andme-waiting").hide(); $("#23andme-complete-submit").css('visibility', 'visible'); } } }); });
Fix JS to use 2-space tabs
Fix JS to use 2-space tabs
JavaScript
mit
PersonalGenomesOrg/open-humans,OpenHumans/open-humans,PersonalGenomesOrg/open-humans,OpenHumans/open-humans,OpenHumans/open-humans,PersonalGenomesOrg/open-humans,PersonalGenomesOrg/open-humans,OpenHumans/open-humans
0100ebf9a24675a16ec200caf894af862196589c
d3/js/wgaPipeline.js
d3/js/wgaPipeline.js
/** * Creates an object of type wgaPipeline for drawing whole genome alignment visualizations * @author Markus Ankenbrand <[email protected]> * @constructor * @param {Object} svg - jQuery object containing a svg DOM element. Visualizations will be drawn on this svg. Size may be changed by object methods. Previous content will be deleted. * @example * // initializes an wgaPipeline object (wga) on the svg element with id 'canvas' * var svg = $('#canvas'); * var wga = new wgaPipeline(svg); */ function WgaPipeline(svg) { this.svg = svg; this.data = {}; }
/** * Creates an object of type wgaPipeline for drawing whole genome alignment visualizations * @author Markus Ankenbrand <[email protected]> * @constructor * @param {Object} svg - jQuery object containing a svg DOM element. Visualizations will be drawn on this svg. Size may be changed by object methods. Previous content will be deleted. * @example * // initializes an wgaPipeline object (wga) on the svg element with id 'canvas' * var svg = $('#canvas'); * var wga = new wgaPipeline(svg); */ function WgaPipeline(svg) { this.svg = svg; this.data = {}; } WgaPipeline.prototype.setData = function() { };
Test for existence of setData method passes
Test for existence of setData method passes
JavaScript
mit
BioInf-Wuerzburg/AliTV,BioInf-Wuerzburg/AliTV,AliTVTeam/AliTV,BioInf-Wuerzburg/AliTV,BioInf-Wuerzburg/AliTV,BioInf-Wuerzburg/AliTV,BioInf-Wuerzburg/AliTV,AliTVTeam/AliTV
c74647dae08d8d5f55a3d68de956a37b1fccec0e
assets/main.js
assets/main.js
function do_command(item, command, val) { var data = {}; data[item] = command; if (val != undefined) { data["value"] = val; } $.get("/CMD", data); } function do_scene(scene, action) { $.get("/api/scene/" + scene + "/command/" + (action?action:"")); } $(function() { $(".command").each(function() { var elm = $(this); elm.on(elm.data("event"), function() { if (elm.data("use-val") == "true") { do_command(elm.data("item"), elm.data("command"), elm.val()); } else { do_command(elm.data("item"), elm.data("command")); } }); }); $(".scene-control").each(function() { var elm = $(this); elm.click(function(evt) { do_scene(elm.data("scene"), elm.data("action")); }); }); });
function do_command(item, command, val) { var data = {}; if (val != undefined) { data["val"] = val; } $.get("/api/item/" + item + "/command/" + command, data); } function do_scene(scene, action) { $.get("/api/scene/" + scene + "/command/" + (action?action:"")); } $(function() { $(".command").each(function() { var elm = $(this); elm.on(elm.data("event"), function() { if (elm.data("use-val")) { do_command(elm.data("item"), elm.data("command"), elm.val()); } else { do_command(elm.data("item"), elm.data("command")); } }); }); $(".scene-control").each(function() { var elm = $(this); elm.click(function(evt) { do_scene(elm.data("scene"), elm.data("action")); }); }); });
Update javascript to use native API
Update javascript to use native API
JavaScript
mit
idiotic/idiotic-webui,idiotic/idiotic-webui,idiotic/idiotic-webui
d90f7b2a0393318affbb02ff89a63ade1a8b0469
javascript/example_code/nodegetstarted/sample.js
javascript/example_code/nodegetstarted/sample.js
/ Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // Licensed under the Apache-2.0 License on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND. // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-started-nodejs.html // Load the SDK and UUID var AWS = require('aws-sdk'); var uuid = require('uuid'); // Create unique bucket name var bucketName = 'node-sdk-sample-' + uuid.v4(); // Create name for uploaded object key var keyName = 'hello_world.txt'; // Create a promise on S3 service object var bucketPromise = new AWS.S3({apiVersion: '2006-03-01'}).createBucket({Bucket: bucketName}).promise(); // Handle promise fulfilled/rejected states bucketPromise.then( function(data) { // Create params for putObject call var objectParams = {Bucket: bucketName, Key: keyName, Body: 'Hello World!'}; // Create object upload promise var uploadPromise = new AWS.S3({apiVersion: '2006-03-01'}).putObject(objectParams).promise(); uploadPromise.then( function(data) { console.log("Successfully uploaded data to " + bucketName + "/" + keyName); }); }).catch( function(err) { console.error(err, err.stack); });
// Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // Licensed under the Apache-2.0 License on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND. // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-started-nodejs.html // Load the SDK and UUID var AWS = require('aws-sdk'); var uuid = require('uuid'); // Create unique bucket name var bucketName = 'node-sdk-sample-' + uuid.v4(); // Create name for uploaded object key var keyName = 'hello_world.txt'; // Create a promise on S3 service object var bucketPromise = new AWS.S3({apiVersion: '2006-03-01'}).createBucket({Bucket: bucketName}).promise(); // Handle promise fulfilled/rejected states bucketPromise.then( function(data) { // Create params for putObject call var objectParams = {Bucket: bucketName, Key: keyName, Body: 'Hello World!'}; // Create object upload promise var uploadPromise = new AWS.S3({apiVersion: '2006-03-01'}).putObject(objectParams).promise(); uploadPromise.then( function(data) { console.log("Successfully uploaded data to " + bucketName + "/" + keyName); }); }).catch( function(err) { console.error(err, err.stack); });
Add a backslash for a comment
Add a backslash for a comment
JavaScript
apache-2.0
awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples
3bc142f44ebd589227eec3660c72640fdfa7a238
bl/pipeline.js
bl/pipeline.js
var TaskScheduler = require("./task").TaskScheduler; var colors = require("colors"); exports.execute = function(initialStep, context, cb) { var completedSteps = 0; var estimatedSteps = initialStep.remaining; var scheduler = new TaskScheduler({ maxConcurrency: 5, mode: "lifo" }, cb); scheduler.schedule(execute_step, initialStep.weight, initialStep.name, [initialStep, null]); function execute_step(step, item, cb) { step.handler(item, step.args, context, step_complete); function step_complete(err, items) { ++completedSteps; if(step.next) { if(err == null) { if(items == null) { items = []; } else if(items.length == undefined) { items = [items]; } estimatedSteps += (items.length - 1) * step.next.remaining; } else { estimatedSteps -= step.next.remaining; } } console.log("Completed %d steps of %d".green, completedSteps, estimatedSteps); if(step.next && err == null) { items.forEach(function(i) { scheduler.schedule(execute_step, step.next.weight, step.next.name, [step.next, i]); }); } cb(err); } } }
var TaskScheduler = require("./task").TaskScheduler; var colors = require("colors"); exports.execute = function(initialStep, context, cb) { var completedSteps = 0; var estimatedSteps = initialStep.remaining; var scheduler = new TaskScheduler({ maxConcurrency: 5, mode: "lifo" }, cb); scheduler.schedule(execute_step, initialStep.weight, initialStep.name, [initialStep, null]); function execute_step(step, item, cb) { step.handler(item, step.args, context, step_complete); function step_complete(err, items) { ++completedSteps; if(step.next) { if(err == null) { if(items == null) { items = []; } else if(items.length == undefined) { items = [items]; } estimatedSteps += (items.length - 1) * step.next.remaining; } else { estimatedSteps -= step.next.remaining; } } console.log("%s Completed %d steps of %d".green, new Date(), completedSteps, estimatedSteps); if(step.next && err == null) { items.forEach(function(i) { scheduler.schedule(execute_step, step.next.weight, step.next.name, [step.next, i]); }); } cb(err); } } }
Add current date to polling log messages.
Add current date to polling log messages.
JavaScript
mit
aaubry/feed-reader,aaubry/feed-reader
56e784e7e966ccff9ba29b658ebd31406a868987
lib/paymaya/core/HttpConnection.js
lib/paymaya/core/HttpConnection.js
module.exports = HttpConnection; var request = require('requestretry'); var HttpConfig = require("./HttpConfig"); var PaymayaApiError = require("./PaymayaApiError"); function HttpConnection(httpConfig) { this._httpConfig = httpConfig; }; HttpConnection.prototype = { /* PUBLIC FUNCTIONS */ execute: function(data, callback) { var httpOptions = { url: this._httpConfig.getUrl(), method: this._httpConfig.getMethod(), headers: this._httpConfig.getHeaders(), maxAttempts: this._httpConfig.getMaximumRequestAttempt() }; if(data) { httpOptions['body'] = JSON.stringify(data); } request(httpOptions, function(err, response, body) { if(err) { return callback(err); } if(!body && response.statusCode >= 400) { var err = new PaymayaApiError(response.statusCode); return callback(err); } if(typeof body != 'object') { body = JSON.parse(body); } if(body.error) { var err = new PaymayaApiError(response.statusCode, body.error); return callback(err.message); } if(body.message) { return callback(body.message); } callback(null, body); }); } };
module.exports = HttpConnection; var request = require('requestretry'); var HttpConfig = require("./HttpConfig"); var PaymayaApiError = require("./PaymayaApiError"); function HttpConnection(httpConfig) { this._httpConfig = httpConfig; }; HttpConnection.prototype = { /* PUBLIC FUNCTIONS */ execute: function(data, callback) { var httpOptions = { url: this._httpConfig.getUrl(), method: this._httpConfig.getMethod(), headers: this._httpConfig.getHeaders(), maxAttempts: this._httpConfig.getMaximumRequestAttempt() }; if(data) { httpOptions['body'] = JSON.stringify(data); } request(httpOptions, function(err, response, body) { if(err) { return callback(err); } if(!body && response.statusCode >= 400) { var err = new PaymayaApiError(response.statusCode); return callback(err); } if(typeof body != 'object') { body = JSON.parse(body); } if(body.error) { var err = new PaymayaApiError(response.statusCode, body.error); return callback(err.message); } if(body.message && response.statusCode != 200) { return callback(body.message); } callback(null, body); }); } };
Modify displaying of error message
Modify displaying of error message
JavaScript
mit
PayMaya/PayMaya-Node-SDK
bb85a90b6941c8f6d20b2cc6e15359d7daf9b461
src/authentication/sessions.js
src/authentication/sessions.js
'use strict'; export default { setup, }; /** * Module dependencies. */ import SequelizeStore from 'koa-generic-session-sequelize'; import session from 'koa-generic-session'; /** * Prepares session middleware and methods without attaching to the stack * * @param {Object} router * @param {Object} settings * @param {Object} database * @param {Object} [store] Store for `koa-generic-sessions`. Uses the database if a store is not provided * @return {Object} */ function setup(router, settings, database, store) { // attach pre-authenticator middleware router.use(function(ctx, next) { // set the secret keys for Keygrip ctx.app.keys = settings.session.keys; // attach session methods ctx.identityDesk = { get(key) { if (ctx.session && ctx.session.identityDesk && ctx.session.identityDesk[key] !== undefined) { return ctx.session.identityDesk[key]; } else { return undefined; } }, set(values) { ctx.session = ctx.session || { identityDesk: { values } }; ctx.session.identityDesk = ctx.session.identityDesk || { values }; Object.assign(ctx.session.identityDesk, values); }, }; next(); }); // return the session middleware for later use return session({ key: 'identityDesk.sid', store: store || new SequelizeStore(database), }); }
'use strict'; export default { setup, }; /** * Module dependencies. */ import SequelizeStore from 'koa-generic-session-sequelize'; import convert from 'koa-convert'; import session from 'koa-generic-session'; /** * Prepares session middleware and methods without attaching to the stack * * @param {Object} settings * @param {Object} database * @param {Object} [store] Store for `koa-generic-sessions`. Uses the database if a store is not provided * @return {Object} */ function setup(settings, database, store) { return { // session middleware session: convert(session({ key: 'identityDesk.sid', store: store || new SequelizeStore(database), })), sessionMethods: function(ctx, next) { // set the secret keys for Keygrip ctx.app.keys = settings.session.keys; // attach session methods ctx.identityDesk = { get(key) { if (ctx.session && ctx.session.identityDesk && ctx.session.identityDesk[key] !== undefined) { return ctx.session.identityDesk[key]; } else { return undefined; } }, set(values) { ctx.session = ctx.session || { identityDesk: { values } }; ctx.session.identityDesk = ctx.session.identityDesk || { values }; Object.assign(ctx.session.identityDesk, values); }, }; next(); }, }; }
Add missing file from last commit
Add missing file from last commit
JavaScript
mit
HiFaraz/identity-desk
4d6ef02203bb5c198c9a6574601c8664271ad44d
app/javascript/flavours/glitch/components/column_back_button_slim.js
app/javascript/flavours/glitch/components/column_back_button_slim.js
import React from 'react'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import Icon from 'mastodon/components/icon'; export default class ColumnBackButtonSlim extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; handleClick = (event) => { // if history is exhausted, or we would leave mastodon, just go to root. if (window.history.state) { const state = this.context.router.history.location.state; if (event.shiftKey && state && state.mastodonBackSteps) { this.context.router.history.go(-state.mastodonBackSteps); } else { this.context.router.history.goBack(); } } else { this.context.router.history.push('/'); } } render () { return ( <div className='column-back-button--slim'> <div role='button' tabIndex='0' onClick={this.handleClick} className='column-back-button column-back-button--slim-button'> <Icon id='chevron-left' className='column-back-button__icon' fixedWidth /> <FormattedMessage id='column_back_button.label' defaultMessage='Back' /> </div> </div> ); } }
import React from 'react'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import Icon from 'flavours/glitch/components/icon'; export default class ColumnBackButtonSlim extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; handleClick = (event) => { // if history is exhausted, or we would leave mastodon, just go to root. if (window.history.state) { const state = this.context.router.history.location.state; if (event.shiftKey && state && state.mastodonBackSteps) { this.context.router.history.go(-state.mastodonBackSteps); } else { this.context.router.history.goBack(); } } else { this.context.router.history.push('/'); } } render () { return ( <div className='column-back-button--slim'> <div role='button' tabIndex='0' onClick={this.handleClick} className='column-back-button column-back-button--slim-button'> <Icon id='chevron-left' className='column-back-button__icon' fixedWidth /> <FormattedMessage id='column_back_button.label' defaultMessage='Back' /> </div> </div> ); } }
Fix using wrong component in ColumnBackButtonSlim
Fix using wrong component in ColumnBackButtonSlim
JavaScript
agpl-3.0
im-in-space/mastodon,im-in-space/mastodon,glitch-soc/mastodon,im-in-space/mastodon,glitch-soc/mastodon,glitch-soc/mastodon,Kirishima21/mastodon,Kirishima21/mastodon,Kirishima21/mastodon,im-in-space/mastodon,Kirishima21/mastodon,glitch-soc/mastodon
88e405fdaa97a224ad6683d39163a04d86982ede
src/components/video_detail.js
src/components/video_detail.js
import React from 'react'; // import VideoListItem from './video_list_item'; const VideoDetail = ({video}) => { const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9"> <iframe className="embed-responsive-item" src={url}></iframe> </div> <div className="details"> <div>{video.snippet.title}</div> <div>{video.snippet.description}</div> </div> </div> ); }; export default VideoDetail;
Add code to video detail component
Add code to video detail component
JavaScript
mit
izabelka/redux-simple-starter,izabelka/redux-simple-starter
1e2aa246a558447455dba80c4f49e5f9cdbb00c7
test/read-only-parallel.js
test/read-only-parallel.js
const test = require('tape') const BorrowState = require('../lib/module.js') const sleep50ms = require('./sleep.js') const countTo = require('./count-to.js') ;[true, false].forEach((unsafe) => { test(`read-only-parallel (${unsafe ? 'un' : ''}safe)`, (t) => { t.plan(3) t.timeoutAfter(100) let myState = new BorrowState() countTo(3).forEach(() => { myState.block('r') .then(sleep50ms) .then((state) => { t.ok(true) state.unblock() }) }) }) })
const test = require('tape') const BorrowState = require('../lib/module.js') const sleep50ms = require('./sleep.js') const countTo = require('./count-to.js') ;[true, false].forEach((unsafe) => { test(`read-only-parallel (${unsafe ? 'un' : ''}safe)`, (t) => { t.plan(6) t.timeoutAfter(100) let myState = new BorrowState() countTo(3).forEach(() => { t.ok(true) myState.block('r') .then(sleep50ms) .then((state) => { t.ok(true) state.unblock() }) }) }) })
Make sure to count up test additions
Make sure to count up test additions
JavaScript
isc
jamescostian/borrow-state
b948a9b149394932a0d3bf8a957a8792e23510ae
front_end/.eslintrc.js
front_end/.eslintrc.js
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. const path = require('path'); const rulesDirPlugin = require('eslint-plugin-rulesdir'); rulesDirPlugin.RULES_DIR = path.join(__dirname, '..', 'scripts', 'eslint_rules', 'lib'); module.exports = { 'overrides': [{ 'files': ['*.ts'], 'rules': { '@typescript-eslint/explicit-function-return-type': 2, 'rulesdir/kebab_case_events': 2, 'rulesdir/set_data_type_reference': 2, 'rulesdir/lit_html_data_as_type': 2, 'rulesdir/lit_no_style_interpolation': 2, } }] };
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. const path = require('path'); const rulesDirPlugin = require('eslint-plugin-rulesdir'); rulesDirPlugin.RULES_DIR = path.join(__dirname, '..', 'scripts', 'eslint_rules', 'lib'); module.exports = { 'overrides': [{ 'files': ['*.ts'], 'rules': { '@typescript-eslint/explicit-function-return-type': 2, 'rulesdir/kebab_case_events': 2, 'rulesdir/set_data_type_reference': 2, 'rulesdir/lit_html_data_as_type': 2, 'rulesdir/lit_no_style_interpolation': 2, '@typescript-eslint/naming-convention': [ 'error', { 'selector': 'property', 'modifiers': ['private', 'protected'], 'format': ['camelCase'], }, { 'selector': 'method', 'modifiers': ['private', 'protected'], 'format': ['camelCase'], } ] } }] };
Enforce camelCase for private and protected class members
Enforce camelCase for private and protected class members This encodes some of the TypeScript style guides about identifiers https://google.github.io/styleguide/tsguide.html#identifiers (in particular the rules our codebase already adheres to). The automatic enforcement will save time during code reviews. The current TypeScript migration produces a lot of public class properties and methods with leading underscores, so this CL only enforces the rule for protected and private class members; the rule can be enforced for public variables as well at a later point in time. Bug: chromium:1057042 Change-Id: Ic63b0a9b128f8b560020c015a0f91bbf72a9dd6d Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/2672026 Commit-Queue: Sigurd Schneider <[email protected]> Reviewed-by: Tim van der Lippe <[email protected]>
JavaScript
bsd-3-clause
ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend
c7329c1c5347ca2f453c41aeb0f479edc4050187
app/assets/javascripts/hyrax/browse_everything.js
app/assets/javascripts/hyrax/browse_everything.js
//= require jquery.treetable //= require browse_everything/behavior // Show the files in the queue Blacklight.onLoad( function() { // We need to check this because https://github.com/samvera/browse-everything/issues/169 if ($('#browse-btn').length > 0) { $('#browse-btn').browseEverything() .done(function(data) { var evt = { isDefaultPrevented: function() { return false; } }; var files = $.map(data, function(d) { return { name: d.file_name, size: d.file_size, id: d.url } }); $.blueimp.fileupload.prototype.options.done.call($('#fileupload').fileupload(), evt, { result: { files: files }}); }) } });
//= require jquery.treetable //= require browse_everything/behavior // Show the files in the queue function showBrowseEverythingFiles() { // We need to check this because https://github.com/samvera/browse-everything/issues/169 if ($('#browse-btn').length > 0) { $('#browse-btn').browseEverything() .done(function(data) { var evt = { isDefaultPrevented: function() { return false; } }; var files = $.map(data, function(d) { return { name: d.file_name, size: d.file_size, id: d.url } }); $.blueimp.fileupload.prototype.options.done.call($('#fileupload').fileupload(), evt, { result: { files: files }}); }) } } $(document).on('click', '#browse-btn', showBrowseEverythingFiles);
Fix loading of browse-everything done event
Fix loading of browse-everything done event Avoids situations where the prototype browseEverything() function has not been defined yet.
JavaScript
apache-2.0
samvera/hyrax,samvera/hyrax,samvera/hyrax,samvera/hyrax
79ac8a1c0b3e48b3b29f24422ab189d5dccc8fa0
client/src/js/home/components/Welcome.js
client/src/js/home/components/Welcome.js
import React from "react"; import { get } from "lodash-es"; import { connect } from "react-redux"; import { Panel } from "react-bootstrap"; import { getSoftwareUpdates } from "../../updates/actions"; import { Icon } from "../../base"; class Welcome extends React.Component { componentDidMount () { this.props.onGet(); } render () { let version; if (this.props.version) { version = ( <small className="text-muted"> {this.props.version} </small> ); } return ( <div className="container"> <Panel> <Panel.Body> <h3>Virtool {version}</h3> <p>Viral infection diagnostics using next-generation sequencing</p> <a className="btn btn-default" href="http://www.virtool.ca/" target="_blank" rel="noopener noreferrer" > <Icon name="globe" /> Website </a> </Panel.Body> </Panel> </div> ); } } const mapStateToProps = (state) => ({ version: get(state.updates.software, "version") }); const mapDispatchToProps = (dispatch) => ({ onGet: () => { dispatch(getSoftwareUpdates()); } }); export default connect(mapStateToProps, mapDispatchToProps)(Welcome);
import React from "react"; import { get } from "lodash-es"; import { connect } from "react-redux"; import { Panel } from "react-bootstrap"; import { getSoftwareUpdates } from "../../updates/actions"; import { Icon } from "../../base"; class Welcome extends React.Component { componentDidMount () { this.props.onGet(); } render () { let version; if (this.props.version) { version = ( <small className="text-muted"> {this.props.version} </small> ); } return ( <div className="container"> <Panel> <Panel.Body> <h3>Virtool {version}</h3> <p>Viral infection diagnostics using next-generation sequencing</p> <a className="btn btn-default" href="http://www.virtool.ca/" target="_blank" rel="noopener noreferrer" > <Icon name="globe" /> Website </a> </Panel.Body> </Panel> </div> ); } } const mapStateToProps = (state) => ({ version: get(state.updates, "version") }); const mapDispatchToProps = (dispatch) => ({ onGet: () => { dispatch(getSoftwareUpdates()); } }); export default connect(mapStateToProps, mapDispatchToProps)(Welcome);
Fix home virtool version display
Fix home virtool version display
JavaScript
mit
virtool/virtool,igboyes/virtool,igboyes/virtool,virtool/virtool
443a4ae12198f757370e95cf9e2de12aae9f710f
app/assets/javascripts/pages/new/new.component.js
app/assets/javascripts/pages/new/new.component.js
(function(){ 'use strict' const New = { templateUrl: 'pages/new/new.html' // templateUrl: 'components/bookmarks/bookmark-search.html', // controller: 'NewController' // controllerAs: 'model' } angular .module("shareMark") .component("new", New); }());
(function(){ 'use strict' const New = { templateUrl: 'pages/new/new.html', controller: 'NewController', controllerAs: 'model' } angular .module("shareMark") .component("new", New); }());
Update NewComponent to use NewController
Update NewComponent to use NewController
JavaScript
mit
Dom-Mc/shareMark,Dom-Mc/shareMark,Dom-Mc/shareMark
17e546f1a58744f7fe2f4e80147f6df2a203a2ee
esbuild/frappe-html.js
esbuild/frappe-html.js
module.exports = { name: "frappe-html", setup(build) { let path = require("path"); let fs = require("fs/promises"); build.onResolve({ filter: /\.html$/ }, (args) => { return { path: path.join(args.resolveDir, args.path), namespace: "frappe-html", }; }); build.onLoad({ filter: /.*/, namespace: "frappe-html" }, (args) => { let filepath = args.path; let filename = path.basename(filepath).split(".")[0]; return fs .readFile(filepath, "utf-8") .then((content) => { content = JSON.stringify(scrub_html_template(content)); return { contents: `\n\tfrappe.templates['${filename}'] = ${content};\n`, watchFiles: [filepath], }; }) .catch(() => { return { contents: "", warnings: [ { text: `There was an error importing ${filepath}`, }, ], }; }); }); }, }; function scrub_html_template(content) { content = content.replace(/`/g, "\\`"); return content; }
module.exports = { name: "frappe-html", setup(build) { let path = require("path"); let fs = require("fs/promises"); build.onResolve({ filter: /\.html$/ }, (args) => { return { path: path.join(args.resolveDir, args.path), namespace: "frappe-html", }; }); build.onLoad({ filter: /.*/, namespace: "frappe-html" }, (args) => { let filepath = args.path; let filename = path.basename(filepath).split(".")[0]; return fs .readFile(filepath, "utf-8") .then((content) => { content = scrub_html_template(content); return { contents: `\n\tfrappe.templates['${filename}'] = \`${content}\`;\n`, watchFiles: [filepath], }; }) .catch(() => { return { contents: "", warnings: [ { text: `There was an error importing ${filepath}`, }, ], }; }); }); }, }; function scrub_html_template(content) { content = content.replace(/`/g, "\\`"); return content; }
Revert "fix: allow backtick in HTML templates as well"
Revert "fix: allow backtick in HTML templates as well" This reverts commit 2f96458bcb6dfe8b8db4ef0101036b09bfa7c5f5.
JavaScript
mit
StrellaGroup/frappe,StrellaGroup/frappe,frappe/frappe,frappe/frappe,StrellaGroup/frappe,frappe/frappe
7f009627bc82b67f34f93430152da71767be0029
packages/rear-system-package/config/app-paths.js
packages/rear-system-package/config/app-paths.js
const fs = require('fs'); const path = require('path'); const resolveApp = require('rear-core/resolve-app'); const ownNodeModules = fs.realpathSync( path.join(__dirname, '..', 'node_modules') ); const AppPaths = { ownNodeModules, root: resolveApp('src'), appIndexJs: resolveApp('src', 'index.js'), // TODO: rename to appBuild ? dest: resolveApp('lib'), eslintConfig: path.join(ownNodeModules, 'eslint-config-rear', 'index.js'), flowBin: path.join(ownNodeModules, 'flow-bin'), eslintBin: path.join(ownNodeModules, 'eslint'), appNodeModules: resolveApp('node_modules'), } module.exports = AppPaths;
const fs = require('fs'); const path = require('path'); const resolveApp = require('rear-core/resolve-app'); let ownNodeModules; try { // Since this package is also used to build other packages // in this repo, we need to make sure its dependencies // are available when is symlinked by lerna. // Normally, modules are resolved from the app's node_modules. ownNodeModules = fs.realpathSync( path.join(__dirname, '..', 'node_modules') ); } catch (err) { ownNodeModules = resolveApp('node_modules'); } const AppPaths = { ownNodeModules, root: resolveApp('src'), appIndexJs: resolveApp('src', 'index.js'), dest: resolveApp('lib'), eslintConfig: path.join(ownNodeModules, 'eslint-config-rear', 'index.js'), flowBin: path.join(ownNodeModules, 'flow-bin'), eslintBin: path.join(ownNodeModules, 'eslint'), appNodeModules: resolveApp('node_modules'), } module.exports = AppPaths;
Fix an issue that prevented modules to be resolved
Fix an issue that prevented modules to be resolved rear-system-package's config/app-paths.js was trying to resolve node_modules from inside the dependency. This is needed when rear-system-package is symlinked. Normally node_modules paths should be resolved from the app's node_modules.
JavaScript
mit
erremauro/rear,rearjs/rear
8046548e86332e8b544563bcbc660a37b50ebd5e
test/index.js
test/index.js
var assert = require('assert'), capitalize = require('../index.js') describe('Capitalizer', function () { it('Capitalizes the first letter of a string', function () { assert.equal(capitalize('test'), 'Test') assert.equal(capitalize.first('test'), 'Test') }) it('Capitalizes all words in a string', function () { assert.equal( capitalize.all('this is a test sentence'), 'This Is A Test Sentence' ) }) it('Capitalizes all words in an array', function () { assert.equal( capitalize(['this', 'is', 'a', 'test', 'sentence']), ['This', 'Is', 'A', 'Test', 'Sentence'] ) }) it.skip('Recursively capitalizes all strings in an object', function () { assert.equal( capitalize({ name: 'john', hobby: 'chillin', address: { country: 'australia', street: 'wayne boulevard' } }), { name: 'John', hobby: 'Chillin', address: { country: 'Australia', street: 'Wayne boulevard' } } ) }) })
var assert = require('assert'), capitalize = require('../index.js') describe('Capitalizer', function () { it('Capitalizes the first letter of a string', function () { assert.equal(capitalize('test'), 'Test') assert.equal(capitalize.first('test'), 'Test') }) it('Capitalizes all words in a string', function () { assert.equal( capitalize.all('this is a test sentence'), 'This Is A Test Sentence' ) }) it('Capitalizes all words in an array', function () { assert.deepEqual( capitalize(['this', 'is', 'a', 'test', 'sentence']), ['This', 'Is', 'A', 'Test', 'Sentence'] ) }) it.skip('Recursively capitalizes all strings in an object', function () { assert.equal( capitalize({ name: 'john', hobby: 'chillin', address: { country: 'australia', street: 'wayne boulevard' } }), { name: 'John', hobby: 'Chillin', address: { country: 'Australia', street: 'Wayne boulevard' } } ) }) })
Test for deep equality of arrays
Test for deep equality of arrays
JavaScript
mit
adius/capitalizer
314b2f1b8350b64e29824257cef48f142d4c152f
test/index.js
test/index.js
'use strict'; const chai = require('chai'); const plate = require('../index'); const expect = chai.expect; describe('Those postal codes', function() { it('should be valid', function() { expect(plate.validate('10188')).to.be.true; expect(plate.validate('49080')).to.be.true; }); }); describe('Those postal codes', function() { it('should be invalid', function() { expect(plate.validate('90000')).to.be.false; expect(plate.validate('00000')).to.be.false; expect(plate.validate('1abcd')).to.be.false; expect(plate.validate('123456')).to.be.false; expect(plate.validate('1234')).to.be.false; expect(plate.validate('1 2 3 4')).to.be.false; }); }); describe('Those dirty postal codes', function() { it('should be cleaned', function() { expect(plate.clean(' 123 45 ')).to.equal('12345'); }); });
'use strict'; const chai = require('chai'); const postalCode = require('../index'); const expect = chai.expect; describe('Those postal codes', function() { it('should be valid', function() { expect(postalCode.validate('10188')).to.be.true; expect(postalCode.validate('49080')).to.be.true; }); }); describe('Those postal codes', function() { it('should be invalid', function() { expect(postalCode.validate('90000')).to.be.false; expect(postalCode.validate('00000')).to.be.false; expect(postalCode.validate('1abcd')).to.be.false; expect(postalCode.validate('123456')).to.be.false; expect(postalCode.validate('1234')).to.be.false; expect(postalCode.validate('1 2 3 4')).to.be.false; }); }); describe('Those dirty postal codes', function() { it('should be cleaned', function() { expect(postalCode.clean(' 123 45 ')).to.equal('12345'); }); });
Fix wrong naming in tests
Fix wrong naming in tests
JavaScript
mit
alefteris/greece-postal-code
b77fd67ee02329bd25fe224689dcd8434262c282
src/finders/JumpPointFinder.js
src/finders/JumpPointFinder.js
/** * @author aniero / https://github.com/aniero */ var DiagonalMovement = require('../core/DiagonalMovement'); var JPFNeverMoveDiagonally = require('./JPFNeverMoveDiagonally'); var JPFAlwaysMoveDiagonally = require('./JPFAlwaysMoveDiagonally'); var JPFMoveDiagonallyIfNoObstacles = require('./JPFMoveDiagonallyIfNoObstacles'); var JPFMoveDiagonallyIfAtMostOneObstacle = require('./JPFMoveDiagonallyIfAtMostOneObstacle'); /** * Path finder using the Jump Point Search algorithm * @param {object} opt * @param {function} opt.heuristic Heuristic function to estimate the distance * (defaults to manhattan). * @param {DiagonalMovement} opt.diagonalMovement Condition under which diagonal * movement will be allowed. */ function JumpPointFinder(opt) { if (opt.diagonalMovement === DiagonalMovement.Never) { return new JPFNeverMoveDiagonally(opt); } else if (opt.diagonalMovement === DiagonalMovement.Always) { return new JPFAlwaysMoveDiagonally(opt); } else if (opt.diagonalMovement === DiagonalMovement.OnlyWhenNoObstacles) { return new JPFMoveDiagonallyIfNoObstacles(opt); } else { return new JPFMoveDiagonallyIfAtMostOneObstacle(opt); } } module.exports = JumpPointFinder;
/** * @author aniero / https://github.com/aniero */ var DiagonalMovement = require('../core/DiagonalMovement'); var JPFNeverMoveDiagonally = require('./JPFNeverMoveDiagonally'); var JPFAlwaysMoveDiagonally = require('./JPFAlwaysMoveDiagonally'); var JPFMoveDiagonallyIfNoObstacles = require('./JPFMoveDiagonallyIfNoObstacles'); var JPFMoveDiagonallyIfAtMostOneObstacle = require('./JPFMoveDiagonallyIfAtMostOneObstacle'); /** * Path finder using the Jump Point Search algorithm * @param {object} opt * @param {function} opt.heuristic Heuristic function to estimate the distance * (defaults to manhattan). * @param {DiagonalMovement} opt.diagonalMovement Condition under which diagonal * movement will be allowed. */ function JumpPointFinder(opt) { opt = opt || {}; if (opt.diagonalMovement === DiagonalMovement.Never) { return new JPFNeverMoveDiagonally(opt); } else if (opt.diagonalMovement === DiagonalMovement.Always) { return new JPFAlwaysMoveDiagonally(opt); } else if (opt.diagonalMovement === DiagonalMovement.OnlyWhenNoObstacles) { return new JPFMoveDiagonallyIfNoObstacles(opt); } else { return new JPFMoveDiagonallyIfAtMostOneObstacle(opt); } } module.exports = JumpPointFinder;
Fix exception on missing options object
Fix exception on missing options object If the JumpPointFinder constructor was not passed the options object there was a ReferenceError.
JavaScript
bsd-3-clause
radify/PathFinding.js,radify/PathFinding.js
9edb7717b460685efaff9b2974daa9b776bd2921
share/spice/urban_dictionary/urban_dictionary.js
share/spice/urban_dictionary/urban_dictionary.js
// `ddg_spice_urban_dictionary` is a callback function that gets // "urban dictionary cool" or "urban dictionary ROTFL." // Note: This plugin can display adult content and profanity. function ddg_spice_urban_dictionary(response) { "use strict"; if (!(response || response.response.result_type === "exact" || response.list || response.list[0])) { return; } var word = response.list[0].word; var definition = response.list[0].definition.replace(/(\r?\n)+/gi, '<br>'); Spice.render({ data : { 'definition' : definition }, header1 : word + " (Urban Dictionary)", source_url : 'http://www.urbandictionary.com/define.php?term=' + word, source_name : 'Urban Dictionary', template_normal : 'urban_dictionary', force_big_header : true, }); }
// `ddg_spice_urban_dictionary` is a callback function that gets // "urban dictionary cool" or "urban dictionary ROTFL." // Note: This plugin can display adult content and profanity. function ddg_spice_urban_dictionary(response) { "use strict"; if (!(response || response.response.result_type === "exact" || response.list || response.list[0])) { return; } var word = response.list[0].word; var definition = response.list[0].definition.replace(/(\r?\n)+/gi, '<br>'); Spice.render({ data : { 'definition' : definition }, header1 : word + " (Urban Dictionary)", source_url : 'http://www.urbandictionary.com/define.php?term=' + word, source_name : 'Urban Dictionary', template_normal : 'urban_dictionary', force_big_header : true, }); }
Fix whitespace tabs-versus-spaces conflict in Urban_dictionary Spice.
Fix whitespace tabs-versus-spaces conflict in Urban_dictionary Spice.
JavaScript
apache-2.0
alexandernext/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,ppant/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,deserted/zeroclickinfo-spice,ppant/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,levaly/zeroclickinfo-spice,ppant/zeroclickinfo-spice,echosa/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,lerna/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,loganom/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,lernae/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,ppant/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,echosa/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,lernae/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,echosa/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,imwally/zeroclickinfo-spice,levaly/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,lernae/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,sevki/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,soleo/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,P71/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,lernae/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,lerna/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,lerna/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,deserted/zeroclickinfo-spice,echosa/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,sevki/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,stennie/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,mayo/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,levaly/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,levaly/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,imwally/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,deserted/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,stennie/zeroclickinfo-spice,deserted/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,loganom/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,stennie/zeroclickinfo-spice,imwally/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,loganom/zeroclickinfo-spice,mayo/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,soleo/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,soleo/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,mayo/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,lernae/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,levaly/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,mayo/zeroclickinfo-spice,lerna/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,soleo/zeroclickinfo-spice,P71/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,stennie/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,deserted/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,loganom/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,sevki/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,sevki/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,imwally/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,lerna/zeroclickinfo-spice,P71/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,lernae/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,deserted/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,imwally/zeroclickinfo-spice,soleo/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,soleo/zeroclickinfo-spice,P71/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,levaly/zeroclickinfo-spice,echosa/zeroclickinfo-spice
01c7ea21e810e5c27ca8105c5e169c28b57975a8
examples/todo/static/assets/js/app.js
examples/todo/static/assets/js/app.js
var loadTodos = function() { $.ajax({ url: "/graphql?query={todoList{id,text,done}}" }).done(function(data) { console.log(data); var dataParsed = JSON.parse(data); var todos = dataParsed.data.todoList; if (!todos.length) { $('.todo-list-container').append('<p>There are no tasks for you today</p>'); } $.each(todos, function(i, v) { var doneHtml = '<input id="' + v.id + '" type="checkbox"' + (v.done ? ' checked="checked"' : '') + '>'; var labelHtml = '<label for="' + v.id + '">' + doneHtml + v.text + '</label>'; var itemHtml = '<div class="todo-item">' + labelHtml + '</div>'; $('.todo-list-container').append(itemHtml); }); }); }; $(document).ready(function() { loadTodos(); });
var handleTodoList = function(object) { var todos = object; if (!todos.length) { $('.todo-list-container').append('<p>There are no tasks for you today</p>'); } $.each(todos, function(i, v) { var doneHtml = '<input id="' + v.id + '" type="checkbox"' + (v.done ? ' checked="checked"' : '') + '>'; var labelHtml = '<label for="' + v.id + '">' + doneHtml + v.text + '</label>'; var itemHtml = '<div class="todo-item">' + labelHtml + '</div>'; $('.todo-list-container').append(itemHtml); }); }; var loadTodos = function() { $.ajax({ url: "/graphql?query={todoList{id,text,done}}" }).done(function(data) { console.log(data); var dataParsed = JSON.parse(data); handleTodoList(dataParsed.data.todoList); }); }; var addTodo = function(todoText) { if (!todoText || todoText === "") { alert('Please specify a task'); return; } $.ajax({ url: '/graphql?query=mutation+_{createTodo(text:"' + todoText + '"){id,text,done}}' }).done(function(data) { console.log(data); var dataParsed = JSON.parse(data); var todoList = [dataParsed.data.createTodo]; handleTodoList(todoList); }); }; $(document).ready(function() { $('.todo-add-form button').click(function(){ addTodo($('.todo-add-form #task').val()); $('.todo-add-form #task').val(''); }); loadTodos(); });
Add "Add task" functionality, use the mutation
Add "Add task" functionality, use the mutation
JavaScript
mit
kr15h/graphql
7888270cc70a99be1c0fc20945a9684d66a69134
examples/client/app.js
examples/client/app.js
angular.module('MyApp', ['ngResource', 'ngMessages', 'ngRoute', 'ngAuth', 'mgcrea.ngStrap']) .config(['$routeProvider', function($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/home.html', controller: 'HomeCtrl' }) .when('/login', { templateUrl: 'views/login.html', controller: 'LoginCtrl' }) .when('/signup', { templateUrl: 'views/signup.html', controller: 'SignupCtrl' }) .when('/logout', { template: null, controller: 'LogoutCtrl' }) .when('/protected', { templateUrl: 'views/protected.html', controller: 'ProtectedCtrl' }) .otherwise({ redirectTo: '/' }); }]) .config(['AuthProvider', function(AuthProvider) { AuthProvider.configure({ apiUrl: '/api' }); }]);
angular.module('MyApp', ['ngResource', 'ngMessages', 'ngRoute', 'ngAuth', 'mgcrea.ngStrap']) .config(['$routeProvider', 'AuthProvider', function($routeProvider, AuthProvider) { $routeProvider .when('/', { templateUrl: 'views/home.html', controller: 'HomeCtrl' }) .when('/login', { templateUrl: 'views/login.html', controller: 'LoginCtrl' }) .when('/signup', { templateUrl: 'views/signup.html', controller: 'SignupCtrl' }) .when('/logout', { template: null, controller: 'LogoutCtrl' }) .when('/protected', { templateUrl: 'views/protected.html', controller: 'ProtectedCtrl' }) .otherwise({ redirectTo: '/' }); AuthProvider.configure({ apiUrl: '/api' }); }]);
Move AuthProvider into first config block
Move AuthProvider into first config block
JavaScript
mit
hsr-ba-fs15-dat/satellizer,gshireesh/satellizer,bnicart/satellizer,jskrzypek/satellizer,jskrzypek/satellizer,johan--/satellizer,vebin/satellizer,TechyTimo/CoderHunt,celrenheit/satellizer,maciekrb/satellizer,maciekrb/satellizer,david300/satellizer,ELAPAKAHARI/satellizer,gregoriusxu/satellizer,maciekrb/satellizer,rick4470/satellizer,peterkim-ijet/satellizer,m-kostira/satellizer,redwood-strategic/satellizer,jskrzypek/satellizer,redwood-strategic/satellizer,david300/satellizer,hsr-ba-fs15-dat/satellizer,ELAPAKAHARI/satellizer,NikolayGalkin/satellizer,maciekrb/satellizer,gshireesh/satellizer,dgoguerra/satellizer,ezzaouia/satellizer,jonbgallant/satellizer,peterkim-ijet/satellizer,redwood-strategic/satellizer,ELAPAKAHARI/satellizer,ELAPAKAHARI/satellizer,redwood-strategic/satellizer,bartekmis/satellizer,gshireesh/satellizer,suratpyari/satellizer,amitport/satellizer,jskrzypek/satellizer,eduardomb/satellizer,xxryan1234/satellizer,Manumental32/satellizer,maciekrb/satellizer,david300/satellizer,eduardomb/satellizer,redwood-strategic/satellizer,eduardomb/satellizer,jskrzypek/satellizer,celrenheit/satellizer,xxryan1234/satellizer,eduardomb/satellizer,sahat/satellizer,ABPFrameWorkGroup/satellizer,zawmyolatt/satellizer,amitport/satellizer,peterkim-ijet/satellizer,xxryan1234/satellizer,redwood-strategic/satellizer,celrenheit/satellizer,romcyncynatus/satellizer,ELAPAKAHARI/satellizer,elanperach/satellizer,redwood-strategic/satellizer,marfarma/satellizer,maciekrb/satellizer,18098924759/satellizer,jayzeng/satellizer,celrenheit/satellizer,david300/satellizer,hsr-ba-fs15-dat/satellizer,xxryan1234/satellizer,marceldiass/satellizer,xscharlie/satellizer,xxryan1234/satellizer,amitport/satellizer,amitport/satellizer,gshireesh/satellizer,ELAPAKAHARI/satellizer,xxryan1234/satellizer,AmreeshTyagi/satellizer,peterkim-ijet/satellizer,celrenheit/satellizer,NikolayGalkin/satellizer,david300/satellizer,IRlyDontKnow/satellizer,manojpm/satellizer,TheOneTheOnlyDavidBrown/satellizer,raycoding/satellizer,hsr-ba-fs15-dat/satellizer,NikolayGalkin/satellizer,shikhardb/satellizer,baratheraja/satellizer,celrenheit/satellizer,peterkim-ijet/satellizer,andyskw/satellizer,maciekrb/satellizer,peterkim-ijet/satellizer,eduardomb/satellizer,gshireesh/satellizer,amitport/satellizer,gshireesh/satellizer,viniciusferreira/satellizer,jskrzypek/satellizer,TechyTimo/CoderHunt,hsr-ba-fs15-dat/satellizer,xxryan1234/satellizer,NikolayGalkin/satellizer,johan--/satellizer,eduardomb/satellizer,celrenheit/satellizer,eduardomb/satellizer,gshireesh/satellizer,david300/satellizer,jskrzypek/satellizer,maciekrb/satellizer,NikolayGalkin/satellizer,burasu/satellizer,NikolayGalkin/satellizer,david300/satellizer,celrenheit/satellizer,ELAPAKAHARI/satellizer,hsr-ba-fs15-dat/satellizer,TechyTimo/carbon,NikolayGalkin/satellizer,jskrzypek/satellizer,redwood-strategic/satellizer,david300/satellizer,SkydiverFL/satellizer,ELAPAKAHARI/satellizer,memezilla/satellizer,romcyncynatus/satellizer,hsr-ba-fs15-dat/satellizer,TechyTimo/carbon,peterkim-ijet/satellizer,shubham13jain/satellizer,hsr-ba-fs15-dat/satellizer,xxryan1234/satellizer,xxryan1234/satellizer,thiagofesta/satellizer,heinbez/satellizer,sahat/satellizer,gshireesh/satellizer,eduardomb/satellizer,amitport/satellizer,eduardomb/satellizer,redwood-strategic/satellizer,NikolayGalkin/satellizer,amitport/satellizer,gshireesh/satellizer,themifycloud/satellizer,jianwang195823/satellizer,peterkim-ijet/satellizer,jskrzypek/satellizer,thandaanda/satellizer,david300/satellizer,expertmaksud/satellizer
614b4d791cf3660f1e84550cc17e86c2d10f5c9f
iscan/static/iscan/env.js
iscan/static/iscan/env.js
(function (window) { window.__env = window.__env || {}; window.__env.hostUrl = 'https://' + window.location.hostname +'/'; window.__env.apiUrl = window.__env.hostUrl+'api/'; window.__env.intontationUrl = window.__env.hostUrl +'intonation/'; window.__env.annotatorUrl = window.__env.hostUrl +'annotator/api/'; window.__env.baseUrl = '/'; window.__env.siteName = 'ISCAN'; window.__env.enableDebug = true; }(this));
(function (window) { window.__env = window.__env || {}; if (window.location.port) { window.__env.hostUrl = 'https://' + window.location.hostname + ':' + window.location.port + '/'; } else { window.__env.hostUrl = 'https://' + window.location.hostname + '/'; } window.__env.apiUrl = window.__env.hostUrl + 'api/'; window.__env.intontationUrl = window.__env.hostUrl + 'intonation/'; window.__env.annotatorUrl = window.__env.hostUrl + 'annotator/api/'; window.__env.baseUrl = '/'; window.__env.siteName = 'ISCAN'; window.__env.enableDebug = true; }(this));
Fix for missing port on API requests
Fix for missing port on API requests
JavaScript
mit
MontrealCorpusTools/polyglot-server,MontrealCorpusTools/polyglot-server,MontrealCorpusTools/polyglot-server,MontrealCorpusTools/polyglot-server
a707a26bd606f8b10e5610dec5f8f2743b6c41a4
example/test.js
example/test.js
var Compile = require('./index2.js') compile = Compile('b11bf50b8a391d4e8560e97fd9d63460') //Source Code to be compiled remotely var sourceCode = 'print 3*20' //Programming Language Selection var language = 'Python' //Input for the program var testCases = '' //'Run' routine compiles the code and return the answer object compile.Run(sourceCode,language,testCases, function(answer, error){ console.log(answer.langId) console.log(answer.langName) console.log(answer.output) console.log(answer.source) }) // Languages Supported by the API compile.languageSupport(function(languages) { console.log(languages) })
var Compile = require('../index.js') compile = Compile('b11bf50b8a391d4e8560e97fd9d63460') //Source Code to be compiled remotely var sourceCode = 'print 3*20' //Programming Language Selection var language = 'Python' //Input for the program var testCases = '' //'Run' routine compiles the code and return the answer object compile.Run(sourceCode,language,testCases, function(answer, error){ console.log(answer.langId) console.log(answer.langName) console.log(answer.output) console.log(answer.source) }) // Languages Supported by the API compile.languageSupport(function(languages) { console.log(languages) })
Fix mistypo on relative index.js
Fix mistypo on relative index.js
JavaScript
mit
saru95/ideone-npm
1771ab50f1a5d3dbe06871a26bdfa31882e393ac
test/setup.js
test/setup.js
// From https://github.com/airbnb/enzyme/blob/master/docs/guides/jsdom.md var jsdom = require('jsdom').jsdom; var exposedProperties = ['window', 'navigator', 'document']; global.document = jsdom(''); global.window = document.defaultView; Object.keys(document.defaultView).forEach((property) => { if (typeof global[property] === 'undefined') { exposedProperties.push(property); global[property] = document.defaultView[property]; } }); // For some reason, this property does not get set above. global.Image = global.window.Image; global.navigator = { userAgent: 'node.js' }; // HACK: Polyfil that allows codemirror to render in a JSDOM env. global.window.document.createRange = function createRange() { return { setEnd: () => {}, setStart: () => {}, getBoundingClientRect: () => { return { right: 0 }; }, getClientRects: () => { return [] } } }; var mock = require('mock-require'); mock('electron-json-storage', { 'get': function(key, callback){ callback(null, { theme: 'light' }); }, 'set': function(key, json, callback) { callback(null); }, }) mock('electron', { 'shell': { 'openExternal': function(url) { }, }, })
// From https://github.com/airbnb/enzyme/blob/master/docs/guides/jsdom.md var jsdom = require('jsdom').jsdom; var exposedProperties = ['window', 'navigator', 'document']; global.document = jsdom(''); global.window = document.defaultView; Object.keys(document.defaultView).forEach((property) => { if (typeof global[property] === 'undefined') { exposedProperties.push(property); global[property] = document.defaultView[property]; } }); // For some reason, this property does not get set above. global.Image = global.window.Image; global.navigator = { userAgent: 'node.js' }; // HACK: Polyfil that allows codemirror to render in a JSDOM env. global.window.document.createRange = function createRange() { return { setEnd: () => {}, setStart: () => {}, getBoundingClientRect: () => { return { right: 0 }; }, getClientRects: () => { return [] } } }; var mock = require('mock-require'); mock('electron-json-storage', { 'get': function(key, callback){ callback(null, { theme: 'light' }); }, 'set': function(key, json, callback) { callback(null); }, }) mock('electron', { 'shell': { 'openExternal': function(url) { }, }, 'remote': { 'require': function(module) { if (module === 'electron') { return { 'dialog': function() { }, }; } }, }, })
Add mocks for menu tests
Add mocks for menu tests
JavaScript
bsd-3-clause
jdetle/nteract,jdfreder/nteract,jdetle/nteract,nteract/nteract,0u812/nteract,0u812/nteract,nteract/nteract,captainsafia/nteract,temogen/nteract,jdetle/nteract,nteract/composition,rgbkrk/nteract,nteract/nteract,0u812/nteract,captainsafia/nteract,nteract/composition,temogen/nteract,rgbkrk/nteract,rgbkrk/nteract,captainsafia/nteract,jdetle/nteract,captainsafia/nteract,jdfreder/nteract,nteract/composition,0u812/nteract,temogen/nteract,nteract/nteract,rgbkrk/nteract,jdfreder/nteract,nteract/nteract,jdfreder/nteract,rgbkrk/nteract
662828ef56046bc7830718ef897a4ebbefd50278
examples/utils/embedly.js
examples/utils/embedly.js
// @flow const getJSON = ( endpoint: string, data: ?{}, successCallback: ({ url: string, title: string, author_name: string, thumbnail_url: string, }) => void, ) => { const request = new XMLHttpRequest(); request.open("GET", endpoint, true); request.setRequestHeader("Content-Type", "application/json; charset=UTF-8"); request.onload = () => { if (request.status >= 200 && request.status < 400) { successCallback(JSON.parse(request.responseText)); } }; request.send(data); }; /* global EMBEDLY_API_KEY */ const key = typeof EMBEDLY_API_KEY === "undefined" ? "key" : EMBEDLY_API_KEY; const EMBEDLY_ENDPOINT = `https://api.embedly.com/1/oembed?key=${key}`; const get = ( url: string, callback: ({ url: string, title: string, author_name: string, thumbnail_url: string, }) => void, ) => { getJSON(`${EMBEDLY_ENDPOINT}&url=${encodeURIComponent(url)}`, null, callback); }; export default { get, };
// @flow type Embed = { url: string, title: string, author_name: string, thumbnail_url: string, html: string, }; const getJSON = ( endpoint: string, data: ?{}, successCallback: (embed: Embed) => void, ) => { const request = new XMLHttpRequest(); request.open("GET", endpoint, true); request.setRequestHeader("Content-Type", "application/json; charset=UTF-8"); request.onload = () => { if (request.status >= 200 && request.status < 400) { successCallback(JSON.parse(request.responseText)); } }; request.send(data); }; /* global EMBEDLY_API_KEY */ const key = typeof EMBEDLY_API_KEY === "undefined" ? "key" : EMBEDLY_API_KEY; const EMBEDLY_ENDPOINT = `https://api.embedly.com/1/oembed?key=${key}`; const get = (url: string, callback: (embed: Embed) => void) => { getJSON(`${EMBEDLY_ENDPOINT}&url=${encodeURIComponent(url)}`, null, callback); }; export default { get, };
Support retrieving embed HTML in Embedly integration
Support retrieving embed HTML in Embedly integration
JavaScript
mit
springload/draftail,springload/draftail,springload/draftail,springload/draftail
05c19987d3f569aa892d50755c757a6356e4a9f1
environments/react/v15.js
environments/react/v15.js
/** * Js-coding-standards * * @author Robert Rossmann <[email protected]> * @copyright 2016 STRV * @license http://choosealicense.com/licenses/bsd-3-clause BSD-3-Clause License */ 'use strict' module.exports = { extends: [ './recommended.js', './accessibility.js', ], rules: { 'operator-linebreak': 0, 'require-jsdoc': 0, // Disallow Use of console // Turned off for React apps, console is quite useful in browsers 'no-console': 0, }, plugins: [ 'react', ], // Configures the react plugin to treat some rules with regard to this specific React.js version settings: { react: { version: '15.5', }, }, }
/** * Js-coding-standards * * @author Robert Rossmann <[email protected]> * @copyright 2016 STRV * @license http://choosealicense.com/licenses/bsd-3-clause BSD-3-Clause License */ 'use strict' module.exports = { extends: [ './recommended.js', './accessibility.js', ], rules: { 'operator-linebreak': 0, 'require-jsdoc': 0, }, plugins: [ 'react', ], // Configures the react plugin to treat some rules with regard to this specific React.js version settings: { react: { version: '15.5', }, }, }
Fix console still being turned off for react env
Fix console still being turned off for react env
JavaScript
bsd-3-clause
strvcom/js-coding-standards,strvcom/eslint-config-javascript,strvcom/eslint-config-javascript
d607447c7a4ee04fd559ba44f4fbb07ad42b8453
src/components/Counter.js
src/components/Counter.js
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import * as counterActions from '../actions/counterActions'; import { dispatch } from '../store'; @connect(state => ({ counter: state.counter, })) export class Counter extends Component { static propTypes = { counter: PropTypes.number, }; constructor(props) { super(props); } render() { return ( <div> <h2>Counter: {this.props.counter}</h2> <button onClick={() => dispatch(counterActions.decrement())}>-</button> <button onClick={() => dispatch(counterActions.increment())}>+</button> </div> ); } }
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import * as counterActions from '../actions/counterActions'; import { dispatch } from '../store'; @connect(state => ({ counter: state.counter, })) export class Counter extends Component { static propTypes = { counter: PropTypes.number, }; static defaultProps = { counter: 0, }; state = {}; constructor(props) { super(props); } render() { return ( <div> <h2>Counter: {this.props.counter}</h2> <button onClick={() => dispatch(counterActions.decrement())}>-</button> <button onClick={() => dispatch(counterActions.increment())}>+</button> </div> ); } }
Add defaultProps and initial state.
Add defaultProps and initial state.
JavaScript
mit
autozimu/react-hot-boilerplate,autozimu/react-hot-boilerplate
8999a66c88e56bc769bded0fe1ec17e0360682b5
src/core/cb.main/main.js
src/core/cb.main/main.js
function setup(options, imports, register) { // Import var server = imports.server.http; var port = imports.server.port; var watch = imports.watch; var workspace = imports.workspace; var logger = imports.logger.namespace("codebox"); // Start server server.listen(port); server.on('listening', function() { logger.log("Server is listening on ", port); watch.init(workspace.root) .then(function() { logger.log("Started Watch"); }) .fail(function(err) { logger.error("Failed to start Watch because of:"); logger.exception(err, false); }).fin(function() { // Register register(null, {}); }); }) } // Exports module.exports = setup;
function setup(options, imports, register) { // Import var server = imports.server.http; var port = imports.server.port; var watch = imports.watch; var workspace = imports.workspace; var logger = imports.logger.namespace("codebox"); // Start server server.listen(port); server.on('listening', function() { logger.log("Server is listening on ", port); }); watch.init(workspace.root) .then(function() { logger.log("Started Watch"); }) .fail(function(err) { logger.error("Failed to start Watch because of:"); logger.exception(err, false); }).fin(function() { // Register register(null, {}); }); } // Exports module.exports = setup;
Change init of watch and server
Change init of watch and server
JavaScript
apache-2.0
rajthilakmca/codebox,code-box/codebox,code-box/codebox,fly19890211/codebox,etopian/codebox,nobutakaoshiro/codebox,indykish/codebox,Ckai1991/codebox,fly19890211/codebox,CodeboxIDE/codebox,lcamilo15/codebox,kustomzone/codebox,lcamilo15/codebox,ronoaldo/codebox,ronoaldo/codebox,listepo/codebox,rajthilakmca/codebox,indykish/codebox,ahmadassaf/Codebox,Ckai1991/codebox,ahmadassaf/Codebox,etopian/codebox,quietdog/codebox,LogeshEswar/codebox,CodeboxIDE/codebox,quietdog/codebox,nobutakaoshiro/codebox,kustomzone/codebox,LogeshEswar/codebox,smallbal/codebox,blubrackets/codebox,listepo/codebox,rodrigues-daniel/codebox,blubrackets/codebox,smallbal/codebox,rodrigues-daniel/codebox
715fec370fa84ee9687a3e1f34e942a37cdf9dd7
src/js/editing/History.js
src/js/editing/History.js
define(['summernote/core/range'], function (range) { /** * @class editing.History * * Editor History * */ var History = function ($editable) { var stack = [], stackOffset = -1; var editable = $editable[0]; var makeSnapshot = function () { var rng = range.create(); var emptyBookmark = {s: {path: [0], offset: 0}, e: {path: [0], offset: 0}}; return { contents: $editable.html(), bookmark: (rng ? rng.bookmark(editable) : emptyBookmark) }; }; var applySnapshot = function (snapshot) { if (snapshot.contents !== null) { $editable.html(snapshot.contents); } if (snapshot.bookmark !== null) { range.createFromBookmark(editable, snapshot.bookmark).select(); } }; /** * undo */ this.undo = function () { if (0 < stackOffset) { stackOffset--; applySnapshot(stack[stackOffset]); } }; /** * redo */ this.redo = function () { if (stack.length - 1 > stackOffset) { stackOffset++; applySnapshot(stack[stackOffset]); } }; /** * recorded undo */ this.recordUndo = function () { stackOffset++; // Wash out stack after stackOffset if (stack.length > stackOffset) { stack = stack.slice(0, stackOffset); } // Create new snapshot and push it to the end stack.push(makeSnapshot()); }; // Create first undo stack this.recordUndo(); }; return History; });
define(['summernote/core/range'], function (range) { /** * @class editing.History * * Editor History * */ var History = function ($editable) { var stack = [], stackOffset = -1; var editable = $editable[0]; var makeSnapshot = function () { var rng = range.create(); var emptyBookmark = {s: {path: [], offset: 0}, e: {path: [], offset: 0}}; return { contents: $editable.html(), bookmark: (rng ? rng.bookmark(editable) : emptyBookmark) }; }; var applySnapshot = function (snapshot) { if (snapshot.contents !== null) { $editable.html(snapshot.contents); } if (snapshot.bookmark !== null) { range.createFromBookmark(editable, snapshot.bookmark).select(); } }; /** * undo */ this.undo = function () { if (0 < stackOffset) { stackOffset--; applySnapshot(stack[stackOffset]); } }; /** * redo */ this.redo = function () { if (stack.length - 1 > stackOffset) { stackOffset++; applySnapshot(stack[stackOffset]); } }; /** * recorded undo */ this.recordUndo = function () { stackOffset++; // Wash out stack after stackOffset if (stack.length > stackOffset) { stack = stack.slice(0, stackOffset); } // Create new snapshot and push it to the end stack.push(makeSnapshot()); }; // Create first undo stack this.recordUndo(); }; return History; });
Fix script error when last undo.
Fix script error when last undo.
JavaScript
mit
bebeeteam/summernote,summernote/summernote,summernote/summernote,AshDevFr/winternote,summernote/summernote,bebeeteam/summernote,bebeeteam/summernote,AshDevFr/winternote,AshDevFr/winternote
68bb8489b6fe7b2466159b2e5b9e08c21c466588
src/button.js
src/button.js
const React = require('react'); const classNames = require('classnames'); class Button extends React.Component { render() { const { className, children, type, ...props } = this.props; const buttonClassNames = classNames({ btn: true, 'btn-sm': this.props.size === 'small', 'btn-xs': this.props.size === 'extra-small', 'btn-lg': this.props.size === 'large', [`btn-${this.props.type}`]: true, }, className); return <button type="button" {...props} className={buttonClassNames} > {children} </button>; } } Button.propTypes = { size: React.PropTypes.oneOf([ 'small', 'extra-small', 'large', ]), type: React.PropTypes.oneOf([ 'default', 'danger', 'success', 'info' ]), className: React.PropTypes.string, children: React.PropTypes.node, }; Button.defaultProps = { type: 'default' }; module.exports = Button;
const React = require('react'); const classNames = require('classnames'); class Button extends React.Component { render() { const { className, children, theme, ...props } = this.props; const buttonClassNames = classNames({ btn: true, 'btn-sm': this.props.size === 'small', 'btn-xs': this.props.size === 'extra-small', 'btn-lg': this.props.size === 'large', [`btn-${this.props.theme}`]: true, }, className); return ( <button {...props} className={buttonClassNames}> {children} </button> ); } } Button.propTypes = { size: React.PropTypes.oneOf([ 'small', 'extra-small', 'large', ]), type: React.PropTypes.oneOf([ 'button', 'submit', ]), theme: React.PropTypes.oneOf([ 'default', 'danger', 'success', 'info' ]), className: React.PropTypes.string, children: React.PropTypes.node, }; Button.defaultProps = { type: 'button', theme: 'default' }; module.exports = Button;
Change `type` prop to `theme`
Change `type` prop to `theme`
JavaScript
mit
Opstarts/opstarts-ui
10503ba849b7f43e18509e08bd26b66917fa84ea
src/config.js
src/config.js
module.exports = { token: process.env.TOKEN || '1234567890abcdef', settings: { webHook: { port: process.env.PORT || 443, host: process.env.HOST || '0.0.0.0' } }, telegram: { port: 443, host: process.env.URL || 'https://rollrobot.herokuapp.com' }, botan: { token: process.env.TOKEN || '1234abcd-12ab-12ab-12ab-1234567890ab' } };
module.exports = { token: process.env.TOKEN || '1234567890abcdef', settings: { webHook: { port: process.env.PORT || 443, host: process.env.HOST || '0.0.0.0' } }, telegram: { port: 443, host: process.env.URL || 'https://rollrobot.herokuapp.com' }, botan: { token: process.env.BOTAN || '1234abcd-12ab-12ab-12ab-1234567890ab' } };
Fix Botan token variable name
:bug: Fix Botan token variable name
JavaScript
mit
edloidas/rollrobot
bc6633cdbfaccdec91725caf578c159e7bbd8baa
bin/cli.js
bin/cli.js
#!/usr/bin/env node require('babel-polyfill'); var cli = require('../lib/cli'); cli.run(process);
#!/usr/bin/env node require('babel-polyfill'); var cli = require('../lib/cli'); cli.default.run(process);
Use `.default` to access exported function
Use `.default` to access exported function
JavaScript
mit
Springworks/node-scale-reader
b41e1a78f7ac0fa996b290391273cd70d6375193
test/components/control.js
test/components/control.js
import React from 'react/addons'; let find = React.addons.TestUtils.findRenderedDOMComponentWithTag; let render = React.addons.TestUtils.renderIntoDocument; let Control = reqmod('components/control'); /** * Control components are those little icon based buttons, which can be toggled * active. */ describe('components/control', () => { it('should render correctly', () => { // First we render the actual 'control' component into our 'document'. let controlComponent = render( <Control icon="book" onClick={() => {}} /> ); // Next we check that it has the correct class... It should not be // toggled 'active' by default. controlComponent.getDOMNode().className.should.equal('control'); // Retrieve the actual 'icon' component from inside the 'control'. let iconComponent = find(controlComponent, 'span'); // Make sure the 'book' icon is reflected in the CSS classes. iconComponent.getDOMNode().className.should.endWith('fa-book'); }); it('should be able to be toggled active', () => { let controlComponent = render( <Control icon="book" onClick={() => {}} active={true} /> ); controlComponent.getDOMNode().className.should.endWith('active'); }); });
import React from 'react/addons'; let find = React.addons.TestUtils.findRenderedDOMComponentWithTag; let render = React.addons.TestUtils.renderIntoDocument; let Control = reqmod('components/control'); // Since we don't want React warnings about some deprecated stuff being spammed // in our test run, we disable the warnings with this... console.warn = () => { } /** * Control components are those little icon based buttons, which can be toggled * active. */ describe('components/control', () => { it('should render correctly', () => { // First we render the actual 'control' component into our 'document'. let controlComponent = render( <Control icon="book" onClick={() => {}} /> ); // Next we check that it has the correct class... It should not be // toggled 'active' by default. controlComponent.getDOMNode().className.should.equal('control'); // Retrieve the actual 'icon' component from inside the 'control'. let iconComponent = find(controlComponent, 'span'); // Make sure the 'book' icon is reflected in the CSS classes. iconComponent.getDOMNode().className.should.endWith('fa-book'); }); it('should be able to be toggled active', () => { let controlComponent = render( <Control icon="book" onClick={() => {}} active={true} /> ); controlComponent.getDOMNode().className.should.endWith('active'); }); });
Add an override to console.warn for testing to suppress React warnings.
Add an override to console.warn for testing to suppress React warnings.
JavaScript
mit
melonmanchan/teamboard-client-react,JanKuukkanen/Oauth-client-react,JanKuukkanen/Oauth-client-react,N4SJAMK/teamboard-client-react,tanelih/teamboard-client-react,melonmanchan/teamboard-client-react,santtusulander/teamboard-client-react,N4SJAMK/teamboard-client-react,santtusulander/teamboard-client-react,nikolauska/teamboard-client-react,AatuPitkanen/teamboard-client-react,AatuPitkanen/teamboard-client-react,JanKuukkanen/teamboard-client-react,nikolauska/teamboard-client-react,tanelih/teamboard-client-react,JanKuukkanen/teamboard-client-react
fd876469738834dc91e5ce179e2ccd9bc18ab37a
ui/app/serializers/node.js
ui/app/serializers/node.js
import { assign } from '@ember/polyfills'; import { inject as service } from '@ember/service'; import ApplicationSerializer from './application'; export default ApplicationSerializer.extend({ config: service(), attrs: { isDraining: 'Drain', httpAddr: 'HTTPAddr', }, normalize(modelClass, hash) { // Transform map-based objects into an array-based fragment lists const drivers = hash.Drivers || {}; hash.Drivers = Object.keys(drivers).map(key => { return assign({}, drivers[key], { Name: key }); }); const hostVolumes = hash.HostVolumes || {}; hash.HostVolumes = Object.keys(hostVolumes).map(key => hostVolumes[key]); return this._super(modelClass, hash); }, extractRelationships(modelClass, hash) { const { modelName } = modelClass; const nodeURL = this.store .adapterFor(modelName) .buildURL(modelName, this.extractId(modelClass, hash), hash, 'findRecord'); return { allocations: { links: { related: `${nodeURL}/allocations`, }, }, }; }, });
import { assign } from '@ember/polyfills'; import { inject as service } from '@ember/service'; import ApplicationSerializer from './application'; export default ApplicationSerializer.extend({ config: service(), attrs: { isDraining: 'Drain', httpAddr: 'HTTPAddr', }, normalize(modelClass, hash) { // Transform map-based objects into an array-based fragment lists const drivers = hash.Drivers || {}; hash.Drivers = Object.keys(drivers).map(key => { return assign({}, drivers[key], { Name: key }); }); if (hash.HostVolumes) { const hostVolumes = hash.HostVolumes; hash.HostVolumes = Object.keys(hostVolumes).map(key => hostVolumes[key]); } return this._super(modelClass, hash); }, extractRelationships(modelClass, hash) { const { modelName } = modelClass; const nodeURL = this.store .adapterFor(modelName) .buildURL(modelName, this.extractId(modelClass, hash), hash, 'findRecord'); return { allocations: { links: { related: `${nodeURL}/allocations`, }, }, }; }, });
Fix a bug where the NodeListStub API response would override existing HostVolumes in the store
Fix a bug where the NodeListStub API response would override existing HostVolumes in the store
JavaScript
mpl-2.0
hashicorp/nomad,hashicorp/nomad,dvusboy/nomad,burdandrei/nomad,burdandrei/nomad,dvusboy/nomad,hashicorp/nomad,hashicorp/nomad,hashicorp/nomad,hashicorp/nomad,burdandrei/nomad,burdandrei/nomad,burdandrei/nomad,dvusboy/nomad,dvusboy/nomad,dvusboy/nomad,dvusboy/nomad,burdandrei/nomad,dvusboy/nomad,burdandrei/nomad
0b9bed076bac3f942e904a5e8388880af515ced0
api/db/user.js
api/db/user.js
'use strict' module.exports = function (sequelize, DataTypes) { let User = sequelize.define('User', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4 }, email: { type: DataTypes.STRING, allowNull: false }, password: { type: DataTypes.STRING(1024), allowNull: false }, salt: { type: DataTypes.STRING, allowNull: true }, nicknames: { type: 'citext[]', allowNull: true, defaultValue: 'ARRAY[]::citext[]' }, drilled: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }, drilledDispatch: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }, group: { type: DataTypes.ENUM('normal', 'overseer', 'moderator', 'admin'), allowNull: false, defaultValue: 'normal' }, dispatch: { type: DataTypes.BOOLEAN, allowNull: true, defaultValue: null, unique: true } }, { paranoid: true, classMethods: { associate: function (models) { User.hasMany(models.Rat, { as: 'rats' }) } } }) return User }
'use strict' module.exports = function (sequelize, DataTypes) { let User = sequelize.define('User', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4 }, email: { type: DataTypes.STRING, allowNull: false }, password: { type: DataTypes.STRING(1024), allowNull: false }, salt: { type: DataTypes.STRING, allowNull: true }, nicknames: { type: 'citext[]', allowNull: true, defaultValue: sequelize.literal('ARRAY[]::citext[]') }, drilled: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }, drilledDispatch: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }, group: { type: DataTypes.ENUM('normal', 'overseer', 'moderator', 'admin'), allowNull: false, defaultValue: 'normal' }, dispatch: { type: DataTypes.BOOLEAN, allowNull: true, defaultValue: null, unique: true } }, { paranoid: true, classMethods: { associate: function (models) { User.hasMany(models.Rat, { as: 'rats' }) } } }) return User }
Use literal function for citext array default value, not string
Use literal function for citext array default value, not string
JavaScript
bsd-3-clause
FuelRats/api.fuelrats.com,FuelRats/api.fuelrats.com,FuelRats/api.fuelrats.com
ed6eed2c1f589c179cb57d9386f29cbfdbf1fc37
packages/rocketchat-ui-sidenav/client/sidebarItem.js
packages/rocketchat-ui-sidenav/client/sidebarItem.js
/* globals menu */ Template.sidebarItem.helpers({ canLeave() { const roomData = Session.get(`roomData${ this.rid }`); if (!roomData) { return false; } if (((roomData.cl != null) && !roomData.cl) || (roomData.t === 'd')) { return false; } else { return true; } } }); Template.sidebarItem.events({ 'click [data-id], click .sidebar-item__link'() { return menu.close(); } }); Template.sidebarItem.onCreated(function() { // console.log('sidebarItem', this.data); });
/* globals menu popover */ Template.sidebarItem.helpers({ canLeave() { const roomData = Session.get(`roomData${ this.rid }`); if (!roomData) { return false; } if (((roomData.cl != null) && !roomData.cl) || (roomData.t === 'd')) { return false; } else { return true; } } }); Template.sidebarItem.events({ 'click [data-id], click .sidebar-item__link'() { return menu.close(); }, 'click .sidebar-item__menu'(e) { const config = { popoverClass: 'sidebar-item', columns: [ { groups: [ { items: [ { icon: 'eye-off', name: t('Hide_room'), type: 'sidebar-item', id: 'hide' }, { icon: 'sign-out', name: t('Leave_room'), type: 'sidebar-item', id: 'leave' } ] } ] } ], mousePosition: { x: e.clientX, y: e.clientY }, data: { template: this.t, rid: this.rid, name: this.name } }; popover.open(config); } }); Template.sidebarItem.onCreated(function() { // console.log('sidebarItem', this.data); });
Add leave and hide buttons again
Add leave and hide buttons again
JavaScript
mit
NexFive/DrustChat,NexFive/DrustChat,NexFive/DrustChat,NexFive/DrustChat
9c6ee2b1a02d751bb4a1134a2a0d07e531d50acd
examples/simple-svg/app/stores/circle.js
examples/simple-svg/app/stores/circle.js
import { animate } from '../actions/animate' const Circle = { getInitialState() { return Circle.set(null, { color: 'orange', time: Date.now() }) }, set (_, { color, time }) { let sin = Math.sin(time / 200) let cos = Math.cos(time / 200) return { color : color, cx : 50 * sin, cy : 35 * cos, r : 12 + (8 * cos) } }, register () { return { [animate.loadings] : Circle.set, [animate.done] : Circle.set } } } export default Circle
import { animate } from '../actions/animate' const Circle = { getInitialState() { return Circle.set(null, { color: 'orange', time: Date.now() }) }, set (_, { color, time }) { let sin = Math.sin(time / 200) let cos = Math.cos(time / 200) return { color : color, cx : 50 * sin, cy : 35 * cos, r : 12 + (8 * cos) } }, register () { return { [animate.loading] : Circle.set, [animate.done] : Circle.set } } } export default Circle
Remove intentional error added for error reporting.
Remove intentional error added for error reporting.
JavaScript
mit
vigetlabs/microcosm,leobauza/microcosm,leobauza/microcosm,vigetlabs/microcosm,leobauza/microcosm,vigetlabs/microcosm
461893aac3ec8cd55caa2946b015891a9daff0cc
lib/engine/buildDigest.js
lib/engine/buildDigest.js
const _ = require('lodash'), fstate = require('../util/fstate'), digest = require('../util/digest'), hashcache = require('../util/hashcache'), log = require('../util/log') ; function buildDigest(buildDir, cb) { fstate(buildDir, { includeDirectories: true }, (err, files) => { if (err) return cb(err); const buildId = digest(_.map( _.sortBy(files, 'relPath'), fileInfo => hashcache(fileInfo.absPath)).join(' '), 'base64'); log.verbose(`Current build-digest for ${buildDir} is "${buildId}"`); return cb(null, buildId); }); } module.exports = _.debounce(buildDigest, 300);
const _ = require('lodash'), fstate = require('../util/fstate'), digest = require('../util/digest'), hashcache = require('../util/hashcache'), log = require('../util/log') ; function buildDigest(buildDir, cb) { fstate(buildDir, (err, files) => { if (err) return cb(err); const buildId = digest(_.map( _.sortBy(files, 'relPath'), fileInfo => hashcache(fileInfo.absPath)).join(' '), 'base64'); log.verbose(`Current build-digest for ${buildDir} is "${buildId}"`); return cb(null, buildId); }); } module.exports = _.debounce(buildDigest, 300);
Exclude directories from build digest.
Exclude directories from build digest.
JavaScript
mit
Iceroad/martinet,Iceroad/martinet,Iceroad/martinet
de04f9e1f50dc38e70cb4b47271829042dc9b301
client/reducers/index.js
client/reducers/index.js
import { combineReducers } from 'redux'; import { routerReducer } from 'react-router-redux'; import { reducer as formReducer } from 'redux-form'; import auth from './userSignUp'; import login from './login'; import book from './book'; import favorites from './favorites'; import profile from './profile'; import { books, mostUpvotedBooks } from './books'; const rootReducer = combineReducers({ form: formReducer, auth, login, books, book, mostUpvotedBooks, favorites, profile, routing: routerReducer, }); export default rootReducer;
import { combineReducers } from 'redux'; import { routerReducer } from 'react-router-redux'; import { reducer as formReducer } from 'redux-form'; import auth from './userSignUp'; import login from './login'; import book from './book'; import favorites from './favorites'; import profile from './profile'; import addBook from './addBook'; import { books, mostUpvotedBooks } from './books'; const rootReducer = combineReducers({ form: formReducer, auth, login, books, book, addBook, mostUpvotedBooks, favorites, profile, routing: routerReducer, }); export default rootReducer;
Add addBook reducer to root reducer
Add addBook reducer to root reducer
JavaScript
mit
amarachukwu-agbo/hello-books,amarachukwu-agbo/hello-books
a7af375c66552df8a73f945679b1ff01f95c6f36
client/webpack.common.js
client/webpack.common.js
const path = require('path'); const cleanWebPackPlugin = require('clean-webpack-plugin'); module.exports = { output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/', }, plugins: [ new cleanWebPackPlugin(['dist']), ], module: { rules: [ { test: /\.js$/, use: { loader: 'babel-loader', }, exclude: /node_modules/, }, { test: /\.scss$/, use: [ { loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader" }, ] }, { test: /\.(png|svg|gif|jpg)$/, use: { loader: 'file-loader', }, }, ], }, };
const path = require('path'); const cleanWebPackPlugin = require('clean-webpack-plugin'); module.exports = { output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/', }, plugins: [ new cleanWebPackPlugin(['dist']), ], module: { rules: [ { test: /\.js$/, loader: 'babel-loader', options: { cacheDirectory: true, plugins: ['react-hot-loader/babel'], }, exclude: /node_modules/, }, { test: /\.scss$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' }, { loader: 'sass-loader' }, ] }, { test: /\.(png|svg|gif|jpg)$/, use: { loader: 'file-loader', }, }, ], }, };
Set up hot module replacement for react components
Set up hot module replacement for react components
JavaScript
mit
amarachukwu-agbo/hello-books,amarachukwu-agbo/hello-books
219639c6d2d3df9b6126b1cb6407173d95a53d80
packages/soya-next/src/cookies/withCookiesPage.js
packages/soya-next/src/cookies/withCookiesPage.js
import React from "react"; import PropTypes from "prop-types"; import hoistStatics from "hoist-non-react-statics"; import { Cookies } from "react-cookie"; import getDisplayName from "../utils/getDisplayName"; import { NEXT_STATICS } from "../constants/Statics"; export default Page => { class WithCookies extends React.Component { static displayName = getDisplayName("WithCookies", Page); static propTypes = { cookies: PropTypes.oneOfType([ PropTypes.shape({ cookies: PropTypes.objectOf(PropTypes.string) }), PropTypes.instanceOf(Cookies) ]).isRequired }; static async getInitialProps(ctx) { const cookies = ctx.req ? ctx.req.universalCookies : new Cookies(); const props = Page.getInitialProps && (await Page.getInitialProps({ ...ctx, cookies })); return { ...props, cookies }; } constructor(props) { super(props); this.cookies = process.browser ? new Cookies() : props.cookies; } render() { const { ...props } = this.props; delete props.cookies; return <Page {...props} cookies={this.cookies} />; } } return hoistStatics(WithCookies, Page, NEXT_STATICS); };
import React from "react"; import PropTypes from "prop-types"; import hoistStatics from "hoist-non-react-statics"; import { Cookies } from "react-cookie"; import getDisplayName from "../utils/getDisplayName"; import { NEXT_STATICS } from "../constants/Statics"; export default Page => { class WithCookies extends React.Component { static displayName = getDisplayName("WithCookies", Page); static propTypes = { cookies: PropTypes.oneOfType([ PropTypes.shape({ cookies: PropTypes.objectOf(PropTypes.string) }), PropTypes.instanceOf(Cookies) ]).isRequired }; static async getInitialProps(ctx) { const cookies = (ctx.req && ctx.req.universalCookies) || new Cookies(); const props = Page.getInitialProps && (await Page.getInitialProps({ ...ctx, cookies })); return { ...props, cookies }; } constructor(props) { super(props); this.cookies = process.browser ? new Cookies() : props.cookies; } render() { const { ...props } = this.props; delete props.cookies; return <Page {...props} cookies={this.cookies} />; } } return hoistStatics(WithCookies, Page, NEXT_STATICS); };
Fix undefined cookies on server
Fix undefined cookies on server
JavaScript
mit
traveloka/soya-next
92d8cf6dbaa7145f225366a874f1b69a6382b1c3
server/helpers/subscriptionManager.js
server/helpers/subscriptionManager.js
// import { RedisPubSub } from 'graphql-redis-subscriptions'; import { PubSub } from 'graphql-subscriptions'; const pubsub = new PubSub(); /* const pubsub = new RedisPubSub({ connection: { host: 'redis.ralexanderson.com', port: 6379, }, });*/ export { pubsub };
// import { RedisPubSub } from 'graphql-redis-subscriptions'; import { PubSub } from "graphql-subscriptions"; const pubsub = new PubSub(); /* const pubsub = new RedisPubSub({ connection: { host: 'redis.ralexanderson.com', port: 6379, }, });*/ pubsub.ee.setMaxListeners(150); export { pubsub };
Increase the max event listener count
Increase the max event listener count
JavaScript
apache-2.0
Thorium-Sim/thorium,Thorium-Sim/thorium,Thorium-Sim/thorium,Thorium-Sim/thorium
a20e046f7b866fe23a6cb6547653ab97107deac9
frontend/src/store.js
frontend/src/store.js
import { createStore, applyMiddleware, compose } from 'redux' import { browserHistory} from 'react-router' import { syncHistoryWithStore, routerMiddleware } from 'react-router-redux' import createReducer from './reducers' import createSagaMiddleware from 'redux-saga' import rootSaga from './sagas' export default function configureStore(initialState = {}) { const sagaMiddleware = createSagaMiddleware() const history = browserHistory const middlewares = [ sagaMiddleware, routerMiddleware(history) ] const enhancers = [ applyMiddleware(...middlewares) ] const composeEnhancers = process.env.NODE_ENV !== 'production' && typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose; const store = createStore( createReducer(), initialState, composeEnhancers(...enhancers) ) const syncedHistory = syncHistoryWithStore(history, store) sagaMiddleware.run(rootSaga, syncedHistory) return { store, history: syncedHistory } }
import { createStore, applyMiddleware, compose } from 'redux' import { browserHistory } from 'react-router' import { syncHistoryWithStore, routerMiddleware } from 'react-router-redux' import createReducer from './reducers' import createSagaMiddleware from 'redux-saga' import rootSaga from './sagas' export default function configureStore(initialState = {}) { const sagaMiddleware = createSagaMiddleware() const middlewares = [ sagaMiddleware, routerMiddleware(browserHistory) ] const enhancers = [ applyMiddleware(...middlewares) ] const composeEnhancers = process.env.NODE_ENV !== 'production' && typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose; const store = createStore( createReducer(), initialState, composeEnhancers(...enhancers) ) sagaMiddleware.run(rootSaga, browserHistory) return { store, history: syncHistoryWithStore(browserHistory, store) } }
Fix duplicated calls of sagas based on history
Fix duplicated calls of sagas based on history
JavaScript
mit
luxons/seven-wonders,luxons/seven-wonders,luxons/seven-wonders
bea0e08a0f75d9ce5cd5f661db0aca50e678534c
lib/tooltip/fix-button.js
lib/tooltip/fix-button.js
/* @flow */ import React from 'react' class FixButton extends React.Component { handleClick(): void { this.props.cb() } render() { return <button className="fix-btn" onClick={() => this.handleClick()}>Fix</button> } } module.exports = FixButton
/* @flow */ import React from 'react' class FixButton extends React.Component { props: { cb: () => void, }; handleClick(): void { this.props.cb() } render() { return <button className="fix-btn" onClick={() => this.handleClick()}>Fix</button> } } module.exports = FixButton
Add props declaration of FixButton
Add props declaration of FixButton To fix CI error
JavaScript
mit
steelbrain/linter-ui-default,steelbrain/linter-ui-default,AtomLinter/linter-ui-default
98df85a394c3d3b64f017cfcf8481dead53bd858
components/CopyButton.js
components/CopyButton.js
import React from 'react'; import ClipboardJS from 'clipboard'; import 'balloon-css/balloon.css'; import levelNames from "../constants/levelNames"; export default class CopyButton extends React.PureComponent { constructor(props) { super(props); this.copyBtnRef = React.createRef(); this.clipboardRef = React.createRef(); } static defaultProps = { content: '', }; componentDidMount() { this.clipboardRef.current = new ClipboardJS(this.copyBtnRef.current, { text: () => this.props.content, }); this.clipboardRef.current.on('success', () => { // this.setState({ isSuccessMsgShow: true }); const copyBtnRef = this.copyBtnRef.current; copyBtnRef.setAttribute('data-balloon', '複製成功!'); copyBtnRef.setAttribute('data-balloon-visible', ''); copyBtnRef.setAttribute('data-balloon-pos', 'up'); setTimeout(function() { copyBtnRef.removeAttribute('data-balloon'); copyBtnRef.removeAttribute('data-balloon-visible'); copyBtnRef.removeAttribute('data-balloon-pos'); }, 3000); }); } render() { return ( <button ref={this.copyBtnRef} key="copy" onClick={() => {}} className="btn-copy" > 複製到剪貼簿 <style jsx>{` .btn-copy { margin-left: 10px; } `}</style> </button> ); } }
import React from 'react'; import ClipboardJS from 'clipboard'; import 'balloon-css/balloon.css'; export default class CopyButton extends React.PureComponent { constructor(props) { super(props); this.copyBtnRef = React.createRef(); this.clipboardRef = React.createRef(); } static defaultProps = { content: '', }; state = { btnAttributes: {}, }; componentDidMount() { this.clipboardRef.current = new ClipboardJS(this.copyBtnRef.current, { text: () => this.props.content, }); this.clipboardRef.current.on('success', () => { const self = this; this.setState({ btnAttributes: { 'data-balloon': '複製成功!', 'data-balloon-visible': '', 'data-balloon-pos': 'up', }}); setTimeout(function() { self.setState({ btnAttributes: {} }); }, 1000); }); } render() { return ( <button ref={this.copyBtnRef} key="copy" onClick={() => {}} className="btn-copy" { ...this.state.btnAttributes } > 複製到剪貼簿 <style jsx>{` .btn-copy { margin-left: 10px; } `}</style> </button> ); } }
Use attribute object from state
Use attribute object from state
JavaScript
mit
cofacts/rumors-site,cofacts/rumors-site
5ce70bfc71c927a7abce4de2a1ac5840003ceebd
src/js/Helpers/VectorHelpers.js
src/js/Helpers/VectorHelpers.js
const massToRadius = mass => Math.log2(mass)/10; const translate = (object3D, velocity) => { object3D.translateX(velocity.x); object3D.translateY(velocity.y); object3D.translateZ(velocity.z); } const rand = (min, max) => min + Math.random()*(max - min); const vLog = (v, msg) => console.log(msg, JSON.stringify(v.toArray())); const filterClose = (dancers, position, radius) => ( dancers.filter(dancer => dancer.position.distanceTo(position) > radius) ); const vectorToString = vector => { return vector.toArray().map(component => +component.toString().slice(0,15)).join(' ') }; const objToArr = obj => { const result = []; for (var i = 0; i < obj.length; i++) { result.push(obj[i]); } return result; }; export { massToRadius, translate, rand, vLog, filterClose, vectorToString, objToArr, }
const massToRadius = mass => Math.log2(mass)/10; const translate = (object3D, velocity) => { object3D.translateX(velocity.x); object3D.translateY(velocity.y); object3D.translateZ(velocity.z); } const getR = (body1, body2) => body2.position.sub(body1.position); const rand = (min, max) => min + Math.random()*(max - min); const vLog = (v, msg) => console.log(msg, JSON.stringify(v.toArray())); const filterClose = (dancers, position, radius) => ( dancers.filter(dancer => dancer.position.distanceTo(position) > radius) ); const vectorToString = vector => { return vector.toArray().map(component => +component.toString().slice(0,15)).join(' ') }; const objToArr = obj => { const result = []; for (var i = 0; i < obj.length; i++) { result.push(obj[i]); } return result; }; export { massToRadius, getR, translate, rand, vLog, filterClose, vectorToString, objToArr, }
Add function to get displacement (vR) vector
Add function to get displacement (vR) vector
JavaScript
mit
elliotaplant/celestial-dance,elliotaplant/celestial-dance
f163eac1c635e9573cc2c11083312acd0cce9c21
src/land_registry_elements/email-repeat/EmailRepeat.js
src/land_registry_elements/email-repeat/EmailRepeat.js
/* global $ */ 'use strict' /** * Email repeat */ function EmailRepeat (element, config) { var options = {} $.extend(options, config) // Private variables var hintWrapper var hint /** * Set everything up */ function create () { // Bail out if we don't have the proper element to act upon if (!element) { return } hintWrapper = $('<div class="panel panel-border-narrow email-hint spacing-top-single"><p>Please ensure your email address is displayed correctly below. We will need this if you need to reset your password in future.</p><p class="bold email-hint-value"></p></div>') hint = $(hintWrapper).find('.email-hint-value') $(element).on('change', updateHint) $(element).on('input', updateHint) } /** * */ function updateHint () { $(element).after(hintWrapper) // If the input field gets emptied out again, remove the hint if (element.value.length === 0) { hintWrapper.remove() return } // Update the hint to match the input value hint.text(element.value) } /** * Tear everything down again */ function destroy () { hintWrapper.remove() $(element).off('change', updateHint) $(element).off('input', updateHint) } var self = { create: create, destroy: destroy } return self } export { EmailRepeat }
/* global $ */ 'use strict' /** * Email repeat */ function EmailRepeat (element, config) { var options = {} $.extend(options, config) // Private variables var hintWrapper var hint /** * Set everything up */ function create () { // Bail out if we don't have the proper element to act upon if (!element) { return } hintWrapper = $('<div class="panel panel-border-narrow email-hint spacing-top-single"><p>Please ensure your email address is displayed correctly below. We will need this if you need to reset your password in future.</p></div>') hint = $('<p class="bold email-hint-value"></p>') $(hintWrapper).append(hint) $(element).on('change', updateHint) $(element).on('input', updateHint) } /** * */ function updateHint () { $(element).after(hintWrapper) // If the input field gets emptied out again, remove the hint if (element.value.length === 0) { hintWrapper.remove() return } // Update the hint to match the input value hint.text(element.value) } /** * Tear everything down again */ function destroy () { hintWrapper.remove() $(element).off('change', updateHint) $(element).off('input', updateHint) } var self = { create: create, destroy: destroy } return self } export { EmailRepeat }
Fix IE8 bug with email repeat
Fix IE8 bug with email repeat
JavaScript
mit
LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements
67a3aee413c05e895ed200b6cb1912bcebd538dd
eloquent_js_exercises/chapter05/chapter05_ex04.js
eloquent_js_exercises/chapter05/chapter05_ex04.js
function every(array, test) { for (var i = 0; i < array.length; ++i) { if (!test(array[i])) return false; } return true; } function some(array, test) { for (var i = 0; i < array.length; ++i) { if (test(array[i])) return true; } return false; }
function dominantDirection(text) { let scripts = countBy(text, char => { let script = characterScript(char.codePointAt(0)); return script ? script.direction : "none"; }).filter(({name}) => name != "none"); return scripts.reduce((a, b) => a.count > b.count ? a : b).name; }
Add Chapter 05, exercise 4
Add Chapter 05, exercise 4
JavaScript
mit
bewuethr/ctci
4f6299f4e88e89c0cd0971f318eef6823ae0cfc2
src/js/utils/Announcer.js
src/js/utils/Announcer.js
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import CSSClassnames from './CSSClassnames'; const CLASS_ROOT = CSSClassnames.APP; function clearAnnouncer() { const announcer = document.querySelector(`.${CLASS_ROOT}__announcer`); announcer.innerHTML = ''; }; export function announcePageLoaded (title) { announce(`${title} page was loaded`); } export function announce (message, mode = 'assertive') { const announcer = document.querySelector(`.${CLASS_ROOT}__announcer`); announcer.setAttribute('aria-live', 'off'); announcer.innerHTML = message; setTimeout(clearAnnouncer, 500); announcer.setAttribute('aria-live', mode); } export default { announce, announcePageLoaded };
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import CSSClassnames from './CSSClassnames'; const CLASS_ROOT = CSSClassnames.APP; function clearAnnouncer() { const announcer = document.querySelector(`.${CLASS_ROOT}__announcer`); if(announcer) { announcer.innerHTML = ''; } }; export function announcePageLoaded (title) { announce(`${title} page was loaded`); } export function announce (message, mode = 'assertive') { const announcer = document.querySelector(`.${CLASS_ROOT}__announcer`); if(announcer) { announcer.setAttribute('aria-live', 'off'); announcer.innerHTML = message; setTimeout(clearAnnouncer, 500); announcer.setAttribute('aria-live', mode); } } export default { announce, announcePageLoaded };
Fix exceptions when using Toast without having App
Fix exceptions when using Toast without having App See issue #995
JavaScript
apache-2.0
nickjvm/grommet,nickjvm/grommet,HewlettPackard/grommet,linde12/grommet,HewlettPackard/grommet,kylebyerly-hp/grommet,HewlettPackard/grommet,grommet/grommet,grommet/grommet,grommet/grommet
572baf69c38359e6f86df7a0ce53ae4a3d440ae7
src/layouts/layout-1-1.js
src/layouts/layout-1-1.js
import React from 'react'; export default (components, className, onClick) => ( <div className={className + ' horizontal'} onClick={onClick}> {components[0]} </div> );
import React from 'react'; export default (components, className, onClick) => ( <div className={className + ' vertical'} onClick={onClick}> {components[0]} </div> );
Make the 1-1 layout vertical
Make the 1-1 layout vertical
JavaScript
mit
nuruddeensalihu/binary-next-gen,binary-com/binary-next-gen,binary-com/binary-next-gen,binary-com/binary-next-gen,nazaninreihani/binary-next-gen,nazaninreihani/binary-next-gen,nuruddeensalihu/binary-next-gen,nazaninreihani/binary-next-gen,nuruddeensalihu/binary-next-gen
3a5eedacce41150794cd17a53de9b7cffd2be6d1
src/templateLayout.wef.js
src/templateLayout.wef.js
/*! * TemplateLayout Wef plugin * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ //requires: cssParser //exports: templateLayout (function () { var templateLayout = { name:"templateLayout", version:"0.0.1", description:"W3C CSS Template Layout Module", authors:["Pablo Escalada <[email protected]>"], licenses:["MIT"], //TODO: Licenses templateLayout:function () { document.addEventListener('selectorFound', function (e) { // e.target matches the elem from above lastEvent = e; //console.log(lastEvent.selectorText | lastEvent.property); }, false); document.addEventListener('propertyFound', function (e) { // e.target matches the elem from above lastEvent = e; //console.log(lastEvent.selectorText | lastEvent.property); }, false); return templateLayout; }, getLastEvent:function () { return lastEvent; } }; var lastEvent = 0; wef.plugins.register("templateLayout", templateLayout); })();
/*! * TemplateLayout Wef plugin * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ //requires: cssParser //exports: templateLayout (function () { var templateLayout = { name:"templateLayout", version:"0.0.1", description:"W3C CSS Template Layout Module", authors:["Pablo Escalada <[email protected]>"], licenses:["MIT"], //TODO: Licenses init:function () { document.addEventListener('propertyFound', function (e) { // e.target matches the elem from above lastEvent = e; //console.log(lastEvent.property); }, false); return templateLayout; }, getLastEvent:function () { return lastEvent; } }; var lastEvent = 0; wef.plugins.register("templateLayout", templateLayout); })();
Remove selectorFound event listener Rename templateLayout() to init()
Remove selectorFound event listener Rename templateLayout() to init()
JavaScript
mit
diesire/cssTemplateLayout,diesire/cssTemplateLayout,diesire/cssTemplateLayout
39a9f5fd3f0c2c5ab00f51c36c21b281e0476928
application.js
application.js
#!/usr/bin/env node var express = require('express'), kotoumi = require('./index'), http = require('http'); var application = express(); var server = http.startServer(application); application.kotoumi({ prefix: '', server: server }); serer.listen(13000);
#!/usr/bin/env node var express = require('express'), kotoumi = require('./index'), http = require('http'); var application = express(); var server = http.createServer(application); application.kotoumi({ prefix: '', server: server }); serer.listen(13000);
Fix typo on the method name: startServer => createServer
Fix typo on the method name: startServer => createServer
JavaScript
mit
KitaitiMakoto/express-droonga,droonga/express-droonga,KitaitiMakoto/express-droonga,droonga/express-droonga
2afc346f0fa3492cdbadff72dd47abec9b53fe76
source/assets/js/components/sass-syntax-switcher.js
source/assets/js/components/sass-syntax-switcher.js
$(function() { $( "#topic-2" ).tabs(); $( "#topic-3" ).tabs(); $( "#topic-5" ).tabs(); $( "#topic-6" ).tabs(); $( "#topic-7" ).tabs(); $( "#topic-8" ).tabs(); // Hover states on the static widgets $( "#dialog-link, #icons li" ).hover( function() { $( this ).addClass( "ui-state-hover" ); }, function() { $( this ).removeClass( "ui-state-hover" ); } ); });
$(function() { $( "#topic-2" ).tabs(); $( "#topic-3" ).tabs(); $( "#topic-5" ).tabs(); $( "#topic-6" ).tabs(); $( "#topic-7" ).tabs(); $( "#topic-8" ).tabs(); // Hover states on the static widgets $( "#dialog-link, #icons li" ).hover( function() { $( this ).addClass( "ui-state-hover" ); }, function() { $( this ).removeClass( "ui-state-hover" ); } ); // Switch ALL the tabs (Sass/SCSS) together var noRecursion = false, jqA = $( "a.ui-tabs-anchor" ), jqASass = jqA.filter( ":contains('Sass')" ).click(function() { if ( !noRecursion ) { noRecursion = true; jqASass.not( this ).click(); noRecursion = false; } }), jqASCSS = jqA.filter( ":contains('SCSS')" ).click(function() { if ( !noRecursion ) { noRecursion = true; jqASCSS.not( this ).click(); noRecursion = false; } }) ; });
Switch all the Sass/SCSS tabs together
Switch all the Sass/SCSS tabs together
JavaScript
mit
lostapathy/sass-site,Mr21/sass-site,mikaspell/sass-site-rus,lostapathy/sass-site,sass/sass-site,mikaspell/sass-site-rus,Mr21/sass-site,mikaspell/sass-site-rus,arhoads/sass-site,una/sass-site,lostapathy/sass-site,sass/sass-site,una/sass-site,arhoads/sass-site,Mr21/sass-site,sass/sass-site,una/sass-site,arhoads/sass-site
8e5dfec02570e58741c6a92b694d854efbcc23f2
lib/controllers/api/v1/users.js
lib/controllers/api/v1/users.js
'use strict'; var mongoose = require('mongoose'), utils = require('../utils'), User = mongoose.model('User'), Application = mongoose.model('Application'), SimpleApiKey = mongoose.model('SimpleApiKey'), OauthConsumer = mongoose.model('OauthConsumer'), Event = mongoose.model('Event'), User = mongoose.model('User'), Chapter = mongoose.model('Chapter'), middleware = require('../../../middleware'), devsite = require('../../../clients/devsite'); module.exports = function(app, cacher) { app.route("get", "/organizer/:gplusId", { summary: "Returns if the specified Google+ user is an Organizer of one or more Chapters" }, cacher.cache('hours', 24), function(req, res) { Chapter.find({organizers: req.params.gplusId}, function(err, chapters) { if (err) { console.log(err); return res.send(500, "Internal Error"); } var response = { msg: "ok", user: req.params.gplusId, chapters: [] }; for(var i = 0; i < chapters.length; i++) { response.chapters.push({ id: chapters[i]._id, name: chapters[i].name }); } return res.send(200, response); } ); }); }
'use strict'; var mongoose = require('mongoose'), utils = require('../utils'), User = mongoose.model('User'), Application = mongoose.model('Application'), SimpleApiKey = mongoose.model('SimpleApiKey'), OauthConsumer = mongoose.model('OauthConsumer'), Event = mongoose.model('Event'), User = mongoose.model('User'), Chapter = mongoose.model('Chapter'), middleware = require('../../../middleware'), devsite = require('../../../clients/devsite'); module.exports = function(app, cacher) { app.route("get", "/organizer/:gplusId", { summary: "Returns if the specified Google+ user is an Organizer of one or more Chapters" }, cacher.cache('hours', 24), function(req, res) { Chapter.find({organizers: req.params.gplusId}, function(err, chapters) { if (err) { console.log(err); return res.send(500, "Internal Error"); } var response = { user: req.params.gplusId, chapters: [] }; for(var i = 0; i < chapters.length; i++) { response.chapters.push({ id: chapters[i]._id, name: chapters[i].name }); } return res.jsonp(response); } ); }); }
Fix missin JSONP support on /organizer/:gplusId
Fix missin JSONP support on /organizer/:gplusId
JavaScript
apache-2.0
Splaktar/hub,fchuks/hub,gdg-x/hub,Splaktar/hub,nassor/hub,gdg-x/hub,nassor/hub,fchuks/hub
19b3f18accbbe1dccceae3e3471fc20ade51c914
khufu-runtime/src/dom.js
khufu-runtime/src/dom.js
import {text} from 'incremental-dom' export function item(value) { if(typeof value == 'function') { value() } else { text(value) } }
import {text} from 'incremental-dom' export function item(value, key) { if(typeof value == 'function') { value(key) } else { text(value) } }
Fix incorrect key propagation to child view
Fix incorrect key propagation to child view
JavaScript
apache-2.0
tailhook/khufu
385fa00d3219f84eec099ebf2551e8941f5e7262
sashimi-webapp/src/database/stringManipulation.js
sashimi-webapp/src/database/stringManipulation.js
export default function stringManipulation() { this.stringConcat = function stringConcat(...stringToConcat) { return stringToConcat.join(''); }; this.stringDateTime00Format = function stringDateTime00Format(dateTimeNumber) { if (typeof dateTimeNumber == 'number') { if (dateTimeNumber < 10) { return this.stringConcat('0', dateTimeNumber); } } return dateTimeNumber; }; this.resolveSQLInjections = function resolveSQLInjections(stringToReplace) { return stringToReplace.replace(/["'\\]/g, (char) => { switch (char) { case '"': case '\\': return `\\${char}`; // prepends a backslash to backslash, percent, // and double/single quotes default: return char; } }); }; this.revertSQLInjections = function revertSQLInjections(stringToReplace) { return stringToReplace.replace(/[\\\\"\\\\\\\\]/g, (char) => { switch (char) { case '\\\\"': return '"'; case '\\\\\\\\': return '\\'; // prepends a backslash to backslash, percent, // and double/single quotes default: return char; } }); }; this.getPreviousPath = function getPreviousPath(fullPath, lastFolderName) { const lengthOfExtraCurrentFolder = lastFolderName.length + 1; // extra slash return fullPath.substring(0, fullPath.length - lengthOfExtraCurrentFolder); }; }
export default function stringManipulation() { this.stringConcat = function stringConcat(...stringToConcat) { return stringToConcat.join(''); }; this.stringDateTime00Format = function stringDateTime00Format(dateTimeNumber) { if (typeof dateTimeNumber == 'number') { if (dateTimeNumber < 10) { return this.stringConcat('0', dateTimeNumber); } } return dateTimeNumber; }; this.replaceAll = function replaceAll(string, stringToReplace, replacement) { return string.replace(new RegExp(stringToReplace, 'g'), replacement); }; this.resolveSQLInjections = function resolveSQLInjections(stringToReplace) { return stringToReplace.replace(/["\\]/g, (char) => { switch (char) { case '"': case '\\': return `\\${char}`; // prepends a backslash to backslash, percent, // and double/single quotes default: return char; } }); }; this.revertSQLInjections = function revertSQLInjections(stringToReplace) { stringToReplace = this.replaceAll(stringToReplace, '\\\\"', '"'); stringToReplace = this.replaceAll(stringToReplace, '\\\\\\\\', '\\'); return stringToReplace; }; this.getPreviousPath = function getPreviousPath(fullPath, lastFolderName) { const lengthOfExtraCurrentFolder = lastFolderName.length + 1; // extra slash return fullPath.substring(0, fullPath.length - lengthOfExtraCurrentFolder); }; }
Fix unable to revert resolving of SQLinjection
Fix unable to revert resolving of SQLinjection [1] Revert back code for replaceAll [2] Revert 2 resolve strings one by one
JavaScript
mit
nus-mtp/sashimi-note,nus-mtp/sashimi-note,nus-mtp/sashimi-note
e8797027f38494db861d946f74e07e3a2b805a8a
src/md_document_block.js
src/md_document_block.js
"use strict"; var getItemURL = require('./get_item_url') , regex = /^document (\d+)$/ module.exports = function (md, opts) { opts = opts || {}; md.use(require('markdown-it-container'), 'document', { validate: function (params) { return params.trim().match(regex) }, render: function (tokens, idx) { var match = tokens[idx].info.trim().match(regex) if (tokens[idx].nesting === 1) { let documentURL = getItemURL(opts.projectBaseURL, 'document', match[1]) , documentText = opts.makeCitationText(documentURL) tokens[idx].meta = { enItemType: 'document', enItemID: match[1] } return '<div class="doc-block"><div class="doc">' + documentText + '</div>'; } else { return '</div>'; } } }); }
"use strict"; var getItemURL = require('./get_item_url') , regex = /^document (\d+)$/ function createRule(md, projectBaseURL, makeCitationText) { return function enDocumentBlockMetaRule(state) { var blockTokens = state.tokens blockTokens.forEach(function (token) { if (token.type === 'container_document_open') { let match = token.info.trim().match(regex) , documentURL = getItemURL(projectBaseURL, 'document', match[1]) , documentText = makeCitationText(documentURL) token.meta = { enCitationText: documentText, enItemType: 'document', enItemID: match[1] } } }) } } module.exports = function (md, opts) { opts = opts || {}; md.use(require('markdown-it-container'), 'document', { validate: function (params) { return params.trim().match(regex) }, render: function (tokens, idx) { if (tokens[idx].nesting === 1) { return '<div class="doc-block"><div class="doc">' + tokens[idx].meta.enCitationText + '</div>'; } else { return '</div>'; } } }); md.core.ruler.push( 'en_document_block_meta', createRule(md, opts.projectBaseURL, opts.makeCitationText) ) }
Store document meta properties in document block extension
Store document meta properties in document block extension
JavaScript
agpl-3.0
editorsnotes/editorsnotes-markup-parser
22aadec7318bbf4c79bb14d2615cef9480c7469f
library/CM/FormField/Integer.js
library/CM/FormField/Integer.js
/** * @class CM_FormField_Integer * @extends CM_FormField_Abstract */ var CM_FormField_Integer = CM_FormField_Abstract.extend({ _class: 'CM_FormField_Integer', ready: function() { var field = this; var $slider = this.$(".slider"); var $input = this.$("input"); $slider.slider({ value: $input.val(), min: field.getOption("min"), max: field.getOption("max"), step: field.getOption("step"), slide: function(event, ui) { var value = ui.value + 0; $input.val(value); $(this).children(".ui-slider-handle").text(value); }, change: function(event, ui) { var value = ui.value + 0; $input.val(value); $(this).children(".ui-slider-handle").text(value); } }); $slider.children(".ui-slider-handle").text($input.val()); $input.watch("disabled", function (propName, oldVal, newVal) { $slider.slider("option", "disabled", newVal); $slider.toggleClass("disabled", newVal); }); $input.changetext(function() { $slider.slider("option", "value", $(this).val()); field.trigger('change'); }); } });
/** * @class CM_FormField_Integer * @extends CM_FormField_Abstract */ var CM_FormField_Integer = CM_FormField_Abstract.extend({ _class: 'CM_FormField_Integer', ready: function() { var field = this; var $slider = this.$(".slider"); var $input = this.$("input"); $slider.slider({ value: $input.val(), min: field.getOption("min"), max: field.getOption("max"), step: field.getOption("step"), slide: function(event, ui) { var value = ui.value + 0; $input.val(value); $(this).children(".ui-slider-handle").text(value); }, change: function(event, ui) { var value = ui.value + 0; $input.val(value); $(this).children(".ui-slider-handle").text(value); } }); $slider.children(".ui-slider-handle").text($input.val()); $input.watch("disabled", function (propName, oldVal, newVal) { $slider.slider("option", "disabled", newVal); }); $input.changetext(function() { $slider.slider("option", "value", $(this).val()); field.trigger('change'); }); } });
Remove unneeded disabled class for slider
Remove unneeded disabled class for slider
JavaScript
mit
njam/CM,fauvel/CM,cargomedia/CM,tomaszdurka/CM,alexispeter/CM,tomaszdurka/CM,fvovan/CM,alexispeter/CM,fauvel/CM,vogdb/cm,alexispeter/CM,fvovan/CM,zazabe/cm,zazabe/cm,vogdb/cm,njam/CM,alexispeter/CM,mariansollmann/CM,vogdb/cm,cargomedia/CM,vogdb/cm,tomaszdurka/CM,zazabe/cm,cargomedia/CM,mariansollmann/CM,vogdb/cm,fauvel/CM,njam/CM,fvovan/CM,christopheschwyzer/CM,christopheschwyzer/CM,mariansollmann/CM,fvovan/CM,christopheschwyzer/CM,tomaszdurka/CM,christopheschwyzer/CM,tomaszdurka/CM,fauvel/CM,njam/CM,fauvel/CM,njam/CM,zazabe/cm,mariansollmann/CM,cargomedia/CM
fa62c68db63dd7e8ca0543947191d2586aed76e4
app/components/Footer/__tests__/Footer-test.js
app/components/Footer/__tests__/Footer-test.js
'use strict'; jest.unmock('./../Footer'); import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import Footer from './../Footer'; describe('Footer', () => { it('verify the text content and link are correctly', () => { const footer = TestUtils.renderIntoDocument( <Footer /> ); const footerNode = ReactDOM.findDOMNode(footer); expect(footerNode.textContent).toEqual('Made with by @afonsopacifer'); }); });
'use strict'; jest.unmock('./../Footer'); import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import Footer from './../Footer'; describe('Footer', () => { it('verify the text content are correctly', () => { const footer = TestUtils.renderIntoDocument( <Footer /> ); const footerNode = ReactDOM.findDOMNode(footer); expect(footerNode.textContent).toEqual('Made with by @afonsopacifer'); }); it('link of github author should be https://github.com/afonsopacifer', () => { const footer = TestUtils.renderIntoDocument( <Footer /> ); const linkElement = TestUtils.scryRenderedDOMComponentsWithTag(footer, 'a'); expect(linkElement.length).toEqual(1); expect(linkElement[0].getAttribute('href')).toEqual('https://github.com/afonsopacifer'); }); });
Make more tests at Footer component
Make more tests at Footer component
JavaScript
mit
afonsopacifer/react-pomodoro,afonsopacifer/react-pomodoro
bb910f984edd8080e5fe1d1b34a7dfec7ac9d785
lib/api/encodeSummary.js
lib/api/encodeSummary.js
var encodeSummaryArticle = require('../json/encodeSummaryArticle'); /** Encode summary to provide an API to plugin @param {Output} output @param {Config} config @return {Object} */ function encodeSummary(output, summary) { var result = { /** Iterate over the summary @param {Function} iter */ walk: function (iter) { summary.getArticle(function(article) { var jsonArticle = encodeSummaryArticle(article, false); return iter(jsonArticle); }); }, /** Get an article by its level @param {String} level @return {Object} */ getArticleByLevel: function(level) { var article = summary.getByLevel(level); return (article? encodeSummaryArticle(article) : undefined); }, /** Get an article by its path @param {String} level @return {Object} */ getArticleByPath: function(level) { var article = summary.getByPath(level); return (article? encodeSummaryArticle(article) : undefined); } }; return result; } module.exports = encodeSummary;
var encodeSummaryArticle = require('../json/encodeSummaryArticle'); /** Encode summary to provide an API to plugin @param {Output} output @param {Config} config @return {Object} */ function encodeSummary(output, summary) { var result = { /** Iterate over the summary, it stops when the "iter" returns false @param {Function} iter */ walk: function (iter) { summary.getArticle(function(article) { var jsonArticle = encodeSummaryArticle(article, false); return iter(jsonArticle); }); }, /** Get an article by its level @param {String} level @return {Object} */ getArticleByLevel: function(level) { var article = summary.getByLevel(level); return (article? encodeSummaryArticle(article) : undefined); }, /** Get an article by its path @param {String} level @return {Object} */ getArticleByPath: function(level) { var article = summary.getByPath(level); return (article? encodeSummaryArticle(article) : undefined); } }; return result; } module.exports = encodeSummary;
Improve comment for API summary.walk
Improve comment for API summary.walk
JavaScript
apache-2.0
gencer/gitbook,ryanswanson/gitbook,tshoper/gitbook,tshoper/gitbook,strawluffy/gitbook,GitbookIO/gitbook,gencer/gitbook
3d0c696f418fa672231c32737d706a62e5c5d9af
src/react/inputs/input.js
src/react/inputs/input.js
import React from 'react'; import {Icon} from '../iconography'; import classnames from 'classnames'; import PropTypes from 'prop-types'; export class Input extends React.Component { static propTypes = { size: PropTypes.string, icon: PropTypes.string }; componentDidMount() { require('../../css/inputs'); } render() { const {size, icon, ...props} = this.props; const input = (<input {...{ ...props, className: classnames(props.className, { 'input-sm': ['sm', 'small'].indexOf(size) !== -1, 'input-lg': ['lg', 'large'].indexOf(size) !== -1 }) }} />); if (!icon) return input; return ( <div className="input-icon-container"> {input} <Icon {...{src: icon}}/> </div> ); } }
import React from 'react'; import {Icon} from '../iconography'; import classnames from 'classnames'; import PropTypes from 'prop-types'; export class Input extends React.Component { static propTypes = { size: PropTypes.string, icon: PropTypes.string, innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]) }; componentDidMount() { require('../../css/inputs'); } render() { const {size, icon, innerRef, ...props} = this.props; const input = (<input {...{ ...props, ref: innerRef, className: classnames(props.className, { 'input-sm': ['sm', 'small'].indexOf(size) !== -1, 'input-lg': ['lg', 'large'].indexOf(size) !== -1 }) }} />); if (!icon) return input; return ( <div className="input-icon-container"> {input} <Icon {...{src: icon}}/> </div> ); } }
Add innerRef prop to Input component
Add innerRef prop to Input component
JavaScript
mit
pivotal-cf/pivotal-ui,pivotal-cf/pivotal-ui,pivotal-cf/pivotal-ui
ed9a606f20b97646d23bd23f693f2fe630394422
src/scripts/data_table.js
src/scripts/data_table.js
/*eslint-env node */ var m = require("mithril"); var tabs = require("./polythene_tabs"); tabs.onClick(function(newIndex, oldIndex) { var h = require("./headers")[newIndex]; grid.setRef(require("./firebase_ref").child(h.field), h.columns); }); var t = document.createElement("div"); m.mount(t, tabs.view); var grid = require("./w2ui_grid"); grid.view.style.height = "calc(100% - 48px)"; var wrapper = document.createElement("div"); wrapper.appendChild(t); wrapper.appendChild(grid.view); module.exports = wrapper;
/*eslint-env node */ var m = require("mithril"); var grid = require("./w2ui_grid"); grid.view.style.height = "calc(100% - 48px)"; var tabs = require("./polythene_tabs"); tabs.onClick(function(newIndex, oldIndex) { var h = require("./headers")[newIndex]; grid.setRef(require("./firebase_ref").child(h.field), h.columns); }); var t = document.createElement("div"); m.mount(t, tabs.view); var wrapper = document.createElement("div"); wrapper.appendChild(t); wrapper.appendChild(grid.view); module.exports = wrapper;
Define "grid" variable before it's used.
Define "grid" variable before it's used.
JavaScript
mit
1stop-st/frame
64d42211a279c8cfd56f4fad8c255b4e28c53721
src/ui/app.js
src/ui/app.js
angular.module('proxtop', ['ngMaterial', 'ui.router', 'angular-progress-arc', 'pascalprecht.translate']) .config(['$stateProvider', '$urlRouterProvider', '$translateProvider', function($stateProvider, $urlRouterProvider, $translateProvider) { $urlRouterProvider.otherwise('/'); $translateProvider.useStaticFilesLoader({ prefix: 'ui/locale/locale-', suffix: '.json' }); $translateProvider.preferredLanguage('de'); $translateProvider.useSanitizeValueStrategy('sanitizeParameters'); }]);
angular.module('proxtop', ['ngMaterial', 'ui.router', 'angular-progress-arc', 'pascalprecht.translate']) .config(['$stateProvider', '$urlRouterProvider', '$translateProvider', function($stateProvider, $urlRouterProvider, $translateProvider) { $urlRouterProvider.otherwise('/'); $translateProvider.useStaticFilesLoader({ prefix: 'ui/locale/locale-', suffix: '.json' }); $translateProvider.preferredLanguage('de'); $translateProvider.useSanitizeValueStrategy('escape'); }]);
Use sanitization method that doesn't require more dependencies.
Use sanitization method that doesn't require more dependencies.
JavaScript
mit
kumpelblase2/proxtop,kumpelblase2/proxtop,kumpelblase2/proxtop,kumpelblase2/proxtop
411c9404e0dedc5cd79a5b09d3afb6bfb7d69e0a
confirm.js
confirm.js
/** * Show confirm popup, when user close tab with non-synchronized actions. * * @param {Syncable|Client} client Observed Client instance * or object with `sync` property. * @param {String} [warning] The text of the warning. * * @return {Function} Unbind confirm listener. * * @example * import confirm from 'logux-status/confirm' * confirm(client, 'Post does not saved to server. Are you sure to leave?') */ function confirm (client, warning) { var sync = client.sync warning = warning || 'Some data was not saved to server. ' + 'Are you sure to leave?' function listen (e) { if (typeof e === 'undefined') e = window.event if (e) e.returnValue = warning return warning } return sync.on('state', function () { if (sync.state === 'wait' || sync.state === 'sending') { window.addEventListener('beforeunload', listen, false) } else { window.removeEventListener('beforeunload', listen, false) } }) } module.exports = confirm
/** * Show confirm popup, when user close tab with non-synchronized actions. * * @param {Syncable|Client} client Observed Client instance * or object with `sync` property. * @param {String} [warning] The text of the warning. * * @return {Function} Unbind confirm listener. * * @example * import confirm from 'logux-status/confirm' * confirm(client, 'Post does not saved to server. Are you sure to leave?') */ function confirm (client, warning) { var sync = client.sync warning = warning || 'Some data was not saved to server. ' + 'Are you sure to leave?' function listen (e) { if (typeof e === 'undefined') e = window.event if (e) e.returnValue = warning return warning } return sync.on('state', function () { if (sync.state === 'wait' || sync.state === 'sending') { window.addEventListener('beforeunload', listen) } else { window.removeEventListener('beforeunload', listen) } }) } module.exports = confirm
Remove default value for addEventListener
Remove default value for addEventListener
JavaScript
mit
logux/logux-client,logux/logux-client
94d8fd7c76248223fad33e9b5c964b3824db722f
console.js
console.js
(function () { var _console = window.console; var _methods = { log: window.console.log, error: window.console.error, info: window.console.info, debug: window.console.debug, clear: window.console.clear, }; var $body = document.body; function append (message) { $body.append(message); } function clear () { $body.innerHtml = ""; _methods.clear.call(_console); }; function message (text, color, $message) { $message = document.createElement('span'); $message.style.color = color || '#000000'; $message.innerText = text; return $message; } function write (key, color) { return function () { Function.prototype.apply.call(_methods[key], _console, arguments); append(message(Array.prototype.slice.call(arguments).join(' '), color)); }; } window.console.clear = clear; window.console.error = write('error', '#ff0000'); window.console.log = write('log'); window.console.info = write('info'); window.console.debug = write('debug'); function errorHandler (e) { e.preventDefault(); console.error(e.message); return true; } if (window.attachEvent) { window.attachEvent('onerror', errorHandler); } else { window.addEventListener('error', errorHandler, true); } }) ();
(function () { var _console = window.console; var _methods = { log: window.console.log, error: window.console.error, info: window.console.info, debug: window.console.debug, clear: window.console.clear, }; function append (message) { if (document.body) { document.body.append(message); } else { setTimeout(append, 100, message); } } function clear () { if (document.body) { document.body.innerHtml = null; } _methods.clear.call(_console); }; function message (text, color, $message) { $message = document.createElement('span'); $message.style.color = color || '#000000'; $message.innerText = text; return $message; } function write (key, color) { return function () { Function.prototype.apply.call(_methods[key], _console, arguments); append(message(Array.prototype.slice.call(arguments).join(' '), color)); }; } window.console.clear = clear; window.console.error = write('error', '#ff0000'); window.console.log = write('log'); window.console.info = write('info'); window.console.debug = write('debug'); function errorHandler (e) { e.preventDefault(); console.error(e.message); return true; } if (window.attachEvent) { window.attachEvent('onerror', errorHandler); } else { window.addEventListener('error', errorHandler, true); } }) ();
Fix to append when document body is ready
Fix to append when document body is ready
JavaScript
mit
eu81273/jsfiddle-console
0ec9d4ed2037fb68143bb9d816cf679ee099b2bd
tutorials/build-website.js
tutorials/build-website.js
var path = require('path'); var fs = require('fs-extra'); var pug = require('pug'); var buildUtils = require('../examples/build-utils'); // generate the tutorials fs.ensureDirSync('website/source/tutorials'); var tutorials = buildUtils.getList('tutorials', 'tutorial', path.resolve('website', 'source')); tutorials.map(function (json) { var pugTemplate = fs.readFileSync(path.relative('.', path.resolve(json.dir, 'index.pug')), 'utf8'); pugTemplate = pugTemplate.replace('extends ../common/index.pug', 'extends ../common/index-website.pug'); var fn = pug.compile(pugTemplate, { pretty: false, filename: path.relative('.', path.resolve(json.dir, 'index.pug')) }); var html = fn(json); html = `--- layout: tutorial title: ${json.title} about: ${json.about.text} tutorialCss: ${JSON.stringify(json.tutorialCss)} tutorialJs: ${JSON.stringify(json.tutorialJs)} --- ` + html; fs.writeFileSync(path.resolve(json.output, 'index.html'), html); }); // copy common files fs.copySync('tutorials/common', 'website/source/tutorials/common'); buildUtils.writeYamlList(path.resolve('website', 'source', '_data'), 'tutorials.yml', tutorials);
var path = require('path'); var fs = require('fs-extra'); var pug = require('pug'); var buildUtils = require('../examples/build-utils'); // generate the tutorials fs.ensureDirSync('website/source/tutorials'); var tutorials = buildUtils.getList('tutorials', 'tutorial', path.resolve('website', 'source')); tutorials.map(function (json) { var pugTemplate = fs.readFileSync(path.relative('.', path.resolve(json.dir, 'index.pug')), 'utf8'); pugTemplate = pugTemplate.replace('extends ../common/index.pug', 'extends ../common/index-website.pug'); var fn = pug.compile(pugTemplate, { pretty: false, filename: path.relative('.', path.resolve(json.dir, 'index.pug')) }); var html = fn(json); html = html.replace(/<=/g, '&lt;=').replace(/>=/g, '&gt;='); html = `--- layout: tutorial title: ${json.title} about: ${json.about.text} tutorialCss: ${JSON.stringify(json.tutorialCss)} tutorialJs: ${JSON.stringify(json.tutorialJs)} --- ` + html; fs.writeFileSync(path.resolve(json.output, 'index.html'), html); }); // copy common files fs.copySync('tutorials/common', 'website/source/tutorials/common'); buildUtils.writeYamlList(path.resolve('website', 'source', '_data'), 'tutorials.yml', tutorials);
Fix the website tutorial build to escape <=.
Fix the website tutorial build to escape <=.
JavaScript
apache-2.0
Kitware/geojs,OpenGeoscience/geojs,OpenGeoscience/geojs,Kitware/geojs,Kitware/geojs,OpenGeoscience/geojs
54181a9a43eddee7a19e8fd7ffb29a37ee8fd4d9
src/popup/js/config/svgIcons.js
src/popup/js/config/svgIcons.js
angular.module('Shazam2Spotify') .config(function() { // Load SVG icons (dirty, should not use jQuery...) $.ajax({ url: 'img/icons.svg', method: 'GET', dataType: 'html', success: function(data) { $("body").prepend(data); } }); });
angular.module('Shazam2Spotify') .run(function($http) { // Load SVG icons (dirty, should not use jQuery...) $http.get('img/icons.svg', {responseType: 'html'}). success(function(data) { angular.element('body').prepend(data); }); });
Load SVG icons with $http instead of jQuery
Load SVG icons with $http instead of jQuery
JavaScript
mit
leeroybrun/chrome-shazify,leeroybrun/chrome-shazify
69e7c35ed30ebeda6a5d701dad3abc10542d4088
app/assets/javascripts/behaviors/toggle_disable_list_command.js
app/assets/javascripts/behaviors/toggle_disable_list_command.js
$(function() { $(document).on("change", "[data-behavior~=toggle-disable-list-command]", function(e) { var commandButtonsSelector = $(e.target).data("commands"); var commandButtons = $(e.target).closest(commandButtonsSelector); console.log(commandButtons.length); }); });
$(function() { $(document).on("change", "[data-behavior~=toggle-disable-list-command]", function(e) { var commandButtonsSelector = $(e.target).data("commands"); var commandButtons = $(document).find(commandButtonsSelector); var list = $(document).find("[name='" + $(e.target).attr("name") + "']:checked"); if (list.length > 0) { commandButtons.removeClass("disabled").attr("disabled", false); } else { commandButtons.addClass("disabled").attr("disabled", true); } }); });
Implement toggle behavior from checkbox change
Implement toggle behavior from checkbox change
JavaScript
agpl-3.0
UM-USElab/gradecraft-development,UM-USElab/gradecraft-development,mkoon/gradecraft-development,UM-USElab/gradecraft-development,mkoon/gradecraft-development,UM-USElab/gradecraft-development,mkoon/gradecraft-development
3c34ff5ce1b1dc7d609a458b7483762a88c87179
build/serve.js
build/serve.js
var path = require('path'); var url = require('url'); var closure = require('closure-util'); var nomnom = require('nomnom'); var log = closure.log; var options = nomnom.options({ port: { abbr: 'p', 'default': 3000, help: 'Port for incoming connections', metavar: 'PORT' }, loglevel: { abbr: 'l', choices: ['silly', 'verbose', 'info', 'warn', 'error'], 'default': 'info', help: 'Log level', metavar: 'LEVEL' } }).parse(); /** @type {string} */ log.level = options.loglevel; log.info('ol3-cesium', 'Parsing dependencies ...'); var manager = new closure.Manager({ closure: true, // use the bundled Closure Library lib: [ 'src/**/*.js' ] }); manager.on('error', function(e) { log.error('ol3-cesium', e.message); }); manager.on('ready', function() { var server = new closure.Server({ manager: manager, loader: '/@loader' }); server.listen(options.port, function() { log.info('ol3-cesium', 'Listening on http://localhost:' + options.port + '/ (Ctrl+C to stop)'); }); server.on('error', function(err) { log.error('ol3-cesium', 'Server failed to start: ' + err.message); process.exit(1); }); });
var path = require('path'); var url = require('url'); var closure = require('closure-util'); var nomnom = require('nomnom'); var log = closure.log; var options = nomnom.options({ port: { abbr: 'p', 'default': 3000, help: 'Port for incoming connections', metavar: 'PORT' }, loglevel: { abbr: 'l', choices: ['silly', 'verbose', 'info', 'warn', 'error'], 'default': 'info', help: 'Log level', metavar: 'LEVEL' } }).parse(); /** @type {string} */ log.level = options.loglevel; log.info('ol3-cesium', 'Parsing dependencies ...'); var manager = new closure.Manager({ closure: true, // use the bundled Closure Library lib: [ 'src/**/*.js' ], ignoreRequires: '^ol\\.' }); manager.on('error', function(e) { log.error('ol3-cesium', e.message); }); manager.on('ready', function() { var server = new closure.Server({ manager: manager, loader: '/@loader' }); server.listen(options.port, function() { log.info('ol3-cesium', 'Listening on http://localhost:' + options.port + '/ (Ctrl+C to stop)'); }); server.on('error', function(err) { log.error('ol3-cesium', 'Server failed to start: ' + err.message); process.exit(1); }); });
Use closure-util's ignoreRequires for the examples
Use closure-util's ignoreRequires for the examples
JavaScript
bsd-2-clause
openlayers/ol3-cesium,gejgalis/ol3-cesium,phuree/ol-cesium,fredj/ol3-cesium,openlayers/ol-cesium,fredj/ol3-cesium,phuree/ol-cesium,ahocevar/ol3-cesium,gberaudo/ol3-cesium,oterral/ol3-cesium,thhomas/ol3-cesium,gberaudo/ol3-cesium,bartvde/ol3-cesium,camptocamp/ol3-cesium,openlayers/ol-cesium,thhomas/ol3-cesium,fredj/ol3-cesium,thhomas/ol3-cesium,epointal/ol3-cesium,camptocamp/ol3-cesium,GistdaDev/ol3-cesium,epointal/ol3-cesium,klokantech/ol3-cesium,gejgalis/ol3-cesium,GistdaDev/ol3-cesium,openlayers/ol3-cesium,bartvde/ol3-cesium,gejgalis/ol3-cesium,oterral/ol3-cesium
1077451e514b05a4bf12d8032f55e403fa96c877
js/src/index.js
js/src/index.js
// Load css require('leaflet/dist/leaflet.css'); require('leaflet-draw/dist/leaflet.draw.css'); require('leaflet.markercluster/dist/MarkerCluster.css'); require('leaflet.markercluster/dist/MarkerCluster.Default.css'); require('leaflet-measure/dist/leaflet-measure.css'); require('leaflet-fullscreen/dist/leaflet.fullscreen.css'); require('./jupyter-leaflet.css'); // Forcibly load the marker icon images to be in the bundle. require('leaflet/dist/images/marker-shadow.png'); require('leaflet/dist/images/marker-icon.png'); require('leaflet/dist/images/marker-icon-2x.png'); // Export everything from jupyter-leaflet and the npm package version number. hasL = (typeof(window.L) != 'undefined'); module.exports = require('./jupyter-leaflet.js'); module.exports['version'] = require('../package.json').version; if (hasL) { console.log("Existing `L` detected, running ipyleaflet's Leaflet in no-conflict mode as `ipyL`"); ipyL = L.noConflict(); }
// Load css require('leaflet/dist/leaflet.css'); require('leaflet-draw/dist/leaflet.draw.css'); require('leaflet.markercluster/dist/MarkerCluster.css'); require('leaflet.markercluster/dist/MarkerCluster.Default.css'); require('leaflet-measure/dist/leaflet-measure.css'); require('leaflet-fullscreen/dist/leaflet.fullscreen.css'); require('./jupyter-leaflet.css'); // Forcibly load the marker icon images to be in the bundle. require('leaflet/dist/images/marker-shadow.png'); require('leaflet/dist/images/marker-icon.png'); require('leaflet/dist/images/marker-icon-2x.png'); // Export everything from jupyter-leaflet and the npm package version number. var _oldL = window.L; module.exports = require('./jupyter-leaflet.js'); module.exports['version'] = require('../package.json').version; // if previous L existed and it got changed while loading this module if (_oldL !== undefined && _oldL !== window.L) { console.log("Existing `L` detected, running ipyleaflet's Leaflet in no-conflict mode as `ipyL`"); ipyL = L.noConflict(); }
Use more robust check before using noConflict() mode
Use more robust check before using noConflict() mode Basically detect the case when L is already the same Leaflet library instance that was loaded by some other extension, in which case there is no need to use noConflict. This does not address the problem of plugins assuming single global L when there are several different Leaflet libs, but it does address #337, since other extension share the same Leaflet instance.
JavaScript
mit
ellisonbg/leafletwidget,ellisonbg/leafletwidget
1ae13b69aba04aefcdfc6ac5022db03945e96f96
tests/web/casperjs/homepage.js
tests/web/casperjs/homepage.js
/** * homepage.js - Homepage tests. */ var x = require('casper').selectXPath; casper.options.viewportSize = {width: 1920, height: 961}; casper.on('page.error', function(msg, trace) { this.echo('Error: ' + msg, 'ERROR'); for(var i=0; i<trace.length; i++) { var step = trace[i]; this.echo(' ' + step.file + ' (line ' + step.line + ')', 'ERROR'); } }); casper.on('remote.message', function(message) { this.echo('Message: ' + message); }); casper.test.begin('Tests homepage structure', function suite(test) { casper.start('http://web', function() { test.assertTitle("TestProject", "Title is correct"); casper.wait(2000); test.assertVisible('h2'); }); casper.run(function() { test.done(); }); });
/** * homepage.js - Homepage tests. */ var x = require('casper').selectXPath; casper.options.viewportSize = {width: 1920, height: 961}; casper.on('page.error', function(msg, trace) { this.echo('Error: ' + msg, 'ERROR'); for(var i=0; i<trace.length; i++) { var step = trace[i]; this.echo(' ' + step.file + ' (line ' + step.line + ')', 'ERROR'); } }); casper.on('remote.message', function(message) { this.echo('Message: ' + message); }); casper.test.begin('Tests homepage structure', function suite(test) { casper.start('http://web', function() { // This works because the title is set in the "parent" template. test.assertTitle("TestProject", "Title is correct"); casper.wait(2000); // This fails, I'm guessing because the h2 is only in the "child" template, // it seems that CasperJS doesn't render the angular2 app correctly // and the child route templates are not injected into the page correctly. test.assertVisible('h2'); }); casper.run(function() { test.done(); }); });
Add more comments to the CasperJS test
Add more comments to the CasperJS test
JavaScript
mit
emmetog/demo-docker-microservice-app,emmetog/demo-docker-microservice-app,emmetog/demo-docker-microservice-app,emmetog/demo-docker-microservice-app,emmetog/demo-docker-microservice-app,emmetog/demo-docker-microservice-app
e4748c49a296ceae8a2ecf2b91d8dd9bcb81abbd
app/assets/javascripts/helpers/languagesHelper.js
app/assets/javascripts/helpers/languagesHelper.js
define([], function() { /** * List of the key languages of the platform */ var languageList = { en: 'English', zh: '中文', fr: 'Français', id: 'Bahasa Indonesia', pt_BR: 'Português (Brasil)', es_MX: 'Español (Mexico)' }; var languagesHelper = { /** * Returns the list of key languages * @returns {Object} key languages list */ getList: function() { return languageList; }, /** * Returns a list of the key languages * with the selected option passed by param * @param {string} selected language * @returns {Array} list of languages with selection */ getListSelected: function(selectedLanguage) { var langList = []; for (var lang in languageList) { langList.push({ key: lang, name: languageList[lang], selected: lang === selectedLanguage ? 'selected' : '' }); } return langList; } } return languagesHelper; });
define([], function() { /** * List of the key languages of the platform */ var languageList = { en: 'English', zh: '中文', fr: 'Français', id: 'Bahasa Indonesia', pt_BR: 'Português', es_MX: 'Español' }; var languagesHelper = { /** * Returns the list of key languages * @returns {Object} key languages list */ getList: function() { return languageList; }, /** * Returns a list of the key languages * with the selected option passed by param * @param {string} selected language * @returns {Array} list of languages with selection */ getListSelected: function(selectedLanguage) { var langList = []; for (var lang in languageList) { langList.push({ key: lang, name: languageList[lang], selected: lang === selectedLanguage ? 'selected' : '' }); } return langList; } } return languagesHelper; });
Update languages literals in subscription selector
Update languages literals in subscription selector
JavaScript
mit
Vizzuality/gfw,Vizzuality/gfw
5e0f5b68b4e085968544f9ff52eb3f7bc7558b81
src/article/converter/r2t/DispQuoteConverter.js
src/article/converter/r2t/DispQuoteConverter.js
import { findChild, findAllChildren } from '../util/domHelpers' /** * A converter for JATS `<disp-quote>`. * Our internal model deviates from the original one in that the the attribution is separated from * the quote content by using a dedicated text property 'attrib' */ export default class DispQuoteConverter { get type () { return 'disp-quote' } get tagName () { return 'disp-quote' } import (el, node, importer) { let pEls = findAllChildren(el, 'p') let attrib = findChild(el, 'attrib') if (attrib) { node.attrib = importer.annotatedText(attrib, [node.id, 'attrib']) } node._childNodes = pEls.map(p => { return importer.convertElement(p).id }) } export (node, el, exporter) { let $$ = exporter.$$ let children = node.getChildren() el.append( children.map(child => { return exporter.convertNode(child) }) ) if (node.attrib) { el.append( $$('attrib').append( exporter.annotatedText([node.id, 'attrib']) ) ) } } }
import { findChild, findAllChildren } from '../util/domHelpers' /** * A converter for JATS `<disp-quote>`. * Our internal model deviates from the original one in that the the attribution is separated from * the quote content by using a dedicated text property 'attrib' */ export default class DispQuoteConverter { get type () { return 'disp-quote' } get tagName () { return 'disp-quote' } import (el, node, importer) { let $$ = el.createElement.bind(el.getOwnerDocument()) let pEls = findAllChildren(el, 'p') if (pEls.length === 0) { pEls.push($$('p')) } let attrib = findChild(el, 'attrib') if (attrib) { node.attrib = importer.annotatedText(attrib, [node.id, 'attrib']) } node._childNodes = pEls.map(p => { return importer.convertElement(p).id }) } export (node, el, exporter) { let $$ = exporter.$$ let children = node.getChildren() el.append( children.map(child => { return exporter.convertNode(child) }) ) if (node.attrib) { el.append( $$('attrib').append( exporter.annotatedText([node.id, 'attrib']) ) ) } } }
Make a converter robust against missing paragraph.
Make a converter robust against missing paragraph.
JavaScript
mit
substance/texture,substance/texture
3a8a1f0d1f9fc7d5a38aba6e5bd042086c488adb
src/scripts/content/youtrack.js
src/scripts/content/youtrack.js
/*jslint indent: 2 */ /*global $: false, document: false, togglbutton: false*/ 'use strict'; /* the first selector is required for youtrack-5 and the second for youtrack-6 */ togglbutton.render('.fsi-toolbar-content:not(.toggl), .toolbar_fsi:not(.toggl)', {observe: true}, function (elem) { var link, description, numElem = $('a.issueId'), titleElem = $(".issue-summary"), projectElem = $('.fsi-properties .disabled.bold'); description = titleElem.textContent; description = numElem.firstChild.textContent.trim() + " " + description.trim(); link = togglbutton.createTimerLink({ className: 'youtrack', description: description, projectName: projectElem ? projectElem.textContent : '' }); elem.insertBefore(link, titleElem); }); // Agile board togglbutton.render('#board .sb-task:not(.toggl)', {observe: true}, function (elem) { var link, container = $('.sb-task-title', elem), description = $('.sb-task-summary', elem).textContent, projectName = $('#selectAgile').value.split("(")[1].replace(")", "").trim(); link = togglbutton.createTimerLink({ className: 'youtrack', description: description, projectName: projectName }); container.appendChild(link); });
/*jslint indent: 2 */ /*global $: false, document: false, togglbutton: false*/ 'use strict'; /* the first selector is required for youtrack-5 and the second for youtrack-6 */ togglbutton.render('.fsi-toolbar-content:not(.toggl), .toolbar_fsi:not(.toggl)', {observe: true}, function (elem) { var link, description, numElem = $('a.issueId'), titleElem = $(".issue-summary"), projectElem = $('.fsi-properties a[title^="Project"], .fsi-properties .disabled.bold'); description = titleElem.textContent; description = numElem.firstChild.textContent.trim() + " " + description.trim(); link = togglbutton.createTimerLink({ className: 'youtrack', description: description, projectName: projectElem ? projectElem.textContent : '' }); elem.insertBefore(link, titleElem); }); // Agile board togglbutton.render('#board .sb-task:not(.toggl)', {observe: true}, function (elem) { var link, container = $('.sb-task-title', elem), description = $('.sb-task-summary', elem).textContent, projectName = $('#selectAgile').value.split("(")[1].replace(")", "").trim(); link = togglbutton.createTimerLink({ className: 'youtrack', description: description, projectName: projectName }); container.appendChild(link); });
Fix project name fetch regression
[YouTrack] Fix project name fetch regression
JavaScript
bsd-3-clause
glensc/toggl-button,andreimoldo/toggl-button,eatskolnikov/toggl-button,eatskolnikov/toggl-button,andreimoldo/toggl-button,glensc/toggl-button,bitbull-team/toggl-button,glensc/toggl-button,bitbull-team/toggl-button
d2d8ef7e882dcf28ae306780bb463e800b0ad15c
js/validation/validate.js
js/validation/validate.js
var _ = require('lodash'); var async = require('async'); var joy = require('./joy/joy.js'); var schemas = { 'basal-rate-segment': require('./basal'), bolus: require('./bolus'), cbg: require('./bg'), common: require('./common'), deviceMeta: joy(), message: require('./message'), settings: require('./settings'), smbg: require('./bg'), wizard: require('./wizard') }; module.exports = { validateOne: function(datum, cb) { var handler = schemas[datum.type]; if (handler == null) { datum.errorMessage = util.format('Unknown data.type[%s]', datum.type); cb(new Error(datum.errorMessage), datum); } else { try { handler(datum); } catch (e) { console.log('Oh noes! This is wrong:\n', datum); console.log(util.format('Error Message: %s%s', datum.type, e.message)); datum.errorMessage = e.message; result.invalid.push(datum); return cb(e, datum); } cb(null, datum); } }, validateAll: function(data, cb) { console.time('Pure'); async.map(data, this.validateOne.bind(this), function(err, results) { console.timeEnd('Pure'); cb(err, results); }); } };
var _ = require('lodash'); var async = require('async'); var util = require('util'); var joy = require('./joy/joy.js'); var schemas = { 'basal-rate-segment': require('./basal'), bolus: require('./bolus'), cbg: require('./bg'), common: require('./common'), deviceMeta: joy(), message: require('./message'), settings: require('./settings'), smbg: require('./bg'), wizard: require('./wizard') }; module.exports = { validateOne: function(datum, cb) { var handler = schemas[datum.type]; if (handler == null) { datum.errorMessage = util.format('Unknown data.type[%s]', datum.type); cb(new Error(datum.errorMessage), datum); } else { try { handler(datum); } catch (e) { console.log('Oh noes! This is wrong:\n', datum); console.log(util.format('Error Message: %s%s', datum.type, e.message)); datum.errorMessage = e.message; result.invalid.push(datum); return cb(e, datum); } cb(null, datum); } }, validateAll: function(data, cb) { console.time('Pure'); async.map(data, this.validateOne.bind(this), function(err, results) { console.timeEnd('Pure'); cb(err, results); }); } };
Fix "util not defined" error from merge conflict
Fix "util not defined" error from merge conflict
JavaScript
bsd-2-clause
tidepool-org/tideline,tidepool-org/tideline
08d124de7b69cc5ff47f02230145c0a7b667cad6
chrome-keys.js
chrome-keys.js
var util = require('util'), webdriver = require('selenium-webdriver'); var driver = new webdriver.Builder(). usingServer('http://localhost:4444/wd/hub'). withCapabilities({'browserName': 'chrome'}). build(); // driver.get('http://juliemr.github.io/webdriver-bugs/'); driver.get('http://localhost:8111/button.html'); driver.findElement(webdriver.By.css('button')).click(); driver.actions().sendKeys(webdriver.Key.RIGHT).perform(); driver.sleep(4000); driver.quit();
var util = require('util'), webdriver = require('selenium-webdriver'); var driver = new webdriver.Builder(). usingServer('http://localhost:4444/wd/hub'). withCapabilities({'browserName': 'chrome'}). build(); driver.get('http://juliemr.github.io/webdriver-bugs/button.html'); // driver.get('http://localhost:8111/button.html'); driver.findElement(webdriver.By.css('button')).click(); driver.actions().sendKeys(webdriver.Key.RIGHT).perform(); driver.sleep(4000); driver.quit();
Fix address to work online
Fix address to work online
JavaScript
mit
juliemr/webdriver-bugs
f3ceda6f44b63bbef13e11345722805054b537e5
test/TestPermuteReduce.js
test/TestPermuteReduce.js
var expect = require('chai').expect; var permuterFactory = require('../index').permuterFactory; describe('permuter', function () { it('should work stand-alone', function () { var permuter = permuterFactory(['a','b']); expect(permuter(['x'])).to.eql([ ['x', 'a'], ['x', 'b'] ]); }); it('should work with reduce', function () { var permuter = permuterFactory(['a', 'b']); expect([['x']].reduce(permuter, [])).to.eql([ ['x', 'a'], ['x', 'b'] ]); }); });
var expect = require('chai').expect; var permuterFactory = require('../index').permuterFactory; describe('permuter', function () { it('should work stand-alone', function () { var permuter = permuterFactory(['a','b']); expect(permuter(['x'])).to.eql([ ['x', 'a'], ['x', 'b'] ]); }); it('should work with reduce', function () { var permuter = permuterFactory(['a', 'b']); expect([['x']].reduce(permuter, [])).to.eql([ ['x', 'a'], ['x', 'b'] ]); }); it('can be used to compute swedish ancestor names', function () { var parents = ['mor', 'far']; var permuter = permuterFactory(parents); expect([['']] .reduce(permuter, []) .reduce(permuter, []) .map(function (cur) {return cur.join('');})).to.eql([ 'mormor', 'morfar', 'farmor', 'farfar' ]); }); });
Add example for swedish grandparent names
Add example for swedish grandparent names
JavaScript
mit
tylerpeterson/node-swiss-army-knife
3a06fc67796abb9c93a7c607e2d766dc065f1fd6
example/index.js
example/index.js
// Dpeendencies var EngineParserGen = require("../lib"); // "test-app" should be a valid Engine app in $ENGINE_APPS dir var epg = new EngineParserGen("test-app"); //epg.parse(function (err, parsed) { // debugger //}); epg.renameInstance("layout", "another_layout", (err) => { if (err) { return console.log(err); } epg.save(function (err) { console.log(err || "Saved"); }); });
// Dpeendencies var EngineParserGen = require("../lib"); // "test-app" should be a valid Engine app in $ENGINE_APPS dir var epg = new EngineParserGen("test-app"); //epg.parse(function (err, parsed) { // debugger //}); epg.renameInstance("layout", "another_layout", (err, toBeSaved, toBeDeleted) => { if (err) { return console.log(err); } epg.save({ delete: toBeDeleted , save: toBeSaved }, function (err) { console.log(err || "Saved"); }); });
Send the data to the save method.
Send the data to the save method.
JavaScript
mit
jillix/engine-parser
e7fae9c368829013857e03316af06ed511bbfbe8
extendStorage.js
extendStorage.js
/* Wonder how this works? Storage is the Prototype of both localStorage and sessionStorage. Got it? */ (function() { 'use strict'; Storage.prototype.set = function(key, obj) { var t = typeof obj; if (t==='undefined' || obj===null ) this.removeItem(key); this.setItem(key, (t==='object')?JSON.stringify(obj):obj); }; Storage.prototype.get = function(key) { var obj = this.getItem(key); try { var j = JSON.parse(obj); if (j && typeof j === "object") return j; } catch (e) { } return obj; }; Storage.prototype.has = window.hasOwnProperty; Storage.prototype.remove = window.removeItem; Storage.prototype.keys = function(){ return Object.keys(this.valueOf()); }; })();
/* Wonder how this works? Storage is the Prototype of both localStorage and sessionStorage. Got it? */ (function() { 'use strict'; function extend(){ for(var i=1; i<arguments.length; i++) for(var key in arguments[i]) if(arguments[i].hasOwnProperty(key)) { if (typeof arguments[0][key] === 'object' && typeof arguments[i][key] === 'object') extend(arguments[0][key], arguments[i][key]); else arguments[0][key] = arguments[i][key]; } return arguments[0]; } Storage.prototype.set = function(key, obj) { var t = typeof obj; if (t==='undefined' || obj===null ) this.removeItem(key); this.setItem(key, (t==='object')?JSON.stringify(obj):obj); }; Storage.prototype.get = function(key) { var obj = this.getItem(key); try { var j = JSON.parse(obj); if (j && typeof j === "object") return j; } catch (e) { } return obj; }; Storage.prototype.extend = function(key, obj_merge) { this.set(key,extend(this.get(key),obj_merge); }; Storage.prototype.has = window.hasOwnProperty; Storage.prototype.remove = window.removeItem; Storage.prototype.keys = function(){ return Object.keys(this.valueOf()); }; })();
Add localStorage.extend with recursive support (but no typechecking)
Add localStorage.extend with recursive support (but no typechecking)
JavaScript
mit
zevero/simpleWebstorage
4e1b941dac03bca3acb0143ad91daa1f9a3e2936
packages/react-server-cli/src/commands/compile.js
packages/react-server-cli/src/commands/compile.js
import compileClient from "../compileClient" import handleCompilationErrors from "../handleCompilationErrors"; import setupLogging from "../setupLogging"; import logProductionWarnings from "../logProductionWarnings"; const logger = require("react-server").logging.getLogger(__LOGGER__); export default function compile(options){ setupLogging(options); logProductionWarnings(options); const {compiler} = compileClient(options); logger.notice("Starting compilation of client JavaScript..."); compiler.run((err, stats) => { const error = handleCompilationErrors(err, stats); if (!error) { logger.notice("Successfully compiled client JavaScript."); } else { logger.error(error); } }); }
import compileClient from "../compileClient" import handleCompilationErrors from "../handleCompilationErrors"; import setupLogging from "../setupLogging"; import logProductionWarnings from "../logProductionWarnings"; import {logging} from "../react-server"; const logger = logging.getLogger(__LOGGER__); export default function compile(options){ setupLogging(options); logProductionWarnings(options); const {compiler} = compileClient(options); logger.notice("Starting compilation of client JavaScript..."); compiler.run((err, stats) => { const error = handleCompilationErrors(err, stats); if (!error) { logger.notice("Successfully compiled client JavaScript."); } else { logger.error(error); } }); }
Fix a weird logger instantiation
Fix a weird logger instantiation
JavaScript
apache-2.0
emecell/react-server,davidalber/react-server,redfin/react-server,lidawang/react-server,doug-wade/react-server,szhou8813/react-server,doug-wade/react-server,redfin/react-server,szhou8813/react-server,lidawang/react-server,davidalber/react-server,emecell/react-server
4d0ee58f3adb7f9862c0000664989c40335f7abd
test/index.js
test/index.js
var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); var expect = chai.expect; var rollupBabelLibBundler = require('../lib'); describe('rollup-babel-lib-bundler', function() { it('is a function', function() { expect(rollupBabelLibBundler).to.be.a('function'); }); it('returns a promise', function(done) { var promise = rollupBabelLibBundler(); expect(promise).to.be.a('Promise'); expect(promise).to.eventually.be.rejected.and.notify(done); }); it('creates new files', function(done) { var promise = rollupBabelLibBundler({ entry: 'test/sample.js', }); expect(promise).to.eventually.be.a('array').and.notify(done); }); });
var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); var expect = chai.expect; var rollupBabelLibBundler = require('../lib'); describe('rollup-babel-lib-bundler', function() { it('is a function', function() { expect(rollupBabelLibBundler).to.be.a('function'); }); it('returns a promise', function(done) { var promise = rollupBabelLibBundler(); // On Node 0.10, promise is shimmed if (typeof promise !== 'object') { expect(promise).to.be.a('Promise'); } expect(promise).to.eventually.be.rejected.and.notify(done); }); it('creates new files', function(done) { var promise = rollupBabelLibBundler({ entry: 'test/sample.js', }); expect(promise).to.eventually.be.a('array').and.notify(done); }); });
Update test for Node 0.10
Update test for Node 0.10
JavaScript
mit
frostney/rollup-babel-lib-bundler
6695b1260a4e325e1a9ace924f9d81d108178d37
src/pexprs-toExpected.js
src/pexprs-toExpected.js
// -------------------------------------------------------------------- // Imports // -------------------------------------------------------------------- var common = require('./common.js'); var pexprs = require('./pexprs.js'); var awlib = require('awlib'); var printString = awlib.stringUtils.printString; var makeStringBuffer = awlib.objectUtils.stringBuffer; // -------------------------------------------------------------------- // Operations // -------------------------------------------------------------------- pexprs.PExpr.prototype.toExpected = function(ruleDict) { return undefined; }; pexprs.anything.toExpected = function(ruleDict) { return "any object"; }; pexprs.end.toExpected = function(ruleDict) { return "end of input"; }; pexprs.Prim.prototype.toExpected = function(ruleDict) { return printString(this.obj); }; pexprs.Not.prototype.toExpected = function(ruleDict) { return "no " + this.expr.toExpected(); }; // TODO: think about Listy and Obj pexprs.Apply.prototype.toExpected = function(ruleDict) { var description = ruleDict[this.ruleName].description; if (description) { return description; } else { var article = /^[aeiouAEIOU]/.test(this.ruleName) ? "an" : "a"; return article + " " + this.ruleName; } };
// -------------------------------------------------------------------- // Imports // -------------------------------------------------------------------- var common = require('./common.js'); var pexprs = require('./pexprs.js'); var awlib = require('awlib'); var printString = awlib.stringUtils.printString; var makeStringBuffer = awlib.objectUtils.stringBuffer; // -------------------------------------------------------------------- // Operations // -------------------------------------------------------------------- pexprs.PExpr.prototype.toExpected = function(ruleDict) { return undefined; }; pexprs.anything.toExpected = function(ruleDict) { return "any object"; }; pexprs.end.toExpected = function(ruleDict) { return "end of input"; }; pexprs.Prim.prototype.toExpected = function(ruleDict) { return printString(this.obj); }; pexprs.Not.prototype.toExpected = function(ruleDict) { if (this.expr === pexprs.anything) { return "nothing"; } else { return "no " + this.expr.toExpected(); } }; // TODO: think about Listy and Obj pexprs.Apply.prototype.toExpected = function(ruleDict) { var description = ruleDict[this.ruleName].description; if (description) { return description; } else { var article = /^[aeiouAEIOU]/.test(this.ruleName) ? "an" : "a"; return article + " " + this.ruleName; } };
Print end as "nothing" instead of "no any object"
Print end as "nothing" instead of "no any object"
JavaScript
mit
DanielTomlinson/ohm,cdglabs/ohm,DanielTomlinson/ohm,anfedorov/ohm,coopsource/ohm,anfedorov/ohm,coopsource/ohm,coopsource/ohm,cdglabs/ohm,anfedorov/ohm,harc/ohm,cdglabs/ohm,harc/ohm,harc/ohm,DanielTomlinson/ohm
1c6cfedaca2be22f1720b4f6cd64764199be173e
test/stores/Store.spec.js
test/stores/Store.spec.js
import store from "src/stores/Store.js"; describe("store", () => { it("should exist", () => { store.should.exist; }); it("should have all API methods", () => { store.dispatch.should.be.a.function; store.getState.should.be.a.function; store.replaceReducer.should.be.a.function; store.subscribe.should.be.a.function; }); });
import store from "src/stores/Store.js"; import app from "src/reducers/App.js"; describe("store", () => { it("should exist", () => { store.should.exist; }); it("should have all API methods", () => { store.dispatch.should.be.a.function; store.getState.should.be.a.function; store.replaceReducer.should.be.a.function; store.subscribe.should.be.a.function; }); it("should use app reducer", () => { var storeState = store.dispath({type: "bla-bla-bla"}); var defaultState = app(undefined, {type: "bla-bla-bla"}); storeState.should.be.eql(defaultState); }) });
Add test if store use app reducer
Refactor: Add test if store use app reducer
JavaScript
mit
Lingvokot/Tic-Tac-Toe-React,Lingvokot/Tic-Tac-Toe-React,Lingvokot/Tic-Tac-Toe-React
18a90886ef4ea64a75ff0182af60dff5a308052e
app/components/vm-hover.js
app/components/vm-hover.js
import Ember from 'ember'; export default Ember.Component.extend({ isShowingHover: false, commitTitle: function() { if (this.get('vm.commit.title').match(/^Merge/)) { return this.get('vm.commit.title').replace(/ of.*/g,'').replace(/ into.*/g,''); } return this.get('vm.commit.title'); }.property('vm.commit.title'), setShowingHover: function() { var access_level = this.get('session').get('data.authenticated.access_level'); if (access_level >= 20) { this.set('isShowingHover', this.get('isShowingHovers') === this.get('vm').id); } else { this.set('isShowingHover', false); } }.observes('isShowingHovers'), // Return true if is running state isRunning: function() { if (parseInt(this.get('vm.status'), 10) > 0) { return true; } return false; }.property('vm.status'), // Return true if user is a Dev or more isDev: function() { var access_level = this.get('session').get('data.authenticated.access_level'); if (access_level >= 30) { return true; } return false; }.property('session.data.authenticated.access_level'), actions: { // close the modal, reset showing variable closeHover: function() { this.set('isShowingHovers', -1); } } });
import Ember from 'ember'; export default Ember.Component.extend({ isShowingHover: false, commitTitle: function() { if (this.get('vm.commit.title') && this.get('vm.commit.title').match(/^Merge/)) { return this.get('vm.commit.title').replace(/ of.*/g,'').replace(/ into.*/g,''); } return this.get('vm.commit.title'); }.property('vm.commit.title'), setShowingHover: function() { var access_level = this.get('session').get('data.authenticated.access_level'); if (access_level >= 20) { this.set('isShowingHover', this.get('isShowingHovers') === this.get('vm').id); } else { this.set('isShowingHover', false); } }.observes('isShowingHovers'), // Return true if is running state isRunning: function() { if (parseInt(this.get('vm.status'), 10) > 0) { return true; } return false; }.property('vm.status'), // Return true if user is a Dev or more isDev: function() { var access_level = this.get('session').get('data.authenticated.access_level'); if (access_level >= 30) { return true; } return false; }.property('session.data.authenticated.access_level'), actions: { // close the modal, reset showing variable closeHover: function() { this.set('isShowingHovers', -1); } } });
Fix issue on match vm title
Fix issue on match vm title
JavaScript
mit
ricofehr/nextdeploy-webui,ricofehr/nextdeploy-webui
5abc414fc9e8249a1a89f4c7d5aa9e9c4f821e7d
src/config.js
src/config.js
import DefaultConfig from 'anyware/lib/game-logic/config/default-config'; import GAMES from 'anyware/lib/game-logic/constants/games'; class Config extends DefaultConfig { constructor() { super(); this.CLIENT_CONNECTION_OPTIONS = { protocol: "wss", username: "anyware", password: "anyware", host: "broker.shiftr.io" }; this.diskUrls = { disk0: 'images/disk0.png', disk1: 'images/disk1.png', disk2: 'images/disk2.png' }; this.projectionParameters = { scale: 1, translate: [0, 0], }; // this.GAMES_SEQUENCE = [ // GAMES.DISK, // GAMES.SIMON // ]; } // FIXME: Configure user colors here? How to communicate that to CSS? } export default new Config();
import DefaultConfig from 'anyware/lib/game-logic/config/default-config'; import GAMES from 'anyware/lib/game-logic/constants/games'; class Config extends DefaultConfig { constructor() { super(); this.DEBUG.console = true; this.CLIENT_CONNECTION_OPTIONS = { protocol: "wss", username: "anyware", password: "anyware", host: "broker.shiftr.io" }; this.diskUrls = { disk0: 'images/disk0.png', disk1: 'images/disk1.png', disk2: 'images/disk2.png' }; this.projectionParameters = { scale: 1, translate: [0, 0], }; // this.GAMES_SEQUENCE = [ // GAMES.DISK, // GAMES.SIMON // ]; } // FIXME: Configure user colors here? How to communicate that to CSS? } export default new Config();
Print console messages by default in the emulator
Print console messages by default in the emulator
JavaScript
mit
anyWareSculpture/sculpture-emulator-client,anyWareSculpture/sculpture-emulator-client
399a94ec926e48935a9a2d7139c1ef477125bd25
test/modules/version/program.js
test/modules/version/program.js
define(function (require) { var a = require('./a.js?v=1.0'); var a2 = require('./a.js?v=2.0'); var test = require('../../test'); test.assert(a.foo === 1, 'module version.'); test.assert(a.foo === a2.foo, 'module version.'); test.done(); });
define(function (require) { var a = require('./a.js?v=1.0'); var a2 = require('./a.js?v=2.0'); var test = require('../../test'); test.assert(a.foo === 1, a.foo); test.assert(a.foo === a2.foo, a2.foo); test.done(); });
Update the version test case
Update the version test case
JavaScript
mit
zaoli/seajs,angelLYK/seajs,zwh6611/seajs,yuhualingfeng/seajs,zwh6611/seajs,imcys/seajs,tonny-zhang/seajs,lee-my/seajs,ysxlinux/seajs,lianggaolin/seajs,mosoft521/seajs,FrankElean/SeaJS,judastree/seajs,angelLYK/seajs,tonny-zhang/seajs,chinakids/seajs,lee-my/seajs,yuhualingfeng/seajs,tonny-zhang/seajs,jishichang/seajs,longze/seajs,PUSEN/seajs,baiduoduo/seajs,kuier/seajs,AlvinWei1024/seajs,angelLYK/seajs,coolyhx/seajs,liupeng110112/seajs,lovelykobe/seajs,kaijiemo/seajs,PUSEN/seajs,Lyfme/seajs,121595113/seajs,yern/seajs,JeffLi1993/seajs,mosoft521/seajs,eleanors/SeaJS,seajs/seajs,LzhElite/seajs,miusuncle/seajs,yuhualingfeng/seajs,treejames/seajs,LzhElite/seajs,seajs/seajs,zaoli/seajs,hbdrawn/seajs,lianggaolin/seajs,evilemon/seajs,yern/seajs,baiduoduo/seajs,PUSEN/seajs,kuier/seajs,sheldonzf/seajs,coolyhx/seajs,Lyfme/seajs,hbdrawn/seajs,JeffLi1993/seajs,twoubt/seajs,yern/seajs,lee-my/seajs,MrZhengliang/seajs,coolyhx/seajs,121595113/seajs,jishichang/seajs,imcys/seajs,uestcNaldo/seajs,sheldonzf/seajs,treejames/seajs,kuier/seajs,moccen/seajs,miusuncle/seajs,AlvinWei1024/seajs,FrankElean/SeaJS,ysxlinux/seajs,zaoli/seajs,eleanors/SeaJS,chinakids/seajs,twoubt/seajs,jishichang/seajs,seajs/seajs,uestcNaldo/seajs,judastree/seajs,LzhElite/seajs,sheldonzf/seajs,liupeng110112/seajs,ysxlinux/seajs,imcys/seajs,liupeng110112/seajs,evilemon/seajs,evilemon/seajs,longze/seajs,MrZhengliang/seajs,treejames/seajs,uestcNaldo/seajs,wenber/seajs,lovelykobe/seajs,lovelykobe/seajs,wenber/seajs,lianggaolin/seajs,Gatsbyy/seajs,judastree/seajs,kaijiemo/seajs,mosoft521/seajs,longze/seajs,FrankElean/SeaJS,zwh6611/seajs,AlvinWei1024/seajs,MrZhengliang/seajs,13693100472/seajs,Gatsbyy/seajs,kaijiemo/seajs,JeffLi1993/seajs,Gatsbyy/seajs,eleanors/SeaJS,baiduoduo/seajs,moccen/seajs,13693100472/seajs,miusuncle/seajs,wenber/seajs,Lyfme/seajs,twoubt/seajs,moccen/seajs
c2179a52ea6c1a422061a25a83ee27428a5494fb
server.js
server.js
'use strict'; var config = require('./server/config'); var express = require('express'); var handlebars = require('express-handlebars'); var app = express(); // Middlewares configuration var oneWeek = 604800000; app.use(express.static('build', { maxAge: oneWeek })); app.use(express.static('data', { maxAge: oneWeek, extensions: ['png'] })); // Handlebars configuration app.set('views', 'client/views'); app.engine('.hbs', handlebars({ extname: '.hbs', partialsDir: ['client/views/components/', 'client/views/partials/'] })); app.set('view engine', '.hbs'); // Starts application listening app.listen(config.port, (err) => { console.log('running on ' + config.port); }); // Regsiters routes var indexRoutes = require('./server/routes/indexRoutes'); app.use('/', indexRoutes);
'use strict'; var config = require('./server/config'); var express = require('express'); var handlebars = require('express-handlebars'); var app = express(); // Middlewares configuration var oneWeek = 604800000; app.use(express.static('build')); app.use(express.static('data', { maxAge: oneWeek, extensions: ['png'] })); // Handlebars configuration app.set('views', 'client/views'); app.engine('.hbs', handlebars({ extname: '.hbs', partialsDir: ['client/views/components/', 'client/views/partials/'] })); app.set('view engine', '.hbs'); // Starts application listening app.listen(config.port, (err) => { console.log('running on ' + config.port); }); // Regsiters routes var indexRoutes = require('./server/routes/indexRoutes'); app.use('/', indexRoutes);
Remove cache on build folder
Remove cache on build folder
JavaScript
apache-2.0
Softcadbury/FootballDashboard,Softcadbury/football-peek,Softcadbury/FootballDashboard,Softcadbury/DashboardFootball,Softcadbury/DashboardFootball
5697e7eab5f1402a2e4ab7922e2f044429c8ac64
lib/helpers/helpers.js
lib/helpers/helpers.js
'use strict'; module.exports = { getClassesFromSelector: function (selector) { if (!selector) { return []; } var classRegEx = /[_a-zA-Z][_a-zA-Z0-9-]*/g; return selector.match(classRegEx); }, getSelectorLength: function (selector) { var classes = this.getClassesFromSelector(selector); return classes ? classes.length : 0; } };
'use strict'; module.exports = { getClassesFromSelector: function (selector) { if (!selector) { return []; } var classRegEx = /[_a-zA-Z][_a-zA-Z0-9-]*/g; return selector.match(classRegEx) || []; }, getSelectorLength: function (selector) { var classes = this.getClassesFromSelector(selector); return classes.length; } };
Return empty list on non match
Return empty list on non match
JavaScript
mit
timeinfeldt/grunt-csschecker,timeinfeldt/grunt-csschecker
36829b9b66474d38de527f2d1457c32b86500402
karma.conf.js
karma.conf.js
var webpack = require('webpack'); module.exports = function (config) { config.set({ browsers: [ process.env.CONTINUOUS_INTEGRATION ? 'Firefox' : 'Chrome' ], singleRun: process.env.CONTINUOUS_INTEGRATION === 'true', frameworks: [ 'mocha' ], files: [ 'tests.webpack.js' ], preprocessors: { 'tests.webpack.js': [ 'webpack', 'sourcemap' ] }, webpack: { devtool: 'inline-source-map', module: { loaders: [ { test: /\.js$/, loader: 'jsx-loader?harmony' } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('test') }) ] }, webpackServer: { noInfo: true } }); };
var webpack = require('webpack'); module.exports = function (config) { config.set({ browsers: [ process.env.CONTINUOUS_INTEGRATION ? 'Firefox' : 'Chrome' ], singleRun: process.env.CONTINUOUS_INTEGRATION === 'true', frameworks: [ 'mocha' ], files: [ 'tests.webpack.js' ], preprocessors: { 'tests.webpack.js': [ 'webpack', 'sourcemap' ] }, reporters: [ 'dots' ], webpack: { devtool: 'inline-source-map', module: { loaders: [ { test: /\.js$/, loader: 'jsx-loader?harmony' } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('test') }) ] }, webpackServer: { noInfo: true } }); };
Use "dots" karma reporter (for Travis CI web UI)
Use "dots" karma reporter (for Travis CI web UI)
JavaScript
mit
careerlounge/react-router,yanivefraim/react-router,kelsadita/react-router,rkit/react-router,qimingweng/react-router,Nedomas/react-router,calebmichaelsanchez/react-router,Gazler/react-router,vic/react-router,amplii/react-router,Semora/react-router,mozillo/react-router,FredKSchott/react-router,dozoisch/react-router,tmbtech/react-router,knowbody/react-router,dyzhu12/react-router,johnochs/react-router,wushuyi/react-router,steffenmllr/react-router,dalexand/react-router,meraki/react-router,brenoc/react-router,leeric92/react-router,jamiehill/react-router,gdi2290/react-router,leeric92/react-router,chrisirhc/react-router,gilesbradshaw/react-router,moudy/react-router,iest/react-router,zeke/react-router,rafrex/react-router,dandean/react-router,asaf/react-router,robertniimi/react-router,gaearon/react-router,clloyd/react-router,alexlande/react-router,chf2/react-router,lingard/react-router,pjuke/react-router,gabrielalmeida/react-router,BowlingX/react-router,kirill-konshin/react-router,Duc-Ngo-CSSE/react-router,lrs/react-router,wesbos/react-router,thewillhuang/react-router,Jastrzebowski/react-router,chrisirhc/react-router,iNikNik/react-router,devmeyster/react-router,flocks/react-router,fanhc019/react-router,yanivefraim/react-router,tmbtech/react-router,mjw56/react-router,goblortikus/react-router,robertniimi/react-router,micahlmartin/react-router,ricca509/react-router,yongxu/react-router,elpete/react-router,laskos/react-router,omerts/react-router,rackt/react-router,santiagoaguiar/react-router,jflam/react-router,okcoker/react-router,nickaugust/react-router,birkmann/react-router,fiture/react-router,calebmichaelsanchez/react-router,darul75/react-router,SpainTrain/react-router,skevy/react-router,jeffreywescott/react-router,pjuke/react-router,opichals/react-router,ricca509/react-router,rkaneriya/react-router,fractal5/react-router,idolize/react-router,egobrightan/react-router,muffinresearch/react-router,edpaget/react-router,mattcreager/react-router,reapp/react-router,etiennetremel/react-router,iamdustan/react-router,jobcrackerbah/react-router,pherris/react-router,runlevelsix/react-router,adityapunjani/react-router,goblortikus/react-router,stonegithubs/react-router,taion/rrtr,egobrightan/react-router,prathamesh-sonpatki/react-router,gbaladi/react-router,singggum3b/react-router,freeyiyi1993/react-router,pheadra/react-router,yongxu/react-router,mikekidder/react-router,dalexand/react-router,iamdustan/react-router,justinwoo/react-router,gabrielalmeida/react-router,stevewillard/react-router,aastey/react-router,bmathews/react-router,fractal5/react-router,justinanastos/react-router,masterfung/react-router,migolo/react-router,gabrielalmeida/react-router,lyle/react-router,mulesoft/react-router,tsing/react-router,KamilSzot/react-router,ustccjw/react-router,jepezi/react-router,clloyd/react-router,upraised/react-router,mattkrick/react-router,robertniimi/react-router,navyxie/react-router,oliverwoodings/react-router,iNikNik/react-router,juampynr/react-router,camsong/react-router,chunwei/react-router,kittens/react-router,devmeyster/react-router,contra/react-router,careerlounge/react-router,eriknyk/react-router,nosnickid/react-router,arbas/react-router,acdlite/react-router,sugarshin/react-router,mhils/react-router,Takeno/react-router,darul75/react-router,wesbos/react-router,andreftavares/react-router,cgrossde/react-router,osnr/react-router,ReactTraining/react-router,Duc-Ngo-CSSE/react-router,arthurflachs/react-router,apoco/react-router,TylerLH/react-router,jwaltonmedia/react-router,amsardesai/react-router,sebmck/react-router,zhijiansha123/react-router,nauzethc/react-router,emmenko/react-router,omerts/react-router,taurose/react-router,chloeandisabel/react-router,FbF/react-router,phoenixbox/react-router,ArmendGashi/react-router,angus-c/react-router,Gazler/react-router,Nedomas/react-router,mhuggins7278/react-router,goblortikus/react-router,brenoc/react-router,benjie/react-router,juampynr/react-router,nkatsaros/react-router,steffenmllr/react-router,alexlande/react-router,carlosmontes/react-router,asaf/react-router,ryardley/react-router,RobertKielty/react-router,jflam/react-router,pekkis/react-router,xiaoking/react-router,FredKSchott/react-router,dyzhu12/react-router,ksivam/react-router,tkirda/react-router,careerlounge/react-router,Jastrzebowski/react-router,cold-brew-coding/react-router,barretts/react-router,birkmann/react-router,TylerLH/react-router,cgrossde/react-router,knowbody/react-router,ndreckshage/react-router,edpaget/react-router,artnez/react-router,santiagoaguiar/react-router,javawizard/react-router,pekkis/react-router,baillyje/react-router,jbbr/react-router,frostney/react-router,Takeno/react-router,arbas/react-router,opichals/react-router,gaearon/react-router,dandean/react-router,geminiyellow/react-router,acdlite/react-router,subpopular/react-router,nickaugust/react-router,nosnickid/react-router,laskos/react-router,lrs/react-router,darul75/react-router,flocks/react-router,dmitrigrabov/react-router,JohnyDays/react-router,buildo/react-router,phoenixbox/react-router,kurayama/react-router,herojobs/react-router,buildo/react-router,birendra-ideas2it/react-router,vic/react-router,stanleycyang/react-router,javawizard/react-router,FredKSchott/react-router,zipongo/react-router,eriknyk/react-router,andreftavares/react-router,CivBase/react-router,runlevelsix/react-router,AnSavvides/react-router,jobcrackerbah/react-router,OrganicSabra/react-router,steffenmllr/react-router,littlefoot32/react-router,dmitrigrabov/react-router,arthurflachs/react-router,BowlingX/react-router,daannijkamp/react-router,1000hz/react-router,benjie/react-router,grgur/react-router,rackt/react-router,jerrysu/react-router,MattSPalmer/react-router,Semora/react-router,dtschust/react-router,gdi2290/react-router,wmyers/react-router,subpopular/react-router,BerkeleyTrue/react-router,stshort/react-router,zenlambda/react-router,keathley/react-router,bs1180/react-router,OpenGov/react-router,RickyDan/react-router,kenwheeler/react-router,besarthoxhaj/react-router,acdlite/react-router,zhijiansha123/react-router,mhuggins7278/react-router,nottombrown/react-router,prathamesh-sonpatki/react-router,gbaladi/react-router,okcoker/react-router,stonegithubs/react-router,nauzethc/react-router,ReactTraining/react-router,AsaAyers/react-router,stevewillard/react-router,mozillo/react-router,buildo/react-router,ndreckshage/react-router,edpaget/react-router,sprjr/react-router,justinanastos/react-router,dontcallmedom/react-router,jayphelps/react-router,Sirlon/react-router,arasmussen/react-router,yanivefraim/react-router,malte-wessel/react-router,daannijkamp/react-router,qimingweng/react-router,albertolacework/react-router,davertron/react-router,jbbr/react-router,d-oliveros/react-router,besarthoxhaj/react-router,sugarshin/react-router,sebmck/react-router,chentsulin/react-router,elpete/react-router,masterfung/react-router,vic/react-router,RickyDan/react-router,jhta/react-router,9618211/react-router,justinwoo/react-router,OrganicSabra/react-router,wmyers/react-router,andrefarzat/react-router,rkit/react-router,juampynr/react-router,aastey/react-router,juliocanares/react-router,Reggino/react-router,reapp/react-router,mattydoincode/react-router,cpojer/react-router,baillyje/react-router,mattcreager/react-router,skevy/react-router,pherris/react-router,iest/react-router,justinwoo/react-router,9618211/react-router,amplii/react-router,kevinsimper/react-router,fiture/react-router,neebz/react-router,johnochs/react-router,ThibWeb/react-router,sebmck/react-router,reactjs/react-router,gilesbradshaw/react-router,whouses/react-router,sugarshin/react-router,collardeau/react-router,mikekidder/react-router,mjw56/react-router,1000hz/react-router,Jonekee/react-router,birkmann/react-router,mulesoft/react-router,MrBackKom/react-router,arusakov/react-router,malte-wessel/react-router,packetloop/react-router,natorojr/react-router,timuric/react-router,aldendaniels/react-router,jmeas/react-router,masterfung/react-router,ThibWeb/react-router,appspector/react-router,jmeas/react-router,albertolacework/react-router,oliverwoodings/react-router,trotzig/react-router,nhunzaker/react-router,RickyDan/react-router,jwaltonmedia/react-router,laskos/react-router,lvgunst/react-router,1000hz/react-router,johnochs/react-router,adityapunjani/react-router,claudiopro/react-router,grgur/react-router,wesbos/react-router,geminiyellow/react-router,juliocanares/react-router,upraised/react-router,jerrysu/react-router,fractal5/react-router,mulesoft/react-router,opichals/react-router,RobertKielty/react-router,cpojer/react-router,jepezi/react-router,OpenGov/react-router,JohnyDays/react-router,zeke/react-router,lazywei/react-router,packetloop/react-router,camsong/react-router,nottombrown/react-router,elpete/react-router,nvartolomei/react-router,moudy/react-router,birendra-ideas2it/react-router,goblortikus/react-router,lmtdit/react-router,sprjr/react-router,ksivam/react-router,Sirlon/react-router,stanleycyang/react-router,muffinresearch/react-router,angus-c/react-router,brigand/react-router,rdjpalmer/react-router,samidarko/react-router,tikotzky/react-router,kevinsimper/react-router,leeric92/react-router,9618211/react-router,mikepb/react-router,brownbathrobe/react-router,martypenner/react-router,rubengrill/react-router,timuric/react-router,KamilSzot/react-router,jeffreywescott/react-router,etiennetremel/react-router,jflam/react-router,lyle/react-router,dashed/react-router,singggum3b/react-router,nimi/react-router,mattkrick/react-router,chloeandisabel/react-router,juliocanares/react-router,JohnyDays/react-router,naoufal/react-router,devmeyster/react-router,collardeau/react-router,dozoisch/react-router,kelsadita/react-router,shunitoh/react-router,Dodelkin/react-router,grgur/react-router,aaron-goshine/react-router,brandonlilly/react-router,santiagoaguiar/react-router,tylermcginnis/react-router,kurayama/react-router,mattcreager/react-router,benjie/react-router,lvgunst/react-router,jerrysu/react-router,chunwei/react-router,chloeandisabel/react-router,kittens/react-router,cold-brew-coding/react-router,tmbtech/react-router,dozoisch/react-router,asaf/react-router,javawizard/react-router,matthewlehner/react-router,iNikNik/react-router,kittens/react-router,nimi/react-router,flocks/react-router,frostney/react-router,lyle/react-router,jdelight/react-router,mikekidder/react-router,zeke/react-router,batmanimal/react-router,apoco/react-router,chf2/react-router,brigand/react-router,natorojr/react-router,whouses/react-router,martypenner/react-router,navyxie/react-router,dtschust/react-router,osnr/react-router,Jastrzebowski/react-router,lingard/react-router,arusakov/react-router,ustccjw/react-router,thefringeninja/react-router,stanleycyang/react-router,SpainTrain/react-router,krawaller/react-router,zipongo/react-router,hgezim/react-router,DelvarWorld/react-router,chentsulin/react-router,navy235/react-router,Gazler/react-router,iamdustan/react-router,xiaoking/react-router,freeyiyi1993/react-router,OrganicSabra/react-router,stevewillard/react-router,FreedomBen/react-router,MrBackKom/react-router,tsing/react-router,OpenGov/react-router,kevinsimper/react-router,amsardesai/react-router,jbbr/react-router,jmeas/react-router,axross/react-router,batmanimal/react-router,taurose/react-router,nkatsaros/react-router,emmenko/react-router,jdelight/react-router,tylermcginnis/react-router,aldendaniels/react-router,appspector/react-router,d-oliveros/react-router,collardeau/react-router,stonegithubs/react-router,contra/react-router,mikepb/react-router,omerts/react-router,MrBackKom/react-router,tikotzky/react-router,schnerd/react-router,emmenko/react-router,martypenner/react-router,mikepb/react-router,hgezim/react-router,naoufal/react-router,mhuggins7278/react-router,nosnickid/react-router,eriknyk/react-router,zhijiansha123/react-router,prathamesh-sonpatki/react-router,maksad/react-router,amplii/react-router,wushuyi/react-router,gaearon/react-router,lrs/react-router,camsong/react-router,FbF/react-router,shunitoh/react-router,keathley/react-router,cojennin/react-router,Sirlon/react-router,andrefarzat/react-router,backendeveloper/react-router,reactjs/react-router,Dodelkin/react-router,sleexyz/react-router,BerkeleyTrue/react-router,DelvarWorld/react-router,claudiopro/react-router,rkit/react-router,CivBase/react-router,jobcrackerbah/react-router,micahlmartin/react-router,kirill-konshin/react-router,singggum3b/react-router,dashed/react-router,osnr/react-router,sleexyz/react-router,naoufal/react-router,joeyates/react-router,oliverwoodings/react-router,jamiehill/react-router,knowbody/react-router,chentsulin/react-router,apoco/react-router,mhils/react-router,joeyates/react-router,stshort/react-router,nhunzaker/react-router,jayphelps/react-router,thewillhuang/react-router,Jonekee/react-router,frankleng/react-router,ReactTraining/react-router,ReactTraining/react-router,lmtdit/react-router,trotzig/react-router,dandean/react-router,brandonlilly/react-router,dtschust/react-router,cpojer/react-router,buddhike/react-router,micahlmartin/react-router,dontcallmedom/react-router,navy235/react-router,sleexyz/react-router,jhta/react-router,littlefoot32/react-router,keathley/react-router,lingard/react-router,nimi/react-router,contra/react-router,herojobs/react-router,Reggino/react-router,phoenixbox/react-router,rafrex/react-router,backendeveloper/react-router,barretts/react-router,artnez/react-router,rdjpalmer/react-router,ryardley/react-router,ArmendGashi/react-router,bs1180/react-router,limarc/react-router,timuric/react-router,bmathews/react-router,dyzhu12/react-router,tikotzky/react-router,MattSPalmer/react-router,claudiopro/react-router,aaron-goshine/react-router,arthurflachs/react-router,Takeno/react-router,idolize/react-router,packetloop/react-router,Reggino/react-router,samidarko/react-router,RobertKielty/react-router,djkirby/react-router,jhnns/react-router,gbaladi/react-router,AnSavvides/react-router,nvartolomei/react-router,zenlambda/react-router,frostney/react-router,idolize/react-router,nkatsaros/react-router,qimingweng/react-router,krawaller/react-router,matthewlehner/react-router,FreedomBen/react-router,brownbathrobe/react-router,mattydoincode/react-router,andrefarzat/react-router,frankleng/react-router,tsing/react-router,backendeveloper/react-router,Semora/react-router,migolo/react-router,Duc-Ngo-CSSE/react-router,jeffreywescott/react-router,AsaAyers/react-router,thefringeninja/react-router,djkirby/react-router,artnez/react-router,davertron/react-router,kenwheeler/react-router,FbF/react-router,rubengrill/react-router,herojobs/react-router,levjj/react-router,jhnns/react-router,muffinresearch/react-router,geminiyellow/react-router,adityapunjani/react-router,gdi2290/react-router,BowlingX/react-router,wushuyi/react-router,FreedomBen/react-router,maksad/react-router,limarc/react-router,thefringeninja/react-router,carlosmontes/react-router,dontcallmedom/react-router,mhils/react-router,cojennin/react-router,meraki/react-router,lazywei/react-router,angus-c/react-router,dashed/react-router,subpopular/react-router,brigand/react-router,neebz/react-router,ricca509/react-router,AsaAyers/react-router,justinanastos/react-router,gilesbradshaw/react-router,schnerd/react-router,fanhc019/react-router,levjj/react-router,pherris/react-router,appspector/react-router,jayphelps/react-router,navy235/react-router,besarthoxhaj/react-router,arasmussen/react-router,baillyje/react-router,pheadra/react-router,jepezi/react-router,kirill-konshin/react-router,daannijkamp/react-router,OpenGov/react-router,kenwheeler/react-router,alexlande/react-router,wmyers/react-router,freeyiyi1993/react-router,bmathews/react-router,buddhike/react-router,amsardesai/react-router,rkaneriya/react-router,axross/react-router,pekkis/react-router,xiaoking/react-router,tkirda/react-router
abfe24acc0c7d37bd59f91b66c8479730b8dad27
grammar.js
grammar.js
module.exports = grammar({ name: 'ruby', rules: { program: $ => $._compound_statement, _compound_statement: $ => seq($._statement, rep(seq($._terminator, $._expression)), optional($._terminator)), _statement: $ => choice($._expression), _expression: $ => choice($._argument), _argument: $ => choice($._primary), _primary: $ => choice($._variable), _variable: $ => choice($.identifier , 'nil', 'self'), identifier: $ => seq(rep(choice('@', '$')), /[a-zA-Z_][a-zA-Z0-9_]*/), _line_break: $ => '\n', _terminator: $ => choice($._line_break, ';'), } });
module.exports = grammar({ name: 'ruby', rules: { program: $ => $._compound_statement, _compound_statement: $ => seq($._statement, rep(seq($._terminator, $._expression)), optional($._terminator)), _statement: $ => choice($._expression), _expression: $ => choice($._argument), _argument: $ => choice($._primary), _primary: $ => choice($._variable), _variable: $ => choice($.identifier , 'nil', 'self'), identifier: $ => seq(rep(choice('@', '$')), /[a-zA-Z_][a-zA-Z0-9_]*/), comment: $ => seq('#', /.*/), _line_break: $ => '\n', _terminator: $ => choice($._line_break, ';'), } });
Define a dubious comment rule.
Define a dubious comment rule.
JavaScript
mit
tree-sitter/tree-sitter-ruby,tree-sitter/tree-sitter-ruby,tree-sitter/tree-sitter-ruby,tree-sitter/tree-sitter-ruby,tree-sitter/tree-sitter-ruby,tree-sitter/tree-sitter-ruby,tree-sitter/tree-sitter-ruby,tree-sitter/tree-sitter-ruby
3c153d1b1ccdcbb4ce20d8c4f55af73adceccfbc
src/flexio.js
src/flexio.js
import _ from 'lodash' import https from 'https' import axios from 'axios' import * as task from './task' import pipe from './pipe' import pipes from './pipes' import connections from './connections' var base_url = 'https://www.flex.io/api/v1' var cfg = { token: '', baseUrl: 'https://www.flex.io/api/v1', insecure: false, debug: false } export default { // see `../build/webpack.dist.js` version: VERSION, // allow all tasks exports from `./task/index.js` task, setup(token, params) { cfg = _.assign({}, { token }, params) this._createHttp() return this }, getConfig() { return _.assign({}, cfg) }, http() { if (!this._http) this._createHttp() return this._http }, pipe() { return pipe() }, pipes() { return pipes() }, connections() { return connections() }, _createHttp() { // axios instance options with base url and auth token var axios_opts = { baseURL: cfg.baseUrl, headers: { 'Authorization': 'Bearer ' + cfg.token } } // if the `insecure` flag is set, allow unauthorized HTTPS calls if (cfg.insecure === true) { _.assign(axios_opts, { httpsAgent: new https.Agent({ rejectUnauthorized: false }) }) } this._http = axios.create(axios_opts) } }
import _ from 'lodash' import axios from 'axios' import * as task from './task' import pipe from './pipe' import pipes from './pipes' import connections from './connections' var base_url = 'https://www.flex.io/api/v1' var cfg = { token: '', baseUrl: 'https://www.flex.io/api/v1', insecure: false, debug: false } export default { // see `../build/webpack.dist.js` version: VERSION, // allow all tasks exports from `./task/index.js` task, setup(token, params) { cfg = _.assign({}, { token }, params) this._createHttp() return this }, getConfig() { return _.assign({}, cfg) }, http() { if (!this._http) this._createHttp() return this._http }, pipe() { return pipe() }, pipes() { return pipes() }, connections() { return connections() }, _createHttp() { // axios instance options with base url and auth token var axios_opts = { baseURL: cfg.baseUrl, headers: { 'Authorization': 'Bearer ' + cfg.token } } // TODO: try to figure out a better way to do this... // if the `insecure` flag is set, allow unauthorized HTTPS calls if (cfg.insecure === true) process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0" this._http = axios.create(axios_opts) } }
Use `process.env.NODE_TLS_REJECT_UNAUTHORIZED` to make insecure calls.
Use `process.env.NODE_TLS_REJECT_UNAUTHORIZED` to make insecure calls.
JavaScript
mit
flexiodata/flexio-sdk-js,flexiodata/flexio-sdk-js
a6a74ccf7f7b42844bf8f50dc5db18c914b7f61e
src/main/webapp/js/controller/ProtocolListController.js
src/main/webapp/js/controller/ProtocolListController.js
'use strict'; indexApp.controller('ProtocolListController', function ProtocolListController($scope, indexData, $location){ $scope.protocolList = indexData.getProtocolList(); $scope.deleteProtocol = function(protocol){ indexData.deleteProtocol(protocol); $location.path('/'); } } );
'use strict'; indexApp.controller('ProtocolListController', function ProtocolListController($scope, indexData, $location){ $scope.protocolList = indexData.getProtocolList(); $scope.deleteProtocol = function(protocol){ indexData.deleteProtocol(protocol); $scope.protocolList = indexData.getProtocolList(); $location.path('/'); } } );
Refresh protocol list after protocol removal
Refresh protocol list after protocol removal
JavaScript
mit
GreyTeardrop/typeground,GreyTeardrop/typeground,GreyTeardrop/typeground
d24fe086319e786c18e9378178cbbfaca15978e6
src/tests/jasmine/client/unit/sample/spec/PlayerSpec.js
src/tests/jasmine/client/unit/sample/spec/PlayerSpec.js
/* globals Player: false, Song: false */ describe('Player', function() { var player; var song; beforeEach(function() { player = new Player(); song = new Song(); }); it('should be able to play a Song', function() { player.play(song); expect(player.currentlyPlayingSong).toEqual(song); //demonstrates use of custom matcher expect(player).toBePlaying(song); }); describe('when song has been paused', function() { beforeEach(function() { player.play(song); player.pause(); }); it('should indicate that the song is currently paused', function() { expect(player.isPlaying).toBeFalsy(); // demonstrates use of 'not' with a custom matcher expect(player).not.toBePlaying(song); }); it('should be possible to resume', function() { player.resume(); expect(player.isPlaying).toBeTruthy(); expect(player.currentlyPlayingSong).toEqual(song); }); }); // demonstrates use of spies to intercept and test method calls it('tells the current song if the user has made it a favorite', function() { spyOn(song, 'persistFavoriteStatus'); player.play(song); player.makeFavorite(); expect(song.persistFavoriteStatus).toHaveBeenCalledWith(true); }); });
/* globals Player: false, Song: false */ describe('Player', function() { var player; var song; beforeEach(function() { player = new Player(); song = new Song(); }); it('should be able to play a Song', function() { player.play(song); expect(player.currentlyPlayingSong).toEqual(0); //demonstrates use of custom matcher expect(player).toBePlaying(song); }); describe('when song has been paused', function() { beforeEach(function() { player.play(song); player.pause(); }); it('should indicate that the song is currently paused', function() { expect(player.isPlaying).toBeFalsy(); // demonstrates use of 'not' with a custom matcher expect(player).not.toBePlaying(song); }); it('should be possible to resume', function() { player.resume(); expect(player.isPlaying).toBeTruthy(); expect(player.currentlyPlayingSong).toEqual(song); }); }); // demonstrates use of spies to intercept and test method calls it('tells the current song if the user has made it a favorite', function() { spyOn(song, 'persistFavoriteStatus'); player.play(song); player.makeFavorite(); expect(song.persistFavoriteStatus).toHaveBeenCalledWith(true); }); });
Build and tests work, now testing that it will actually fail if a test fails
Build and tests work, now testing that it will actually fail if a test fails
JavaScript
mit
Zywave/Retrospectre,Zywave/Retrospectre,Zywave/Retrospectre
63bfd706d40c35b14fd852ff1efa8e0eb6237f08
RNTester/js/examples/XHR/XHRExampleAbortController.js
RNTester/js/examples/XHR/XHRExampleAbortController.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow */ 'use strict'; const React = require('react'); const {Alert, Button, View} = require('react-native'); class XHRExampleAbortController extends React.Component<{...}, {...}> { _timeout: any; _submit(abortDelay) { clearTimeout(this._timeout); // eslint-disable-next-line no-undef const abortController = new AbortController(); fetch('https://facebook.github.io/react-native/', { signal: abortController.signal, }) .then(res => res.text()) .then(res => Alert.alert(res)) .catch(err => Alert.alert(err.message)); this._timeout = setTimeout(() => { abortController.abort(); }, abortDelay); } componentWillUnmount() { clearTimeout(this._timeout); } render(): React.Node { return ( <View> <Button title="Abort before response" onPress={() => { this._submit(0); }} /> <Button title="Abort after response" onPress={() => { this._submit(5000); }} /> </View> ); } } module.exports = XHRExampleAbortController;
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow */ 'use strict'; const React = require('react'); const {Alert, Button, View} = require('react-native'); class XHRExampleAbortController extends React.Component<{...}, {...}> { _timeout: any; _submit(abortDelay) { clearTimeout(this._timeout); const abortController = new global.AbortController(); fetch('https://facebook.github.io/react-native/', { signal: abortController.signal, }) .then(res => res.text()) .then(res => Alert.alert(res)) .catch(err => Alert.alert(err.message)); this._timeout = setTimeout(() => { abortController.abort(); }, abortDelay); } componentWillUnmount() { clearTimeout(this._timeout); } render(): React.Node { return ( <View> <Button title="Abort before response" onPress={() => { this._submit(0); }} /> <Button title="Abort after response" onPress={() => { this._submit(5000); }} /> </View> ); } } module.exports = XHRExampleAbortController;
Move eslint-disable no-undef to a global comment
Move eslint-disable no-undef to a global comment Summary: Switch the only `// eslint-disable no-undef` to defined the global instead so that the new babel-eslint-no-undef compile time check doesn't need to understand inline eslint comments. Changelog: [Internal] Reviewed By: cpojer Differential Revision: D18644590 fbshipit-source-id: ac9c6da3a5e63b285b5e1dde210613b5d893641b
JavaScript
mit
facebook/react-native,facebook/react-native,hammerandchisel/react-native,arthuralee/react-native,janicduplessis/react-native,facebook/react-native,javache/react-native,exponent/react-native,myntra/react-native,javache/react-native,exponentjs/react-native,facebook/react-native,janicduplessis/react-native,janicduplessis/react-native,myntra/react-native,hammerandchisel/react-native,arthuralee/react-native,exponent/react-native,hoangpham95/react-native,janicduplessis/react-native,hoangpham95/react-native,pandiaraj44/react-native,facebook/react-native,exponent/react-native,exponent/react-native,facebook/react-native,hammerandchisel/react-native,hoangpham95/react-native,exponent/react-native,arthuralee/react-native,hammerandchisel/react-native,exponentjs/react-native,myntra/react-native,hoangpham95/react-native,janicduplessis/react-native,hoangpham95/react-native,exponentjs/react-native,exponentjs/react-native,exponentjs/react-native,myntra/react-native,exponent/react-native,pandiaraj44/react-native,facebook/react-native,arthuralee/react-native,hoangpham95/react-native,hammerandchisel/react-native,javache/react-native,hammerandchisel/react-native,pandiaraj44/react-native,hoangpham95/react-native,myntra/react-native,pandiaraj44/react-native,janicduplessis/react-native,facebook/react-native,javache/react-native,myntra/react-native,pandiaraj44/react-native,myntra/react-native,pandiaraj44/react-native,janicduplessis/react-native,javache/react-native,exponent/react-native,javache/react-native,myntra/react-native,pandiaraj44/react-native,exponentjs/react-native,javache/react-native,hammerandchisel/react-native,javache/react-native,facebook/react-native,myntra/react-native,exponentjs/react-native,exponent/react-native,hoangpham95/react-native,exponentjs/react-native,hammerandchisel/react-native,janicduplessis/react-native,pandiaraj44/react-native,javache/react-native,arthuralee/react-native
d38e1808a476d6783bf9ea0989e8dfb61ad6b731
lib/name-formatter.js
lib/name-formatter.js
var _ = require('underscore'); module.exports = function(name) { var nameConversions = [ firstInitialAndLastName = /^(\w).*\s(\w+)$/, firstAndLastName = /^(\w+)\s(\w+)$/, firstNameAndLastInitial = /^(\w+)\s(\w).+$/ ]; var emailDelimiters = [ contiguous = "$1$2", dot = "$1.$2", dash = "$1-$2", underscore = "$1_$2", reversed = "$2$1", reversedDot = "$2.$1", reversedDash = "$2-$1", reversedUnderscore = "$2_$1", justLastName = "$2", justFirstName = "$1", ]; return name.toLowerCase().replace( _.shuffle(nameConversions)[0], _.shuffle(emailDelimiters)[0] ) + randomSuffix(); }; // Generate the random chance that a random number will be affixed to the end function randomSuffix() { var randomChance = Math.round(Math.random()); if ( randomChance ) { return Math.floor(Math.random()*1001); } else { return ""; } }
var _ = require('underscore'); module.exports = function(name) { var nameConversions = [ initials = /^(\w).*\s(\w).*$/ firstInitialAndLastName = /^(\w).*\s(\w+)$/, firstAndLastName = /^(\w+)\s(\w+)$/, firstNameAndLastInitial = /^(\w+)\s(\w).+$/ ]; var emailDelimiters = [ contiguous = "$1$2", dot = "$1.$2", dash = "$1-$2", underscore = "$1_$2", reversed = "$2$1", reversedDot = "$2.$1", reversedDash = "$2-$1", reversedUnderscore = "$2_$1", justLastName = "$2", justFirstName = "$1", ]; return name.toLowerCase().replace( _.shuffle(nameConversions)[0], _.shuffle(emailDelimiters)[0] ) + randomSuffix(); }; // Generate the random chance that a random number will be affixed to the end function randomSuffix() { var randomChance = Math.round(Math.random()); if ( randomChance ) { return Math.floor(Math.random()*101); } else { return ""; } }
Add initials and lower random number
Add initials and lower random number
JavaScript
mit
stevekinney/node-fake-email