commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
c0df19293939a7d706fb00748b5521af7376bdf0
Fix issue with data refresh rate configuration
app/components/app/index.js
app/components/app/index.js
import numeral from 'numeral' import WS from 'websocket' import subscriptions from 'resources/subscriptions' class LocalStorage { get(key) { var value = localStorage.getItem(key) if (typeof value !== 'undefined') { try { value = JSON.parse(value) } catch (e) { console.error('Invalid storage object') console.error(e) } } return value } set(key, value) { localStorage.setItem(key, JSON.stringify(value)) } remove(key) { localStorage.removeItem(key) } } // Layout wrapper functions function wrapper(type) { return function(...contents) { return { type: type, contents: contents } } } var row = wrapper('row') var col = wrapper('col') var section = wrapper('section') var module = function(id, config={}) { return { type: 'module', id: id, 'module-config': config, } } var storage = new LocalStorage() export default { template: require('./template.jade')({styles: require('./stylesheet.sass')}), components: { layout: require('../layout'), settings: require('../settings'), actiongroups: require('../modules/actiongroups'), history: require('../modules/history'), map: require('../modules/map'), navigation: require('../modules/navigation'), orbit: require('../modules/orbit'), resources: require('../modules/resources'), vessel: require('../modules/vessel'), }, data() { var config = storage.get('config') var refreshRate = config ? (config.refreshRate || 1) : 1 return { config: config || { telemachus: { host: '10.0.0.110', port: 8085, refreshRate: refreshRate, refreshInterval: parseInt(1 / refreshRate * 1000), }, rendering: { fps: 60, useNormalMaps: true, useSpecularMaps: true, showSkybox: true, showLensFlare: true, postProcessing: true, }, }, storage: storage, ws: null, wsConnected: false, settingsVisible: false, data: {}, layout: [ col( row( section( row( col( module('actiongroups') ) ) ) ), row( section(module('orbit')) ), row( section(module('map')) ) ) ], } }, created() { // Connect to Telemachus socket this.ws = new WS(`ws://${this.config.telemachus.host}:${this.config.telemachus.port}/datalink`) this.ws.addOpenHandler(() => { this.wsConnected = true // Subscribe to data from Telemachus this.ws.send({rate: this.config.telemachus.refreshInterval, '+': subscriptions}) }) this.ws.addCloseHandler(() => this.wsConnected = false) this.ws.addMessageHandler(ev => { var msg = JSON.parse(ev.data) console.debug('Received message from Telemachus:', msg) Object.keys(msg).forEach(k => { if (!this.data[k]) { this.data.$add(k, null) } this.data[k] = msg[k] }) }) this.ws.connect().fail(msg => console.error(msg)) }, methods: { numeral: numeral, saveConfig() { this.storage.set('config', this.config) }, }, }
JavaScript
0.000001
@@ -1396,17 +1396,27 @@ )%0A%09%09var -r +telemachusR efreshRa @@ -1437,16 +1437,27 @@ (config. +telemachus. refreshR @@ -1469,16 +1469,178 @@ %7C 1) : 1 +%0A%09%09var telemachusRefreshInterval = parseInt(1 / telemachusRefreshRate * 1000)%0A%09%09if (config) %7B%0A%09%09%09config.telemachus.refreshInterval = telemachusRefreshInterval%0A%09%09%7D %0A%0A%09%09retu @@ -1745,17 +1745,27 @@ shRate: -r +telemachusR efreshRa @@ -1794,40 +1794,33 @@ al: -parseInt(1 / refreshRate * 1000) +telemachusRefreshInterval ,%0A%09%09
c9ff3546b1819e256e8ca47b51f9f9818d0e5b02
Update FirstUsePage propTypes
src/pages/FirstUsePage.js
src/pages/FirstUsePage.js
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import React from 'react'; import PropTypes from 'prop-types'; import { Image, StyleSheet, Text, TextInput, View } from 'react-native'; import { Button } from 'react-native-ui-components'; import { SyncState } from '../widgets'; import { getAppVersion } from '../settings'; import { DemoUserModal } from '../widgets/modals'; import globalStyles, { SUSSOL_ORANGE, WARM_GREY } from '../globalStyles'; export class FirstUsePage extends React.Component { constructor(props) { super(props); this.state = { appVersion: '', status: 'uninitialised', // uninitialised, initialising, initialised, error. serverURL: '', syncSiteName: '', syncSitePassword: '', isDemoUserModalOpen: false, }; this.setAppVersion(); this.siteNameInputRef = null; this.passwordInputRef = null; this.onPressConnect = this.onPressConnect.bind(this); } async onPressConnect() { const { onInitialised, synchroniser } = this.props; const { serverURL, syncSiteName, syncSitePassword } = this.state; try { this.setState({ status: 'initialising' }); await synchroniser.initialise(serverURL, syncSiteName, syncSitePassword); this.setState({ status: 'initialised' }); onInitialised(); } catch (error) { this.setState({ status: 'error' }); } } async setAppVersion() { const appVersion = await getAppVersion(); this.setState({ appVersion }); } get canAttemptLogin() { const { status, serverURL, syncSiteName, syncSitePassword } = this.state; return ( (status === 'uninitialised' || status === 'error') && serverURL.length > 0 && syncSiteName.length > 0 && syncSitePassword.length > 0 ); } get buttonText() { const { syncState } = this.props; const { status } = this.state; const { progressMessage, errorMessage, progress, total } = syncState; switch (status) { case 'initialising': return `${progressMessage}${total > 0 ? `\n${progress}/${total}` : ''}`; case 'error': return `${errorMessage}\nTap to retry.`; case 'initialised': return 'Success!'; default: return 'Connect'; } } handleDemoModalOpen = () => this.setState({ isDemoUserModalOpen: true }); handleDemoModalClose = () => this.setState({ isDemoUserModalOpen: false }); render() { const { syncState } = this.props; const { appVersion, isDemoUserModalOpen, serverURL, status, syncSiteName, syncSitePassword, } = this.state; return ( <View style={[globalStyles.verticalContainer, localStyles.verticalContainer]}> <View style={globalStyles.authFormContainer}> <Image resizeMode="contain" style={globalStyles.authFormLogo} // eslint-disable-next-line global-require source={require('../images/logo_large.png')} /> <View style={globalStyles.horizontalContainer}> <TextInput style={globalStyles.authFormTextInputStyle} placeholderTextColor={SUSSOL_ORANGE} underlineColorAndroid={SUSSOL_ORANGE} placeholder="Primary Server URL" value={serverURL} editable={status !== 'initialising'} returnKeyType="next" selectTextOnFocus autoCorrect={false} onChangeText={text => this.setState({ serverURL: text, status: 'uninitialised' })} onSubmitEditing={() => { if (this.siteNameInputRef) this.siteNameInputRef.focus(); }} /> </View> <View style={globalStyles.horizontalContainer}> <TextInput ref={reference => { this.siteNameInputRef = reference; }} style={globalStyles.authFormTextInputStyle} placeholderTextColor={SUSSOL_ORANGE} underlineColorAndroid={SUSSOL_ORANGE} placeholder="Sync Site Name" value={syncSiteName} editable={status !== 'initialising'} returnKeyType="next" selectTextOnFocus onChangeText={text => this.setState({ syncSiteName: text, status: 'uninitialised' })} onSubmitEditing={() => { if (this.passwordInputRef) this.passwordInputRef.focus(); }} /> </View> <View style={globalStyles.horizontalContainer}> <TextInput ref={reference => { this.passwordInputRef = reference; }} style={globalStyles.authFormTextInputStyle} placeholder="Sync Site Password" placeholderTextColor={SUSSOL_ORANGE} underlineColorAndroid={SUSSOL_ORANGE} value={syncSitePassword} secureTextEntry editable={status !== 'initialising'} returnKeyType="done" selectTextOnFocus onChangeText={text => this.setState({ syncSitePassword: text, status: 'uninitialised', }) } onSubmitEditing={() => { if (this.passwordInputRef) this.passwordInputRef.blur(); if (this.canAttemptLogin) this.onPressConnect(); }} /> </View> <SyncState style={localStyles.initialisationStateIcon} state={syncState} showText={false} /> <View style={globalStyles.authFormButtonContainer}> <Button style={globalStyles.authFormButton} textStyle={globalStyles.authFormButtonText} text={this.buttonText} onPress={this.onPressConnect} disabledColor={WARM_GREY} isDisabled={!this.canAttemptLogin} /> </View> </View> <View style={localStyles.demoSiteRequestButtonContainer}> <View style={globalStyles.horizontalContainer}> <Button style={[globalStyles.authFormButton, { flex: 1 }]} textStyle={globalStyles.authFormButtonText} text="Request a Demo Store" onPress={this.handleDemoModalOpen} disabledColor={WARM_GREY} isDisabled={status !== 'uninitialised' && status !== 'error'} /> </View> </View> <Text style={globalStyles.authWindowButtonText}> v{appVersion}</Text> <DemoUserModal isOpen={isDemoUserModalOpen} onClose={this.handleDemoModalClose} /> </View> ); } } export default FirstUsePage; /* eslint-disable react/forbid-prop-types */ FirstUsePage.propTypes = { onInitialised: PropTypes.func.isRequired, synchroniser: PropTypes.object.isRequired, syncState: PropTypes.object.isRequired, }; const localStyles = StyleSheet.create({ demoSiteRequestButtonContainer: { marginHorizontal: 300, alignItems: 'center', justifyContent: 'flex-start', }, initialisationStateIcon: { marginTop: 46, marginBottom: 24, }, verticalContainer: { alignItems: 'center', flex: 1, }, });
JavaScript
0
@@ -119,25 +119,24 @@ rop-types';%0A -%0A import %7B Ima @@ -246,24 +246,65 @@ mponents';%0A%0A +import %7B Synchroniser %7D from '../sync';%0A%0A import %7B Syn @@ -6878,53 +6878,8 @@ e;%0A%0A -/* eslint-disable react/forbid-prop-types */%0A Firs @@ -6963,38 +6963,56 @@ iser: PropTypes. -object +instanceOf(Synchroniser) .isRequired,%0A s @@ -7035,14 +7035,156 @@ pes. -object +shape(%7B%0A progressMessage: PropTypes.string,%0A errorMessage: PropTypes.string,%0A progress: PropTypes.number,%0A total: PropTypes.number,%0A %7D) .isR
8eda3ea7d42ac0986577b1f73d9af18cac7428a0
remove test image uri
src/MessageImage.js
src/MessageImage.js
import PropTypes from 'prop-types'; import React from 'react'; import { Image, StyleSheet, View, ViewPropTypes, Dimensions, TouchableWithoutFeedback, Modal, } from 'react-native'; import Lightbox from 'react-native-lightbox'; import PhotoView from 'react-native-photo-view'; import GiftedChatInteractionManager from './GiftedChatInteractionManager'; import I18n from './I18nUtil'; export default class MessageImage extends React.Component { constructor(props) { super(props); this.state = { uri: this.props.currentMessage.image, switchToDefaultImg: false, retryTime: 0, } } onLoad() { // console.log('onLoad'); // if (this.state.retryTime >= 3) { // this.setState({ // uri: this.getFullSizeImageUri(), // retryTime: 0, // switchToDefaultImg: false, // }); // } } onLoadError(e) { if (this.errTimer) clearTimeout(this.errTimer); // console.log('onError rt:', this.state.retryTime); if (this.state.retryTime >= 3) { // GiftedChatInteractionManager.runAfterInteractions(() => { this.errTimer = setTimeout(() => { this.setState({ switchToDefaultImg: true }); }, 100); // }); } else { // GiftedChatInteractionManager.runAfterInteractions(() => { this.errTimer = setTimeout(() => { const newRetryTime = this.state.retryTime + 1; this.setState({ retryTime: newRetryTime, uri: this.getFullSizeImageUri() + '&retryTime=' + newRetryTime, }); }, 100); // }); } } onOpen() { // GiftedChatInteractionManager.runAfterInteractions(() => { setTimeout(() => { this.setState({ uri: this.getFullSizeImageUri(), retryTime: 0, switchToDefaultImg: false, }); }, 100); // }); } onClose() { // GiftedChatInteractionManager.runAfterInteractions(() => { setTimeout(() => { this.setState({ uri: this.getThumbImageUri(), }); }, 100); // }); } getThumbImageUri() { return this.props.currentMessage.image; } getFullSizeImageUri() { return this.props.currentMessage.image.replace('index=1', 'index=0'); } renderImage() { // console.log('switchToDefaultImg:', this.state.switchToDefaultImg); if (this.state.switchToDefaultImg === true) { return ( <Image {...this.props.imageProps} style={[styles.thumb, this.props.imageStyle]} source={require('./images/missing_image.png')} /> ); } return ( <Image {...this.props.imageProps} style={[styles.image, this.props.imageStyle]} source={{uri: this.state.uri}} onLoad={() => { this.onLoad() }} onError={e => { this.onLoadError(e) }} /> ); } render() { const { width, height } = Dimensions.get('window'); return ( <View style={[styles.container, this.props.containerStyle]}> {/* <Lightbox activeProps={{ style: [styles.imageActive, { width, height }], }} springConfig={{ tension: 40, friction: 7 }} {...this.props.lightboxProps} onClose={() => { this.onClose() }} onOpen={() => { this.onOpen() }} > {this.renderImage()} </Lightbox> */} <TouchableWithoutFeedback onPress={() => {this.onOpen()}}> {this.renderImage()} </TouchableWithoutFeedback> <Modal visible={this.state.openModal} transparent={true} animationType='none'> <View style={{flex:1, width, height, alignItems:'center', justifyContent:'center', backgroundColor:'#000'}}> <PhotoView source={{uri: 'http://1.bp.blogspot.com/_7ErfTFmlXs8/S7LVbJN0EHI/AAAAAAAAAXg/9NpEDjUxMws/s1600/%E7%86%8A%E5%90%89.JPG'}} minimumZoomScale={1} maximumZoomScale={4} androidScaleType="center" style={{width, height}}/> <View style={{position:'absolute', backgroundColor:'transparent', right:20, top:20}}> <TouchableWithoutFeedback onPress={() => {this.onClose()}}> <View style={styles.closeButton}> <Text style={{fontSize:16, color:'#CCC'}}> {I18n.get('Close')} </Text> </View> </TouchableWithoutFeedback> </View> </View> </Modal> </View> ); } } const styles = StyleSheet.create({ container: { }, thumb: { width: 64, height: 64, borderRadius: 13, margin: 3, resizeMode: 'cover', }, image: { width: 150, height: 100, borderRadius: 13, margin: 3, resizeMode: 'cover', }, imageActive: { flex: 1, resizeMode: 'contain', }, closeButton: { padding: 5, borderStyle: 'solid', borderWidth: StyleSheet.hairlineWidth, borderColor: '#CCC', borderRadius: 6, } }); MessageImage.defaultProps = { currentMessage: { image: null, }, containerStyle: {}, imageStyle: {}, }; MessageImage.propTypes = { currentMessage: PropTypes.object, containerStyle: ViewPropTypes.style, imageStyle: Image.propTypes.style, imageProps: PropTypes.object, lightboxProps: PropTypes.object, };
JavaScript
0.000002
@@ -3458,112 +3458,22 @@ ri: -'http://1.bp.blogspot.com/_7ErfTFmlXs8/S7LVbJN0EHI/AAAAAAAAAXg/9NpEDjUxMws/s1600/%25E7%2586%258A%25E5%2590%2589.JPG' +this.state.uri %7D%7D%0A%09
bef2d7ca9d21a31d5ba663c1ee533ca3eb51a1b4
Fix the z-index problem with other front-end libs, like Bootstrap
gulpfile.js
gulpfile.js
/* eslint-env node */ /* eslint strict:0 */ var gulp = require("gulp"); var insert = require("gulp-file-insert"); var uglify = require("gulp-uglify"); var cssnano = require("gulp-cssnano"); var eslint = require("gulp-eslint"); var autoprefixer = require("gulp-autoprefixer"); var sass = require("gulp-sass"); var size = require("gulp-size"); var runSequnce = require("run-sequence"); var connect = require("gulp-connect"); var karma = require("karma").Server; var concat = require("gulp-concat"); var p = function (path) { return __dirname + (path.charAt(0) === "/" ? "" : "/") + path; }; gulp.task("css", function() { return gulp .src(p("src/aNoty.scss")) .pipe(sass()) .pipe(autoprefixer("last 8 version", {cascade: true})) .pipe(cssnano()) .pipe(size({ gzip: true, showFiles: true })) .pipe(gulp.dest(p("dist"))) .pipe(connect.reload()); }); gulp.task("js", function () { return gulp .src(p("src/aNoty.js")) .pipe(insert({"/* style.css */": "dist/aNoty.css"})) .pipe(uglify({ outSourceMap: false })) .pipe(size({ gzip: true, showFiles: true })) .pipe(gulp.dest(p("dist"))) .pipe(connect.reload()); }); gulp.task("lint", function() { return gulp .src(p("src/*.js")) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failOnError()); }); gulp.task("karma", function (done) { new karma({ configFile: __dirname + "/karma.conf.js" }, function() { done(); }).start(); }); gulp.task("connect", function() { connect.server({ root: "dist", livereload: true, port: 3000 }); }); gulp.task("test", ["lint", "karma"]); gulp.task("watch", function () { gulp.watch([ p("src/*.scss"), p("src/*.js") ], ["build"]); }); gulp.task("build", function(cb) { runSequnce("css", "lint", "js", cb); }); gulp.task("default", ["connect", "karma", "watch"]);
JavaScript
0.000826
@@ -767,16 +767,33 @@ cssnano( +%7B zindex: false %7D ))%0A
651942a878833813753d1309d237c0e34dba53aa
I might know where is the problem
public/js/controllers/calculations.js
public/js/controllers/calculations.js
updateCalculations = function (inputSet, voltages) { //Epsilon - relative permittivity, hardcoded for now var epsilon = inputSet.e; var a0_anion = Number(inputSet.a0Anion); var a0_cation = Number(inputSet.a0Cation); var gamma_anion = Number(inputSet.gammaAnion); var gamma_cation = Number(inputSet.gammaCation); //Also known as sigma anion var anionCharges = calculateSurfaceCharges(inputSet.anion.r, a0_anion, gamma_anion, inputSet.electrode, epsilon, voltages); //Also known as sigma cation var cationCharges = calculateSurfaceCharges(inputSet.cation.r, a0_cation, gamma_cation, inputSet.electrode, epsilon, voltages); var charges = mergeSurfaceCharges(anionCharges, cationCharges, inputSet.anion, inputSet.cation, voltages); //Equation 2 stuff var u2s = calculateU2s(charges, inputSet.electrode, epsilon); //Equation 3 stuff var cs = calculateCs(charges, voltages, u2s); inputSet.data = cs; }; //Used for calculating anion and cation surface charge. //Same function is used for both since their models are similar //(at least the values relevant to the calculation are named the same) calculateSurfaceCharges = function (r, a0, gamma, electrode, epsilon, voltages) { //Constant value var c1 = 16.02177; //Constant value var c2 = 0.8854188;//[F/nm] //constant value var e = 2.718282; //theta max is equal to c1 / r^2 var thetaMax = c1 / Math.pow(r, 2); //[1e/nm2] //u max is equal to theta max * (d + r) * c2 / epsilon var uMax = thetaMax * (electrode.d + r) * c2 / epsilon; //[1e/nm*] var values = []; for (var i = 0; i < voltages.length; i++) { var u1 = voltages[i]; var u = u1 / uMax; //-1 if u1 is negative, 1 if u1 is positive(or zero) via js ternary operator var stepFunction = u1 > 0 ? 1 : -1; //exponent is equal to e ^ [ a0 + (1 - a0) * e^(- gamma * u^2) ] var exponent = Math.pow(e, a0 + (1 - a0) * Math.pow(e, -gamma * Math.pow(u, 2))); //The surface charge of the ion, marked with sigma usually var charge = stepFunction * thetaMax * Math.abs(u) * exponent; values.push(charge); } return values; }; mergeSurfaceCharges = function (anionCharges, cationCharges, anion, cation, voltages) { var gamma = Math.sqrt(anion.gamma * cation.gamma); var values = []; for (var i = 0; i < voltages.length; i++) { var u1 = voltages[i]; var anionWeight = 0.5 + tanh(gamma * u1) / 2; var cationWeight = 0.5 - tanh(gamma * u1) / 2; var charge = anionCharges[i] * anionWeight + cationCharges[i] * cationWeight; values.push(charge); } return values; }; calculateU2s = function (surfaceCharges, electrode, epsilon) { //Constant value var c2 = 0.8854188; var values = []; for (var i = 0; i < surfaceCharges.length; i++) { var sigma = surfaceCharges[i]; var f_sigma = electrode.f1 + (electrode.f2 - electrode.f1) * (tanh(sigma / electrode.f3) + 1) / 2; var g_sigma = electrode.g1 * Math.pow((sigma - electrode.g2), 2) + electrode.g3; var u2 = -sigma / (1 / f_sigma + 1 / g_sigma) * c2 / epsilon; values.push(u2); } return values; }; calculateCs = function (sigmas, u1s, u2s) { var values = []; for (var i = 0; i < sigmas.length - 1; i++) { var uCurrent = Number(u1s[i]) + u2s[i]; var uNext = Number(u1s[i + 1]) + u2s[i + 1]; var uDelta = uCurrent - uNext; var sigmaCurrent = sigmas[i]; var sigmaNext = sigmas[i + 1]; var sigmaDelta = sigmaCurrent - sigmaNext; values.push(sigmaDelta / uDelta); } return values; };
JavaScript
0.688868
@@ -2801,32 +2801,55 @@ /Constant value%0A + var c1 = 16.02177;%0A var c2 = 0.8 @@ -3056,16 +3056,21 @@ (sigma / + c1 / electro @@ -3140,16 +3140,21 @@ ((sigma +/ c1 - electr
21c9f0c6f54925e677edcbcc5e21f44c15c54656
Call private method (Fix #70)
src/Menu.js
src/Menu.js
import React from 'react'; import PropTypes from 'prop-types'; import { Animated, Dimensions, Easing, Modal, Platform, StatusBar, StyleSheet, TouchableWithoutFeedback, View, ViewPropTypes, } from 'react-native'; const STATES = { HIDDEN: 'HIDDEN', ANIMATING: 'ANIMATING', SHOWN: 'SHOWN', }; const ANIMATION_DURATION = 300; const EASING = Easing.bezier(0.4, 0, 0.2, 1); const SCREEN_INDENT = 8; class Menu extends React.Component { _container = null; state = { menuState: STATES.HIDDEN, top: 0, left: 0, menuWidth: 0, menuHeight: 0, buttonWidth: 0, buttonHeight: 0, menuSizeAnimation: new Animated.ValueXY({ x: 0, y: 0 }), opacityAnimation: new Animated.Value(0), }; _setContainerRef = ref => { this._container = ref; }; // Start menu animation _onMenuLayout = e => { if (this.state.menuState === STATES.ANIMATING) { return; } const { width, height } = e.nativeEvent.layout; this.setState( { menuState: STATES.ANIMATING, menuWidth: width, menuHeight: height, }, () => { Animated.parallel([ Animated.timing(this.state.menuSizeAnimation, { toValue: { x: width, y: height }, duration: ANIMATION_DURATION, easing: EASING, }), Animated.timing(this.state.opacityAnimation, { toValue: 1, duration: ANIMATION_DURATION, easing: EASING, }), ]).start(); }, ); }; _onDismiss = () => { if (this.props.onHidden) { this.props.onHidden(); } }; show = () => { this._container.measureInWindow((left, top, buttonWidth, buttonHeight) => { this.setState({ buttonHeight, buttonWidth, left, menuState: STATES.SHOWN, top, }); }); }; hide = onHidden => { Animated.timing(this.state.opacityAnimation, { toValue: 0, duration: ANIMATION_DURATION, easing: EASING, }).start(() => { // Reset state this.setState( { menuState: STATES.HIDDEN, menuSizeAnimation: new Animated.ValueXY({ x: 0, y: 0 }), opacityAnimation: new Animated.Value(0), }, () => { if (onHidden) { onHidden(); } // Invoke onHidden callback if defined if (Platform.OS !== 'ios' && this.props.onHidden) { this.props.onHidden(); } }, ); }); }; render() { const dimensions = Dimensions.get('window'); const { width: windowWidth } = dimensions; const windowHeight = dimensions.height - (StatusBar.currentHeight || 0); const { menuSizeAnimation, menuWidth, menuHeight, buttonWidth, buttonHeight, opacityAnimation, } = this.state; const menuSize = { width: menuSizeAnimation.x, height: menuSizeAnimation.y, }; // Adjust position of menu let { left, top } = this.state; const transforms = []; // Flip by X axis if menu hits right screen border if (left > windowWidth - menuWidth - SCREEN_INDENT) { transforms.push({ translateX: Animated.multiply(menuSizeAnimation.x, -1), }); left = Math.min(windowWidth - SCREEN_INDENT, left + buttonWidth); } else if (left < SCREEN_INDENT) { left = SCREEN_INDENT; } // Flip by Y axis if menu hits bottom screen border if (top > windowHeight - menuHeight - SCREEN_INDENT) { transforms.push({ translateY: Animated.multiply(menuSizeAnimation.y, -1), }); top = windowHeight - SCREEN_INDENT; top = Math.min(windowHeight - SCREEN_INDENT, top + buttonHeight); } else if (top < SCREEN_INDENT) { top = SCREEN_INDENT; } const shadowMenuContainerStyle = { opacity: opacityAnimation, transform: transforms, left, top, }; const { menuState } = this.state; const animationStarted = menuState === STATES.ANIMATING; const modalVisible = menuState === STATES.SHOWN || animationStarted; const { testID, button, style, children } = this.props; return ( <View ref={this._setContainerRef} collapsable={false} testID={testID}> <View>{button}</View> <Modal visible={modalVisible} onRequestClose={this.hide} supportedOrientations={[ 'portrait', 'portrait-upside-down', 'landscape', 'landscape-left', 'landscape-right', ]} transparent onDismiss={this._onDismiss} > <TouchableWithoutFeedback onPress={this.hide} accessible={false}> <View style={StyleSheet.absoluteFill}> <Animated.View onLayout={this._onMenuLayout} style={[ styles.shadowMenuContainer, shadowMenuContainerStyle, style, ]} > <Animated.View style={[styles.menuContainer, animationStarted && menuSize]} > {children} </Animated.View> </Animated.View> </View> </TouchableWithoutFeedback> </Modal> </View> ); } } Menu.propTypes = { button: PropTypes.node.isRequired, children: PropTypes.node.isRequired, onHidden: PropTypes.func, style: ViewPropTypes.style, testID: ViewPropTypes.testID, }; const styles = StyleSheet.create({ shadowMenuContainer: { position: 'absolute', backgroundColor: 'white', borderRadius: 4, opacity: 0, // Shadow ...Platform.select({ ios: { shadowColor: 'black', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.14, shadowRadius: 2, }, android: { elevation: 8, }, }), }, menuContainer: { overflow: 'hidden', }, }); export default Menu;
JavaScript
0
@@ -2541,16 +2541,83 @@ ;%0A %7D;%0A%0A + // @@ TODO: Rework this%0A _hide = () =%3E %7B%0A this.hide();%0A %7D;%0A%0A render @@ -4465,24 +4465,25 @@ Close=%7Bthis. +_ hide%7D%0A @@ -4786,24 +4786,25 @@ Press=%7Bthis. +_ hide%7D access
addfa716d8c67acac90676786768d0bd15e42cd8
fix house menu
src/Modules/Web/js/houseMenu.js
src/Modules/Web/js/houseMenu.js
/** * @name: PyHouse/src/Modules/Web/js/houseMenu.js * @author: D. Brian Kimmel * @contact: [email protected] * @Copyright (c) 2012-2014 by D. Brian Kimmel * @license: MIT License * @note: Created about 2012 * @summary: Displays the house menu element * */ // import Nevow.Athena // import globals // import helpers /** * The house menu widget. * */ helpers.Widget.subclass(houseMenu, 'HouseMenuWidget').methods( function __init__(self, node) { houseMenu.HouseMenuWidget.upcall(self, "__init__", node); }, // ============================================================================ /** * Startup - Place the widget in the workspace and hide it. * * Override the ready function in C{ helpers.Widget.ready() } */ function ready(self) { function cb_widgetready(res) { // do whatever init needs here, show for the widget is handled in superclass self.hideWidget(); } var uris = collectIMG_src(self.node, null); var l_defer = loadImages(uris); l_defer.addCallback(cb_widgetready); return l_defer; }, function startWidget(self) { showSelectionButtons(self); self.buildLcarSelectScreen(); }, // ============================================================================ /** * Build a screen full of buttons - One for each menu item and some actions. */ function menuItems(self){ var l_list = [ // Key, Caption, Widget Name ['Location' , 'House Information', 'House' ], ['Rooms', 'Rooms', 'Rooms' ], ['Lights', 'Lights', 'Lights' ], ['Buttons', 'Buttons', 'Buttons' ], ['Controllers', 'Controllers', 'Controllers' ], ['Schedules', 'Scheduling', 'Schedules' ], ['Levels', 'Lighhting Control', 'ControlLighting' ], ['Internet', 'Network Addressing', 'Internet' ], ['Thermo', 'Thermostat', 'Thermostat' ], ['Weather', 'Weather', 'Weather' ], ['Nodes', 'Nodes', 'Nodes' ] ]; return l_list; }, function buildLcarSelectScreen(self){ var l_menu_html = "<div class='lcars-row spaced'>\n"; l_menu_html += buildLcarMenuButtons(self.menuItems(), 'doHandleOnClick'); l_menu_html += "</div>\n"; l_menu_html += "<div class='lcars-row spaced'>\n"; l_obj = {'Name' : 'Back', 'Key' : 'Back'}; l_menu_html += buildLcarButton(l_obj, 'doHandleOnClick', 'lcars-salmon-bg'); l_menu_html += "</div>\n"; var l_html = build_lcars_top('House Menu', 'lcars-salmon-color'); l_html += build_lcars_middle_menu(10, l_menu_html); l_html += build_lcars_bottom(); self.nodeById('SelectionButtonsDiv').innerHTML = l_html; }, // ============================================================================ /** * @param self is <"Instance" of undefined.houseMenu.HouseMenuWidget> * @param p_node is node <button> of the button clicked */ function doHandleOnClick(self, p_node) { var l_key = p_node.name; var l_node; switch (l_key) { case 'Location': self.showWidget('House'); break; case 'Rooms': self.showWidget('Rooms'); break; case 'Lights': self.showWidget('Lights'); break; case 'Buttons': self.showWidget('Buttons'); break; case 'Controllers': self.showWidget('Controllers'); break; case 'Schedules': self.showWidget('Schedules'); break; case 'Internet': self.showWidget('Internet'); break; case 'Nodes': self.showWidget('Nodes'); break; case 'Thermo': self.showWidget('Thermostat'); break; case 'Back': self.showWidget('RootMenu'); break; default: Divmod.debug('---', 'houseMenu.doHandleOnClick(Default) was called.'); break; } } ); // Divmod.debug('---', 'houseMenu.doHandleOnClick(Default) was called.'); // console.log("houseMenu.handleDataOnClick() json %O", l_json); // END DBK
JavaScript
0.000004
@@ -1858,17 +1858,16 @@ 'Ligh -h ting Con @@ -1872,16 +1872,17 @@ ontrol', + 'Cont @@ -3195,20 +3195,21 @@ %09%09case ' -Room +Level s':%0A%09%09%09s @@ -3224,21 +3224,31 @@ Widget(' -Rooms +ControlLighting ');%0A%09%09%09b @@ -3607,32 +3607,87 @@ es');%0A%09%09%09break;%0A +%09%09case 'Rooms':%0A%09%09%09self.showWidget('Rooms');%0A%09%09%09break;%0A %09%09case 'Thermo':
74791ac1f4049094bb84e30645e3cbc7d7e7c04f
Allow smaller rockety.yml file by removing configurations which are not needed. For example you may not need any "copy" directive, or "watch". There are project which do not require JavaScript (or CSS, lol). It is possible to comment/remove these rows from the config file and it will not break the build/watch process
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var fs = require('fs'); var merge = require('merge2'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); var less = require('gulp-less'); var sass = require('gulp-sass'); var cleancss = require('gulp-clean-css'); var autoprefixer = require('gulp-autoprefixer'); var sourcemaps = require('gulp-sourcemaps'); var svgstore = require('gulp-svgstore'); var svgmin = require('gulp-svgmin'); var cheerio = require('gulp-cheerio'); var jshint = require('gulp-jshint'); var stylish = require('jshint-stylish'); var uglify = require('gulp-uglify'); var livereload = require('gulp-livereload'); var config = require('js-yaml').safeLoad(fs.readFileSync('rockety.yml', 'utf8')); var sources = []; gulp.task('config', function () { console.log(JSON.stringify(config, null, 4)); }); function css(config) { var stream, vendors = [], vendor, css; (config.css.vendor || []).forEach(function (item) { vendors.push('./src/vendor/' + item); }); vendor = gulp.src(vendors); if (config.css.styles) { css = merge( gulp.src(config.css.styles.less ? config.source + '/less/' + config.css.styles.less : []).pipe(less()), gulp.src(config.css.styles.sass ? config.source + '/sass/' + config.css.styles.sass : []).pipe(sass()) ).pipe(autoprefixer({ browsers: ['last 2 versions'], cascade: false })); } stream = merge(vendor, css || gulp.src([])); if (config.css.sourcemap) { stream = stream.pipe(sourcemaps.init()); } if (config.css.minify) { stream = stream.pipe(cleancss()); } stream = stream.pipe(concat('style.css')); if (config.css.sourcemap) { stream = stream.pipe(sourcemaps.write()); } stream = stream.pipe(gulp.dest(config.dest + '/css')); stream.pipe(livereload()); } function svg(config) { return gulp.src(config.source + '/svg/*.svg') .pipe(rename({prefix: 'shape-'})) .pipe(svgmin()) .pipe(svgstore()) .pipe(cheerio({ run: function ($) { $('svg').attr('style', 'display:none'); }, parserOptions: {xmlMode: true} })) .pipe(rename('shapes.svg')) .pipe(gulp.dest(config.dest + '/svg')) .pipe(livereload()); } function js(config) { var stream, vendors = [], vendor, scripts = [], script; (config.js.vendor || []).forEach(function (item) { vendors.push('./src/vendor/' + item); }); vendor = gulp.src(vendors); (config.js.scripts || []).forEach(function (item) { scripts.push(config.source + '/js/' + item); }); script = gulp.src(scripts); if (scripts.length) { script = script.pipe(jshint()).pipe(jshint.reporter('jshint-stylish', {beep: true})); } stream = merge(vendor, script); if (config.js.sourcemap) { stream = stream.pipe(sourcemaps.init()); } if (config.js.minify) { stream = stream.pipe(uglify()); } stream = stream.pipe(concat('scripts.js', {newLine: ';'})); if (config.js.sourcemap) { stream = stream.pipe(sourcemaps.write()); } stream = stream.pipe(gulp.dest(config.dest + '/js')); stream.pipe(livereload()); } config.forEach(function (source) { sources.push(source.source); gulp.task('css:' + source.source, function () { return css(source) }); gulp.task('svg:' + source.source, function () { return svg(source) }); gulp.task('js:' + source.source, function () { return js(source) }); gulp.task('reload:' + source.source, function () { gulp.src(source.watch).pipe(livereload()); }); gulp.task('copy:' + source.source, function () { source.copy.forEach(function(files) { Object.keys(files).forEach(function(src) { gulp.src(src).pipe(gulp.dest(files[src])).pipe(livereload()); }); }); }); }); gulp.task('css', (sources.map(function(source) { return 'css:' + source; })), function () {}); gulp.task('svg', (sources.map(function(source) { return 'svg:' + source; })), function () {}); gulp.task('js', (sources.map(function(source) { return 'js:' + source; })), function () {}); gulp.task('reload', (sources.map(function(source) { return 'reload:' + source; })), function () {}); gulp.task('copy', (sources.map(function(source) { return 'copy:' + source; })), function () {}); gulp.task('build', ['css', 'svg', 'js'], function () {}); gulp.task('watch', function () { livereload.listen(); config.forEach(function(source) { gulp.watch(source.source + '/less/*.less', ['css:' + source.source]); gulp.watch(source.source + '/sass/*.sass', ['css:' + source.source]); gulp.watch(source.source + '/sass/*.scss', ['css:' + source.source]); gulp.watch(source.source + '/svg/*.svg', ['svg:' + source.source]); gulp.watch(source.source + '/js/*.js', ['js:' + source.source]); gulp.watch(source.watch, ['reload:' + source.source]); var copySources = []; (source.copy || []).forEach(function(files) { Object.keys(files).forEach(function(src) { copySources.push(src); }); }); gulp.watch(copySources, ['copy:' + source.source]); }); });
JavaScript
0.000001
@@ -886,16 +886,62 @@ , css;%0A%0A + if (!config.css) %7B%0A return;%0A %7D%0A%0A (con @@ -980,32 +980,32 @@ nction (item) %7B%0A - vendors. @@ -2462,16 +2462,61 @@ cript;%0A%0A + if (!config.js) %7B%0A return;%0A %7D%0A%0A (con @@ -3866,24 +3866,25 @@ ) %7B%0A +( source.copy. @@ -3882,16 +3882,23 @@ rce.copy + %7C%7C %5B%5D) .forEach @@ -5122,32 +5122,32 @@ ource.source%5D);%0A - gulp.wat @@ -5161,16 +5161,22 @@ ce.watch + %7C%7C %5B%5D , %5B'relo
eea11678c5960cbce7ba827296c91b7d0af1465a
Update master.js
js/master.js
js/master.js
var Master = function(){ var main = ""; return { init: function(){ $('main').html(main); } }; }();
JavaScript
0.000001
@@ -73,24 +73,81 @@ function()%7B%0A + %0A console.log(main);%0A %0A
0c114883e1bd09873e1450e8cb28c3552b1813c4
Add unique ids to CurveLocation.
src/path/CurveLocation.js
src/path/CurveLocation.js
/* * Paper.js - The Swiss Army Knife of Vector Graphics Scripting. * http://paperjs.org/ * * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey * http://lehni.org/ & http://jonathanpuckey.com/ * * Distributed under the MIT license. See LICENSE file for details. * * All rights reserved. */ /** * @name CurveLocation * * @class CurveLocation objects describe a location on {@link Curve} * objects, as defined by the curve {@link #parameter}, a value between * {@code 0} (beginning of the curve) and {@code 1} (end of the curve). If * the curve is part of a {@link Path} item, its {@link #index} inside the * {@link Path#curves} array is also provided. * * The class is in use in many places, such as * {@link Path#getLocationAt(offset, isParameter)}, * {@link Path#getLocationOf(point)}, * {@link Path#getNearestLocation(point), * {@link PathItem#getIntersections(path)}, * etc. */ var CurveLocation = this.CurveLocation = Base.extend(/** @lends CurveLocation# */{ // DOCS: CurveLocation class description: add these back when the mentioned // functioned have been added: {@link Path#split(location)} /** * Creates a new CurveLocation object. * * @param {Curve} curve * @param {Number} parameter * @param {Point} point */ initialize: function(curve, parameter, point, distance) { this._curve = curve; // Also store references to segment1 and segment2, in case path // splitting / dividing is going to happen, in which case the segments // can be used to determine the new curves, see #getCurve(true) this._segment1 = curve._segment1; this._segment2 = curve._segment2; this._parameter = parameter; this._point = point; this._distance = distance; }, /** * The segment of the curve which is closer to the described location. * * @type Segment * @bean */ getSegment: function() { if (!this._segment) { var curve = this.getCurve(), parameter = this.getParameter(); if (parameter == 0) { this._segment = curve._segment1; } else if (parameter == 1) { this._segment = curve._segment2; } else if (parameter == null) { return null; } else { // Determine the closest segment by comparing curve lengths this._segment = curve.getLength(0, parameter) < curve.getLength(parameter, 1) ? curve._segment1 : curve._segment2; } } return this._segment; }, /** * The curve by which the location is defined. * * @type Curve * @bean */ getCurve: function(/* uncached */) { if (!this._curve || arguments[0]) { // If we're asked to get the curve uncached, access current curve // objects through segment1 / segment2. Since path splitting or // dividing might have happened in the meantime, try segment1's // curve, and see if _point lies on it still, otherwise assume it's // the curve before segment2. this._curve = this._segment1.getCurve(); if (this._curve.getParameterOf(this._point) == null) this._curve = this._segment2.getPrevious().getCurve(); } return this._curve; }, /** * The path this curve belongs to, if any. * * @type Item * @bean */ getPath: function() { var curve = this.getCurve(); return curve && curve._path; }, /** * The index of the curve within the {@link Path#curves} list, if the * curve is part of a {@link Path} item. * * @type Index * @bean */ getIndex: function() { var curve = this.getCurve(); return curve && curve.getIndex(); }, /** * The length of the path from its beginning up to the location described * by this object. * * @type Number * @bean */ getOffset: function() { var path = this.getPath(); return path && path._getOffset(this); }, /** * The length of the curve from its beginning up to the location described * by this object. * * @type Number * @bean */ getCurveOffset: function() { var curve = this.getCurve(), parameter = this.getParameter(); return parameter != null && curve && curve.getLength(0, parameter); }, /** * The curve parameter, as used by various bezier curve calculations. It is * value between {@code 0} (beginning of the curve) and {@code 1} (end of * the curve). * * @type Number * @bean */ getParameter: function(/* uncached */) { if ((this._parameter == null || arguments[0]) && this._point) { var curve = this.getCurve(arguments[0] && this._point); this._parameter = curve && curve.getParameterOf(this._point); } return this._parameter; }, /** * The point which is defined by the {@link #curve} and * {@link #parameter}. * * @type Point * @bean */ getPoint: function() { if (!this._point && this._parameter != null) { var curve = this.getCurve(); this._point = curve && curve.getPointAt(this._parameter, true); } return this._point; }, /** * The tangential vector to the {@link #curve} at the given location. * * @type Point * @bean */ getTangent: function() { var parameter = this.getParameter(), curve = this.getCurve(); return parameter != null && curve && curve.getTangentAt(parameter, true); }, /** * The normal vector to the {@link #curve} at the given location. * * @type Point * @bean */ getNormal: function() { var parameter = this.getParameter(), curve = this.getCurve(); return parameter != null && curve && curve.getNormalAt(parameter, true); }, /** * The distance from the queried point to the returned location. * * @type Number * @bean */ getDistance: function() { return this._distance; }, divide: function() { var curve = this.getCurve(true); return curve && curve.divide(this.getParameter(true)); }, split: function() { var curve = this.getCurve(true); return curve && curve.split(this.getParameter(true)); }, /** * @return {String} A string representation of the curve location. */ toString: function() { var parts = [], point = this.getPoint(), f = Formatter.instance; if (point) parts.push('point: ' + point); var index = this.getIndex(); if (index != null) parts.push('index: ' + index); var parameter = this.getParameter(); if (parameter != null) parts.push('parameter: ' + f.number(parameter)); if (this._distance != null) parts.push('distance: ' + f.number(this._distance)); return '{ ' + parts.join(', ') + ' }'; } });
JavaScript
0
@@ -1321,16 +1321,123 @@ ance) %7B%0A +%09%09// Define this CurveLocation's unique id.%0A%09%09this._id = CurveLocation._id = (CurveLocation._id %7C%7C 0) + 1;%0A %09%09this._
aaba6612761d2f1498c531d2217ea7be9b629fdf
Build all files in `src`.
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var babel = require('gulp-babel'); gulp.task('default', function() { return gulp.src('src/URTSI.js') .pipe(babel()) .pipe(gulp.dest('dist')); });
JavaScript
0
@@ -118,13 +118,12 @@ src/ -URTSI +**/* .js'
798b3018d1123ac9eb6c5b3cf1d4498973e1a71e
Fix problem with interleaving upserts
src/storage/electronSqlite.js
src/storage/electronSqlite.js
import path from 'path'; // NOTE: We use window.require instead of require or import so that // Webpack doesn't transform it. These requires happen at runtime // via Electron loading mechanisms. const {app} = window.require('electron').remote; const db = window.require('sqlite'); class ElectronSqliteBackend { constructor(dbFilename) { this.dbFilename = dbFilename; } async initialize() { await db.open(this.dbFilename); await db.run('CREATE TABLE IF NOT EXISTS kv (k TEXT PRIMARY KEY, v TEXT)'); } async getItem(key) { const row = await db.get('SELECT * FROM kv WHERE k = ?', key); return row && row.v; } async setItem(key, value) { // This is supposedly the right way to upsert in sqlite // NOTE: If we had other writers, this would need to be in a transaction await db.run('UPDATE kv SET v = ? WHERE k = ?', value, key); await db.run('INSERT INTO kv (k, v) SELECT ?, ? WHERE changes() = 0', key, value); } async removeItem(key) { await db.run('DELETE FROM kv WHERE k = ?', key); } } export default async function createBackend() { const userDataPath = app.getPath('userData'); const dbFilename = path.join(userDataPath, 'voracious.db'); const backend = new ElectronSqliteBackend(dbFilename); await backend.initialize(); return backend; }
JavaScript
0.998319
@@ -746,137 +746,489 @@ TE: -If we had other writers, this would need to be in a transaction%0A await db.run('UPDATE kv SET v = ? WHERE k = ?', value, key);%0A +This wouldn't really be safe if we had multiple calls%0A // to setItem for same key back to back. There could be a race%0A // where they both try to INSERT, I think.%0A // TODO: Since all calls go through this same backend object,%0A // and they're all async, we could serialize them here.%0A const %7B changes %7D = await db.run('UPDATE kv SET v = ? WHERE k = ?', value, key);%0A if (changes === 0) %7B%0A // If changes is 0 that means the UPDATE failed to match any rows%0A @@ -1267,39 +1267,21 @@ v) -SELECT ?, ? WHERE changes() = 0 +VALUES (?, ?) ', k @@ -1292,16 +1292,22 @@ value);%0A + %7D%0A %7D%0A%0A a
aa648ed13fa2a3c488989468dd5c41420abba37d
Update docusaurus.config.js (#18577)
docs/docusaurus.config.js
docs/docusaurus.config.js
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ // @ts-check // Note: type annotations allow type checking and IDEs autocompletion const lightCodeTheme = require('prism-react-renderer/themes/github'); const darkCodeTheme = require('prism-react-renderer/themes/dracula'); /** @type {import('@docusaurus/types').Config} */ const config = { title: 'Superset', tagline: 'Apache Superset is a modern data exploration and visualization platform', url: 'https://superset.apache.org', baseUrl: '/', onBrokenLinks: 'throw', onBrokenMarkdownLinks: 'throw', favicon: 'img/favicon.ico', organizationName: 'apache', // Usually your GitHub org/user name. projectName: 'superset', // Usually your repo name. themes: [ '@saucelabs/theme-github-codeblock' ], plugins: [ [ '@docusaurus/plugin-client-redirects', { fromExtensions: ['html', 'htm'], toExtensions: ['exe', 'zip'], redirects: [ { to: '/docs/installation/installing-superset-using-docker-compose', from: '/installation.html', }, { to: '/docs/intro', from: '/tutorials.html', }, { to: '/docs/Creating Charts and Dashboards/creating-your-first-dashboard', from: '/admintutorial.html', }, { to: '/docs/Creating Charts and Dashboards/creating-your-first-dashboard', from: '/usertutorial.html', }, { to: '/docs/security', from: '/security.html', }, { to: '/docs/installation/sql-templating', from: '/sqllab.html', }, { to: '/docs/intro', from: '/gallery.html', }, { to: '/docs/connecting-to-databases/druid', from: '/druid.html', }, { to: '/docs/miscellaneous/country-map-tools', from: '/misc.html', }, { to: '/docs/miscellaneous/country-map-tools', from: '/visualization.html', }, { to: '/docs/frequently-asked-questions', from: '/videos.html', }, { to: '/docs/frequently-asked-questions', from: '/faq.html', }, { to: '/docs/Creating Charts and Dashboards/creating-your-first-dashboard', from: '/tutorial.html', }, { to: '/docs/installation/alerts-reports', from: '/docs/installation/email-reports', }, { to: '/docs/intro', from: '/docs/roadmap', }, ], }, ], ], presets: [ [ '@docusaurus/preset-classic', /** @type {import('@docusaurus/preset-classic').Options} */ ({ docs: { sidebarPath: require.resolve('./sidebars.js'), editUrl: 'https://github.com/apache/superset/tree/master/docs-v2', }, blog: { showReadingTime: true, // Please change this to your repo. editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/blog/', }, theme: { customCss: require.resolve('./src/css/custom.css'), }, }), ], ], themeConfig: /** @type {import('@docusaurus/preset-classic').ThemeConfig} */ ({ colorMode: { defaultMode: 'light', disableSwitch: true, }, navbar: { logo: { alt: 'Superset Logo', src: 'img/superset-logo-horiz.svg', srcDark: 'img/superset-logo-horiz-dark.svg', }, items: [ { type: 'doc', docId: 'intro', position: 'left', label: 'Documentation', }, { to: '/community', label: 'Community', position: 'left' }, { href: 'https://github.com/apache/superset', label: 'GitHub', position: 'right', }, ], }, footer: { style: 'dark', links: [ { title: 'Docs', items: [ { label: 'Tutorial', to: '/docs/intro', }, ], }, { title: 'Community', items: [ { label: 'Stack Overflow', href: 'https://stackoverflow.com/questions/tagged/superset+apache-superset', }, { label: 'Slack', href: 'https://join.slack.com/t/apache-superset/shared_invite/zt-uxbh5g36-AISUtHbzOXcu0BIj7kgUaw', }, { label: 'Mailing List', href: 'https://lists.apache.org/[email protected]', }, ], }, { title: 'More', items: [ { label: 'GitHub', href: 'https://github.com/apache/superset', }, ], }, ], copyright: `Copyright © ${new Date().getFullYear()}, The <a href="https://www.apache.org/" target="_blank" rel="noreferrer">Apache Software Foundation</a>, Licensed under the Apache <a href="https://apache.org/licenses/LICENSE-2.0" target="_blank" rel="noreferrer">License</a>. <br/> <small>Apache Superset, Apache, Superset, the Superset logo, and the Apache feather logo are either registered trademarks or trademarks of The Apache Software Foundation. All other products or name brands are trademarks of their respective holders, including The Apache Software Foundation. <a href="https://www.apache.org/" target="_blank">Apache Software Foundation</a> resources</small><br /> <small> <a href="https://www.apache.org/security/" target="_blank" rel="noreferrer">Security</a>&nbsp;|&nbsp; <a href="https://www.apache.org/foundation/sponsorship.html" target="_blank" rel="noreferrer">Donate</a>&nbsp;|&nbsp; <a href="https://www.apache.org/foundation/thanks.html" target="_blank" rel="noreferrer">Thanks</a>&nbsp;|&nbsp; <a href="https://apache.org/events/current-event" target="_blank" rel="noreferrer">Events</a>&nbsp;|&nbsp; <a href="https://apache.org/licenses/" target="_blank" rel="noreferrer">License</a> </small>`, }, prism: { theme: lightCodeTheme, darkTheme: darkCodeTheme, }, }), }; module.exports = config;
JavaScript
0
@@ -3798,11 +3798,8 @@ docs --v2 ',%0A
e84017440250b7c10063f04a5a985c885f04fae9
update cli help info
bin/commands/open.js
bin/commands/open.js
/** * @file command `open` * @author zdying */ 'use strict'; var fs = require('fs'); var path = require('path'); var homedir = require('os-homedir'); var openBrowser = require('op-browser'); var hiproxyDir = path.join(homedir(), '.hiproxy'); module.exports = { command: 'open', describe: 'Open browser and set proxy', usage: 'open', options: { 'browser <browser>': { alias: 'b', validate: /^(chrome|firefox|opera)$/, describe: '浏览器名称,默认:chrome,可选值:chrome,firefox,opera' }, 'pac-proxy': { describe: '是否使用自动代理,如果使用,不在hosts或者rewrite规则中的域名不会走代理' } }, fn: function () { var parsedArgs = this; try { var infoFile = fs.openSync(path.join(hiproxyDir, 'hiproxy.json'), 'r'); var infoTxt = fs.readFileSync(infoFile); var info = JSON.parse(infoTxt); var args = info.args; var port = args.port || 5525; var proxyURL = 'http://127.0.0.1:' + port; if (parsedArgs.pacProxy) { openBrowser.open(parsedArgs.browser || 'chrome', proxyURL, '', proxyURL + '/proxy.pac'); } else { openBrowser.open(parsedArgs.browser || 'chrome', proxyURL, proxyURL, ''); } console.log('Browser opened'); } catch (err) { console.log('Proxy server info read error.'); } } };
JavaScript
0
@@ -332,24 +332,34 @@ usage: 'open + %5Boptions%5D ',%0A options
182c40c55e36d7e626c1780d2ec2c95c54f62ebe
Add more selenium tests
tests/selenium/start.js
tests/selenium/start.js
var server = require('../../server'); server.start(function() { var webdriver = require('selenium-webdriver'), By = require('selenium-webdriver').By; var driver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.firefox()). build(); driver.manage().timeouts().implicitlyWait(30000); driver.get('http://localhost:3000/de/'); driver.findElement(By.id('amount-other-input')).sendKeys('10'); driver.findElement(By.css('.page-active .next-button')).click(); driver.findElement(By.id('payment-cc-label')).click(); driver.findElement(By.name('cc_number')).clear(); driver.findElement(By.name('cc_number')).sendKeys('4242424242424242'); driver.findElement(By.name('cc_expir_month')).clear(); driver.findElement(By.name('cc_expir_month')).sendKeys('01'); driver.findElement(By.name('cc_expir_year')).clear(); driver.findElement(By.name('cc_expir_year')).sendKeys('16'); driver.findElement(By.name('cc_cvv')).clear(); driver.findElement(By.name('cc_cvv')).sendKeys('123'); driver.findElement(By.css('.page-active .next-button')).click(); driver.findElement(By.name('firstname')).clear(); driver.findElement(By.name('firstname')).sendKeys('testname'); driver.findElement(By.name('lastname')).clear(); driver.findElement(By.name('lastname')).sendKeys('lastname'); driver.findElement(By.name('country')).sendKeys('Canada'); driver.findElement(By.name('addr1')).clear(); driver.findElement(By.name('addr1')).sendKeys('test address'); driver.findElement(By.name('city')).clear(); driver.findElement(By.name('city')).sendKeys('testcity'); driver.findElement(By.name('zip')).clear(); driver.findElement(By.name('zip')).sendKeys('m5g 3u7'); driver.findElement(By.id('wsstate_cd')).sendKeys('Ontario'); driver.findElement(By.name('email')).clear(); driver.findElement(By.name('email')).sendKeys('[email protected]'); driver.findElement(By.id('legalConfirm')).click(); driver.findElement(By.css('.submit-btn')).click(); driver.wait(function() { return driver.getCurrentUrl().then(function(url) { return url.indexOf('http://localhost:3000/de/thank-you/') === 0; }); }, 5000).then(function() { server.stop(function() { driver.quit(); }); }); });
JavaScript
0
@@ -35,36 +35,8 @@ ');%0A -server.start(function() %7B%0A var @@ -78,18 +78,16 @@ iver'),%0A - By = r @@ -119,19 +119,16 @@ r').By;%0A -%0A var driv @@ -227,60 +227,326 @@ );%0A%0A - driver.manage().timeouts().implicitlyWait(30000 +server.start(function() %7B%0A test(false, 'http://localhost:3000/de/');%0A driver.wait(function() %7B%0A return driver.getCurrentUrl().then(function(url) %7B%0A return url.indexOf('http://localhost:3000/de/thank-you/') === 0;%0A %7D);%0A %7D).then(function() %7B%0A test(true, 'http://localhost:3000/de/?test=signup-test' );%0A + dr @@ -554,39 +554,396 @@ ver. -get('http://localhost:3000/de/' +wait(function() %7B%0A return driver.getCurrentUrl().then(function(url) %7B%0A return url.indexOf('http://localhost:3000/de/share/') === 0;%0A %7D);%0A %7D).then(function() %7B%0A server.stop(function() %7B%0A driver.quit();%0A %7D);%0A %7D);%0A %7D);%0A%7D);%0A%0Afunction test(noProvince, url) %7B%0A var country = 'Canada';%0A driver.manage().timeouts().implicitlyWait(3000);%0A driver.get(url );%0A @@ -1893,32 +1893,79 @@ ys('lastname');%0A + if (noProvince) %7B%0A country = 'Chile';%0A %7D%0A driver.findEle @@ -1998,24 +1998,23 @@ endKeys( -'Canada' +country );%0A dri @@ -2328,24 +2328,47 @@ 'm5g 3u7');%0A + if (!noProvince) %7B%0A driver.fin @@ -2414,24 +2414,28 @@ 'Ontario');%0A + %7D%0A driver.fin @@ -2569,33 +2569,66 @@ id(' -legalConfirm')).click();%0A +privacy-policy-checkbox')).click();%0A if (noProvince) %7B%0A dr @@ -2651,24 +2651,27 @@ (By. -css('.submit-btn +id('signup-checkbox ')). @@ -2671,32 +2671,36 @@ box')).click();%0A + %7D%0A driver.wait(fu @@ -2696,253 +2696,50 @@ ver. -wait(function() %7B%0A return driver.getCurrentUrl().then(function(url) %7B%0A return url.indexOf('http://localhost:3000/de/thank-you/') === 0;%0A %7D);%0A %7D, 5000).then(function() %7B%0A server.stop(function() %7B%0A driver.quit();%0A %7D);%0A %7D +findElement(By.css('.submit-btn')).click( );%0A%7D -); %0A
27be0da31cfddc6465945d8b0b2c083cf6ceed1e
correct parameter name
defaults.js
defaults.js
var Blake2s = require('blake2s') var crypto = require('crypto') var ecc = require('eccjs') var codec = require('./codec') var curve = ecc.curves.k256 // this is all the developer specifiable things // you need to give secure-scuttlebutt to get it to work. // these should not be user-configurable, but it will // be handy for forks to be able to use different // crypto or encodings etc. module.exports = { //this must return a buffer digest. hash: function (data, enc) { return new Blake2s().update(data, enc).digest() }, isHash: function (data) { return Buffer.isBuffer(data) && data.length == 32 }, keys: { //this should return a key pair: // {public: Buffer, private: Buffer} generate: function () { return ecc.restore(curve, crypto.randomBytes(32)) }, //takes a public key and a hash and returns a signature. //(a signature must be a node buffer) sign: function (pub, hash) { return ecc.sign(curve, pub, hash) }, //takes a public key, signature, and a hash //and returns true if the signature was valid. verify: function (pub, sig, hash) { return ecc.verify(curve, pub, sig, hash) }, //codec for keys. this handles serializing //and deserializing keys for storage. //in elliptic curves, the public key can be //regenerated from the private key, so you only //need to serialize the private key. //in RSA, you need to remember both public and private keys. //maybe it's a good idea to add checksums and stuff //so that you can tell that this is a valid key when //read off the disk? codec: { decode: function (buffer) { return ecc.restore(curve, buffer) }, encode: function (keys) { return keys.private }, //this makes this a valid level codec. buffer: true } }, // the codec that is used to persist into leveldb. // this is the codec that will be passed to levelup. // https://github.com/rvagg/node-levelup#custom_encodings codec: codec }
JavaScript
0.000955
@@ -933,19 +933,20 @@ nction ( -pub +keys , hash) @@ -976,19 +976,20 @@ (curve, -pub +keys , hash)%0A
33160a487f5e0812f645aaecf89c0c5507273224
fix mochaTest failures
apps/test/levelTests.js
apps/test/levelTests.js
/** * The level test driver. * Tests collections are specified in .js files in the solutions directory. * To extract the xml for a test from a workspace, run the following code in * your console: * Blockly.Xml.domToText(Blockly.Xml.blockSpaceToDom(Blockly.mainBlockSpace)); */ // todo - should we also have tests around which blocks to show as part of the // feedback when a user gets the puzzle wrong? var path = require('path'); var assert = require('chai').assert; var $ = require('jquery'); require('jquery-ui'); var testUtils = require('./util/testUtils'); testUtils.setupLocales(); var wrappedEventListener = require('./util/wrappedEventListener'); var testCollectionUtils = require('./util/testCollectionUtils'); // One day this might be the sort of thing we share with initApp.js function loadSource(src) { var deferred = new $.Deferred(); document.body.appendChild($('<script>', { src: src }).on('load', function () { deferred.resolve(); })[0]); return deferred; } describe('Level tests', function() { var studioApp; var originalRender; before(function(done) { this.timeout(15000); window.jQuery = $; window.$ = $; // Load a bunch of droplet sources. We could potentially gate this on level.editCode, // but that doesn't get us a lot since everything is run in a single session now. loadSource('http://localhost:8001/apps/lib/jsinterpreter/acorn_interpreter.js') .then(function () { return loadSource('http://localhost:8001/apps/lib/requirejs/full/require.js'); }) .then(function () { return loadSource('http://localhost:8001/apps/lib/ace/src-noconflict/ace.js'); }) .then(function () { return loadSource('http://localhost:8001/apps/lib/ace/src-noconflict/mode-javascript.js'); }) .then(function () { return loadSource('http://localhost:8001/apps/lib/ace/src-noconflict/ext-language_tools.js'); }) .then(function () { return loadSource('http://localhost:8001/apps/lib/droplet/droplet-full.js'); }) .then(function () { return loadSource('http://localhost:8001/apps/lib/tooltipster/jquery.tooltipster.js'); }) .then(function () { assert(window.requirejs); done(); }); }); beforeEach(function () { testUtils.setupBlocklyFrame(); studioApp = testUtils.getStudioAppSingleton(); wrappedEventListener.attach(); // For some reason, svg rendering is taking a long time in phantomjs. None // of these tests depend on that rendering actually happening. originalRender = Blockly.BlockSvg.prototype.render; Blockly.BlockSvg.prototype.render = function () { this.block_.rendered = true; }; if (window.Studio) { var Projectile = require('@cdo/apps/studio/projectile'); Projectile.__resetIds(); } }); testCollectionUtils.getCollections().forEach(runTestCollection); afterEach(function () { var studioApp = require('@cdo/apps/StudioApp').singleton; if (studioApp.editor && studioApp.editor.aceEditor && studioApp.editor.aceEditor.session && studioApp.editor.aceEditor.session.$mode && studioApp.editor.aceEditor.session.$mode.cleanup) { studioApp.editor.aceEditor.session.$mode.cleanup(); } wrappedEventListener.detach(); Blockly.BlockSvg.prototype.render = originalRender; // Clean up some state that is meant to be per level. This is an issue // because we're using the same window for all tests. if (window.Maze) { window.Maze.bee = null; window.Maze.wordSearch = null; } if (window.Studio) { window.Studio.customLogic = null; window.Studio.interpreter = null; } }); }); // Loads a test collection at path and runs all the tests specified in it. function runTestCollection (item) { var runLevelTest = require('./util/runLevelTest'); // Append back the .js so that we can distinguish 2_1.js from 2_10.js when grepping var path = item.path + '.js'; var testCollection = item.data; var app = testCollection.app; describe(path, function () { testCollection.tests.forEach(function (testData, index) { testUtils.setupLocale(app); var dataItem = require('./util/data')(app); // todo - maybe change the name of expected to make it clear what type of // test is being run, since we're using the same JSON files for these // and our getMissingRequiredBlocks tests (and likely also other things // in the future) if (testData.expected) { it(testData.description, function (done) { // can specify a test specific timeout in json file. if (testData.timeout !== undefined) { this.timeout(testData.timeout); } if (testUtils.debugMode()) { // No timeout if we have a debugger attached this.timeout(0); } runLevelTest(testCollection, testData, dataItem, done); }); } }); }); }
JavaScript
0.000014
@@ -2740,24 +2740,64 @@ resetIds();%0A + Studio.JSInterpreter = undefined;%0A %7D%0A %7D);%0A
894949a3b1896fa1e92a1ecbb2e6e5a05a1b0377
use merge() instead of extend() for when collecting route definitions from source files
src/support/startup/routes.js
src/support/startup/routes.js
"use strict"; var debug = require('debug')('waigo-startup-routes'), queryString = require('query-string'); var waigo = global.waigo, _ = waigo._; /** * Build URL to given route. * @param {App} app The app. * @param {String} routeName Name of route. * @param {Object} [urlParams] URL params for route. * @param {Object} [queryParams] URL query params. * @param {Object} [options] Options. * @param {Boolean} [options.absolute] If `true` then return absolute URL including site base URL. * @return {String} Route URL */ var routeUrl = function(app, routeName, urlParams, queryParams, options) { options = _.extend({ absolute: false }, options); debug('Generate URL for route ' + routeName); var route = app.routes.byName[routeName]; if (!route) { throw new Error('No route named: ' + routeName); } var str = options.absolute ? app.config.baseURL : ''; str += route.url; // TODO: integrate params if (!_.isEmpty(queryParams)) { str += '?' + queryString.stringify(queryParams); } return str; }; /** * Setup route mappings. * * This sets up a `koa-trie-router` and maps routes to it using the * [route mapper](../routeMapper.js.html). * * @param {Object} app The application. */ module.exports = function*(app) { debug('Setting up routes'); require('koa-trie-router')(app); var routeFiles = waigo.getFilesInFolder('routes'); app.routes = {}; _.each(routeFiles, function(routeFile) { debug('Loading ' + routeFile); _.extend(app.routes, waigo.load(routeFile)); }); waigo.load('support/routeMapper').map(app, app.routes); app.use(app.router); // helper to build a URL based on a route app.routeUrl = app.locals.routeUrl = _.bind(routeUrl, null, app); };
JavaScript
0
@@ -1532,22 +1532,21 @@ %0A%0A _. -extend +merge (app.rou
40932674d7a1504bf8c126d5d3b550b96bd5813c
fix myBootstrapFormGroup for multi with no label (the col-xx-offset must be handled in first multi)
app/directives/Bootstrap.js
app/directives/Bootstrap.js
'use strict'; angular.module('myApp') .directive("myHasError", function() { return { restrict: 'A', transclude: true, template: function(element, attrs) { // cleanup element: element.removeAttr('my-has-error'); var name = attrs.myHasError; return "<div ng-class=\"{'has-error': submitted && myForm." + name + ".$invalid}\" ng-transclude></div>"; } }; }) .directive("myErrorMsgs", function() { return { restrict: 'A', transclude: true, template: function(element, attrs) { // cleanup element: element.removeAttr('my-error-msgs'); var name = attrs.myErrorMsgs; var error_msgs = '<div ng-messages="myForm.' + name + '.$error" ng-if="submitted">' + '<div ng-messages-include="form-errors"></div>' + '</div>'; var error_msgs2 = '<div ng-repeat="err in [errorMessages.' + name + ']" ng-if="submitted">' + '<div ng-include="\'templates/form-errors-custom.html\'"></div>' + '</div>'; return "<div><div ng-transclude></div>" + error_msgs + error_msgs2 + "</div>"; } }; }) .directive("myBootstrapFormGroup", function() { return { restrict: 'A', transclude: true, template: function(element, attrs) { var name = attrs.myBootstrapFormGroup; // cleanup element: element.removeAttr('my-bootstrap-form-group'); element.removeAttr('label'); element.removeAttr('multi'); element.addClass("form-group"); var mayHasErrorAttr = name && !attrs.multi ? "my-has-error='" + name + "'" : ''; var error_msgs = name && !attrs.multi ? "my-error-msgs='" + name + "'" : ''; var label = attrs.label ? '<label class="col-md-3 control-label" for="' + name + '">' + attrs.label + '</label>' : ''; var subClass = (attrs.label ? '' : 'col-md-offset-3') + ' ' + (attrs.multi ? '' : 'col-md-9'); var sub = '<div class="' + subClass + '" ' + error_msgs + '><div ng-transclude></div></div>'; return "<div " + mayHasErrorAttr + ">" + label + sub + "</div>"; } }; }) .directive("formControl", function() { return { restrict: 'A', require: 'ngModel', // controller to be passed into directive linking function link: function (scope, elem, attr, ctrl) { elem.addClass("form-control"); elem.attr('id', attr.name); } }; });
JavaScript
0
@@ -1766,16 +1766,31 @@ s.label +%7C%7C attrs.multi ? '' : '
fc6a8e0d2cd15f6162ec5f811d94e6ac18f0e8a8
add more test unit in client
src/api-test/domain/client/client-validate-spec.js
src/api-test/domain/client/client-validate-spec.js
'use strict'; const ClientValidate = require('../../../api/domain/client/client-validate'); describe('api domain client validate', () => { const APP = {}; let CLIENT; let clientValidate; beforeEach(() => { dottie.set(APP, 'domain.client.ClientModel', {}); CLIENT = { active: true, color: '', id: '61361f65-cb46-4d24-8cac-b085c1c4961c', name: '' }; clientValidate = new ClientValidate(APP); }); it('should be defined', () => { expect(clientValidate).to.not.be.undefined; }); it('name should be required', done => { delete CLIENT.name; clientValidate.nameIsRequired(CLIENT) .then(result => { expect(result.code).to.equal('client.name.required'); expect(result.message).to.equal('Name is required'); return done(); }) .catch(done); }); it('name should be maximum 100 characters', done => { CLIENT.name = properties.BIG_TEXT; clientValidate.nameMustHaveMaximum100Characters(CLIENT) .then(result => { expect(result.code).to.equal('client.name.maxlength'); expect(result.message).to.equal('Name must have a maximum of 100 characters'); return done(); }) .catch(done); }); it('name should be unique, Sending a new name', done => { const anotherClient = clone(CLIENT); anotherClient.name = 'Internal'; APP.domain.client.ClientModel.findOne = simpleMock.stub().resolveWith(); clientValidate.nameMustBeUnique(anotherClient) .then(() => { expect(APP.domain.client.ClientModel.findOne.callCount).to.equal(1); return done(); }) .catch(done); }); it('name should be unique, Sending same name with equal ID', done => { const anotherClient = clone(CLIENT); APP.domain.client.ClientModel.findOne = simpleMock.stub().resolveWith(CLIENT); clientValidate.nameMustBeUnique(anotherClient) .then(result => { expect(APP.domain.client.ClientModel.findOne.callCount).to.equal(1); return done(); }) .catch(done); }); it('name should be unique, Sending same name with different ID´s', done => { const anotherClient = clone(CLIENT); anotherClient.id = '2103c936-6613-4479-975c-cd1a87fe1e41'; APP.domain.client.ClientModel.findOne = simpleMock.stub().resolveWith(CLIENT); clientValidate.nameMustBeUnique(anotherClient) .then(result => { expect( APP.domain.client.ClientModel.findOne.callCount).to.equal(1); expect(result.code).to.equal('client.name.unique'); expect(result.message).to.equal('Name must be unique'); return done(); }) .catch(done); }); it('color should be maximum 20 characters', done => { CLIENT.color = properties.BIG_TEXT; clientValidate.colorMustHaveMaximum20Characters(CLIENT) .then(result => { expect(result.code).to.equal('client.color.maxlength'); expect(result.message).to.equal('Color must have a maximum of 20 characters'); return done(); }) .catch(done); }); });
JavaScript
0
@@ -379,16 +379,28 @@ name: ' +Grower games '%0A %7D; @@ -3071,13 +3071,1436 @@ );%0A %7D); +%0A%0A describe('# onCreate', () =%3E %7B%0A beforeEach(() =%3E %7B%0A delete CLIENT.id;%0A APP.domain.client.ClientModel.findOne = simpleMock.stub().resolveWith();%0A %7D);%0A%0A it('create a new valid client', done =%3E %7B%0A clientValidate.onCreate(CLIENT)%0A .then(() =%3E done())%0A .catch(done);%0A %7D);%0A%0A it('create a new invalid client', done =%3E %7B%0A delete CLIENT.name;%0A%0A clientValidate.onCreate(CLIENT)%0A .then(() =%3E done('should be error'))%0A .catch(error =%3E %7B%0A expect(error.name).to.equal('BusinessError');%0A expect(error.errors.length).to.equal(1);%0A expect(error.errors%5B0%5D.code).to.equal('client.name.required');%0A return done();%0A %7D);%0A %7D);%0A %7D);%0A%0A describe('# onUpdate', () =%3E %7B%0A beforeEach(() =%3E %7B%0A APP.domain.client.ClientModel.findOne = simpleMock.stub().resolveWith();%0A %7D);%0A%0A it('update a valid client', done =%3E %7B%0A clientValidate.onUpdate(CLIENT)%0A .then(() =%3E done())%0A .catch(error =%3E done(error));%0A %7D);%0A%0A it('update a invalid client', done =%3E %7B%0A delete CLIENT.name;%0A%0A clientValidate.onUpdate(CLIENT)%0A .then(() =%3E done())%0A .catch(error =%3E %7B%0A expect(error.name).to.equal('BusinessError');%0A expect(error.errors.length).to.equal(1);%0A expect(error.errors%5B0%5D.code).to.equal('client.name.required');%0A return done();%0A %7D);%0A %7D);%0A %7D); %0A%7D);%0A
7292b665dc486a84708605923dac85fb9c90ab67
remove SpectraProcessor from vh
eln/libs.js
eln/libs.js
export { default as OCLE } from './libs/OCLE'; export { OCLUtils, OCL } from './libs/OCLUtils'; export { default as SD } from './libs/SD'; export { default as elnPlugin } from './libs/elnPlugin'; export { default as Image } from './libs/Image'; export { default as MolecularFormula } from './libs/MolecularFormula'; export { default as convertToJcamp } from './libs/convertToJcamp'; export { parseXY } from './libs/parseXY'; export { convert } from './libs/jcampconverter'; export { SpectraProcessor } from './libs/SpectraProcessor';
JavaScript
0
@@ -471,64 +471,4 @@ r';%0A -export %7B SpectraProcessor %7D from './libs/SpectraProcessor';%0A
733e94ad0a092c3ae078982fd0b510e266c32a79
Improve error reporting in arangosh with kickstarter.
js/client/modules/org/arangodb/cluster.js
js/client/modules/org/arangodb/cluster.js
/*jslint indent: 2, nomen: true, maxlen: 100, sloppy: true, vars: true, white: true, regexp: true plusplus: true */ /*global require, exports */ //////////////////////////////////////////////////////////////////////////////// /// @brief ArangoShell client API for cluster operation /// /// @file /// /// DISCLAIMER /// /// Copyright 2013 triagens GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Max Neunhoeffer /// @author Copyright 2014, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// var internal = require("internal"); var arangosh = require("org/arangodb/arangosh"); var db = require("org/arangodb").db; function Planner (userConfig) { "use strict"; if (typeof userConfig !== "object") { throw "userConfig must be an object"; } var r = db._connection.POST("/_admin/clusterPlanner", JSON.stringify(userConfig)); r = arangosh.checkRequestResult(r); this.clusterPlan = r.clusterPlan; this.config = r.config; } Planner.prototype.getPlan = function () { return this.clusterPlan; }; function Kickstarter (clusterPlan, myname) { "use strict"; if (typeof clusterPlan !== "object") { throw "clusterPlan must be an object"; } this.clusterPlan = clusterPlan; if (myname === undefined) { this.myname = "me"; } else { this.myname = myname; } } Kickstarter.prototype.launch = function () { "use strict"; var r = db._connection.POST("/_admin/clusterDispatch", JSON.stringify({"action": "launch", "clusterPlan": this.clusterPlan, "myname": this.myname})); arangosh.checkRequestResult(r); this.runInfo = r.runInfo; return r; }; Kickstarter.prototype.shutdown = function () { "use strict"; var r = db._connection.POST("/_admin/clusterDispatch", JSON.stringify({"action": "shutdown", "clusterPlan": this.clusterPlan, "myname": this.myname, "runInfo": this.runInfo})); arangosh.checkRequestResult(r); return r; }; Kickstarter.prototype.relaunch = function () { "use strict"; var r = db._connection.POST("/_admin/clusterDispatch", JSON.stringify({"action": "relaunch", "clusterPlan": this.clusterPlan, "myname": this.myname})); arangosh.checkRequestResult(r); this.runInfo = r.runInfo; return r; }; Kickstarter.prototype.cleanup = function () { "use strict"; var r = db._connection.POST("/_admin/clusterDispatch", JSON.stringify({"action": "cleanup", "clusterPlan": this.clusterPlan, "myname": this.myname})); arangosh.checkRequestResult(r); return r; }; Kickstarter.prototype.isHealthy = function () { "use strict"; var r = db._connection.POST("/_admin/clusterDispatch", JSON.stringify({"action": "isHealthy", "clusterPlan": this.clusterPlan, "myname": this.myname, "runInfo": this.runInfo})); arangosh.checkRequestResult(r); return r; }; exports.Planner = Planner; exports.Kickstarter = Kickstarter; // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @\\}\\)" // End:
JavaScript
0
@@ -2338,42 +2338,8 @@ ));%0A - arangosh.checkRequestResult(r);%0A th @@ -2354,32 +2354,32 @@ fo = r.runInfo;%0A + return r;%0A%7D;%0A%0A @@ -2792,42 +2792,8 @@ ));%0A - arangosh.checkRequestResult(r);%0A re @@ -3147,42 +3147,8 @@ ));%0A - arangosh.checkRequestResult(r);%0A th @@ -3528,42 +3528,8 @@ ));%0A - arangosh.checkRequestResult(r);%0A re @@ -3956,42 +3956,8 @@ ));%0A - arangosh.checkRequestResult(r);%0A re @@ -3995,16 +3995,16 @@ lanner;%0A + exports. @@ -4035,14 +4035,8 @@ r;%0A%0A - %0A%0A // -
8ac7f47ac0f1b75ec0ad238c4545952aa52db530
Add Enter handler to confirm
app/components/Fields/Group/NewBlockModal.js
app/components/Fields/Group/NewBlockModal.js
import React, { Component, PropTypes } from 'react'; import Input from 'components/Input'; import Button from 'components/Button'; import { slugify } from 'utils/helpers'; export default class NewBlockModal extends Component { static propTypes = { confirm: PropTypes.func.isRequired, close: PropTypes.func, } static defaultProps = { close: null, } constructor(props) { super(props); this.confirm = this.confirm.bind(this); this.handleTitleChange = this.handleTitleChange.bind(this); } state = { title: '' } confirm() { this.props.confirm({ name: this.name.value, handle: slugify(this.state.title), fields: [{ label: 'Blank', handle: 'blank-0', }], }); this.props.close(); } handleTitleChange(title) { this.setState({ title }); } render() { const { close } = this.props; return ( <div className="modal--newblock"> <Input name="name" label="Name" required ref={(r) => { this.name = r; }} instructions="What this block will be called in the dashboard." onChange={this.handleTitleChange} full autoFocus /> <Input name="handle" label="Handle" required readOnly ref={(r) => { this.handle = r; }} instructions="How you'll refer to this block type in your templates." full code value={slugify(this.state.title)} /> <div className="modal__buttons"> <Button small onClick={this.confirm}>Confirm</Button> <Button small onClick={close} kind="subtle">Cancel</Button> </div> </div> ); } }
JavaScript
0
@@ -513,20 +513,78 @@ (this);%0A + this.handleKeyPress = this.handleKeyPress.bind(this);%0A %7D%0A - %0A state @@ -889,16 +889,86 @@ );%0A %7D%0A%0A + handleKeyPress(e) %7B%0A if (e.key === 'Enter') this.confirm();%0A %7D%0A%0A render @@ -1306,32 +1306,32 @@ %0A full%0A - autoFo @@ -1334,16 +1334,59 @@ toFocus%0A + onKeyPress=%7Bthis.handleKeyPress%7D%0A
f3f3b9b33ce8af8fafcdfff92b6ad0a16c7c2498
Add uniqId to CardModel
src/redux/modules/card.js
src/redux/modules/card.js
import { Record as record } from 'immutable'; export const CardModel = record({ id: null, name: '', mana: null, attack: null, defense: null, });
JavaScript
0
@@ -52,12 +52,12 @@ rt c -onst +lass Car @@ -67,9 +67,15 @@ del -= +extends rec @@ -153,10 +153,95 @@ null,%0A%7D) -; + %7B%0A constructor(obj) %7B%0A super(obj);%0A this.uniqId = this.id + +new Date();%0A %7D%0A%7D %0A
d7bedcb13737ef41e859f598c604cd26b0ab27b4
Add api argument in exported function of events.js
src/components/transactions/src/controller/events.js
src/components/transactions/src/controller/events.js
'use strict'; module.exports = function (options, imports) { var logger = imports.logger.get('General Ledgers ctrl - Events'); };
JavaScript
0.000001
@@ -51,16 +51,21 @@ imports +, api ) %7B%0A%0A%09va
e400603d54bce1d235be5aa1aa761c9665edd328
fix indentation in module render-template
src/assets/js/modules/functions/render-template.js
src/assets/js/modules/functions/render-template.js
'use strict'; /** * template cache * @type {Object} */ var cache = {}; /** * render a html/js template * inspired by john resig's micro templating: * http://ejohn.org/blog/javascript-micro-templating/ * * @param {string} str template string * @param {object} data template data object * @return {HTMLCollection} rendered template */ function renderTemplate(str, data) { var dom = document.implementation.createHTMLDocument(), fn = cache[str] = cache[str] || new Function('obj', // eslint-disable-line no-new-func 'var p=[],print=function(){p.push.apply(p,arguments);};' + 'with(obj){p.push(\'' + str.replace(/[\r\t\n]/g, ' ') .split('{%').join('\t') .replace(/((^|%\})[^\t]*)"/g, '$1\r') .replace(/\t=(.*?)%\}/g, '\',$1,\'') .split('\t').join('\');') .split('%}').join('p.push(\'') .split('\r').join('"') + '\');}return p.join("");'); data = typeof data === 'object' ? data : {}; dom.body.innerHTML = fn(data); return dom.body.children.length > 1 ? dom.body.children : dom.body.children[0]; } module.exports = renderTemplate;
JavaScript
0.000004
@@ -385,18 +385,16 @@ data) %7B%0A - var do @@ -449,18 +449,16 @@ ,%0A - fn = cac @@ -489,20 +489,16 @@ - - new Func @@ -554,22 +554,16 @@ - - 'var p=%5B @@ -623,22 +623,16 @@ - 'with(ob @@ -657,22 +657,16 @@ - - str.repl @@ -687,24 +687,16 @@ g, ' ')%0A - @@ -731,32 +731,24 @@ - .replace(/(( @@ -781,32 +781,24 @@ - - .replace(/%5Ct @@ -830,32 +830,24 @@ - - .split('%5Ct') @@ -860,24 +860,16 @@ '%5C');')%0A - @@ -911,32 +911,24 @@ - - .split('%5Cr') @@ -950,22 +950,16 @@ - - '%5C');%7Dre @@ -978,18 +978,16 @@ %22%22);');%0A - data = @@ -1025,18 +1025,16 @@ a : %7B%7D;%0A - dom.bo @@ -1060,18 +1060,16 @@ ata);%0A - - return d @@ -1098,20 +1098,16 @@ h %3E 1 ?%0A - dom.
d1901765e0e7e9197b7803701be4cf4b7829db12
Add delay
src/bridge3d/obj/Bridge.js
src/bridge3d/obj/Bridge.js
import { Object3D } from "mx3d"; export default class Bridge extends Object3D { sensors = []; selection = null; bridgeMaterial = new THREE.MeshPhongMaterial( { color: 0x9999aa, specular: 0x555555, shininess: 10 } ); sensorMaterial = new THREE.MeshPhongMaterial( { color: 0xffbc78, specular: 0x555555, shininess: 100 } ); selectedSensorMaterial = new THREE.MeshPhongMaterial( { color: 0xff0000, specular: 0x555555, shininess: 100 } ); constructor({ scene }) { super(); this.scene = scene; } async load(url, onProcess) { console.log("[bridge3d] Loading bridge.obj..."); this.mesh = await this.loadFromObj(url, onProcess); console.log("[bridge3d] bridge.obj is now successfully loaded."); this._loadSensors(); } _loadSensors() { this.mesh.children.forEach(child => { if (child.name.startsWith("sensor_")) { let id = null; let under = false; if (child.name.startsWith("sensor_under_")) { under = true; id = child.name.substr(13); } else { id = child.name.substr(7); } const sensor = { id, name: child.name, mesh: child, under, visible: true }; sensor.mesh.material = this.sensorMaterial; this.sensors["sensor#" + sensor.id] = sensor; this.sensors[sensor.name] = sensor; this.sensors.push(sensor); } else { child.material = this.bridgeMaterial; } }); this.hideAllSensors(); console.log(`[bridge3d] ${this.sensors.length} sensors found.`); } getSensor(key) { if (key.name) { key = key.name; } if (typeof(key) === "number") { return this.sensors[key]; } else if (typeof(key) === "string") { if (this.sensors["sensor#" + key]) { return this.sensors["sensor#" + key]; } else if (this.sensors[key]) { return this.sensors[key]; } } } showSensors(sensorIds) { this.sensors.forEach(sensor => { sensor.visible = sensorIds.indexOf(sensor.id) != -1; if (sensor.visible) { this.mesh.add(sensor.mesh); } else { this.mesh.remove(sensor.mesh); } }); } hideAllSensors() { this.sensors.forEach(sensor => { sensor.visible = false; this.mesh.remove(sensor.mesh); }); } selectSensor(sensor) { if (sensor === undefined || sensor === null) { return; } sensor = this.getSensor(sensor); if (!sensor || sensor === this.selection) { return; } if (this.selection) { this.selection.mesh.material = this.sensorMaterial; } this.selection = sensor; sensor.mesh.material = this.selectedSensorMaterial; } selectAndFocusOnSensor(sensor) { if (sensor) { this.selectSensor(sensor); this.focusOnSensor(sensor); } } focusOnSensor(sensor) { if (sensor === undefined || sensor === null) { return; } sensor = this.getSensor(sensor); const v1 = sensor.mesh.geometry.boundingSphere.center; const v2 = new THREE.Vector3(v1.x + (sensor.under ? 30 : -30), v1.y, v1.z); this.scene.focusOnLine( v1, v2, (sensor.under ? 45 : -45), 2000 ); } }
JavaScript
0.00002
@@ -3757,32 +3757,218 @@ Sensor(sensor);%0A + if (!sensor.mesh.geometry.boundingSphere)%0A %7B%0A setTimeout(() =%3E %7B%0A this.focusOnSensor(sensor);%0A %7D, 100);%0A return;%0A %7D%0A const v1
eb343e8ca35aebd131c1260bf7c423f79de2b86f
Set select2 container CSS class to :all:
src/dal_select2/static/autocomplete_light/select2.js
src/dal_select2/static/autocomplete_light/select2.js
;(function ($) { if (window.__dal__initListenerIsSet) return; $(document).on('autocompleteLightInitialize', '[data-autocomplete-light-function=select2]', function() { var element = $(this); // Templating helper function template(text, is_html) { if (is_html) { var $result = $('<span>'); $result.html(text); return $result; } else { return text; } } function result_template(item) { return template(item.text, element.attr('data-html') !== undefined || element.attr('data-result-html') !== undefined ); } function selected_template(item) { if (item.selected_text !== undefined) { return template(item.selected_text, element.attr('data-html') !== undefined || element.attr('data-selected-html') !== undefined ); } else { return result_template(item); } return } var ajax = null; if ($(this).attr('data-autocomplete-light-url')) { ajax = { url: $(this).attr('data-autocomplete-light-url'), dataType: 'json', delay: 250, data: function (params) { var data = { q: params.term, // search term page: params.page, create: element.attr('data-autocomplete-light-create') && !element.attr('data-tags'), forward: yl.getForwards(element) }; return data; }, processResults: function (data, page) { if (element.attr('data-tags')) { $.each(data.results, function(index, value) { value.id = value.text; }); } return data; }, cache: true }; } $(this).select2({ tokenSeparators: element.attr('data-tags') ? [','] : null, debug: true, placeholder: element.attr('data-placeholder') || '', language: element.attr('data-autocomplete-light-language'), minimumInputLength: element.attr('data-minimum-input-length') || 0, allowClear: ! $(this).is('[required]'), templateResult: result_template, templateSelection: selected_template, ajax: ajax, tags: Boolean(element.attr('data-tags')), }); $(this).on('select2:selecting', function (e) { var data = e.params.args.data; if (data.create_id !== true) return; e.preventDefault(); var select = $(this); $.ajax({ url: $(this).attr('data-autocomplete-light-url'), type: 'POST', dataType: 'json', data: { text: data.id, forward: yl.getForwards($(this)) }, beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", document.csrftoken); }, success: function(data, textStatus, jqXHR ) { select.append( $('<option>', {value: data.id, text: data.text, selected: true}) ); select.trigger('change'); select.select2('close'); } }); }); }); window.__dal__initListenerIsSet = true; $('[data-autocomplete-light-function=select2]:not([id*="__prefix__"])').each(function() { window.__dal__initialize(this); }); })(yl.jQuery);
JavaScript
0
@@ -2254,16 +2254,56 @@ : true,%0A + containerCssClass: ':all:',%0A
bcae1122364138b75e5cbd6470387777c8f15d9d
fix capitalization
src/reporting/Reporter.js
src/reporting/Reporter.js
const XUnitReport = testResults => { let testCaseToXML = (suiteName, testName, testCase) => { var passed = testCase.expected == testCase.actual; var xml = ' <testcase classname="' + suiteName + '" name="' + testName + '"'; if (passed) { xml += '/>\n'; } else { xml += '>\n <failure message="Expected ' + testCase.expected + ' but got ' + testCase.actual + '">' + testCase.error + '</failure>\n'; xml += ' </testcase>\n'; } return xml; }; let testSuiteToXML = (suiteName, suite) => { let xml = ' <testsuite tests="' + numTests.toString() + '">\n'; let tests = Object.keys(suite); tests.forEach(test => { xml += testCaseToXML(suiteName, test, suite[test]); }); for (var testName in suite) { } xml += ' </testsuite>\n'; return xml; }; let jsonToXUnit = results => { let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<testsuites>\n'; let { suites } = results.tests; let suiteNames = Object.keys(suites); suiteNames && suiteNames.forEach(suite => { xml += testSuiteToXML(suite, suites[suite]); }); xml += '</testsuites>\n'; return xml; }; let xunit = jsonToXunit(testResults); }; export const reporter = XUnitReport; export const postTestResults = (testResultJSON, params) => { const headers = new Headers({ ...params.headers }); const body = { testResult: testResultJSON }; const requestParams = { method: params.method, headers: headers || undefined, body: JSON.stringify(body) }; return fetch(params.url, requestParams) .then(response => response.text()) .then(responseData => { console.log('responseData', responseData); }) .catch(failure => { console.warn(failure); }); };
JavaScript
0.001343
@@ -1261,17 +1261,17 @@ jsonToX -u +U nit(test
ac3758e226af958b56ef7ded70622c81f2fc8101
Improve the subscriptions grid layout
src/client/javascript/pages/subscriptions.react.js
src/client/javascript/pages/subscriptions.react.js
const Player = React.createClass({ onStateChange: function (event) { switch (event.data) { case YT.PlayerState.PLAYING: Socket.emit('video/start', this.state.player.getVideoData()['video_id']); break; case YT.PlayerState.PAUSED: Socket.emit('video/pause', this.state.player.getVideoData()['video_id']); break; case YT.PlayerState.BUFFERING: Socket.emit('video/buffer', this.state.player.getVideoData()['video_id']); break; case YT.PlayerState.ENDED: Socket.emit('video/end', this.state.player.getVideoData()['video_id']); break; }; }, updateVideo: function (id) { this.setState((state) => { return { id: id, player: state.player }; }); this.state.player.cueVideoById(id); }, playVideo: function (id) { this.setState((state) => { return { id: id, player: state.player }; }); this.state.player.loadVideoById(id); }, componentDidMount: function () { this.setState({ id: null, // YT may not be loaded at this time, need to find a solution... // That's probably why I can't put this in a getInitialState method player: new YT.Player('player', { events: { onStateChange: this.onStateChange } }) }); Socket.on('video/cue', this.updateVideo); Socket.on('video/play', this.playVideo); }, render: function () { return <div id="player"></div>; } }); const PlaylistItem = React.createClass({ playVideo: function () { if (this.props.id) { Socket.emit('video/play', this.props); } }, render: function () { return ( <div> <div className="playlist-item"> <h5> <a onClick={this.playVideo} title={this.props.title}> {this.props.title} </a> </h5> <h6>{this.props.channel}</h6> </div> <hr /> </div> ); } }); const Playlist = React.createClass({ getInitialState: function () { return { videos: [] }; }, componentDidMount: function () { Socket.on('playlist/update', (playlist) => { this.setState({ videos: playlist }); }); }, render: function () { let videos = []; for (var index in this.state.videos) { videos.push( <PlaylistItem key={this.state.videos[index].id} id={this.state.videos[index].id} thumbnail={this.state.videos[index].thumbnail} title={this.state.videos[index].title} channel={this.state.videos[index].channel} /> ); } return ( <div id="playlist"> {videos} </div> ); } }); const CurrentPlaylist = React.createClass({ render: function () { return ( <div id="current-playlist"> <Playlist /> <Player /> </div> ); } }); const Video = React.createClass({ cueVideo: function () { if (this.props.id) { Socket.emit('video/cue', this.props); } }, setNextVideo: function () { if (this.props.id) { Socket.emit('video/next', this.props); } }, render: function () { return ( <article className="video col-md-3 col-sm-6 col-xs-12"> <div className="ratio-container"> <img className="thumbnail lazyload blur-up" data-sizes="auto" data-src={this.props.thumbnail} src="images/loader.gif" /> </div> <span className="duration">{this.props.duration}</span> <header> <button className="btn btn-secondary btn-sm cue" onClick={this.cueVideo} title="Cue this video">+</button> <h5> <a onClick={this.setNextVideo} title={this.props.title}> {this.props.title} </a> </h5> <h6>{this.props.channel}</h6> </header> </article> ); } }); const VideoGrid = React.createClass({ render: function () { if (this.props.videos.length) { let videoNodes = this.props.videos.map((video) => { return ( <Video key={video.id} id={video.id} duration={video.duration} thumbnail={video.thumbnail} title={video.title} channel={video.channel} /> ) }); return ( <section id="videos-grid" className="row"> {videoNodes} </section> ); } return <h4>Nothing to show at the moment</h4>; } }); const SubscriptionsPage = React.createClass({ getInitialState: function () { return { loading: true, videos: null }; }, componentDidMount: function () { Socket.emit('subscriptions/list'); Socket.on('subscriptions/list', (subscriptions) => { this.setState({ loading: false, videos: subscriptions }); window.addEventListener('paste', this.onPaste); }); }, componentWillUnmount: function () { Socket.removeAllListeners('subscriptions/list'); window.removeEventListener('paste', this.onPaste); }, onPaste: function (event) { if (!event.clipboardData.getData('text/plain')) return; Socket.emit('video/paste', event.clipboardData.getData('text/plain')); }, render: function () { if (this.state.loading) { return ( <div className="jumbotron"> <h1 className="display-3">Let us load your data</h1> <p className="lead">You are connected to the YouTube API</p> <p>It may take a while</p> </div> ); } return ( <div> <VideoGrid videos={this.state.videos} /> <CurrentPlaylist /> </div> ); } });
JavaScript
0.000001
@@ -3231,16 +3231,34 @@ deo +col-xl-2 col-lg-3 col-md- -3 +4 col
c3523d5e933462ebaf3d4d8f2defe21ccc9dc718
Update index.js
src/routes/Email/index.js
src/routes/Email/index.js
/** * Created by user on 2016/12/16. */ export default (store) => ({ path : 'email', /* Async getComponent is only invoked when route matches */ getComponent (nextState, cb) { /* Webpack - use 'require.ensure' to create a split point and embed an async module loader (jsonp) when bundling */ require.ensure([], (require) => { /* Webpack - use require callback to define dependencies for bundling */ const About = require('./components/EmailMenu').default // const reducer = require('./modules/counter').default /* Add the reducer to the store on key 'counter' */ // injectReducer(store, { key: 'about', null }) /* Return getComponent */ cb(null, About) /* Webpack named bundle */ }, 'counter') } })
JavaScript
0.000002
@@ -498,12 +498,12 @@ mail -Menu +Cont ').d
8754bb9bc3f53694a4c36b377fcca9f1e33153d5
Fix the import cluster issue
lib/shared/addon/components/cru-cluster/component.js
lib/shared/addon/components/cru-cluster/component.js
import Component from '@ember/component'; import { get, set, computed, observer, setProperties } from '@ember/object'; import { inject as service } from '@ember/service'; import ViewNewEdit from 'shared/mixins/view-new-edit'; import ChildHook from 'shared/mixins/child-hook'; import { alias } from '@ember/object/computed'; import { loadStylesheet, proxifyUrl } from 'shared/utils/load-script'; import layout from './template'; import { isEmpty } from '@ember/utils'; const MEMBER_CONFIG = { type: 'clusterRoleTemplateBinding', }; export default Component.extend(ViewNewEdit, ChildHook, { layout, globalStore: service(), intl: service(), access: service(), cluster: alias('model.cluster'), originalCluster: alias('model.originalCluster'), primaryResource: alias('model.cluster'), step: 1, initialProvider: null, memberConfig: MEMBER_CONFIG, newCluster: false, needReloadSchema: false, reloadingSchema: false, schemaReloaded: false, init() { this._super(...arguments); // On edit pass in initialProvider, for create just set provider directly const initialProvider = get(this, 'initialProvider'); if ( initialProvider ) { set(this, 'provider', initialProvider); } if ( isEmpty(get(this, 'cluster.id')) ){ set(this, 'newCluster', true); } }, actions: { clickNext() { this.$('BUTTON[type="submit"]').click(); }, close() { this.sendAction('close'); }, }, providerChoices: computed( 'isEdit', 'cluster.rancherKubernetesEngineConfig', 'nodeDrivers.[]', 'schemaReloaded', 'intl.locale', function() { const intl = get(this, 'intl'); let out = [ {name: 'googlegke', driver: 'googlegke'}, {name: 'amazoneks', driver: 'amazoneks'}, {name: 'azureaks', driver: 'azureaks'}, ]; get(this, 'model.nodeDrivers').filterBy('state','active').sortBy('name').forEach((driver) => { const name = get(driver, 'name'); const hasUi = get(driver, 'hasUi'); const hasIcon = get(driver, 'hasBuiltinIconOnly'); const uiUrl = get(driver, 'uiUrl'); const configName = `${name}Config`; const driverSchema = get(this, 'globalStore').getById('schema', configName.toLowerCase()); if( uiUrl ) { const cssUrl = proxifyUrl(uiUrl.replace(/\.js$/,'.css'), get(this, 'app.proxyEndpoint')); loadStylesheet(cssUrl, `driver-ui-css-${name}`); } if ( driverSchema ) { out.push({ name: name, driver: 'rke', genericIcon: !hasUi && !hasIcon, nodeComponent: hasUi ? name : 'generic', nodeWhich: name, }); } else { set(this, 'needReloadSchema', true); } }), out.push({ name: 'custom', driver: 'rke', nodeWhich: 'custom', preSave: true }); out.push({ name: 'import', driver: 'import', preSave: true }); out.forEach((driver) => { const key = `clusterNew.${driver.name}.label`; if ( !get(driver,'displayName') && intl.exists(key) ) { set(driver, 'displayName', intl.t(key)); } }); if ( get(this, 'isEdit') && get(this, 'cluster.rancherKubernetesEngineConfig') ) { out = out.filterBy('driver','rke'); } return out; }), reloadSchema: observer('needReloadSchema', function() { if ( !get(this, 'reloadingSchema') && get(this, 'needReloadSchema') ) { set(this, 'reloadingSchema', true); get(this, 'globalStore').findAll('schema', { url: '/v3/schemas', forceReload: true }).then(() => { setProperties(this, { schemaReloaded: true, reloadingSchema: false }); }); } }), providerGroups: computed('providerChoices.@each.{name,driver,nodeComponent,nodeWhich,preSave}', function() { const choices = get(this, 'providerChoices'); const rkeGroup = []; const cloudGroup = []; const customGroup = []; const importGroup = []; choices.forEach((item) => { if (get(item, 'driver') === 'rke' && get(item, 'name') !== 'custom') { rkeGroup.pushObject(item); } else if (get(item, 'driver') === 'import' && get(item, 'name') !== 'custom') { importGroup.pushObject(item); } else if (get(item, 'name') === 'custom') { customGroup.pushObject(item); } else { cloudGroup.pushObject(item); } }); return { rkeGroup, cloudGroup, customGroup, importGroup }; }), driverInfo: computed('provider', function() { const name = get(this, 'provider'); const choices = get(this, 'providerChoices'); const entry = choices.findBy('name', name); if ( entry ) { return { name: entry.name, driverComponent: `cluster-driver/driver-${entry.driver}`, nodeWhich: entry.nodeWhich, preSave: !!entry.preSave, }; } }), didSave() { const originalCluster = get(this, 'cluster'); return originalCluster.waitForCondition('InitialRolesPopulated').then(() => { return this.applyHooks().then(() => { const clone = originalCluster.clone(); setProperties({ cluster: clone, originalCluster: originalCluster, }); return clone; }); }); }, doneSaving() { if ( get(this, 'step') === 1 && get(this, 'driverInfo.preSave') ) { setProperties(this, { step: 2, initialProvider: get(this, 'provider') }); } else { this.sendAction('close'); } }, });
JavaScript
0.000048
@@ -5401,16 +5401,22 @@ perties( +this, %7B%0A
21e26b276e88346984a95683cd558292ad9ea964
make comments to posts have course_ID too
client/views/courses/details/course.discussion.js
client/views/courses/details/course.discussion.js
//load template-content Template.discussion.helpers({ post: function() { //get all first-level posts var posts = CourseDiscussions.find({ course_ID: this._id, parent_ID: { $exists: false }, }, {sort: {time_updated: -1, time_created: -1}} ); var ordered_posts = []; // loop over first-level post, search each post for comments, order by most recent posts.forEach(function (post){ ordered_posts.push(post); var comments = CourseDiscussions.find({parent_ID: post._id}, {sort: {time_created: -1}}); comments.forEach(function (comment){ ordered_posts.push(comment); }); }); //return array with proper order return ordered_posts; } }); Template.newPost.created = function() { this.writing = new ReactiveVar(false); } Template.newPost.helpers({ writing: function() { return Template.instance().writing.get(); } }); Template.newPost.events({ 'click button.write': function () { if (pleaseLogin()) return; Template.instance().writing.set(true); }, 'click button.add': function () { if (pleaseLogin()) return; var timestamp = new Date(); var user = Meteor.userId(); var course = this._id; var parent_ID = this.parent && this.parent._id if (parent_ID) { CourseDiscussions.insert({ "parent_ID":parent_ID, "course_ID":course, "time_created":timestamp, "time_updated":timestamp, "user_ID":user, "title":$("#post_title").val(), "text":$("#post_text").val() }); } else { CourseDiscussions.insert({ "course_ID":course, "time_created":timestamp, "time_updated":timestamp, "user_ID":user, "title":$("#post_title").val(), "text":$("#post_text").val() }); // HACK update course so time_lastchange is updated Meteor.call("save_course", course, {}) } Template.instance().writing.set(false); }, 'click button.cancel': function () { Template.instance().writing.set(false); } }); Template.discussion.rendered = function() { this.$("[data-toggle='tooltip']").tooltip(); };
JavaScript
0
@@ -1279,38 +1279,53 @@ %09%09%09%09%22course_ID%22: +this.parent. course +_ID ,%0A%09%09%09%09%22time_crea
bcf4eb5691e266af25ea7f463923d065f6d97895
Add default divisor for Price
packages/components/components/price/Price.js
packages/components/components/price/Price.js
import React from 'react'; import PropTypes from 'prop-types'; const CURRENCIES = { USD: '$', EUR: '€', CHF: 'CHF' }; const Price = ({ children: amount = 0, currency = '', className = '' }) => { const symbol = CURRENCIES[currency] || currency; const value = Number(amount).toFixed(2); const prefix = value < 0 ? '-' : ''; const absValue = Math.abs(value); return ( <span className={`price ${className}`}> {currency === 'USD' ? `${prefix}${symbol}${absValue}` : `${prefix}${absValue} ${symbol}`} </span> ); }; Price.propTypes = { currency: PropTypes.string, children: PropTypes.number.isRequired, className: PropTypes.string }; export default Price;
JavaScript
0.000001
@@ -193,16 +193,25 @@ ame = '' +, divisor %7D) =%3E %7B @@ -295,16 +295,48 @@ r(amount + %3E 0 ? amount / divisor : amount ).toFixe @@ -737,16 +737,119 @@ s.string +,%0A divisor: PropTypes.number.isRequired%0A%7D;%0A%0APrice.defaultProps = %7B%0A children: 0,%0A divisor: 100 %0A%7D;%0A%0Aexp
39f9b8ee35196e49375b9e6761053cf10e08d46b
refactor badges by user to be consistent with other routes
src/routes/users/index.js
src/routes/users/index.js
'use strict'; var returnBadges, badgerService; var mongoose = require('mongoose'); var User = mongoose.model('User'); function getBadgeResponse(orcid) { return badgerService.getBadges(orcid); } function getBadges(request, response) { var orcid = request.params.orcid; if (!orcid) { response.status(400).end(); return; } returnBadges(getBadgeResponse(orcid), request, response); } function getBadgeCount(request, response) { var orcid = request.params.orcid; if (!orcid) { response.status(400).end(); return; } var getTheBadges = getBadgeResponse(orcid); getTheBadges(function (error, badges) { if (error !== null || !badges) { response.json(0); } else { response.json(badges.length); } }); } function getBadgesByType(request, response){ if (!request.params.orcid || !request.params.badge) { response.status(400).end(); return; } return badgerService.getBadges(request.params.orcid, request.params.badge); } function getBadgesByBadge(request, response) { returnBadges(getBadgesByType(request, response), request, response); } function getBadgesByBadgeCount(request, response) { getBadgesByType(request, response)(function (error, badges) { if (error !== null || !badges) { response.json(0); } else { response.json(badges.length); } }); } function getUser(request, response) { var orcid; response.header('Cache-Control', 'private, no-cache, no-store, must-revalidate'); if (request.session.orcid_token && request.session.orcid_token.token) { orcid = request.session.orcid_token.token.orcid; } var query = User.where({ orcid:orcid }); query.findOne(function(err, user) { if (user) { response.json(user); } else { response.json( orcid ? { name: request.session.orcid_token.name, orcid: orcid } : null ); } }); } module.exports = function (rb, bs) { returnBadges = rb; badgerService = bs; return { getBadges: getBadges, getBadgeCount: getBadgeCount, getBadgesByBadge: getBadgesByBadge, getBadgesByBadgeCount: getBadgesByBadgeCount, getUser: getUser }; };
JavaScript
0
@@ -134,88 +134,14 @@ adge -Response(orcid) %7B%0A return badgerService.getBadges(orcid);%0A%7D%0A%0Afunction getBadges +ByUser (req @@ -156,36 +156,29 @@ sponse) %7B%0A -var orcid = +if (! request.para @@ -181,38 +181,24 @@ params.orcid -;%0A if (!orcid ) %7B%0A resp @@ -249,57 +249,53 @@ turn -B + b adge -s(getBadgeResponse(orcid), request, response +rService.getBadges(request.params.orcid );%0A%7D @@ -309,29 +309,25 @@ ion getBadge -Count +s (request, re @@ -342,167 +342,158 @@ %7B%0A -var orcid = request.params.orcid;%0A if (!orcid) %7B%0A response.status(400).end();%0A return;%0A %7D%0A%0A var +returnBadges(getBadgeByUser(request, response), request, response);%0A%7D%0A%0Afunction get -The Badge -s = getBadgeResponse(orcid); +Count(request, response) %7B %0A get -The Badge -s +ByUser(request, response) (fun
82d20b00937392af7c1118ab9743e3b286e9ea12
Fix bug https://github.com/rancher/rancher/issues/11803
lib/shared/addon/components/empty-table/component.js
lib/shared/addon/components/empty-table/component.js
import { inject as service } from '@ember/service'; import Component from '@ember/component'; import layout from './template'; export default Component.extend({ layout, app: service(), scope: service(), classNames: ['row border-dash'], showNew: true, disabled: false, ctx: 'projectId', // or clusterId });
JavaScript
0.000005
@@ -203,16 +203,33 @@ vice(),%0A + app: service(), %0A class
3202d09db9e2388f68283554ad2817d27e7b69c2
add js to make center of map responsive
source/javascripts/directory.js
source/javascripts/directory.js
(function() { var handler = Gmaps.build('Google'); // console.dir(handler); var mapOptions = $('meta[name=mapOptions]').attr('content'); var locations = $('meta[name=locations]').attr('content'); var categories = $('meta[name=categories]').attr('content'); var markerLocations = []; var filteredLocations = []; var meetupList = $('.list a'); var defaultCoord = {lat: 49.282982, lng: -123.056554}; var defaultLatLng = new google.maps.LatLng(defaultCoord.lat, defaultCoord.lng); var categoryList = $('.js-menu > ul'); var markerIcon = { "url": '/images/directory/map-pin.png', "width": 33, "height": 39 }; var generateMarkerData = function(element) { var orgMarkup = ""; orgMarkup += "<h2 class='name'>"+element.name+"</h2>"; orgMarkup += "<div class='address'>"+element.address+"</div>"; orgMarkup += "<div class='view'><a href='"+element.website+"' target='_blank'>Go to website</a></div>"; element.infowindow = "<div class='map-marker'>"+orgMarkup+"</div>"; element.picture = markerIcon; if(element.lat && element.lng){ markerLocations.push(element); } } var setDefaultLocation = function() { handler.buildMap(mapOptions, function() { handler.map.centerOn(defaultLatLng); handler.getMap().setZoom(14); }); } var setZoomBasedOnLatitudePosition = function (latitudePosition) { if(latitudePosition != defaultCoord.lat){ handler.getMap().setZoom(16); }else{ handler.getMap().setZoom(14); } } var setGeolocation = function(pos) { var crd = pos.coords; var latlng = new google.maps.LatLng(crd.latitude, crd.longitude); handler.map.centerOn(latlng); setZoomBasedOnLatitudePosition(handler.getMap().getCenter().k); } var bindLiToMarker = function(json_array) { _.each(json_array, function(json){ var markerId = json.name.toLowerCase().replace(/\W/g, ''); var currentMarker = $('#'+markerId); currentMarker.on('click', function(e){ meetupList.removeClass('active'); $(this).addClass("active"); e.preventDefault(); handler.getMap().setZoom(16); json.marker.setMap(handler.getMap()); //because clusterer removes map property from marker json.marker.panTo(); google.maps.event.trigger(json.marker.getServiceObject(), 'click'); $("html, body").animate({ scrollTop:0 },"slow"); }); google.maps.event.addListener(json.marker.getServiceObject(), 'click', function(){ meetupList.removeClass('active'); currentMarker.addClass("active"); handler.getMap().setZoom(20); }); }); } var drawMap = function(points) { var markers = handler.addMarkers(points); _.each(points, function(json, index){ json.marker = markers[index]; }); // bindLiToMarker(markerLocations); handler.bounds.extendWith(markers); // setZoomBasedOnLatitudePosition(handler.getMap().getCenter().k); } var cleanMap = function(points) { handler.removeMarkers(); } var zoomToPosition = function(position) { var marker = handler.addMarker({ lat: position.coords.latitude, lng: position.coords.longitude }); handler.map.centerOn(marker); handler.bounds.extendWith(marker); handler.getMap().setZoom(18); } var generateCategoriesList = function(element) { var link = $("<a />", {html: element.name, href: '#'}); var listItem = $("<li />").append(link); categoryList.append(listItem); link.on('click', function(e){ filterCategories(element.name); $('.js-menu-screen').trigger('click'); }); } var generateCategories = function() { _.each(categories, generateCategoriesList); } var filterCategories = function(categoryFilter){ var filteredLocations = _.filter(markerLocations, function(item){ if ((typeof(item.category) !== 'undefined') && (item.category !== null)) { return item.category.name == categoryFilter; } }); cleanMap(markerLocations); buildMap(filteredLocations); handler.map.centerOn(defaultLatLng); handler.getMap().setZoom(16); } var buildMap = function(points) { handler.buildMap(mapOptions, function() { drawMap(points); }); } mapOptions = JSON.parse(mapOptions); locations = JSON.parse(locations); categories = JSON.parse(categories); mapOptions.provider.zoomControlOptions = google.maps.ZoomControlStyle.SMALL; setDefaultLocation(); navigator.geolocation.getCurrentPosition(setGeolocation); // map all locations on page load _.each(locations,generateMarkerData); buildMap(markerLocations); generateCategories(); })();
JavaScript
0
@@ -4686,16 +4686,238 @@ ions);%0A%0A + google.maps.event.addDomListener(window, %22resize%22, function() %7B%0A%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0var center = handler.getMap().getCenter();%0A%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0google.maps.event.trigger(handler.getMap(), %22resize%22);%0A%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0handler.getMap().setCenter(center);%0A %7D);%0A%0A genera
142cc761aa23044a97bca78a7779506d235a65ff
Remove UpgradeModal
packages/components/containers/payments/PlansSection.js
packages/components/containers/payments/PlansSection.js
import React, { useState, useEffect } from 'react'; import { c } from 'ttag'; import { SubTitle, Alert, DowngradeModal, MozillaInfoPanel, useSubscription, Loader, usePlans, useApi, useUser, useModals, useEventManager, useNotifications } from 'react-components'; import { checkSubscription, deleteSubscription } from 'proton-shared/lib/api/payments'; import { DEFAULT_CURRENCY, DEFAULT_CYCLE } from 'proton-shared/lib/constants'; import { getPlans, isBundleEligible } from 'proton-shared/lib/helpers/subscription'; import SubscriptionModal from './subscription/SubscriptionModal'; import { mergePlansMap, getCheckParams } from './subscription/helpers'; import UpgradeModal from './subscription/UpgradeModal'; import PlansTable from './PlansTable'; const PlansSection = () => { const { call } = useEventManager(); const { createNotification } = useNotifications(); const { createModal } = useModals(); const [user] = useUser(); const { isFree } = user; const [subscription = {}, loadingSubscription] = useSubscription(); const [plans = [], loadingPlans] = usePlans(); const api = useApi(); const [showUpgradeModal, setShowUpgradeModel] = useState(false); const [currency, setCurrency] = useState(DEFAULT_CURRENCY); const [cycle, setCycle] = useState(DEFAULT_CYCLE); const bundleEligible = isBundleEligible(subscription); const { CouponCode, Plans = [] } = subscription; const names = getPlans(subscription) .map(({ Title }) => Title) .join(c('Separator, spacing is important').t` and `); const handleUnsubscribe = async () => { await api(deleteSubscription()); await call(); createNotification({ text: c('Success').t`You have successfully unsubscribed` }); }; const handleOpenModal = () => { if (isFree) { return createNotification({ type: 'error', text: c('Info').t`You already have a free account` }); } createModal(<DowngradeModal onConfirm={handleUnsubscribe} />); }; const handleModal = (newPlansMap) => async () => { if (!newPlansMap) { handleOpenModal(); return; } const plansMap = mergePlansMap(newPlansMap, subscription); const couponCode = CouponCode ? CouponCode : undefined; // From current subscription; CouponCode can be null const { Coupon } = await api( checkSubscription(getCheckParams({ plans, plansMap, currency, cycle, coupon: couponCode })) ); const coupon = Coupon ? Coupon.Code : undefined; // Coupon can equals null createModal( <SubscriptionModal subscription={subscription} plansMap={plansMap} coupon={coupon} currency={currency} cycle={cycle} /> ); }; useEffect(() => { if (loadingPlans || loadingSubscription) { return; } const [{ Currency, Cycle } = {}] = plans; setCurrency(subscription.Currency || Currency); setCycle(subscription.Cycle || Cycle); if (isFree) { setShowUpgradeModel(true); } }, [loadingSubscription, loadingPlans]); useEffect(() => { if (showUpgradeModal) { createModal(<UpgradeModal plans={plans} onUpgrade={handleModal({ plus: 1 })} />); } }, [showUpgradeModal]); if (subscription.isManagedByMozilla) { return ( <> <SubTitle>{c('Title').t`Plans`}</SubTitle> <MozillaInfoPanel /> </> ); } if (loadingSubscription || loadingPlans) { return ( <> <SubTitle>{c('Title').t`Plans`}</SubTitle> <Loader /> </> ); } return ( <> <SubTitle>{c('Title').t`Plans`}</SubTitle> <Alert learnMore="https://protonmail.com/support/knowledge-base/paid-plans/"> {bundleEligible ? ( <div>{c('Info') .t`Get 20% bundle discount when you purchase ProtonMail and ProtonVPN together.`}</div> ) : null} {Plans.length ? <div>{c('Info').t`You are currently subscribed to ${names}.`}</div> : null} </Alert> <PlansTable currency={currency} cycle={cycle} updateCurrency={setCurrency} updateCycle={setCycle} onSelect={handleModal} user={user} subscription={subscription} plans={plans} /> <p className="small">* {c('Info concerning plan features').t`denotes customizable features`}</p> </> ); }; export default PlansSection;
JavaScript
0
@@ -699,64 +699,8 @@ s';%0A -import UpgradeModal from './subscription/UpgradeModal';%0A impo @@ -1113,77 +1113,8 @@ );%0A%0A - const %5BshowUpgradeModal, setShowUpgradeModel%5D = useState(false);%0A @@ -3035,303 +3035,45 @@ - if (isFree) %7B%0A setShowUpgradeModel(true);%0A %7D%0A %7D, %5BloadingSubscription, loadingPlans%5D);%0A%0A useEffect(() =%3E %7B%0A if (showUpgradeModal) %7B%0A createModal(%3CUpgradeModal plans=%7Bplans%7D onUpgrade=%7BhandleModal(%7B plus: 1 %7D)%7D /%3E);%0A %7D%0A %7D, %5BshowUpgradeModal +%7D, %5BloadingSubscription, loadingPlans %5D);%0A
d7bc8bc780bd8d9cb675e4d448a3e4e1ec6f609f
Fix wrong parameter name check
packages/core/strapi/lib/core-api/service/pagination.js
packages/core/strapi/lib/core-api/service/pagination.js
'use strict'; const _ = require('lodash'); const { has, toNumber, isUndefined, isPlainObject } = require('lodash/fp'); /** * Default limit values from config * @return {{maxLimit: number, defaultLimit: number}} */ const getLimitConfigDefaults = () => ({ defaultLimit: toNumber(strapi.config.get('api.rest.defaultLimit', 25)), maxLimit: toNumber(strapi.config.get('api.rest.maxLimit')) || null, }); /** * if there is max limit set and limit exceeds this number, return configured max limit * @param {number} limit - limit you want to cap * @param {number?} maxLimit - maxlimit used has capping * @returns {number} */ const applyMaxLimit = (limit, maxLimit) => { if (maxLimit && (limit === -1 || limit > maxLimit)) { return maxLimit; } return limit; }; const shouldCount = params => { if (_.has(params, 'pagination.withCount')) { return params.pagination.withCount === 'false' ? false : true; } return Boolean(strapi.config.get('api.rest.withCount', true)); }; const isOffsetPagination = pagination => has('start', pagination) || has('limit', pagination); const isPagedPagination = pagination => has('page', pagination) || has('page', pagination); const getPaginationInfo = params => { const { defaultLimit, maxLimit } = getLimitConfigDefaults(); if (isUndefined(params.pagination) || !isPlainObject(params.pagination)) { return { page: 1, pageSize: defaultLimit, }; } const { pagination } = params; if (isOffsetPagination(pagination) && isPagedPagination(pagination)) { throw new Error('Invalid pagination parameters. Expected either start/limit or page/pageSize'); } if (isPagedPagination(pagination)) { const pageSize = isUndefined(pagination.pageSize) ? defaultLimit : Math.max(1, toNumber(pagination.pageSize)); return { page: Math.max(1, toNumber(pagination.page || 1)), pageSize: applyMaxLimit(pageSize, maxLimit), }; } const limit = isUndefined(pagination.limit) ? defaultLimit : Math.max(1, toNumber(pagination.limit)); return { start: Math.max(0, toNumber(pagination.start || 0)), limit: applyMaxLimit(limit, maxLimit), }; }; const convertPagedToStartLimit = pagination => { if (_.has(pagination, 'page')) { const { page, pageSize } = pagination; return { start: (page - 1) * pageSize, limit: pageSize, }; } return pagination; }; const transformPaginationResponse = (paginationInfo, count) => { if (paginationInfo.page) { return { ...paginationInfo, pageCount: Math.ceil(count / paginationInfo.pageSize), total: count, }; } return { ...paginationInfo, total: count, }; }; module.exports = { getPaginationInfo, convertPagedToStartLimit, transformPaginationResponse, shouldCount, };
JavaScript
0.000005
@@ -1154,32 +1154,36 @@ on) %7C%7C has('page +Size ', pagination);%0A
e5eecc9e4cd25c0e8a255c3039d0c5342aece6ad
Update gulpfile.js with better defaults
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); var autoprefixer = require('gulp-autoprefixer'); var browserSync = require('browser-sync'); // Static Server / Watching files gulp.task('serve', ['styles'], function() { browserSync.init({ server: './' }); gulp.watch('src/scss/**/*.scss', ['styles']); gulp.watch('*.html').on('change', browserSync.reload); }); // Compile sass into CSS gulp.task('styles', function() { return gulp.src('src/scss/**/*.scss') .pipe(sass({outputStyle: 'compressed'})) .pipe(autoprefixer('last 2 versions', '> 2%')) .pipe(gulp.dest('dist/css/')) .pipe(browserSync.stream()); }); gulp.task('default', ['serve']);
JavaScript
0
@@ -1,8 +1,104 @@ +// *************************************%0A// Gulpfile%0A// *************************************%0A%0A 'use str @@ -113,16 +113,24 @@ ar gulp + = requir @@ -149,16 +149,24 @@ ar sass + = requir @@ -246,16 +246,17 @@ serSync + = requir @@ -282,38 +282,333 @@ %0A// -Static Server / Watching files +-------------------------------------%0A// Options%0A// -------------------------------------%0A%0Avar options = %7B%0A%0A%09html: %7B%0A%09%09files : '*.html'%0A%09%7D,%0A%0A%09sass: %7B%0A%09%09files%09 : 'src/scss/**/*.scss',%0A%09%09destination : 'dist/css'%0A%09%7D%0A%7D;%0A%0A// -------------------------------------%0A// Task: Serve%0A// -------------------------------------%0A %0Agul @@ -701,36 +701,34 @@ p.watch( -'src/scss/**/*.scss' +options.sass.files , %5B'styl @@ -746,24 +746,34 @@ p.watch( -'*.html' +options.html.files ).on('ch @@ -812,29 +812,102 @@ %0A// -Compile sass into CSS +-------------------------------------%0A// Task: Sass%0A// -------------------------------------%0A %0Agul @@ -953,36 +953,34 @@ ulp.src( -'src/scss/**/*.scss' +options.sass.files )%0A%09%09.pip @@ -1014,16 +1014,43 @@ essed'%7D) +.on('error', sass.logError) )%0A%09%09.pip @@ -1070,17 +1070,17 @@ r('last -2 +3 version @@ -1085,16 +1085,8 @@ ons' -, '%3E 2%25' ))%0A%09 @@ -1106,19 +1106,32 @@ est( -'dist/css/' +options.sass.destination ))%0A%09 @@ -1165,16 +1165,117 @@ );%0A%7D);%0A%0A +// -------------------------------------%0A// Task: Default%0A// -------------------------------------%0A%0A gulp.tas @@ -1294,12 +1294,13 @@ %5B'serve'%5D); +%0A
ba0c1c5f47a0254784bdf522f51cf36e3478d281
Align Babel targets with browsers that have CSS grid support
assets/brunch-config.js
assets/brunch-config.js
exports.config = { // See http://brunch.io/#documentation for docs. files: { javascripts: { joinTo: { "js/app.js": /^js/, "js/vendor.js": /^(?!js)/, }, }, stylesheets: { joinTo: "css/app.css", order: { after: ["web/static/css/app.css"], // concat app.css last }, }, templates: { joinTo: "js/app.js", }, }, conventions: { // This option sets where we should place non-css and non-js assets in. // By default, we set this to "/assets/static". Files in this directory // will be copied to `paths.public`, which is "priv/static" by default. assets: /^(static)/, }, // Phoenix paths configuration paths: { // Dependencies and current project directories to watch watched: ["static", "css", "js", "vendor"], // Where to compile files to public: "../priv/static", }, // Configure your plugins plugins: { sass: { mode: "native", }, babel: { presets: [ [ "@babel/preset-env", { useBuiltIns: "entry", targets: { phantomjs: "2.1.1", }, }, ], "@babel/preset-react", ], ignore: [/vendor/], }, }, overrides: { production: { optimize: true, sourceMaps: false, plugins: { sass: { mode: "native", }, babel: { presets: [ [ "@babel/preset-env", { useBuiltIns: "entry", targets: { firefox: "49", chrome: "53", safari: "10", edge: "14", }, }, ], "@babel/preset-react", ], ignore: [/vendor/], }, }, }, }, modules: { autoRequire: { "js/app.js": ["js/app"], }, }, npm: { enabled: true, }, };
JavaScript
0
@@ -1589,10 +1589,10 @@ x: %22 -49 +52 %22,%0A @@ -1622,9 +1622,9 @@ : %225 -3 +7 %22,%0A @@ -1651,16 +1651,18 @@ ari: %2210 +.3 %22,%0A @@ -1686,9 +1686,9 @@ : %221 -4 +6 %22,%0A
0da6bb6419b260bdd0f733d871f75a4561bde0cb
Remove import from dictionary
source/views/dictionary/list.js
source/views/dictionary/list.js
// @flow import React from 'react' import {StyleSheet, RefreshControl, Platform} from 'react-native' import {SearchableAlphabetListView} from '../components/searchable-alphabet-listview' import {Column} from '../components/layout' import { Detail, Title, ListRow, ListSectionHeader, ListSeparator, } from '../components/list' import delay from 'delay' import {reportNetworkProblem} from '../../lib/report-network-problem' import type {WordType} from './types' import type {TopLevelViewPropsType} from '../types' import {tracker} from '../../analytics' import groupBy from 'lodash/groupBy' import head from 'lodash/head' import uniq from 'lodash/uniq' import words from 'lodash/words' import deburr from 'lodash/deburr' import * as defaultData from '../../../docs/dictionary.json' const GITHUB_URL = 'https://stodevx.github.io/AAO-React-Native/dictionary.json' const ROW_HEIGHT = Platform.OS === 'ios' ? 76 : 89 const SECTION_HEADER_HEIGHT = Platform.OS === 'ios' ? 33 : 41 const splitToArray = (str: string) => words(deburr(str.toLowerCase())) const termToArray = (term: WordType) => uniq([...splitToArray(term.word), ...splitToArray(term.definition)]) const styles = StyleSheet.create({ row: { height: ROW_HEIGHT, }, rowSectionHeader: { height: SECTION_HEADER_HEIGHT, }, rowDetailText: { fontSize: 14, }, }) type Props = TopLevelViewPropsType type State = { results: {[key: string]: Array<WordType>}, allTerms: Array<WordType>, loading: boolean, } export class DictionaryView extends React.PureComponent<void, Props, State> { static navigationOptions = { title: 'Campus Dictionary', headerBackTitle: 'Dictionary', } state = { results: defaultData.data, allTerms: defaultData.data, loading: true, } componentWillMount() { this.refresh() } refresh = async () => { const start = Date.now() this.setState(() => ({loading: true})) await this.fetchData() // wait 0.5 seconds – if we let it go at normal speed, it feels broken. const elapsed = Date.now() - start if (elapsed < 500) { await delay(500 - elapsed) } this.setState(() => ({loading: false})) } fetchData = async () => { let {data: allTerms} = await fetchJson(GITHUB_URL).catch(err => { reportNetworkProblem(err) return defaultData }) if (process.env.NODE_ENV === 'development') { allTerms = defaultData.data } this.setState(() => ({allTerms})) } onPressRow = (data: WordType) => { tracker.trackEvent('dictionary', data.word) this.props.navigation.navigate('DictionaryDetailView', {item: data}) } renderRow = ({item}: {item: WordType}) => <ListRow onPress={() => this.onPressRow(item)} contentContainerStyle={styles.row} arrowPosition="none" > <Column> <Title lines={1}>{item.word}</Title> <Detail lines={2} style={styles.rowDetailText}> {item.definition} </Detail> </Column> </ListRow> renderSectionHeader = ({title}: {title: string}) => <ListSectionHeader title={title} style={styles.rowSectionHeader} /> renderSeparator = (sectionId: string, rowId: string) => <ListSeparator key={`${sectionId}-${rowId}`} /> performSearch = (text: ?string) => { if (!text) { this.setState(state => ({results: state.allTerms})) return } const query = text.toLowerCase() this.setState(state => ({ results: state.allTerms.filter(term => termToArray(term).some(word => word.startsWith(query)), ), })) } render() { return ( <SearchableAlphabetListView cell={this.renderRow} cellHeight={ ROW_HEIGHT + (Platform.OS === 'ios' ? 11 / 12 * StyleSheet.hairlineWidth : 0) } data={groupBy(this.state.results, item => head(item.word))} onSearch={this.performSearch} renderSeparator={this.renderSeparator} sectionHeader={this.renderSectionHeader} sectionHeaderHeight={SECTION_HEADER_HEIGHT} /> ) } }
JavaScript
0.000002
@@ -52,24 +52,8 @@ eet, - RefreshControl, Pla
eb068c345fa34f865af56fd2dfe69fef23c57fe3
Swap y axis coordinates to fix bug
jquery.flot.image.js
jquery.flot.image.js
/* Flot plugin for plotting images, e.g. useful for putting ticks on a prerendered complex visualization. The data syntax is [[image, x1, y1, x2, y2], ...] where (x1, y1) and (x2, y2) are where you intend the two opposite corners of the image to end up in the plot. Image must be a fully loaded Javascript image (you can make one with new Image()). If the image is not complete, it's skipped when plotting. There are two helpers included for retrieving images. The easiest work the way that you put in URLs instead of images in the data (like ["myimage.png", 0, 0, 10, 10]), then call $.plot.image.loadData(data, options, callback) where data and options are the same as you pass in to $.plot. This loads the images, replaces the URLs in the data with the corresponding images and calls "callback" when all images are loaded (or failed loading). In the callback, you can then call $.plot with the data set. See the included example. A more low-level helper, $.plot.image.load(urls, callback) is also included. Given a list of URLs, it calls callback with an object mapping from URL to Image object when all images are loaded or have failed loading. Options for the plugin are series: { images: { show: boolean anchor: "corner" or "center" } } which can be specified for a specific series $.plot($("#placeholder"), [{ data: [ ... ], images: { ... } ]) Note that because the data format is different from usual data points, you can't use images with anything else in a specific data series. Setting "anchor" to "center" causes the pixels in the image to be anchored at the pixel centers inside of at the corners, effectively letting half a pixel stick out as border. A possible future direction could be support for tiling for large images (like Google Maps). */ (function ($) { var options = { series: { images: { show: false, anchor: "corner" // or "center" } } }; $.plot.image = {}; $.plot.image.loadDataImages = function (series, options, callback) { var urls = [], points = []; var defaultShow = options.series.images.show; $.each(series, function (i, s) { if (!(defaultShow || s.images.show)) return; if (s.data) s = s.data; $.each(s, function (i, p) { if (typeof p[0] == "string") { urls.push(p[0]); points.push(p); } }); }); $.plot.image.load(urls, function (loadedImages) { $.each(points, function (i, p) { var url = p[0]; if (loadedImages[url]) p[0] = loadedImages[url]; }); callback(); }); } $.plot.image.load = function (urls, callback) { var missing = urls.length, loaded = {}; if (missing == 0) callback({}); $.each(urls, function (i, url) { var handler = function () { --missing; loaded[url] = this; if (missing == 0) callback(loaded); }; $('<img />').load(handler).error(handler).attr('src', url); }); } function draw(plot, ctx) { var plotOffset = plot.getPlotOffset(); $.each(plot.getData(), function (i, series) { var points = series.datapoints.points, ps = series.datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { var img = points[i], x1 = points[i + 1], y1 = points[i + 2], x2 = points[i + 3], y2 = points[i + 4], xaxis = series.xaxis, yaxis = series.yaxis, tmp; // actually we should check img.complete, but it // appears to be a somewhat unreliable indicator in // IE6 (false even after load event) if (!img || img.width <= 0 || img.height <= 0) continue; if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; } // clip if (x1 == x2 || y1 == y2 || x1 >= xaxis.max || x2 <= xaxis.min || y1 >= yaxis.max || y2 <= yaxis.min) continue; var sx1 = 0, sy1 = 0, sx2 = img.width, sy2 = img.height; if (series.images.anchor == "center") { sx1 += 0.5; sy1 += 0.5; sx2 -= 0.5; sy2 -= 0.5; } if (x1 < xaxis.min) { sx1 += (sx2 - sx1) * (xaxis.min - x1) / (x2 - x1); x1 = xaxis.min; } if (x2 > xaxis.max) { sx2 += (sx2 - sx1) * (xaxis.max - x2) / (x2 - x1); x2 = xaxis.max; } if (y1 < yaxis.min) { sy1 += (sy2 - sy1) * (yaxis.min - y1) / (y2 - y1); y1 = yaxis.min; } if (y2 > yaxis.max) { sy2 += (sy2 - sy1) * (yaxis.max - y2) / (y2 - y1); y2 = yaxis.max; } x1 = xaxis.p2c(x1); x2 = xaxis.p2c(x2); y1 = yaxis.p2c(y1); y2 = yaxis.p2c(y2); // the transformation may have swapped us if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; } ctx.drawImage(img, sx1, sy1, sx2 - sx1, sy2 - sy1, x1 + plotOffset.left, y1 + plotOffset.top, x2 - x1, y2 - y1); } }); } function processRawData(plot, series, data, datapoints) { if (!series.images.show) return; // format is Image, x1, y1, x2, y2 (opposite corners) datapoints.format = [ { required: true }, { x: true, number: true, required: true }, { y: true, number: true, required: true }, { x: true, number: true, required: true }, { y: true, number: true, required: true } ]; } function init(plot) { plot.hooks.processRawData.push(processRawData); plot.hooks.draw.push(draw); } $.plot.plugins.push({ init: init, options: options, name: 'image', version: '1.0' }); })(jQuery);
JavaScript
0.000001
@@ -5370,23 +5370,23 @@ sy -1 +2 += (sy -2 +1 - sy -1 +2 ) * @@ -5534,23 +5534,23 @@ sy -2 +1 += (sy -2 +1 - sy -1 +2 ) * @@ -5625,32 +5625,48 @@ %7D%0A + %0A
3becb8edbbe5644c56b08e0b64de7eb5cf819330
fix connectors when inputs/outputs are undefined
packages/elements/src/input-connector-linkable/index.js
packages/elements/src/input-connector-linkable/index.js
import InputConnectorElement from '../input-connector/index.js'; const CONNECTORS = new Set(); let activeConnector = null; /** * Handle connector elements linking */ class InputConnectorLinkableElement extends InputConnectorElement { constructor() { super(); this.shadowRoot.querySelector('slot style').insertAdjacentHTML('beforeend', ` :host { cursor: pointer; margin: 0; padding: .2em; touch-action: none; } :host(:hover) { background: red; } :host(:focus-within) { background: green; } :host([connected]) { background: orange; } `); this.addEventListener('pointerdown', this._onPointerDown); this._onWindowPointerUpBinded = this._onWindowPointerUp.bind(this); this.addEventListener('pointerup', (event) => { }, { passive: false }); } connectedCallback() { CONNECTORS.add(this); } disconnectedCallback() { CONNECTORS.delete(this); super.disconnectedCallback(); } _onPointerDown() { if (activeConnector) { return; } activeConnector = this; window.addEventListener('pointerup', this._onWindowPointerUpBinded, { passive: false }); this.dispatchEvent(new CustomEvent('linkstart', { composed: true, bubbles: true, detail: { input: this, output: undefined, }, })); } _onWindowPointerUp(event) { if (!activeConnector) { return; } let hitConnector; for (const connector of CONNECTORS) { const boundingClientRect = connector.getBoundingClientRect(); if (event.clientX > boundingClientRect.x && event.clientX < boundingClientRect.x + boundingClientRect.width && event.clientY > boundingClientRect.y && event.clientY < boundingClientRect.y + boundingClientRect.height) { hitConnector = connector; } } if (hitConnector === activeConnector) { return; } window.removeEventListener('pointerup', this._onWindowPointerUpBinded); if (!hitConnector || (activeConnector.type === hitConnector.type && hitConnector.type !== InputConnectorLinkableElement.TYPE_BOTH)) { activeConnector = null; this.dispatchEvent(new CustomEvent('linkend', { composed: true, bubbles: true, detail: { input: null, output: null, }, })); return; } const inputConnector = activeConnector.type & InputConnectorLinkableElement.TYPE_OUTPUT ? activeConnector : hitConnector; const outputConnector = hitConnector.type & InputConnectorLinkableElement.TYPE_INPUT ? hitConnector : activeConnector; inputConnector.outputs.add(outputConnector); activeConnector = null; this.dispatchEvent(new CustomEvent('linkend', { composed: true, bubbles: true, detail: { input: inputConnector, output: outputConnector, }, })); } } export default InputConnectorLinkableElement;
JavaScript
0.000014
@@ -2470,32 +2470,96 @@ Connector.type & + InputConnectorLinkableElement.TYPE_INPUT %7C%7C hitConnector.type & InputConnectorL @@ -2587,22 +2587,19 @@ UTPUT ? -active +hit Connecto @@ -2602,19 +2602,22 @@ ector : -hit +active Connecto @@ -2647,18 +2647,20 @@ ector = -h i +npu tConnect @@ -2665,56 +2665,28 @@ ctor -.type & InputConnectorLinkableElement.TYPE_INPUT + === activeConnector ? h
73a48318a19a207c63f6d03ecea8ce35b7e2364a
Fix error when rendering limited account in web UI (#19413)
app/javascript/mastodon/components/avatar.js
app/javascript/mastodon/components/avatar.js
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { autoPlayGif } from '../initial_state'; import classNames from 'classnames'; export default class Avatar extends React.PureComponent { static propTypes = { account: ImmutablePropTypes.map, size: PropTypes.number.isRequired, style: PropTypes.object, inline: PropTypes.bool, animate: PropTypes.bool, }; static defaultProps = { animate: autoPlayGif, size: 20, inline: false, }; state = { hovering: false, }; handleMouseEnter = () => { if (this.props.animate) return; this.setState({ hovering: true }); } handleMouseLeave = () => { if (this.props.animate) return; this.setState({ hovering: false }); } render () { const { account, size, animate, inline } = this.props; const { hovering } = this.state; const style = { ...this.props.style, width: `${size}px`, height: `${size}px`, backgroundSize: `${size}px ${size}px`, }; if (account) { const src = account.get('avatar'); const staticSrc = account.get('avatar_static'); if (hovering || animate) { style.backgroundImage = `url(${src})`; } else { style.backgroundImage = `url(${staticSrc})`; } } return ( <div className={classNames('account__avatar', { 'account__avatar-inline': inline })} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} style={style} role='img' aria-label={account.get('acct')} /> ); } }
JavaScript
0
@@ -1610,24 +1610,25 @@ bel=%7Baccount +? .get('acct')
26b66284d6442cb8e15beff8952bb0e208ac124d
update .jsdoc.js by add protos and remove double quotes (#71)
packages/google-devtools-cloudbuild/.jsdoc.js
packages/google-devtools-cloudbuild/.jsdoc.js
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // 'use strict'; module.exports = { opts: { readme: './README.md', package: './package.json', template: './node_modules/jsdoc-fresh', recurse: true, verbose: true, destination: './docs/' }, plugins: [ 'plugins/markdown', 'jsdoc-region-tag' ], source: { excludePattern: '(^|\\/|\\\\)[._]', include: [ 'build/src' ], includePattern: '\\.js$' }, templates: { copyright: 'Copyright 2019 Google, LLC.', includeDate: false, sourceFiles: false, systemName: '@google-cloud/cloudbuild', theme: 'lumen', default: { "outputSourceFiles": false } }, markdown: { idInHeadings: true } };
JavaScript
0
@@ -950,16 +950,32 @@ ild/src' +,%0A 'protos' %0A %5D,%0A @@ -1202,17 +1202,16 @@ %7B%0A -%22 outputSo @@ -1219,17 +1219,16 @@ rceFiles -%22 : false%0A
11b16b870615e4929ff17e8762faca9b068ec692
Reset tile keys
player.js
player.js
var _ = require('lodash') var inherits = require('inherits') var aabb = require('aabb-2d') var math = require('mathjs') var transform = require('./transform.js') var circle = require('./geo/circle.js') var Collision = require('./collision.js') var Fixmove = require('./fixmove.js') var Automove = require('./automove.js') var Freemove = require('./freemove.js') var Entity = require('crtrdg-entity') module.exports = Player; inherits(Player, Entity); function Player(opts){ this.geometry = circle({ position: opts.position, angle: opts.angle, fill: opts.fill, stroke: opts.stroke, scale: opts.scale, thickness: opts.thickness, children: [ circle({fill: opts.fill, stroke: opts.stroke, thickness: opts.thickness, position: [-0.7, -.9], scale: 0.6, angle: -45, aspect: 0.6}), circle({fill: opts.fill, stroke: opts.stroke, thickness: opts.thickness, position: [0.7, -.9], scale: 0.6, angle: 45, aspect: 0.6}) ] }) this.movement = {} this.movement.center = new Fixmove() this.movement.tile = new Automove({ keymap: ['Q', 'W', 'E', 'A', 'S', 'D'], heading: [-60, 0, 60, -120, -180, 120], shift: 8 }) this.movement.path = new Automove({ keymap: ['S'], heading: [-180] }) this.collision = new Collision() this.waiting = true } Player.prototype.move = function(keyboard, world) { var self = this var current = self.geometry.transform var tile = world.tiles[world.locate(self.position())] var inside = tile.children[0].contains(current.position()) var delta if (inside) { var keysDown = keyboard.keysDown if (self.movement.tile.keypress(keysDown)) self.waiting = false if (self.waiting) { delta = self.movement.center.compute(current, {position: [tile.transform.position()[0], tile.transform.position()[1]]}) } else { delta = self.movement.tile.compute(keysDown, current, tile.transform) } } else { self.waiting = true delta = self.movement.path.compute(keyboard.keysDown, current) } self.geometry.update(delta) self.collision.handle(world, self.geometry, delta) } Player.prototype.draw = function(context, camera) { this.geometry.draw(context, camera, {order: 'bottom'}) } Player.prototype.position = function() { return this.geometry.transform.position() } Player.prototype.angle = function() { return this.geometry.transform.angle() } Player.prototype.scale = function() { return this.geometry.transform.scale() }
JavaScript
0
@@ -1584,45 +1584,8 @@ ) %7B%0A - var keysDown = keyboard.keysDown%0A @@ -1616,16 +1616,25 @@ eypress( +keyboard. keysDown @@ -1861,16 +1861,25 @@ compute( +keyboard. keysDown @@ -1946,16 +1946,47 @@ = true%0A + self.movement.tile.reset()%0A delt
f96020b2f8b62d2efca0d69321c785befbde3a7c
Fix DraftEditorPlaceholder shouldComponetUpdate
src/component/base/DraftEditorPlaceholder.react.js
src/component/base/DraftEditorPlaceholder.react.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 strict-local * @emails oncall+draft_js */ 'use strict'; import type {DraftTextAlignment} from 'DraftTextAlignment'; import type EditorState from 'EditorState'; const React = require('React'); const cx = require('cx'); const shallowEqual = require('shallowEqual'); type Props = { accessibilityID: string, className?: string, editorState: EditorState, text: string, textAlignment: DraftTextAlignment, ... }; /** * This component is responsible for rendering placeholder text for the * `DraftEditor` component. * * Override placeholder style via CSS. */ class DraftEditorPlaceholder extends React.Component<Props> { shouldComponentUpdate(nextProps: Props): boolean { const {editorState, ...otherProps} = this.props; const {editorState: nextEditorState, ...nextOtherProps} = nextProps; return ( editorState.getSelection().getHasFocus() !== nextEditorState.getSelection().getHasFocus() || shallowEqual(otherProps, nextOtherProps) ); } render(): React.Node { const innerClassName = // We can't use joinClasses since the fbjs flow definition is wrong. Using // cx to concatenate is rising issues with haste internally. // eslint-disable-next-line fb-www/cx-concat cx('public/DraftEditorPlaceholder/inner') + (this.props.className != null ? ` ${this.props.className}` : ''); return ( <div className={cx({ 'public/DraftEditorPlaceholder/root': true, 'public/DraftEditorPlaceholder/hasFocus': this.props.editorState .getSelection() .getHasFocus(), })}> <div className={innerClassName} id={this.props.accessibilityID} style={{ whiteSpace: 'pre-wrap', }}> {this.props.text} </div> </div> ); } } module.exports = DraftEditorPlaceholder;
JavaScript
0.000003
@@ -1144,16 +1144,17 @@ %7C%0A +! shallowE
b6cb93a163fa14afd6589966fa7eb3905f90fc6e
remove logging from solver function
src/arithmetic/solveRational.js
src/arithmetic/solveRational.js
import * as mats from './matrices'; import { intMatrices, matrices, residueClassRing } from './types'; const iops = intMatrices; const fops = matrices; const p = 9999991; const pops = mats.extend(residueClassRing(p), ['Integer'], true); const invModP = M => { const ops = pops; const n = M.length; const A = M.map((row, i) => row.concat(ops.unitVector(n, i))); const E = ops.rowEchelonForm(A); return E.map(row => row.slice(n)); }; const numberOfPAdicStepsNeeded = (A, b) => { const lengths = M => fops.transposed(M).map(r => fops.norm(r)); const max = v => v.reduce((x, y) => x > y ? x : y); const product = v => v.reduce((x, y) => x * y); const ls = lengths(A).concat(max(lengths(b))); const delta = product(ls.sort().slice(A[0].length)); const golden = (1 + Math.sqrt(5)) / 2; return Math.ceil(2 * Math.log(delta * golden) / Math.log(p)); }; const rationalReconstruction = (s, h) => { const ops = iops; let u = [h, s]; let v = [0, 1]; let sign = 1; while (ops.gt(ops.times(u[1], u[1]), h)) { const q = ops.idiv(u[0], u[1]); u = [u[1], ops.minus(u[0], ops.times(q, u[1]))]; v = [v[1], ops.plus(v[0], ops.times(q, v[1]))]; sign *= -1; } return fops.div(ops.times(sign, u[1]), v[1]); }; export default function solve(A, b) { console.log(`solve(${A}, ${b})`); const C = invModP(A); console.log(` C = ${C}`); console.log(` A * C = ${pops.times(A, C)}`); const nrSteps = numberOfPAdicStepsNeeded(A, b); console.log(` nrSteps = ${nrSteps}`); let bi = b; let pi = 1; let si = 0; for (let i = 0; i < nrSteps; ++i) { const xi = pops.times(C, bi); bi = iops.idiv(iops.minus(bi, iops.times(A, xi)), p); si = iops.plus(si, iops.times(pi, xi)); pi = iops.times(pi, p); } const s = si; console.log(` s = ${s}`); const r = s.map(row => row.map(x => rationalReconstruction(x, pi))); console.log(` r = ${r}`); return r; }; if (require.main == module) { Array.prototype.toString = function() { return '[ ' + this.map(x => x.toString()).join(', ') + ' ]'; }; solve( [ [ 4, -4 ], [ 1, 0 ] ], [ [ 1, 1, 1 ], [ 0, 0, 0 ] ] ); }
JavaScript
0.000001
@@ -1298,139 +1298,25 @@ cons -ole.log(%60solve($%7BA%7D, $%7Bb%7D)%60);%0A const C = invModP(A);%0A console.log(%60 C = $%7BC%7D%60);%0A console.log(%60 A * C = $%7Bpops.times(A, C)%7D%60);%0A +t C = invModP(A); %0A c @@ -1365,49 +1365,8 @@ b); -%0A console.log(%60 nrSteps = $%7BnrSteps%7D%60); %0A%0A @@ -1616,67 +1616,20 @@ %7D%0A - const s = si;%0A console.log(%60 s = $%7Bs%7D%60);%0A%0A const r = +%0A return s +i .map @@ -1686,50 +1686,8 @@ ));%0A - console.log(%60 r = $%7Br%7D%60);%0A%0A return r;%0A %7D;%0A%0A @@ -1832,21 +1832,236 @@ %7D;%0A%0A -solve +const testSolver = (A, b) =%3E %7B%0A console.log();%0A console.log(%60solving $%7BA%7D * x = $%7Bb%7D%60);%0A const x = solve(A, b);%0A console.log(%60 x = $%7Bx%7D%60);%0A console.log(%60 A * x = $%7Bfops.times(A, x)%7D%60);%0A %7D;%0A%0A testSolver (%0A %5B
7ad4a158d6ba7876a340f0fd97a6299ea0997233
update on start
job/index.js
job/index.js
var CronJob = require('cron').CronJob; var moment = require('moment'); var updateData = require('./updateData'); var cleanData = require('./cleanData'); //var time = '0 */1 * * * *'; var twoHours = '0 */2 * * *';//2 hours var sixHours = '0 */6 * * *'; // 6 hours //var time = '00 30 3 * * *'; var clean = function() { console.log('cleaning', moment().toDate()); cleanData.start(); }; var update = function() { console.log('updateData', moment().toDate()); updateData.start(); }; var cleaner = new CronJob({ cronTime: sixHours, onTick: clean }) var updater = new CronJob({ cronTime: twoHours, onTick: update }) clean(function() { update(); }) updater.start(); cleaner.start();
JavaScript
0
@@ -629,31 +629,19 @@ %0A%0Aclean( -function() %7B%0A +);%0A update() @@ -641,19 +641,16 @@ pdate(); -%0A%7D) %0A%0Aupdate
e3ca70f8a0ba584e1e37c184a2c7d819ed12b782
Add compile:typescript:aot task. Remove unnecessary tasks from watch task
gulpfile.js
gulpfile.js
"use strict"; const fs = require( "fs" ); const del = require( "del" ); const gulp = require( "gulp" ); const util = require( "gulp-util" ); const runSequence = require( "run-sequence" ); const sourcemaps = require( "gulp-sourcemaps" ); const ts = require( "gulp-typescript" ); const dts = require( "dts-generator" ); const glob = require( "glob" ); const minimatch = require( "minimatch" ); const jeditor = require( "gulp-json-editor" ); const tslint = require( "gulp-tslint" ); let config = { source: { typescript: [ "src/**/*.ts", "!src/**/*.spec.ts", ] }, dist: { tsOutput: "dist", all: "dist/**/*" } }; gulp.task( "default", [ "build" ] ); gulp.task( "build", [ "clean:dist" ], ( done ) => { runSequence( "clean:dist", [ "compile:typescript", "prepare-npm-package" ], done ); } ); gulp.task( "compile:typescript", () => { let tsProject = ts.createProject( "tsconfig.json", { "declaration": true } ); let tsResults = gulp.src( config.source.typescript ) .pipe( sourcemaps.init() ) .pipe( tsProject() ); tsResults.dts .pipe( gulp.dest( config.dist.tsOutput ) ) ; return tsResults.js .pipe( sourcemaps.write( "." ) ) .pipe( gulp.dest( config.dist.tsOutput ) ) ; } ); gulp.task( "clean:dist", ( done ) => { return del( config.dist.all, done ); } ); gulp.task( "lint", [ "lint:typescript" ] ); gulp.task( "lint:typescript", () => { return gulp.src( config.source.typescript ) .pipe( tslint( { tslint: require( "tslint" ) } ) ) .pipe( tslint.report( "prose" ) ) ; } ); gulp.task( "prepare-npm-package", ( done ) => { runSequence( [ "prepare-npm-package:copy-docs", "prepare-npm-package:copy-package-json" ], done ); } ); gulp.task( "prepare-npm-package:copy-docs", () => { return gulp.src( [ "README.md", "CHANGELOG.md", "LICENSE", ] ).pipe( gulp.dest( config.dist.tsOutput ) ); } ); gulp.task( "prepare-npm-package:copy-package-json", () => { return gulp.src( "package.json" ) .pipe( jeditor( ( json ) => { delete json.private; delete json.scripts; delete json.devDependencies; json.main = json.main.replace( "dist/", "" ); json.typings = json.typings.replace( "dist/", "" ); return json; } ) ) .pipe( gulp.dest( config.dist.tsOutput ) ); } ); gulp.task( "watch", ( done ) => { runSequence( [ "compile:styles", "compile:templates", "compile:typescript" ], [ "watch:styles", "watch:templates", "watch:typescript" ], done ); } ); gulp.task( "watch:typescript", () => { return gulp.watch( config.source.typescript, [ "compile:typescript" ] ); } );
JavaScript
0.000168
@@ -477,16 +477,62 @@ lint%22 ); +%0Aconst exec = require( %22child_process%22 ).exec; %0A%0Alet co @@ -778,16 +778,18 @@ ence(%0A%09%09 +%5B %22clean:d @@ -793,16 +793,36 @@ n:dist%22, + %22clean:compiled%22 %5D, %0A%09%09%5B %22co @@ -837,16 +837,20 @@ pescript +:aot %22, %22prep @@ -1285,32 +1285,194 @@ t ) )%0A%09%09;%0A%7D );%0A%0A +gulp.task( %22compile:typescript:aot%22, function( cb ) %7B%0A%09exec( %22node_modules/.bin/ngc -p tsconfig.json%22, function( err, stdout, stderr ) %7B%0A%09%09cb( err );%0A%09%7D );%0A%7D );%0A%0A gulp.task( %22clea @@ -2545,47 +2545,8 @@ %0A%09%09%5B - %22compile:styles%22, %22compile:templates%22, %22co @@ -2561,24 +2561,28 @@ pescript +:aot %22 %5D,%0A%09%09%5B %22watch: @@ -2577,43 +2577,8 @@ %0A%09%09%5B - %22watch:styles%22, %22watch:templates%22, %22wa @@ -2715,24 +2715,28 @@ e:typescript +:aot %22 %5D );%0A%7D );%0A
7ad00ae0bbd599e742448a71ce4f83160490c6af
put a more recent strict_min_version
tools/manifests/firefox.js
tools/manifests/firefox.js
const {config} = require('node-config-ts'); module.exports = { ...require('./common.js'), optional_permissions: ['tabs'], applications: { gecko: { id: config.FirefoxId, strict_min_version: '52.0', }, }, };
JavaScript
0.000016
@@ -210,10 +210,10 @@ n: ' -52 +84 .0',
177bdb56f18c5ce4d3d0215b5cf6e66febc371e9
Add a check for history and replaceState.
src/auth.js
src/auth.js
window.extractToken = (hash) => { const match = hash.match(/access_token=(\w+)/); let token = !!match && match[1]; if (!token) { token = localStorage.getItem('ello_access_token'); } return token; } window.checkAuth = () => { const token = extractToken(document.location.hash); window.history.replaceState(window.history.state, document.title, window.location.pathname) document.location.hash = '' // this is a fallback for IE < 10 if (token) { localStorage.setItem('ello_access_token', token) } else { // TODO: protocol, hostname, <port>, scope, client_id are all ENVs? const url = 'https://' + ENV.AUTH_DOMAIN + '/api/oauth/authorize.html' + '?response_type=token' + '&scope=web_app' + '&client_id=' + ENV.AUTH_CLIENT_ID + '&redirect_uri=' + ENV.AUTH_REDIRECT_URI; window.location.href = url; } } window.resetAuth = () => { const token = localStorage.getItem('ello_access_token'); if (token) { localStorage.removeItem('ello_access_token'); window.checkAuth() } } window.checkAuth()
JavaScript
0
@@ -287,16 +287,73 @@ .hash);%0A + if (window.history && window.history.replaceState) %7B%0A window @@ -438,16 +438,29 @@ thname)%0A + %7D else %7B%0A docume @@ -515,16 +515,20 @@ IE %3C 10%0A + %7D%0A if (to
1f701b4ea816392af783333c66bf7d3c77899995
add bet strategy
player.js
player.js
var NAME = "Crazy Penguins"; module.exports = { VERSION: "0.0.6", bet_request: function (game_state, bet) { var player = game_state.players[game_state.in_action]; var maxbet = game_state.players.reduce(function (p, n) { return n.bet > p ? n.bet : p }, 0); if (player.hole_cards[0] && player.hole_cards[1] && player.hole_cards[0].rank == player.hole_cards[1].rank) { bet(maxbet + game_state.minimum_raise); } else { bet(game_state.minimum_raise); } }, showdown: function (game_state) { } };
JavaScript
0.000006
@@ -374,24 +374,94 @@ %5B1%5D.rank) %7B%0A + bet(player.stack);%0A %7D else if (maxbet %3C player.stack / 10) %7B%0A bet(ma
8c2b69876fc028d5e3be65cb53f2f84f5a239330
Fix variable names in two loops.
src/chat/narrowsReducer.js
src/chat/narrowsReducer.js
/* @flow strict-local */ import union from 'lodash.union'; import type { NarrowsState, Action } from '../types'; import { DEAD_QUEUE, LOGOUT, LOGIN_SUCCESS, ACCOUNT_SWITCH, MESSAGE_FETCH_COMPLETE, EVENT_NEW_MESSAGE, EVENT_MESSAGE_DELETE, EVENT_UPDATE_MESSAGE_FLAGS, } from '../actionConstants'; import { LAST_MESSAGE_ANCHOR, FIRST_UNREAD_ANCHOR } from '../constants'; import { isMessageInNarrow, STARRED_NARROW_STR } from '../utils/narrow'; import { NULL_OBJECT } from '../nullObjects'; const initialState: NarrowsState = NULL_OBJECT; const messageFetchComplete = (state, action) => { const key = JSON.stringify(action.narrow); const fetchedMessageIds = action.messages.map(message => message.id); const replaceExisting = action.anchor === FIRST_UNREAD_ANCHOR || action.anchor === LAST_MESSAGE_ANCHOR; return { ...state, [key]: replaceExisting ? fetchedMessageIds : union(state[key], fetchedMessageIds).sort((a, b) => a - b), }; }; const eventNewMessage = (state, action) => { let stateChange = false; const msg = {}; Object.keys(state).forEach(key => { const isInNarrow = isMessageInNarrow(action.message, JSON.parse(key), action.ownEmail); const isCaughtUp = action.caughtUp[key] && action.caughtUp[key].newer; const messageDoesNotExist = state[key].find(id => action.message.id === id) === undefined; if (isInNarrow && isCaughtUp && messageDoesNotExist) { stateChange = true; msg[key] = [...state[key], action.message.id]; } else { msg[key] = state[key]; } }); const newState = msg; return stateChange ? newState : state; }; const eventMessageDelete = (state, action) => { let stateChange = false; const updatedState = {}; Object.keys(state).forEach(key => { updatedState[key] = state[key].filter(id => id !== action.messageId); stateChange = stateChange || updatedState[key].length < state[key].length; }); const newState = updatedState; return stateChange ? newState : state; }; const eventUpdateMessageFlags = (state, action) => { const { messages, flag, operation } = action; const messagesSet = new Set(messages); const updates = []; if (flag === 'starred' && state[STARRED_NARROW_STR]) { if (operation === 'add') { updates.push({ [STARRED_NARROW_STR]: [...state[STARRED_NARROW_STR], ...messages].sort(), }); } else { // operation === 'remove' updates.push({ [STARRED_NARROW_STR]: state[STARRED_NARROW_STR].filter(id => !messagesSet.has(id)), }); } } if (!updates.length) { return state; } return Object.assign({}, state, ...updates); }; export default (state: NarrowsState = initialState, action: Action): NarrowsState => { switch (action.type) { case DEAD_QUEUE: case LOGOUT: case LOGIN_SUCCESS: case ACCOUNT_SWITCH: return initialState; case MESSAGE_FETCH_COMPLETE: return messageFetchComplete(state, action); case EVENT_NEW_MESSAGE: return eventNewMessage(state, action); case EVENT_MESSAGE_DELETE: return eventMessageDelete(state, action); case EVENT_UPDATE_MESSAGE_FLAGS: return eventUpdateMessageFlags(state, action); default: return state; } };
JavaScript
0
@@ -1059,19 +1059,24 @@ const -msg +newState = %7B%7D;%0A @@ -1462,27 +1462,32 @@ true;%0A -msg +newState %5Bkey%5D = %5B... @@ -1537,19 +1537,24 @@ %7B%0A -msg +newState %5Bkey%5D = @@ -1581,32 +1581,8 @@ %7D);%0A - const newState = msg;%0A re @@ -1705,23 +1705,19 @@ const -updated +new State = @@ -1762,23 +1762,19 @@ %3E %7B%0A -updated +new State%5Bke @@ -1861,23 +1861,19 @@ ange %7C%7C -updated +new State%5Bke @@ -1913,41 +1913,8 @@ %7D);%0A - const newState = updatedState;%0A re
dfb97e28de0104012fecbc20d58bba1577e25655
Test for proxy to be applied
spec/Layers/BasemapLayerSpec.js
spec/Layers/BasemapLayerSpec.js
/* eslint-env mocha */ describe('L.esri.BasemapLayer', function () { function createMap () { // create container var container = document.createElement('div'); // give container a width/height container.setAttribute('style', 'width:500px; height: 500px;'); // add container to body document.body.appendChild(container); return L.map(container).setView([37.75, -122.45], 5); } var map; var server; var clock; var mockAttributions = { 'contributors': [ { 'attribution': 'SkyNet', 'coverageAreas': [ { 'zoomMax': 19, 'zoomMin': 0, 'score': 50, 'bbox': [-84.94, -179.66, 84.94, 179.66] } ] }, { 'attribution': 'City & County of San Francisco', 'coverageAreas': [ { 'zoomMax': 19, 'zoomMin': 16, 'score': 100, 'bbox': [37.71, -122.51, 37.83, -122.36] } ] } ] }; beforeEach(function () { clock = sinon.useFakeTimers(); server = sinon.fakeServer.create(); server.respondWith('GET', new RegExp(/.*/), JSON.stringify(mockAttributions)); map = createMap(); }); afterEach(function () { clock.restore(); server.restore(); map.remove(); }); it('can return valid basemaps', function () { var testmaps = ['Streets', 'Topographic', 'NationalGeographic', 'Oceans', 'OceansLabels', 'DarkGray', 'DarkGrayLabels', 'Gray', 'GrayLabels', 'Imagery', 'ImageryLabels', 'ImageryTransportation', 'ShadedRelief', 'ShadedReliefLabels', 'Terrain', 'TerrainLabels', 'USATopo', 'ImageryClarity', 'ImageryFirefly', 'Physical']; for (var i = 0, len = testmaps.length; i < len; i++) { var name = testmaps[i]; expect(L.esri.basemapLayer(name)).to.be.instanceof(L.esri.BasemapLayer); expect(L.esri.basemapLayer(name)._url).to.equal(L.esri.BasemapLayer.TILES[name].urlTemplate); } }); it('can survive adding/removing basemaps w/ labels', function () { var moremaps = ['Oceans', 'DarkGray', 'Gray', 'Imagery', 'ShadedRelief', 'Terrain']; for (var i = 0, len = moremaps.length; i < len; i++) { var layer = L.esri.basemapLayer(moremaps[i]).addTo(map); var layerWithLabels = L.esri.basemapLayer(moremaps[i] + 'Labels').addTo(map); expect(map.hasLayer(layer)).to.equal(true); expect(map.hasLayer(layerWithLabels)).to.equal(true); map.removeLayer(layer); map.removeLayer(layerWithLabels); expect(map.hasLayer(layer)).to.equal(false); expect(map.hasLayer(layerWithLabels)).to.equal(false); } }); it('can be added to the map as normal', function () { var baseLayer = L.esri.basemapLayer('Streets'); map.addLayer(baseLayer); expect(map.hasLayer(baseLayer)).to.equal(true); }); it('will append tokens when fetching tiles if necessary', function () { var baseLayer = L.esri.basemapLayer('Streets', {token: 'bogus'}); map.addLayer(baseLayer); expect(baseLayer._url).to.contain('token=bogus'); }); it('will throw an error given invalid basemap name', function () { expect(function () { L.esri.basemapLayer('junk'); }).to.throw(/Invalid parameter/); }); it('should have an L.esri.basemapLayer alias', function () { expect(L.esri.basemapLayer('Topographic')).to.be.instanceof(L.esri.BasemapLayer); }); // /* // need to figure out how to wire up the mockAttributions to // test display when map is panned beyond the dateline // // i dont understand how to spoof http responses for inner logic private function calls // like the jsonp request made inside L.esri.Util._getAttributionData(); // */ // it('can display attribution when panned beyond the dateline', function () { // var baseLayer = L.esri.basemapLayer('Streets'); // map.addLayer(baseLayer); // // L.esri.Util._getAttributionData(baseLayer.options.attributionUrl, map); // // map.setView([ 37.30, 360], 10); // clock.tick(151); // // var check = false; // for(var prop in map.attributionControl._attributions) { // // console.log(prop); // if (prop.match(/SkyNet/i) != null) { // test = true; // }; // } // // expect(check).to.equal(true); // }); });
JavaScript
0
@@ -3069,32 +3069,305 @@ bogus');%0A %7D);%0A%0A + it('will prepend proxy when fetching tiles if necessary', function () %7B%0A var proxyURL = 'http://example.proxy';%0A var baseLayer = L.esri.basemapLayer('Streets', %7Bproxy: proxyURL%7D);%0A map.addLayer(baseLayer);%0A expect(baseLayer._url).to.contain(proxyURL);%0A %7D);%0A%0A it('will throw
b7151e690e22e30832dd309ce37987beef63bba1
update some. remove unnecessary return statement
src/understreck.some/index.js
src/understreck.some/index.js
import isArray from '../understreck.isarray' import isFunction from '../understreck.isfunction' function some (collection, predicate) { //, thisArg const length = collection ? collection.length : 0 if (isArray(collection) && isFunction(predicate)) { let index = -1 while (++index < length) { if (predicate(collection[index])) { return true } } return false } return false } export default some
JavaScript
0.999246
@@ -378,25 +378,8 @@ %7D%0A - return false%0A %7D%0A
d67b5967a5ec833a928dd328b9e247cc2094b183
Scroll to top after hitting button
src/components/narrative/MobileNarrativeDisplay.js
src/components/narrative/MobileNarrativeDisplay.js
import React from "react"; import { connect } from "react-redux"; import queryString from "query-string"; import { changePage, EXPERIMENTAL_showMainDisplayMarkdown } from "../../actions/navigation"; import { TOGGLE_NARRATIVE } from "../../actions/types"; import { linkStyles, MobileBannerTop, MobileBannerBottom, MobileContentContainer, EndOfNarrative } from "./styles"; import Tree from "../tree"; import Map from "../map/map"; import MainDisplayMarkdown from "./MainDisplayMarkdown"; const BANNER_HEIGHT = 50; /** * A React component which takes up the entire screen and displays narratives in * "mobile" format. Instead of each narrative page displayed as narrative-text in * the sidebar & viz on the right hand section of the page, as we do for laptops * we render both in a "scrolly" fashion. Banners at the top/bottom of the page * allow you to navigate between pages. * * TODO: a lot of code is duplicated between this and `narratives/index.js` + * `main/index.js`. These should be brought out into functions. Same with * styling. * TODO: entropy / frequencies panels */ @connect((state) => ({ loaded: state.narrative.loaded, blocks: state.narrative.blocks, currentInFocusBlockIdx: state.narrative.blockIdx, panelsToDisplay: state.controls.panelsToDisplay })) class MobileNarrativeDisplay extends React.Component { constructor(props) { super(props); this.state = { showingEndOfNarrativePage: false, bannerHeight: BANNER_HEIGHT, contentHeight: window.innerHeight - 2*BANNER_HEIGHT }; this.exitNarrativeMode = () => { this.props.dispatch({type: TOGGLE_NARRATIVE, display: false}); }; this.goToNextPage = () => { if (this.state.showingEndOfNarrativePage) return; // no-op if (this.props.currentInFocusBlockIdx+1 === this.props.blocks.length) { this.setState({showingEndOfNarrativePage: true}); return; } this._goToPage(this.props.currentInFocusBlockIdx+1); }; this.goToPreviousPage = () => { if (this.props.currentInFocusBlockIdx === 0) return; // no-op this._goToPage(this.props.currentInFocusBlockIdx-1); }; this._goToPage = (idx) => { // TODO: this `if` statement should be moved to the `changePage` function or similar if (this.props.blocks[idx] && this.props.blocks[idx].mainDisplayMarkdown) { this.props.dispatch(EXPERIMENTAL_showMainDisplayMarkdown({ query: queryString.parse(this.props.blocks[idx].query), queryToDisplay: {n: idx} })); return; } this.props.dispatch(changePage({ changeDataset: false, query: queryString.parse(this.props.blocks[idx].query), queryToDisplay: {n: idx}, push: true })); }; // TODO: bind down & up arrows (is this ok since we also have scollable content?) } pageNarrativeContent() { if (this.props.blocks[this.props.currentInFocusBlockIdx].mainDisplayMarkdown) { /* don't display normal narrative content if the block defines `mainDisplayMarkdown` */ return null; } const block = this.props.blocks[this.props.currentInFocusBlockIdx]; return ( <div id={`MobileNarrativeBlock_${this.props.currentInFocusBlockIdx}`} key={block.__html} style={{ padding: "10px 20px", height: "inherit", overflow: "hidden" }} dangerouslySetInnerHTML={block} /> ); } renderMainMarkdown() { if (this.props.panelsToDisplay.includes("EXPERIMENTAL_MainDisplayMarkdown")) { return <MainDisplayMarkdown width={window.innerWidth}/>; } return null; } renderVizCards(height) { if (this.props.blocks[this.props.currentInFocusBlockIdx].mainDisplayMarkdown) { /* don't display normal narrative content if the block defines `mainDisplayMarkdown` */ return null; } if (this.props.currentInFocusBlockIdx === 0) { /* don't display viz panels for intro page */ return null; } const width = window.innerWidth - 50; // TODO return ( <> {this.props.panelsToDisplay.includes("tree") ? <Tree width={width} height={height} /> : null} {this.props.panelsToDisplay.includes("map") ? <Map width={width} height={height} justGotNewDatasetRenderNewMap={false} /> : null} </> ); } renderEndOfNarrative() { return ( <> <this.PreviousButton> Previous </this.PreviousButton> <MobileContentContainer height={this.state.contentHeight+this.state.bannerHeight}> <EndOfNarrative> <h1>End of Narrative</h1> <a style={{...linkStyles}} onClick={() => this._goToPage(0)} > Jump to the beginning </a> <br /> <a style={{...linkStyles}} onClick={this.exitNarrativeMode} > Leave the narrative & explore the data yourself </a> </EndOfNarrative> </MobileContentContainer> </> ); } renderStartOfNarrative() { return ( <> <MobileContentContainer height={this.state.contentHeight + this.state.bannerHeight}> {this.pageNarrativeContent()} {this.renderVizCards(this.state.contentHeight)} {this.renderMainMarkdown()} </MobileContentContainer> <this.NextButton> Next </this.NextButton> </> ); } renderMiddleOfNarrative() { return ( <> <this.PreviousButton> Previous </this.PreviousButton> <MobileContentContainer height={this.state.contentHeight}> {this.pageNarrativeContent()} {this.renderVizCards(this.state.contentHeight)} {this.renderMainMarkdown()} </MobileContentContainer> <this.NextButton> Next </this.NextButton> </> ); } NextButton = (props) => ( <MobileBannerBottom height={this.state.bannerHeight} onClick={this.goToNextPage} > {props.children} </MobileBannerBottom> ) PreviousButton = (props) => ( <MobileBannerTop height={this.state.bannerHeight} onClick={this.goToPreviousPage} > {props.children} </MobileBannerTop> ) render() { if (this.state.showingEndOfNarrativePage) { return this.renderEndOfNarrative(); } else if (this.props.currentInFocusBlockIdx === 0) { return this.renderStartOfNarrative(); } return this.renderMiddleOfNarrative(); } } export default MobileNarrativeDisplay;
JavaScript
0.998932
@@ -516,16 +516,117 @@ T = 50;%0A +%0Aconst scrollToTop = () =%3E %7B%0A document.getElementById('MobileNarrativeBlock').scrollIntoView();%0A%7D;%0A%0A /**%0A * A @@ -2861,24 +2861,46 @@ e%0A %7D)); +%0A%0A scrollToTop(); %0A %7D;%0A
d0181114bf8572b5152743e4d032865475dce9dd
Optimize startsWith algorithm in HeaderCtrl
app/scripts/controllers/header-controller.js
app/scripts/controllers/header-controller.js
'use strict'; /** * @ngdoc function * @name otaniemi3dApp.controller:HeaderCtrl * @description * # HeaderCtrl * Controller of the otaniemi3dApp */ angular.module('otaniemi3dApp') .controller('HeaderCtrl', function ($scope, $location, $rootScope) { // Check if current URL-location matches the highlighted item $scope.isActive = function (viewLocation) { //startsWith() return $location.path().indexOf(viewLocation) === 0; }; $scope.isCollapsed = true; $scope.$on('$routeChangeSuccess', function () { $rootScope.fullscreen = false; }); });
JavaScript
0
@@ -418,17 +418,21 @@ .path(). -i +lastI ndexOf(v @@ -442,16 +442,19 @@ Location +, 0 ) === 0;
766f788534822d52fea329b0ad8a89650dddce4b
Drop unnecessary dataType check.
js/Column.js
js/Column.js
/*eslint-env browser */ /*globals require: false, module: false */ 'use strict'; var React = require('react'); var _ = require('./underscore_ext'); var MenuItem = require('react-bootstrap/lib/MenuItem'); var SplitButton = require('react-bootstrap/lib/SplitButton'); var Resizable = require('react-resizable').Resizable; var DefaultTextInput = require('./DefaultTextInput'); var {RefGeneAnnotation} = require('./refGeneExons'); var xenaQuery = require('./xenaQuery'); // XXX move this? function download([fields, rows]) { var txt = _.map([fields].concat(rows), row => row.join('\t')).join('\n'); // use blob for bug in chrome: https://code.google.com/p/chromium/issues/detail?id=373182 var url = URL.createObjectURL(new Blob([txt], { type: 'text/tsv' })); var a = document.createElement('a'); var filename = 'xenaDownload.tsv'; _.extend(a, { id: filename, download: filename, href: url }); document.body.appendChild(a); a.click(); document.body.removeChild(a); } // For geneProbesMatrix we will average across probes to compute KM. For // other types, we can't support multiple fields. This should really be // in a prop set by the column, or in a multimethod. Having this here is bad. function disableKM(column, hasSurvival) { if (!hasSurvival) { return [true, 'No survival data for cohort']; } if (column.fields.length > 1 && column.dataType !== 'geneProbesMatrix') { return [true, 'Unsupported for multiple genes/ids']; } return [false, '']; } var ResizeOverlay = React.createClass({ getInitialState: () => ({zooming: false}), onResizeStart: function () { var {width, height} = this.props; this.setState({zooming: true, zoomSize: {width, height}}); }, onResize: function (ev, {size}) { this.setState({zoomSize: size}); }, onResizeStop: function (...args) { var {onResizeStop} = this.props; this.setState({zooming: false}); if (onResizeStop) { onResizeStop(...args); } }, render: function () { var {zooming, zoomSize} = this.state; // XXX This margin setting really belongs elsewhere. return ( <div className='resizeOverlay' style={{position: 'relative', marginBottom: '5px'}}> {zooming ? <div style={{ width: zoomSize.width, height: zoomSize.height, position: 'absolute', top: 0, left: 0, zIndex: 999, backgroundColor: 'rgba(0,0,0,0.4)' }} /> : null} <Resizable handleSize={[20, 20]} onResizeStop={this.onResizeStop} onResize={this.onResize} onResizeStart={this.onResizeStart} width={this.props.width} height={this.props.height}> <div style={{position: 'relative', cursor: 'none', zIndex: 0}}> {this.props.children} </div> </Resizable> </div> ); } }); var Column = React.createClass({ onResizeStop: function (ev, {size}) { this.props.callback(['resize', this.props.id, size]); }, onRemove: function () { this.props.callback(['remove', this.props.id]); }, onDownload: function () { download(this.props.download()); }, onAbout: function () { var {column} = this.props; var dsID = column.dsID; var [host, dataset] = xenaQuery.parse_host(dsID); var url = `../datapages/?dataset=${encodeURIComponent(dataset)}&host=${encodeURIComponent(host)}`; window.open(url); }, onViz: function () { this.props.onViz(this.props.id); }, onKm: function () { let {callback, id} = this.props; callback(['km-open', id]); }, render: function () { var {id, callback, plot, legend, column, zoom, menu, data, hasSurvival} = this.props, {width, columnLabel, fieldLabel} = column, [kmDisabled, kmTitle] = disableKM(column, hasSurvival), // move this to state to generalize to other annotations. doRefGene = column.dataType === 'mutationVector', // In FF spans don't appear as event targets. In Chrome, they do. // If we omit Sortable-handle here, Chrome will only catch events // in the button but not in the span. If we omit Sortable-handle // in SplitButton, FF will catch no events, since span doesn't // emit any. moveIcon = (<span className="glyphicon glyphicon-resize-horizontal Sortable-handle" aria-hidden="true"> </span>); return ( <div className='Column' style={{width: width, position: 'relative'}}> <SplitButton className='Sortable-handle' title={moveIcon} bsSize='xsmall'> {menu} {menu && <MenuItem divider />} <MenuItem title={kmTitle} onSelect={this.onKm} disabled={kmDisabled}>Kaplan Meier Plot</MenuItem> <MenuItem onSelect={this.onDownload}>Download</MenuItem> <MenuItem onSelect={this.onAbout}>About the Dataset</MenuItem> <MenuItem onSelect={this.onViz}>Viz Settings</MenuItem> <MenuItem onSelect={this.onRemove}>Remove</MenuItem> </SplitButton> <br/> <DefaultTextInput columnID={id} callback={callback} eventName='columnLabel' value={columnLabel} /> <DefaultTextInput columnID={id} callback={callback} eventName='fieldLabel' value={fieldLabel} /> <div style={{height: 20}}> {doRefGene && data ? <RefGeneAnnotation width={width} refGene={data.refGene[column.fields[0]]} layout={column.layout} position={{gene: column.fields[0]}}/> : null} </div> <ResizeOverlay onResizeStop={this.onResizeStop} width={width} height={zoom.height}> {plot} </ResizeOverlay> {legend} </div> ); } }); module.exports = Column;
JavaScript
0
@@ -1338,50 +1338,8 @@ %3E 1 - && column.dataType !== 'geneProbesMatrix' ) %7B%0A
ad5396938d329e79daa3195423ef627aff95fa05
Fix wildcard template inclusion from dynamic require
src/scripts/shell/content/content.controller.js
src/scripts/shell/content/content.controller.js
export default class ContentController { constructor(dimActivityTrackerService, dimState, ngDialog, $rootScope, loadingTracker, dimPlatformService, $interval, hotkeys, $timeout, dimStoreService, dimXurService, dimSettingsService, $window, $scope, $state, dimFeatureFlags, dimVendorService) { 'ngInject'; var vm = this; // Variables for templates that webpack does not automatically correct. vm.$DIM_VERSION = $DIM_VERSION; vm.$DIM_FLAVOR = $DIM_FLAVOR; vm.$DIM_CHANGELOG = $DIM_CHANGELOG; vm.loadingTracker = loadingTracker; vm.platforms = []; vm.platformChange = function platformChange(platform) { loadingTracker.addPromise(dimPlatformService.setActive(platform)); }; $scope.$on('dim-platforms-updated', function(e, args) { vm.platforms = args.platforms; }); $scope.$on('dim-active-platform-updated', function(e, args) { dimState.active = vm.currentPlatform = args.platform; }); loadingTracker.addPromise(dimPlatformService.getPlatforms()); vm.settings = dimSettingsService; $scope.$watch(() => { return vm.settings.itemSize; }, function(size) { document.querySelector('html').style.setProperty("--item-size", size + 'px'); }); $scope.$watch(() => { return vm.settings.charCol; }, function(cols) { document.querySelector('html').style.setProperty("--character-columns", cols); }); $scope.$watch(() => { return vm.settings.vaultMaxCol; }, function(cols) { document.querySelector('html').style.setProperty("--vault-max-columns", cols); }); vm.featureFlags = dimFeatureFlags; vm.vendorService = dimVendorService; hotkeys.add({ combo: ['f'], description: 'Start a search', callback: function(event) { $rootScope.$broadcast('dim-focus-filter-input'); event.preventDefault(); event.stopPropagation(); } }); hotkeys.add({ combo: ['esc'], allowIn: ['INPUT', 'SELECT', 'TEXTAREA'], callback: function() { $rootScope.$broadcast('dim-escape-filter-input'); } }); hotkeys.add({ combo: ['r'], description: "Refresh inventory", callback: function() { vm.refresh(); } }); hotkeys.add({ combo: ['i'], description: "Toggle showing full item details", callback: function() { $rootScope.$broadcast('dim-toggle-item-details'); } }); if (vm.featureFlags.tagsEnabled) { /* Add each hotkey manually until hotkeys can be translated. _.each(dimSettingsService.itemTags, (tag) => { if (tag.hotkey) { hotkeys.add({ combo: [tag.hotkey], description: "Mark item as '" + tag.label + "'", callback: function() { $rootScope.$broadcast('dim-item-tag', { tag: tag.type }); } }); } }); */ hotkeys.add({ combo: ['!'], description: "Mark item as 'Favorite'", callback: function() { $rootScope.$broadcast('dim-item-tag', { tag: 'favorite' }); } }); hotkeys.add({ combo: ['@'], description: "Mark item as 'Keep'", callback: function() { $rootScope.$broadcast('dim-item-tag', { tag: 'keep' }); } }); hotkeys.add({ combo: ['#'], description: "Mark item as 'Junk'", callback: function() { $rootScope.$broadcast('dim-item-tag', { tag: 'junk' }); } }); hotkeys.add({ combo: ['$'], description: "Mark item as 'Infuse'", callback: function() { $rootScope.$broadcast('dim-item-tag', { tag: 'infuse' }); } }); } hotkeys.add({ combo: ['x'], description: "Clear new items", callback: function() { dimStoreService.clearNewItems(); } }); hotkeys.add({ combo: ['ctrl+alt+shift+d'], callback: function() { dimFeatureFlags.debugMode = true; console.log("***** DIM DEBUG MODE ENABLED *****"); } }); /** * Show a popup dialog containing the given template. Its class * will be based on the name. */ function showPopupFunction(name) { var result; return function(e) { e.stopPropagation(); if (result) { result.close(); } else { ngDialog.closeAll(); result = ngDialog.open({ template: require('app/views/' + name + '.template.html'), className: name, appendClassName: 'modal-dialog' }); result.closePromise.then(function() { result = null; }); } }; } vm.showSetting = showPopupFunction('settings'); vm.showAbout = showPopupFunction('about'); vm.showSupport = showPopupFunction('support'); vm.showFilters = showPopupFunction('filters'); vm.showXur = showPopupFunction('xur'); vm.showMatsExchange = showPopupFunction('mats-exchange'); function toggleState(name) { return function(e) { $state.go($state.is(name) ? 'inventory' : name); }; } vm.toggleMinMax = toggleState('best'); vm.toggleVendors = toggleState('vendors'); vm.toggleRecordBooks = toggleState('record-books'); vm.xur = dimXurService; vm.refresh = function refresh() { loadingTracker.addPromise(dimStoreService.reloadStores()); }; } }
JavaScript
0
@@ -1,8 +1,388 @@ +import settingsTemplate from 'app/views/settings.template.html';%0Aimport aboutTemplate from 'app/views/about.template.html';%0Aimport supportTemplate from 'app/views/support.template.html';%0Aimport filtersTemplate from 'app/views/filters.template.html';%0Aimport xurTemplate from 'app/views/xur.template.html';%0Aimport matsExchangeTemplate from 'app/views/mats-exchange.template.html';%0A%0A export d @@ -4759,28 +4759,38 @@ unction(name +, template ) %7B%0A - var re @@ -5009,48 +5009,16 @@ te: -require('app/views/' + name + '. template .htm @@ -5017,15 +5017,8 @@ late -.html') ,%0A @@ -5267,16 +5267,34 @@ ettings' +, settingsTemplate );%0A v @@ -5332,16 +5332,31 @@ ('about' +, aboutTemplate );%0A v @@ -5398,16 +5398,33 @@ support' +, supportTemplate );%0A v @@ -5466,16 +5466,33 @@ filters' +, filtersTemplate );%0A v @@ -5526,16 +5526,29 @@ on('xur' +, xurTemplate );%0A v @@ -5601,16 +5601,38 @@ xchange' +, matsExchangeTemplate );%0A%0A
95711b3fc86b247383306c39ad42ebab520dec38
break up post into smaller functions.
src/server/routes/film.js
src/server/routes/film.js
const express = require('express'); const path = require('path'); const Film = require('../model/Film'); const filmData = require('../methods/getFilmData/FilmData'); const script = require('../methods/script'); const getBechdelResults = require('../methods/bechdel/getBechdelResults'); const multer = require('multer'); const router = express.Router(); const upload = multer({ dest: 'uploads/' }); const isNotCorrectFileFormat = file => { return path.extname(file.originalname) !== '.txt'; }; const fileWasNotUploadedCorrectly = file => { const exists = !file; return exists; }; const errorReadingScript = title => { const titleExists = !title; return titleExists; }; const handleError = (res, errMsg) => { console.error(errMsg); return res.status(500).send(errMsg); }; const filmFound = film => { return film.length > 0; }; const resetAll = scriptPath => { filmData.clear(); script.clearTemp(scriptPath); return true; }; const handleFilmFoundInDB = (res, film, scriptPath) => { script.clearTemp(scriptPath); const response = { ...film, success: true, cacheHit: true, }; return handleResponse(res, response); }; const handleGetAllFilms = async (req, res) => { try { const films = await Film.listAll(); if (!filmFound) { return handleError(res, 'No list of films returned from film.listAll()'); } return handleResponse(res, films); } catch (error) { return handleError(res, error); } }; const handleResponse = (res, data) => { return res.json(data); }; const handlePostFilm = async (req, res) => { const { file } = req; const scriptPath = file.path; if (fileWasNotUploadedCorrectly(file)) { return handleError(res, 'No script submitted, please try again'); } if (isNotCorrectFileFormat(file)) { return handleError(res, 'Please send a .txt script'); } try { const title = await script.readMovieTitle(scriptPath); if (errorReadingScript(title)) { return handleError(res, 'Error reading script'); } const film = await Film.findByTitle(title); if (filmFound(film)) { return handleFilmFoundInDB(res, film, scriptPath); } const bechdelResults = await getBechdelResults(title, scriptPath); const { actors, images, metadata } = filmData.getAllData(); const filmMetaData = { title, bechdelResults, actors, images, data: metadata, }; await Film.insertFilm(filmMetaData); const finalFilm = await Film.findByTitle(title); resetAll(scriptPath); const response = { ...finalFilm, title, success: true, cacheHit: false, }; return handleResponse(res, response); } catch (err) { resetAll(scriptPath); return handleError(res, 'Please try again'); } }; const handleDeleteFilm = async (req, res) => { try { const success = await Film.deleteFilm(req.params.id); if (success) { const response = { success: true }; return handleResponse(res, response); } return handleError(res, 'No movie found by that ID'); } catch (err) { return handleError(res, err); } }; const handleGetFilm = async (req, res) => { try { const film = await Film.findByID(req.params.id); if (!film) { return handleError(res, 'No movie found by that ID'); } return handleResponse(res, film); } catch (err) { return handleError(res, err); } }; /* * FILM ROUTES */ router .route('/') .get(handleGetAllFilms) .post(upload.single('script'), handlePostFilm); router .route('/:id') .get(handleGetFilm) .delete(handleDeleteFilm); module.exports = router;
JavaScript
0
@@ -1436,378 +1436,52 @@ nst -handleResponse = (res, data) =%3E %7B%0A%09return res.json(data);%0A%7D;%0A%0Aconst handlePostFilm = async (req, res) =%3E %7B%0A%09const %7B file %7D = req;%0A%09const scriptPath = file.path;%0A%0A%09if (fileWasNotUploadedCorrectly(file)) %7B%0A%09%09return handleError +processScript = async (res, - 'No script - submitted, please try again');%0A%09%7D%0A%09if (isNotCorrectFileFormat(file)) %7B%0A%09%09return handleError(res, 'Please send a .txt script');%0A%09%7D +Path) =%3E %7B %0A%09tr @@ -2327,32 +2327,446 @@ again');%0A%09%7D%0A%7D;%0A%0A +const handleResponse = (res, data) =%3E %7B%0A%09return res.json(data);%0A%7D;%0A%0Aconst handlePostFilm = async (req, res) =%3E %7B%0A%09const %7B file %7D = req;%0A%09const scriptPath = file.path;%0A%0A%09if (fileWasNotUploadedCorrectly(file)) %7B%0A%09%09return handleError(res, 'No script submitted, please try again');%0A%09%7D%0A%09if (isNotCorrectFileFormat(file)) %7B%0A%09%09return handleError(res, 'Please send a .txt script');%0A%09%7D%0A%09processScript(res, scriptPath);%0A%7D;%0A%0A const handleDele
81020cfce422a230b75b3c8e9371a5cae925fbaa
Connect behaviour : remove state, use forceUpdate
src/behaviours/store/connect.js
src/behaviours/store/connect.js
import {isArray, isFunction} from 'lodash/lang'; import {capitalize} from 'lodash/string' import {keys} from 'lodash/object'; import React, {Component} from 'react'; // - Provide the component // - Provide the store configuration `[{store: yourStore, properties: ['property1', 'property2']}]` // - Provide a function to read state from your store export default function connectToStores(storesConfiguration, getState) { // Validate the stores object if (!isArray(storesConfiguration)) { throw new Error('connectToStores: you need to provide an array of store config.'); } // Validate . if (!isFunction(getState)) { throw new Error('connectToStores: you need to provide function to read state from store.'); } // Return a wrapper function around the component return function connectComponent(DecoratedComponent) { // Save the display name for later const displayName = DecoratedComponent.displayName || 'Component'; // The goal of this class is to connect a component to a list of stores with properties. class StoreConnector extends Component { constructor(props) { super(props); //Build the initial state from props. this.state = getState(props); this._isMounted = false; } // When the component will mount, we listen to all stores changes. // When a change occurs the state is read again from the state. componentWillMount() { storesConfiguration.forEach(storeConf => { const {properties, store} = storeConf; properties.forEach((property) => { if (!store || !store.definition || !store.definition[property]) { console.warn(` StoreConnector ${displayName}: You add a property : ${property} in your store configuration which is not in your definition : ${keys(store.definition)} `); } const capitalizedProperty = capitalize(property); storeConf.store[`add${capitalizedProperty}ChangeListener`](this.handleStoresChanged); storeConf.store[`add${capitalizedProperty}ErrorListener`](this.handleStoresChanged); }); }); } // When a component will receive a new props. componentWillReceiveProps(nextProps) { this.updateState(nextProps); } // Component unmount. componentWillUnmount() { this._isMounted = false; storesConfiguration.forEach(storeConf => { const {properties, store} = storeConf; properties.forEach((property) => { const capitalizedProperty = capitalize(property); store[`remove${capitalizedProperty}ChangeListener`](this.handleStoresChanged); store[`remove${capitalizedProperty}ErrorListener`](this.handleStoresChanged); }); }); } componentDidMount() { this._isMounted = true; this.updateState(this.props); } updateState(props) { if (this._isMounted) { this.setState(getState(props)); } } //Handle the store changes handleStoresChanged = () => { this.updateState(this.props); }; // Render the component with only props, some from the real props some from the state render() { const {props, state} = this; return ( <DecoratedComponent {...props} {...state} /> ); } } StoreConnector.displayName = `${displayName}Connected`; return StoreConnector; }; } // Add a function to connect a store to a component . // All the store properties values will be provided to the component as props. // This could be use as an ES7 annotation or as a function. // ### ES6 version // ```jsx // store // const newStore = new CoreStore({definition: {name: 'name', email: 'email'}}); //Component // const Component = props => <div>{JSON.stringify(props)}</div>; // create a connector function // const connector = storeConnectBehaviour( // [{store: newStore, properties: ['name', 'email']}], // (props) => {return newStore.getValue()} // ); // Component connected to the store // const ConnectedComponent = connector(Component); // ``` // ### ES7 version // ```jsx // Class version // @connect( [{store: newStore, properties: ['name', 'email']}],(props) => newStore.getValue()) // class YourComponent extends Component{ // render(){ // return <div>{JSON.stringify(props)}</div>; // } // } // ```
JavaScript
0
@@ -1,16 +1,17 @@ import %7B + isArray, @@ -21,16 +21,17 @@ Function + %7D from ' @@ -52,16 +52,17 @@ import %7B + capitali @@ -63,16 +63,17 @@ pitalize + %7D from ' @@ -95,20 +95,22 @@ import %7B + keys + %7D from ' @@ -140,16 +140,17 @@ React, %7B + Componen @@ -150,16 +150,17 @@ omponent + %7D from ' @@ -751,17 +751,16 @@ );%0A %7D - %0A // @@ -1215,131 +1215,70 @@ -//Build the initial state from props.%0A this.state = getState(props);%0A this._isMounted = false +this.handleStoresChanged = this.handleStoresChanged.bind(this) ;%0A @@ -1558,32 +1558,33 @@ const %7B + properties, stor @@ -1576,32 +1576,33 @@ roperties, store + %7D = storeConf;%0A @@ -2422,177 +2422,8 @@ %7D%0A%0A - // When a component will receive a new props.%0A componentWillReceiveProps(nextProps) %7B%0A this.updateState(nextProps);%0A %7D%0A%0A @@ -2612,24 +2612,25 @@ const %7B + properties, @@ -2634,16 +2634,17 @@ s, store + %7D = stor @@ -3047,301 +3047,8 @@ %7D%0A%0A - componentDidMount() %7B%0A this._isMounted = true;%0A this.updateState(this.props);%0A %7D%0A%0A updateState(props) %7B %0A if (this._isMounted) %7B%0A this.setState(getState(props));%0A %7D%0A %7D%0A%0A @@ -3117,16 +3117,10 @@ nged - = () =%3E +() %7B%0A @@ -3143,30 +3143,20 @@ his. -updateState(this.props +forceUpdate( );%0A @@ -3295,53 +3295,8 @@ ) %7B%0A - const %7Bprops, state%7D = this;%0A @@ -3384,16 +3384,21 @@ %7B... +this. props%7D%0A @@ -3424,21 +3424,37 @@ %7B... -state +getState(this.props) %7D%0A
795d9019504759733dc0c435b6c146874e8badc9
revert value for the fieldByFormat.v2 (set the "deps" value again)
packages/decl/lib/stringify.js
packages/decl/lib/stringify.js
'use strict'; const assert = require('assert'); const JSON5 = require('json5'); const format = require('./format'); const DEFAULTS = { exportType: 'json', space: 4 }; // different format exports declaration in different fields // and this specific point is used for detecting input format // if it isn't passed. This logic performed by detect method // which called from parse method. const fieldByFormat = { v1: 'blocks', enb: 'deps', v2: '' }; const generators = { json5: (obj, space) => JSON5.stringify(obj, null, space), json: (obj, space) => JSON.stringify(obj, null, space), commonjs: (obj, space) => `module.exports = ${JSON5.stringify(obj, null, space)};\n`, es2015: (obj, space) => `export default ${JSON5.stringify(obj, null, space)};\n` }; // Aliases generators.es6 = generators.es2015; generators.cjs = generators.commonjs; /** * Create string representation of declaration * * @param {BemCell|BemCell[]} decl - source declaration * @param {Object} opts - additional options * @param {String} opts.format - format of declaration (v1, v2, enb) * @param {String} [opts.exportType=json5] - defines how to wrap result (commonjs, json5, json, es6|es2015) * @param {String|Number} [opts.space] - number of space characters or string to use as a white space * @returns {String} */ module.exports = function (decl, opts) { const options = Object.assign({}, DEFAULTS, opts); assert(options.format, 'You must declare target format'); assert(fieldByFormat.hasOwnProperty(options.format), 'Specified format isn\'t supported'); assert(generators.hasOwnProperty(options.exportType), 'Specified export type isn\'t supported'); Array.isArray(decl) || (decl = [decl]); const formatedDecl = format(decl, { format: options.format }); const field = fieldByFormat[options.format]; let stringifiedObj = { format: options.format }; if (field) { stringifiedObj[field] = formatedDecl; } else { stringifiedObj = formatedDecl; } return generators[options.exportType](stringifiedObj, options.space); };
JavaScript
0
@@ -450,16 +450,20 @@ v2: ' +deps '%0A%7D;%0A%0Aco
bcd38a4c67ddb54069da16344da5571e6eb12447
Fix lint error
tests/unit/move-test.js
tests/unit/move-test.js
import { run } from '@ember/runloop'; import { module, test } from 'qunit'; import Sprite from 'ember-animated/-private/sprite'; import { Move } from 'ember-animated/motions/move'; import { equalBounds, approxEqualPixels, visuallyConstant, } from '../helpers/assertions'; import { MotionTester, TimeControl } from 'ember-animated/test-support'; let tester, environment, offsetParent, target, innerContent, time; module('Unit | Move', function(hooks) { hooks.beforeEach(function(assert) { assert.equalBounds = equalBounds; assert.approxEqualPixels = approxEqualPixels; assert.visuallyConstant = visuallyConstant; time = new TimeControl(); tester = MotionTester.create({ motion: Move, }); let fixture = document.querySelector('#qunit-fixture'); fixture.innerHTML = ` <div class="environment"> <div class="offset-parent"> <div class="sibling"></div> <div class="target"> <div class="inner-content"></div> </div> <div class="sibling"></div> </div> </div> `; environment = fixture.querySelector('.environment'); offsetParent = fixture.querySelector('.offset-parent'); target = fixture.querySelector('.target'); innerContent = fixture.querySelector('.inner-content'); environment.style.width = '600px'; offsetParent.style.position = 'relative'; innerContent.style.width = '400px'; }); hooks.afterEach(function() { time.finished(); }); test('simple motion', function(assert) { assert.expect(2); let p = Sprite.offsetParentStartingAt(target); p.measureFinalBounds(); let s = Sprite.positionedStartingAt(target, p); let startBounds = s.element.getBoundingClientRect(); target.style.left = '300px'; target.style.top = '400px'; let endBounds = s.element.getBoundingClientRect(); s.measureFinalBounds(); s.lock(); tester.beforeAnimation = () => { assert.equalBounds(s.element.getBoundingClientRect(), startBounds); }; tester.afterAnimation = () => { assert.equalBounds(s.element.getBoundingClientRect(), endBounds); }; let done = assert.async(); run(() => { tester.run(s, { duration: 60 }).then(done, done); time.advance(60); }); }); test('simple motion, interrupted', function(assert) { target.style['margin-left'] = '0px'; target.style['margin-top'] = '0px'; target.style.position = 'relative'; let p = Sprite.offsetParentStartingAt(target); p.measureFinalBounds(); let s = Sprite.positionedStartingAt(target, p); target.style.left = '300px'; target.style.top = '400px'; s.measureFinalBounds(); s.lock(); run(() => { tester.run(s, { duration: 1000 }); }); return time.advance(500).then(() => { assert.approxEqualPixels( s.getCurrentBounds().top, s.initialBounds.top + 200, 'top', ); assert.approxEqualPixels( s.getCurrentBounds().left, s.initialBounds.left + 150, 'left', ); let newSprite = Sprite.positionedStartingAt(target, p); newSprite.lock(); target.style.left = '400px'; target.style.top = '500px'; newSprite.unlock(); newSprite.measureFinalBounds(); newSprite.lock(); run(() => { tester.run(newSprite, { duration: 1000 }); }); assert.approxEqualPixels( newSprite.getCurrentBounds().top, s.initialBounds.top + 200, 'top continuity', ); assert.approxEqualPixels( newSprite.getCurrentBounds().left, s.initialBounds.left + 150, 'left continuity', ); return time.advance(1005).then(() => { assert.visuallyConstant(target, () => { newSprite.unlock(); }); }); }); }); test('interrupting with same destination does not extend animation time', function(assert) { let p = Sprite.offsetParentStartingAt(target); p.measureFinalBounds(); let s = Sprite.positionedStartingAt(target, p); s.lock(); document.querySelector('#qunit-fixture .sibling').style.height = '50px'; s.unlock(); s.measureFinalBounds(); s.lock(); run(() => { tester.run(s, { duration: 1000 }); }); return time.advance(500).then(() => { assert.approxEqualPixels( s.getCurrentBounds().top, s.initialBounds.top + 25, 'top', ); let newSprite = Sprite.positionedStartingAt(target, p); newSprite.lock(); newSprite.unlock(); newSprite.measureFinalBounds(); newSprite.lock(); run(() => { tester.run(newSprite, { duration: 1000 }); }); return time.advance(501).then(() => { assert.ok(!tester.get('isAnimating'), 'should be finished by now'); }); }); }); test('overshooting motion', async function(assert) { target.style['margin-left'] = '0px'; target.style['margin-top'] = '0px'; target.style.position = 'relative'; let p = Sprite.offsetParentStartingAt(target); p.measureFinalBounds(); let s = Sprite.positionedStartingAt(target, p); target.style.left = '400px'; s.measureFinalBounds(); s.lock(); let motion = new Move(s, { easing: (v) => v < 0.5 ? -v : 2 - v }); tester.run(motion, { duration: 400 }); await time.advance(100); assert.equal(s.getCurrentBounds().left, -100); await time.advance(200); assert.equal(s.getCurrentBounds().left, 500); await time.advance(100); assert.equal(s.getCurrentBounds().left, 400); }); });
JavaScript
0.000035
@@ -5227,15 +5227,14 @@ ng: -(v) +v =%3E +( v %3C @@ -5249,16 +5249,18 @@ : 2 - v +), %0A %7D);
4f2a49335f3fc2d03e052c91746ec88eb750e3ba
Add docs
src/services/domMocker.js
src/services/domMocker.js
window.getJasmineRequireObj().domMocker = function () { var oldDocument, getElementById = function (parent, id) { var children = parent.childNodes, child, result, i; for (i = 0; i < children.length; i++) { child = children[i]; if (child.id === id) { return child; } result = getElementById.call(this, child, id); if (result) { return result; } } }, stubElement = function (el) { var original = el.addEventListener; el.events = {}; el.addEventListener = function (name, listener) { if (this.events[name]) { this.events[name].push(listener); } else { this.events[name] = [listener]; } original.call(this, name, listener); }; return el; }, isAlreadyMocked = function (el) { return el.events; }, processElement = function (el) { if (!isAlreadyMocked.call(this, el)) { return stubElement.call(this, el); } return el; }, getSingleElement = function (el) { return el ? processElement.call(this, el) : null; }, processElements = function (elements) { var i, length = elements.length; for (i = 0; i < length; i++) { processElement.call(this, elements[i]); } return elements; }; this.mockWith = function (dom) { var docCreateElementBackup = document.createElement; oldDocument = { getElementsByTagName: document.getElementsByTagName, getElementById: document.getElementById, querySelector: document.querySelector, querySelectorAll: document.querySelectorAll, getElementsByClassName: document.getElementsByClassName, addEventListener: document.addEventListener }; document.getElementsByTagName = function (tagName) { if (tagName.toLowerCase() === 'html') { // This array could lead to problems return processElements.call(this, [dom]); } return processElements.call(this, dom.getElementsByTagName(tagName)); }; document.getElementById = function (id) { return getSingleElement.call(this, getElementById.call(this, dom, id)); }; document.getElementsByClassName = function (className) { return processElements.call(this, dom.getElementsByClassName(className)); }; document.querySelector = function (selector) { return getSingleElement.call(this, dom.querySelector(selector)); }; document.querySelectorAll = function (selector) { return processElements.call(this, dom.querySelectorAll(selector)); }; processElement.call(this, document); document.createElement = function () { // when this method is spied in the specs there is a conflic because // the spies are set back after the virtual dom is set back // if (!oldDocument) { // this.createElement = docCreateElementBackup; // return this.createElement.apply(this, arguments); // } else { return processElement.call(this, docCreateElementBackup.apply(this, arguments)); //} }; }; this.unMock = function () { var method; for (method in oldDocument) { if (oldDocument.hasOwnProperty(method)) { document[method] = oldDocument[method]; } } delete document.events; }; };
JavaScript
0.000001
@@ -1,8 +1,81 @@ +/**%0A * Service to mock the document API%0A *%0A * @constructor domMocker%0A */%0A window.g @@ -1784,32 +1784,120 @@ ts;%0A %7D;%0A%0A + /**%0A * @param %7BHTMLElement%7D dom Virtual dom%0A * @memberof domMocker%0A */%0A this.mockWit @@ -3862,24 +3862,67 @@ %7D;%0A %7D;%0A%0A + /**%0A * @memberof domMocker%0A */%0A this.unM
50a6c1f907194606257e25fb54acbf3fdaf2e532
fix broken formatting
planet/js/StringHelper.js
planet/js/StringHelper.js
// Copyright (c) 2018 Euan Ong // // This program is free software; you can redistribute it and/or // modify it under the terms of the The GNU Affero General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // You should have received a copy of the GNU Affero General Public // License along with this library; if not, write to the Free Software // Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA function StringHelper(Planet) { //[id, string, property (if present)] // append to innerhtml this.strings = [ ["logo-container",_("Planet")], ["close-planet",_("Close Planet",_("data-tooltip")], ["planet-open-file",_("Open project from file",_("data-tooltip")], ["planet-new-project",_("New project",_("data-tooltip")], ["local-tab",_("Local")], ["global-tab",_("Global")], ["global-search",_("Search for a project",_("placeholder")], ["localtitle",_("My Projects")], ["publisher-ptitle",_("Publish Project")], ["publish-title-label",_("Project title")], ["publish-tags-label",_("Tags (max 5)")], ["publish-description-label",_("Description")], ["publisher-submit",_("Submit")], ["publisher-cancel",_("Cancel")], ["deleter-confirm",_("Delete \"<span id=\"deleter-title\"></span>\"?")], ["deleter-paragraph",_("Permanently delete project \"<span id=\"deleter-name\"></span>\"?")], ["deleter-button",_("Delete")], ["deleter-cancel",_("Cancel")], ["globaltitle",_("Explore Projects")], ["view-more-chips",_("View More")], ["option-recent",_("Most recent")], ["option-liked",_("Most liked")], ["option-downloaded",_("Most downloaded")], ["option-alphabetical",_("A-Z")], ["option-sort-by",_("Sort by")], ["load-more-projects",_("Load More Projects")], ["projectviewer-last-updated-heading",_("Last Updated")], ["projectviewer-date-heading",_("Creation Date")], ["projectviewer-downloads-heading",_("Number of Downloads:")], ["projectviewer-likes-heading",_("Number of Likes:")], ["projectviewer-tags-heading",_("Tags:")], ["projectviewer-description-heading",_("Description")], ["projectviewer-report-project",_("Report Project")], ["projectviewer-report-title",_("Report Project")], ["projectviewer-report-conduct",_("Report projects which violate the <a href=\"https://github.com/sugarlabs/sugar-docs/blob/master/CODE_OF_CONDUCT.md\" target=\"_blank\">Sugar Labs Code of Conduct</a>.")], ["projectviewer-report-reason",_("Reason for reporting project")], ["projectviewer-report-submit",_("Submit")], ["projectviewer-reportsubmit-title",_("Report Project")], ["projectviewer-report-close",_("Close")], ["projectviewer-download-file",_("Download as File")], ["projectviewer-open-mb",_("Open in Music Blocks")] ] this.init = function(){ for (var i = 0; i<this.strings.length; i++){ var obj = this.strings[i]; var elem = document.getElementById(obj[0]); if (this.strings[i].length==3){ elem.setAttribute(obj[2],obj[1]); } else { elem.innerHTML+=obj[1]; } } }; };
JavaScript
0.000041
@@ -706,19 +706,18 @@ Planet%22 +) , -_( %22data-to @@ -714,33 +714,32 @@ ),%22data-tooltip%22 -) %5D,%0A %5B%22pla @@ -779,19 +779,18 @@ om file%22 +) , -_( %22data-to @@ -787,33 +787,32 @@ ),%22data-tooltip%22 -) %5D,%0A %5B%22pla @@ -843,19 +843,18 @@ project%22 +) , -_( %22data-to @@ -859,17 +859,16 @@ tooltip%22 -) %5D,%0A @@ -981,19 +981,18 @@ project%22 +) , -_( %22placeho @@ -996,17 +996,16 @@ eholder%22 -) %5D,%0A
29fabb5e8bb9327514cd1f56c2aea84c25c067f8
fix depreciated geo url
src/belt.js
src/belt.js
const request = require('request'); const config = require('./config'); const db = require('./db'); const { promisify } = require('util'); const reqAsync = promisify(request); const path = require('path'); const debug = require('./debug'); const REGEX_RAW_GIST_URL = /^https?:\/\/gist\.githubusercontent\.com\/(.+?\/[0-9a-f]+\/raw\/(?:[0-9a-f]+\/)?.+\..+)$/i; const CDN_URL = 'https://cdn.staticaly.com/gist'; const GIT_API_URL = 'https://api.github.com/'; const REGISTRY_URL = 'https://registry.npmjs.org/'; const GEO_IP = 'http://freegeoip.net/json/'; const pkgApi = async (repo, pkg) => { try { const res = await reqAsync(`https://umdfied-cdn.herokuapp.com/standalone/${repo}`); if (res.statusCode === 200 && res.body) { const cdnlink = await createGist(pkg, res.body); return cdnlink; } return false; } catch (e) { console.error(e.stack || e.message) return false; } }; const validatePackage = async (pkg, ver) => { try { let payload = false; const isOrg = /^@/.test(pkg); pkg = encodeURIComponent(pkg); if (!isOrg) { ver = !ver ? 'latest' : ver; const res = await reqAsync(`${REGISTRY_URL + pkg}/${ver}`); const body = JSON.parse(res.body); if (res.statusCode === 200 && body) { payload = { name: body.name, version: body.version }; } }else{ if(ver && !/^v/.test(ver) && ver !== 'latest') { ver = `v${ver}` }else if (ver && ver === 'latest') { ver = '' } const res = await reqAsync(`${REGISTRY_URL + pkg}/${ver}`); const body = JSON.parse(res.body); if (res.statusCode === 200 && body) { payload = { name: body.name, version: ver ? body.version: body['dist-tags'].latest }; } } return payload; } catch (e) { console.error(e.stack || e.message) return false; } }; const createGist = async (pkg, content) => { try { const data = { 'description': `Umdfied build of ${pkg}`, 'public': true, 'files': {} }; pkg = pkg.replace(/@/,'').replace(/\//,'-') const fname = `${pkg}.min.js`; data.files[fname] = { content }; const reqOpts = { method: 'POST', url: '/gists', headers: { 'Authorization': `token ${config.GIT_TOKEN}`, 'User-Agent': 'Umdfied-App' }, baseUrl: GIT_API_URL, json: true, body: data }; const res = await reqAsync(reqOpts); const body = res.body; debug(body, 'createGist'); let cdnurl = body.files[fname].raw_url.replace(REGEX_RAW_GIST_URL, `${CDN_URL}/$1`); return cdnurl; } catch (e) { console.log(e); } }; const getCountry = async ip => { try { const res = await reqAsync({ url: GEO_IP + ip, json: true }); const country = res.body.country_name; if (country) { return country; } return 'anonymous'; } catch (e) { return 'anonymous'; } }; const normalizeIp = ip => ip.replace(/^::ffff:/i, ''); const updateCdn = function(cdnurl) { return cdnurl.replace(/(cdn\.rawgit\.com|gistcdn\.githack\.com)/, 'cdn.staticaly.com/gist') } exports.umdfied = async (pkg, ver, ip) => { try { ip = normalizeIp(ip); const usrCountry = await getCountry(ip); debug(usrCountry, 'usrCountry'); await db.saveUsrInfo({ ip, country: usrCountry }); console.log('Checking DB', 'db'); const repoInfo = await validatePackage(pkg, ver); if (!repoInfo) { return false; } let fromDb = await db.getPkg(repoInfo.name, repoInfo.version); if (fromDb && (fromDb.cdn.includes('rawgit.com') || fromDb.cdn.includes('githack.com'))) { fromDb = await db.updatePkg(repoInfo.name, repoInfo.version, updateCdn(fromDb.cdn)); } if (fromDb) { return { gitCdn: fromDb.cdn, semver: fromDb.version }; } const repo = `${encodeURIComponent(repoInfo.name)}@${repoInfo.version}`; console.log(repo, 'repo'); const gitCdn = await pkgApi(repo, pkg); console.log(gitCdn, 'gitCdn'); if (!gitCdn) { return false; } await db.savePkg(repoInfo.name, repoInfo.version, gitCdn); return { gitCdn, semver: repoInfo.version }; } catch (e) { console.error(`${e.message}\n${e.stack}`, 'umdfied Error'); return false; } };
JavaScript
0
@@ -526,30 +526,38 @@ http +s :// -freegeoip.net/json/ +api.ipgeolocation.io/ipgeo ';%0A%0A @@ -2682,32 +2682,113 @@ ip =%3E %7B%0A try %7B%0A + const geourl = %60$%7BGEO_IP%7D?apiKey=$%7Bprocess.env.GEO_KEY%7D&ip=$%7Bip%7D&fields=geo%60%0A const res = @@ -2813,19 +2813,14 @@ rl: -GEO_IP + ip +geourl , js
8b89a3cfbf419866673067b647eca69c06e3a737
update Tbody
src/_Tbody/Tbody.js
src/_Tbody/Tbody.js
/** * @file Tbody component * @author liangxiaojun([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; // Components import Tr from '../_Tr'; // Statics import HorizontalAlign from '../_statics/HorizontalAlign'; import SelectMode from '../_statics/SelectMode'; import SelectAllMode from '../_statics/SelectAllMode'; import SortingType from '../_statics/SortingType'; // Vendors import Util from '../_vendors/Util'; class Tbody extends Component { static Align = HorizontalAlign; static SelectMode = SelectMode; static SelectAllMode = SelectAllMode; static SortingType = SortingType; constructor(props, ...restArgs) { super(props, ...restArgs); } isItemChecked = rowData => { const {selectMode, idProp, value} = this.props; if (!rowData || !value || selectMode === SelectMode.NORMAL) { return false; } switch (selectMode) { case SelectMode.MULTI_SELECT: return value && value.findIndex(item => item[idProp] === rowData[idProp]) !== -1; case SelectMode.SINGLE_SELECT: return value[idProp] === rowData[idProp]; } }; handleTrMouseEnter = (e, rowIndex) => { const {onRowHover} = this.props; onRowHover && onRowHover(rowIndex); }; handleTrMouseLeave = (e, rowIndex) => { const {onRowHover} = this.props; onRowHover && onRowHover(null); }; render() { const { className, style, columns, data, startIndex, idProp, disabled, isMouseEventForbidden, // not passing down these props value, ...restProps } = this.props; return ( <tbody className={className} style={style}> { data && data.map((row, index) => row ? <Tr {...restProps} key={idProp && idProp in row ? row[idProp] : index} index={index} rowIndex={startIndex + index} columns={columns} data={row} tableData={data} isChecked={this.isItemChecked(row)} disabled={disabled || row.disabled} isMouseEventForbidden={isMouseEventForbidden} onMouseEnter={this.handleTrMouseEnter} onMouseLeave={this.handleTrMouseLeave}/> : null ) } </tbody> ); } } Tbody.propTypes = { className: PropTypes.string, style: PropTypes.object, /** * The select mode of table. */ selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)), /** * The select all mode of table, all or current page. */ selectAllMode: PropTypes.oneOf(Util.enumerateValue(SelectAllMode)), /** * Children passed into table header. */ columns: PropTypes.arrayOf(PropTypes.shape({ /** * fixed position of column ( 'left' / 'right' ). */ fixed: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * width of column. */ width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * minimum width of column. */ minWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * align of current column. */ align: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * no wrap of current column. */ noWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]), /** * The class name of header. */ headClassName: PropTypes.string, /** * Override the styles of header. */ headStyle: PropTypes.object, /** * align of table header cell */ headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * The render content in table head. * (1) callback: * function (tableData, colIndex) { * return colIndex; * } * * (2) others: * render whatever you pass */ headRenderer: PropTypes.any, /** * column span of table header. * (1) function callback: * function (tableData, colIndex) { * return null; * } * * (2) number: * render whatever you pass */ headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), /** * no wrap of table header. */ headNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]), /** * The class name of td. */ bodyClassName: PropTypes.string, /** * Override the styles of td. */ bodyStyle: PropTypes.object, /** * align of table body cell. */ bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * The render content in table body. * (1) callback: * function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) { * return rowData.id; * } * * (2) others: * render whatever you pass */ bodyRenderer: PropTypes.any, /** * column span of table body. * (1) function callback: * function (rowData, colIndex, rowIndex) { * return null; * } * * (2) number: * render whatever you pass */ bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), /** * no wrap of table body. */ bodyNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]), /** * The class name of footer. */ footClassName: PropTypes.string, /** * Override the styles of footer. */ footStyle: PropTypes.object, /** * align of table footer cell */ footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * The render content in table foot. * (1) callback: * function (tableData, colIndex) { * return colIndex; * } * * (2) others: * render whatever you pass */ footRenderer: PropTypes.any, /** * column span of table foot. * (1) function callback: * function (tableData, colIndex) { * return null; * } * * (2) number: * render whatever you pass */ footSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), /** * no wrap of table foot. */ footNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]), /** * If true,this column can be sorted. */ sortable: PropTypes.bool, /** * Sorting property. */ sortingProp: PropTypes.string, defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)) })).isRequired, data: PropTypes.array, value: PropTypes.array, hoverRowIndex: PropTypes.number, startIndex: PropTypes.number, idProp: PropTypes.string, disabled: PropTypes.bool, baseColIndex: PropTypes.number, expandRows: PropTypes.array, isMouseEventForbidden: PropTypes.bool, /** * sorting */ sorting: PropTypes.shape({ prop: PropTypes.string, type: PropTypes.oneOf(Util.enumerateValue(SortingType)) }), /** * callback */ onRowClick: PropTypes.func, onCellClick: PropTypes.func, onRowHover: PropTypes.func, onExpand: PropTypes.func, onCollapse: PropTypes.func }; Tbody.defaultProps = { selectMode: SelectMode.SINGLE_SELECT, startIndex: 0, idProp: 'id', disabled: false, baseColIndex: 0, expandRows: [], isMouseEventForbidden: false }; export default Tbody;
JavaScript
0.000001
@@ -1249,37 +1249,36 @@ eEnter = (e, row -Index +Data ) =%3E %7B%0A c @@ -1345,21 +1345,20 @@ over(row -Index +Data );%0A %7D @@ -1390,19 +1390,8 @@ = ( -e, rowIndex ) =%3E @@ -7709,21 +7709,16 @@ hoverRow -Index : PropTy @@ -7717,30 +7717,30 @@ : PropTypes. -number +object ,%0A startI
45e59032265587c79161e59333419ef34a6818b1
fix uninitialised state and eventlistener leak
src/components/views/rooms/RoomUpgradeWarningBar.js
src/components/views/rooms/RoomUpgradeWarningBar.js
/* Copyright 2018 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import React from 'react'; import PropTypes from 'prop-types'; import * as sdk from '../../../index'; import Modal from '../../../Modal'; import { _t } from '../../../languageHandler'; import {MatrixClientPeg} from "../../../MatrixClientPeg"; export default class RoomUpgradeWarningBar extends React.Component { static propTypes = { room: PropTypes.object.isRequired, recommendation: PropTypes.object.isRequired, }; componentDidMount() { const tombstone = this.props.room.currentState.getStateEvents("m.room.tombstone", ""); this.setState({upgraded: tombstone && tombstone.getContent().replacement_room}); MatrixClientPeg.get().on("RoomState.events", this._onStateEvents); } _onStateEvents = (event, state) => { if (!this.props.room || event.getRoomId() !== this.props.room.roomId) { return; } if (event.getType() !== "m.room.tombstone") return; const tombstone = this.props.room.currentState.getStateEvents("m.room.tombstone", ""); this.setState({upgraded: tombstone && tombstone.getContent().replacement_room}); }; onUpgradeClick = () => { const RoomUpgradeDialog = sdk.getComponent('dialogs.RoomUpgradeDialog'); Modal.createTrackedDialog('Upgrade Room Version', '', RoomUpgradeDialog, {room: this.props.room}); }; render() { const AccessibleButton = sdk.getComponent('elements.AccessibleButton'); let doUpgradeWarnings = ( <div> <div className="mx_RoomUpgradeWarningBar_body"> <p> {_t( "Upgrading this room will shut down the current instance of the room and create " + "an upgraded room with the same name.", )} </p> <p> {_t( "<b>Warning</b>: Upgrading a room will <i>not automatically migrate room members " + "to the new version of the room.</i> We'll post a link to the new room in the old " + "version of the room - room members will have to click this link to join the new room.", {}, { "b": (sub) => <b>{sub}</b>, "i": (sub) => <i>{sub}</i>, }, )} </p> </div> <p className="mx_RoomUpgradeWarningBar_upgradelink"> <AccessibleButton onClick={this.onUpgradeClick}> {_t("Upgrade this room to the recommended room version")} </AccessibleButton> </p> </div> ); if (this.state.upgraded) { doUpgradeWarnings = ( <div className="mx_RoomUpgradeWarningBar_body"> <p> {_t("This room has already been upgraded.")} </p> </div> ); } return ( <div className="mx_RoomUpgradeWarningBar"> <div className="mx_RoomUpgradeWarningBar_wrapped"> <div className="mx_RoomUpgradeWarningBar_header"> {_t( "This room is running room version <roomVersion />, which this homeserver has " + "marked as <i>unstable</i>.", {}, { "roomVersion": () => <code>{this.props.room.getVersion()}</code>, "i": (sub) => <i>{sub}</i>, }, )} </div> {doUpgradeWarnings} <div className="mx_RoomUpgradeWarningBar_small"> {_t("Only room administrators will see this warning")} </div> </div> </div> ); } }
JavaScript
0.000001
@@ -10,16 +10,21 @@ ght 2018 +-2020 New Vec @@ -999,24 +999,103 @@ ed,%0A %7D;%0A%0A + constructor(props) %7B%0A super(props);%0A this.state = %7B%7D;%0A %7D%0A%0A componen @@ -1371,24 +1371,205 @@ ts);%0A %7D%0A%0A + componentWillUnmount() %7B%0A const cli = MatrixClientPeg.get();%0A if (cli) %7B%0A cli.removeListener(%22RoomState.events%22, this._onStateEvents);%0A %7D%0A %7D%0A%0A _onState
0820ad27b0f7b6a29614f03f2570c99e50a4f5a7
Package settings now read from package file in parent folder
plugin.js
plugin.js
var through = require('through2') var gutil = require('gulp-util') var superagent = require('superagent') var extend = require('extend') var PluginError = gutil.PluginError var defaultConfig = { port: 23956 } function gulpVSDTE(config) { var options = extend({}, defaultConfig, config || {}); var files = [] var endpoint = 'http://localhost:' + options.port + '/project/files' return through.obj(function (file, enc, cb) { // Record the path for sending to EnvDTE files.push(file.path) // Spit the file back into the pipeline without modification this.push(file) cb() }, function (cb) { superagent.put(endpoint) .send(JSON.stringify(files)) .set('Content-Type', 'application/json') .end(function (err, res) { if (err) gutil.log(err) else gutil.log(res.text) cb() }) }) } module.exports = gulpVSDTE;
JavaScript
0
@@ -130,16 +130,53 @@ extend') +%0Avar pkg = require('../package.json') %0A%0Avar Pl @@ -226,16 +226,23 @@ onfig = +extend( %7B%0A po @@ -252,16 +252,39 @@ 23956%0A%7D +, pkg.notifyDte %7C%7C %7B%7D); %0A%0Afuncti
0009f646092c5e0ead10b0f491f10ba1a74c6506
Access the array, not the item!
src/client/vogue-client.js
src/client/vogue-client.js
// Vogue - Client // Copyright (c) 2011 Andrew Davey ([email protected]) (function () { var script, hop = Object.prototype.hasOwnProperty, head = document.getElementsByTagName("head")[0]; function vogue() { var stylesheets, socket = io.connect(script.rootUrl); /** * Watch for all available stylesheets. */ function watchAllStylesheets() { var href; for (href in stylesheets) { if (hop.call(stylesheets, href)) { socket.emit("watch", { href: href }); } } } /** * Reload a stylesheet. * * @param {String} href The URL of the stylesheet to be reloaded. */ function reloadStylesheet(href) { var newHref = stylesheets[href].href + (href.indexOf("?") >= 0 ? "&" : "?") + "_vogue_nocache=" + (new Date).getTime(), stylesheet; // Check if the appropriate DOM Node is there. if (!stylesheets[href].setAttribute) { // Create the link. stylesheet = document.createElement("link"); stylesheet.setAttribute("rel", "stylesheet"); stylesheet.setAttribute("href", newHref); head.appendChild(stylesheet); // Update the reference to the newly created link. stylesheets[href] = stylesheet; } else { // Update the href to the new URL. stylesheets[href].href = newHref; } } /** * Handle messages from socket.io, and load the appropriate stylesheet. * * @param message Socket.io message object. * @param message.href The url of the stylesheet to be loaded. */ function handleMessage(message) { reloadStylesheet(message.href); } /** * Fetch all the local stylesheets from the page. * * @returns {Object} The list of local stylesheets keyed by their base URL. */ function getLocalStylesheets() { /** * Checks if the stylesheet is local. * * @param {Object} link The link to check for. * @returns {Boolean} */ function isLocalStylesheet(link) { var href, i, isExternal = true; if (link.getAttribute("rel") !== "stylesheet") { return false; } href = link.href; for (i = 0; i < script.bases.length; i += 1) { if (href.indexOf(script.bases[i]) > -1) { isExternal = false; break; } } return !(isExternal && href.match(/^https?:/)); } /** * Checks if the stylesheet's media attribute is 'print' * * @param (Object) link The stylesheet element to check. * @returns (Boolean) */ function isPrintStylesheet(link) { return link.getAttribute("media") === "print"; } /** * Get the link's base URL. * * @param {String} href The URL to check. * @returns {String|Boolean} The base URL, or false if no matches found. */ function getBase(href) { var base, j; for (j = 0; j < script.bases.length; j += 1) { base = script.bases[j]; if (href.indexOf(base) > -1) { return href.substr(base.length); } } return false; } function getProperty(property) { return this[property]; } var stylesheets = {}, reImport = /@import\s+url\(["']?([^"'\)]+)["']?\)/g, links = document.getElementsByTagName("link"), link, href, matches, content, i, m; // Go through all the links in the page, looking for stylesheets. for (i = 0, m = links.length; i < m; i += 1) { link = links[i]; if (isPrintStylesheet(link)) continue; if (!isLocalStylesheet(link)) continue; // Link is local, get the base URL. href = getBase(link.href); if (href !== false) { stylesheets[href] = link; } } // Go through all the style tags, looking for @import tags. links = document.getElementsByTagName("style"); for (i = 0, m = links.length; i < m; i += 1) { if (isPrintStylesheet(link[i])) continue; content = links[i].text || links[i].textContent; while ((matches = reImport.exec(content))) { link = { rel: "stylesheet", href: matches[1], getAttribute: getProperty }; if (isLocalStylesheet(link)) { // Link is local, get the base URL. href = getBase(link.href); if (href !== false) { stylesheets[href] = link; } } } } return stylesheets; } stylesheets = getLocalStylesheets(); socket.on("connect", watchAllStylesheets); socket.on("update", handleMessage); } /** * Load a script into the page, and call a callback when it is loaded. * * @param {String} src The URL of the script to be loaded. * @param {Function} loadedCallback The function to be called when the script is loaded. */ function loadScript(src, loadedCallback) { var script = document.createElement("script"); script.setAttribute("type", "text/javascript"); script.setAttribute("src", src); // Call the callback when the script is loaded. script.onload = loadedCallback; script.onreadystatechange = function () { if (this.readyState === "complete" || this.readyState === "loaded") { loadedCallback(); } }; head.appendChild(script); } /** * Load scripts into the page, and call a callback when they are loaded. * * @param {Array} scripts The scripts to be loaded. * @param {Function} loadedCallback The function to be called when all the scripts have loaded. */ function loadScripts(scripts, loadedCallback) { var srcs = [], property, count, i, src, countDown = function () { count -= 1; if (!count) { loadedCallback(); } }; for (property in scripts) { if (!(property in window)) { srcs.push(scripts[property]); } } count = srcs.length; if (!count) { loadedCallback(); } for (i = 0; i < srcs.length; i += 1) { src = srcs[i]; loadScript(src, countDown); } } /** * Fetches the info for the vogue client. */ function getScriptInfo() { var bases = [ document.location.protocol + "//" + document.location.host ], scripts, src, rootUrl, baseMatch; if (typeof window.__vogue__ === "undefined") { scripts = document.getElementsByTagName("script"); // The last parsed script will be our script. src = scripts[scripts.length - 1].getAttribute("src"); rootUrl = src.match(/^https?\:\/\/(.*?)\//)[0]; // There is an optional base argument, that can be used. baseMatch = src.match(/\bbase=(.*)(&|$)/); if (baseMatch) { bases = bases.concat(baseMatch[1].split(",")); } return { rootUrl: rootUrl, bases: bases }; } else { window.__vogue__.bases = bases; return window.__vogue__; } } /** * Fetches the port from the URL. * * @param {String} url URL to get the port from * @returns {Number} The port number, or 80 if no port number found or is invalid. */ function getPort(url) { // URL may contain the port number after the second colon. // http://domain:1234/ var index = url.indexOf(":", 6); // skipping 6 characters to ignore first colon return index < 0 ? 80 : parseInt(url.substr(index + 1), 10); } script = getScriptInfo(); loadScripts({ io: script.rootUrl + "socket.io/socket.io.js" }, vogue); }());
JavaScript
0.000001
@@ -4177,16 +4177,17 @@ eet(link +s %5Bi%5D)) co
fcd8979670c80ca156b233200b2fe3ee28c59238
change wzrd.in to own fork
src/belt.js
src/belt.js
const request = require('request'); const config = require('./config'); const db = require('./db'); const {promisify} = require('util'); const reqAsync = promisify(request); const path = require('path'); const debug = require('./debug'); const REGEX_RAW_GIST_URL = /^https?:\/\/gist\.githubusercontent\.com\/(.+?\/[0-9a-f]+\/raw\/(?:[0-9a-f]+\/)?.+\..+)$/i; const CDN_URL = 'https://cdn.rawgit.com'; const GIT_API_URL = 'https://api.github.com/'; const REGISTRY_URL = 'https://registry.npmjs.org/'; const GEO_IP = 'http://freegeoip.net/json/'; const pkgApi = async (repo, pkg) => { try { const res = await reqAsync(`https://wzrd.in/standalone/${repo}`); if (res.statusCode === 200 && res.body) { const cdnlink = await createGist(pkg, res.body); return cdnlink; } return false; } catch (e) { return false; } }; const validatePackage = async (pkg, ver) => { try { ver = !ver ? 'latest' : ver; const res = await reqAsync(`${REGISTRY_URL + pkg}/${ver}`); const body = JSON.parse(res.body); if (res.statusCode === 200 && body) { return {name: body.name, version: body.version}; } return false; } catch (e) { return false; } }; const createGist = async (pkg, content) => { try { const data = { 'description': `Umdfied build of ${pkg}`, 'public': true, 'files': {} }; const fname = `${pkg}.min.js`; data.files[fname] = {content}; const reqOpts = { method: 'POST', url: '/gists', headers: { 'Authorization': `token ${config.GIT_TOKEN}`, 'User-Agent': 'Umdfied-App' }, baseUrl: GIT_API_URL, json: true, body: data }; const res = await reqAsync(reqOpts); const body = res.body; debug(body, 'createGist'); let cdnurl = body.files[fname].raw_url.replace(REGEX_RAW_GIST_URL, `${CDN_URL}/$1`); return cdnurl; } catch (e) { console.log(e); } }; const getCountry = async ip => { try { const res = await reqAsync({url: GEO_IP + ip, json: true}); const country = res.body.country_name; if (country) { return country; } return 'anonymous'; } catch (e) { return 'anonymous'; } }; const normalizeIp = ip => ip.replace(/^::ffff:/i, ''); exports.umdfied = async (pkg, ver, ip) => { try { ip = normalizeIp(ip); const usrCountry = await getCountry(ip); debug(usrCountry, 'usrCountry'); await db.saveUsrInfo({ip, country: usrCountry}); debug('Checking DB', 'db'); const repoInfo = await validatePackage(pkg, ver); if (!repoInfo) { return false; } const fromDb = await db.getPkg(repoInfo.name, repoInfo.version); if (fromDb) { return {gitCdn: fromDb.cdn, semver: fromDb.version}; } const repo = `${repoInfo.name}@${repoInfo.version}`; debug(repo, 'repo'); const gitCdn = await pkgApi(repo, pkg); debug(gitCdn, 'gitCdn'); if (!gitCdn) { return false; } await db.savePkg(repoInfo.name, repoInfo.version, gitCdn); return {gitCdn, semver: repoInfo.version}; } catch (e) { debug(`${e}\n${e.stack}`, 'umdfied Error'); return false; } };
JavaScript
0
@@ -628,15 +628,33 @@ s:// -wzrd.in +umdfied-cdn.herokuapp.com /sta
ea63835e905fa9205ae5123e6bed8e26d9a9af79
Fix incorrect response in unlock
packages/components/containers/api/ApiProvider.js
packages/components/containers/api/ApiProvider.js
import { useReducer, useRef, useState } from 'react'; import PropTypes from 'prop-types'; import { updateServerTime } from '@proton/crypto'; import configureApi from '@proton/shared/lib/api'; import { getApiError, getApiErrorMessage, getIsOfflineError, getIsUnreachableError, } from '@proton/shared/lib/api/helpers/apiErrorHelper'; import withApiHandlers from '@proton/shared/lib/api/helpers/withApiHandlers'; import { getClientID } from '@proton/shared/lib/apps/helper'; import xhr from '@proton/shared/lib/fetch/fetch'; import { withLocaleHeaders } from '@proton/shared/lib/fetch/headers'; import { getDateHeader } from '@proton/shared/lib/fetch/helpers'; import { localeCode } from '@proton/shared/lib/i18n'; import { useModals, useNotifications } from '../../hooks'; import UnlockModal from '../login/UnlockModal'; import AuthModal from '../password/AuthModal'; import DelinquentModal from './DelinquentModal'; import ApiContext from './apiContext'; import ApiServerTimeContext from './apiServerTimeContext'; import ApiStatusContext, { defaultApiStatus } from './apiStatusContext'; import HumanVerificationModal from './humanVerification/HumanVerificationModal'; const getSilenced = ({ silence } = {}, code) => { if (Array.isArray(silence)) { return silence.includes(code); } return !!silence; }; const reducer = (oldState, diff) => { const newState = { ...oldState, ...diff, }; // To prevent rerenders if (Object.keys(newState).every((key) => oldState[key] === newState[key])) { return oldState; } return newState; }; /** @type any */ const ApiProvider = ({ config, onLogout, children, UID, noErrorState }) => { const { createNotification } = useNotifications(); const { createModal } = useModals(); const [apiStatus, setApiStatus] = useReducer(reducer, defaultApiStatus); const [apiServerTime, setApiServerTime] = useState(undefined); const apiRef = useRef(); if (!apiRef.current) { const handleMissingScopes = ({ scopes: missingScopes = [], error, options }) => { if (missingScopes.includes('nondelinquent')) { return new Promise((resolve, reject) => { createModal( <DelinquentModal onClose={() => { error.cancel = true; reject(error); }} /> ); }); } if (missingScopes.includes('locked')) { return new Promise((resolve, reject) => { createModal( <UnlockModal onCancel={() => { error.cancel = true; reject(error); }} onSuccess={() => { if (!apiRef.current) { reject(error); return; } return resolve(apiRef.current(options)); }} /> ); }); } if (missingScopes.includes('password')) { return new Promise((resolve, reject) => { createModal( <AuthModal config={options} onCancel={() => { error.cancel = true; reject(error); }} onError={(apiError) => { reject(apiError); }} onSuccess={(result) => resolve(result.response)} /> ); }); } return Promise.reject(error); }; const handleVerification = ({ token, methods, onVerify, title }, error) => { return new Promise((resolve, reject) => { createModal( <HumanVerificationModal title={title} token={token} methods={methods} onVerify={onVerify} onSuccess={resolve} onError={reject} onClose={() => { error.cancel = true; reject(error); }} /> ); }); }; const call = configureApi({ ...config, clientID: getClientID(config.APP_NAME), xhr, UID, }); const callWithApiHandlers = withApiHandlers({ call, UID, onMissingScopes: handleMissingScopes, onVerification: handleVerification, }); apiRef.current = ({ output = 'json', ...rest }) => { // Only need to send locale headers in public app const config = UID ? rest : withLocaleHeaders(localeCode, rest); return callWithApiHandlers(config) .then((response) => { const serverTime = getDateHeader(response.headers); if (!serverTime) { // The HTTP Date header is mandatory, so this should never occur. // We need the server time for proper time sync: // falling back to the local time can result in e.g. unverifiable signatures throw new Error('Could not fetch server time'); } setApiServerTime(updateServerTime(serverTime)); setApiStatus(defaultApiStatus); if (output === 'stream') { return response.body; } if (output === 'raw') { return response; } return response[output](); }) .catch((e) => { const serverTime = e.response?.headers ? getDateHeader(e.response.headers) : undefined; if (serverTime) { setApiServerTime(updateServerTime(serverTime)); } const { code } = getApiError(e); const errorMessage = getApiErrorMessage(e); const handleErrorNotification = () => { if (errorMessage) { const isSilenced = getSilenced(e.config, code); if (!isSilenced) { createNotification({ type: 'error', expiration: config?.notificationExpiration, text: errorMessage, }); } } }; // Intended for the verify app where we always want to pass an error notification if (noErrorState) { handleErrorNotification(); throw e; } const isOffline = getIsOfflineError(e); const isUnreachable = getIsUnreachableError(e); if (isOffline || isUnreachable) { setApiStatus({ apiUnreachable: isUnreachable ? errorMessage : '', offline: isOffline, }); throw e; } setApiStatus({ apiUnreachable: defaultApiStatus.apiUnreachable, offline: defaultApiStatus.offline, }); if (e.name === 'AbortError' || e.cancel) { throw e; } if (e.name === 'AppVersionBadError') { setApiStatus({ appVersionBad: true }); throw e; } if (e.name === 'InactiveSession') { onLogout(); throw e; } handleErrorNotification(); throw e; }); }; } return ( <ApiContext.Provider value={apiRef.current}> <ApiStatusContext.Provider value={apiStatus}> <ApiServerTimeContext.Provider value={apiServerTime}>{children}</ApiServerTimeContext.Provider> </ApiStatusContext.Provider> </ApiContext.Provider> ); }; ApiProvider.propTypes = { children: PropTypes.node.isRequired, config: PropTypes.object.isRequired, noErrorState: PropTypes.bool, UID: PropTypes.string, onLogout: PropTypes.func, }; export default ApiProvider;
JavaScript
0.998882
@@ -3188,23 +3188,45 @@ current( +%7B ... options +, output: 'raw' %7D ));%0A
a6a8951c64f37ad9d813819dfbc80a543ef19314
Remove timeout from runTestcafe
packages/core/resolve-scripts/src/run_testcafe.js
packages/core/resolve-scripts/src/run_testcafe.js
import { getInstallations } from 'testcafe-browser-tools' import fetch from 'isomorphic-fetch' import path from 'path' import respawn from 'respawn' import fsExtra from 'fs-extra' import webpack from 'webpack' import spawnAsync from './spawn_async' import getWebpackConfigs from './get_webpack_configs' import writePackageJsonsForAssemblies from './write_package_jsons_for_assemblies' import getPeerDependencies from './get_peer_dependencies' import showBuildInfo from './show_build_info' import copyEnvToDist from './copy_env_to_dist' import validateConfig from './validate_config' const runTestcafe = async ({ resolveConfig, adjustWebpackConfigs, functionalTestsDir, browser, customArgs = [], timeout }) => { validateConfig(resolveConfig) const nodeModulesByAssembly = new Map() const webpackConfigs = await getWebpackConfigs({ resolveConfig, nodeModulesByAssembly, adjustWebpackConfigs }) const peerDependencies = getPeerDependencies() const compiler = webpack(webpackConfigs) fsExtra.copySync( path.resolve(process.cwd(), resolveConfig.staticDir), path.resolve(process.cwd(), resolveConfig.distDir, './client') ) await new Promise((resolve, reject) => { compiler.run((err, { stats }) => { stats.forEach(showBuildInfo.bind(null, err)) writePackageJsonsForAssemblies( resolveConfig.distDir, nodeModulesByAssembly, peerDependencies ) copyEnvToDist(resolveConfig.distDir) const hasNoErrors = stats.reduce( (acc, val) => acc && (val != null && !val.hasErrors()), true ) void (hasNoErrors ? resolve() : reject(err)) }) }) const serverPath = path.resolve( process.cwd(), path.join(resolveConfig.distDir, './common/local-entry/local-entry.js') ) const server = respawn(['node', serverPath], { cwd: process.cwd(), maxRestarts: 0, kill: 5000, stdio: 'inherit' }) process.on('exit', () => { server.stop() }) server.start() while (true) { const statusUrl = `http://localhost:${resolveConfig.port}${ resolveConfig.rootPath ? `/${resolveConfig.rootPath}` : '' }/api/status` try { const response = await fetch(statusUrl) if ((await response.text()) === 'ok') break } catch (e) {} } const targetBrowser = browser == null ? Object.keys(await getInstallations())[0] : browser const targetTimeout = timeout == null ? 20000 : timeout try { await spawnAsync( 'npx', [ 'testcafe', targetBrowser, functionalTestsDir, '--app-init-delay', targetTimeout, '--selector-timeout', targetTimeout, '--assertion-timeout', targetTimeout, '--page-load-timeout', targetTimeout, ...(targetBrowser === 'remote' ? ['--qr-code'] : []), ...customArgs ], { stdio: 'inherit', cwd: process.cwd() } ) await Promise.race([ new Promise(resolve => setTimeout(resolve, 10000)), new Promise(resolve => server.stop(resolve)) ]) } catch (error) { await Promise.race([ new Promise(resolve => setTimeout(resolve, 10000)), new Promise(resolve => server.stop(resolve)) ]) throw error } } export default runTestcafe
JavaScript
0.000001
@@ -2950,37 +2950,16 @@ await -Promise.race(%5B%0A new Prom @@ -3004,67 +3004,8 @@ 00)) -,%0A new Promise(resolve =%3E server.stop(resolve))%0A %5D) %0A %7D @@ -3035,29 +3035,8 @@ ait -Promise.race(%5B%0A new @@ -3085,67 +3085,8 @@ 00)) -,%0A new Promise(resolve =%3E server.stop(resolve))%0A %5D) %0A
554fbc6dc63c1d1e418f470330b03b123b006084
tweak width of alignment track qual display
src/JBrowse/View/Track/Alignments.js
src/JBrowse/View/Track/Alignments.js
define( ['dojo/_base/declare', 'dojo/_base/array', 'JBrowse/Util', 'JBrowse/View/Track/HTMLFeatures' ], function( declare, array, Util, HTMLFeatures ) { return declare( HTMLFeatures, /** * @lends JBrowse.View.Track.Alignments */ { constructor: function() { }, _defaultConfig: function() { return Util.deepUpdate( dojo.clone( this.inherited(arguments) ), { style: { className: 'alignment', arrowheadClass: 'arrowhead' } } ); }, renderFeature: function(feature, uniqueId, block, scale, containerStart, containerEnd, destBlock ) { var featDiv = this.inherited( arguments ); this._drawMismatches( feature, featDiv, scale ); // if this feature is part of a multi-segment read, and not // all of its segments are aligned, add missing_mate to its // class if( feature.get('multi_segment_template') && !feature.get('multi_segment_all_aligned') ) featDiv.className += ' missing_mate'; return featDiv; }, /** * draw base-mismatches on the feature */ _drawMismatches: function( feature, featDiv, scale ) { // recall: scale is pixels/basepair if ( scale >= 0.5 ) { var mismatches = this._getMismatches( feature ); var charSize = this.getCharacterMeasurements(); var drawChars = scale >= charSize.w; var featureLength = feature.get('end') - feature.get('start'); array.forEach( mismatches, function( mismatch ) { array.forEach( mismatch.bases, function( base, i ) { dojo.create('span', { className: 'mismatch base base_'+(base == '*' ? 'deletion' : base.toLowerCase()), style: { position: 'absolute', left: (mismatch.start+i)/featureLength*100 + '%', width: Math.max(scale,1) + 'px' }, innerHTML: drawChars ? base : '' }, featDiv ); }, this ); }); } }, _getMismatches: function( feature ) { var seq = feature.get('seq'); if( ! seq ) return m; // parse the MD tag if it has one var mdTag = feature.get('MD'); if( mdTag ) { return this._mdToMismatches( feature, mdTag ); } return []; }, /** * parse a SAM MD tag to find mismatching bases of the template versus the reference * @returns {Array[Object]} array of mismatches and their positions * @private */ _mdToMismatches: function( feature, mdstring ) { var mismatchRecords = []; var curr = { start: 0, bases: '' }; var seq = feature.get('seq'); var nextRecord = function() { mismatchRecords.push( curr ); curr = { start: curr.start + curr.bases.length, bases: ''}; }; array.forEach( mdstring.match(/(\d+|\^[a-z]+|[a-z])/ig), function( token ) { if( token.match(/^\d/) ) { // matching bases curr.start += parseInt( token ); } else if( token.match(/^\^/) ) { // insertion in the template var i = token.length-1; while( i-- ) { curr.bases += '*'; } nextRecord(); } else if( token.match(/^[a-z]/i) ) { // mismatch curr.bases = seq.substr( curr.start, token.length ); nextRecord(); } }); return mismatchRecords; }, // stub out subfeature rendering, this track doesn't render subfeatures renderSubfeature: function() {}, /** * @returns {Object} containing <code>h</code> and <code>w</code>, * in pixels, of the characters being used for sequences */ getCharacterMeasurements: function() { if( !this._measurements ) this._measurements = this._measureSequenceCharacterSize( this.div ); return this._measurements; }, /** * Conducts a test with DOM elements to measure sequence text width * and height. */ _measureSequenceCharacterSize: function( containerElement ) { var widthTest = dojo.create('div', { innerHTML: '<span class="base mismatch">A</span>' +'<span class="base mismatch">C</span>' +'<span class="base mismatch">T</span>' +'<span class="base mismatch">G</span>' +'<span class="base mismatch">N</span>', style: { visibility: 'hidden', position: 'absolute', left: '0px' } }, containerElement ); var result = { w: widthTest.clientWidth / 5, h: widthTest.clientHeight }; containerElement.removeChild(widthTest); return result; }, /** * Make a default feature detail page for the given feature. * @returns {HTMLElement} feature detail page HTML */ defaultFeatureDetail: function( /** JBrowse.Track */ track, /** Object */ f, /** HTMLElement */ div ) { var fmt = dojo.hitch( this, function( name, value ) { name = Util.ucFirst( name.replace(/_/g,' ') ); return this._fmtDetailField(name, value); }); var container = dojo.create('div', { className: 'detail feature-detail feature-detail-'+track.name, innerHTML: '' }); container.innerHTML += fmt( 'Name', f.get('name') ); container.innerHTML += fmt( 'Type', f.get('type') ); container.innerHTML += fmt( 'Score', f.get('score') ); container.innerHTML += fmt( 'Description', f.get('note') ); container.innerHTML += fmt( 'Position', Util.assembleLocString({ start: f.get('start'), end: f.get('end'), ref: this.refSeq.name }) + ({'1':' (+)', '-1': ' (-)', 0: ' (no strand)' }[f.get('strand')] || '') ); var alignment = '<div class="alignment sequence">'+f.get('seq')+'</div>'; if( f.get('seq') ) { container.innerHTML += fmt('Sequence and Quality', this._renderSeqQual( f ) ); } var additionalTags = array.filter( f.tags(), function(t) { return ! {name:1,score:1,start:1,end:1,strand:1,note:1,subfeatures:1,type:1}[t.toLowerCase()]; } ).sort(); dojo.forEach( additionalTags, function(t) { container.innerHTML += fmt( t, f.get(t) ); }); return container; }, _renderSeqQual: function( feature ) { var seq = feature.get('seq'), qual = feature.get('qual') || ''; if( !seq ) return ''; qual = qual.split(/\s+/); var fieldWidth = (''+Math.max.apply( Math, qual )).length; // pad the sequence with spaces var seqPadding = ' '; while( seqPadding.length < fieldWidth-1 ) { seqPadding += ' '; } var paddedSeq = array.map( seq, function(s) { return s + seqPadding; }); var tableRowHTML = function(fields, class_) { class_ = class_ ? ' class="'+class_+'"' : ''; return '<tr'+class_+'>'+array.map( fields, function(f) { return '<td>'+f+'</td>'; }).join('')+'</tr>'; }; // insert newlines var rendered = ''; var lineFields = Math.round(65/fieldWidth); while( paddedSeq.length ) { var line = paddedSeq.slice(0,Math.min( paddedSeq.length, lineFields ) ); paddedSeq = paddedSeq.slice(lineFields); rendered += tableRowHTML( line, 'seq' ); if( qual.length ) { line = qual.slice(0, Math.min( qual.length, lineFields )); qual = qual.slice(lineFields); rendered += tableRowHTML( line, 'qual' ); } } return '<table class="baseQuality">'+rendered+'</table>'; } }); });
JavaScript
0
@@ -8131,17 +8131,17 @@ .round(6 -5 +0 /fieldWi
3c091a8fa54541db7ca48d37678f99c7cf0d04a0
Add event listener for convert button click
js/FatTweet.class.js
js/FatTweet.class.js
class FatTweet { constructor(){ this.processTweetBoxes(); } processTweetBoxes(){ var FT = this; var $tweetBoxes = $('.tweet-box[name="tweet"]:not(.fat-tweet-processed)'); if(!$tweetBoxes.length) return; $tweetBoxes .addClass('fat-tweet-processed') .each(function(){ var $tweetBox = $(this); var $form = $tweetBox.closest('form'); FT.processTweetForm($form); }); } processTweetForm($form){ var $button = $('<button class="btn fat-tweet-convert-text js-tooltip" data-delay="150" data-original-title="Convert text into image" type="button"><img src="'+chrome.runtime.getURL('img/32.png')+'"></button>'); $form .addClass('fat-tweet-processed-form') .find('.btn.tweet-btn') .before($button); return $form; } isTweetFormProcessed($form){ return $form.hasClass('fat-tweet-processed-form'); } convertText($form){ var FT = this; var $area = $form.find('.tweet-box[name="tweet"]'); $area.addClass('screenshot-process'); html2canvas($area.get(0), { onrendered: function(canvas) { $area.after(canvas); $area .removeClass('screenshot-process') .html(FT.getLinksClean($area.children('div'))); $area.focus(); } }); } getLinksClean($content){ var $links = $content.find('a'); var $newContent = $('<div></div>'); var contentLength = 0; $links.each(function(){ var linkTextLength = $(this).text().toString().length; if(contentLength + linkTextLength > 140){ return false; } contentLength = contentLength + linkTextLength; $newContent.append($(this)).append(' '); }); return $newContent; } }
JavaScript
0
@@ -59,24 +59,245 @@ eetBoxes();%0A + var FT = this;%0A $('body').on('click', '.fat-tweet-convert-text', function(e)%7B%0A e.preventDefault();%0A var $form = $(this).closest('form');%0A FT.convertText($form);%0A %7D);%0A %7D%0A pr
3f04cce7ffea23df2735588c7197823f6474c522
Remove unused dependencies from main controller
src/client/app/newrelic/main.js
src/client/app/newrelic/main.js
(function() { "use strict"; /* @ngInject */ function MainController($scope, $log, poller, localStorageService, User, BoxService, ServerPoller, HEALTH_CHECK_RANK, GROUP_POLLING_CONFIG, $, _) { $scope.applications = {}; $scope.servers = {}; $scope.size = {}; $scope.user = User; $scope.setPollers = function (pollers) { _.each(pollers, function(pollerType) { var serverPoller = ServerPoller.getServerPoller(pollerType); serverPoller.promise.then(null, null, function (data) { $scope.time = ServerPoller.getTime(); $('#time-display').toggleClass('color-red', !data.links); if (!data.links) { $scope.playAlarm(); return; } $scope.parseData(data[pollerType], pollerType); }); }); }; $scope.getBoxClass = new BoxService().getBoxClass; $scope.parseData = function (data, pollerType) { //initialize alert to off. var shouldAlert = false; //get amount of servers/applications $scope.size[pollerType] = data.length; _.each(data, function (res) { //all names to lowercase res.name = res.name.toLowerCase(); //Finding relevant group name var findByGroupName = function(group) { return (res.name.indexOf(group.type) > -1); }; //Assigning to relevant group. assign to default group if not assigned. var groupSelected = _.find(GROUP_POLLING_CONFIG.grouping, findByGroupName) || GROUP_POLLING_CONFIG.defaultGroup; //removing '-' char from servers/applications names res.name = $.trim(res.name.replace(groupSelected.type, '').replace('-',' ')); //Creating a group if group was not created. Group are sorted by their rank if (!$scope[pollerType][groupSelected.type]) { $scope[pollerType][groupSelected.type] = { data: {}, name: groupSelected.type, rank: groupSelected.rank }; } var data = $scope[pollerType][groupSelected.type].data; //get server/application current status (green/orange/red/grey/gray) var currentStatus = HEALTH_CHECK_RANK[res.health_status] || 0; //get server/application previous data to compare with current var previousData = data[res.name] || {}; //get server/application previous status (green/orange/red/grey/gray) var previousStatus = HEALTH_CHECK_RANK[previousData.health_status] || 0; //compare between current & previous status. Negative status means server/application status got worse. var status = (currentStatus - previousStatus); $log.debug('status', status); if (groupSelected.alarm && (status > 0)) { //alert will be played. shouldAlert = true; } //update server/application data data[res.name] = res; }); //playing alert in case should alert set to true. if (shouldAlert) { $scope.playAlarm(); } }; $scope.playAlarm = function () { document.getElementById('soundAlarm').play(); }; $scope.saveSettings = function () { $scope.user.save(); $scope.setPollers(['applications', 'servers']); }; $scope.setPollers(['applications', 'servers']); } angular .module("app.newrelic") .controller("MainCtrl", MainController); }());
JavaScript
0.000001
@@ -91,37 +91,8 @@ log, - poller, localStorageService, Use
1f7644147cc413491b9e998435cf73efb7a1fe75
make purge-translations windows compatible
gulpfile.js
gulpfile.js
const gulp = require('gulp'); const webpack = require('webpack'); const webpackStream = require('webpack-stream'); const mainWebpackConfig = require('./source/main/webpack.config'); const rendererWebpackConfig = require('./source/renderer/webpack.config'); const shell = require('gulp-shell'); const electronConnect = require('electron-connect'); const mainOutputDestination = gulp.dest('dist/main'); const rendererOutputDestination = gulp.dest('dist/renderer'); const buildMain = (config, done) => gulp.src('source/main/index.js') .pipe(webpackStream(Object.assign({}, mainWebpackConfig, config), webpack, done)) .pipe(mainOutputDestination); const buildRenderer = (config, done) => gulp.src('source/renderer/index.js') .pipe(webpackStream(Object.assign({}, rendererWebpackConfig, config), webpack, done)) .pipe(rendererOutputDestination); // Setup electron-connect server to start the app in development mode const electronServer = electronConnect.server.create({ spawnOpt: { env: Object.assign({}, process.env, { NODE_ENV: 'development' }) } }); gulp.task('build-main', (done) => buildMain({}, done)); gulp.task('build-main-watch', (done) => buildMain({ watch: true }, done)); gulp.task('build-renderer', (done) => buildRenderer({}, done)); gulp.task('build-renderer-watch', (done) => buildRenderer({ watch: true }, done)); gulp.task('build', gulp.series('build-main', 'build-renderer')); gulp.task('build-watch', gulp.series('build-main-watch', 'build-renderer-watch')); gulp.task('cucumber', shell.task('npm run cucumber --')); gulp.task('cucumber-watch', shell.task('nodemon --exec npm run cucumber-watch')); gulp.task('test', gulp.series('build', 'cucumber')); gulp.task('test-watch', gulp.series('build-watch', 'cucumber-watch')); gulp.task('purge-translations', shell.task('rm -rf ./translations/messages/app')); gulp.task('electron:restart', (done) => { electronServer.restart(); done(); }); gulp.task('electron:reload', (done) => { electronServer.reload(); done(); }); gulp.task('start-dev', () => { electronServer.start(); gulp.watch('dist/main/index.js', gulp.series('electron:restart')); gulp.watch('dist/renderer/*', gulp.series('electron:reload')); }); gulp.task('start', shell.task('cross-env NODE_ENV=production electron ./')); gulp.task('dev', gulp.series('purge-translations', 'build-watch', 'start-dev'));
JavaScript
0
@@ -1822,12 +1822,12 @@ k('r -m -r +imra f ./
be7273a7704830f3e9a8e8c4b78903af75020f15
add start timer function
js/script.js
js/script.js
// Declare global variables var mainTimer = document.getElementById('startTimer'); var timerState = document.getElementById('displayTimer'); // Event handler for user clicks on main timer mainTimer.addEventListener('click', startTimer); function startTimer() { if (timerState.style.zIndex == '-1') { timerState.style.zIndex = '1'; } else { timerState.style.zIndex = '-1'; } }
JavaScript
0.000002
@@ -133,16 +133,113 @@ Timer'); +%0Avar currentTimer = document.getElementById('displayTimer').innerHTML;%0Aconsole.log(currentTimer); %0A%0A// Eve @@ -315,21 +315,24 @@ click', -start +activate Timer);%0A @@ -341,21 +341,24 @@ unction -start +activate Timer() @@ -502,8 +502,85 @@ %7D%0A%0A%7D +%0A%0Afunction startTimer() %7B%0A if (timerState.style.zIndex == '-1') %7B%0A%0A %7D%0A%7D
11e5e994cf9e2a98fcc900d09c68e0452095af10
Add docs.rs integration
app/routes/crate/version.js
app/routes/crate/version.js
import Ember from 'ember'; import ajax from 'ic-ajax'; export default Ember.Route.extend({ refreshAfterLogin: Ember.observer('session.isLoggedIn', function() { this.refresh(); }), model(params) { const requestedVersion = params.version_num === 'all' ? '' : params.version_num; const crate = this.modelFor('crate'); const controller = this.controllerFor(this.routeName); const maxVersion = crate.get('max_version'); const isUnstableVersion = version => { const versionLen = version.length; let majorMinorPatchChars = 0; let result = false; for (let i = 0; i < versionLen; i++) { const char = version.charAt(i); if (!isNaN(parseInt(char)) || char === '.') { majorMinorPatchChars++; } else { break; } } if (versionLen !== majorMinorPatchChars) { result = true; } return result; }; // Fallback to the crate's last stable version // If `max_version` is `0.0.0` then all versions have been yanked if (!requestedVersion && maxVersion !== '0.0.0') { if (isUnstableVersion(maxVersion)) { crate.get('versions').then(versions => { const latestStableVersion = versions.find(version => { if (!isUnstableVersion(version.get('num'))) { return version; } }); if (latestStableVersion == null) { // If no stable version exists, fallback to `maxVersion` params.version_num = maxVersion; } else { params.version_num = latestStableVersion.get('num'); } }); } else { params.version_num = maxVersion; } } controller.set('crate', crate); controller.set('requestedVersion', requestedVersion); controller.set('fetchingFollowing', true); if (this.session.get('currentUser')) { ajax(`/api/v1/crates/${crate.get('name')}/following`) .then((d) => controller.set('following', d.following)) .finally(() => controller.set('fetchingFollowing', false)); } // Find version model return crate.get('versions') .then(versions => { const version = versions.find(version => version.get('num') === params.version_num); if (params.version_num && !version) { this.controllerFor('application').set('nextFlashError', `Version '${params.version_num}' of crate '${crate.get('name')}' does not exist`); } return version || versions.find(version => version.get('num') === maxVersion) || versions.objectAt(0); }); }, serialize(model) { let version_num = model ? model.get('num') : ''; return { version_num }; }, });
JavaScript
0
@@ -2451,32 +2451,524 @@ e));%0A %7D%0A%0A + if (!crate.get('documentation')) %7B%0A let crateName = crate.get('name');%0A let crateVersion = params.version_num;%0A ajax(%60https://docs.rs/crate/$%7BcrateName%7D/$%7BcrateVersion%7D/builds.json%60)%0A .then((r) =%3E %7B%0A if (r.length %3E 0 && r%5B0%5D.build_status === true) %7B%0A crate.set('documentation', %60https://docs.rs/$%7BcrateName%7D/$%7BcrateVersion%7D/$%7BcrateName%7D/%60);%0A %7D%0A %7D);%0A %7D%0A%0A // Find
d83a0b04f6f44356f6106a82159cf1bdfc561191
fix for swagger
packages/custom/icapi/server/controllers/users.js
packages/custom/icapi/server/controllers/users.js
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), User = mongoose.model('User'), utils = require('./utils'); /** * Find all users */ exports.all = function(req, res) { var query = {}; var Query = User.find(query); Query.limit(200 || req.query.limit); Query.exec(function(err, users) { utils.checkAndHandleError(err, res, 'Failed to load users'); res.status(200); return res.json(users); }); }; exports.read = function(req, res) { User.findById(req.params.id, function(err, user) { utils.checkAndHandleError(err, res, 'Failed to load user'); res.status(200); return res.json(user); }); }; exports.getByEntity = function(req, res) { //It is a temporary function. need to change this function to use elasticsearch!!!! var query = { _id: req.params.id }; var model = (req.params.entity.charAt(0).toUpperCase() + req.params.entity.slice(1)).substring(0, req.params.entity.length - 1); var Query = mongoose.model(model).findOne(query); Query.exec(function(err, project) { if (err || !project) utils.checkAndHandleError(err ? err : !project, res, 'Failed to load project with id: ' + req.params.id); else { var userIds = project.watchers; userIds.push(project.creator); User.find({ _id: { $in: userIds } }).exec(function(err, users) { res.status(200); return res.json(users); }); } }); };
JavaScript
0
@@ -769,16 +769,56 @@ rch!!!!%0A +%09res.status(200);%0A%09return res.json(%5B%5D);%0A %09var que
3d296db30ac5bf3ee68d67ebcd4a1f58e97a1ba4
use setUrlParameters for tests fo viewPossibleMovements
src/main/webapp/inc/js/app/tests/game/ctrl.spec.js
src/main/webapp/inc/js/app/tests/game/ctrl.spec.js
'use strict'; describe('game', function () { var $scope, controller, $httpBackend; var square; var cardName = 'King'; var cardColor = 'Red'; var createGameUrl = '/aot/rest/createGame'; var createGameMethod = 'POST'; var viewPossibleMovementsUrl = '/aot/rest/getPossibleSquares?card_color=' + cardColor + '&card_name=' + cardName; var viewPossibleMovementsMethod = 'GET'; var playUrl = '/aot/rest/play'; var playMethod = 'GET'; function selecteCard() { $scope.selectedCard.card_name = cardName; $scope.selectedCard.card_color = cardColor; } beforeEach(angular.mock.module('lastLine.game')); beforeEach(angular.mock.inject(function ($rootScope, $controller, $compile) { $scope = $rootScope.$new(); controller = $controller; controller('game', {$scope: $scope}); var squareHtml = '<div id="square-0-0"></div>'; square = angular.element(squareHtml); square.attr('ng-class', "{highlightedSquare: highlightedSquares.indexOf('square-0-0') > -1}"); var compiled = $compile(square); compiled($scope); $scope.$digest(); })); beforeEach(angular.mock.inject(function ($rootScope, $controller, _$httpBackend_) { $httpBackend = _$httpBackend_; $httpBackend.when(createGameMethod, createGameUrl) .respond({ nextPlayer: { name: "Toto", id: "0" }, possibleCardsNextPlayer: [ { name: "King", color: "Red" } ] }); $httpBackend.when(viewPossibleMovementsMethod, viewPossibleMovementsUrl) .respond(["square-0-0", "square-1-1"]); $httpBackend.when(playMethod, playUrl) .respond({ newSquare: "#0-8", nextPlayer: { name: "Toto", id: "0" }, possibleCardsNextPlayer: [ { name: "King", color: "Red" } ] }); })); it('should have scope to be defined', function () { expect($scope).toBeDefined(); }); describe('viewPossibleMovements', function () { it('correct card selected', function () { $scope.viewPossibleMovements(cardName, cardColor); $httpBackend.flush(); expect($scope.selectedCard).toEqual({card_name: cardName, card_color: cardColor}); }); it('correct squares are highlighted', function () { $scope.viewPossibleMovements(cardName, cardColor); $httpBackend.flush(); expect($scope.highlightedSquares).toEqual(["square-0-0", "square-1-1"]); $scope.$digest(); expect(square.attr('class')).toContain('highlightedSquare'); }); }); describe('isSelected', function () { it('card should be selected', function () { selecteCard(); expect($scope.isSelected(cardName, cardColor)).toBe(true); }); it('card should not be selected', function () { // No card selected expect($scope.isSelected('cardName', 'cardColor')).toBe(false); // Inexistant card selected selecteCard(); expect($scope.isSelected('cardName', 'cardColor')).toBe(false); }); }); }); });
JavaScript
0
@@ -304,60 +304,9 @@ ares -?card_color=' + cardColor + '&card_name=' + cardName +' ;%0A @@ -1670,32 +1670,270 @@ %7D);%0A%0A + var viewPossibleMovementsParameters = %7Bcard_color: cardColor, card_name: cardName%7D;%0A var viewPossibleMovementsUrlWithParameters = setUrlParameters(viewPossibleMovementsUrl,%0A viewPossibleMovementsParameters);%0A $httpBac @@ -1995,16 +1995,30 @@ mentsUrl +WithParameters )%0A
8c38705cf69221c9903a25a9d938a41c8dab825e
Add RawConsoleLogger to output log records to console
handlers.js
handlers.js
var LEVELS = require('./levels'); var compileFormat = require('./utils/message'); /** * Basic handler. Does not actually handle anything. * Usefull for extensions and stubs. All implementors must implement _handle(record) * method. record instance shared among all handlers, do not modify it. * */ function NullHandler() { this._level = LEVELS.ALL; } NullHandler.prototype = { /** * Set max accepted log level for this handler * @param {string} level * @return {this} */ setLevel: function(level) { if(typeof level === 'string') { level = LEVELS[level.toUpperCase()]; } if(typeof level !== 'number' || !(level in LEVELS)) { throw new Error(level + ' does not exists'); } this._level = level; return this; }, _enabledFor: function(level) { return this._level <= level; }, handle: function(record) { if(this._enabledFor(record.level)) { this._handle(record); } }, _handle: function() { } }; module.exports.NullHandler = NullHandler; var DEFAULT_FORMAT = '%date %-5level %logger - %message%n%error'; /** * Used as base class for most handlers * All extensions should implement method `_handle(record)` */ function BaseHandler() { NullHandler.call(this); this.setFormat(DEFAULT_FORMAT); } BaseHandler.prototype = Object.create(NullHandler.prototype); /** * Set log record format for this handler. * Default record format is `[%date] %-5level %logger - %message%n%error` * * Possible parameters: * - `%d{FORMAT}` or `%date{FORMAT}` - how to format record timestamp. `{FORMAT}` is optional stftime string, by default it is `%Y/%m/%d %H:%M:%S,%L` * - `%pid` - output process.pid * - `%level` or `%le` or `%p` - output record level name like ERROR or WARN * - `%logger` or `%lo` or `%c` - output logger name * - `%%` - output % * - `%n` - output EOL * - `%err` or `%error` - output stack trace of passed error * - `%x` or `%x{field}` - output JSON.stringified value of context field * * Also available text decorators (now only colors): * - `%highlight(text)` - will decorate passed text with record level decorator * - `%cyan(text)` * - other colors * - `%cyan.bold(text)` * - other bold colors * * Example: `%date000 %highlight(%5level) %cyan(%logger) - %message%n%error` * * Also it is possible to set it to function. One of possible examples jsonFormat (`require('huzzah/json-format')` ). * It can accept the same serializers bunyan can accept and you will have json output at the end. * * @param {string|function} format - It is either formatted string as described, or function returning string and accepts just one argument log record * @return {this} */ BaseHandler.prototype.setFormat = function(format) { switch (typeof format) { case 'string': this.formatRecord = compileFormat(format); break; case 'function': this.formatRecord = format; break; default: throw new Error('`format` can be function or string'); } return this; }; module.exports.BaseHandler = BaseHandler; /** * Just simple console handler */ function ConsoleHandler() { BaseHandler.call(this); } ConsoleHandler.prototype = Object.create(BaseHandler.prototype); ConsoleHandler.prototype._handle = function(record) { var line = this.formatRecord(record); if(record.level > LEVELS.INFO) { process.stderr.write(line); } else { process.stdout.write(line); } }; module.exports.ConsoleHandler = ConsoleHandler; /** * Allow to pass records to stream */ function StreamHandler() { BaseHandler.call(this); this.setShouldFormat(true); } StreamHandler.prototype = Object.create(BaseHandler.prototype); StreamHandler.prototype._handle = function(record) { var out = this._shouldFormat ? this.formatRecord(record) : record; this._stream.write(out); }; /** * Should we format record before passing to stream? By default it is true * @param {boolean} value * @return {this} */ StreamHandler.prototype.setShouldFormat = function(value) { this._shouldFormat = value; return this; }; /** * Stream to pass records * @param {WritableStream} stream * @return {this} */ StreamHandler.prototype.setStream = function(stream) { this._stream = stream; return this; }; module.exports.StreamHandler = StreamHandler;
JavaScript
0
@@ -3476,24 +3476,630 @@ leHandler;%0A%0A +/**%0A * Like ConsoleHandler but output whole record to console. This can be usefull%0A * in browser to see inspections.%0A */%0Afunction RawConsoleHandler() %7B%0A BaseHandler.call(this);%0A%7D%0A%0ARawConsoleHandler.prototype = Object.create(BaseHandler.prototype);%0ARawConsoleHandler.prototype._handle = function(record) %7B%0A if(record.level %3C LEVELS.INFO) %7B%0A console.log(record);%0A %7D else if (record.level %3C LEVELS.WARN) %7B%0A console.info(record);%0A %7D else if (record.level %3C LEVELS.ERROR) %7B%0A console.warn(record);%0A %7D else %7B%0A console.error(record);%0A %7D%0A%7D;%0A%0Amodule.exports.RawConsoleHandler = RawConsoleHandler;%0A%0A /**%0A * Allow
10bc0172efdfabd95c2c355883218e6cacfb055f
Add trivia
js/script.js
js/script.js
var trivia = [ "My favorite super hero is Spider-man.", "My favorite color is red (that's probably obvious).", "The first programming language I mastered was GML (Game Maker Language).", "I chose Bulbasaur as my first pokemon.", "I sang Mr. Grinch in a talent show; I didn't win.", "I have an army of Dwarfs.", "I've never seen Star Wars.", "I've hand made 2 bows and arrows.", "My favorite super hero movie is The Dark Knight.", "My favorite Chirstmas characters are The Grinch and Ebenezer Scrooge.", "Personally, I prefer Luigi to Mario.", "I can't whistle (yet).", "I have a bad habit of swallowing my gum (but I'm still alive).", "Captain America: Civil War was great, you should go see it!" ] $(document).ready(function() { slides(); projects(); $("#trivia").text(trivia[Math.floor(Math.random() * trivia.length)]); });
JavaScript
0.999411
@@ -731,16 +731,104 @@ see it!%22 +,%0D%0A %22The copyright statement at the bottom is only there to make the page look better.%22 %0D%0A%5D%0D%0A%0D%0A$
5ebcc15da506b87cb82d8dad853e363459a67d35
Add missing resolve parameter to refresh_all
src/ggrc/assets/javascripts/models/refresh_queue.js
src/ggrc/assets/javascripts/models/refresh_queue.js
/*! Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> Created By: [email protected] Maintained By: [email protected] */ (function(can, $) { /* RefreshQueue * * enqueue(obj, force=false) -> queue or null * trigger() -> Deferred */ can.Construct("ModelRefreshQueue", { }, { init: function(model) { this.model = model; this.ids = []; this.deferred = new $.Deferred(); this.triggered = false; this.completed = false; this.updated_at = Date.now(); } , enqueue: function(id) { if (this.triggered) return null; else { if (this.ids.indexOf(id) === -1) { this.ids.push(id); this.updated_at = Date.now(); } return this; } } , trigger: function() { var self = this; if (!this.triggered) { this.triggered = true; if (this.ids.length > 0) this.model.findAll({ id__in: this.ids.join(",") }).then(function() { self.completed = true; self.deferred.resolve(); }, function() { self.deferred.reject.apply(self.deferred, arguments); }); else { this.completed = true; this.deferred.resolve(); } } return this.deferred; } , trigger_with_debounce: function(delay, manager) { var ms_to_wait = (delay || 0) + this.updated_at - Date.now(); if (!this.triggered) { if (ms_to_wait < 0 && (!manager || manager.triggered_queues().length < 6)) this.trigger(); else setTimeout(this.proxy("trigger_with_debounce", delay, manager), ms_to_wait); } return this.deferred; } }); can.Construct("RefreshQueueManager", { model_bases: { // This won't work until Relatable/Documentable/etc mixins can handle // queries with multiple `type` values. // Regulation: 'Directive' //, Contract: 'Directive' //, Policy: 'Directive' //, Standard: 'Directive' //, System: 'SystemOrProcess' //, Process: 'SystemOrProcess' } }, { init: function() { this.null_queue = new ModelRefreshQueue(null); this.queues = []; } , triggered_queues: function() { return can.map(this.queues, function(queue) { if (queue.triggered) return queue; }); } , enqueue: function(obj, force) { var self = this , model = obj.constructor , model_name = model.shortName , found_queue = null , id = obj.id ; if (!obj.selfLink) { if (obj instanceof can.Model) { model_name = obj.constructor.shortName; } else if (obj.type) { // FIXME: obj.kind is to catch invalid stubs coming from Directives model_name = obj.type || obj.kind; } } model = CMS.Models[model_name]; if (this.constructor.model_bases[model_name]) { model_name = this.constructor.model_bases[model_name]; model = CMS.Models[model_name]; } if (!force) // Check if the ID is already contained in another queue can.each(this.queues, function(queue) { if (!found_queue && queue.model === model && queue.ids.indexOf(id) > -1) found_queue = queue; }); if (!found_queue) { can.each(this.queues, function(queue) { if (!found_queue && queue.model === model && !queue.triggered && queue.ids.length < 50) { found_queue = queue.enqueue(id); return false; } }); if (!found_queue) { found_queue = new ModelRefreshQueue(model); this.queues.push(found_queue) found_queue.enqueue(id); found_queue.deferred.done(function() { var index = self.queues.indexOf(found_queue); if (index > -1) self.queues.splice(index, 1); }); } } return found_queue; } }); can.Construct("RefreshQueue", { refresh_queue_manager: new RefreshQueueManager(), refresh_all: function(instance, props, force) { var dfd = new $.Deferred(); _refresh_all(instance, props, dfd); return dfd; // Helper function called recursively for each property function _refresh_all(instance, props, dfd) { var prop = props[0], next_props = props.slice(1), next = instance[prop], refresh_queue = new RefreshQueue(), dfds = [], deferred; if (next) { refresh_queue.enqueue(next, force); deferred = refresh_queue.trigger(); } else if (instance.get_binding) { next = instance.get_binding(prop); if (next) { deferred = next.refresh_list(); } } if (deferred) { deferred.then(function(refreshed_items) { if (next_props.length) { can.each(refreshed_items, function(item) { var d = new $.Deferred(); _refresh_all(item, next_props, d); dfds.push(d); }); // Resolve the original deferred only when all list deferreds // have been resolved $.when.apply($, dfds).then(function() { dfd.resolve(); }); return; } // All items were refreshed, resolve the deferred if (next.push || next.list) { // Last refreshed property was a list dfd.resolve(refreshed_items); } // Last refreshed property was a single instance, return it as such dfd.resolve(refreshed_items[0]); }); } else { console.warn("refresh_all failed at", prop); } } }, }, { init: function() { this.objects = []; this.queues = []; this.deferred = new $.Deferred(); this.triggered = false; this.completed = false; } , enqueue: function(obj, force) { var that = this; if (!obj) return; if (this.triggered) return null; if (obj.push) { can.each(obj, function(o) { that.enqueue(o, force); }); return this; } this.objects.push(obj); if (force || !obj.selfLink) { queue = this.constructor.refresh_queue_manager.enqueue(obj, force); if (this.queues.indexOf(queue) === -1) this.queues.push(queue); } return this; } , trigger: function(delay) { var self = this , deferreds = [] ; if (!delay) delay = 50; this.triggered = true; can.each(this.queues, function(queue) { deferreds.push(queue.trigger_with_debounce( 50, self.constructor.refresh_queue_manager)); }); if (deferreds.length > 0) $.when.apply($, deferreds).then(function() { self.deferred.resolve(can.map(self.objects, function(obj) { return obj.reify(); })); }, function() { self.deferred.reject.apply(self.deferred, arguments); }); else return this.deferred.resolve(this.objects); return this.deferred; } }); })(window.can, window.can.$);
JavaScript
0
@@ -5424,32 +5424,37 @@ ).then(function( +items ) %7B%0A @@ -5461,32 +5461,37 @@ dfd.resolve( +items );%0A
a29fe2e87d7518cb8fae2a5fc918076dfd096e65
Update script.js
js/script.js
js/script.js
$(document).ready(function() { $('.scroll-link').on('click', function(event){ event.preventDefault(); var sectionID = $(this).attr("data-id"); scrollToID('#' + sectionID, 750); }); if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { $(".timeline-text-container").on("click", function () { $(this).children(".timeline-hover-notice").hide(); $(this).children(".timeline-class-desc").slideToggle(); }); } else { $(".timeline-text-container").on("mouseenter", function () { $(this).children(".timeline-hover-notice").hide(); $(this).children(".timeline-class-desc").slideToggle(); }); $(".timeline-text-container").on("mouseleave", function () { $(this).children(".timeline-class-desc").slideToggle(); }); } navSetter('main'); navSetter('timeline'); navSetter('portfolio'); }); // scroll function function scrollToID(id, speed){ var targetOffset = $(id).offset().top -40; $('html,body').animate({scrollTop:targetOffset}, speed); } function navSetter(id) { var target = $("#"+id).offset().top -50, timeout = null; $(window).scroll(function () { if (!timeout) { timeout = setTimeout(function () { clearTimeout(timeout); timeout = null; if ($(window).scrollTop() >= target) { $(".nav").children().removeClass('active'); $("#nav-"+id).addClass('active'); } }, 250); } }); }
JavaScript
0.000002
@@ -451,24 +451,147 @@ %09%7D else %7B%0A%09%09 +$('.project').hover(function()%7B%0A%09%09%09$(this).find(%22.hover%22).slideToggle();%0A%09%09//$(this).find(%22.hover%22).fadeIn(300);%0A%09%09%7D);%0A%09%09/* $(%22.timeline @@ -886,16 +886,18 @@ );%0A%09%09%7D); +*/ %0A%09%7D%0A%0A%09na
70590c266ba3d20ad24ff6745cad277e79f65646
fix database update saga
app/sagas/databaseUpdate.js
app/sagas/databaseUpdate.js
import firebaseApp from '../api/firebase' import { eventChannel, buffers } from 'redux-saga' import { put, take } from 'redux-saga/effects' import { fetchDataSuccess, fetchDataFailure } from '../actions/index' export default function * databaseUpdate () { const chan = eventChannel(emit => { const connectionRef = firebaseApp.database().ref() connectionRef.on('value', snapshot => emit(snapshot.val())) // don't stop the channel return () => {} }, buffers.expanding(1)) while (true) { let data = yield take(chan) if (data) { yield put(fetchDataSuccess(data)) } else { yield put(fetchDataFailure(data)) } } }
JavaScript
0
@@ -86,16 +86,49 @@ x-saga'%0A +import %7B isEmpty %7D from 'lodash'%0A import %7B @@ -232,14 +232,8 @@ ions -/index '%0A%0Ae @@ -411,16 +411,87 @@ pshot =%3E + %7B%0A // emitted value can't be null when there are no recipes%0A emit(sn @@ -502,17 +502,29 @@ ot.val() -) + %7C%7C %7B%7D)%0A %7D )%0A // @@ -651,22 +651,32 @@ %0A if +(!isEmpty (data) +) %7B%0A
3f5b2580957e240d927ea5a362eddb932c64dd9b
Add youtube video to !w.lewd
src/commands/image/lewd.js
src/commands/image/lewd.js
/** * Created by Julian/Wolke on 15.11.2016. */ let RRACommand = require('../../structures/rraCommand'); class LewdImage extends RRACommand { constructor({t}) { super(); this.cmd = 'lewd'; this.cat = 'image'; this.needGuild = false; this.t = t; this.accessLevel = 0; } } module.exports = LewdImage;
JavaScript
0.000002
@@ -48,19 +48,46 @@ */%0A%0Alet -RRA +axios = require('axios');%0Alet Command @@ -118,12 +118,9 @@ res/ -rraC +c omma @@ -153,11 +153,8 @@ nds -RRA Comm @@ -306,16 +306,16 @@ .t = t;%0A - @@ -341,16 +341,492 @@ 0;%0A %7D +%0A%0A async run(msg) %7B%0A if (Math.random() %3E 0.7)%0A return await msg.channel.createMessage('https://www.youtube.com/watch?v=qr89xoZyE1g');%0A try %7B%0A let res = await axios.get('https://rra.ram.moe/i/r', %7B params: %7B %22type%22: this.cmd %7D %7D);%0A let path = res.data.path.replace('/i/', '');%0A await msg.channel.createMessage(%60https://cdn.ram.moe/$%7Bpath%7D%60);%0A %7D catch (e) %7B%0A return winston.error(e);%0A %7D%0A %7D %0A%7D%0Amodul
ec1e977084e805538951c52c14dfefa949a3e9ed
Fix "invalid weak map key" error when nodes in the layout inspector are empty strings
src/ui/components/elements-inspector/sidebar.js
src/ui/components/elements-inspector/sidebar.js
/** * Copyright 2018-present Facebook. * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * @format */ import type {Element} from './ElementsInspector.js'; import type {PluginClient} from '../../../plugin'; import type Client from '../../../Client.js'; import type Logger from '../../../fb-stubs/Logger.js'; import Panel from '../Panel.js'; import ManagedDataInspector from '../data-inspector/ManagedDataInspector.js'; import {Component} from 'react'; import {Console} from '../console'; import {GK} from 'flipper'; const deepEqual = require('deep-equal'); type OnValueChanged = (path: Array<string>, val: any) => void; type InspectorSidebarSectionProps = { data: any, id: string, onValueChanged: ?OnValueChanged, tooltips?: Object, }; class InspectorSidebarSection extends Component<InspectorSidebarSectionProps> { setValue = (path: Array<string>, value: any) => { if (this.props.onValueChanged) { this.props.onValueChanged([this.props.id, ...path], value); } }; shouldComponentUpdate(nextProps: InspectorSidebarSectionProps) { return ( !deepEqual(nextProps, this.props) || this.props.id !== nextProps.id || this.props.onValueChanged !== nextProps.onValueChanged ); } extractValue = (val: any, depth: number) => { if (val && val.__type__) { return { mutable: Boolean(val.__mutable__), type: val.__type__ === 'auto' ? typeof val.value : val.__type__, value: val.value, }; } else { return { mutable: typeof val === 'object', type: typeof val, value: val, }; } }; render() { const {id} = this.props; return ( <Panel heading={id} floating={false} grow={false}> <ManagedDataInspector data={this.props.data} setValue={this.props.onValueChanged ? this.setValue : undefined} extractValue={this.extractValue} expandRoot={true} collapsed={true} tooltips={this.props.tooltips} /> </Panel> ); } } type Props = {| element: ?Element, tooltips?: Object, onValueChanged: ?OnValueChanged, client: PluginClient, realClient: Client, logger: Logger, extensions?: Array<any>, |}; type State = {| isConsoleEnabled: boolean, |}; export class InspectorSidebar extends Component<Props, State> { state = { isConsoleEnabled: false, }; constructor(props: Props) { super(props); this.checkIfConsoleIsEnabled(); } componentDidUpdate(prevProps: Props, prevState: State) { if (prevProps.client !== this.props.client) { this.checkIfConsoleIsEnabled(); } } checkIfConsoleIsEnabled() { this.props.client .call('isConsoleEnabled') .then((result: {isEnabled: boolean}) => { this.setState({isConsoleEnabled: result.isEnabled}); }); } render() { const {element, extensions} = this.props; if (!element || !element.data) { return null; } const sections = (extensions && /* $FlowFixMe(>=0.86.0) This * comment suppresses an error found when Flow v0.86 was * deployed. To see the error, delete this comment and * run Flow. */ extensions.map(ext => ext( this.props.client, this.props.realClient, element.id, this.props.logger, ), )) || []; for (const key in element.data) { if (key === 'Extra Sections') { for (const extraSection in element.data[key]) { let data = element.data[key][extraSection]; // data might be sent as stringified JSON, we want to parse it for a nicer persentation. if (typeof data === 'string') { try { data = JSON.parse(data); } catch (e) { // data was not a valid JSON, using string instead } } sections.push( <InspectorSidebarSection tooltips={this.props.tooltips} key={extraSection} id={extraSection} data={data} onValueChanged={this.props.onValueChanged} />, ); } } else { sections.push( <InspectorSidebarSection tooltips={this.props.tooltips} key={key} id={key} data={element.data[key]} onValueChanged={this.props.onValueChanged} />, ); } } if (GK.get('sonar_show_console_plugin') && this.state.isConsoleEnabled) { sections.push( <Panel heading="JS Console" floating={false} grow={false}> <Console client={this.props.client} getContext={() => element.id} /> </Panel>, ); } return sections; } }
JavaScript
0.000825
@@ -3935,28 +3935,195 @@ ON, -using string instead +type is required to be an object%0A console.error(%0A %60ElementsInspector unable to parse extra section: $%7BextraSection%7D%60,%0A );%0A data = %7B%7D; %0A
a6e47e408f9988f73993b84fa3d32b9dc45c1bc6
add lazy-load margin so images load 100px below fold
js/agency.js
js/agency.js
$(document).ready(function() { $("#texty").addClass("scrolling"); var topBtn = false; $("body").scroll(function() { if ($("#cor").isInViewport()) { $("#cor").addClass("slideLeft"); } else if ($("#tow").isInViewport()) { $("#tow").addClass("slideRight"); } else if ($("#sky").isInViewport()) { $("#sky").addClass("slideLeft"); } else if ($("#bud").isInViewport()) { $("#bud").addClass("slideRight"); } else if ($("#hay").isInViewport()) { $("#hay").addClass("slideLeft"); } else if ($("#hill").isInViewport()) { $("#hill").addClass("slideRight"); } else if ($("#cen").isInViewport()) { $("#cen").addClass("slideLeft"); } else if ($("#chq").isInViewport()) { $("#chq").addClass("slideLeft"); } else if ($("#portfolio").isInViewport()) { $("#portfolio").addClass("fade"); } if (document.body.scrollTop < 250) { if (document.getElementById("top-btn").classList.contains("in")) { document.getElementById("top-btn").classList.remove("in"); } } if (document.body.scrollTop >= 250) { if (!document.getElementById("top-btn").classList.contains("in")) { document.getElementById("top-btn").classList.add("in"); } } }); // window.addEventListener('resize', function(){ // if(window.innerWidth > 568){ // } // }); // Smooth scrolling using jQuery easing // $('a[href*="#"]:not([href="#"]:not([href*="#portfolioModal"]))').click( // function() { // if ( // location.pathname.replace(/^\//, "") == // this.pathname.replace(/^\//, "") && // location.hostname == this.hostname // ) { // var target = $(this.hash); // target = target.length ? target : $("[name=" + this.hash.slice(1) + "]"); // if (target.length) { // $("html, body").animate( // { // scrollTop: target.offset().top // }, // 800, // "easeInOutExpo" // ); // return false; // } // } // } // ); // function scrollFunction() { // document.body.scrollTop > 250 ? document.getElementById("top-btn").style.display = "flex" : document.getElementById("top-btn").style.display = "none"; // console.log('scrollFunction') // } // function topFunction() { // (document.body.scrollTop = 0), (document.documentElement.scrollTop = 0); // console.log('topFunction') // } // (window.onscroll = function() { // scrollFunction(); // }) $(document).scrollTop() > 250 && (document.getElementById("top-btn").style.display = "flex"), $("#top-btn").on("click", function() { $(".top-link").trigger("click"); }), $('a[href*="#"]') .not('[href="#"]') .not('[href="#0"]') .click(function(e) { if ( location.pathname.replace(/^\//, "") == this.pathname.replace(/^\//, "") && location.hostname == this.hostname ) { var t = $(this.hash); (t = t.length ? t : $("[name=" + this.hash.slice(1) + "]")), t.length && (e.preventDefault(), $("html, body").animate( { scrollTop: t.offset().top }, 1e3, function() { var e = $(t); return ( e.focus(), !e.is(":focus") && (e.attr("tabindex", "-1"), void e.focus()) ); } )); } }); $.fn.isInViewport = function() { var tony = $(this); if (tony.offset() !== undefined) { var elementTop = $(this).offset().top; var elementBottom = elementTop + $(this).outerHeight(); var viewportTop = $(window).scrollTop(); var viewportBottom = viewportTop + $(window).height(); return elementBottom > viewportTop && elementTop < viewportBottom; } }; }); // End of use strict function BackgroundNode(_ref) { var node = _ref.node, loadedClassName = _ref.loadedClassName; var src = node.getAttribute("data-background-image-url"); var show = function show(onComplete) { requestAnimationFrame(function() { node.style.backgroundImage = "url(" + src + ")"; node.classList.add(loadedClassName); onComplete(); }); }; return { node: node, // onComplete is called after the image is done loading. load: function load(onComplete) { var img = new Image(); img.onload = show(onComplete); img.src = src; } }; } var defaultOptions = { selector: "[data-background-image-url]", loadedClassName: "loaded" }; function BackgroundLazyLoader() { var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultOptions, selector = _ref2.selector, loadedClassName = _ref2.loadedClassName; var nodes = [].slice .apply(document.querySelectorAll(selector)) .map(function(node) { return new BackgroundNode({ node: node, loadedClassName: loadedClassName }); }); var callback = function callback(entries, observer) { entries.forEach(function(_ref3) { var target = _ref3.target, isIntersecting = _ref3.isIntersecting; if (!isIntersecting) { return; } var obj = nodes.find(function(it) { return it.node.isSameNode(target); }); if (obj) { obj.load(function() { // Unobserve the node: observer.unobserve(target); // Remove this node from our list: nodes = nodes.filter(function(n) { return !n.node.isSameNode(target); }); // If there are no remaining unloaded nodes, // disconnect the observer since we don't need it anymore. if (!nodes.length) { observer.disconnect(); } }); } }); }; var observer = new IntersectionObserver(callback); nodes.forEach(function(node) { return observer.observe(node.node); }); } BackgroundLazyLoader(); var fontsUsed = [ "Questrial", "Fjalla One", "Roboto Slab", "Helvetica Neue", "Helvetica", "Arial", "sans-serif", "Montserrat", ]
JavaScript
0
@@ -6046,19 +6046,68 @@ callback +, %7B%0A rootMargin: %22200px%22,%0A threshold: 0%0A %7D );%0A - nodes. @@ -6208,160 +6208,4 @@ ();%0A -%0A%0Avar fontsUsed = %5B%0A %22Questrial%22,%0A %22Fjalla One%22, %0A %22Roboto Slab%22, %0A %22Helvetica Neue%22, %0A %22Helvetica%22, %0A %22Arial%22, %0A %22sans-serif%22, %0A %22Montserrat%22, %0A %5D
34fd1b9b81c2d248cafce92e02c14af3d79b60c2
Put brackets around a statement to ensure proper order and combinations.
src/api/property.js
src/api/property.js
import assignSafe from '../util/assign-safe'; import dashCase from '../util/dash-case'; import data from '../util/data'; import maybeThis from '../util/maybe-this'; import notify from './notify'; // TODO: Lean out option normalisation. function property (name, prop) { var internalGetter, internalSetter, internalValue, isBoolean; if (typeof prop === 'object') { prop = assignSafe({}, prop); } else { prop = { type: prop }; } if (prop.attr === true) { prop.attr = dashCase(name); } if (prop.notify === undefined) { prop.notify = true; } if (typeof prop.type !== 'function') { prop.type = val => val; } if (prop.init !== undefined && typeof prop.init !== 'function') { let value = prop.init; prop.init = () => value; } internalGetter = prop.get; internalSetter = prop.set; isBoolean = prop.type && prop.type === Boolean; prop.get = function () { return internalGetter ? internalGetter.apply(this) : internalValue; }; prop.set = function (value) { var info = data(this); // If the property is being updated and it is a boolean we must just check // if the attribute exists because "" is true for a boolean attribute. if (info.updatingProperty && isBoolean) { value = this.hasAttribute(prop.attr); } // We report both new and old values; var newValue = prop.type(value); var oldValue = this[name]; // TODO: Should we check at this point to see if it has changed and do // nothing if it hasn't? How can we then force-update if we need to? // Regardless of any options, we store the value internally. internalValue = newValue; // We check first to see if we're already updating the property from // the attribute. If we are, then there's no need to update the attribute // especially because it would invoke an infinite loop. if (prop.attr && !info.updatingProperty) { info.updatingAttribute = true; if (isBoolean && internalValue) { this.setAttribute(prop.attr, ''); } else if (internalValue == null || isBoolean && !internalValue) { this.removeAttribute(prop.attr, ''); } else { this.setAttribute(prop.attr, internalValue); } info.updatingAttribute = false; } // A setter is responsible for setting its own value. We still store the // value internally because the default getter may still be used to return // that value. Even if it's not, we use it to reference the old value which // is useful information for the setter. if (internalSetter) { internalSetter.call(this, newValue, oldValue); } if (prop.notify) { notify(this, name, { newValue: newValue, oldValue: oldValue }); } }; return prop; } function defineProperty (elem, name, prop) { // We don't need to scope the data to the component ID be cause if multiple // bindings on the same component define the same attribute, then they'd // conflict anyways. var info = data(elem); if (!info.attributeToPropertyMap) { info.attributeToPropertyMap = {}; } prop = property(name, prop); Object.defineProperty(elem, name, prop); // TODO: What happens if the setter does something with a descendant that // may not exist yet? // // Initialise the value if a initial value was provided. Attributes that exist // on the element should trump any default values that are provided. if (prop.init !== undefined && !prop.attr || !elem.hasAttribute(prop.attr)) { elem[name] = prop.init.call(elem); } // This ensures that the corresponding attribute will know to update this // property when it is set. if (prop.attr) { info.attributeToPropertyMap[prop.attr] = name; } } function defineProperties (elem, props) { Object.keys(props).forEach(function (name) { defineProperty(elem, name, props[name]); }); } export default maybeThis(function (elem, props = {}, prop = {}) { if (typeof props === 'string') { defineProperty(elem, props, prop); } else { defineProperties(elem, props); } });
JavaScript
0
@@ -3457,33 +3457,20 @@ op.init -!== undefined && +( !prop.at @@ -3505,16 +3505,17 @@ p.attr)) +) %7B%0A e
8193f309dc9c8d434e4244085496e65edc7b7165
Update comment/documentation
lib/OpenLayers/Format/XML/VersionedOGC.js
lib/OpenLayers/Format/XML/VersionedOGC.js
/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the 2-clause BSD license. * See license.txt in the OpenLayers distribution or repository for the * full text of the license. */ /** * @requires OpenLayers/Format/XML.js * @requires OpenLayers/Format/OGCExceptionReport.js */ /** * Class: OpenLayers.Format.XML.VersionedOGC * Base class for versioned formats, i.e. a format which supports multiple * versions. * * Inherits from: * - <OpenLayers.Format.XML> */ OpenLayers.Format.XML.VersionedOGC = OpenLayers.Class(OpenLayers.Format.XML, { /** * APIProperty: defaultVersion * {String} Version number to assume if none found. */ defaultVersion: null, /** * APIProperty: version * {String} Specify a version string if one is known. */ version: null, /** * APIProperty: profile * {String} If provided, use a custom profile. */ profile: null, /** * APIProperty: allowFallback * {Boolean} If a profiled parser cannot be found for the returned version, * use a non-profiled parser as the fallback. Application code using this * should take into account that the return object structure might be * missing the specifics of the profile. Defaults to false. */ allowFallback: false, /** * APIProperty: errorProperty * {String} Which property of the returned object to check for in order to * determine whether or not parsing has failed. In the case that the * errorProperty is undefined on the returned object, the document will be * run through an OGCExceptionReport parser. */ errorProperty: null, /** * Property: name * {String} The name of this parser, this is the part of the CLASS_NAME * except for "OpenLayers.Format." */ name: null, /** * APIProperty: stringifyOutput * {Boolean} If true, write will return a string otherwise a DOMElement. * Default is false. */ stringifyOutput: false, /** * Property: parser * {Object} Instance of the versioned parser. Cached for multiple read and * write calls of the same version. */ parser: null, /** * Constructor: OpenLayers.Format.XML.VersionedOGC. * Constructor. * * Parameters: * options - {Object} Optional object whose properties will be set on * the object. */ initialize: function(options) { OpenLayers.Format.XML.prototype.initialize.apply(this, [options]); var className = this.CLASS_NAME; this.name = className.substring(className.lastIndexOf(".")+1); }, /** * Method: getVersion * Returns the version to use. Subclasses can override this function * if a different version detection is needed. * * Parameters: * root - {DOMElement} * options - {Object} Optional configuration object. * * Returns: * {String} The version to use. */ getVersion: function(root, options) { var version; // read if (root) { version = this.version; if(!version) { version = root.getAttribute("version"); if(!version) { version = this.defaultVersion; } } } else { // write version = (options && options.version) || this.version || this.defaultVersion; } return version; }, /** * Method: getParser * Get an instance of the cached parser if available, otherwise create one. * * Parameters: * version - {String} * * Returns: * {<OpenLayers.Format>} */ getParser: function(version) { version = version || this.defaultVersion; var profile = this.profile ? "_" + this.profile : ""; if(!this.parser || this.parser.VERSION != version) { var format = OpenLayers.Format[this.name][ "v" + version.replace(/\./g, "_") + profile ]; if(!format) { if (profile !== "" && this.allowFallback) { // fallback to the non-profiled version of the parser profile = ""; format = OpenLayers.Format[this.name][ "v" + version.replace(/\./g, "_") ]; } if (!format) { throw "Can't find a " + this.name + " parser for version " + version + profile; } } this.parser = new format(this.options); } return this.parser; }, /** * APIMethod: write * Write a document. * * Parameters: * obj - {Object} An object representing the document. * options - {Object} Optional configuration object. * * Returns: * {String} The document as a string */ write: function(obj, options) { var version = this.getVersion(null, options); this.parser = this.getParser(version); var root = this.parser.write(obj, options); if (this.stringifyOutput === false) { return root; } else { return OpenLayers.Format.XML.prototype.write.apply(this, [root]); } }, /** * APIMethod: read * Read a doc and return an object representing the document. * * Parameters: * data - {String | DOMElement} Data to read. * options - {Object} Options for the reader. * * Returns: * {Object} An object representing the document. */ read: function(data, options) { if(typeof data == "string") { data = OpenLayers.Format.XML.prototype.read.apply(this, [data]); } var root = data.documentElement; var version = this.getVersion(root); this.parser = this.getParser(version); // Select the parser var obj = this.parser.read(data, options); // Parse the data var errorProperty = this.parser.errorProperty || null; if (errorProperty !== null && obj[errorProperty] === undefined) { // an error must have happened, so parse it and report back var format = new OpenLayers.Format.OGCExceptionReport(); obj.error = format.read(data); } obj.version = version; return obj; }, CLASS_NAME: "OpenLayers.Format.XML.VersionedOGC" });
JavaScript
0
@@ -484,16 +484,505 @@ rsions.%0A + *%0A * To enable checking if parsing succeeded, you will need to define a property%0A * called errorProperty on the parser you want to check. The parser will then%0A * check the returned object to see if that property is present. If it is, it%0A * assumes the parsing was successful. If it is not present (or is null), it will%0A * pass the document through an OGCExceptionReport parser.%0A * %0A * If errorProperty is undefined for the parser, this error checking mechanism%0A * will be disabled.%0A *%0A *%0A * %0A * I @@ -1865,364 +1865,8 @@ e,%0A%0A - /**%0A * APIProperty: errorProperty%0A * %7BString%7D Which property of the returned object to check for in order to%0A * determine whether or not parsing has failed. In the case that the%0A * errorProperty is undefined on the returned object, the document will be%0A * run through an OGCExceptionReport parser.%0A */%0A errorProperty: null,%0A%0A
36e30170acb856d092c689cc90bd3adf0fa401db
Update arrays.js
js/arrays.js
js/arrays.js
// --------------------------------------------------------------- // Arrays // @Author: Mark McCann // @License: None, Public Domain // --------------------------------------------------------------- /** * removes duplicates from an array * @param {array} array * @return {array} */ var uniqueArray = function (array) { var a = array.concat(); for(var i=0; i < a.length; ++i) { for(var j=i+1; j<a.length; ++j) { if(a[i] === a[j]) { a.splice(j--, 1); } } } return a; } /** * check to see if object exists in an array * @param {array} array - haystack * @param {anything} obj - needle * @return {array} */ var contains = function (a, obj) { var i = a.length; while (i--) { if (a[i] === obj) { return true; } } return false; } /** * checks to see if variable is an array * @param {array} a * @return {boolean} */ var isArray = function ( a ) { return (Object.prototype.toString.call( a ) === '[object Array]'); } // IE9+ Version Array.isArray( a );
JavaScript
0.000001
@@ -1078,8 +1078,345 @@ y( a );%0A +%0A/**%0A * loops through an array runs callback and passes in key and value%0A * @param %7Barray%7D the array%0A * @param %7Bfunction%7D callback function%0A * @param %7Bobject%7D optional scope parameter %0A */%0Avar forEach = function ( array, callback, scope ) %7B%0A for (var i = 0; i %3C array.length; i++) %7B%0A callback.call(scope, i, array%5Bi%5D);%0A %7D%0A%7D%0A
b4266b7eaca3604223fa0fca4b7e1dc33bb4d669
check validation of token first
src/javascript/binary/static/virtual_acc_opening.js
src/javascript/binary/static/virtual_acc_opening.js
pjax_config_page("new_account/virtualws", function(){ return { onLoad: function() { if (getCookieItem('login')) { window.location.href = page.url.url_for('user/my_accountws'); return; } Content.populate(); var virtualForm = $('#virtual-form'); handle_residence_state_ws(); BinarySocket.send({residence_list:1}); var form = document.getElementById('virtual-form'); var errorPassword = document.getElementById('error-password'), errorRPassword = document.getElementById('error-r-password'), errorResidence = document.getElementById('error-residence'), errorAccount = document.getElementById('error-account-opening'), errorVerificationCode = document.getElementById('error-verification-code'); if (isIE() === false) { $('#password').on('input', function() { $('#password-meter').attr('value', testPassword($('#password').val())[0]); }); } else { $('#password-meter').remove(); } if (form) { virtualForm.submit( function(evt) { evt.preventDefault(); var verificationCode = document.getElementById('verification-code').value, residence = document.getElementById('residence').value, password = document.getElementById('password').value, rPassword = document.getElementById('r-password').value; Validate.errorMessageResidence(residence, errorResidence); Validate.errorMessageToken(verificationCode, errorVerificationCode); Validate.hideErrorMessage(errorAccount); if (Validate.errorMessagePassword(password, rPassword, errorPassword, errorRPassword) && !Validate.errorMessageResidence(residence, errorResidence)){ BinarySocket.init({ onmessage: function(msg){ var response = JSON.parse(msg.data); if (response) { var type = response.msg_type; var error = response.error; if (type === 'new_account_virtual' && !error){ // set a flag to push to gtm in my_account localStorage.setItem('new_account', '1'); document.getElementById('email').value = response.new_account_virtual.email; form.setAttribute('action', '/login'); form.setAttribute('method', 'POST'); virtualForm.unbind('submit'); form.submit(); } else if (type === 'error' || error) { if (error.code === 'InvalidToken') { virtualForm.empty(); $('.notice-message').remove(); var noticeText = '<p>' + Content.localize().textClickHereToRestart.replace('[_1]', page.url.url_for('')) + '</p>'; virtualForm.html(noticeText); return; } else if (error.code === 'PasswordError') { errorAccount.textContent = text.localize('Password is not strong enough.'); } else if (error.message) { errorAccount.textContent = error.message; } Validate.displayErrorMessage(errorAccount); } } } }); VirtualAccOpeningData.getDetails(password, residence, verificationCode); } }); } } }; });
JavaScript
0
@@ -1807,16 +1807,83 @@ sidence) + && Validate.validateToken(verificationCode, errorVerificationCode) )%7B%0A
bb1256dfc57de2af57295b4d02e1b33da5dc4ceb
Add move to top logic.
src/focus/controlbar.js
src/focus/controlbar.js
console.log( "=== simpread focus controlbar load ===" ) var fcontrol = ( function() { var template = '<div class="ks-simpread-constrolbar">\ <ul>\ <li><span class="topicon"></span></li>\ <li><span class="settingicon"></span></li>\ <li><span class="closeicon"></span></li>\ </ul>\ </div>'; function FControl() { this.$parent = null; this.$target = null; } /* Add focus constrol bar */ FControl.prototype.Render = function( root ) { console.log( "=== simpread focus controlbar add ===" ); this.$parent = $(root); $( root ).append( template ); this.$target = $( ".ks-simpread-constrolbar" ).find( "span" ); addStyle( this.$target ); addEventHandler( this.$target, root ); } /* Remove focus constrol bar */ FControl.prototype.Remove = function() { console.log( "=== simpread focus controlbar remove ===" ); this.$target.off( "click" ); this.$target.remove(); } /* Add focus constrol bar style */ function addStyle( $target ) { var path = chrome.extension.getURL("/"); $($target[0]).attr( "style", "background-image:url(" + path + "assets/images/top.png)" ); $($target[1]).attr( "style", "background-image:url(" + path + "assets/images/setting.png)" ); $($target[2]).attr( "style", "background-image:url(" + path + "assets/images/close.png)" ); } /* Add focus constrol bar event */ function addEventHandler( $target, root ) { $target.click( function( event) { switch ( $(event.currentTarget).attr( "class" ) ) { case "topicon": console.log("==== focus control top active ====") break; case "settingicon": console.log("==== focus control setting active ====") break; case "closeicon": console.log("==== focus control close active ====") $(root).click(); break; } }) } return new FControl(); })();
JavaScript
0
@@ -88,16 +88,31 @@ var +timer,%0A template @@ -1917,32 +1917,63 @@ p active ====%22)%0A + moveTop();%0A @@ -1975,32 +1975,32 @@ break;%0A - @@ -2314,16 +2314,820 @@ %7D) +;%0A /*$( document ).scroll( function( event ) %7B%0A var osTop = document.body.scrollTop;%0A if ( osTop %3E= document.documentElement.clientHeight ) %7B%0A $target.find( %22span%22 ).hide();%0A %7Delse%7B%0A $target.find( %22span%22 ).show();%0A %7D%0A if( !isTop ) %7B%0A clearInterval( timer );%0A %7D%0A isTop = false;%0A %7D);*/%0A %7D%0A%0A /*%0A Move top%0A */%0A function moveTop() %7B%0A timer = setInterval( function() %7B%0A var osTop = document.body.scrollTop;%0A var speed = Math.floor( -osTop / 3 );%0A document.body.scrollTop = osTop + speed;%0A isTop = true;%0A if( osTop == 0 ) %7B%0A clearInterval( timer );%0A %7D%0A %7D, 30 ); %0A %7D%0A%0A @@ -3157,10 +3157,9 @@ ();%0A + %7D)(); -%0A
96ad6333ef8c595a3fa4b1885711c55ecc76b4ed
Abort creating geofences if no triggers are found
js/api/Geofencing.js
js/api/Geofencing.js
import _ from 'lodash'; import Store from '../data/Store'; import realm from '../data/Realm'; import { BackgroundGeolocation } from './BackgroundProcess'; import { loadCachedGeofenceTriggers } from './Triggers'; import { showToast, notifyOnBackground } from './Notifications'; // Cache a MapPage component for to update when geofencing triggers are crossed. let activeMap = null; // Timer to suppress repeated notifications when geofences get updated. let supressNotificationsTimestamp = 0; /** * Event function for when geofences are entered, exited, or dwelled on. * @param {objects} params Parameters provided by the crossed geofence */ export function crossGeofence(params) { console.log(`Geofence crossed: ${params.action} - ${params.identifier}`); // Update Map if (activeMap && activeMap.active) { activeMap.updateMarkers(params); } try { const trigger = realm.objects('GeofenceTrigger').filtered(`id = "${params.identifier}"`)[0]; if (trigger) { // Notify on entry if (_.lowerCase(params.action) === 'enter' && supressNotificationsTimestamp < Date.now()) { const form = realm.objects('Form').filtered(`id = "${trigger.formId}"`)[0]; const survey = realm.objects('Survey').filtered(`id = "${trigger.surveyId}"`)[0]; if (form && survey) { notifyOnBackground(`${form.title} - New geofence form available.`, true); showToast(form.title, 'New geofence form available.', 'globe', 8, () => { Store.navigator.push({ path: 'form', title: survey.title, forms: form, survey: survey, type: 'geofence', }); }); // Supress local notifications in case the API receives multiple geofence crossing events in rapid succession. supressNotificationsTimestamp = Date.now() + 500; } } // Update Geofence Trigger realm.write(() => { trigger.triggered = true; trigger.inRange = _.lowerCase(params.action) !== 'exit'; trigger.updateTimestamp = Date.now(); }); } else { console.warn('Trigger not found.'); } } catch (e) { console.warn(e); } } /** * Caches a MapPage component inside a variable for easy access * @param {element} component React class element to be cached */ export function setActiveMap(component) { activeMap = component; BackgroundGeolocation.on('geofence', crossGeofence); } /** * Clears and deactivates the currently cached map element * @param {element} component React class element to be cleared */ export function clearActiveMap(component) { if (activeMap === component) { component.active = false; activeMap = null; } } /** * Erases all active geofences in the native geofencing api. * @param {Function} callback Callback function to execute afterwards. */ export function resetGeofences(callback) { supressNotificationsTimestamp = Date.now() + 5000; BackgroundGeolocation.removeGeofences(() => { console.log('Cleared current geofencing settings.'); callback(); }, (err) => { console.warn('Error resetting geofencing settings.'); console.warn(err); callback(err); } ); } /** * Creates native geofence objects using the 3rd-party geolocation library. * Erases previous set of native geofences and adds new ones based on geofence triggers. */ export function setupGeofences(callback) { // BackgroundGeolocation.stop() loadCachedGeofenceTriggers({excludeCompleted: true}, (err, response) => { resetGeofences((err2) => { if (err2) { console.warn('Unable to load geofence triggers'); console.warn(err2); return; } const triggerGeofences = response.map((trigger) => { return { identifier: trigger.id, radius: trigger.radius, latitude: trigger.latitude, longitude: trigger.longitude, notifyOnEntry: true, notifyOnExit: true, notifyOnDwell: true, loiteringDelay: 30000, }; }); console.log(`Adding ${triggerGeofences.length} geofences...`); supressNotificationsTimestamp = Date.now() + 5000; BackgroundGeolocation.addGeofences(triggerGeofences, () => { console.log('Successfully added geofences.'); }, (err3) => { console.warn('Failed to add geofences.', err3); }); if (callback) { callback(); } }); BackgroundGeolocation.on('geofence', crossGeofence); }); } /** * Adds a single geofence to the native geolocation API. * @param {object} trigger Realm 'Trigger' object containing the geofence's required data. */ export function addGeofence(trigger) { const geofence = { identifier: trigger.id, radius: trigger.radius, latitude: trigger.latitude, longitude: trigger.longitude, notifyOnEntry: true, notifyOnExit: true, notifyOnDwell: false, loiteringDelay: 60000, }; supressNotificationsTimestamp = Date.now() + 5000; BackgroundGeolocation.addGeofence(geofence, () => { console.log('Successfully added geofence.'); BackgroundGeolocation.on('geofence', crossGeofence); }, (error) => { console.warn('Failed to add geofence.', error); }); } /** * Removes a Geofence from the background check * @param {string} id Geofence indentifier */ export function removeGeofenceById(id) { supressNotificationsTimestamp = Date.now() + 5000; BackgroundGeolocation.removeGeofence(id, () => { console.log(`Removed geofence: ${id}`); }); } /** * Returns an object containing last recorded geolocation data via an async callback * @param {Function} callback Returns object containing the current latitude, longitude, accuracy, and timestamp. */ export function getUserLocationData(callback) { let coords = { latitude: 0, longitude: 0, accuracy: 0, timestamp: new Date(), }; if (Store.backgroundServiceState === 'deactivated') { console.log('deactivated, returning blank data'); callback(coords); return; } try { BackgroundGeolocation.getLocations((locations) => { const current = locations[0]; if (current && current.coords) { coords = { latitude: current.coords.latitude, longitude: current.coords.longitude, accuracy: current.coords.accuracy, timestamp: current.timestamp, }; callback(coords); } else { callback(coords); } }, () => { callback(coords); }); } catch (e) { callback(coords); } } /** * Dev: logs a list of the currently active geofences in the native API. */ export function logActiveGeofences() { BackgroundGeolocation.getGeofences((geofences) => { console.log('active geofences: '); console.log(geofences); }); }
JavaScript
0
@@ -4172,16 +4172,208 @@ s...%60);%0A + if (triggerGeofences.length === 0) %7B%0A console.log(%60Unable to add geofences: No triggers found.%60);%0A if (callback) %7B%0A callback();%0A %7D%0A return;%0A %7D%0A%0A su
4a02bd15057030b956c53102cf3c4f250dbb84e9
use array funciton
src/getLatestVersion.js
src/getLatestVersion.js
/** * Created by kimxogus on 2016. 12. 15.. */ import { isNil, defaultsDeep } from "lodash"; import { Platform } from "react-native"; import Native from "./native"; let latestVersion; // Used by iOS Only let appName; let appID; export function setAppName(_appName) { appName = _appName; } export function setAppID(_appID) { appID = _appID; } export const defaultOption = { forceUpdate: false, url: null, fetchOptions: { timeout: 5000 } }; export function getLatestVersion(option) { option = defaultsDeep(option, defaultOption); if (isNil(option.url)) { option.url = getStoreUrl(); // To prevent getStore to be executed when it's not needed. } if (!option.forceUpdate && !isNil(latestVersion)) { return Promise.resolve(latestVersion); } else { return getLatestVersionFromUrl(option.url, option.fetchOptions); } } function getStoreUrl() { if (Platform.OS === "ios" && (!appName || !appID)) { throw new Error("'appName' or 'appID' is undefined.\nSet those values correctly using 'setAppName()' and 'setAppID()'"); } return Platform.select({ android: "https://play.google.com/store/apps/details?id=" + Native.getPackageName(), ios: "https://itunes.apple.com/" + Native.getCountry() + "/app/" + appName + "/id" + appID }); } const MARKETVERSION_STARTTOKEN = "softwareVersion\">"; const MARKETVERSION_STARTTOKEN_LENGTH = MARKETVERSION_STARTTOKEN.length; const MARKETVERSION_ENDTOKEN = "<"; function getLatestVersionFromUrl(url, fetchOptions) { return fetch(url, fetchOptions) .then(res => { return res.text(); }) .then((text) => { const indexStart = text.indexOf(MARKETVERSION_STARTTOKEN); if (indexStart === -1) { latestVersion = text.trim(); return Promise.resolve(latestVersion); } text = text.substr(indexStart + MARKETVERSION_STARTTOKEN_LENGTH); const indexEnd = text.indexOf(MARKETVERSION_ENDTOKEN); if (indexEnd === -1) { return Promise.reject("Parse error."); } text = text.substr(0, indexEnd); latestVersion = text.trim(); return Promise.resolve(latestVersion); }); }
JavaScript
0.006988
@@ -1556,23 +1556,8 @@ s =%3E - %7B%0A return res @@ -1563,23 +1563,16 @@ s.text() -;%0A %7D )%0A .t @@ -1579,14 +1579,12 @@ hen( -( text -) =%3E
a0c23fbb3b6262d80ebae0d98d98b59870e31710
add a conditional for armatureScale in skeletal animation
src/library_animations/parse-skeletal-animations.js
src/library_animations/parse-skeletal-animations.js
var mat4Multiply = require('gl-mat4/multiply') var mat4Scale = require('gl-mat4/scale') var mat4Transpose = require('gl-mat4/transpose') module.exports = ParseLibraryAnimations // TODO: parse interpolation // TODO: Don't hard code attribute location // TODO: Don't assume that joint animations are in order // TODO: Inefficient. use depth first traversal function ParseLibraryAnimations (library_animations, jointBindPoses, visualSceneData) { var animations = library_animations[0].animation var allKeyframes = {} var keyframeJointMatrices = {} var jointRelationships = visualSceneData.jointRelationships var armatureScale = visualSceneData.armatureScale // First pass.. get all the joint matrices animations.forEach(function (anim, animationIndex) { if (anim.$.id.indexOf('pose_matrix') !== -1) { // TODO: Is this the best way to get an animations joint target? var animatedJointName = anim.channel[0].$.target.split('/')[0] var currentKeyframes = anim.source[0].float_array[0]._.split(' ').map(Number) var currentJointPoseMatrices = anim.source[1].float_array[0]._.split(' ').map(Number) currentKeyframes.forEach(function (_, keyframeIndex) { keyframeJointMatrices[currentKeyframes[keyframeIndex]] = keyframeJointMatrices[currentKeyframes[keyframeIndex]] || {} var currentJointMatrix = currentJointPoseMatrices.slice(16 * keyframeIndex, 16 * keyframeIndex + 16) if (!jointRelationships[animatedJointName].parent) { // apply library visual scene transformations to top level parent joint(s) mat4Scale(currentJointMatrix, currentJointMatrix, armatureScale) } keyframeJointMatrices[currentKeyframes[keyframeIndex]][animatedJointName] = currentJointMatrix }) } }) // Second pass.. Calculate world matrices animations.forEach(function (anim, animationIndex) { if (anim.$.id.indexOf('pose_matrix') !== -1) { var animatedJointName = anim.channel[0].$.target.split('/')[0] var currentKeyframes = anim.source[0].float_array[0]._.split(' ').map(Number) currentKeyframes.forEach(function (_, keyframeIndex) { var currentKeyframe = currentKeyframes[keyframeIndex] allKeyframes[currentKeyframes[keyframeIndex]] = allKeyframes[currentKeyframe] || [] // Multiply by parent world matrix var jointWorldMatrix = getParentWorldMatrix(animatedJointName, currentKeyframe, jointRelationships, keyframeJointMatrices) // Multiply our joint's inverse bind matrix mat4Multiply(jointWorldMatrix, jointBindPoses[animatedJointName], jointWorldMatrix) // Turn our row major matrix into a column major matrix. OpenGL uses column major mat4Transpose(jointWorldMatrix, jointWorldMatrix) // Trim to 6 significant figures (Maybe even 6 is more than needed?) jointWorldMatrix = jointWorldMatrix.map(function (val) { return parseFloat(val.toFixed(6)) }) allKeyframes[currentKeyframe].push(jointWorldMatrix) }) } }) return allKeyframes } // TODO: Refactor. Depth first traversal might make all of this less hacky function getParentWorldMatrix (jointName, keyframe, jointRelationships, keyframeJointMatrices, accumulator) { // child -> parent -> parent -> ... var jointMatrixTree = foo(jointName, keyframe, jointRelationships, keyframeJointMatrices, accumulator) // TODO: Revisit this. Thrown in to pass tests. Maybe just return `jointMatrix` // when there aren't any parent matrices to factor in var worldMatrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] jointMatrixTree.forEach(function (jointMatrix) { // TODO: Still not sure why we multiply in this order mat4Multiply(worldMatrix, worldMatrix, jointMatrix) }) return worldMatrix } // TODO: Clean up... well.. at least it works now :sweat_smile: function foo (jointName, keyframe, jointRelationships, keyframeJointMatrices) { var jointMatrix = keyframeJointMatrices[keyframe][jointName] var parentJointName = jointRelationships[jointName].parent if (parentJointName) { return [jointMatrix].concat(foo(parentJointName, keyframe, jointRelationships, keyframeJointMatrices)) } return [jointMatrix] }
JavaScript
0
@@ -1573,16 +1573,49 @@ oint(s)%0A + if (armatureScale) %7B%0A @@ -1681,16 +1681,28 @@ eScale)%0A + %7D%0A
d2cb18e92384cb5fd9b8f85216d1230a721c6c4f
Set up user input validation
bin/webScript.js
bin/webScript.js
$( document ).ready(function() { var stageNum = 1; $( "#addStage" ).click(function() { var newStage = "<li class='stage' ><h4>Stage " + stageNum + "</h4>Number of people <input type='number' class='people' min='0' style='width:50px'><br>Rule <input type='number' class='rule' min='0' style='width:50px'></li>" $("#trialSim").append(newStage); stageNum += 1 }); $("#start").click(function(){ var values = []; var peopleArray = $('.people').toArray().map(function(people) { return $(people).val(); }); var ruleArray = $('.rule').toArray().map(function(rule) { return $(rule).val(); }); var inputData = R.zip(peopleArray, ruleArray); }); });
JavaScript
0.000002
@@ -645,50 +645,645 @@ var -inputData = R.zip(peopleArray, ruleArray); +sumPeople = 0%0A %09%09for (var i = 0; i%3CpeopleArray.length, i++)%7B%0A %09%09%09if (peopleArray%5Bi%5D === %22%22 %7C%7C ruleArray%5Bi%5D === %22%22)%7B%0A %09%09%09%09var emptyBox = true%0A %09%09%09%7D%0A %09%09%09sumPeople += peopleArray%5Bi%5D%0A %09%09%09if (ruleArray%5Bi%5D%3EsumPeople) %7B%0A %09%09%09%09var ruleTooBig = true%0A %09%09%09%09//alert saying that the number of people to pass is greater than the total number%0A %09%09%09%7D %09%09%09%0A %09%09%7D%0A %09%09%0A %09%09var inputData = R.zip(peopleArray, ruleArray);%0A %09%09inputData = R.map(function (tuple) %7B return %7B numPeople: tuple%5B0%5D, passThreshold: tuple%5B1%5D %7D; %7D,inputData);%0A%09%09%09//at this point, we are ready to call createGrid on inputData%0A%09%09%09createGrid(x, %5B %09%09%09 %0A