<commit_before>/**
 *  a swipe left component. (消息列表左滑解决方案)
 */

'use strict';

import React, { Component } from 'react';
import {
    View,
    Text,
    Image,
    StyleSheet,
    PanResponder,
    Animated,
    TouchableHighlight,
} from 'react-native';

export default class Swipes extends Component {

    constructor(props) {
        super(props);
        let _width = _width || this._getBtnBoxWidth();
        this.state = {
            isOpen: false,
            height: 0,
            RowTranslateX: new Animated.Value(0),
            BtnTranslateX: new Animated.Value(0)
        };

    }

    _closeRow = () => {
        let _width = _width || this._getBtnBoxWidth();
        this._setIsOpenState(false);
        this._setHasIdOpenState(false);

        this.moving(this.state.RowTranslateX, 0);
        this.moving(this.state.BtnTranslateX, 0);
    }

    _getBtnBoxWidth() {
        let arr = [];

        this.props.rightBtn.map(function(item){
            return arr.push(item.width);
        })

        return arr.reduce(function(pre, cur) {
            return pre + cur;
        });

    }

    componentWillMount() {

        this._panResponder = PanResponder.create({
            onStartShouldSetPanResponder: (evt, gestureState) => {
                return (this.state.isOpen || this.props.root.state.hasIdOpen)? true : false;
            },
            onStartShouldSetPanResponderCapture: (evt, gestureState) => {
                return (this.state.isOpen || this.props.root.state.hasIdOpen)? true : false;
            },
            onMoveShouldSetPanResponder: (evt, gestureState) => {return Math.abs(gestureState.dx) > 0;},
            onMoveShouldSetPanResponderCapture: (evt, gestureState) => {return Math.abs(gestureState.dx) > 0;},
            onPanResponderMove: (evt, gestureState) => {this._onPanResponderMove(evt, gestureState)},
            onPanResponderRelease: (evt, gestureState) => {this._onPanResponderRelease(evt, gestureState)},
            onPanResponderTerminate: (evt, gestureState) => {this._onPanResponderTerminate(evt, gestureState)},
        })

    }

    _onPanResponderMove(evt, gestureState) {
        let dx;
        let _width = _width || this._getBtnBoxWidth();
        let right = -_width;

        if(Math.abs(gestureState.dx)>5) {
            this.disallowScroll();
        }

        this.isRowMove();

        if(!this.state.isOpen) {

            dx = gestureState.dx;

            if(dx < -10) {
                dx += 10;

                if(dx >= right) {
                    this.setState({
                        BtnTranslateX: new Animated.Value(dx)
                    });
                } else {
                    this.setState({
                        BtnTranslateX: new Animated.Value(right)
                    });
                }

                if(dx < 50) {
                    this.setState({
                        RowTranslateX: new Animated.Value(dx)
                    });
                }

            }

        } else {
            dx = right + gestureState.dx;

            if(dx>right) {
                this.setState({
                    BtnTranslateX: new Animated.Value(dx)
                })
            }

            if(dx < 50) {
                this.setState({
                    RowTranslateX: new Animated.Value(dx)
                })
            }

        }

    }

    _onPanResponderRelease(evt, gestureState) {
        let toValue;
        let isOpen;
        let dx;
        let _width = _width || this._getBtnBoxWidth();
        let right = -_width;
        let range;

        if(this.state.isOpen || this.props.root.state.hasIdOpen) {
            dx = right + gestureState.dx;
            range = right + 40
        } else {
            dx = gestureState.dx;
            range = -40;
        }

        if(dx<range && dx!== right) {
            toValue = right;
            isOpen = true;
            this.disallowScroll();
            this.isRowOpen();
            this._setHasIdOpenState(true);
        } else {
            toValue = 0;
            isOpen = false;
            this.allowScroll();
            /* 点击其他row关闭openRow */
            this.closeRow();
        }

        this._setIsOpenState(isOpen);

        this.moving(this.state.RowTranslateX, toValue);
        this.moving(this.state.BtnTranslateX, toValue);

    }

    _onPanResponderTerminate(evt, gestureState) {
        this.isTerminate();
        let _width = _width || this._getBtnBoxWidth();
        let right = -_width;
        if(this.state.RowTranslateX._value < -2) {
            this.disallowScroll();
            this.isRowOpen();
            this._setIsOpenState(true);
            this._setHasIdOpenState(true);

            this.moving(this.state.RowTranslateX, -_width);
            this.moving(this.state.BtnTranslateX, -_width);
        }

        return false;

    }

    _setHasIdOpenState(bool) {
        this.props.root.setState({
            hasIdOpen: bool
        })
    }

    _setIsOpenState(bool) {
        this.setState({
            isOpen: bool
        });
    }

    moving(k, v) {
        let type = this.props.animationType;
        let duration = this.props.duration
        if(type === 'timing'){
            Animated.timing(k, {
                toValue: v,
                duration: duration
            }).start();
        } else if(type === 'spring') {
            Animated.spring(k, {
                toValue: v,
                duration: duration
            }).start();
        }

    }

    isRowOpen() {
        let root = this.props.root;
        let id = this.props.id;
        if(!root.openRowId)
        root.openRowId = id;
    }

    isRowMove() {
        let root = this.props.root;
        let id = this.props.id;
        if(root.openRowId && root.openRowId !== id) {
            root._dataRow[root.openRowId]._closeRow();
            root.openRowId = '';
        }
    }

    isTerminate() {
        let root = this.props.root;
        let id = this.props.id;
        if(root.openRowId && root.openRowId !== id) {
            root._dataRow[root.openRowId]._closeRow();
        }
        root.openRowId = id;
    }

    closeRow() {
        let root = this.props.root;
        if(root.openRowId) {
            root._dataRow[root.openRowId]._closeRow();
        }
    }

    allowScroll() {
        let root = this.props.root;

        /* 接入原生下拉 */
        root.setState({
            scrollEnable: true
        })

        /* 接入第三方下拉 */
        /* 指定到像相应的scrollView对象 */
        // root.refs.listview.refs.listviewscroll.setState({
        //     scrollEnabled: true
        // });
    }

    disallowScroll() {
        let root = this.props.root;

        /* 接入原生下拉 */
        root.setState({
            scrollEnable: false
        })

        /* 接入第三方下拉 */
        /* 指定到像相应的scrollView对象 */
        // root.refs.listview.refs.listviewscroll.setState({
        //     scrollEnabled: false
        // });
    }

    render() {
        let _width = _width || this._getBtnBoxWidth();
        return (
            <View onLayout={(e)=>{this.setState({height:e.nativeEvent.layout.height})}}>
                <View ref='view' style={[styles.containerBox, {backgroundColor:this.props.boxbgColor}]}>

                    <Animated.View style={
                        [styles.container, {
                            backgroundColor: this.props.rowbgColor,
                            left: 0,
                            transform: [{translateX: this.state.RowTranslateX}]
                        }]}
                        {...this._panResponder.panHandlers}>
                        {this.props.children}
                    </Animated.View>

                    <Animated.View style={
                        [styles.deletebtnbox,{
                            width: _width,
                            right: -_width,
                            transform: [{translateX: this.state.BtnTranslateX}],
                            height: this.state.height}
                        ]}>
                            {this.props.rightBtn.map((item)=>{

                        return <TouchableHighlight key={item.id} style={[styles.deletebtn, {width: item.width, height: this.state.height, backgroundColor: item.bgColor}]} onPress={item.onPress} underlayColor={item.underlayColor}>
                                {item.text?
                                    <Text style={{color: item.color||null, fontSize: item.fontSize||null}}>{item.text}</Text>
                                    :
                                    item.image?
                                        <Image style={[styles.deleteBut, {width: 50, height: 50}]} source={{uri: item.image}} />
                                        :
                                        null}
                            </TouchableHighlight>
                        })}
                    </Animated.View>
                </View>
            </View>
        );
    }

}

Swipes.defaultProps = {
    boxbgColor: '#eeeeee',
    rowbgColor: '#ffffff',
    animationType: 'timing',
    duration: 150,
}

let styles = StyleSheet.create({
    containerBox: {
        flex: 1,
        flexDirection: 'row',
        justifyContent:'center',
        overflow: 'hidden',
        position: 'relative',
    },
    container: {
        flex: 1,
        borderBottomWidth: 1,
        borderBottomColor: '#eeeeee',
        overflow: 'hidden',
    },
    deletebtnbox: {
        flex: 1,
        position: 'absolute',
        top: 0,
        bottom: 0,
        right: 0,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent:'center',
    },
    deletebtn: {
        alignItems: 'center',
        justifyContent: 'center'
    }
})
<commit_msg>Return rowId with onPress callback<commit_after>/**
 *  a swipe left component. (消息列表左滑解决方案)
 */

'use strict';

import React, { Component } from 'react';
import {
    View,
    Text,
    Image,
    StyleSheet,
    PanResponder,
    Animated,
    TouchableHighlight,
} from 'react-native';

export default class Swipes extends Component {

    constructor(props) {
        super(props);
        let _width = _width || this._getBtnBoxWidth();
        this.state = {
            isOpen: false,
            height: 0,
            RowTranslateX: new Animated.Value(0),
            BtnTranslateX: new Animated.Value(0)
        };

    }

    _closeRow = () => {
        let _width = _width || this._getBtnBoxWidth();
        this._setIsOpenState(false);
        this._setHasIdOpenState(false);

        this.moving(this.state.RowTranslateX, 0);
        this.moving(this.state.BtnTranslateX, 0);
    }

    _getBtnBoxWidth() {
        let arr = [];

        this.props.rightBtn.map(function(item){
            return arr.push(item.width);
        })

        return arr.reduce(function(pre, cur) {
            return pre + cur;
        });

    }

    componentWillMount() {

        this._panResponder = PanResponder.create({
            onStartShouldSetPanResponder: (evt, gestureState) => {
                return (this.state.isOpen || this.props.root.state.hasIdOpen)? true : false;
            },
            onStartShouldSetPanResponderCapture: (evt, gestureState) => {
                return (this.state.isOpen || this.props.root.state.hasIdOpen)? true : false;
            },
            onMoveShouldSetPanResponder: (evt, gestureState) => {return Math.abs(gestureState.dx) > 0;},
            onMoveShouldSetPanResponderCapture: (evt, gestureState) => {return Math.abs(gestureState.dx) > 0;},
            onPanResponderMove: (evt, gestureState) => {this._onPanResponderMove(evt, gestureState)},
            onPanResponderRelease: (evt, gestureState) => {this._onPanResponderRelease(evt, gestureState)},
            onPanResponderTerminate: (evt, gestureState) => {this._onPanResponderTerminate(evt, gestureState)},
        })

    }

    _onPanResponderMove(evt, gestureState) {
        let dx;
        let _width = _width || this._getBtnBoxWidth();
        let right = -_width;

        if(Math.abs(gestureState.dx)>5) {
            this.disallowScroll();
        }

        this.isRowMove();

        if(!this.state.isOpen) {

            dx = gestureState.dx;

            if(dx < -10) {
                dx += 10;

                if(dx >= right) {
                    this.setState({
                        BtnTranslateX: new Animated.Value(dx)
                    });
                } else {
                    this.setState({
                        BtnTranslateX: new Animated.Value(right)
                    });
                }

                if(dx < 50) {
                    this.setState({
                        RowTranslateX: new Animated.Value(dx)
                    });
                }

            }

        } else {
            dx = right + gestureState.dx;

            if(dx>right) {
                this.setState({
                    BtnTranslateX: new Animated.Value(dx)
                })
            }

            if(dx < 50) {
                this.setState({
                    RowTranslateX: new Animated.Value(dx)
                })
            }

        }

    }

    _onPanResponderRelease(evt, gestureState) {
        let toValue;
        let isOpen;
        let dx;
        let _width = _width || this._getBtnBoxWidth();
        let right = -_width;
        let range;

        if(this.state.isOpen || this.props.root.state.hasIdOpen) {
            dx = right + gestureState.dx;
            range = right + 40
        } else {
            dx = gestureState.dx;
            range = -40;
        }

        if(dx<range && dx!== right) {
            toValue = right;
            isOpen = true;
            this.disallowScroll();
            this.isRowOpen();
            this._setHasIdOpenState(true);
        } else {
            toValue = 0;
            isOpen = false;
            this.allowScroll();
            /* 点击其他row关闭openRow */
            this.closeRow();
        }

        this._setIsOpenState(isOpen);

        this.moving(this.state.RowTranslateX, toValue);
        this.moving(this.state.BtnTranslateX, toValue);

    }

    _onPanResponderTerminate(evt, gestureState) {
        this.isTerminate();
        let _width = _width || this._getBtnBoxWidth();
        let right = -_width;
        if(this.state.RowTranslateX._value < -2) {
            this.disallowScroll();
            this.isRowOpen();
            this._setIsOpenState(true);
            this._setHasIdOpenState(true);

            this.moving(this.state.RowTranslateX, -_width);
            this.moving(this.state.BtnTranslateX, -_width);
        }

        return false;

    }

    _setHasIdOpenState(bool) {
        this.props.root.setState({
            hasIdOpen: bool
        })
    }

    _setIsOpenState(bool) {
        this.setState({
            isOpen: bool
        });
    }

	_onPress = (item, rowId) => event => {
		item.onPress(event, rowId)
	}

    moving(k, v) {
        let type = this.props.animationType;
        let duration = this.props.duration
        if(type === 'timing'){
            Animated.timing(k, {
                toValue: v,
                duration: duration
            }).start();
        } else if(type === 'spring') {
            Animated.spring(k, {
                toValue: v,
                duration: duration
            }).start();
        }

    }

    isRowOpen() {
        let root = this.props.root;
        let id = this.props.id;
        if(!root.openRowId)
        root.openRowId = id;
    }

    isRowMove() {
        let root = this.props.root;
        let id = this.props.id;
        if(root.openRowId && root.openRowId !== id) {
            root._dataRow[root.openRowId]._closeRow();
            root.openRowId = '';
        }
    }

    isTerminate() {
        let root = this.props.root;
        let id = this.props.id;
        if(root.openRowId && root.openRowId !== id) {
            root._dataRow[root.openRowId]._closeRow();
        }
        root.openRowId = id;
    }

    closeRow() {
        let root = this.props.root;
        if(root.openRowId) {
            root._dataRow[root.openRowId]._closeRow();
        }
    }

    allowScroll() {
        let root = this.props.root;

        /* 接入原生下拉 */
        root.setState({
            scrollEnable: true
        })

        /* 接入第三方下拉 */
        /* 指定到像相应的scrollView对象 */
        // root.refs.listview.refs.listviewscroll.setState({
        //     scrollEnabled: true
        // });
    }

    disallowScroll() {
        let root = this.props.root;

        /* 接入原生下拉 */
        root.setState({
            scrollEnable: false
        })

        /* 接入第三方下拉 */
        /* 指定到像相应的scrollView对象 */
        // root.refs.listview.refs.listviewscroll.setState({
        //     scrollEnabled: false
        // });
    }

    render() {
        let _width = _width || this._getBtnBoxWidth();
		const rowId = this.props.id
        return (
            <View onLayout={(e)=>{this.setState({height:e.nativeEvent.layout.height})}}>
                <View ref='view' style={[styles.containerBox, {backgroundColor:this.props.boxbgColor}]}>

                    <Animated.View style={
                        [styles.container, {
                            backgroundColor: this.props.rowbgColor,
                            left: 0,
                            transform: [{translateX: this.state.RowTranslateX}]
                        }]}
                        {...this._panResponder.panHandlers}>
                        {this.props.children}
                    </Animated.View>

                    <Animated.View style={
                        [styles.deletebtnbox,{
                            width: _width,
                            right: -_width,
                            transform: [{translateX: this.state.BtnTranslateX}],
                            height: this.state.height}
                        ]}>
                            {this.props.rightBtn.map((item)=>{

                        return <TouchableHighlight key={item.id} style={[styles.deletebtn, {width: item.width, height: this.state.height, backgroundColor: item.bgColor}]} onPress={this._onPress(item, rowId)} underlayColor={item.underlayColor}>
                                {item.text?
                                    <Text style={{color: item.color||null, fontSize: item.fontSize||null}}>{item.text}</Text>
                                    :
                                    item.image?
                                        <Image style={[styles.deleteBut, {width: 50, height: 50}]} source={{uri: item.image}} />
                                        :
                                        null}
                            </TouchableHighlight>
                        })}
                    </Animated.View>
                </View>
            </View>
        );
    }

}

Swipes.defaultProps = {
    boxbgColor: '#eeeeee',
    rowbgColor: '#ffffff',
    animationType: 'timing',
    duration: 150,
}

let styles = StyleSheet.create({
    containerBox: {
        flex: 1,
        flexDirection: 'row',
        justifyContent:'center',
        overflow: 'hidden',
        position: 'relative',
    },
    container: {
        flex: 1,
        // borderBottomWidth: 1,
        // borderBottomColor: '#eeeeee',
        overflow: 'hidden',
    },
    deletebtnbox: {
        flex: 1,
        position: 'absolute',
        top: 0,
        bottom: 0,
        right: 0,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent:'center',
    },
    deletebtn: {
        alignItems: 'center',
        justifyContent: 'center'
    }
})
<|endoftext|>


<commit_before>var electron = require('electron')
var path = require('path')

var app = electron.app

// report crashes
// require('crash-reporter').start({
//   productName: 'WebTorrent',
//   companyName: 'WebTorrent',
//   submitURL: 'https://webtorrent.io/crash-report',
//   autoSubmit: true
// })

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')()

// prevent window being garbage collected
var mainWindow

app.on('ready', function () {
  mainWindow = createMainWindow()
})

app.on('activate', function () {
  if (!mainWindow) mainWindow = createMainWindow()
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

function createMainWindow () {
  const win = new electron.BrowserWindow({
    width: 600,
    height: 400
  })
  win.loadURL('file://' + path.join(__dirname, 'index.html'))
  win.once('closed', function () {
    mainWindow = null
  })
  return win
}
<commit_msg>os x: hide title bar<commit_after>var electron = require('electron')
var path = require('path')

var app = electron.app

// report crashes
// require('crash-reporter').start({
//   productName: 'WebTorrent',
//   companyName: 'WebTorrent',
//   submitURL: 'https://webtorrent.io/crash-report',
//   autoSubmit: true
// })

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')()

// prevent window being garbage collected
var mainWindow

app.on('ready', function () {
  mainWindow = createMainWindow()
})

app.on('activate', function () {
  if (!mainWindow) mainWindow = createMainWindow()
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

function createMainWindow () {
  const win = new electron.BrowserWindow({
    width: 600,
    height: 400,
    titleBarStyle: 'hidden'
  })
  win.loadURL('file://' + path.join(__dirname, 'index.html'))
  win.once('closed', function () {
    mainWindow = null
  })
  return win
}
<|endoftext|>


<commit_before>'use strict';

var dsv = require('d3-dsv'),
    sexagesimal = require('sexagesimal');

var latRegex = /(Lat)(itude)?/gi,
    lonRegex = /(L)(on|ng)(gitude)?/i;

function guessHeader(row, regexp) {
    var name, match, score;
    for (var f in row) {
        match = f.match(regexp);
        if (match && (!name || match[0].length / f.length > score)) {
            score = match[0].length / f.length;
            name = f;
        }
    }
    return name;
}

function guessLatHeader(row) { return guessHeader(row, latRegex); }
function guessLonHeader(row) { return guessHeader(row, lonRegex); }

function isLat(f) { return !!f.match(latRegex); }
function isLon(f) { return !!f.match(lonRegex); }

function keyCount(o) {
    return (typeof o == 'object') ? Object.keys(o).length : 0;
}

function autoDelimiter(x) {
    var delimiters = [',', ';', '\t', '|'];
    var results = [];

    delimiters.forEach(function (delimiter) {
        var res = dsv.dsvFormat(delimiter).parse(x);
        if (res.length >= 1) {
            var count = keyCount(res[0]);
            for (var i = 0; i < res.length; i++) {
                if (keyCount(res[i]) !== count) return;
            }
            results.push({
                delimiter: delimiter,
                arity: Object.keys(res[0]).length,
            });
        }
    });

    if (results.length) {
        return results.sort(function (a, b) {
            return b.arity - a.arity;
        })[0].delimiter;
    } else {
        return null;
    }
}

/**
 * Silly stopgap for dsv to d3-dsv upgrade
 *
 * @param {Array} x dsv output
 * @returns {Array} array without columns member
 */
function deleteColumns(x) {
    delete x.columns;
    return x;
}

function auto(x) {
    var delimiter = autoDelimiter(x);
    if (!delimiter) return null;
    return deleteColumns(dsv.dsvFormat(delimiter).parse(x));
}

function csv2geojson(x, options, callback) {

    if (!callback) {
        callback = options;
        options = {};
    }

    options.delimiter = options.delimiter || ',';

    var latfield = options.latfield || '',
        lonfield = options.lonfield || '',
        crs = options.crs || '';

    var features = [],
        featurecollection = {type: 'FeatureCollection', features: features};

    if (crs !== '') {
        featurecollection.crs = {type: 'name', properties: {name: crs}};
    }

    if (options.delimiter === 'auto' && typeof x == 'string') {
        options.delimiter = autoDelimiter(x);
        if (!options.delimiter) {
            callback({
                type: 'Error',
                message: 'Could not autodetect delimiter'
            });
            return;
        }
    }

    var parsed = (typeof x == 'string') ?
        dsv.dsvFormat(options.delimiter).parse(x) : x;

    if (!parsed.length) {
        callback(null, featurecollection);
        return;
    }

    var errors = [];
    var i;

    if (!latfield) latfield = guessLatHeader(parsed[0]);
    if (!lonfield) lonfield = guessLonHeader(parsed[0]);
    var noGeometry = (!latfield || !lonfield);

    if (noGeometry) {
        for (i = 0; i < parsed.length; i++) {
            features.push({
                type: 'Feature',
                properties: parsed[i],
                geometry: null
            });
        }
        callback(errors.length ? errors : null, featurecollection);
        return;
    }

    for (i = 0; i < parsed.length; i++) {
        if (parsed[i][lonfield] !== undefined &&
            parsed[i][latfield] !== undefined) {

            var lonk = parsed[i][lonfield],
                latk = parsed[i][latfield],
                lonf, latf,
                a;

            a = sexagesimal(lonk, 'EW');
            if (a) lonk = a;
            a = sexagesimal(latk, 'NS');
            if (a) latk = a;

            lonf = parseFloat(lonk);
            latf = parseFloat(latk);

            if (isNaN(lonf) ||
                isNaN(latf)) {
                errors.push({
                    message: 'A row contained an invalid value for latitude or longitude',
                    row: parsed[i],
                    index: i
                });
            } else {
                if (!options.includeLatLon) {
                    delete parsed[i][lonfield];
                    delete parsed[i][latfield];
                }

                features.push({
                    type: 'Feature',
                    properties: parsed[i],
                    geometry: {
                        type: 'Point',
                        coordinates: [
                            parseFloat(lonf),
                            parseFloat(latf)
                        ]
                    }
                });
            }
        }
    }

    callback(errors.length ? errors : null, featurecollection);
}

function toLine(gj) {
    var features = gj.features;
    var line = {
        type: 'Feature',
        geometry: {
            type: 'LineString',
            coordinates: []
        }
    };
    for (var i = 0; i < features.length; i++) {
        line.geometry.coordinates.push(features[i].geometry.coordinates);
    }
    line.properties = features.reduce(function (aggregatedProperties, newFeature) {
        for (var key in newFeature.properties) {
            if (!aggregatedProperties[key]) {
                aggregatedProperties[key] = [];
            }
            aggregatedProperties[key].push(newFeature.properties[key]);
        }
        return aggregatedProperties;
    }, {});
    return {
        type: 'FeatureCollection',
        features: [line]
    };
}

function toPolygon(gj) {
    var features = gj.features;
    var poly = {
        type: 'Feature',
        geometry: {
            type: 'Polygon',
            coordinates: [[]]
        }
    };
    for (var i = 0; i < features.length; i++) {
        poly.geometry.coordinates[0].push(features[i].geometry.coordinates);
    }
    poly.properties = features.reduce(function (aggregatedProperties, newFeature) {
        for (var key in newFeature.properties) {
            if (!aggregatedProperties[key]) {
                aggregatedProperties[key] = [];
            }
            aggregatedProperties[key].push(newFeature.properties[key]);
        }
        return aggregatedProperties;
    }, {});
    return {
        type: 'FeatureCollection',
        features: [poly]
    };
}

module.exports = {
    isLon: isLon,
    isLat: isLat,
    guessLatHeader: guessLatHeader,
    guessLonHeader: guessLonHeader,
    csv: dsv.csvParse,
    tsv: dsv.tsvParse,
    dsv: dsv,
    auto: auto,
    csv2geojson: csv2geojson,
    toLine: toLine,
    toPolygon: toPolygon
};
<commit_msg>require @mapbox namespaced sexagesimal<commit_after>'use strict';

var dsv = require('d3-dsv'),
    sexagesimal = require('@mapbox/sexagesimal');

var latRegex = /(Lat)(itude)?/gi,
    lonRegex = /(L)(on|ng)(gitude)?/i;

function guessHeader(row, regexp) {
    var name, match, score;
    for (var f in row) {
        match = f.match(regexp);
        if (match && (!name || match[0].length / f.length > score)) {
            score = match[0].length / f.length;
            name = f;
        }
    }
    return name;
}

function guessLatHeader(row) { return guessHeader(row, latRegex); }
function guessLonHeader(row) { return guessHeader(row, lonRegex); }

function isLat(f) { return !!f.match(latRegex); }
function isLon(f) { return !!f.match(lonRegex); }

function keyCount(o) {
    return (typeof o == 'object') ? Object.keys(o).length : 0;
}

function autoDelimiter(x) {
    var delimiters = [',', ';', '\t', '|'];
    var results = [];

    delimiters.forEach(function (delimiter) {
        var res = dsv.dsvFormat(delimiter).parse(x);
        if (res.length >= 1) {
            var count = keyCount(res[0]);
            for (var i = 0; i < res.length; i++) {
                if (keyCount(res[i]) !== count) return;
            }
            results.push({
                delimiter: delimiter,
                arity: Object.keys(res[0]).length,
            });
        }
    });

    if (results.length) {
        return results.sort(function (a, b) {
            return b.arity - a.arity;
        })[0].delimiter;
    } else {
        return null;
    }
}

/**
 * Silly stopgap for dsv to d3-dsv upgrade
 *
 * @param {Array} x dsv output
 * @returns {Array} array without columns member
 */
function deleteColumns(x) {
    delete x.columns;
    return x;
}

function auto(x) {
    var delimiter = autoDelimiter(x);
    if (!delimiter) return null;
    return deleteColumns(dsv.dsvFormat(delimiter).parse(x));
}

function csv2geojson(x, options, callback) {

    if (!callback) {
        callback = options;
        options = {};
    }

    options.delimiter = options.delimiter || ',';

    var latfield = options.latfield || '',
        lonfield = options.lonfield || '',
        crs = options.crs || '';

    var features = [],
        featurecollection = {type: 'FeatureCollection', features: features};

    if (crs !== '') {
        featurecollection.crs = {type: 'name', properties: {name: crs}};
    }

    if (options.delimiter === 'auto' && typeof x == 'string') {
        options.delimiter = autoDelimiter(x);
        if (!options.delimiter) {
            callback({
                type: 'Error',
                message: 'Could not autodetect delimiter'
            });
            return;
        }
    }

    var parsed = (typeof x == 'string') ?
        dsv.dsvFormat(options.delimiter).parse(x) : x;

    if (!parsed.length) {
        callback(null, featurecollection);
        return;
    }

    var errors = [];
    var i;

    if (!latfield) latfield = guessLatHeader(parsed[0]);
    if (!lonfield) lonfield = guessLonHeader(parsed[0]);
    var noGeometry = (!latfield || !lonfield);

    if (noGeometry) {
        for (i = 0; i < parsed.length; i++) {
            features.push({
                type: 'Feature',
                properties: parsed[i],
                geometry: null
            });
        }
        callback(errors.length ? errors : null, featurecollection);
        return;
    }

    for (i = 0; i < parsed.length; i++) {
        if (parsed[i][lonfield] !== undefined &&
            parsed[i][latfield] !== undefined) {

            var lonk = parsed[i][lonfield],
                latk = parsed[i][latfield],
                lonf, latf,
                a;

            a = sexagesimal(lonk, 'EW');
            if (a) lonk = a;
            a = sexagesimal(latk, 'NS');
            if (a) latk = a;

            lonf = parseFloat(lonk);
            latf = parseFloat(latk);

            if (isNaN(lonf) ||
                isNaN(latf)) {
                errors.push({
                    message: 'A row contained an invalid value for latitude or longitude',
                    row: parsed[i],
                    index: i
                });
            } else {
                if (!options.includeLatLon) {
                    delete parsed[i][lonfield];
                    delete parsed[i][latfield];
                }

                features.push({
                    type: 'Feature',
                    properties: parsed[i],
                    geometry: {
                        type: 'Point',
                        coordinates: [
                            parseFloat(lonf),
                            parseFloat(latf)
                        ]
                    }
                });
            }
        }
    }

    callback(errors.length ? errors : null, featurecollection);
}

function toLine(gj) {
    var features = gj.features;
    var line = {
        type: 'Feature',
        geometry: {
            type: 'LineString',
            coordinates: []
        }
    };
    for (var i = 0; i < features.length; i++) {
        line.geometry.coordinates.push(features[i].geometry.coordinates);
    }
    line.properties = features.reduce(function (aggregatedProperties, newFeature) {
        for (var key in newFeature.properties) {
            if (!aggregatedProperties[key]) {
                aggregatedProperties[key] = [];
            }
            aggregatedProperties[key].push(newFeature.properties[key]);
        }
        return aggregatedProperties;
    }, {});
    return {
        type: 'FeatureCollection',
        features: [line]
    };
}

function toPolygon(gj) {
    var features = gj.features;
    var poly = {
        type: 'Feature',
        geometry: {
            type: 'Polygon',
            coordinates: [[]]
        }
    };
    for (var i = 0; i < features.length; i++) {
        poly.geometry.coordinates[0].push(features[i].geometry.coordinates);
    }
    poly.properties = features.reduce(function (aggregatedProperties, newFeature) {
        for (var key in newFeature.properties) {
            if (!aggregatedProperties[key]) {
                aggregatedProperties[key] = [];
            }
            aggregatedProperties[key].push(newFeature.properties[key]);
        }
        return aggregatedProperties;
    }, {});
    return {
        type: 'FeatureCollection',
        features: [poly]
    };
}

module.exports = {
    isLon: isLon,
    isLat: isLat,
    guessLatHeader: guessLatHeader,
    guessLonHeader: guessLonHeader,
    csv: dsv.csvParse,
    tsv: dsv.tsvParse,
    dsv: dsv,
    auto: auto,
    csv2geojson: csv2geojson,
    toLine: toLine,
    toPolygon: toPolygon
};
<|endoftext|>


<commit_before>require('newrelic');
if (!process.env.SLACK_API_TOKEN) require('dotenv').config();
var express = require('express');
var app     = express();

app.set('port', (process.env.PORT || 5000));

//For avoidong Heroku $PORT error
app.get('/', function(request, response) {
    var result = 'App is running'
    response.send(result);
}).listen(app.get('port'), function() {
    console.log('App is running, server is listening on port ', app.get('port'));
});

console.log(process.env.SLACK_API_TOKEN);

// Required modules
var RtmClient = require('@slack/client').RtmClient;
var RTM_EVENTS = require('@slack/client').RTM_EVENTS;
var WebClient = require('@slack/client').WebClient;
var Client = require('node-rest-client').Client;

// Global variables
var client = new Client({port: process.env.PORT});
var token = process.env.SLACK_API_TOKEN || '';
var apikey = process.env.TICKETMASTER_API_KEY || '';
var rtm = new RtmClient(token);
var web = new WebClient(token);

// Data object for the web.chat.postMessage call
var msgdata = {
	username: "apibot",
	icon_emoji: ":bee:"
};

function sendHelpMenu(message) {
	msgdata.attachments = [{
        "color": "#B7C9D3",
        "title": "Get this help menu",
		"text": "`\\` or `\\ help`",
		"mrkdwn_in": ["text"]
	}, {
        "color": "#768692",
        "title": "Count all events in the API",
		"text": "`\\ count`",
		"mrkdwn_in": ["text"]
	}, {
        "color": "#B7C9D3",
        "title": "Count all events sourced by Ticketmaster",
		"text": "`\\ count ticketmaster`",
		"mrkdwn_in": ["text"]
	}, {
        "color": "#768692",
        "title": "Count all events sourced by Universe in Great Britain",
		"text": "`\\ count universe GB`",
		"mrkdwn_in": ["text"]
	}, {
        "color": "#B7C9D3",
        "title": "Search events by keyword",
		"text": "`\\ search event Adele`",
		"mrkdwn_in": ["text"]
	}, {
        "color": "#768692",
        "title": "Get event details by ID",
		"text": "`\\ get event Z7r9jZ1AvOYAP`",
		"mrkdwn_in": ["text"]
	}, {
        "color": "#B7C9D3",
        "title": "Get event details by source ID",
		"text": "`\\ get:source event 1500508BE50D4ED5`",
		"mrkdwn_in": ["text"]
	}];
    web.chat.postMessage(message.channel, "Hello! I'm your <http://developer.ticketmaster.com|Ticketmaster API> assistant. Here's a few examples of what I can do:", msgdata);
}

function sendEventCard(message, url, data) {
	if (data.name) {
		var attr, ven, seg, loc = "N/A";
		if (data.classifications && data.classifications.length) {
			seg = data.classifications[0].segment.name;
		}
		if (data._embedded && data._embedded.attractions && data._embedded.attractions.length) {
			attr = "<" + data._embedded.attractions[0].url + "|" + data._embedded.attractions[0].name + ">";
		}
		if (data._embedded && data._embedded.venues && data._embedded.venues.length) {
			ven = "<" + data._embedded.venues[0].url + "|" + data._embedded.venues[0].name + ">";
			loc = data._embedded.venues[0].city.name + ", " + data._embedded.venues[0].state.stateCode + " " + data._embedded.venues[0].postalCode + "\n" + data._embedded.venues[0].country.name;

		}
		msgdata.attachments = [{
            "color": "#768692",
			"title": "<" + data.url + "|" + data.name + "> ",
			"image_url": data.images[0].url,
			"mrkdwn_in": ["text"]
    	}, {
			"color": "#768692",
			"fields": [{
				"title": "Event ID",
				"value": data.id,
				"short": true
			}, {
				"title": "Source ID",
				"value": data.source.id,
				"short": true
			}, {
				"title": "Source",
				"value": data.source.name,
				"short": true
			}, {
				"title": "Attraction",
				"value": attr,
				"short": true
			}, {
				"title": "Venues",
				"value": ven,
				"short": true
			}, {
				"title": "Segment",
				"value": seg,
				"short": true
			}, {
				"title": "Location",
				"value": loc,
				"short": true
			}, {
				"title": "Status",
				"value": (data.active) ? 'Active' : 'Inactive',
				"short": true
			}]
    	}];
		web.chat.postMessage(message.channel, "Here's the event I found: (<"+ url + "|api call>)", msgdata);
	} else {
		web.chat.postMessage(message.channel, "Hmm, something went wrong. #BlameSylvain. Here's the API call I made: " + url, msgdata);
	}
}

function handleRtmMessage(message) { // listening in on the messages in the channels that added me!
	if (message.type == "message" && message.text && (message.text.substring(0, 1) == "\\" || message.text.substring(0, 13) == '<@U1K1RGWUQ>:')) { // Making sure they're asking me to do something!
		console.log('Message:', message);
		msgdata.attachments = [];
		rtm.sendMessage('...', message.channel);
		// Analyze the command
		var arr = message.text.split(' ');
		if (arr[1]) {
			switch(arr[1]) {
			case 'count':
				var url = "https://app.ticketmaster.com/discovery/v2/events.json?apikey="+ apikey +"&size=1";
				if (arr[2]) {
					url += "&source=" + arr[2];
				}
				if (arr[3]) {
					url += "&countryCode=" + arr[3];
				}
				var source = arr[2] || 'The entire marketplace';
				client.get(url, function (data) {
					if (data.page) {
						var msg = source + ' has a total of *' + data.page.totalElements + '* events';
						if (arr[3]) {
							msg += " in " + arr[3];
						}
						web.chat.postMessage(message.channel, msg, msgdata);
					} else {
						web.chat.postMessage(message.channel, "Hmm, something went wrong. #BlameSylvain. Here's the <" + url + "|API call> I made", msgdata);
					}
				});
				break;
			case 'search':
				if (arr[2]) {
					switch(arr[2]) {
					case 'event':
						if (arr[3]) {
							var url = "https://app.ticketmaster.com/discovery/v2/events.json?keyword=" + arr[3] + "&view=internal&size=1&apikey="+ apikey;
							client.get(url, function (data) {
								sendEventCard(message, url, data._embedded.events[0]);
							});
						} else {
							web.chat.postMessage(message.channel, "I need the event ID", msgdata);
						}
						break;
					case 'attr':
						break;
					case 'venue':
						break;
					default:
						web.chat.postMessage(message.channel, 'Not sure I know what that is :)', msgdata);
						break;
					}
				} else {
					web.chat.postMessage(message.channel, 'What do you want me to get?', msgdata);
				}
				break;
			case 'get':
				if (arr[2]) {
					switch(arr[2]) {
					case 'event':
						if (arr[3]) {
							var url = "https://app.ticketmaster.com/discovery/v2/events/" + arr[3] + ".json?view=internal&apikey="+ apikey;
							client.get(url, function (data) {
								sendEventCard(message, url, data);
							});
						} else {
							web.chat.postMessage(message.channel, "I need the event ID", msgdata);
						}
						break;
					case 'attr':
						break;
					case 'venue':
						break;
					default:
						web.chat.postMessage(message.channel, 'Not sure I know what that is :)', msgdata);
						break;
					}
				} else {
					web.chat.postMessage(message.channel, 'What do you want me to get?', msgdata);
				}
				break;
			case 'get:source':
			case 'legacy':
				if (arr[2]) {
					switch(arr[2]) {
					case 'event':
						if (arr[3]) {
							var url = "https://app.ticketmaster.com/discovery/v2/events/legacy/" + arr[3] + ".json?apikey="+ apikey;
							client.get(url, function (data) {
								sendEventCard(message, url, data);
							});
						} else {
							web.chat.postMessage(message.channel, "I need the event source ID", msgdata);
						}
						break;
					case 'attr':
						break;
					case 'venue':
						break;
					default:
						web.chat.postMessage(message.channel, 'Not sure I know what that is :)', msgdata);
						break;
					}
				} else {
					web.chat.postMessage(message.channel, 'What do you want me to get?', msgdata);
				}
				break;
			case 'help':
				sendHelpMenu(message);
				break;
			case 'list:sources':
				web.chat.postMessage(message.channel, "Our marketplace sports content and data from *Ticketmaster*, *Universe*, *FrontGate*, and *TMR*. You can use the command `\\ count [source]` to get total events from that source.", msgdata);
			}
		} else {
			sendHelpMenu(message);
		}
	}
}

// Start the bot!
rtm.start();
rtm.on(RTM_EVENTS.MESSAGE, handleRtmMessage);
<commit_msg>Adding a dev bot<commit_after>// Include monitoring and alerting. This is also used to keep the dyno from idling.
require('newrelic');

// If environment variables aren't defined, load the .env file
if (!process.env.SLACK_API_TOKEN) require('dotenv').config();

//For avoidong Heroku $PORT error
var express = require('express');
var app     = express();
app.set('port', (process.env.PORT || 5000));
app.get('/', function(request, response) {
    var result = 'App is running';
    response.send(result);
}).listen(app.get('port'), function() {
    console.log('App is running, server is listening on port ', app.get('port'));
});

// Required modules
var RtmClient = require('@slack/client').RtmClient;
var RTM_EVENTS = require('@slack/client').RTM_EVENTS;
var WebClient = require('@slack/client').WebClient;
var Client = require('node-rest-client').Client;

// Global variables
var client = new Client({port: process.env.PORT});
var token = process.env.SLACK_API_TOKEN || '';
var apikey = process.env.TICKETMASTER_API_KEY || '';
var rtm = new RtmClient(token);
var web = new WebClient(token);

// Data object for the web.chat.postMessage call
var msgdata = {
	username: (process.env.DEV) ? "apibot-dev" : "apibot",
	icon_emoji: (process.env.DEV) ? ":bug:" : ":bee:"
};

// Display variables
console.log("Slack Token: " + process.env.SLACK_API_TOKEN + " | Ticketmaster Key: " + process.env.TICKETMASTER_API_KEY + " | Port: " + process.env.PORT);

function sendHelpMenu(message) {
	msgdata.attachments = [{
        "color": "#B7C9D3",
        "title": "Get this help menu",
		"text": "`\\` or `\\ help`",
		"mrkdwn_in": ["text"]
	}, {
        "color": "#768692",
        "title": "Count all events in the API",
		"text": "`\\ count`",
		"mrkdwn_in": ["text"]
	}, {
        "color": "#B7C9D3",
        "title": "Count all events sourced by Ticketmaster",
		"text": "`\\ count ticketmaster`",
		"mrkdwn_in": ["text"]
	}, {
        "color": "#768692",
        "title": "Count all events sourced by Universe in Great Britain",
		"text": "`\\ count universe GB`",
		"mrkdwn_in": ["text"]
	}, {
        "color": "#B7C9D3",
        "title": "Search events by keyword",
		"text": "`\\ search event Adele`",
		"mrkdwn_in": ["text"]
	}, {
        "color": "#768692",
        "title": "Get event details by ID",
		"text": "`\\ get event Z7r9jZ1AvOYAP`",
		"mrkdwn_in": ["text"]
	}, {
        "color": "#B7C9D3",
        "title": "Get event details by source ID",
		"text": "`\\ get:source event 1500508BE50D4ED5`",
		"mrkdwn_in": ["text"]
	}];
    web.chat.postMessage(message.channel, "Hello! I'm your <http://developer.ticketmaster.com|Ticketmaster API> assistant. Here's a few examples of what I can do:", msgdata);
}

function sendEventCard(message, url, data) {
	if (data.name) {
		var attr, ven, seg, loc = "N/A";
		if (data.classifications && data.classifications.length) {
			seg = data.classifications[0].segment.name;
		}
		if (data._embedded && data._embedded.attractions && data._embedded.attractions.length) {
			attr = "<" + data._embedded.attractions[0].url + "|" + data._embedded.attractions[0].name + ">";
		}
		if (data._embedded && data._embedded.venues && data._embedded.venues.length) {
			ven = "<" + data._embedded.venues[0].url + "|" + data._embedded.venues[0].name + ">";
			loc = data._embedded.venues[0].city.name + ", " + data._embedded.venues[0].state.stateCode + " " + data._embedded.venues[0].postalCode + "\n" + data._embedded.venues[0].country.name;

		}
		msgdata.attachments = [{
            "color": "#768692",
			"title": "<" + data.url + "|" + data.name + "> ",
			"image_url": data.images[0].url,
			"mrkdwn_in": ["text"]
    	}, {
			"color": "#768692",
			"fields": [{
				"title": "Event ID",
				"value": data.id,
				"short": true
			}, {
				"title": "Source ID",
				"value": data.source.id,
				"short": true
			}, {
				"title": "Source",
				"value": data.source.name,
				"short": true
			}, {
				"title": "Attraction",
				"value": attr,
				"short": true
			}, {
				"title": "Venues",
				"value": ven,
				"short": true
			}, {
				"title": "Segment",
				"value": seg,
				"short": true
			}, {
				"title": "Location",
				"value": loc,
				"short": true
			}, {
				"title": "Status",
				"value": (data.active) ? 'Active' : 'Inactive',
				"short": true
			}]
    	}];
		web.chat.postMessage(message.channel, "Here's the event I found: (<"+ url.replace(process.env.TICKETMASTER_API_KEY, "") + "|api call>)", msgdata);
	} else {
		web.chat.postMessage(message.channel, "Hmm, something went wrong. #BlameSylvain. Here's the API call I made: " + url.replace(process.env.TICKETMASTER_API_KEY, ""), msgdata);
	}
}

function handleRtmMessage(message) { // listening in on the messages in the channels that added me!
	if (message.type == "message" && message.text && message.text.substring(0, 1) == "\\") { // Making sure they're asking me to do something!
		console.log('Message:', message);
		msgdata.attachments = [];
		// rtm.sendMessage('...', message.channel);
		// Analyze the command
		var arr = message.text.split(' ');
		if (arr[1]) {
			switch(arr[1]) {
			case 'count':
				var url = "https://app.ticketmaster.com/discovery/v2/events.json?apikey="+ apikey +"&size=1";
				if (arr[2]) {
					url += "&source=" + arr[2];
				}
				if (arr[3]) {
					url += "&countryCode=" + arr[3];
				}
				var source = arr[2] || 'The entire marketplace';
				client.get(url, function (data) {
					if (data.page) {
						var msg = source + ' has a total of *' + data.page.totalElements + '* events';
						if (arr[3]) {
							msg += " in " + arr[3];
						}
						web.chat.postMessage(message.channel, msg, msgdata);
					} else {
						web.chat.postMessage(message.channel, "Hmm, something went wrong. #BlameSylvain. Here's the <" + url.replace(process.env.TICKETMASTER_API_KEY, "") + "|API call> I made", msgdata);
					}
				});
				break;
			case 'search':
				if (arr[2]) {
					switch(arr[2]) {
					case 'event':
						if (arr[3]) {
							var url = "https://app.ticketmaster.com/discovery/v2/events.json?keyword=" + arr[3] + "&view=internal&size=1&apikey="+ apikey;
							client.get(url, function (data) {
								sendEventCard(message, url, data._embedded.events[0]);
							});
						} else {
							web.chat.postMessage(message.channel, "I need the event ID", msgdata);
						}
						break;
					case 'attr':
						break;
					case 'venue':
						break;
					default:
						web.chat.postMessage(message.channel, 'Not sure I know what that is :)', msgdata);
						break;
					}
				} else {
					web.chat.postMessage(message.channel, 'What do you want me to get?', msgdata);
				}
				break;
			case 'get':
				if (arr[2]) {
					switch(arr[2]) {
					case 'event':
						if (arr[3]) {
							var url = "https://app.ticketmaster.com/discovery/v2/events/" + arr[3] + ".json?view=internal&apikey="+ apikey;
							client.get(url, function (data) {
								sendEventCard(message, url, data);
							});
						} else {
							web.chat.postMessage(message.channel, "I need the event ID", msgdata);
						}
						break;
					case 'attr':
						break;
					case 'venue':
						break;
					default:
						web.chat.postMessage(message.channel, 'Not sure I know what that is :)', msgdata);
						break;
					}
				} else {
					web.chat.postMessage(message.channel, 'What do you want me to get?', msgdata);
				}
				break;
			case 'get:source':
			case 'legacy':
				if (arr[2]) {
					switch(arr[2]) {
					case 'event':
						if (arr[3]) {
							var url = "https://app.ticketmaster.com/discovery/v2/events/legacy/" + arr[3] + ".json?apikey="+ apikey;
							client.get(url, function (data) {
								sendEventCard(message, url, data);
							});
						} else {
							web.chat.postMessage(message.channel, "I need the event source ID", msgdata);
						}
						break;
					case 'attr':
						break;
					case 'venue':
						break;
					default:
						web.chat.postMessage(message.channel, 'Not sure I know what that is :)', msgdata);
						break;
					}
				} else {
					web.chat.postMessage(message.channel, 'What do you want me to get?', msgdata);
				}
				break;
			case 'help':
				sendHelpMenu(message);
				break;
			case 'list:sources':
				web.chat.postMessage(message.channel, "Our marketplace sports content and data from *Ticketmaster*, *Universe*, *FrontGate*, and *TMR*. You can use the command `\\ count [source]` to get total events from that source.", msgdata);
			}
		} else {
			sendHelpMenu(message);
		}
	}
}

// Start the bot!
rtm.start();
rtm.on(RTM_EVENTS.MESSAGE, handleRtmMessage);
<|endoftext|>


<commit_before>/* eslint-env node */
'use strict';

const VersionChecker = require('ember-cli-version-checker');
const clone = require('clone');
const path = require('path');

let count = 0;

function addBaseDir(Plugin) {
  let type = typeof Plugin;

  if (type === 'function' && !Plugin.baseDir) {
    Plugin.baseDir = () => __dirname;
  } else if (type === 'object' && Plugin !== null && Plugin.default) {
    addBaseDir(Plugin.default);
  }
}

module.exports = {
  name: 'ember-cli-babel',
  configKey: 'ember-cli-babel',

  init: function() {
    this._super.init && this._super.init.apply(this, arguments);

    let checker = new VersionChecker(this);
    let dep = this.emberCLIChecker = checker.for('ember-cli', 'npm');

    this._shouldShowBabelDeprecations = !dep.lt('2.11.0-beta.2');
  },

  buildBabelOptions(_config) {
    let config = _config || this._getAddonOptions();

    return this._getBabelOptions(config);
  },

  _debugTree() {
    if (!this._cachedDebugTree) {
      this._cachedDebugTree = require('broccoli-debug').buildDebugCallback(`ember-cli-babel:${this._parentName()}`);
    }

    return this._cachedDebugTree.apply(null, arguments);
  },

  transpileTree(inputTree, config) {
    let description = `000${++count}`.slice(-3);
    let postDebugTree = this._debugTree(inputTree, `${description}:input`);

    let BabelTranspiler = require('broccoli-babel-transpiler');
    let output = new BabelTranspiler(postDebugTree, this.buildBabelOptions(config));

    return this._debugTree(output, `${description}:output`);
  },

  setupPreprocessorRegistry: function(type, registry) {
    registry.add('js', {
      name: 'ember-cli-babel',
      ext: 'js',
      toTree: (tree) => this.transpileTree(tree)
    });
  },

  _shouldIncludePolyfill: function() {
    let addonOptions = this._getAddonOptions();
    let babelOptions = addonOptions.babel;
    let customOptions = addonOptions['ember-cli-babel'];

    if (this._shouldShowBabelDeprecations && !this._polyfillDeprecationPrinted &&
      babelOptions && 'includePolyfill' in babelOptions) {

      this._polyfillDeprecationPrinted = true;

      // we can use writeDeprecateLine() here because the warning will only be shown on newer Ember CLIs
      this.ui.writeDeprecateLine(
        'Putting the "includePolyfill" option in "babel" is deprecated, please put it in "ember-cli-babel" instead.');
    }

    if (customOptions && 'includePolyfill' in customOptions) {
      return customOptions.includePolyfill === true;
    } else if (babelOptions && 'includePolyfill' in babelOptions) {
      return babelOptions.includePolyfill === true;
    } else {
      return false;
    }
  },

  _importPolyfill: function(app) {
    let polyfillPath = 'vendor/babel-polyfill/polyfill.js';

    if (this.import) {  // support for ember-cli >= 2.7
      this.import(polyfillPath, { prepend: true });
    } else if (app.import) { // support ember-cli < 2.7
      app.import(polyfillPath, { prepend: true });
    } else {
      console.warn('Please run: ember install ember-cli-import-polyfill');
    }
  },

  treeForVendor: function() {
    if (!this._shouldIncludePolyfill()) { return; }

    const Funnel = require('broccoli-funnel');
    const UnwatchedDir = require('broccoli-source').UnwatchedDir;

    // Find babel-core's browser polyfill and use its directory as our vendor tree
    let polyfillDir = path.dirname(require.resolve('babel-polyfill/dist/polyfill'));

    return new Funnel(new UnwatchedDir(polyfillDir), {
      destDir: 'babel-polyfill'
    });
  },

  included: function(app) {
    this._super.included.apply(this, arguments);
    this.app = app;

    if (this._shouldIncludePolyfill()) {
      this._importPolyfill(app);
    }
  },

  isPluginRequired(pluginName) {
    let targets = this._getTargets();

    // if no targets are setup, assume that all plugins are required
    if (!targets) { return true; }

    const isPluginRequired = require('babel-preset-env').isPluginRequired;
    const pluginList = require('babel-preset-env/data/plugins');

    return isPluginRequired(targets, pluginList[pluginName]);
  },

  _getAddonOptions: function() {
    return (this.parent && this.parent.options) || (this.app && this.app.options) || {};
  },

  _parentName() {
    let parentName;

    if (this.parent) {
      if (typeof this.parent.name === 'function') {
        parentName = this.parent.name();
      } else {
        parentName = this.parent.name;
      }
    }

    return parentName;
  },

  _getAddonProvidedConfig(addonOptions) {
    let babelOptions = clone(addonOptions.babel || {});

    // used only to support using ember-cli-babel@6 at the
    // top level (app or addon during development) on ember-cli
    // older than 2.13
    //
    // without this, we mutate the same shared `options.babel.plugins`
    // that is used to transpile internally (via `_prunedBabelOptions`
    // in older ember-cli versions)
    let babel6Options = clone(addonOptions.babel6 || {});

    let options;
    // options.modules is set only for things assuming babel@5 usage
    if (babelOptions.modules) {
      // using babel@5 configuration with babel@6
      // without overriding here we would trigger
      // an error
      options = Object.assign({}, babel6Options);
    } else {
      // shallow merge both babelOptions and babel6Options
      // (plugins/postTransformPlugins are handled separately)
      options = Object.assign({}, babelOptions, babel6Options);
    }

    let plugins = [].concat(babelOptions.plugins, babel6Options.plugins).filter(Boolean);
    let postTransformPlugins = [].concat(babelOptions.postTransformPlugins, babel6Options.postTransformPlugins).filter(Boolean);

    return {
      options,
      plugins,
      postTransformPlugins
    };
  },

  _getBabelOptions(config) {
    let addonProvidedConfig = this._getAddonProvidedConfig(config);
    let shouldCompileModules = this._shouldCompileModules(config);

    let providedAnnotation = config['ember-cli-babel'] && config['ember-cli-babel'].annotation;

    let sourceMaps = false;
    if (config.babel && 'sourceMaps' in config.babel) {
      sourceMaps = config.babel.sourceMaps;
    }

    let options = {
      annotation: providedAnnotation || `Babel: ${this._parentName()}`,
      sourceMaps
    };

    let userPlugins = addonProvidedConfig.plugins;
    let userPostTransformPlugins = addonProvidedConfig.postTransformPlugins;

    options.plugins = [].concat(
      userPlugins,
      this._getDebugMacroPlugins(config),
      this._getEmberModulesAPIPolyfill(config),
      shouldCompileModules && this._getModulesPlugin(),
      this._getPresetEnvPlugins(addonProvidedConfig),
      userPostTransformPlugins
    ).filter(Boolean);

    if (shouldCompileModules) {
      options.moduleIds = true;
      options.resolveModuleSource = require('amd-name-resolver').moduleResolve;
    }

    options.highlightCode = false;
    options.babelrc = false;

    return options;
  },

  _getDebugMacroPlugins(config) {
    let addonOptions = config['ember-cli-babel'] || {};

    if (addonOptions.disableDebugTooling) { return; }

    const DebugMacros = require('babel-plugin-debug-macros').default;
    const isProduction = process.env.EMBER_ENV === 'production';

    let options = {
      envFlags: {
        source: '@glimmer/env',
        flags: { DEBUG: !isProduction, CI: !!process.env.CI }
      },

      externalizeHelpers: {
        global: 'Ember'
      },

      debugTools: {
        source: '@ember/debug',
        assertPredicateIndex: 1
      }
    };

    return [[DebugMacros, options]];
  },

  _getEmberModulesAPIPolyfill(config) {
    let addonOptions = config['ember-cli-babel'] || {};

    if (addonOptions.disableEmberModulesAPIPolyfill) { return; }

    if (this._emberVersionRequiresModulesAPIPolyfill()) {
      const ModulesAPIPolyfill = require('babel-plugin-ember-modules-api-polyfill');

      return [[ModulesAPIPolyfill, { blacklist: { '@ember/debug': ['assert', 'deprecate', 'warn']} }]];
    }
  },

  _getPresetEnvPlugins(config) {
    let options = config.options;

    let targets = this._getTargets();
    let browsers = targets && targets.browsers;
    let presetOptions = Object.assign({}, options, {
      modules: false,
      targets
    });

    let presetEnvPlugins = this._presetEnv(null, presetOptions).plugins;

    presetEnvPlugins.forEach(function(pluginArray) {
      let Plugin = pluginArray[0];
      addBaseDir(Plugin);
    });

    return presetEnvPlugins;
  },

  _presetEnv() {
    const presetEnv = require('babel-preset-env').default;

    return presetEnv.apply(null, arguments);
  },

  _getTargets() {
    let targets = this.project && this.project.targets && this.project.targets;

    let parser = require('babel-preset-env/lib/targets-parser').default;
    if (typeof targets === 'object' && targets !== null) {
      return parser(targets);
    } else {
      return targets;
    }
  },

  _getModulesPlugin() {
    const ModulesTransform = require('babel-plugin-transform-es2015-modules-amd');

    addBaseDir(ModulesTransform);

    return [
      [ModulesTransform, { noInterop: true }],
    ];
  },

  /*
   * Used to discover if the addon's current configuration will compile modules
   * or not.
   *
   * @public
   * @method shouldCompileModules
   */
  shouldCompileModules() {
    return this._shouldCompileModules(this._getAddonOptions());
  },

  // will use any provided configuration
  _shouldCompileModules(options) {
    let addonOptions = options['ember-cli-babel'];
    let babelOptions = options.babel;

    if (addonOptions && 'compileModules' in addonOptions) {
      return addonOptions.compileModules;
    } else if (babelOptions && 'compileModules' in babelOptions) {
      if (this._shouldShowBabelDeprecations && !this._compileModulesDeprecationPrinted) {
        this._compileModulesDeprecationPrinted = true;
        // we can use writeDeprecateLine() here because the warning will only be shown on newer Ember CLIs
        this.ui.writeDeprecateLine('Putting the "compileModules" option in "babel" is deprecated, please put it in "ember-cli-babel" instead.');
      }

      return babelOptions.compileModules;
    } else {
      return this.emberCLIChecker.gt('2.12.0-alpha.1');
    }
  },

  _emberVersionRequiresModulesAPIPolyfill() {
    // once a version of Ember ships with the
    // emberjs/rfcs#176 modules natively this will
    // be updated to detect that and return false
    return true;
  }
};
<commit_msg>Fix isPluginRequired for babel-preset-env@2 restructuring.<commit_after>/* eslint-env node */
'use strict';

const VersionChecker = require('ember-cli-version-checker');
const clone = require('clone');
const path = require('path');

let count = 0;

function addBaseDir(Plugin) {
  let type = typeof Plugin;

  if (type === 'function' && !Plugin.baseDir) {
    Plugin.baseDir = () => __dirname;
  } else if (type === 'object' && Plugin !== null && Plugin.default) {
    addBaseDir(Plugin.default);
  }
}

module.exports = {
  name: 'ember-cli-babel',
  configKey: 'ember-cli-babel',

  init: function() {
    this._super.init && this._super.init.apply(this, arguments);

    let checker = new VersionChecker(this);
    let dep = this.emberCLIChecker = checker.for('ember-cli', 'npm');

    this._shouldShowBabelDeprecations = !dep.lt('2.11.0-beta.2');
  },

  buildBabelOptions(_config) {
    let config = _config || this._getAddonOptions();

    return this._getBabelOptions(config);
  },

  _debugTree() {
    if (!this._cachedDebugTree) {
      this._cachedDebugTree = require('broccoli-debug').buildDebugCallback(`ember-cli-babel:${this._parentName()}`);
    }

    return this._cachedDebugTree.apply(null, arguments);
  },

  transpileTree(inputTree, config) {
    let description = `000${++count}`.slice(-3);
    let postDebugTree = this._debugTree(inputTree, `${description}:input`);

    let BabelTranspiler = require('broccoli-babel-transpiler');
    let output = new BabelTranspiler(postDebugTree, this.buildBabelOptions(config));

    return this._debugTree(output, `${description}:output`);
  },

  setupPreprocessorRegistry: function(type, registry) {
    registry.add('js', {
      name: 'ember-cli-babel',
      ext: 'js',
      toTree: (tree) => this.transpileTree(tree)
    });
  },

  _shouldIncludePolyfill: function() {
    let addonOptions = this._getAddonOptions();
    let babelOptions = addonOptions.babel;
    let customOptions = addonOptions['ember-cli-babel'];

    if (this._shouldShowBabelDeprecations && !this._polyfillDeprecationPrinted &&
      babelOptions && 'includePolyfill' in babelOptions) {

      this._polyfillDeprecationPrinted = true;

      // we can use writeDeprecateLine() here because the warning will only be shown on newer Ember CLIs
      this.ui.writeDeprecateLine(
        'Putting the "includePolyfill" option in "babel" is deprecated, please put it in "ember-cli-babel" instead.');
    }

    if (customOptions && 'includePolyfill' in customOptions) {
      return customOptions.includePolyfill === true;
    } else if (babelOptions && 'includePolyfill' in babelOptions) {
      return babelOptions.includePolyfill === true;
    } else {
      return false;
    }
  },

  _importPolyfill: function(app) {
    let polyfillPath = 'vendor/babel-polyfill/polyfill.js';

    if (this.import) {  // support for ember-cli >= 2.7
      this.import(polyfillPath, { prepend: true });
    } else if (app.import) { // support ember-cli < 2.7
      app.import(polyfillPath, { prepend: true });
    } else {
      console.warn('Please run: ember install ember-cli-import-polyfill');
    }
  },

  treeForVendor: function() {
    if (!this._shouldIncludePolyfill()) { return; }

    const Funnel = require('broccoli-funnel');
    const UnwatchedDir = require('broccoli-source').UnwatchedDir;

    // Find babel-core's browser polyfill and use its directory as our vendor tree
    let polyfillDir = path.dirname(require.resolve('babel-polyfill/dist/polyfill'));

    return new Funnel(new UnwatchedDir(polyfillDir), {
      destDir: 'babel-polyfill'
    });
  },

  included: function(app) {
    this._super.included.apply(this, arguments);
    this.app = app;

    if (this._shouldIncludePolyfill()) {
      this._importPolyfill(app);
    }
  },

  isPluginRequired(pluginName) {
    let targets = this._getTargets();

    // if no targets are setup, assume that all plugins are required
    if (!targets) { return true; }

    const isPluginRequired = require('babel-preset-env').isPluginRequired;
    const getTargets = require('babel-preset-env/lib/targets-parser').default;
    const pluginList = require('babel-preset-env/data/plugins');

    let parsedTargets = getTargets(targets);
    return isPluginRequired(parsedTargets, pluginList[pluginName]);
  },

  _getAddonOptions: function() {
    return (this.parent && this.parent.options) || (this.app && this.app.options) || {};
  },

  _parentName() {
    let parentName;

    if (this.parent) {
      if (typeof this.parent.name === 'function') {
        parentName = this.parent.name();
      } else {
        parentName = this.parent.name;
      }
    }

    return parentName;
  },

  _getAddonProvidedConfig(addonOptions) {
    let babelOptions = clone(addonOptions.babel || {});

    // used only to support using ember-cli-babel@6 at the
    // top level (app or addon during development) on ember-cli
    // older than 2.13
    //
    // without this, we mutate the same shared `options.babel.plugins`
    // that is used to transpile internally (via `_prunedBabelOptions`
    // in older ember-cli versions)
    let babel6Options = clone(addonOptions.babel6 || {});

    let options;
    // options.modules is set only for things assuming babel@5 usage
    if (babelOptions.modules) {
      // using babel@5 configuration with babel@6
      // without overriding here we would trigger
      // an error
      options = Object.assign({}, babel6Options);
    } else {
      // shallow merge both babelOptions and babel6Options
      // (plugins/postTransformPlugins are handled separately)
      options = Object.assign({}, babelOptions, babel6Options);
    }

    let plugins = [].concat(babelOptions.plugins, babel6Options.plugins).filter(Boolean);
    let postTransformPlugins = [].concat(babelOptions.postTransformPlugins, babel6Options.postTransformPlugins).filter(Boolean);

    return {
      options,
      plugins,
      postTransformPlugins
    };
  },

  _getBabelOptions(config) {
    let addonProvidedConfig = this._getAddonProvidedConfig(config);
    let shouldCompileModules = this._shouldCompileModules(config);

    let providedAnnotation = config['ember-cli-babel'] && config['ember-cli-babel'].annotation;

    let sourceMaps = false;
    if (config.babel && 'sourceMaps' in config.babel) {
      sourceMaps = config.babel.sourceMaps;
    }

    let options = {
      annotation: providedAnnotation || `Babel: ${this._parentName()}`,
      sourceMaps
    };

    let userPlugins = addonProvidedConfig.plugins;
    let userPostTransformPlugins = addonProvidedConfig.postTransformPlugins;

    options.plugins = [].concat(
      userPlugins,
      this._getDebugMacroPlugins(config),
      this._getEmberModulesAPIPolyfill(config),
      shouldCompileModules && this._getModulesPlugin(),
      this._getPresetEnvPlugins(addonProvidedConfig),
      userPostTransformPlugins
    ).filter(Boolean);

    if (shouldCompileModules) {
      options.moduleIds = true;
      options.resolveModuleSource = require('amd-name-resolver').moduleResolve;
    }

    options.highlightCode = false;
    options.babelrc = false;

    return options;
  },

  _getDebugMacroPlugins(config) {
    let addonOptions = config['ember-cli-babel'] || {};

    if (addonOptions.disableDebugTooling) { return; }

    const DebugMacros = require('babel-plugin-debug-macros').default;
    const isProduction = process.env.EMBER_ENV === 'production';

    let options = {
      envFlags: {
        source: '@glimmer/env',
        flags: { DEBUG: !isProduction, CI: !!process.env.CI }
      },

      externalizeHelpers: {
        global: 'Ember'
      },

      debugTools: {
        source: '@ember/debug',
        assertPredicateIndex: 1
      }
    };

    return [[DebugMacros, options]];
  },

  _getEmberModulesAPIPolyfill(config) {
    let addonOptions = config['ember-cli-babel'] || {};

    if (addonOptions.disableEmberModulesAPIPolyfill) { return; }

    if (this._emberVersionRequiresModulesAPIPolyfill()) {
      const ModulesAPIPolyfill = require('babel-plugin-ember-modules-api-polyfill');

      return [[ModulesAPIPolyfill, { blacklist: { '@ember/debug': ['assert', 'deprecate', 'warn']} }]];
    }
  },

  _getPresetEnvPlugins(config) {
    let options = config.options;

    let targets = this._getTargets();
    let browsers = targets && targets.browsers;
    let presetOptions = Object.assign({}, options, {
      modules: false,
      targets
    });

    let presetEnvPlugins = this._presetEnv(null, presetOptions).plugins;

    presetEnvPlugins.forEach(function(pluginArray) {
      let Plugin = pluginArray[0];
      addBaseDir(Plugin);
    });

    return presetEnvPlugins;
  },

  _presetEnv() {
    const presetEnv = require('babel-preset-env').default;

    return presetEnv.apply(null, arguments);
  },

  _getTargets() {
    let targets = this.project && this.project.targets && this.project.targets;

    let parser = require('babel-preset-env/lib/targets-parser').default;
    if (typeof targets === 'object' && targets !== null) {
      return parser(targets);
    } else {
      return targets;
    }
  },

  _getModulesPlugin() {
    const ModulesTransform = require('babel-plugin-transform-es2015-modules-amd');

    addBaseDir(ModulesTransform);

    return [
      [ModulesTransform, { noInterop: true }],
    ];
  },

  /*
   * Used to discover if the addon's current configuration will compile modules
   * or not.
   *
   * @public
   * @method shouldCompileModules
   */
  shouldCompileModules() {
    return this._shouldCompileModules(this._getAddonOptions());
  },

  // will use any provided configuration
  _shouldCompileModules(options) {
    let addonOptions = options['ember-cli-babel'];
    let babelOptions = options.babel;

    if (addonOptions && 'compileModules' in addonOptions) {
      return addonOptions.compileModules;
    } else if (babelOptions && 'compileModules' in babelOptions) {
      if (this._shouldShowBabelDeprecations && !this._compileModulesDeprecationPrinted) {
        this._compileModulesDeprecationPrinted = true;
        // we can use writeDeprecateLine() here because the warning will only be shown on newer Ember CLIs
        this.ui.writeDeprecateLine('Putting the "compileModules" option in "babel" is deprecated, please put it in "ember-cli-babel" instead.');
      }

      return babelOptions.compileModules;
    } else {
      return this.emberCLIChecker.gt('2.12.0-alpha.1');
    }
  },

  _emberVersionRequiresModulesAPIPolyfill() {
    // once a version of Ember ships with the
    // emberjs/rfcs#176 modules natively this will
    // be updated to detect that and return false
    return true;
  }
};
<|endoftext|>


<commit_before>var gulp = require('gulp'),
	webpack = require('gulp-webpack'),
    notify = require('gulp-notify');
    gulpif = require('gulp-if'),
    uglify = require('gulp-uglify'),
    elixir = require('laravel-elixir'),
     _ = require('underscore'),
    utilities = require('laravel-elixir/ingredients/helpers/utilities');

elixir.extend('webpack', function (src, outputDir, options) {

	var config = this,
        baseDir = config.assetsDir + 'js',
        defaultOptions;

    defaultOptions = {
    };

    src = utilities.buildGulpSrc(src, baseDir, '**/*.js');

    options = _.extend(defaultOptions, options);

	gulp.task('webpack', function () {
		var onError = function(err) {
            notify.onError({
                title:    "Laravel Elixir",
                subtitle: "Webpack Compilation Failed!",
                message:  "Error: <%= error.message %>",
                icon: __dirname + '/../laravel-elixir/icons/fail.png'
            })(err);

            this.emit('end');
        };

		return gulp.src(src)
			.pipe(webpack(options)).on('error', onError)
			.pipe(gulpif(config.production, uglify()))
        	.pipe(gulp.dest(outputDir || config.jsOutput))
        	.pipe(notify({
                title: 'Laravel Elixir',
                subtitle: 'Webpack Compiled!',
                icon: __dirname + '/../laravel-elixir/icons/laravel.png',
                message: ' '
            }));
	});

    this.registerWatcher('webpack', baseDir + '/**/*.js');

    return this.queueTask('webpack');

});<commit_msg>fix formatting<commit_after>var gulp = require('gulp'),
    webpack = require('gulp-webpack'),
    notify = require('gulp-notify');
    gulpif = require('gulp-if'),
    uglify = require('gulp-uglify'),
    elixir = require('laravel-elixir'),
     _ = require('underscore'),
    utilities = require('laravel-elixir/ingredients/helpers/utilities');

elixir.extend('webpack', function (src, outputDir, options) {

    var config = this,
        baseDir = config.assetsDir + 'js',
        defaultOptions;

    defaultOptions = {
    };

    src = utilities.buildGulpSrc(src, baseDir, '**/*.js');

    options = _.extend(defaultOptions, options);

    gulp.task('webpack', function () {
        var onError = function(err) {
            notify.onError({
                title:    "Laravel Elixir",
                subtitle: "Webpack Compilation Failed!",
                message:  "Error: <%= error.message %>",
                icon: __dirname + '/../laravel-elixir/icons/fail.png'
            })(err);

            this.emit('end');
        };

        return gulp.src(src)
            .pipe(webpack(options)).on('error', onError)
            .pipe(gulpif(config.production, uglify()))
            .pipe(gulp.dest(outputDir || config.jsOutput))
            .pipe(notify({
                title: 'Laravel Elixir',
                subtitle: 'Webpack Compiled!',
                icon: __dirname + '/../laravel-elixir/icons/laravel.png',
                message: ' '
            }));
    });

    this.registerWatcher('webpack', baseDir + '/**/*.js');

    return this.queueTask('webpack');

});<|endoftext|>


<commit_before>module.exports = {
  AdNotExistError:                              'ad not exist',
  AlreadyActivatedError:                        'already activated',
  AppNotExistError:                             'app not exist',
  AppPlatformSettingsNotExistError:             'app platform settings not exist',
  AttachmentNotExistError:                      'attachment not exist',
  ClientNotExistError:                          'client not exist',
  CubePointAggregationFailedError:              'failed to aggregate cube point',
  CubePointNotExistError:                       'cube point not exist',
  DuplicateKeyError:                            'duplicate key',
  FailedToCreateAdClickError:                   'failed to create ad click',
  FailedToCreateAdError:                        'failed to create ad',
  FailedToCreateAppPlatformSettingsError:       'failed to create app platform settings',
  FailedToCreateAttachmentError:                'failed to create attachment',
  FailedToCreateDeviceError:                    'failed to create device, contact us',
  FailedToCreateDeviceDataBlobError:            'failed to create device data blob',
  FailedToCreateGenreError:                     'failed to create genre',
  FailedToCreateMPoiWifiRuleError:              'failed to create poi wifi rule',
  FailedToCreatePoiError:                       'failed to create poi',
  FailedToCreateScenarioError:                  'failed to create scenario',
  FailedToCreateSubscriptionError:              'failed to create subscription',
  FailedToCreateUserError:                      'failed to create user',
  FailedToDeleteFileError:                      'failed to delete file',
  FailedToDestroyAdError:                       'failed to destroy ad',
  FailedToDestroyAppPlatformSettingsError:      'failed to destroy app platform settings',
  FailedToDestroyAttachmentError:               'failed to destroy attachment',
  FailedToDestroyGenreError:                    'failed to destroy genre',
  FailedToDestroyMPoiWifiRuleError:             'failed to destroy poi wifi rule',
  FailedToDestroyScenarioError:                 'failed to destroy scenario',
  FailedToDestroySubscriptionError:             'failed to destroy subscription',
  FailedToEnsureDeviceError:                    'rpc error, failed to ensure device',
  FailedToExportPoiError:                       'failed to export poi',
  FailedToFindAdError:                          'failed to find ad',
  FailedToFindAppError:                         'failed to get app, check if appKey is valid',
  FailedToFindAppPlatformSettingsError:         'failed to find app platform settings',
  FailedToFindAttachmentError:                  'failed to find attachment',
  FailedToFindCubePointError:                   'failed to find cube point',
  FailedToFindFileError:                        'failed to find file',
  FailedToFindGenreError:                       'failed to find genre',
  FailedToFindJobError:                         'failed to find job',
  FailedToFindPoiPullRequestError:              'failed to find poi pull request, contact us',
  FailedToFindPoisError:                        'failed to find pois',
  FailedToFindRegionsError:                     'failed to find regions',
  FailedToFindResourceError:                    'failed to find specified resource',
  FailedToFindScenarioError:                    'failed to find scenario',
  FailedToFindSubscriptionError:                'failed to find subscription',
  FailedToFindUserBehaviorsError:               'failed to find user behaviors',
  FailedToFindUsersError:                       'failed to find users',
  FailedToGenerateTokenError:                   'failed to generate token, contact us',
  FailedToGetAppError:                          'rpc error, failed to Get App',
  FailedToGetDeviceError:                       'failed to get device, contact us',
  FailedToGetJobError:                          'failed to get job status',
  FailedToGetPoiError:                          'rpc error, failed to get poi',
  FailedToHashPasswordError:                    'failed to hash password',
  FailedToImportPoiError:                       'failed to import error',
  FailedToQueueDeviceDataCollectJobError:       'failed to queue device data collect job',
  FailedToQueuePoiExportJobError:               'failed to queue poi export job',
  FailedToQueuePoiImportJobError:               'failed to queue poi import job',
  FailedToQueuePoiRemoveJobError:               'failed to queue poi remove job',
  FailedToQueuePoiRevertJobError:               'failed to queue poi revert job',
  FailedToReadCertificateError:                 'failed to read certificate, please check the password is correct',
  FailedToReadFileError:                        'error when read file',
  FailedToSaveDeviceError:                      'failed to create/update device, contact us',
  FailedToSaveFileError:                        'failed to save file',
  FailedToSaveUserError:                        'failed to save user, please check if required field is correct',
  FailedToSendMailError:                        'failed to send mail',
  FailedToUpdateAdError:                        'failed to update ad',
  FailedToUpdateAdLastOperationError:           'failed to update ad last operation',
  FailedToUpdateAppError:                       'failed to update app',
  FailedToUpdateAppLastOperationError:          'failed to update app last operation',
  FailedToUpdateAppPlatformSettingsError:       'failed to update app platform settings',
  FailedToUpdateAttachmentError:                'failed to update attachment',
  FailedToUpdateDeviceError:                    'failed to update device, contact us',
  FailedToUpdateGenreError:                     'failed to update genre',
  FailedToUpdateMPoiWifiRuleError:              'failed to update poi wifi rule',
  FailedToUpdatePoiError:                       'failed to update poi',
  FailedToUpdatePoiPullRequestError:            'failed to update poi pull request',
  FailedToUpdateScenarioError:                  'failed to update scenario',
  FailedToUpdateScenarioLastOperationError:     'failed to update scenario last operation',
  FailedToUpdateSubscriptionError:              'failed to update subscription',
  FailedToUploadDeviceDataError:                'failed to upload data',
  FailedToValidateEmailError:                   'failed to validate email',
  FileNotExistError:                            'file not exist',
  GenreNotExistError:                           'genre not exist',
  InternalError:                                'internal error, contact us',
  InvalidActivationCodeError:                   'invalid activation code',
  InvalidAdSignatureError:                      'invalid ad signature',
  InvalidAppKeyError:                           'invalid appKey',
  InvalidAppSecretError:                        'invalid appSecret',
  InvalidClientKeyError:                        'invalid clientKey',
  InvalidClientSecretError:                     'invalid clientSecret',
  InvalidLocationError:                         'invalid location',
  InvalidPasswordResetCodeError:                'invalid password reset code',
  InvalidTokenError:                            'invalid token',
  MPoiWifiRuleNotExistError:                    'poi wifi rule not exist',
  NotYourAppError:                              'app is not yours',
  PasswordNotMatchError:                        'password not match',
  PendingPoiPullRequestExistsError:             'pending poi pull request exists',
  PoiNotExistError:                             'poi not exist',
  PoiNotReadyError:                             'poi not ready',
  PoiPullRequestNotActiveError:                 'poi pull request not active',
  PoiPullRequestNotExistError:                  'poi pull request not exist',
  RequireAdClickError:                          'require ad click',
  RequireAdError:                               'require ad',
  RequireAdIdError:                             'require ad id',
  RequireAppBundleError:                        'require appBundle',
  RequireAppError:                              'require app',
  RequireAppIdError:                            'require app id',
  RequireAppKeyError:                           'require appKey',
  RequireAppPlatformSettingsIdError:            'require app platform settings id',
  RequireAppSecretError:                        'require appSecret',
  RequireAttachmentError:                       'require attachment',
  RequireAttachmentIdError:                     'require attachment id',
  RequireBeaconsOrWifisOrLocationError:         'require beacon or wifi or location',
  RequireBssidError:                            'require wifi bssid',
  RequireClientKeyError:                        'require clientKey',
  RequireClientSecretError:                     'require clientSecret',
  RequireDeviceDataBlobError:                   'require device data blob',
  RequireDataFileError:                         'require uploaded data file',
  RequireDeviceError:                           'require device',
  RequireDeviceUdidError:                       'require deviceUdid',
  RequireFileBucketError:                       'require file bucket',
  RequireFilePathError:                         'require file path',
  RequireGenreError:                            'require genre',
  RequireGenreIdError:                          'require genre id',
  RequireJobIdError:                            'require job id',
  RequireMPoiWifiRuleError:                     'require poi wifi rule',
  RequireMPoiWifiRuleIdError:                   'require poi wifi rule id',
  RequireOwnerError:                            'require owner',
  RequirePasswordError:                         'require password',
  RequirePoiError:                              'require poi',
  RequirePoiIdError:                            'require poi id',
  RequirePoiIdOrUmmError:                       'require poi id or umm',
  RequirePoiPullRequestError:                   'require poi pull request info',
  RequirePoiPullRequestIdError:                 'require poi pull request id',
  RequirePoisError:                             'require pois',
  RequireScenarioError:                         'require scenario',
  RequireScenarioIdError:                       'require scenario id',
  RequireSsidError:                             'require wifi ssid',
  RequireSubscriptionError:                     'require subscription',
  RequireSubscriptionIdError:                   'require subscription id',
  RequireTokenError:                            'require token',
  RequireUmmError:                              'require beacon umm',
  RequireUsernameError:                         'require username',
  RequireUserOrCodeToResetPasswordError:        'require user or code to reset password',
  ScenarioNotExistError:                        'scenario not exist',
  SubscriptionNotExistError:                    'subscription not exist',
  Success:                                      'success',
  SystemBusyError:                              'system busy, retry later',
  TokenExpiredError:                            'token is expired',
  UserAlreadySignupError:                       'failed to signup, user already signup',
  UserNotExistError:                            'user not exist',
  WrongParameterError:                          'wrong parameter'
};
<commit_msg>add plan error messages.<commit_after>module.exports = {
  AdNotExistError:                              'ad not exist',
  AlreadyActivatedError:                        'already activated',
  AppNotExistError:                             'app not exist',
  AppPlatformSettingsNotExistError:             'app platform settings not exist',
  AttachmentNotExistError:                      'attachment not exist',
  ClientNotExistError:                          'client not exist',
  CubePointAggregationFailedError:              'failed to aggregate cube point',
  CubePointNotExistError:                       'cube point not exist',
  DuplicateKeyError:                            'duplicate key',
  FailedToCreateAdClickError:                   'failed to create ad click',
  FailedToCreateAdError:                        'failed to create ad',
  FailedToCreateAppPlatformSettingsError:       'failed to create app platform settings',
  FailedToCreateAttachmentError:                'failed to create attachment',
  FailedToCreateDeviceError:                    'failed to create device, contact us',
  FailedToCreateDeviceDataBlobError:            'failed to create device data blob',
  FailedToCreateGenreError:                     'failed to create genre',
  FailedToCreateMPoiWifiRuleError:              'failed to create poi wifi rule',
  FailedToCreatePlanError:                      'failed to create plan',
  FailedToCreatePoiError:                       'failed to create poi',
  FailedToCreateScenarioError:                  'failed to create scenario',
  FailedToCreateSubscriptionError:              'failed to create subscription',
  FailedToCreateUserError:                      'failed to create user',
  FailedToDeleteFileError:                      'failed to delete file',
  FailedToDestroyAdError:                       'failed to destroy ad',
  FailedToDestroyAppPlatformSettingsError:      'failed to destroy app platform settings',
  FailedToDestroyAttachmentError:               'failed to destroy attachment',
  FailedToDestroyGenreError:                    'failed to destroy genre',
  FailedToDestroyMPoiWifiRuleError:             'failed to destroy poi wifi rule',
  FailedToDestroyPlanError:                     'failed to destroy plan',
  FailedToDestroyScenarioError:                 'failed to destroy scenario',
  FailedToDestroySubscriptionError:             'failed to destroy subscription',
  FailedToEnsureDeviceError:                    'rpc error, failed to ensure device',
  FailedToExportPoiError:                       'failed to export poi',
  FailedToFindAdError:                          'failed to find ad',
  FailedToFindAppError:                         'failed to get app, check if appKey is valid',
  FailedToFindAppPlatformSettingsError:         'failed to find app platform settings',
  FailedToFindAttachmentError:                  'failed to find attachment',
  FailedToFindCubePointError:                   'failed to find cube point',
  FailedToFindFileError:                        'failed to find file',
  FailedToFindGenreError:                       'failed to find genre',
  FailedToFindJobError:                         'failed to find job',
  FailedToFindPlanError:                        'failed to find plan',
  FailedToFindPoiPullRequestError:              'failed to find poi pull request, contact us',
  FailedToFindPoisError:                        'failed to find pois',
  FailedToFindRegionsError:                     'failed to find regions',
  FailedToFindResourceError:                    'failed to find specified resource',
  FailedToFindScenarioError:                    'failed to find scenario',
  FailedToFindSubscriptionError:                'failed to find subscription',
  FailedToFindUserBehaviorsError:               'failed to find user behaviors',
  FailedToFindUsersError:                       'failed to find users',
  FailedToGenerateTokenError:                   'failed to generate token, contact us',
  FailedToGetAppError:                          'rpc error, failed to Get App',
  FailedToGetDeviceError:                       'failed to get device, contact us',
  FailedToGetJobError:                          'failed to get job status',
  FailedToGetPoiError:                          'rpc error, failed to get poi',
  FailedToHashPasswordError:                    'failed to hash password',
  FailedToImportPoiError:                       'failed to import error',
  FailedToQueueDeviceDataCollectJobError:       'failed to queue device data collect job',
  FailedToQueuePoiExportJobError:               'failed to queue poi export job',
  FailedToQueuePoiImportJobError:               'failed to queue poi import job',
  FailedToQueuePoiRemoveJobError:               'failed to queue poi remove job',
  FailedToQueuePoiRevertJobError:               'failed to queue poi revert job',
  FailedToReadCertificateError:                 'failed to read certificate, please check the password is correct',
  FailedToReadFileError:                        'error when read file',
  FailedToSaveDeviceError:                      'failed to create/update device, contact us',
  FailedToSaveFileError:                        'failed to save file',
  FailedToSaveUserError:                        'failed to save user, please check if required field is correct',
  FailedToSendMailError:                        'failed to send mail',
  FailedToUpdateAdError:                        'failed to update ad',
  FailedToUpdateAdLastOperationError:           'failed to update ad last operation',
  FailedToUpdateAppError:                       'failed to update app',
  FailedToUpdateAppLastOperationError:          'failed to update app last operation',
  FailedToUpdateAppPlatformSettingsError:       'failed to update app platform settings',
  FailedToUpdateAttachmentError:                'failed to update attachment',
  FailedToUpdateDeviceError:                    'failed to update device, contact us',
  FailedToUpdateGenreError:                     'failed to update genre',
  FailedToUpdateMPoiWifiRuleError:              'failed to update poi wifi rule',
  FailedToUpdatePlanError:                      'failed to update plan',
  FailedToUpdatePoiError:                       'failed to update poi',
  FailedToUpdatePoiPullRequestError:            'failed to update poi pull request',
  FailedToUpdateScenarioError:                  'failed to update scenario',
  FailedToUpdateScenarioLastOperationError:     'failed to update scenario last operation',
  FailedToUpdateSubscriptionError:              'failed to update subscription',
  FailedToUploadDeviceDataError:                'failed to upload data',
  FailedToValidateEmailError:                   'failed to validate email',
  FileNotExistError:                            'file not exist',
  GenreNotExistError:                           'genre not exist',
  InternalError:                                'internal error, contact us',
  InvalidActivationCodeError:                   'invalid activation code',
  InvalidAdSignatureError:                      'invalid ad signature',
  InvalidAppKeyError:                           'invalid appKey',
  InvalidAppSecretError:                        'invalid appSecret',
  InvalidClientKeyError:                        'invalid clientKey',
  InvalidClientSecretError:                     'invalid clientSecret',
  InvalidLocationError:                         'invalid location',
  InvalidPasswordResetCodeError:                'invalid password reset code',
  InvalidTokenError:                            'invalid token',
  MPoiWifiRuleNotExistError:                    'poi wifi rule not exist',
  NotYourAppError:                              'app is not yours',
  PasswordNotMatchError:                        'password not match',
  PendingPoiPullRequestExistsError:             'pending poi pull request exists',
  PlanNotExistError:                            'plan not exist',
  PoiNotExistError:                             'poi not exist',
  PoiNotReadyError:                             'poi not ready',
  PoiPullRequestNotActiveError:                 'poi pull request not active',
  PoiPullRequestNotExistError:                  'poi pull request not exist',
  RequireAdClickError:                          'require ad click',
  RequireAdError:                               'require ad',
  RequireAdIdError:                             'require ad id',
  RequireAppBundleError:                        'require appBundle',
  RequireAppError:                              'require app',
  RequireAppIdError:                            'require app id',
  RequireAppKeyError:                           'require appKey',
  RequireAppPlatformSettingsIdError:            'require app platform settings id',
  RequireAppSecretError:                        'require appSecret',
  RequireAttachmentError:                       'require attachment',
  RequireAttachmentIdError:                     'require attachment id',
  RequireBeaconsOrWifisOrLocationError:         'require beacon or wifi or location',
  RequireBssidError:                            'require wifi bssid',
  RequireClientKeyError:                        'require clientKey',
  RequireClientSecretError:                     'require clientSecret',
  RequireDeviceDataBlobError:                   'require device data blob',
  RequireDataFileError:                         'require uploaded data file',
  RequireDeviceError:                           'require device',
  RequireDeviceUdidError:                       'require deviceUdid',
  RequireFileBucketError:                       'require file bucket',
  RequireFilePathError:                         'require file path',
  RequireGenreError:                            'require genre',
  RequireGenreIdError:                          'require genre id',
  RequireJobIdError:                            'require job id',
  RequireMPoiWifiRuleError:                     'require poi wifi rule',
  RequireMPoiWifiRuleIdError:                   'require poi wifi rule id',
  RequireOwnerError:                            'require owner',
  RequirePasswordError:                         'require password',
  RequirePlanError:                             'require plan',
  RequirePlanIdError:                           'require plan id',
  RequirePoiError:                              'require poi',
  RequirePoiIdError:                            'require poi id',
  RequirePoiIdOrUmmError:                       'require poi id or umm',
  RequirePoiPullRequestError:                   'require poi pull request info',
  RequirePoiPullRequestIdError:                 'require poi pull request id',
  RequirePoisError:                             'require pois',
  RequireScenarioError:                         'require scenario',
  RequireScenarioIdError:                       'require scenario id',
  RequireSsidError:                             'require wifi ssid',
  RequireSubscriptionError:                     'require subscription',
  RequireSubscriptionIdError:                   'require subscription id',
  RequireTokenError:                            'require token',
  RequireUmmError:                              'require beacon umm',
  RequireUsernameError:                         'require username',
  RequireUserOrCodeToResetPasswordError:        'require user or code to reset password',
  ScenarioNotExistError:                        'scenario not exist',
  SubscriptionNotExistError:                    'subscription not exist',
  Success:                                      'success',
  SystemBusyError:                              'system busy, retry later',
  TokenExpiredError:                            'token is expired',
  UserAlreadySignupError:                       'failed to signup, user already signup',
  UserNotExistError:                            'user not exist',
  WrongParameterError:                          'wrong parameter'
};
<|endoftext|>