<commit_before>var React = require('react-native')
var deviceScreen = require('Dimensions').get('window')
var tween = require('./Tweener')

var {
  PanResponder,
  View,
  StyleSheet
} = React

/**
 * Check if the current gesture offset bigger than allowed one
 * before opening menu
 * @param  {Number} dx Gesture offset from the left side of the window
 * @return {Boolean}
 */
var drawer = React.createClass({

  _left: 0,
  _prevLeft: 0,
  _offsetOpen: 0,
  _offsetClosed: 0,
  _open: false,
  _panning: false,
  _tweenPending: false,
  _lastPress: 0,

  propTypes: {
    type: React.PropTypes.string,
    closedDrawerOffset: React.PropTypes.number,
    openDrawerOffset: React.PropTypes.number,
    openDrawerThreshold: React.PropTypes.number,
    relativeDrag: React.PropTypes.bool,
    panStartCompensation: React.PropTypes.bool,
    panOpenMask: React.PropTypes.number,
    panCloseMask: React.PropTypes.number,
    initializeOpen: React.PropTypes.bool,
    tweenHandler: React.PropTypes.func,
    tweenDuration: React.PropTypes.number,
    tweenEasing: React.PropTypes.string,
    disabled: React.PropTypes.bool,
    acceptDoubleTap: React.PropTypes.bool,
    onOpen: React.PropTypes.func,
    onClose: React.PropTypes.func,
  },

  getDefaultProps () {
    return {
      type: 'displace',
      closedDrawerOffset: 0,
      openDrawerOffset: 0,
      openDrawerThreshold: .25,
      relativeDrag: false,
      panStartCompensation: true,
      panOpenMask: .25,
      panCloseMask: .25,
      initializeOpen: false,
      tweenHandler: null,
      tweenDuration: 250,
      tweenEasing: 'linear',
      disabled: false,
      acceptDoubleTap: false,
      onOpen: () => {},
      onClose: () => {},
    }
  },

  propsWhomRequireUpdate: [
    'closedDrawerOffset',
    'openDrawerOffset',
    'type'
  ],

  shouldComponentUpdate(nextProps, nextState) {
    this.propsWhomRequireUpdate.forEach((key) => {
      if(this.props[key] !== nextProps[key]) return true
    })
    return false
  },

  componentWillReceiveProps(nextProps){
    if(this.shouldComponentUpdate(nextProps)){
      this.initialize(nextProps)
    }
  },

  initialize(props){
    var fullWidth = deviceScreen.width
    this._offsetClosed = props.closedDrawerOffset%1 === 0 ? props.closedDrawerOffset : props.closedDrawerOffset*fullWidth
    this._offsetOpen = props.openDrawerOffset%1 === 0 ? props.openDrawerOffset : props.openDrawerOffset*fullWidth

    var styles = {
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
      },
    }
    styles.main = {
      flex: 1,
      position: 'absolute',
      top: 0,
      height: deviceScreen.height,
    }
    styles.drawer = {
      flex: 1,
      position: 'absolute',
      top: 0,
      height: deviceScreen.height,
    }

    //open
    if(props.initializeOpen === true){
      this._open = true
      this._left = fullWidth - this._offsetOpen
      this._prevLeft = this._left
      if(props.type === 'static'){
        styles.main.left = fullWidth - this._offsetOpen
        styles.drawer.left = 0
        styles.main.width = fullWidth - this._offsetClosed
        styles.drawer.width = fullWidth
      }
      if(props.type === 'overlay'){
        styles.main.left = 0
        styles.drawer.left = 0
        styles.main.width = fullWidth
        styles.drawer.width = fullWidth - this._offsetOpen
      }
      if(props.type === 'displace'){
        styles.main.left = fullWidth - this._offsetOpen
        styles.drawer.left = 0
        styles.main.width = fullWidth - this._offsetClosed
        styles.drawer.width = fullWidth - this._offsetOpen
      }
    }
    //closed
    else{
      this._open = false
      this._left = this._offsetClosed
      this._prevLeft = this._left
      if(props.type === 'static'){
        styles.main.left = this._offsetClosed
        styles.drawer.left = 0
        styles.main.width = fullWidth - this._offsetClosed
        styles.drawer.width = fullWidth
      }
      if(props.type === 'overlay'){
        styles.main.left = this._offsetClosed
        styles.drawer.left = this._offsetClosed + this._offsetOpen - fullWidth
        styles.main.width = fullWidth
        styles.drawer.width = fullWidth - this._offsetOpen
      }
      if(props.type === 'displace'){
        styles.main.left = this._offsetClosed
        styles.drawer.left = - fullWidth + this._offsetClosed + this._offsetOpen
        styles.main.width = fullWidth - this._offsetClosed
        styles.drawer.width = fullWidth - this._offsetOpen
      }
    }

    if(this.refs.main){
      this.refs.drawer.setNativeProps({ left: styles.drawer.left})
      this.refs.main.setNativeProps({ left: styles.main.left})
    }
    else{
      this.stylesheet = StyleSheet.create(styles)

      this.responder = PanResponder.create({
        onStartShouldSetPanResponder: this.handleStartShouldSetPanResponder,
        onPanResponderMove: this.handlePanResponderMove,
        onPanResponderRelease: this.handlePanResponderEnd,
      })
    }
  },

  componentWillMount: function() {
    this.initialize(this.props)
  },

  /**
   * Change `left` style attributes
   * Works only if `drawer` is a ref to React.Component
   * @return {Void}
   */
  updatePosition: function() {
    var mainProps = {}
    var drawerProps = {}

    var maxLeft = this.getMaxLeft()
    var ratio = (this._left-this._offsetClosed)/(this.getMaxLeft()-this._offsetClosed)

    switch(this.props.type){
      case 'overlay':
        drawerProps.left = -deviceScreen.width+this._offsetOpen+this._left
        mainProps.left = this._offsetClosed
        break
      case 'static':
        mainProps.left = this._left
        drawerProps.left = 0
        break
      case 'displace':
        mainProps.left = this._left
        drawerProps.left = -deviceScreen.width+this._left+this._offsetOpen
        break
    }

    if(this.props.tweenHandler){
      var propsFrag = this.props.tweenHandler(ratio)
      mainProps = Object.assign(mainProps, propsFrag.main)
      drawerProps = Object.assign(drawerProps, propsFrag.drawer)
    }
    this.refs.drawer.setNativeProps(drawerProps)
    this.refs.main.setNativeProps(mainProps)
  },

  shouldOpenDrawer(dx: Number) {
    if(this._open){
      return dx < deviceScreen.width*this.props.openDrawerThreshold
    }
    else{
      return dx > deviceScreen.width*this.props.openDrawerThreshold
    }
  },

  /**
   * Permission to use responder
   * @return {Boolean} true
   */
  handleStartShouldSetPanResponder: function(e: Object, gestureState: Object) {
    if(this.props.disabled){ return false }
    var x0 = e.nativeEvent.pageX
    //@TODO lol formatting?
    if(  (this._open && deviceScreen.width - x0 > deviceScreen.width*this.props.panCloseMask)
      || (!this._open && x0 > deviceScreen.width*this.props.panOpenMask)
    ){
      return false
    }

    if(this.props.acceptDoubleTap){
      var now = new Date().getTime()
      if(now - this._lastPress < 500){
        this._open ? this.close() : this.open()
      }
      this._lastPress = now
    }

    return true
  },

  /**
   * Handler on responder move
   * @param  {Synthetic Event} e
   * @param  {Object} gestureState
   * @return {Void}
   */
  handlePanResponderMove: function(e: Object, gestureState: Object) {
    //Math is ugly overly verbose here, probably can be greatly cleaned up
    var dx = gestureState.dx
    //@TODO store adjustedDx max so that it does not uncompensate when panning back
    var dx = gestureState.dx
    //Do nothing if we are panning the wrong way
    if(this._open ^ dx < 0){ return false}

    var absDx = Math.abs(dx)
    var moveX = gestureState.moveX
    var relMoveX = this._open ? -deviceScreen.width + moveX : moveX
    var delta = relMoveX - dx
    var factor = absDx/Math.abs(relMoveX)
    var adjustedDx = dx + delta*factor
    this._left = this.props.panStartCompensation ? this._prevLeft + adjustedDx : this._prevLeft + dx
    this.updatePosition()
    this._panning = true
  },

  /**
   * Open menu
   * @return {Void}
   */
  open: function() {
    if(this.props.disabled){ return null }
    tween({
      start: this._left,
      end: this.getMaxLeft(),
      duration: this.props.tweenDuration,
      easingType: this.props.tweenEasing,
      onFrame: (tweenValue) => {
        this._left = tweenValue
        this.updatePosition()
      },
      onEnd: () => {
        this._open = true
        this._prevLeft = this._left
        this.props.onOpen()
        // @TODO _initializeAfterAnimation ????
      }
    })
  },

  /**
   * Close menu
   * @return {Void}
   */
  close: function() {
    if(this.props.disabled){ return null }
    tween({
      start: this._left,
      end: this.getMinLeft(),
      easingType: this.props.tweenEasing,
      duration: this.props.tweenDuration,
      onFrame: (tweenValue) => {
        this._left = tweenValue
        this.updatePosition()
      },
      onEnd: () => {
        this._open = false
        this._prevLeft = this._left
        this.props.onClose()
        // @TODO _initializeAfterAnimation ????
      }
    })
  },

  openDrawer: function(){
    console.warn('rn-drawer: `openDrawer` is deprecated, use `open` instead.')
    this.open()
  },

  closeDrawer: function(){
    console.warn('rn-drawer: `closeDrawer` is deprecated, use `close` instead.')
    this.close()
  },

  /**
   * Handler on responder move ending
   * @param  {Synthetic Event} e
   * @param  {Object} gestureState
   * @return {Void}
   */
  handlePanResponderEnd: function(e: Object, gestureState: Object) {
    //Do nothing if we are not in an active pan state
    if(!this._panning){ return }
    //@TODO:Reevaluate - If we are panning the wrong way when the pan ends,
    // which animation should trigger?
    // if(this._open ^ gestureState.dx < 0){ return }

    var absRelMoveX = this._open ? deviceScreen.width - gestureState.moveX : gestureState.moveX
    var calcPos = this.props.relativeDrag ? Math.abs(gestureState.dx) : absRelMoveX
    if (this.shouldOpenDrawer(calcPos)) {
      this.open()
    } else {
      this.close()
    }

    this.updatePosition()
    this._prevLeft = this._left
    this._panning = false
  },

  /**
   * Get content view. This view will be rendered over menu
   * @return {React.Component}
   */
  getMainView: function() {
    return (
      <View
        key="main"
        style={this.stylesheet.main}
        ref="main"
        {...this.responder.panHandlers}>
        {this.props.children}
      </View>
    )
  },

  /**
   * Get menu view. This view will be rendered under
   * content view. Also, this function will decorate
   * passed `menu` component with side menu API
   * @return {React.Component}
   */
  getDrawerView: function() {
    var drawerActions = {
      close: this.closeDrawer
    }

    return (
      <View
        key="drawer"
        style={this.stylesheet.drawer}
        ref="drawer"
        {...this.responder.panHandlers}>
        {this.props.content}
      </View>
    )
  },

  /**
   * Compose and render menu and content view
   * @return {React.Component}
   */
  render: function() {
    switch(this.props.type){
      case 'overlay':
        var first = this.getMainView()
        var second = this.getDrawerView()
        break
      default:
        var first = this.getDrawerView()
        var second = this.getMainView()
        break
    }
    return (
      <View style={this.stylesheet.container} key="drawerContainer">
        {first}
        {second}
      </View>
    )
  },

  getMaxLeft: function(){
    return deviceScreen.width - this._offsetOpen
  },

  getMinLeft() {
    return this._offsetClosed
  },

})

module.exports = drawer
<commit_msg>readd styles<commit_after>var React = require('react-native')
var deviceScreen = require('Dimensions').get('window')
var tween = require('./Tweener')

var {
  PanResponder,
  View,
  StyleSheet
} = React

/**
 * Check if the current gesture offset bigger than allowed one
 * before opening menu
 * @param  {Number} dx Gesture offset from the left side of the window
 * @return {Boolean}
 */
var drawer = React.createClass({

  _left: 0,
  _prevLeft: 0,
  _offsetOpen: 0,
  _offsetClosed: 0,
  _open: false,
  _panning: false,
  _tweenPending: false,
  _lastPress: 0,

  propTypes: {
    type: React.PropTypes.string,
    closedDrawerOffset: React.PropTypes.number,
    openDrawerOffset: React.PropTypes.number,
    openDrawerThreshold: React.PropTypes.number,
    relativeDrag: React.PropTypes.bool,
    panStartCompensation: React.PropTypes.bool,
    panOpenMask: React.PropTypes.number,
    panCloseMask: React.PropTypes.number,
    initializeOpen: React.PropTypes.bool,
    tweenHandler: React.PropTypes.func,
    tweenDuration: React.PropTypes.number,
    tweenEasing: React.PropTypes.string,
    disabled: React.PropTypes.bool,
    acceptDoubleTap: React.PropTypes.bool,
    styles: React.PropTypes.object,
    onOpen: React.PropTypes.func,
    onClose: React.PropTypes.func,
  },

  getDefaultProps () {
    return {
      type: 'displace',
      closedDrawerOffset: 0,
      openDrawerOffset: 0,
      openDrawerThreshold: .25,
      relativeDrag: false,
      panStartCompensation: true,
      panOpenMask: .25,
      panCloseMask: .25,
      initializeOpen: false,
      tweenHandler: null,
      tweenDuration: 250,
      tweenEasing: 'linear',
      disabled: false,
      acceptDoubleTap: false,
      onOpen: () => {},
      onClose: () => {},
    }
  },

  propsWhomRequireUpdate: [
    'closedDrawerOffset',
    'openDrawerOffset',
    'type'
  ],

  shouldComponentUpdate(nextProps, nextState) {
    this.propsWhomRequireUpdate.forEach((key) => {
      if(this.props[key] !== nextProps[key]) return true
    })
    return false
  },

  componentWillReceiveProps(nextProps){
    if(this.shouldComponentUpdate(nextProps)){
      this.initialize(nextProps)
    }
  },

  initialize(props){
    var fullWidth = deviceScreen.width
    this._offsetClosed = props.closedDrawerOffset%1 === 0 ? props.closedDrawerOffset : props.closedDrawerOffset*fullWidth
    this._offsetOpen = props.openDrawerOffset%1 === 0 ? props.openDrawerOffset : props.openDrawerOffset*fullWidth

    var styles = {
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
      },
    }
    styles.main = Object.assign({
        flex: 1,
        position: 'absolute',
        top: 0,
        height: deviceScreen.height,
      }, this.props.styles.main)
    styles.drawer = Object.assign({
        flex: 1,
        position: 'absolute',
        top: 0,
        height: deviceScreen.height,
      }, this.props.styles.drawer)

    //open
    if(props.initializeOpen === true){
      this._open = true
      this._left = fullWidth - this._offsetOpen
      this._prevLeft = this._left
      if(props.type === 'static'){
        styles.main.left = fullWidth - this._offsetOpen
        styles.drawer.left = 0
        styles.main.width = fullWidth - this._offsetClosed
        styles.drawer.width = fullWidth
      }
      if(props.type === 'overlay'){
        styles.main.left = 0
        styles.drawer.left = 0
        styles.main.width = fullWidth
        styles.drawer.width = fullWidth - this._offsetOpen
      }
      if(props.type === 'displace'){
        styles.main.left = fullWidth - this._offsetOpen
        styles.drawer.left = 0
        styles.main.width = fullWidth - this._offsetClosed
        styles.drawer.width = fullWidth - this._offsetOpen
      }
    }
    //closed
    else{
      this._open = false
      this._left = this._offsetClosed
      this._prevLeft = this._left
      if(props.type === 'static'){
        styles.main.left = this._offsetClosed
        styles.drawer.left = 0
        styles.main.width = fullWidth - this._offsetClosed
        styles.drawer.width = fullWidth
      }
      if(props.type === 'overlay'){
        styles.main.left = this._offsetClosed
        styles.drawer.left = this._offsetClosed + this._offsetOpen - fullWidth
        styles.main.width = fullWidth
        styles.drawer.width = fullWidth - this._offsetOpen
      }
      if(props.type === 'displace'){
        styles.main.left = this._offsetClosed
        styles.drawer.left = - fullWidth + this._offsetClosed + this._offsetOpen
        styles.main.width = fullWidth - this._offsetClosed
        styles.drawer.width = fullWidth - this._offsetOpen
      }
    }

    if(this.refs.main){
      this.refs.drawer.setNativeProps({ left: styles.drawer.left})
      this.refs.main.setNativeProps({ left: styles.main.left})
    }
    else{
      this.stylesheet = StyleSheet.create(styles)

      this.responder = PanResponder.create({
        onStartShouldSetPanResponder: this.handleStartShouldSetPanResponder,
        onPanResponderMove: this.handlePanResponderMove,
        onPanResponderRelease: this.handlePanResponderEnd,
      })
    }
  },

  componentWillMount: function() {
    this.initialize(this.props)
  },

  /**
   * Change `left` style attributes
   * Works only if `drawer` is a ref to React.Component
   * @return {Void}
   */
  updatePosition: function() {
    var mainProps = {}
    var drawerProps = {}

    var maxLeft = this.getMaxLeft()
    var ratio = (this._left-this._offsetClosed)/(this.getMaxLeft()-this._offsetClosed)

    switch(this.props.type){
      case 'overlay':
        drawerProps.left = -deviceScreen.width+this._offsetOpen+this._left
        mainProps.left = this._offsetClosed
        break
      case 'static':
        mainProps.left = this._left
        drawerProps.left = 0
        break
      case 'displace':
        mainProps.left = this._left
        drawerProps.left = -deviceScreen.width+this._left+this._offsetOpen
        break
    }

    if(this.props.tweenHandler){
      var propsFrag = this.props.tweenHandler(ratio)
      mainProps = Object.assign(mainProps, propsFrag.main)
      drawerProps = Object.assign(drawerProps, propsFrag.drawer)
    }
    this.refs.drawer.setNativeProps(drawerProps)
    this.refs.main.setNativeProps(mainProps)
  },

  shouldOpenDrawer(dx: Number) {
    if(this._open){
      return dx < deviceScreen.width*this.props.openDrawerThreshold
    }
    else{
      return dx > deviceScreen.width*this.props.openDrawerThreshold
    }
  },

  /**
   * Permission to use responder
   * @return {Boolean} true
   */
  handleStartShouldSetPanResponder: function(e: Object, gestureState: Object) {
    if(this.props.disabled){ return false }
    var x0 = e.nativeEvent.pageX
    //@TODO lol formatting?
    if(  (this._open && deviceScreen.width - x0 > deviceScreen.width*this.props.panCloseMask)
      || (!this._open && x0 > deviceScreen.width*this.props.panOpenMask)
    ){
      return false
    }

    if(this.props.acceptDoubleTap){
      var now = new Date().getTime()
      if(now - this._lastPress < 500){
        this._open ? this.close() : this.open()
      }
      this._lastPress = now
    }

    return true
  },

  /**
   * Handler on responder move
   * @param  {Synthetic Event} e
   * @param  {Object} gestureState
   * @return {Void}
   */
  handlePanResponderMove: function(e: Object, gestureState: Object) {
    //Math is ugly overly verbose here, probably can be greatly cleaned up
    var dx = gestureState.dx
    //@TODO store adjustedDx max so that it does not uncompensate when panning back
    var dx = gestureState.dx
    //Do nothing if we are panning the wrong way
    if(this._open ^ dx < 0){ return false}

    var absDx = Math.abs(dx)
    var moveX = gestureState.moveX
    var relMoveX = this._open ? -deviceScreen.width + moveX : moveX
    var delta = relMoveX - dx
    var factor = absDx/Math.abs(relMoveX)
    var adjustedDx = dx + delta*factor
    this._left = this.props.panStartCompensation ? this._prevLeft + adjustedDx : this._prevLeft + dx
    this.updatePosition()
    this._panning = true
  },

  /**
   * Open menu
   * @return {Void}
   */
  open: function() {
    if(this.props.disabled){ return null }
    tween({
      start: this._left,
      end: this.getMaxLeft(),
      duration: this.props.tweenDuration,
      easingType: this.props.tweenEasing,
      onFrame: (tweenValue) => {
        this._left = tweenValue
        this.updatePosition()
      },
      onEnd: () => {
        this._open = true
        this._prevLeft = this._left
        this.props.onOpen()
        // @TODO _initializeAfterAnimation ????
      }
    })
  },

  /**
   * Close menu
   * @return {Void}
   */
  close: function() {
    if(this.props.disabled){ return null }
    tween({
      start: this._left,
      end: this.getMinLeft(),
      easingType: this.props.tweenEasing,
      duration: this.props.tweenDuration,
      onFrame: (tweenValue) => {
        this._left = tweenValue
        this.updatePosition()
      },
      onEnd: () => {
        this._open = false
        this._prevLeft = this._left
        this.props.onClose()
        // @TODO _initializeAfterAnimation ????
      }
    })
  },

  openDrawer: function(){
    console.warn('rn-drawer: `openDrawer` is deprecated, use `open` instead.')
    this.open()
  },

  closeDrawer: function(){
    console.warn('rn-drawer: `closeDrawer` is deprecated, use `close` instead.')
    this.close()
  },

  /**
   * Handler on responder move ending
   * @param  {Synthetic Event} e
   * @param  {Object} gestureState
   * @return {Void}
   */
  handlePanResponderEnd: function(e: Object, gestureState: Object) {
    //Do nothing if we are not in an active pan state
    if(!this._panning){ return }
    //@TODO:Reevaluate - If we are panning the wrong way when the pan ends,
    // which animation should trigger?
    // if(this._open ^ gestureState.dx < 0){ return }

    var absRelMoveX = this._open ? deviceScreen.width - gestureState.moveX : gestureState.moveX
    var calcPos = this.props.relativeDrag ? Math.abs(gestureState.dx) : absRelMoveX
    if (this.shouldOpenDrawer(calcPos)) {
      this.open()
    } else {
      this.close()
    }

    this.updatePosition()
    this._prevLeft = this._left
    this._panning = false
  },

  /**
   * Get content view. This view will be rendered over menu
   * @return {React.Component}
   */
  getMainView: function() {
    return (
      <View
        key="main"
        style={this.stylesheet.main}
        ref="main"
        {...this.responder.panHandlers}>
        {this.props.children}
      </View>
    )
  },

  /**
   * Get menu view. This view will be rendered under
   * content view. Also, this function will decorate
   * passed `menu` component with side menu API
   * @return {React.Component}
   */
  getDrawerView: function() {
    var drawerActions = {
      close: this.closeDrawer
    }

    return (
      <View
        key="drawer"
        style={this.stylesheet.drawer}
        ref="drawer"
        {...this.responder.panHandlers}>
        {this.props.content}
      </View>
    )
  },

  /**
   * Compose and render menu and content view
   * @return {React.Component}
   */
  render: function() {
    switch(this.props.type){
      case 'overlay':
        var first = this.getMainView()
        var second = this.getDrawerView()
        break
      default:
        var first = this.getDrawerView()
        var second = this.getMainView()
        break
    }
    return (
      <View style={this.stylesheet.container} key="drawerContainer">
        {first}
        {second}
      </View>
    )
  },

  getMaxLeft: function(){
    return deviceScreen.width - this._offsetOpen
  },

  getMinLeft() {
    return this._offsetClosed
  },

})

module.exports = drawer
<|endoftext|>


<commit_before>var JSONStream = require('JSONStream');
var through = require('through2');
var umd = require('umd');

var fs = require('fs');
var path = require('path');

var combineSourceMap = require('combine-source-map');

var defaultPreludePath = path.join(__dirname, '_prelude.js');
var defaultPrelude = fs.readFileSync(defaultPreludePath, 'utf8');

function newlinesIn(src) {
  if (!src) return 0;
  var newlines = src.match(/\n/g);

  return newlines ? newlines.length : 0;
}

module.exports = function (opts) {
    if (!opts) opts = {};
    var parser = opts.raw ? through.obj() : JSONStream.parse([ true ]);
    var stream = through.obj(
        function (buf, enc, next) { parser.write(buf); next() },
        function () { parser.end() }
    );
    parser.pipe(through.obj(write, end));
    stream.standaloneModule = opts.standaloneModule;

    var first = true;
    var entries = [];
    var prelude = opts.prelude || defaultPrelude;
    var preludePath = opts.preludePath || defaultPreludePath;

    var lineno = 1 + newlinesIn(prelude);
    var sourcemap;

    return stream;

    function write (row, enc, next) {
        if (first && opts.standalone) {
            var pre = umd.prelude(opts.standalone).trim();
            stream.push(pre + 'return ');
        }
        else if (first && opts.hasExports) {
            var pre = opts.externalRequireName || 'require';
            this.push(pre + '=');
        }
        if (first) stream.push(prelude + '({');

        if (row.sourceFile && !row.nomap) {
            if (!sourcemap) {
                sourcemap = combineSourceMap.create();
                sourcemap.addFile(
                    { sourceFile: preludePath, source: prelude },
                    { line: 0 }
                );
            }
            sourcemap.addFile(
                { sourceFile: row.sourceFile, source: row.source },
                { line: lineno }
            );
        }

        var wrappedSource = [
            (first ? '' : ','),
            JSON.stringify(row.id),
            ':[',
            'function(require,module,exports){\n',
            combineSourceMap.removeComments(row.source),
            '\n},',
            '{' + Object.keys(row.deps || {}).sort().map(function (key) {
                return JSON.stringify(key) + ':'
                    + JSON.stringify(row.deps[key])
                ;
            }).join(',') + '}',
            ']'
        ].join('');

        stream.push(wrappedSource);
        lineno += newlinesIn(wrappedSource);

        first = false;
        if (row.entry && row.order !== undefined) {
            entries[row.order] = row.id;
        }
        else if (row.entry) entries.push(row.id);
        next();
    }

    function end () {
        if (first) stream.push(prelude + '({');
        entries = entries.filter(function (x) { return x !== undefined });

        stream.push('},{},' + JSON.stringify(entries) + ')');

        if (opts.standalone) {
            stream.push(
                '(' + JSON.stringify(stream.standaloneModule) + ')'
                + umd.postlude(opts.standalone)
            );
        }

        if (sourcemap) {
            var comment = sourcemap.comment();
            if (opts.sourceMapPrefix) {
                comment = comment.replace(
                    /^\/\/#/, function () { return opts.sourceMapPrefix }
                )
            }
            stream.push('\n' + comment);
        }
        if (!sourcemap && !opts.standalone) stream.push(';\n');

        stream.push(null);
    }
};
<commit_msg>hasExports<commit_after>var JSONStream = require('JSONStream');
var through = require('through2');
var umd = require('umd');

var fs = require('fs');
var path = require('path');

var combineSourceMap = require('combine-source-map');

var defaultPreludePath = path.join(__dirname, '_prelude.js');
var defaultPrelude = fs.readFileSync(defaultPreludePath, 'utf8');

function newlinesIn(src) {
  if (!src) return 0;
  var newlines = src.match(/\n/g);

  return newlines ? newlines.length : 0;
}

module.exports = function (opts) {
    if (!opts) opts = {};
    var parser = opts.raw ? through.obj() : JSONStream.parse([ true ]);
    var stream = through.obj(
        function (buf, enc, next) { parser.write(buf); next() },
        function () { parser.end() }
    );
    parser.pipe(through.obj(write, end));
    stream.standaloneModule = opts.standaloneModule;
    stream.hasExports = opts.hasExports;

    var first = true;
    var entries = [];
    var prelude = opts.prelude || defaultPrelude;
    var preludePath = opts.preludePath || defaultPreludePath;

    var lineno = 1 + newlinesIn(prelude);
    var sourcemap;

    return stream;

    function write (row, enc, next) {
        if (first && opts.standalone) {
            var pre = umd.prelude(opts.standalone).trim();
            stream.push(pre + 'return ');
        }
        else if (first && stream.hasExports) {
            var pre = opts.externalRequireName || 'require';
            stream.push(pre + '=');
        }
        if (first) stream.push(prelude + '({');

        if (row.sourceFile && !row.nomap) {
            if (!sourcemap) {
                sourcemap = combineSourceMap.create();
                sourcemap.addFile(
                    { sourceFile: preludePath, source: prelude },
                    { line: 0 }
                );
            }
            sourcemap.addFile(
                { sourceFile: row.sourceFile, source: row.source },
                { line: lineno }
            );
        }

        var wrappedSource = [
            (first ? '' : ','),
            JSON.stringify(row.id),
            ':[',
            'function(require,module,exports){\n',
            combineSourceMap.removeComments(row.source),
            '\n},',
            '{' + Object.keys(row.deps || {}).sort().map(function (key) {
                return JSON.stringify(key) + ':'
                    + JSON.stringify(row.deps[key])
                ;
            }).join(',') + '}',
            ']'
        ].join('');

        stream.push(wrappedSource);
        lineno += newlinesIn(wrappedSource);

        first = false;
        if (row.entry && row.order !== undefined) {
            entries[row.order] = row.id;
        }
        else if (row.entry) entries.push(row.id);
        next();
    }

    function end () {
        if (first) stream.push(prelude + '({');
        entries = entries.filter(function (x) { return x !== undefined });

        stream.push('},{},' + JSON.stringify(entries) + ')');

        if (opts.standalone) {
            stream.push(
                '(' + JSON.stringify(stream.standaloneModule) + ')'
                + umd.postlude(opts.standalone)
            );
        }

        if (sourcemap) {
            var comment = sourcemap.comment();
            if (opts.sourceMapPrefix) {
                comment = comment.replace(
                    /^\/\/#/, function () { return opts.sourceMapPrefix }
                )
            }
            stream.push('\n' + comment);
        }
        if (!sourcemap && !opts.standalone) stream.push(';\n');

        stream.push(null);
    }
};
<|endoftext|>


<commit_before>export default class Affixed {
  constructor(options = {}) {
    this.isTicking = false;
    // merge options
    const DEFAULTS = {
      element: null,
      offset: 0,
      type: 'absolute',
    };
    this.options = Object.assign({}, DEFAULTS, options);
    // retrieve the computer styles for the parent element
    this.parentStyles = window.getComputedStyle(this.options.element.parentNode);
    this.parentMarginBottom = parseInt(this.parentStyles.marginBottom, 10);
    // register window scroll event
    window.addEventListener('scroll', ::this.onWindowScroll);
  }

  /**
   * Implemented with rAF (https://developer.mozilla.org/en-US/docs/Web/Events/scroll)
   */
  onWindowScroll(e) {
    this.lastY = window.scrollY;
    if (!this.isTicking) {
      window.requestAnimationFrame(() => {
        const elementHeight = this.options.element.clientHeight;
        // if scrolled passed the given offset
        if (this.lastY > this.options.offset) {
          // apply the position
          this.options.element.style.position = this.options.type;
          this.options.element.style.width = '100%';
          // re-position the element based on the type (fixed, or absolute)
          switch (this.options.type) {
            case 'fixed':
              this.options.element.style.top = '0px';
              break;
            case 'absolute':
              this.options.element.style.top = this.lastY + 'px';
              this.options.element.parentNode.style.marginBottom = (this.parentMarginBottom + elementHeight) + 'px';
              break;
          }
        } else {
          this.options.element.style.position = 'static';
          this.options.element.parentNode.style.marginBottom = this.parentMarginBottom + 'px';
        }
        // not ticking
        this.isTicking = false;
      });
    }
    // currently ticking
    this.isTicking = true;
  }

}
<commit_msg>renamed param<commit_after>export default class Affixed {
  constructor(options = {}) {
    this.isTicking = false;
    // merge options
    const DEFAULTS = {
      element: null,
      offset: 0,
      position: 'absolute',
    };
    this.options = Object.assign({}, DEFAULTS, options);
    // retrieve the computer styles for the parent element
    this.parentStyles = window.getComputedStyle(this.options.element.parentNode);
    this.parentMarginBottom = parseInt(this.parentStyles.marginBottom, 10);
    // register window scroll event
    window.addEventListener('scroll', ::this.onWindowScroll);
  }

  /**
   * Implemented with rAF (https://developer.mozilla.org/en-US/docs/Web/Events/scroll)
   */
  onWindowScroll(e) {
    this.lastY = window.scrollY;
    if (!this.isTicking) {
      window.requestAnimationFrame(() => {
        const elementHeight = this.options.element.clientHeight;
        // if scrolled passed the given offset
        if (this.lastY > this.options.offset) {
          // apply the position
          this.options.element.style.position = this.options.position;
          this.options.element.style.width = '100%';
          // re-position the element based on the position ("fixed", or "absolute")
          switch (this.options.position) {
            case 'fixed':
              this.options.element.style.top = '0px';
              break;
            case 'absolute':
              this.options.element.style.top = this.lastY + 'px';
              this.options.element.parentNode.style.marginBottom = (this.parentMarginBottom + elementHeight) + 'px';
              break;
          }
        } else {
          this.options.element.style.position = 'static';
          this.options.element.parentNode.style.marginBottom = this.parentMarginBottom + 'px';
        }
        // not ticking
        this.isTicking = false;
      });
    }
    // currently ticking
    this.isTicking = true;
  }

}
<|endoftext|>


<commit_before>// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 8080;

server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

// Routing
app.use(express.static(__dirname + '/public'));

// Chatroom

var numUsers = 0;

io.on('connection', function (socket) {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new message', function (data) {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (username) {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the client emits 'typing', we broadcast it to others
  socket.on('typing', function () {
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  // when the client emits 'stop typing', we broadcast it to others
  socket.on('stop typing', function () {
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });
});
<commit_msg>change config<commit_after>// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);

var ip = process.env.OPENSHIFT_NODEJS_IP || '192.168.1.102';
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;

server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

// Routing
app.use(express.static(__dirname + '/public'));

// Chatroom

var numUsers = 0;

io.on('connection', function (socket) {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new message', function (data) {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (username) {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the client emits 'typing', we broadcast it to others
  socket.on('typing', function () {
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  // when the client emits 'stop typing', we broadcast it to others
  socket.on('stop typing', function () {
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });
});
<|endoftext|>


<commit_before>var request = require('request');
var Q = require('q');

var ReCaptcha = function(options){
  if(!options.secret){
    throw new Error('No ReCaptcha Secret (Please provide your API secret key)')
  } else {
    this.secret = options.secret;
  }

  if(options.sendIp){
    this.sendIp = true;
  }

  if(options.endRequest){
    this.endRequest = true;
  }

  this.secret = options.secret;
};

ReCaptcha.prototype = {
  secret: null,
  sendIp: false,
  endRequest: false
};

ReCaptcha.middleware = function(req, res, next){
  if(!req.body['g-recaptcha-response'] || !req.body.recaptcha){
    res.status(400).end();
  } else {
    var options = {
      response: req.body['g-recaptcha-response'] || req.body.recaptcha
    };

    if(this.sendIp){
      options.remoteip = req.ip;
    }

    this._checkToken(options).then(function(response){
      req.recaptcha = response;
      next();
    }, function(response){
      req.recaptcha = response;
      if(this.endRequest){
        res.status(400).end();
      } else {
        next();
      }
    })
  }
};

ReCaptcha.prototype.check = function(token, ip){
  var deferred = Q.defer();

  if(!token){
    deferred.reject(new Error('No token supplied'));
  } else {
    var options = {
      response: token
    };

    if(ip){
      options.remoteip = ip;
    }

    this._checkToken(options).then(function(response){
      deferred.resolve(response);
    }, function(response){
      deferred.reject(response);
    })
  }

  return deferred.promise;
};

ReCaptcha.prototype._checkToken = function(options){
  var data = {
    secret: this.secret,
    response: options.response
  };

  if(options.ip && this.sendIp){
    data.remoteip = options.ip;
  }

  var deferred = Q.defer();

  var url = 'https://www.google.com/recaptcha/api/siteverify';

  request.post(url, {form:data}, function (err, res, body) {
    body = JSON.parse(body);

    if(err){
      deferred.reject(err);
    }

    if(body.success){
      deferred.resolve(body);
    } else {
      deferred.reject(body);
    }
  });

  return deferred.promise;
};

ReCaptcha.prototype.secret = function(input){
  if(input){
    this.secret = input;
  }

  return this.secret;
};

ReCaptcha.prototype.sendIp = function(input){
  if(input){
    this.sendIp = input;
  }

  return this.sendIp;
};

module.exports = ReCaptcha;
<commit_msg>Utility method for endRequest parameter<commit_after>var request = require('request');
var Q = require('q');

var ReCaptcha = function(options){
  if(!options.secret){
    throw new Error('No ReCaptcha Secret (Please provide your API secret key)')
  } else {
    this.secret = options.secret;
  }

  if(options.sendIp){
    this.sendIp = true;
  }

  if(options.endRequest){
    this.endRequest = true;
  }

  this.secret = options.secret;
};

ReCaptcha.prototype = {
  secret: null,
  sendIp: false,
  endRequest: false
};

ReCaptcha.middleware = function(req, res, next){
  if(!req.body['g-recaptcha-response'] || !req.body.recaptcha){
    res.status(400).end();
  } else {
    var options = {
      response: req.body['g-recaptcha-response'] || req.body.recaptcha
    };

    if(this.sendIp){
      options.remoteip = req.ip;
    }

    this._checkToken(options).then(function(response){
      req.recaptcha = response;
      next();
    }, function(response){
      req.recaptcha = response;
      if(this.endRequest){
        res.status(400).end();
      } else {
        next();
      }
    })
  }
};

ReCaptcha.prototype.check = function(token, ip){
  var deferred = Q.defer();

  if(!token){
    deferred.reject(new Error('No token supplied'));
  } else {
    var options = {
      response: token
    };

    if(ip){
      options.remoteip = ip;
    }

    this._checkToken(options).then(function(response){
      deferred.resolve(response);
    }, function(response){
      deferred.reject(response);
    })
  }

  return deferred.promise;
};

ReCaptcha.prototype._checkToken = function(options){
  var data = {
    secret: this.secret,
    response: options.response
  };

  if(options.ip && this.sendIp){
    data.remoteip = options.ip;
  }

  var deferred = Q.defer();

  var url = 'https://www.google.com/recaptcha/api/siteverify';

  request.post(url, {form:data}, function (err, res, body) {
    body = JSON.parse(body);

    if(err){
      deferred.reject(err);
    }

    if(body.success){
      deferred.resolve(body);
    } else {
      deferred.reject(body);
    }
  });

  return deferred.promise;
};

ReCaptcha.prototype.secret = function(input){
  if(input){
    this.secret = input;
  }

  return this.secret;
};

ReCaptcha.prototype.sendIp = function(input){
  if(input){
    this.sendIp = input;
  }

  return this.sendIp;
};

ReCaptcha.prototype.endRequest = function(input){
  if(input){
    this.endRequest = input;
  }

  return this.endRequest;
};

module.exports = ReCaptcha;
<|endoftext|>


<commit_before>/*!
 * array-slice <https://github.com/jonschlinkert/array-slice>
 *
 * Copyright (c) 2014-2015, 2017, Jon Schlinkert.
 * Released under the MIT License.
 */

'use strict';

module.exports = function slice(arr, start, end) {
  var len = arr.length;
  var range = [];

  start = idx(arr, start);
  end = idx(arr, end, len);

  while (start < end) {
    range.push(arr[start++]);
  }
  return range;
};

function idx(arr, pos, end) {
  var len = arr.length;

  if (pos == null) {
    pos = end || 0;
  } else if (pos < 0) {
    pos = Math.max(len + pos, 0);
  } else {
    pos = Math.min(pos, len);
  }

  return pos;
}
<commit_msg>update idx method first paramter from pass Array to pass Array's length.<commit_after>/*!
 * array-slice <https://github.com/jonschlinkert/array-slice>
 *
 * Copyright (c) 2014-2015, 2017, Jon Schlinkert.
 * Released under the MIT License.
 */

'use strict';

module.exports = function slice(arr, start, end) {
  var len = arr.length;
  var range = [];

  start = idx(len, start);
  end = idx(len, end, len);

  while (start < end) {
    range.push(arr[start++]);
  }
  return range;
};

function idx(len, pos, end) {
  if (pos == null) {
    pos = end || 0;
  } else if (pos < 0) {
    pos = Math.max(len + pos, 0);
  } else {
    pos = Math.min(pos, len);
  }

  return pos;
}
<|endoftext|>


<commit_before>const SHORTSPLIT = /$|[!-@\[-`{-~]/

module.exports = function(args, opts) {
  opts = opts || {}
  var alias = aliases(opts.alias)
  return parse(
    args,
    alias,
    defaults(opts.default, alias),
    opts.unknown,
    { _: [] }
  )
}

function parse(args, aliases, defaults, unknown, out) {
  for (var i = 0, j = 0, len = args.length, _ = out._; i < len; i++) {
    var arg = args[i]

    if ("--" === arg) {
      while (++i < len) {
        _.push(args[i])
      }
    } else if ("-" === arg[0]) {
      if ("-" === arg[1]) {
        var end = arg.indexOf("=")
        if (0 <= end) {
          set(arg.slice(2, end), arg.slice(end + 1), out, aliases, unknown)
        } else {
          if ("n" === arg[2] && "o" === arg[3] && "-" === arg[4]) {
            set(arg.slice(5), false, out, aliases, unknown)
          } else {
            set(
              arg.slice(2),
              (j = i + 1) === len || "-" === args[j][0] || args[(i = j)],
              out,
              aliases,
              unknown
            )
          }
        }
      } else {
        var end = arg.slice(2).search(SHORTSPLIT) + 2
        var value = end === arg.length
          ? (j = i + 1) === len || "-" === args[j][0] || args[(i = j)]
          : arg.slice(end)

        for (j = 1; j < end; ) {
          set(arg[j], ++j !== end || value, out, aliases, unknown)
        }
      }
    } else {
      _.push(arg)
    }
  }

  for (var key in defaults) {
    if (undefined === out[key]) {
      out[key] = defaults[key]
    }
  }

  return out
}

function aliases(aliases) {
  var out = {}

  for (var key in aliases) {
    var alias = (out[key] = toArray(aliases[key]))

    for (var i = 0, len = alias.length; i < len; i++) {
      var curr = (out[alias[i]] = [key])

      for (var j = 0; j < len; j++) {
        if (i !== j) {
          curr.push(alias[j])
        }
      }
    }
  }

  return out
}

function defaults(defaults, aliases) {
  var out = {}

  for (var key in defaults) {
    var value = defaults[key];
    var alias = aliases[key];

    if (undefined === out[key]) {
      out[key] = value;

      if (undefined !== alias) {
        for (var i = 0, len = alias.length; i < len; i++) {
          out[alias[i]] = value
        }
      }
    }
  }

  return out
}

function set(key, value, out, aliases, unknown) {
  var curr = out[key]
  var alias = aliases[key]
  var hasAlias = undefined !== alias

  if (hasAlias || undefined === unknown || unknown(key) !== false) {
    if (undefined === curr) {
      out[key] = value
    } else {
      if (Array.isArray(curr)) {
        curr.push(value)
      } else {
        out[key] = [curr, value]
      }
    }

    if (hasAlias) {
      for (var i = 0, len = alias.length; i < len; ) {
        out[alias[i++]] = out[key]
      }
    }
  }
}

function toArray(any) {
  return Array.isArray(any) ? any : [any]
}
<commit_msg>Optimize shortsplitting (#22)<commit_after>const SHORTSPLIT = /$|[!-@\[-`{-~].*/g

module.exports = function(args, opts) {
  opts = opts || {}
  var alias = aliases(opts.alias)
  return parse(
    args,
    alias,
    defaults(opts.default, alias),
    opts.unknown,
    { _: [] }
  )
}

function parse(args, aliases, defaults, unknown, out) {
  for (var i = 0, j = 0, len = args.length, _ = out._; i < len; i++) {
    var arg = args[i]

    if ("--" === arg) {
      while (++i < len) {
        _.push(args[i])
      }
    } else if ("-" === arg[0]) {
      if ("-" === arg[1]) {
        var end = arg.indexOf("=")
        if (0 <= end) {
          set(arg.slice(2, end), arg.slice(end + 1), out, aliases, unknown)
        } else {
          if ("n" === arg[2] && "o" === arg[3] && "-" === arg[4]) {
            set(arg.slice(5), false, out, aliases, unknown)
          } else {
            set(
              arg.slice(2),
              (j = i + 1) === len || "-" === args[j][0] || args[(i = j)],
              out,
              aliases,
              unknown
            )
          }
        }
      } else {
        SHORTSPLIT.lastIndex = 2
        var match = SHORTSPLIT.exec(arg)
        var value = match[0] || (j = i + 1) === len || "-" === args[j][0] || args[(i = j)]
        var end = match.index

        for (j = 1; j < end; ) {
          set(arg[j], ++j !== end || value, out, aliases, unknown)
        }
      }
    } else {
      _.push(arg)
    }
  }

  for (var key in defaults) {
    if (undefined === out[key]) {
      out[key] = defaults[key]
    }
  }

  return out
}

function aliases(aliases) {
  var out = {}

  for (var key in aliases) {
    var alias = (out[key] = toArray(aliases[key]))

    for (var i = 0, len = alias.length; i < len; i++) {
      var curr = (out[alias[i]] = [key])

      for (var j = 0; j < len; j++) {
        if (i !== j) {
          curr.push(alias[j])
        }
      }
    }
  }

  return out
}

function defaults(defaults, aliases) {
  var out = {}

  for (var key in defaults) {
    var value = defaults[key];
    var alias = aliases[key];

    if (undefined === out[key]) {
      out[key] = value;

      if (undefined !== alias) {
        for (var i = 0, len = alias.length; i < len; i++) {
          out[alias[i]] = value
        }
      }
    }
  }

  return out
}

function set(key, value, out, aliases, unknown) {
  var curr = out[key]
  var alias = aliases[key]
  var hasAlias = undefined !== alias

  if (hasAlias || undefined === unknown || unknown(key) !== false) {
    if (undefined === curr) {
      out[key] = value
    } else {
      if (Array.isArray(curr)) {
        curr.push(value)
      } else {
        out[key] = [curr, value]
      }
    }

    if (hasAlias) {
      for (var i = 0, len = alias.length; i < len; ) {
        out[alias[i++]] = out[key]
      }
    }
  }
}

function toArray(any) {
  return Array.isArray(any) ? any : [any]
}
<|endoftext|>


<commit_before>const DEBUG = require ('debug');
const debug = DEBUG('main');

const appRoot = require ('app-root-path');
var i2c = require('i2c-bus'), //https://github.com/fivdi/i2c-bus
	i2c1 = i2c.openSync(1);

var BMP280 = require (appRoot + "/modules/BMP280");
var bmp280 = new BMP280 (i2c1);

debug ("Running");

var devs = i2c1.scanSync();
debug ("Devices: " + JSON.stringify (devs));

var t = bmp280.read_temp ();
debug ("I think the temperature is " + t + "C");
debug ("I think the temperature is " + (t*9/5 +32) + "F");

var p = bmp280.read_pressure ();
debug ("I think the pressure is " + p/1000 + "kPa");
debug ("I think the pressure is " + p/1000 * 0.2952998 + "inHg");

debug ("calibrating...")
bmp280.load_calibration (false)

var t = bmp280.read_temp ();
debug ("I think the temperature is " + t + "C");
debug ("I think the temperature is " + (t*9/5 +32) + "F");

var p = bmp280.read_pressure ();
debug ("I think the pressure is " + p/1000 + "kPa");
debug ("I think the pressure is " + p/1000 * 0.2952998 + "inHg");

debug ("Done.");<commit_msg>added test code for altitude and sea level pressure<commit_after>const DEBUG = require ('debug');
const debug = DEBUG('main');

const appRoot = require ('app-root-path');
var i2c = require('i2c-bus'), //https://github.com/fivdi/i2c-bus
	i2c1 = i2c.openSync(1);

var BMP280 = require (appRoot + "/modules/BMP280");
var bmp280 = new BMP280 (i2c1);

debug ("Running");

var devs = i2c1.scanSync();
debug ("Devices: " + JSON.stringify (devs));

var t = bmp280.read_temp ();
debug ("I think the temperature is " + t + "C");
debug ("I think the temperature is " + (t*9/5 +32) + "F");

var p = bmp280.read_pressure ();
debug ("I think the pressure is " + p/1000 + " kPa");
debug ("I think the pressure is " + p/1000 * 0.2952998 + " inHg");

debug ("calibrating...")
bmp280.load_calibration (false)

var t = bmp280.read_temp ();
debug ("I think the temperature is " + t + "C");
debug ("I think the temperature is " + (t*9/5 +32) + "F");

var p = bmp280.read_pressure ();
debug ("I think the pressure is " + p/1000 + " kPa");
debug ("I think the pressure is " + p/1000 * 0.2952998 + " inHg");

var alt = bmp280.read_altitude();
debug ("Altitude is " + alt + " m");

var slp = bmp280.read_sealevel_pressure (alt);
debug ("Sea level pressure: " + slp + " Pa");

debug ("Done.");<|endoftext|>


<commit_before>var transformTools = require('browserify-transform-tools');
var glob = require('glob');
var path = require('path');

module.exports = transformTools.makeRequireTransform('require-globify', {
    jsFilesOnly: true,
    evaluateArguments: true
  },
  function (args, opts, done) {
    var optsObj = args[1];
    if (typeof  optsObj !== 'undefined' && (optsObj.hash || optsObj.glob)) {
      var cwd = path.dirname(opts.file),
        globPattern = args[0],
        files = glob.sync(globPattern, {
          cwd: cwd
        });
      if (files.length !== 0 && files.length > 0) {
        var modules = [];
        var replacement;
        for (var fi = 0, fl = files.length; fi < fl; fi++) {
          if (path.resolve(cwd, files[fi]) !== opts.file) {
            modules.push(files[fi]);
          }
        }
        if ((typeof optsObj.hash !== "undefined" && optsObj.hash !== null && optsObj.hash !== false)) {
          for (var mi = 0, mil = modules.length; mi < mil; mi++) {
            var module = modules[mi];
            var hashProp = optsObj.ext ? path.basename(module) : path.basename(module, path.extname(module));
            modules[mi] = '"' + hashProp + '": require(\'' + module + '\')';
          }
          replacement = '{' + modules.join(', ') + '}';
        } else {
          replacement = 'require(\'' + modules.join('\');\nrequire(\'') + '\')';
        }
        done(null, replacement);
      } else {
        done('Glob expression "' + globPattern + '" couldn\'t find any files');
      }
    } else {
      done();
    }
  }
);<commit_msg>Fixed bug where extensions were applied inside the require call when they shouldn't be<commit_after>var transformTools = require('browserify-transform-tools');
var glob = require('glob');
var path = require('path');

module.exports = transformTools.makeRequireTransform('require-globify', {
    jsFilesOnly: true,
    evaluateArguments: true
  },
  function (args, opts, done) {
    var optsObj = args[1];
    if (typeof  optsObj !== 'undefined' && (optsObj.hash || optsObj.glob)) {
      var cwd = path.dirname(opts.file),
        globPattern = args[0],
        files = glob.sync(globPattern, {
          cwd: cwd
        });
      if (files.length !== 0 && files.length > 0) {
        var modules = [];
        var replacement;
        for (var fi = 0, fl = files.length; fi < fl; fi++) {
          if (path.resolve(cwd, files[fi]) !== opts.file) {
            modules.push(files[fi]);
          }
        }
        if ((typeof optsObj.hash !== "undefined" && optsObj.hash !== null && optsObj.hash !== false)) {
          for (var mi = 0, mil = modules.length; mi < mil; mi++) {
            var mod = modules[mi];
            var hashKey = optsObj.ext ? path.basename(mod) : path.basename(mod, path.extname(mod));
            var modulePath = path.dirname(mod) + '/' + hashKey;
            modules[mi] = '"' + hashKey + '": require("' + modulePath + '")';
          }
          replacement = '{' + modules.join(', ') + '}';
        } else {
          replacement = 'require("' + modules.join('");\nrequire("') + '")';
        }
        done(null, replacement);
      } else {
        done('Glob expression "' + globPattern + '" couldn\'t find any files');
      }
    } else {
      done();
    }
  }
);<|endoftext|>


<commit_before>!function(root, name, make) {
  typeof module != 'undefined' && module.exports ? module.exports = make() : root[name] = make()
}(this, 'associated', function() {

  function control($label) {
    var id = $label.attr('for')
    return id ? new $label.constructor('#' + id) : $label.find('input,textarea,select,button')
  }

  function label($input) {
    var $parent = $input.closest('label')
    return $parent.length ? $parent : forId($input).first()
  }

  function forId($input) {
    var id = $input.attr('id')
    return new $input.constructor(id ? 'label[for="' +  id + '"]' : id)
  }

  function labels($input) {
    return $input.closest('label').add(forId($input))
  }

  return {
    control: control,
    label: label,
    labels: labels
  }
});
<commit_msg>support amd<commit_after>!function(root, name, make) {
  if (typeof module != 'undefined' && module.exports) module.exports = make()
  else if (typeof define == 'function' && define.amd) define(make)
  else root[name] = make()
}(this, 'associated', function() {

  function control($label) {
    var id = $label.attr('for')
    return id ? new $label.constructor('#' + id) : $label.find('input,textarea,select,button')
  }

  function label($input) {
    var $parent = $input.closest('label')
    return $parent.length ? $parent : forId($input).first()
  }

  function forId($input) {
    var id = $input.attr('id')
    return new $input.constructor(id ? 'label[for="' +  id + '"]' : id)
  }

  function labels($input) {
    return $input.closest('label').add(forId($input))
  }

  return {
    control: control,
    label: label,
    labels: labels
  }
});
<|endoftext|>


<commit_before>import React, {
  StyleSheet,
  Navigator,
  View,
  Platform,
  PropTypes,
  Text,
  StatusBar,
} from 'react-native';

import EventEmitter from 'react-native/Libraries/vendor/emitter/EventEmitter';

import NavBarContainer from './components/NavBarContainer';
import * as Styles from './styles';
import aspect from 'aspect-js';
import _ from 'underscore';

const propTypes = {
  backButtonComponent: PropTypes.func,
  bgStyle: PropTypes.object,
  borderBottomWidth: PropTypes.number,
  borderColor: PropTypes.string,
  customAction: PropTypes.func,
  firstRoute: PropTypes.object.isRequired,
  handleBackAndroid: PropTypes.bool,
  headerStyle: View.propTypes.style,
  hideNavigationBar: PropTypes.bool,
  noStatusBar: PropTypes.bool,
  rightCorner: PropTypes.func,
  statusBarColor: PropTypes.string,
  statusBarProps: PropTypes.object,
  titleStyle: Text.propTypes.style,
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
  },
});

class Router extends React.Component {
  constructor(props) {
    super(props);

    this.onForward = this.onForward.bind(this);
    this.onBack = this.onBack.bind(this);
    this.onReplaceRoute = this.onReplaceRoute.bind(this);
    this.onResetToRoute = this.onResetToRoute.bind(this);
    this.onToFirstRoute = this.onToFirstRoute.bind(this);
    this.customAction = this.customAction.bind(this);
    this.renderScene = this.renderScene.bind(this);

    this.onWillPop = this.onWillPop.bind(this);
    this.onDidPop = this.onDidPop.bind(this);

    this.onWillPush = this.onWillPush.bind(this);
    this.onDidPush = this.onDidPush.bind(this);

    this.onWillResetTo = this.onWillResetTo.bind(this);
    this.onDidResetTo = this.onDidResetTo.bind(this);

    this.onWillReplace = this.onWillReplace.bind(this);
    this.onDidReplace = this.onDidReplace.bind(this);

    this.onWillPopToTop = this.onWillPopToTop.bind(this);
    this.onDidPopToTop = this.onDidPopToTop.bind(this);

    this.state = {
      route: {
        name: null,
        index: null,
      },
    };
    this.emitter = new EventEmitter();
  }

  componentWillMount() {
    this.state.route = this.props.firstRoute;
  }

  componentDidMount() {
    this.refs.navigator.navigationContext.addListener('willfocus', (event) => {
      const route = event.data.route;
      this.setState({ route });
      this.emitter.emit('willFocus', route.name);
    });

    this.refs.navigator.navigationContext.addListener('didfocus', (event) => {
      const route = event.data.route;
      this.emitter.emit('didFocus', route.name);
    });

    aspect.before(this.refs.navigator, 'pop', () => {
      this.onWillPop();
    });
    aspect.after(this.refs.navigator, 'pop', () => {
      this.onDidPop();
    });

    aspect.before(this.refs.navigator, 'push', (route) => {
      this.onWillPush(route);
    });
    aspect.after(this.refs.navigator, 'push', (route) => {
      // temporary hack to fix bug in aspect library
      this.onDidPush(route || arguments[1]);
    });

    aspect.before(this.refs.navigator, 'resetTo', (route) => {
      this.onWillResetTo(route);
    });
    aspect.after(this.refs.navigator, 'resetTo', (route) => {
      // temporary hack to fix bug in aspect library
      this.onDidResetTo(route || arguments[1]);
    });

    aspect.before(this.refs.navigator, 'replace', (route) => {
      this.onWillReplace(route);
    });
    aspect.after(this.refs.navigator, 'replace', (route) => {
      // temporary hack to fix bug in aspect library
      this.onDidReplace(route || arguments[1]);
    });

    aspect.before(this.refs.navigator, 'popToTop', () => {
      this.onWillPopToTop();
    });
    aspect.after(this.refs.navigator, 'popToTop', () => {
      this.onDidPopToTop();
    });
  }

  onForward(nextRoute, navigator) {
    navigator.push(
      Object.assign(nextRoute, { index: this.state.route.index + 1 || 1 })
    );
  }

  onBack(navigator) {
    if (this.state.route.index > 0) {
      navigator.pop();
    }
  }

  onReplaceRoute(nextRoute, navigator) {
    navigator.replace(
      Object.assign(nextRoute, { index: this.state.route.index || 0 })
    );
  }

  onResetToRoute(nextRoute, navigator) {
    navigator.resetTo(
      Object.assign(nextRoute, { index: 0 })
    );
  }

  onToFirstRoute(navigator) {
    navigator.popToTop();
  }

  onWillPop() {
    this.emitter.emit('willPop');
  }

  onDidPop() {
    this.emitter.emit('didPop');
  }

  onWillPush(route) {
    this.emitter.emit('willPush', route);
  }

  onDidPush(route) {
    this.emitter.emit('didPush', route);
  }

  onWillResetTo(route) {
    this.emitter.emit('willResetTo', route);
  }

  onDidResetTo(route) {
    this.emitter.emit('didResetTo', route);
  }

  onWillReplace(route) {
    this.emitter.emit('willReplace', route);
  }

  onDidReplace(route) {
    this.emitter.emit('didReplace', route);
  }

  onWillPopToTop() {
    this.emitter.emit('willPopToTop');
  }

  onDidPopToTop() {
    this.emitter.emit('didPopToTop');
  }

  setRightProps(props) {
    this.setState({ rightProps: props });
  }

  setLeftProps(props) {
    this.setState({ leftProps: props });
  }

  setTitleProps(props) {
    this.setState({ titleProps: props });
  }

  customAction(opts) {
    this.props.customAction(opts);
  }

  configureScene(route) {
    return route.sceneConfig || Navigator.SceneConfigs.FloatFromRight;
  }

  renderScene(route, navigator) {
    const goForward = (nextRoute) => {
      this.onForward(nextRoute, navigator);
      this.emitter.emit('push', nextRoute);
    };

    const replaceRoute = (nextRoute) => {
      this.onReplaceRoute(nextRoute, navigator);
      this.emitter.emit('replace', nextRoute);
    };

    const resetToRoute = (nextRoute) => {
      this.onResetToRoute(nextRoute, navigator);
      this.emitter.emit('resetTo', nextRoute);
    };

    const goBackwards = () => {
      this.onBack(navigator);
    };

    const goToFirstRoute = () => {
      this.onToFirstRoute(navigator);
      this.emitter.emit('popToTop');
    };

    const setRightProps = (props) => {
      this.setState({ rightProps: props });
    };

    const setLeftProps = (props) => {
      this.setState({ leftProps: props });
    };

    const setTitleProps = (props) => {
      this.setState({ titleProps: props });
    };

    const customAction = (opts) => {
      this.customAction(opts);
    };

    const Content = route.component;

    // Remove the margin of the navigation bar if not using navigation bar
    const extraStyling = {};
    if (this.props.hideNavigationBar) {
      extraStyling.marginTop = 0;
    }

    let margin;
    if (route.trans) {
      margin = 0;
    } else if (this.props.hideNavigationBar || route.hideNavigationBar) {
      margin = this.props.noStatusBar ? 0 : 20;
    } else {
      margin = Styles.NAV_BAR_HEIGHT;
    }

    return (
      <View
        style={[styles.container, this.props.bgStyle, extraStyling, { marginTop: margin }]}
      >
        <Content
          name={route.name}
          index={route.index}
          data={route.data}
          toRoute={goForward}
          toBack={goBackwards}
          routeEmitter={this.emitter}
          replaceRoute={replaceRoute}
          resetToRoute={resetToRoute}
          reset={goToFirstRoute}
          setRightProps={setRightProps}
          setLeftProps={setLeftProps}
          setTitleProps={setTitleProps}
          customAction={customAction}
          {...route.passProps}
        />
      </View>
    );
  }

  render() {
    let navigationBar;
    let statusBar;
    let statusBarProps = {};

    if (!this.props.hideNavigationBar) {
      navigationBar = (
        <NavBarContainer
          style={this.props.headerStyle}
          navigator={navigator}
          currentRoute={this.state.route}
          backButtonComponent={this.props.backButtonComponent}
          rightCorner={this.props.rightCorner}
          titleStyle={this.props.titleStyle}
          borderBottomWidth={this.props.borderBottomWidth}
          borderColor={this.props.borderColor}
          toRoute={this.onForward}
          toBack={this.onBack}
          replaceRoute={this.onReplaceRoute}
          resetToRoute={this.onResetToRoute}
          goToFirstRoute={this.onToFirstRoute}
          leftProps={this.state.leftProps}
          rightProps={this.state.rightProps}
          titleProps={this.state.titleProps}
          customAction={this.customAction}
          handleBackAndroid={this.props.handleBackAndroid}
        />
      );
    }

    // Check if StatusBar is available (React-Native >= 0.20)
    if (StatusBar) {
      // Check for default values provided to Router
      if (this.props.statusBarProps) {
        // statusBarProps = _.defaults(this.props.statusBarProps, statusBarProps);
        statusBarProps = this.props.statusBarProps;
      }

      // Check for values provided to current route
      if (this.state.route && this.state.route.statusBarProps) {
        statusBarProps = _.defaults(this.state.route.statusBarProps, statusBarProps);
      }

      // Android specific code
      if (Platform.OS === 'android') {
        if (!_.has(statusBarProps, 'backgroundColor') && !_.has(statusBarProps, 'translucent')) {
          let backgroundColor;

          if (this.state.route && this.state.route.headerStyle && this.state.router.headerStyle.backgroundColor) {
            // If current route has specific header style
            const stateHeaderStyle = StyleSheet.flatten(this.props.headerStyle);

            if (stateHeaderStyle && stateHeaderStyle.backgroundColor) {
              backgroundColor = stateHeaderStyle.backgroundColor;
            }
          } else if (this.props.headerStyle) {
            // Otherwise, get backgroundColor as specified to Router
            const propsHeaderStyle = StyleSheet.flatten(this.props.headerStyle);

            if (propsHeaderStyle && propsHeaderStyle.backgroundColor) {
              backgroundColor = propsHeaderStyle.backgroundColor;
            }
          }

          if (backgroundColor) {
            statusBarProps.backgroundColor = backgroundColor;
          }
        }
      } else if (Platform.OS === 'ios') {
        if (!_.has(statusBarProps, 'barStyle')) {
          // NOTE Deprecated prop, shouldn't be used.
          if (this.props.statusBarColor === 'black') {
            statusBarProps.barStyle = 'default';
          } else {
            statusBarProps.barStyle = 'light-content';
          }
        }
      }

      statusBar = (
        <StatusBar
          {...statusBarProps}
        />
      );
    }

    return (
      <View style={{ flex: 1 }}>
        {statusBar}
        <Navigator
          ref="navigator"
          initialRoute={this.props.firstRoute}
          navigationBar={navigationBar}
          renderScene={this.renderScene}
          configureScene={this.configureScene}
        />
      </View>
    );
  }
}

Router.propTypes = propTypes;

export default Router;
<commit_msg>Fix statusbar color when headerStyle is provided<commit_after>import React, {
  StyleSheet,
  Navigator,
  View,
  Platform,
  PropTypes,
  Text,
  StatusBar,
} from 'react-native';

import EventEmitter from 'react-native/Libraries/vendor/emitter/EventEmitter';

import NavBarContainer from './components/NavBarContainer';
import * as Styles from './styles';
import aspect from 'aspect-js';
import _ from 'underscore';

const propTypes = {
  backButtonComponent: PropTypes.func,
  bgStyle: PropTypes.object,
  borderBottomWidth: PropTypes.number,
  borderColor: PropTypes.string,
  customAction: PropTypes.func,
  firstRoute: PropTypes.object.isRequired,
  handleBackAndroid: PropTypes.bool,
  headerStyle: View.propTypes.style,
  hideNavigationBar: PropTypes.bool,
  noStatusBar: PropTypes.bool,
  rightCorner: PropTypes.func,
  statusBarColor: PropTypes.string,
  statusBarProps: PropTypes.object,
  titleStyle: Text.propTypes.style,
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
  },
});

class Router extends React.Component {
  constructor(props) {
    super(props);

    this.onForward = this.onForward.bind(this);
    this.onBack = this.onBack.bind(this);
    this.onReplaceRoute = this.onReplaceRoute.bind(this);
    this.onResetToRoute = this.onResetToRoute.bind(this);
    this.onToFirstRoute = this.onToFirstRoute.bind(this);
    this.customAction = this.customAction.bind(this);
    this.renderScene = this.renderScene.bind(this);

    this.onWillPop = this.onWillPop.bind(this);
    this.onDidPop = this.onDidPop.bind(this);

    this.onWillPush = this.onWillPush.bind(this);
    this.onDidPush = this.onDidPush.bind(this);

    this.onWillResetTo = this.onWillResetTo.bind(this);
    this.onDidResetTo = this.onDidResetTo.bind(this);

    this.onWillReplace = this.onWillReplace.bind(this);
    this.onDidReplace = this.onDidReplace.bind(this);

    this.onWillPopToTop = this.onWillPopToTop.bind(this);
    this.onDidPopToTop = this.onDidPopToTop.bind(this);

    this.state = {
      route: {
        name: null,
        index: null,
      },
    };
    this.emitter = new EventEmitter();
  }

  componentWillMount() {
    this.state.route = this.props.firstRoute;
  }

  componentDidMount() {
    this.refs.navigator.navigationContext.addListener('willfocus', (event) => {
      const route = event.data.route;
      this.setState({ route });
      this.emitter.emit('willFocus', route.name);
    });

    this.refs.navigator.navigationContext.addListener('didfocus', (event) => {
      const route = event.data.route;
      this.emitter.emit('didFocus', route.name);
    });

    aspect.before(this.refs.navigator, 'pop', () => {
      this.onWillPop();
    });
    aspect.after(this.refs.navigator, 'pop', () => {
      this.onDidPop();
    });

    aspect.before(this.refs.navigator, 'push', (route) => {
      this.onWillPush(route);
    });
    aspect.after(this.refs.navigator, 'push', (route) => {
      // temporary hack to fix bug in aspect library
      this.onDidPush(route || arguments[1]);
    });

    aspect.before(this.refs.navigator, 'resetTo', (route) => {
      this.onWillResetTo(route);
    });
    aspect.after(this.refs.navigator, 'resetTo', (route) => {
      // temporary hack to fix bug in aspect library
      this.onDidResetTo(route || arguments[1]);
    });

    aspect.before(this.refs.navigator, 'replace', (route) => {
      this.onWillReplace(route);
    });
    aspect.after(this.refs.navigator, 'replace', (route) => {
      // temporary hack to fix bug in aspect library
      this.onDidReplace(route || arguments[1]);
    });

    aspect.before(this.refs.navigator, 'popToTop', () => {
      this.onWillPopToTop();
    });
    aspect.after(this.refs.navigator, 'popToTop', () => {
      this.onDidPopToTop();
    });
  }

  onForward(nextRoute, navigator) {
    navigator.push(
      Object.assign(nextRoute, { index: this.state.route.index + 1 || 1 })
    );
  }

  onBack(navigator) {
    if (this.state.route.index > 0) {
      navigator.pop();
    }
  }

  onReplaceRoute(nextRoute, navigator) {
    navigator.replace(
      Object.assign(nextRoute, { index: this.state.route.index || 0 })
    );
  }

  onResetToRoute(nextRoute, navigator) {
    navigator.resetTo(
      Object.assign(nextRoute, { index: 0 })
    );
  }

  onToFirstRoute(navigator) {
    navigator.popToTop();
  }

  onWillPop() {
    this.emitter.emit('willPop');
  }

  onDidPop() {
    this.emitter.emit('didPop');
  }

  onWillPush(route) {
    this.emitter.emit('willPush', route);
  }

  onDidPush(route) {
    this.emitter.emit('didPush', route);
  }

  onWillResetTo(route) {
    this.emitter.emit('willResetTo', route);
  }

  onDidResetTo(route) {
    this.emitter.emit('didResetTo', route);
  }

  onWillReplace(route) {
    this.emitter.emit('willReplace', route);
  }

  onDidReplace(route) {
    this.emitter.emit('didReplace', route);
  }

  onWillPopToTop() {
    this.emitter.emit('willPopToTop');
  }

  onDidPopToTop() {
    this.emitter.emit('didPopToTop');
  }

  setRightProps(props) {
    this.setState({ rightProps: props });
  }

  setLeftProps(props) {
    this.setState({ leftProps: props });
  }

  setTitleProps(props) {
    this.setState({ titleProps: props });
  }

  customAction(opts) {
    this.props.customAction(opts);
  }

  configureScene(route) {
    return route.sceneConfig || Navigator.SceneConfigs.FloatFromRight;
  }

  renderScene(route, navigator) {
    const goForward = (nextRoute) => {
      this.onForward(nextRoute, navigator);
      this.emitter.emit('push', nextRoute);
    };

    const replaceRoute = (nextRoute) => {
      this.onReplaceRoute(nextRoute, navigator);
      this.emitter.emit('replace', nextRoute);
    };

    const resetToRoute = (nextRoute) => {
      this.onResetToRoute(nextRoute, navigator);
      this.emitter.emit('resetTo', nextRoute);
    };

    const goBackwards = () => {
      this.onBack(navigator);
    };

    const goToFirstRoute = () => {
      this.onToFirstRoute(navigator);
      this.emitter.emit('popToTop');
    };

    const setRightProps = (props) => {
      this.setState({ rightProps: props });
    };

    const setLeftProps = (props) => {
      this.setState({ leftProps: props });
    };

    const setTitleProps = (props) => {
      this.setState({ titleProps: props });
    };

    const customAction = (opts) => {
      this.customAction(opts);
    };

    const Content = route.component;

    // Remove the margin of the navigation bar if not using navigation bar
    const extraStyling = {};
    if (this.props.hideNavigationBar) {
      extraStyling.marginTop = 0;
    }

    let margin;
    if (route.trans) {
      margin = 0;
    } else if (this.props.hideNavigationBar || route.hideNavigationBar) {
      margin = this.props.noStatusBar ? 0 : 20;
    } else {
      margin = Styles.NAV_BAR_HEIGHT;
    }

    return (
      <View
        style={[styles.container, this.props.bgStyle, extraStyling, { marginTop: margin }]}
      >
        <Content
          name={route.name}
          index={route.index}
          data={route.data}
          toRoute={goForward}
          toBack={goBackwards}
          routeEmitter={this.emitter}
          replaceRoute={replaceRoute}
          resetToRoute={resetToRoute}
          reset={goToFirstRoute}
          setRightProps={setRightProps}
          setLeftProps={setLeftProps}
          setTitleProps={setTitleProps}
          customAction={customAction}
          {...route.passProps}
        />
      </View>
    );
  }

  render() {
    let navigationBar;
    let statusBar;
    let statusBarProps = {};

    if (!this.props.hideNavigationBar) {
      navigationBar = (
        <NavBarContainer
          style={this.props.headerStyle}
          navigator={navigator}
          currentRoute={this.state.route}
          backButtonComponent={this.props.backButtonComponent}
          rightCorner={this.props.rightCorner}
          titleStyle={this.props.titleStyle}
          borderBottomWidth={this.props.borderBottomWidth}
          borderColor={this.props.borderColor}
          toRoute={this.onForward}
          toBack={this.onBack}
          replaceRoute={this.onReplaceRoute}
          resetToRoute={this.onResetToRoute}
          goToFirstRoute={this.onToFirstRoute}
          leftProps={this.state.leftProps}
          rightProps={this.state.rightProps}
          titleProps={this.state.titleProps}
          customAction={this.customAction}
          handleBackAndroid={this.props.handleBackAndroid}
        />
      );
    }

    // Check if StatusBar is available (React-Native >= 0.20)
    if (StatusBar) {
      // Check for default values provided to Router
      if (this.props.statusBarProps) {
        // statusBarProps = _.defaults(this.props.statusBarProps, statusBarProps);
        statusBarProps = this.props.statusBarProps;
      }

      // Check for values provided to current route
      if (this.state.route && this.state.route.statusBarProps) {
        statusBarProps = _.defaults(this.state.route.statusBarProps, statusBarProps);
      }

      // Android specific code
      if (Platform.OS === 'android') {
        if (!_.has(statusBarProps, 'backgroundColor') && !_.has(statusBarProps, 'translucent')) {
          let backgroundColor;

          if (this.state.route && this.state.route.headerStyle) {
            // If current route has specific header style
            const stateHeaderStyle = StyleSheet.flatten(this.state.route.headerStyle);

            if (stateHeaderStyle && stateHeaderStyle.backgroundColor) {
              backgroundColor = stateHeaderStyle.backgroundColor;
            }
          } else if (this.props.headerStyle) {
            // Otherwise, get backgroundColor as specified to Router
            const propsHeaderStyle = StyleSheet.flatten(this.props.headerStyle);

            if (propsHeaderStyle && propsHeaderStyle.backgroundColor) {
              backgroundColor = propsHeaderStyle.backgroundColor;
            }
          }

          if (backgroundColor) {
            statusBarProps.backgroundColor = backgroundColor;
          }
        }
      } else if (Platform.OS === 'ios') {
        if (!_.has(statusBarProps, 'barStyle')) {
          // NOTE Deprecated prop, shouldn't be used.
          if (this.props.statusBarColor === 'black') {
            statusBarProps.barStyle = 'default';
          } else {
            statusBarProps.barStyle = 'light-content';
          }
        }
      }

      statusBar = (
        <StatusBar
          {...statusBarProps}
        />
      );
    }

    return (
      <View style={{ flex: 1 }}>
        {statusBar}
        <Navigator
          ref="navigator"
          initialRoute={this.props.firstRoute}
          navigationBar={navigationBar}
          renderScene={this.renderScene}
          configureScene={this.configureScene}
        />
      </View>
    );
  }
}

Router.propTypes = propTypes;

export default Router;
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

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

  contentFor: function (type, config) {
    var trackOpts;
    var trackConfig;
    var trackConfiguration;
    var trackBoilerPlate;
    var addonConfig;

    if (type === 'head') {
      trackOpts = config.trackJs || {};
      trackConfig = trackOpts.config || {};

      trackConfiguration = '<script type="text/javascript" id="trackjs-configuration">window._trackJs = ' + JSON.stringify(trackConfig) + ';</script>';

      if (trackOpts.url) {
        trackBoilerPlate = '<script type="text/javascript" id="trackjs-boilerplate" src="' + trackOpts.url + '" crossorigin="anonymous"></script>';
      }

      return [trackConfiguration, trackBoilerPlate].join('\n');
    }
  },

  included: function (app) {
    this._super.included(app);

    var options = app.options['ember-cli-trackjs'];

    if (!(options && options.cdn)) {
      app.import(app.bowerDirectory + '/trackjs/tracker.js');
    }
  }
};
<commit_msg>Insert Script Tag at Foot of the `<head>` Tag<commit_after>/* jshint node: true */
'use strict';

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

  contentFor: function (type, config) {
    var trackOpts;
    var trackConfig;
    var trackConfiguration;
    var trackBoilerPlate;
    var addonConfig;

    if (type === 'head-footer') {
      trackOpts = config.trackJs || {};
      trackConfig = trackOpts.config || {};

      trackConfiguration = '<script type="text/javascript" id="trackjs-configuration">window._trackJs = ' + JSON.stringify(trackConfig) + ';</script>';

      if (trackOpts.url) {
        trackBoilerPlate = '<script type="text/javascript" id="trackjs-boilerplate" src="' + trackOpts.url + '" crossorigin="anonymous"></script>';
      }

      return [trackConfiguration, trackBoilerPlate].join('\n');
    }
  },

  included: function (app) {
    this._super.included(app);

    var options = app.options['ember-cli-trackjs'];

    if (!(options && options.cdn)) {
      app.import(app.bowerDirectory + '/trackjs/tracker.js');
    }
  }
};
<|endoftext|>


<commit_before>/* eslint-env node */

'use strict';

var postcss = require('postcss');
var cssMediaQuery = require('css-mediaquery');
var units = require('units-css');

// Utilities
//------------------------------------------------------------------------------

var hasOwnProperty = {}.hasOwnProperty;

var getPxValue = function(value, property) {
  return units.convert('px', value, null, property);
};

// PostCSS plugin wrapper (exports)
//------------------------------------------------------------------------------

module.exports = postcss.plugin('postcss-mq-simplify', function() {
  return function(css) {
    css.eachAtRule('media', function(media) {
      // Update AST value
      media.params = formatMedia(media, buildOutput);
    });
  };
});

// Plugin logic
//------------------------------------------------------------------------------

var formatMedia = function(media, callback) {
  var rules = cssMediaQuery.parse(media.params);
  var conditions = {};

  // Format data structure
  rules.forEach(function(rule) {
    var level = conditions;
    var prevLevel;

    level = createStructure(level, rule.inverse);
    level = createStructure(level, rule.type);
    prevLevel = level; // Cache position

    rule.expressions.forEach(function(expression) {
      level = prevLevel;

      if (typeof expression.modifier !== 'undefined') {
        level = createStructure(level, expression.modifier);
      }

      level = createStructure(level, expression.feature, []);
      level.push(expression.value);
    });
  });

  return callback(media, conditions);
};

var buildOutput = function(media, conditions) {
  var output = [];

  forLevel(conditions, function(inverse, level) {
    output.push(
      inverse === false.toString()
        ? 'only'
        : 'not'
    );

    forLevel(level, function(type, level) {
      output.push(type);

      forLevel(level, function(modifier, level) {
        // level is an array at this point if rule lacks a modifier
        if (Array.isArray(level)) {
          pushFeature(output, modifier, level[0]);
        } else {
          if (typeof transforms[modifier] === 'function') {
            transforms[modifier](level);
          }

          forLevel(level, function(feature, value) {
            pushFeature(output, feature, value[0], modifier);
          });
        }
      });
    });
  });

  return output.join(' ');
};

var createStructure = function(current, level, structure) {
  if (typeof current[level] === 'undefined') {
    current[level] = structure || {};
  }

  return current[level];
};

var forLevel = function(object, callback) {
  var property;

  for (property in object) {
    if (!hasOwnProperty.call(object, property)) {
      continue;
    }

    callback(property, object[property]);
  }
};

var pushFeature = function(output, feature, value, modifier) {
  output.push('and');
  output.push('(' + (modifier ? modifier + '-' : '') + feature + ':');
  output.push(value + ')');
};

// MQ transform methods
//------------------------------------------------------------------------------

var transforms = {};

transforms.min = function(rules) {
  var feature;

  for (feature in rules) {
    if (!hasOwnProperty.call(rules, feature)) {
      continue;
    }

    rules[feature] = [rules[feature].reduce(function(a, b) {
      return getPxValue(a) > getPxValue(b)
        ? a
        : b;
    })];
  }
};

transforms.max = function(rules) {
  var feature;

  for (feature in rules) {
    if (!hasOwnProperty.call(rules, feature)) {
      continue;
    }

    rules[feature] = [rules[feature].reduce(function(a, b) {
      return getPxValue(a) < getPxValue(b)
        ? a
        : b;
    })];
  }
};
<commit_msg>Fix MQ clause/condition appending<commit_after>/* eslint-env node */

'use strict';

var postcss = require('postcss');
var cssMediaQuery = require('css-mediaquery');
var units = require('units-css');

// Utilities
//------------------------------------------------------------------------------

var hasOwnProperty = {}.hasOwnProperty;

var normalizeValue = function(value, property) {
  return units.convert('_default', value, null, property);
};

// PostCSS plugin wrapper (exports)
//------------------------------------------------------------------------------

module.exports = postcss.plugin('postcss-mq-simplify', function() {
  return function(css) {
    css.eachAtRule('media', function(media) {
      // Update AST value
      media.params = formatMedia(media, buildOutput);
    });
  };
});

// Plugin logic
//------------------------------------------------------------------------------

var formatMedia = function(media, callback) {
  var rules = cssMediaQuery.parse(media.params);
  var clauses = [];

  // Format data structure
  rules.forEach(function(rule) {
    var level = {};
    var prevLevel;

    clauses.push(level);
    level = createStructure(level, rule.inverse);
    level = createStructure(level, rule.type);
    prevLevel = level; // Cache position

    rule.expressions.forEach(function(expression) {
      level = prevLevel;

      if (typeof expression.modifier !== 'undefined') {
        level = createStructure(level, expression.modifier);
      }

      level = createStructure(level, expression.feature, []);
      level.push(expression.value);
    });
  });

  return callback(media, clauses);
};

var buildOutput = function(media, clauses) {
  var output = [];

  clauses.forEach(function(clause, index) {
    if (index > 0) {
      output.push(',');
    }

    forLevel(clause, function(inverse, level) {
      output.push(
        inverse === false.toString()
          ? 'only'
          : 'not'
      );

      forLevel(level, function(type, level) {
        output.push(type);

        forLevel(level, function(modifier, level) {
          // level is an array at this point if rule lacks a modifier
          if (Array.isArray(level)) {
            pushFeature(output, modifier, level[0]);
          } else {
            if (typeof transforms[modifier] === 'function') {
              transforms[modifier](level);
            }

            forLevel(level, function(feature, value) {
              pushFeature(output, feature, value[0], modifier);
            });
          }
        });
      });
    });
  });

  return output.join(' ');
};

var createStructure = function(current, level, structure) {
  if (typeof current[level] === 'undefined') {
    current[level] = structure || {};
  }

  return current[level];
};

var forLevel = function(object, callback) {
  var property;

  for (property in object) {
    if (!hasOwnProperty.call(object, property)) {
      continue;
    }

    callback(property, object[property]);
  }
};

var pushFeature = function(output, feature, value, modifier) {
  output.push('and');
  output.push('(' + (modifier ? modifier + '-' : '') + feature + ':');
  output.push(value + ')');
};

// MQ transform methods
//------------------------------------------------------------------------------

var transforms = {};

transforms.min = function(rules) {
  var feature;

  for (feature in rules) {
    if (!hasOwnProperty.call(rules, feature)) {
      continue;
    }

    rules[feature] = [rules[feature].reduce(function(a, b) {
      return normalizeValue(a, feature) > normalizeValue(b, feature)
        ? a
        : b;
    })];
  }
};

transforms.max = function(rules) {
  var feature;

  for (feature in rules) {
    if (!hasOwnProperty.call(rules, feature)) {
      continue;
    }

    rules[feature] = [rules[feature].reduce(function(a, b) {
      return normalizeValue(a, feature) < normalizeValue(b, feature)
        ? a
        : b;
    })];
  }
};
<|endoftext|>