<commit_before>var defined = require('defined');
var createDefaultStream = require('./lib/default_stream');
var Test = require('./lib/test');
var createResult = require('./lib/results');
var through = require('through');

var canEmitExit = typeof process !== 'undefined' && process
    && typeof process.on === 'function'
;
var canExit = typeof process !== 'undefined' && process
    && typeof process.exit === 'function'
;

var nextTick = typeof setImmediate !== 'undefined'
    ? setImmediate
    : process.nextTick
;

exports = module.exports = (function () {
    var harness;
    var lazyLoad = function () {
        return getHarness().apply(this, arguments);
    };

    lazyLoad.only = function () {
        return getHarness().only.apply(this, arguments);
    };

    lazyLoad.createStream = function (opts) {
        if (!opts) opts = {};
        if (!harness) {
            var output = through();
            getHarness({ stream: output, objectMode: opts.objectMode });
            return output;
        }
        return harness.createStream(opts);
    };

    return lazyLoad

    function getHarness (opts) {
        if (!opts) opts = {};
        opts.autoclose = !canEmitExit;
        if (!harness) harness = createExitHarness(opts);
        return harness;
    }
})();

function createExitHarness (conf) {
    if (!conf) conf = {};
    var harness = createHarness({
        autoclose: defined(conf.autoclose, false)
    });

    var stream = harness.createStream({ objectMode: conf.objectMode });
    var es = stream.pipe(conf.stream || createDefaultStream());
    if (canEmitExit) {
        es.on('error', function (err) { harness._exitCode = 1 });
    }

    var ended = false;
    stream.on('end', function () { ended = true });

    if (conf.exit === false) return harness;
    if (!canEmitExit || !canExit) return harness;

    var _error;

    process.on('uncaughtException', function (err) {
        if (err && err.code === 'EPIPE' && err.errno === 'EPIPE'
        && err.syscall === 'write') return;

        _error = err

        throw err
    })

    process.on('exit', function (code) {
        if (_error) {
            return
        }

        if (!ended) {
            var only = harness._results._only;
            for (var i = 0; i < harness._tests.length; i++) {
                var t = harness._tests[i];
                if (only && t.name !== only) continue;
                t._exit();
            }
        }
        harness.close();
        process.exit(code || harness._exitCode);
    });

    return harness;
}

exports.createHarness = createHarness;
exports.Test = Test;
exports.test = exports; // tap compat
exports.test.skip = Test.skip;

var exitInterval;

function createHarness (conf_) {
    if (!conf_) conf_ = {};
    var results = createResult();
    if (conf_.autoclose !== false) {
        results.once('done', function () { results.close() });
    }

    var test = function (name, conf, cb) {
        var t = new Test(name, conf, cb);
        test._tests.push(t);

        (function inspectCode (st) {
            st.on('test', function sub (st_) {
                inspectCode(st_);
            });
            st.on('result', function (r) {
                if (!r.ok) test._exitCode = 1
            });
        })(t);

        results.push(t);
        return t;
    };
    test._results = results;

    test._tests = [];

    test.createStream = function (opts) {
        return results.createStream(opts);
    };

    var only = false;
    test.only = function (name) {
        if (only) throw new Error('there can only be one only test');
        results.only(name);
        only = true;
        return test.apply(null, arguments);
    };
    test._exitCode = 0;

    test.close = function () { results.close() };

    return test;
}
<commit_msg>do not set canEmitExit with browserify process shim<commit_after>var defined = require('defined');
var createDefaultStream = require('./lib/default_stream');
var Test = require('./lib/test');
var createResult = require('./lib/results');
var through = require('through');

var canEmitExit = typeof process !== 'undefined' && process
    && typeof process.on === 'function' && process.browser !== true
;
var canExit = typeof process !== 'undefined' && process
    && typeof process.exit === 'function'
;

var nextTick = typeof setImmediate !== 'undefined'
    ? setImmediate
    : process.nextTick
;

exports = module.exports = (function () {
    var harness;
    var lazyLoad = function () {
        return getHarness().apply(this, arguments);
    };

    lazyLoad.only = function () {
        return getHarness().only.apply(this, arguments);
    };

    lazyLoad.createStream = function (opts) {
        if (!opts) opts = {};
        if (!harness) {
            var output = through();
            getHarness({ stream: output, objectMode: opts.objectMode });
            return output;
        }
        return harness.createStream(opts);
    };

    return lazyLoad

    function getHarness (opts) {
        if (!opts) opts = {};
        opts.autoclose = !canEmitExit;
        if (!harness) harness = createExitHarness(opts);
        return harness;
    }
})();

function createExitHarness (conf) {
    if (!conf) conf = {};
    var harness = createHarness({
        autoclose: defined(conf.autoclose, false)
    });

    var stream = harness.createStream({ objectMode: conf.objectMode });
    var es = stream.pipe(conf.stream || createDefaultStream());
    if (canEmitExit) {
        es.on('error', function (err) { harness._exitCode = 1 });
    }

    var ended = false;
    stream.on('end', function () { ended = true });

    if (conf.exit === false) return harness;
    if (!canEmitExit || !canExit) return harness;

    var _error;

    process.on('uncaughtException', function (err) {
        if (err && err.code === 'EPIPE' && err.errno === 'EPIPE'
        && err.syscall === 'write') return;

        _error = err

        throw err
    })

    process.on('exit', function (code) {
        if (_error) {
            return
        }

        if (!ended) {
            var only = harness._results._only;
            for (var i = 0; i < harness._tests.length; i++) {
                var t = harness._tests[i];
                if (only && t.name !== only) continue;
                t._exit();
            }
        }
        harness.close();
        process.exit(code || harness._exitCode);
    });

    return harness;
}

exports.createHarness = createHarness;
exports.Test = Test;
exports.test = exports; // tap compat
exports.test.skip = Test.skip;

var exitInterval;

function createHarness (conf_) {
    if (!conf_) conf_ = {};
    var results = createResult();
    if (conf_.autoclose !== false) {
        results.once('done', function () { results.close() });
    }

    var test = function (name, conf, cb) {
        var t = new Test(name, conf, cb);
        test._tests.push(t);

        (function inspectCode (st) {
            st.on('test', function sub (st_) {
                inspectCode(st_);
            });
            st.on('result', function (r) {
                if (!r.ok) test._exitCode = 1
            });
        })(t);

        results.push(t);
        return t;
    };
    test._results = results;

    test._tests = [];

    test.createStream = function (opts) {
        return results.createStream(opts);
    };

    var only = false;
    test.only = function (name) {
        if (only) throw new Error('there can only be one only test');
        results.only(name);
        only = true;
        return test.apply(null, arguments);
    };
    test._exitCode = 0;

    test.close = function () { results.close() };

    return test;
}
<|endoftext|>


<commit_before>var PluginBuilder = require("bit-plugin-builder");

var defaults = {
  precompile: function textDependency(meta) {
    return {
      source: "module.exports = " + JSON.stringify(meta.source) + ";"
    };
  }
};

function buildPlugin(options, builder) {
  return builder
    .configure(defaults)
    .configure(options);
}

module.exports = function factory(options) {
  return function(builder) {
    return buildPlugin(options, builder);
  };
};
<commit_msg>confuring postdependency hook instead of precompile since precompile no longer exists<commit_after>var defaults = {
  postdependency: function textDependency(meta) {
    return {
      source: "module.exports = " + JSON.stringify(meta.source) + ";"
    };
  }
};

function buildPlugin(options, builder) {
  return builder
    .configure(defaults)
    .configure(options);
}

module.exports = function factory(options) {
  return function(builder) {
    return buildPlugin(options, builder);
  };
};
<|endoftext|>


<commit_before>// @flow

import React from 'react';
import {
  PanResponder,
  View,
  Dimensions,
  Animated,
  TouchableWithoutFeedback,
} from 'react-native';
import PropTypes from 'prop-types';
import styles from './styles';

type WindowDimensions = { width: number, height: number };

type Props = {
  edgeHitWidth: number,
  toleranceX: number,
  toleranceY: number,
  menuPosition: 'left' | 'right',
  onChange: Function,
  onMove: Function,
  openMenuOffset: number,
  hiddenMenuOffset: number,
  disableGestures: Function | bool,
  animationFunction: Function,
  onStartShouldSetResponderCapture: Function,
  isOpen: bool,
  bounceBackOnOverdraw: bool,
  autoClosing: bool
};

type Event = {
  nativeEvent: {
    layout: {
      width: number,
      height: number,
    },
  },
};

type State = {
  width: number,
  height: number,
  openOffsetMenuPercentage: number,
  openMenuOffset: number,
  hiddenMenuOffsetPercentage: number,
  hiddenMenuOffset: number,
  left: Animated.Value,
};

const deviceScreen: WindowDimensions = Dimensions.get('window');
const barrierForward: number = deviceScreen.width / 4;

function shouldOpenMenu(dx: number): boolean {
  return dx > barrierForward;
}

export default class SideMenu extends React.Component {
  onLayoutChange: Function;
  onStartShouldSetResponderCapture: Function;
  onMoveShouldSetPanResponder: Function;
  onPanResponderMove: Function;
  onPanResponderRelease: Function;
  onPanResponderTerminate: Function;
  state: State;
  prevLeft: number;
  isOpen: boolean;

  constructor(props: Props) {
    super(props);

    this.prevLeft = 0;
    this.isOpen = !!props.isOpen;

    const initialMenuPositionMultiplier = props.menuPosition === 'right' ? -1 : 1;
    const openOffsetMenuPercentage = props.openMenuOffset / deviceScreen.width;
    const hiddenMenuOffsetPercentage = props.hiddenMenuOffset / deviceScreen.width;
    const left: Animated.Value = new Animated.Value(
      props.isOpen
        ? props.openMenuOffset * initialMenuPositionMultiplier
        : props.hiddenMenuOffset,
    );

    this.onLayoutChange = this.onLayoutChange.bind(this);
    this.onStartShouldSetResponderCapture = props.onStartShouldSetResponderCapture.bind(this);
    this.onMoveShouldSetPanResponder = this.handleMoveShouldSetPanResponder.bind(this);
    this.onPanResponderMove = this.handlePanResponderMove.bind(this);
    this.onPanResponderRelease = this.handlePanResponderEnd.bind(this);
    this.onPanResponderTerminate = this.handlePanResponderEnd.bind(this);

    this.state = {
      width: deviceScreen.width,
      height: deviceScreen.height,
      openOffsetMenuPercentage,
      openMenuOffset: deviceScreen.width * openOffsetMenuPercentage,
      hiddenMenuOffsetPercentage,
      hiddenMenuOffset: deviceScreen.width * hiddenMenuOffsetPercentage,
      left,
    };
  }

  componentWillMount(): void {
    this.responder = PanResponder.create({
      onStartShouldSetResponderCapture: this.onStartShouldSetResponderCapture,
      onMoveShouldSetPanResponder: this.onMoveShouldSetPanResponder,
      onPanResponderMove: this.onPanResponderMove,
      onPanResponderRelease: this.onPanResponderRelease,
      onPanResponderTerminate: this.onPanResponderTerminate,
    });
  }

  componentWillReceiveProps(props: Props): void {
    if (typeof props.isOpen !== 'undefined' && this.isOpen !== props.isOpen && (props.autoClosing || this.isOpen === false)) {
      this.openMenu(props.isOpen);
    }
  }

  onLayoutChange(e: Event) {
    const { width, height } = e.nativeEvent.layout;
    const openMenuOffset = width * this.state.openOffsetMenuPercentage;
    const hiddenMenuOffset = width * this.state.hiddenMenuOffsetPercentage;
    this.setState({ width, height, openMenuOffset, hiddenMenuOffset });
  }

  /**
   * Get content view. This view will be rendered over menu
   * @return {React.Component}
   */
  getContentView() {
    let overlay: React.Element<void, void> = null;

    if (this.isOpen) {
      overlay = (
        <TouchableWithoutFeedback onPress={() => this.openMenu(false)}>
          <View style={styles.overlay} />
        </TouchableWithoutFeedback>
      );
    }

    const { width, height } = this.state;
    const ref = sideMenu => (this.sideMenu = sideMenu);
    const style = [
      styles.frontView,
      { width, height },
      this.props.animationStyle(this.state.left),
    ];

    return (
      <Animated.View style={style} ref={ref} {...this.responder.panHandlers}>
        {this.props.children}
        {overlay}
      </Animated.View>
    );
  }

  moveLeft(offset: number) {
    const newOffset = this.menuPositionMultiplier() * offset;

    this.props
      .animationFunction(this.state.left, newOffset)
      .start();

    this.prevLeft = newOffset;
  }

  menuPositionMultiplier(): -1 | 1 {
    return this.props.menuPosition === 'right' ? -1 : 1;
  }

  handlePanResponderMove(e: Object, gestureState: Object) {
    if (this.state.left.__getValue() * this.menuPositionMultiplier() >= 0) {
      let newLeft = this.prevLeft + gestureState.dx;

      if (!this.props.bounceBackOnOverdraw && Math.abs(newLeft) > this.state.openMenuOffset) {
        newLeft = this.menuPositionMultiplier() * this.state.openMenuOffset;
      }

      this.props.onMove(newLeft);
      this.state.left.setValue(newLeft);
    }
  }

  handlePanResponderEnd(e: Object, gestureState: Object) {
    const offsetLeft = this.menuPositionMultiplier() *
      (this.state.left.__getValue() + gestureState.dx);

    this.openMenu(shouldOpenMenu(offsetLeft));
  }

  handleMoveShouldSetPanResponder(e: any, gestureState: any): boolean {
    if (this.gesturesAreEnabled()) {
      const x = Math.round(Math.abs(gestureState.dx));
      const y = Math.round(Math.abs(gestureState.dy));

      const touchMoved = x > this.props.toleranceX && y < this.props.toleranceY;

      if (this.isOpen) {
        return touchMoved;
      }

      const withinEdgeHitWidth = this.props.menuPosition === 'right' ?
        gestureState.moveX > (deviceScreen.width - this.props.edgeHitWidth) :
        gestureState.moveX < this.props.edgeHitWidth;

      const swipingToOpen = this.menuPositionMultiplier() * gestureState.dx > 0;
      return withinEdgeHitWidth && touchMoved && swipingToOpen;
    }

    return false;
  }

  openMenu(isOpen: boolean): void {
    const { hiddenMenuOffset, openMenuOffset } = this.state;
    this.moveLeft(isOpen ? openMenuOffset : hiddenMenuOffset);
    this.isOpen = isOpen;

    this.forceUpdate();
    this.props.onChange(isOpen);
  }

  gesturesAreEnabled(): boolean {
    const { disableGestures } = this.props;

    if (typeof disableGestures === 'function') {
      return !disableGestures();
    }

    return !disableGestures;
  }

  render(): React.Element<void, void> {
    const boundryStyle = this.props.menuPosition === 'right' ?
      { left: this.state.width - this.state.openMenuOffset } :
      { right: this.state.width - this.state.openMenuOffset };

    const menu = (
      <View style={[styles.menu, boundryStyle]}>
        {this.props.menu}
      </View>
    );

    return (
      <View
        style={styles.container}
        onLayout={this.onLayoutChange}
      >
        {menu}
        {this.getContentView()}
      </View>
    );
  }
}

SideMenu.propTypes = {
  edgeHitWidth: PropTypes.number,
  toleranceX: PropTypes.number,
  toleranceY: PropTypes.number,
  menuPosition: PropTypes.oneOf(['left', 'right']),
  onChange: PropTypes.func,
  onMove: PropTypes.func,
  children: PropTypes.node,
  menu: PropTypes.node,
  openMenuOffset: PropTypes.number,
  hiddenMenuOffset: PropTypes.number,
  animationStyle: PropTypes.func,
  disableGestures: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
  animationFunction: PropTypes.func,
  onStartShouldSetResponderCapture: PropTypes.func,
  isOpen: PropTypes.bool,
  bounceBackOnOverdraw: PropTypes.bool,
  autoClosing: PropTypes.bool,
};

SideMenu.defaultProps = {
  toleranceY: 10,
  toleranceX: 10,
  edgeHitWidth: 60,
  children: null,
  menu: null,
  openMenuOffset: deviceScreen.width * (2 / 3),
  disableGestures: false,
  menuPosition: 'left',
  hiddenMenuOffset: 0,
  onMove: () => {},
  onStartShouldSetResponderCapture: () => true,
  onChange: () => {},
  animationStyle: value => ({
    transform: [{
      translateX: value,
    }],
  }),
  animationFunction: (prop, value) => Animated.spring(prop, {
    toValue: value,
    friction: 8,
  }),
  isOpen: false,
  bounceBackOnOverdraw: true,
  autoClosing: true,
};
<commit_msg>Added onSliding function<commit_after>// @flow

import React from 'react';
import {
  PanResponder,
  View,
  Dimensions,
  Animated,
  TouchableWithoutFeedback,
} from 'react-native';
import PropTypes from 'prop-types';
import styles from './styles';

type WindowDimensions = { width: number, height: number };

type Props = {
  edgeHitWidth: number,
  toleranceX: number,
  toleranceY: number,
  menuPosition: 'left' | 'right',
  onChange: Function,
  onMove: Function,
  onSliding: Function,
  openMenuOffset: number,
  hiddenMenuOffset: number,
  disableGestures: Function | bool,
  animationFunction: Function,
  onStartShouldSetResponderCapture: Function,
  isOpen: bool,
  bounceBackOnOverdraw: bool,
  autoClosing: bool
};

type Event = {
  nativeEvent: {
    layout: {
      width: number,
      height: number,
    },
  },
};

type State = {
  width: number,
  height: number,
  openOffsetMenuPercentage: number,
  openMenuOffset: number,
  hiddenMenuOffsetPercentage: number,
  hiddenMenuOffset: number,
  left: Animated.Value,
};

const deviceScreen: WindowDimensions = Dimensions.get('window');
const barrierForward: number = deviceScreen.width / 4;

function shouldOpenMenu(dx: number): boolean {
  return dx > barrierForward;
}

export default class SideMenu extends React.Component {
  onLayoutChange: Function;
  onStartShouldSetResponderCapture: Function;
  onMoveShouldSetPanResponder: Function;
  onPanResponderMove: Function;
  onPanResponderRelease: Function;
  onPanResponderTerminate: Function;
  state: State;
  prevLeft: number;
  isOpen: boolean;

  constructor(props: Props) {
    super(props);

    this.prevLeft = 0;
    this.isOpen = !!props.isOpen;

    const initialMenuPositionMultiplier = props.menuPosition === 'right' ? -1 : 1;
    const openOffsetMenuPercentage = props.openMenuOffset / deviceScreen.width;
    const hiddenMenuOffsetPercentage = props.hiddenMenuOffset / deviceScreen.width;
    const left: Animated.Value = new Animated.Value(
      props.isOpen
        ? props.openMenuOffset * initialMenuPositionMultiplier
        : props.hiddenMenuOffset,
    );

    this.onLayoutChange = this.onLayoutChange.bind(this);
    this.onStartShouldSetResponderCapture = props.onStartShouldSetResponderCapture.bind(this);
    this.onMoveShouldSetPanResponder = this.handleMoveShouldSetPanResponder.bind(this);
    this.onPanResponderMove = this.handlePanResponderMove.bind(this);
    this.onPanResponderRelease = this.handlePanResponderEnd.bind(this);
    this.onPanResponderTerminate = this.handlePanResponderEnd.bind(this);

    this.state = {
      width: deviceScreen.width,
      height: deviceScreen.height,
      openOffsetMenuPercentage,
      openMenuOffset: deviceScreen.width * openOffsetMenuPercentage,
      hiddenMenuOffsetPercentage,
      hiddenMenuOffset: deviceScreen.width * hiddenMenuOffsetPercentage,
      left,
    };

    this.state.left.addListener(({value}) => this.props.onSliding((value - this.state.hiddenMenuOffset) / (this.state.openMenuOffset - this.state.hiddenMenuOffset)));
  }

  componentWillMount(): void {
    this.responder = PanResponder.create({
      onStartShouldSetResponderCapture: this.onStartShouldSetResponderCapture,
      onMoveShouldSetPanResponder: this.onMoveShouldSetPanResponder,
      onPanResponderMove: this.onPanResponderMove,
      onPanResponderRelease: this.onPanResponderRelease,
      onPanResponderTerminate: this.onPanResponderTerminate,
    });
  }

  componentWillReceiveProps(props: Props): void {
    if (typeof props.isOpen !== 'undefined' && this.isOpen !== props.isOpen && (props.autoClosing || this.isOpen === false)) {
      this.openMenu(props.isOpen);
    }
  }

  onLayoutChange(e: Event) {
    const { width, height } = e.nativeEvent.layout;
    const openMenuOffset = width * this.state.openOffsetMenuPercentage;
    const hiddenMenuOffset = width * this.state.hiddenMenuOffsetPercentage;
    this.setState({ width, height, openMenuOffset, hiddenMenuOffset });
  }

  /**
   * Get content view. This view will be rendered over menu
   * @return {React.Component}
   */
  getContentView() {
    let overlay: React.Element<void, void> = null;

    if (this.isOpen) {
      overlay = (
        <TouchableWithoutFeedback onPress={() => this.openMenu(false)}>
          <View style={styles.overlay} />
        </TouchableWithoutFeedback>
      );
    }

    const { width, height } = this.state;
    const ref = sideMenu => (this.sideMenu = sideMenu);
    const style = [
      styles.frontView,
      { width, height },
      this.props.animationStyle(this.state.left),
    ];

    return (
      <Animated.View style={style} ref={ref} {...this.responder.panHandlers}>
        {this.props.children}
        {overlay}
      </Animated.View>
    );
  }

  moveLeft(offset: number) {
    const newOffset = this.menuPositionMultiplier() * offset;

    this.props
      .animationFunction(this.state.left, newOffset)
      .start();

    this.prevLeft = newOffset;
  }

  menuPositionMultiplier(): -1 | 1 {
    return this.props.menuPosition === 'right' ? -1 : 1;
  }

  handlePanResponderMove(e: Object, gestureState: Object) {
    if (this.state.left.__getValue() * this.menuPositionMultiplier() >= 0) {
      let newLeft = this.prevLeft + gestureState.dx;

      if (!this.props.bounceBackOnOverdraw && Math.abs(newLeft) > this.state.openMenuOffset) {
        newLeft = this.menuPositionMultiplier() * this.state.openMenuOffset;
      }

      this.props.onMove(newLeft);
      this.state.left.setValue(newLeft);
    }
  }

  handlePanResponderEnd(e: Object, gestureState: Object) {
    const offsetLeft = this.menuPositionMultiplier() *
      (this.state.left.__getValue() + gestureState.dx);

    this.openMenu(shouldOpenMenu(offsetLeft));
  }

  handleMoveShouldSetPanResponder(e: any, gestureState: any): boolean {
    if (this.gesturesAreEnabled()) {
      const x = Math.round(Math.abs(gestureState.dx));
      const y = Math.round(Math.abs(gestureState.dy));

      const touchMoved = x > this.props.toleranceX && y < this.props.toleranceY;

      if (this.isOpen) {
        return touchMoved;
      }

      const withinEdgeHitWidth = this.props.menuPosition === 'right' ?
        gestureState.moveX > (deviceScreen.width - this.props.edgeHitWidth) :
        gestureState.moveX < this.props.edgeHitWidth;

      const swipingToOpen = this.menuPositionMultiplier() * gestureState.dx > 0;
      return withinEdgeHitWidth && touchMoved && swipingToOpen;
    }

    return false;
  }

  openMenu(isOpen: boolean): void {
    const { hiddenMenuOffset, openMenuOffset } = this.state;
    this.moveLeft(isOpen ? openMenuOffset : hiddenMenuOffset);
    this.isOpen = isOpen;

    this.forceUpdate();
    this.props.onChange(isOpen);
  }

  gesturesAreEnabled(): boolean {
    const { disableGestures } = this.props;

    if (typeof disableGestures === 'function') {
      return !disableGestures();
    }

    return !disableGestures;
  }

  render(): React.Element<void, void> {
    const boundryStyle = this.props.menuPosition === 'right' ?
      { left: this.state.width - this.state.openMenuOffset } :
      { right: this.state.width - this.state.openMenuOffset };

    const menu = (
      <View style={[styles.menu, boundryStyle]}>
        {this.props.menu}
      </View>
    );

    return (
      <View
        style={styles.container}
        onLayout={this.onLayoutChange}
      >
        {menu}
        {this.getContentView()}
      </View>
    );
  }
}

SideMenu.propTypes = {
  edgeHitWidth: PropTypes.number,
  toleranceX: PropTypes.number,
  toleranceY: PropTypes.number,
  menuPosition: PropTypes.oneOf(['left', 'right']),
  onChange: PropTypes.func,
  onMove: PropTypes.func,
  children: PropTypes.node,
  menu: PropTypes.node,
  openMenuOffset: PropTypes.number,
  hiddenMenuOffset: PropTypes.number,
  animationStyle: PropTypes.func,
  disableGestures: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
  animationFunction: PropTypes.func,
  onStartShouldSetResponderCapture: PropTypes.func,
  isOpen: PropTypes.bool,
  bounceBackOnOverdraw: PropTypes.bool,
  autoClosing: PropTypes.bool,
};

SideMenu.defaultProps = {
  toleranceY: 10,
  toleranceX: 10,
  edgeHitWidth: 60,
  children: null,
  menu: null,
  openMenuOffset: deviceScreen.width * (2 / 3),
  disableGestures: false,
  menuPosition: 'left',
  hiddenMenuOffset: 0,
  onMove: () => {},
  onStartShouldSetResponderCapture: () => true,
  onChange: () => {},
  onSliding: () => {},
  animationStyle: value => ({
    transform: [{
      translateX: value,
    }],
  }),
  animationFunction: (prop, value) => Animated.spring(prop, {
    toValue: value,
    friction: 8,
  }),
  isOpen: false,
  bounceBackOnOverdraw: true,
  autoClosing: true,
};
<|endoftext|>


<commit_before>var expect=require("chai").expect,
     sinon=require("sinon"),
     request=require("supertest"),
     app=require("../app.js"),
     address=request("http://localhost:8080"),
     categories = require("../models/category");
     var modelStub = sinon.stub(categories, 'find');

  describe.only("Topic Handler router", function(err){

       it('Getting /topicsHandler/categories get function from "Topics Handler"  through App.js', function(done){
        address
        .get('/topicsHandler/categories')
        .end(function(err,res) {
    		 expect(res.statusCode).to.be.equal(200);
    		 done();
    		});
        });

        describe('Describe Find items-------------------------------1', function(){
          beforeEach(function(){
          modelStub.withArgs({_id: "Hello"}).yields(null, {
            _id: "Hello",
          categoryName:"Big Hello",
          categoryTopics: [{_id: "Computers",
          topicName: "Coding",
          topicIcon: "facebook",
          topicCategory: ["Hello", "Hi", "How are you?"],
          topicDescription: "Hello, This is just a game we are into.",
          topicFollowers: 1212,
          playersPerMatch: 3,
          games:"Single"
}]});
            });

      it('Getting /category/:categoryId get function-------------2', function(done){
        address
         .get("/topicsHandler/category/Hello")
         .end(function(err,res){
         expect(res.statusCode).to.be.equal(200);
          // expect(res.body[0].categoryName).to.be.equal("Big Hello");

           done();
      });
    });
  });
});
<commit_msg>topicshandlertest<commit_after>var expect=require("chai").expect,
     sinon=require("sinon"),
     request=require("supertest"),
     app=require("../app.js"),
     address=request("http://localhost:8080"),
     categories = require("../models/category");
     var modelStub = sinon.stub(categories, 'find');

  describe.only("Topic Handler router", function(err){

       it('Getting /topicsHandler/categories get function from "Topics Handler"  through App.js', function(done){
        address
        .get('/topicsHandler/categories')
        .end(function(err,res) {
    		 expect(res.statusCode).to.be.equal(200);
    		 done();
    		});
        });

        describe('Describe Find items-------------------------------1', function(){
          beforeEach(function(){
          modelStub.withArgs({_id: "Hello"}).yields(null, {
            _id: "Hello",
          categoryName:"Big Hello",
          categoryTopics: [{_id: "Computers",
          topicName: "Coding",
          topicIcon: "facebook",
          topicCategory: ["Hello", "Hi", "How are you?"],
          topicDescription: "Hello, This is just a game we are into.",
          topicFollowers: 1212,
          playersPerMatch: 3,
          games:"Single"
}]});
            });

      it('Getting /category/:categoryId get function-------------2', function(done){
        address
         .get("/topicsHandler/category/Hello")
         .end(function(err,res){
         expect(res.statusCode).to.be.equal(200);
          // expect(res.body[0].categoryName).to.be.equal("Big Hello");

           done();
      });
    });
  });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
/*!
 * -----------
 * SCGDB®-Data
 * -----------
 * Data of SCGDB — A manually curated dedicated schizosaccharomyces comparative genome database.
 * ______________________________________________________________________________________________
 *
 * CCPE ——————— Centre for Computational Protein Engineering.
 *
 * Architecture and Code Handcrafted by Prabhat Kumar.
 * Architectuur en Code handgemaakt door Prabhat Kumar.
 * @author    : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Sequømics Research [http://research.sequomics.com/].
 * @copyright : Sequømics Corporation [http://sequomics.com/].
 * ______________________________________________________________________________________________
 *
 * @date      : 18-Dec-2016
 * @license   : Apache, version 2.0
 * @purpose   : To create Data System(s) with Node.js® and NPM.
 * @require   : Node.js®
 * @require   : NPM
 * @build     : SEED™ — Skövde
 *              └────── A Sequømics Product — http://seed.sequomics.com/.
 * ______________________________________________________________________________________________
 *
 * --/The Heart of Data System/-- of "SCGDB®-Data".
 * ______________________________________________________________________________________________
 */

// global __dirname: true
// global require: true

// # Usage: $ node -v
// # Usage: $ npm -v

// Invoking strict mode.
"use strict";

// To load required Node module.
// -----------------------------
var os         = require('os');
var fs         = require('fs');
var path       = require('path');

// To load required NPM modules.
// -----------------------------
var chalk      = require('chalk');
var semver     = require('semver');

// Default color defined.
// ----------------------
var noop       = chalk.red;
var yeep       = chalk.green;
var okay       = chalk.blue;
var boop       = chalk.cyan;
var goop       = chalk.gray;

///-------------------
// An object literals.
///-------------------
var build = {
  // Non-identifier property names are quoted.
  "system"     : "SEED™",
  "name"       : "Skövde",
  "year"       : "2016",
  "audience"   : "for all scientist and computational biologist."
};

///--------------------------
// A smart stripBOM function.
///----------- 01 -----------
function stripBOM(content) {
  // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  // because the buffer-to-string conversion in `fs.readFileSync()`
  // translates it to FEFF, the UTF-16 BOM.
  if (content.charCodeAt(0) === 0xFEFF) {
    content = content.slice(1);
  }
  return content;
}

///--------------------
// A citation of SCGDB®
///--------------------
var cite = JSON.parse(stripBOM(fs.readFileSync('./citation.json', {
  encoding: "utf8"
})));

// To get credential(s) information.
///---------------------------------
var pass  = JSON.parse(stripBOM(fs.readFileSync('./secret.json', {
  encoding: "utf8"
})));

// Global access variables.
var message   = "SCGDB® — Supported under Mac OS X and Linux only!";
var contact   = "database@sequomics.com";
<commit_msg>Initial commit<commit_after>#!/usr/bin/env node
/*!
 * -----------
 * SCGDB®-Data
 * -----------
 * Data of SCGDB — A manually curated dedicated schizosaccharomyces comparative genome database.
 * ______________________________________________________________________________________________
 *
 * CCPE ——————— Centre for Computational Protein Engineering.
 *
 * Architecture and Code Handcrafted by Prabhat Kumar.
 * Architectuur en Code handgemaakt door Prabhat Kumar.
 * @author    : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Sequømics Research [http://research.sequomics.com/].
 * @copyright : Sequømics Corporation [http://sequomics.com/].
 * ______________________________________________________________________________________________
 *
 * @date      : 18-Dec-2016
 * @license   : Apache, version 2.0
 * @purpose   : To create Data System(s) with Node.js® and NPM.
 * @require   : Node.js®
 * @require   : NPM
 * @build     : SEED™ — Skövde
 *              └────── A Sequømics Product — http://seed.sequomics.com/.
 * ______________________________________________________________________________________________
 *
 * --/The Heart of Data System/-- of "SCGDB®-Data".
 * ______________________________________________________________________________________________
 */

// global __dirname: true
// global require: true

// # Usage: $ node -v
// # Usage: $ npm -v

// Invoking strict mode.
"use strict";

// To load required Node module.
// -----------------------------
var os         = require('os');
var fs         = require('fs');
var path       = require('path');

// To load required NPM modules.
// -----------------------------
var chalk      = require('chalk');
var semver     = require('semver');

// Default color defined.
// ----------------------
var noop       = chalk.red;
var yeep       = chalk.green;
var okay       = chalk.blue;
var boop       = chalk.cyan;
var goop       = chalk.gray;

///-------------------
// An object literals.
///-------------------
var build = {
  // Non-identifier property names are quoted.
  "system"     : "SEED™",
  "name"       : "Skövde",
  "year"       : "2016",
  "audience"   : "for all scientist and computational biologist."
};

///--------------------------
// A smart stripBOM function.
///----------- 01 -----------
function stripBOM(content) {
  // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  // because the buffer-to-string conversion in `fs.readFileSync()`
  // translates it to FEFF, the UTF-16 BOM.
  if (content.charCodeAt(0) === 0xFEFF) {
    content = content.slice(1);
  }
  return content;
}

///--------------------
// A citation of SCGDB®
///--------------------
var cite = JSON.parse(stripBOM(fs.readFileSync('./citation.json', {
  encoding: "utf8"
})));

// To get credential(s) information.
///---------------------------------
var pass  = JSON.parse(stripBOM(fs.readFileSync('./secret.json', {
  encoding: "utf8"
})));

// Global access variables.
var message   = "SCGDB® — Supported under Mac OS X and Linux only!";
var contact   = "database@sequomics.com";
// Our versioning system.
var version   = require("./version");
<|endoftext|>


<commit_before>// Copyright 2013 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

assertEquals(String.fromCharCode(97, 220, 256), 'a' + '\u00DC' + '\u0100');
assertEquals(String.fromCharCode(97, 220, 256), 'a\u00DC\u0100');

assertEquals(['a', 'b', '\xdc'], ['b', '\xdc', 'a'].sort());
assertEquals(['\xfc\xdc', '\xfc'], new RegExp('(\xdc)\\1', 'i').exec('\xfc\xdc'));

<commit_msg>Restore correct regression test for crbug/146910.<commit_after>// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

var x = [];
assertSame(0, x.length);
assertSame(undefined, x[0]);

Object.defineProperty(x, '0', { value: 7, configurable: false });
assertSame(1, x.length);
assertSame(7, x[0]);

x.length = 0;
assertSame(1, x.length);
assertSame(7, x[0]);
<|endoftext|>


<commit_before>/**
 * public api for cartodb
 */

(function() {

  function _Promise() {

  }
  _.extend(_Promise.prototype,  Backbone.Events, {
    done: function(fn) {
      return this.bind('done', fn);
    },
    error: function(fn) {
      return this.bind('error', fn);
    }
  });

  cdb._Promise = _Promise;

  var _requestCache = {};

  /**
   * compose cartodb url
   */
  function cartodbUrl(opts) {
    var host = opts.host || 'cartodb.com';
    var protocol = opts.protocol || 'https';
    return protocol + '://' + opts.user + '.' + host + '/api/v1/viz/' + opts.table + '/viz.json';
  }

  /**
   * given layer params fetchs the layer json
   */
  function _getLayerJson(layer, callback) {
    var url = null;
    if(layer.layers !== undefined || ((layer.kind || layer.type) !== undefined)) {
      // layer object contains the layer data
      _.defer(function() { callback(layer); });
      return;
    } else if(layer.table !== undefined && layer.user !== undefined) {
      // layer object points to cartodbjson
      url = cartodbUrl(layer);
    } else if(layer.indexOf && layer.indexOf('http') === 0) {
      // fetch from url
      url = layer;
    }
    if(url) {
      cdb.vis.Loader.get(url, callback);
    } else {
      _.defer(function() { callback(null); });
    }
  }

  /**
   * create a layer for the specified map
   *
   * @param map should be a L.Map or google.maps.Map object
   * @param layer should be an url or a javascript object with the data to create the layer
   * @param options layer options
   *
   */

  cartodb.createLayer = function(map, layer, options, callback) {

    var promise = new _Promise();
    var layerView, MapType;
    options = options || {};
    if(map === undefined) {
      throw new TypeError("map should be provided");
    }
    if(layer === undefined) {
      throw new TypeError("layer should be provided");
    }
    var args = arguments,
    fn = args[args.length -1];
    if(_.isFunction(fn)) {
      callback = fn;
    }

    promise.addTo = function(map, position) {
      promise.on('done', function() {
        MapType.addLayerToMap(layerView, map, position);
      });
      return promise;
    };

    _getLayerJson(layer, function(visData) {

      var layerData;

      if(!visData) {
        promise.trigger('error');
        return;
      }
      // extract layer data from visualization data
      if(visData.layers) {
        if(visData.layers.length < 2) {
          promise.trigger('error', "visualization file does not contain layer info");
        }
        var idx = options.layerIndex === undefined ? 1: options.layerIndex;
        if(visData.layers.length <= idx) {
          promise.trigger('error', 'layerIndex out of bounds');
          return;
        }
        layerData = visData.layers[idx];
      } else {
        layerData = visData;
      }

      if(!layerData) {
        promise.trigger('error');
        return;
      }

      // update options
      if(options && !_.isFunction(options)) {
        layerData.options = layerData.options || {};
        _.extend(layerData.options, options);
      }

      options = _.defaults(options, {
        infowindow: true,
        https: false,
        legends: true,
        time_slider: true,
        tooltip: true
      });

      // check map type
      // TODO: improve checking
      if(typeof(map.overlayMapTypes) !== "undefined") {
        MapType = cdb.geo.GoogleMapsMapView;
        // check if leaflet is loaded globally
      } else if(map instanceof L.Map || (window.L && map instanceof window.L.Map)) {
        MapType = cdb.geo.LeafletMapView;
      } else {
        promise.trigger('error', "cartodb.js can't guess the map type");
        return promise;
      }

      // create a dummy viz
      var viz = map.viz;
      if(!viz) {
        var mapView = new MapType({
          map_object: map,
          map: new cdb.geo.Map()
        });

        map.viz = viz = new cdb.vis.Vis({
          mapView: mapView
        });

        viz.updated_at = visData.updated_at;
        viz.https = options.https;
      }

      function createLayer() {
        layerView = viz.createLayer(layerData, { no_base_layer: true });

        var torqueLayer;
        var mobileEnabled = /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        var smallEmbed = $(window).width() < 620;

        if(!layerView) {
          promise.trigger('error', "layer not supported");
          return promise;
        }
        if(options.infowindow) {
          viz.addInfowindow(layerView);
        }
        if(options.tooltip) {
          viz.addTooltip(layerView);
        }
        if(options.legends) {
          viz.addLegends([layerData], mobileEnabled || smallEmbed);
        }
        if(options.time_slider && layerView.model.get('type') === 'torque') {
          viz.addTimeSlider(layerView);
          torqueLayer = layerView;
        }

        if (options.mobile_layout && (mobileEnabled || smallEmbed)) {

          options.mapView = map.viz.mapView;

          viz.addOverlay({
            type: 'mobile',
            layerView: layerView,
            overlays: [],
            torqueLayer: torqueLayer,
            options: options
          });
        }

        callback && callback(layerView);
        promise.trigger('done', layerView);
      }

      // load needed modules
      if(!viz.checkModules([layerData])) {
        viz.loadModules([layerData], function() {
          createLayer();
        });
      } else {
        createLayer();
      }

    });

    return promise;

  };

})();
<commit_msg>fixes legend showing<commit_after>/**
 * public api for cartodb
 */

(function() {

  function _Promise() {

  }
  _.extend(_Promise.prototype,  Backbone.Events, {
    done: function(fn) {
      return this.bind('done', fn);
    },
    error: function(fn) {
      return this.bind('error', fn);
    }
  });

  cdb._Promise = _Promise;

  var _requestCache = {};

  /**
   * compose cartodb url
   */
  function cartodbUrl(opts) {
    var host = opts.host || 'cartodb.com';
    var protocol = opts.protocol || 'https';
    return protocol + '://' + opts.user + '.' + host + '/api/v1/viz/' + opts.table + '/viz.json';
  }

  /**
   * given layer params fetchs the layer json
   */
  function _getLayerJson(layer, callback) {
    var url = null;
    if(layer.layers !== undefined || ((layer.kind || layer.type) !== undefined)) {
      // layer object contains the layer data
      _.defer(function() { callback(layer); });
      return;
    } else if(layer.table !== undefined && layer.user !== undefined) {
      // layer object points to cartodbjson
      url = cartodbUrl(layer);
    } else if(layer.indexOf && layer.indexOf('http') === 0) {
      // fetch from url
      url = layer;
    }
    if(url) {
      cdb.vis.Loader.get(url, callback);
    } else {
      _.defer(function() { callback(null); });
    }
  }

  /**
   * create a layer for the specified map
   *
   * @param map should be a L.Map or google.maps.Map object
   * @param layer should be an url or a javascript object with the data to create the layer
   * @param options layer options
   *
   */

  cartodb.createLayer = function(map, layer, options, callback) {

    var promise = new _Promise();
    var layerView, MapType;
    options = options || {};
    if(map === undefined) {
      throw new TypeError("map should be provided");
    }
    if(layer === undefined) {
      throw new TypeError("layer should be provided");
    }
    var args = arguments,
    fn = args[args.length -1];
    if(_.isFunction(fn)) {
      callback = fn;
    }

    promise.addTo = function(map, position) {
      promise.on('done', function() {
        MapType.addLayerToMap(layerView, map, position);
      });
      return promise;
    };

    _getLayerJson(layer, function(visData) {

      var layerData;

      if(!visData) {
        promise.trigger('error');
        return;
      }
      // extract layer data from visualization data
      if(visData.layers) {
        if(visData.layers.length < 2) {
          promise.trigger('error', "visualization file does not contain layer info");
        }
        var idx = options.layerIndex === undefined ? 1: options.layerIndex;
        if(visData.layers.length <= idx) {
          promise.trigger('error', 'layerIndex out of bounds');
          return;
        }
        layerData = visData.layers[idx];
      } else {
        layerData = visData;
      }

      if(!layerData) {
        promise.trigger('error');
        return;
      }

      // update options
      if(options && !_.isFunction(options)) {
        layerData.options = layerData.options || {};
        _.extend(layerData.options, options);
      }

      options = _.defaults(options, {
        infowindow: true,
        https: false,
        legends: true,
        time_slider: true,
        tooltip: true
      });

      // check map type
      // TODO: improve checking
      if(typeof(map.overlayMapTypes) !== "undefined") {
        MapType = cdb.geo.GoogleMapsMapView;
        // check if leaflet is loaded globally
      } else if(map instanceof L.Map || (window.L && map instanceof window.L.Map)) {
        MapType = cdb.geo.LeafletMapView;
      } else {
        promise.trigger('error', "cartodb.js can't guess the map type");
        return promise;
      }

      // create a dummy viz
      var viz = map.viz;
      if(!viz) {
        var mapView = new MapType({
          map_object: map,
          map: new cdb.geo.Map()
        });

        map.viz = viz = new cdb.vis.Vis({
          mapView: mapView
        });

        viz.updated_at = visData.updated_at;
        viz.https = options.https;
      }

      function createLayer() {
        layerView = viz.createLayer(layerData, { no_base_layer: true });

        var torqueLayer;
        var mobileEnabled = /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        var smallEmbed = $(window).width() < 620;

        if(!layerView) {
          promise.trigger('error', "layer not supported");
          return promise;
        }
        if(options.infowindow) {
          viz.addInfowindow(layerView);
        }
        if(options.tooltip) {
          viz.addTooltip(layerView);
        }
        if(options.legends) {
          viz.addLegends([layerData], (options.mobile_layout && (mobileEnabled || smallEmbed)));
        }
        if(options.time_slider && layerView.model.get('type') === 'torque') {
          viz.addTimeSlider(layerView);
          torqueLayer = layerView;
        }

        if (options.mobile_layout && (mobileEnabled || smallEmbed)) {

          options.mapView = map.viz.mapView;

          viz.addOverlay({
            type: 'mobile',
            layerView: layerView,
            overlays: [],
            torqueLayer: torqueLayer,
            options: options
          });
        }

        callback && callback(layerView);
        promise.trigger('done', layerView);
      }

      // load needed modules
      if(!viz.checkModules([layerData])) {
        viz.loadModules([layerData], function() {
          createLayer();
        });
      } else {
        createLayer();
      }

    });

    return promise;

  };

})();
<|endoftext|>


<commit_before>var MapproxyBaseService = function(_section, _model, _dependencies) {
    var _this = this;
    this._items = {};
    this._item;
    this._last;
    this._section = _section;
    this._action;
    this._dependencies = _dependencies;
    this._model = _model;
    this._rootScope;
    this._resource;
    this._messageService;
    this.error;

    this._errorMessageHandler = function(error) {
        _this._rootScope.$broadcast(_this._section + '.' + _this._action + '_error');
        _this._messageService.message(_this._section, _this._action + '_error', error.data.error);
    };
    this._successMessageHandler = function(msg) {
        _this._messageService.message(_this._section, _this._action + '_success', msg);
    };
    this._addDependencies = function(item) {
        item._dependencies = {};
        angular.forEach(_this._dependencies, function(dependency) {
            item._dependencies[dependency._section] = []
            angular.forEach(dependency._items, function(dependencyItem) {
                var useSection = _this._section;
                //layers only have sources for cache- and source-items
                if(item._section == 'caches' && dependencyItem._section == 'layers') {
                    useSection = 'sources';
                }
                if($.inArray(item._id, dependencyItem.data[useSection]) != -1) {
                    item._dependencies[dependency._section].push(dependencyItem);
                }
            });
        });
    };
    this._waitForLoadComplete = function(event) {
        var name = event.name.split('.')[0];
        var loadComplete = _this._loaded;
        angular.forEach(_this.dependencies, function(dependency) {
            if(!dependency._loaded) {
                loadComplete = false;
            }
        });
        if(loadComplete) {
            angular.forEach(_this._items, _this._addDependencies);
            _this._successMessageHandler(_this._localize.getLocalizedString('Load complete'));
        }
    };
    this._removeNonModelProperties = function(data) {
        var cleanup = function(cleanData, data) {
            var _data = {};
            angular.forEach(cleanData, function(value, key) {
                if(angular.isObject(cleanData[key]) && !angular.isArray(cleanData[key])) {
                    _data[key] = cleanup(cleanData[key], data[key]);
                } else {
                    if(angular.isDefined(data)) {
                        _data[key] = data[key]
                    }
                }
            });
            return _data;
        };
        return cleanup(_this._model, data);;
    };
    this.load = function() {
        _this._items = {};
        _this._loaded = false;
        _this._action = 'load';
        _this._loadingInProgress = true;
        _this._resource.query({action: _this._section}, function(result) {
            if(result) {
                angular.forEach(result, function(item) {
                    item._section = _this._section;
                    _this._items[item._id] = item;
                });
                _this._loaded = true;
                _this._loadingInProgress = false;
                if(angular.isDefined(_this._rootScope))
                    _this._rootScope.$broadcast(_this._section + '.load_finished');
            }
        }, _this._errorMessageHandler);
    };
    this.add = function(_item) {
        if(!_item._manual) {
            _item.data = _this._removeNonModelProperties(_item.data);
        }
        var item = new _this._resource(_item);
        delete item._dependencies;
        delete item._section;
        if(angular.isUndefined(item._id)) {
            _this._action = 'add';
            item.$save({action: _this._section},
                function(result) {
                    result._section = _this._section;
                    _this._addDependencies(result);
                    _this._items[result._id] = result;
                    _this._successMessageHandler(_this._localize.getLocalizedString('Successful added'));
                    if(angular.isDefined(_this._rootScope)) {
                        _this._last = result;
                        _this.current(true, result);
                    }
                }, _this._errorMessageHandler);
        } else {
            _this._action = 'update';
            item.$update({action: _this._section, id: item._id}, function(result) {
                result._section = _this._section;
                _this._addDependencies(result);
                _this._items[result._id] = result;
                _this._successMessageHandler(_this._localize.getLocalizedString('Successful updated'));
                if(angular.isDefined(_this._rootScope)) {
                    _this._last = result;
                    _this.current(true, result);
                }
            }, _this._errorMessageHandler);
        }
    };
    this.remove = function(_item) {
        var item = new _this._resource(_item)
        _this._action = 'delete';
        item.$delete({action: _this._section, id: item._id}, function(result) {
            delete(_this._items[result._id]);
            _this._successMessageHandler(_this._localize.getLocalizedString('Successful deleted'));
        }, _this._errorMessageHandler);
    };
    this.list = function() {
        var result = [];
        for(var key in _this._items) {
            result.push(_this._items[key]);
        }
        return result;
    };
    this.byId = function(_id) {
        return angular.isDefined(_this._items[_id]) ? _this._items[_id] : false;
    };
    this.byName = function(_name) {
        for(var id in _this._items) {
            if(_this._items[id].data.name == _name) {
                return _this._items[id];
            }
        }
        return false;
    };
    this.idByName = function(_name) {
        var item = _this.byName(_name);
        return item ? item._id : false;

    };
    this.nameById = function(_id) {
        var item = _this.byId(_id);
        return item ? item.data.name : false;
    };
    this.current = function(_item) {
        if(_item) {
            _this._item = _item;
            if(angular.isDefined(_this._rootScope))
                _this._rootScope.$broadcast(_this._section + '.current');
        } else {
            return $.extend({}, {'data': _this._model}, _this._item);
        }
    };
    this.last = function() {
        return _this._last;
    };
    this.error = function() {
        return _this._error_msg;
    }
    this.return_func = function($rootScope, MapproxyResource, MessageService, localize) {
        _this._rootScope = $rootScope;
        _this._resource = MapproxyResource;
        _this._messageService = MessageService;
        _this._localize = localize;
        _this._rootScope.$on(_this._section + '.load_finished', _this._waitForLoadComplete);
        angular.forEach(_this._dependencies, function(dependency) {
            _this._rootScope.$on(dependency._section + '.load_finished', _this._waitForLoadComplete)
            dependency.return_func(_this._rootScope, _this._resource, _this._messageService, _this._localize);
        });
        if(!_this._loadingInProgress && !_this._loaded) {
            _this.load();
        }
        return _this.return_dict;
    };

    this.return_dict = {
        refresh: _this.load,
        add: _this.add,
        remove: _this.remove,
        list: _this.list,
        byId: _this.byId,
        byName: _this.byName,
        idByName: _this.idByName,
        nameById: _this.nameById,
        current: _this.current,
        last: _this.last,
        error: _this.error,
        section: _this._section,
        model: _this._model
    }
};

var MapproxyLayerService = function(_section, _model, _dependencies) {
    MapproxyBaseService.call(this, _section, _model, _dependencies);
    var _this = this;

    this.prepareLayer = function(store, layer, idx, parent_id) {
        if(angular.isDefined(layer._layers)) {
            angular.forEach(layer._layers, function(child_layer, _idx) {
                _this.prepareLayer(store, child_layer, _idx, layer._id);
            });
        }
        store.push({_id: layer._id, _rank: idx, _parent: parent_id})
    };

    this.tree = function(parent_id) {
        var treeStructure = [];
        var items = angular.copy(_this._items);
        angular.forEach(items, function(item) {
            if(item._parent == null) {
                if($.inArray(item, treeStructure) == -1) {
                    treeStructure.push(item);
                }
            } else {
                if(angular.isArray(items[item._parent]._layers)) {
                    if($.inArray(item, items[item._parent]) == -1) {
                        items[item._parent]._layers.push(item)
                    }
                } else {
                    items[item._parent]._layers = [item]
                }
            }
        });
        return treeStructure;
    };

    this.updateStructure = function(tree) {
        var to_update = [];
        _this._action = 'updateStructure';
        angular.forEach(tree, function(layer, idx) {
            _this.prepareLayer(to_update, layer, idx);
        });
        to_update = new _this._resource({'tree': to_update});
        to_update.$update({action: _this._section}, function(result) {
            _this._successMessageHandler(_this._localize.getLocalizedString('Structure successful updated'));
        }, _this._errorMessageHandler);
    };

    this.return_dict['tree'] = _this.tree;
    this.return_dict['updateStructure'] = _this.updateStructure;
};

WMSSourceService = function(_section) {
    MapproxyBaseService.call(this, _section);
    var _this = this;

    this._addSourceURL = function(layer, sourceURL) {
        layer.sourceURL = sourceURL;
        if(angular.isDefined(layer.layers)) {
            angular.forEach(layer.layers, function(layer) {
                _this._addSourceURL(layer, sourceURL);
            });
        }
    };
    this.list = function() {
        var result = [];
        angular.forEach(_this._items, function(item) {
            var sourceURL = item.data.url;
            angular.forEach(item.data.layer.layers, function(layer) {
                _this._addSourceURL(layer, sourceURL)
            });
        });
        for(var key in _this._items) {
            result.push(_this._items[key]);
        }
        return result;
    };
    this._identifySource = function(url) {
        var source = false;
        angular.forEach(_this._items, function(_source) {
            if(_source.data.url == url) {
                source = _source;
            }
        });
        return source;
    };
    this._identifyLayer = function(layers, layerName) {
        var layer = false;
        angular.forEach(layers, function(_layer) {
            if(!layer) {
                if(_layer.name == layerName) {
                    layer = _layer;
                } else if(angular.isDefined(_layer.layers)) {
                    layer = _this._identifyLayer(_layer.layers, layerName);
                }
            }
        });
        return layer;
    };

    this.layerTitle = function(url, layerName) {
        var source = _this._identifySource(url);
        if(source) {
            var layer = _this._identifyLayer(source.data.layer.layers, layerName);
            if(layer) {
                return layer.title;
            }
        }
        return false;
    };

    this.coverage = function(url) {
        var source = _this._identifySource(url);
        if(source) {
            return source.data.layer.llbbox;
        }
        return false;
    };

    this.srs = function(url) {
        var source = _this._identifySource(url);
        if(source) {
            return source.data.layer.srs;
        }
        return false;
    };

    this.refresh = function(_item) {
        var item = new _this._resource(_item);
        _this._action = 'update';
        item.$update({action: _this._section, id: item._id}, function(result) {
            _this._items[result._id] = result;
            _this._last = result;
            _this._successMessageHandler(_this._localize.getLocalizedString('Successful updated'));
        }, _this._errorMessageHandler);
    };

    this.allURLs = function() {
        var result = [];
        angular.forEach(_this._items, function(wms) {
            result.push(wms.url);
        });
        return result;
    };

    this.return_dict['list'] = _this.list;
    this.return_dict['layerTitle'] = _this.layerTitle;
    this.return_dict['refresh'] = _this.refresh;
    this.return_dict['allURLs'] = _this.allURLs;
    this.return_dict['coverage'] = _this.coverage;
    this.return_dict['srs'] = _this.srs;
};

var layerModel = {
    'name': undefined,
    'title': undefined,
    'sources': [],
    'min_res': undefined,
    'max_res': undefined,
    'min_res_scale': undefined,
    'max_res_scale': undefined
};
var globalsModel = {
    'cache': {
        'meta_size': [],
        'meta_buffer': undefined
    },
    'image': {
        'resampling_method': undefined,
        'paletted': undefined
    }
};
var cacheModel = {
    'name': undefined,
    'sources': [],
    'grids': [],
    'format': undefined,
    'request_format': undefined
};
var gridModel = {
    'name': undefined,
    'srs': undefined,
    'bbox': [],
    'bbox_srs': undefined,
    'origin': undefined,
    'res': [],
    'scales': []
};
var sourceModel = {
    'name': undefined,
    'req': {
        'url': undefined,
        'layers': [],
        'transparent': undefined
    },
    'coverage': {
        'bbox': undefined,
        'srs': undefined
    },
    'supported_formats': []
};
var defaultsModel = {
    'dpi': undefined,
    'srs': []
}

var layerService = new MapproxyLayerService('layers', layerModel);
var globalsService = new MapproxyBaseService('globals', globalsModel);
var servicesService = new MapproxyBaseService('services');
var cacheService = new MapproxyBaseService('caches', cacheModel, [layerService]);
var gridService = new MapproxyBaseService('grids', gridModel, [cacheService]);
var sourceService = new MapproxyBaseService('sources', sourceModel, [cacheService, layerService]);
var wmsService = new WMSSourceService('wms_capabilities');
var defaultsService = new MapproxyBaseService('defaults', defaultsModel);

angular.module('mapproxy_gui.services', ['mapproxy_gui.resources']).

service('WMSSources', wmsService.return_func).
service('MapproxySources', sourceService.return_func).
service('MapproxyCaches', cacheService.return_func).
service('MapproxyGrids', gridService.return_func).
service('MapproxyLayers', layerService.return_func).
service('MapproxyGlobals', globalsService.return_func).
service('MapproxyServices', servicesService.return_func).
service('ProjectDefaults', defaultsService.return_func).

service('DataShareService', function($rootScope) {
    var _this = this;
    this._data = {};

    return {
        data: function(key, value) {
            if(angular.isDefined(value)) {
                _this._data[key] = value;
                $rootScope.$broadcast('dss.' + key);
            } else {
                if(angular.isDefined(_this._data[key])) {
                    return _this._data[key];
                } else {
                    return undefined;
                }
            }
        }
    }
});
<commit_msg>Fixed add/update without model<commit_after>var MapproxyBaseService = function(_section, _model, _dependencies) {
    var _this = this;
    this._items = {};
    this._item;
    this._last;
    this._section = _section;
    this._action;
    this._dependencies = _dependencies;
    this._model = _model;
    this._rootScope;
    this._resource;
    this._messageService;
    this.error;

    this._errorMessageHandler = function(error) {
        _this._rootScope.$broadcast(_this._section + '.' + _this._action + '_error');
        _this._messageService.message(_this._section, _this._action + '_error', error.data.error);
    };
    this._successMessageHandler = function(msg) {
        _this._messageService.message(_this._section, _this._action + '_success', msg);
    };
    this._addDependencies = function(item) {
        item._dependencies = {};
        angular.forEach(_this._dependencies, function(dependency) {
            item._dependencies[dependency._section] = []
            angular.forEach(dependency._items, function(dependencyItem) {
                var useSection = _this._section;
                //layers only have sources for cache- and source-items
                if(item._section == 'caches' && dependencyItem._section == 'layers') {
                    useSection = 'sources';
                }
                if($.inArray(item._id, dependencyItem.data[useSection]) != -1) {
                    item._dependencies[dependency._section].push(dependencyItem);
                }
            });
        });
    };
    this._waitForLoadComplete = function(event) {
        var name = event.name.split('.')[0];
        var loadComplete = _this._loaded;
        angular.forEach(_this.dependencies, function(dependency) {
            if(!dependency._loaded) {
                loadComplete = false;
            }
        });
        if(loadComplete) {
            angular.forEach(_this._items, _this._addDependencies);
            _this._successMessageHandler(_this._localize.getLocalizedString('Load complete'));
        }
    };
    this._removeNonModelProperties = function(data) {
        var cleanup = function(cleanData, data) {
            var _data = {};
            angular.forEach(cleanData, function(value, key) {
                if(angular.isObject(cleanData[key]) && !angular.isArray(cleanData[key])) {
                    _data[key] = cleanup(cleanData[key], data[key]);
                } else {
                    if(angular.isDefined(data)) {
                        _data[key] = data[key]
                    }
                }
            });
            return _data;
        };
        return cleanup(_this._model, data);;
    };
    this.load = function() {
        _this._items = {};
        _this._loaded = false;
        _this._action = 'load';
        _this._loadingInProgress = true;
        _this._resource.query({action: _this._section}, function(result) {
            if(result) {
                angular.forEach(result, function(item) {
                    item._section = _this._section;
                    _this._items[item._id] = item;
                });
                _this._loaded = true;
                _this._loadingInProgress = false;
                if(angular.isDefined(_this._rootScope))
                    _this._rootScope.$broadcast(_this._section + '.load_finished');
            }
        }, _this._errorMessageHandler);
    };
    this.add = function(_item) {
        if(_this._model && !_item._manual) {
            _item.data = _this._removeNonModelProperties(_item.data);
        }
        var item = new _this._resource(_item);
        delete item._dependencies;
        delete item._section;
        if(angular.isUndefined(item._id)) {
            _this._action = 'add';
            item.$save({action: _this._section},
                function(result) {
                    result._section = _this._section;
                    _this._addDependencies(result);
                    _this._items[result._id] = result;
                    _this._successMessageHandler(_this._localize.getLocalizedString('Successful added'));
                    if(angular.isDefined(_this._rootScope)) {
                        _this._last = result;
                        _this.current(true, result);
                    }
                }, _this._errorMessageHandler);
        } else {
            _this._action = 'update';
            item.$update({action: _this._section, id: item._id}, function(result) {
                result._section = _this._section;
                _this._addDependencies(result);
                _this._items[result._id] = result;
                _this._successMessageHandler(_this._localize.getLocalizedString('Successful updated'));
                if(angular.isDefined(_this._rootScope)) {
                    _this._last = result;
                    _this.current(true, result);
                }
            }, _this._errorMessageHandler);
        }
    };
    this.remove = function(_item) {
        var item = new _this._resource(_item)
        _this._action = 'delete';
        item.$delete({action: _this._section, id: item._id}, function(result) {
            delete(_this._items[result._id]);
            _this._successMessageHandler(_this._localize.getLocalizedString('Successful deleted'));
        }, _this._errorMessageHandler);
    };
    this.list = function() {
        var result = [];
        for(var key in _this._items) {
            result.push(_this._items[key]);
        }
        return result;
    };
    this.byId = function(_id) {
        return angular.isDefined(_this._items[_id]) ? _this._items[_id] : false;
    };
    this.byName = function(_name) {
        for(var id in _this._items) {
            if(_this._items[id].data.name == _name) {
                return _this._items[id];
            }
        }
        return false;
    };
    this.idByName = function(_name) {
        var item = _this.byName(_name);
        return item ? item._id : false;

    };
    this.nameById = function(_id) {
        var item = _this.byId(_id);
        return item ? item.data.name : false;
    };
    this.current = function(_item) {
        if(_item) {
            _this._item = _item;
            if(angular.isDefined(_this._rootScope))
                _this._rootScope.$broadcast(_this._section + '.current');
        } else {
            return $.extend({}, {'data': _this._model}, _this._item);
        }
    };
    this.last = function() {
        return _this._last;
    };
    this.error = function() {
        return _this._error_msg;
    }
    this.return_func = function($rootScope, MapproxyResource, MessageService, localize) {
        _this._rootScope = $rootScope;
        _this._resource = MapproxyResource;
        _this._messageService = MessageService;
        _this._localize = localize;
        _this._rootScope.$on(_this._section + '.load_finished', _this._waitForLoadComplete);
        angular.forEach(_this._dependencies, function(dependency) {
            _this._rootScope.$on(dependency._section + '.load_finished', _this._waitForLoadComplete)
            dependency.return_func(_this._rootScope, _this._resource, _this._messageService, _this._localize);
        });
        if(!_this._loadingInProgress && !_this._loaded) {
            _this.load();
        }
        return _this.return_dict;
    };

    this.return_dict = {
        refresh: _this.load,
        add: _this.add,
        remove: _this.remove,
        list: _this.list,
        byId: _this.byId,
        byName: _this.byName,
        idByName: _this.idByName,
        nameById: _this.nameById,
        current: _this.current,
        last: _this.last,
        error: _this.error,
        section: _this._section,
        model: _this._model
    }
};

var MapproxyLayerService = function(_section, _model, _dependencies) {
    MapproxyBaseService.call(this, _section, _model, _dependencies);
    var _this = this;

    this.prepareLayer = function(store, layer, idx, parent_id) {
        if(angular.isDefined(layer._layers)) {
            angular.forEach(layer._layers, function(child_layer, _idx) {
                _this.prepareLayer(store, child_layer, _idx, layer._id);
            });
        }
        store.push({_id: layer._id, _rank: idx, _parent: parent_id})
    };

    this.tree = function(parent_id) {
        var treeStructure = [];
        var items = angular.copy(_this._items);
        angular.forEach(items, function(item) {
            if(item._parent == null) {
                if($.inArray(item, treeStructure) == -1) {
                    treeStructure.push(item);
                }
            } else {
                if(angular.isArray(items[item._parent]._layers)) {
                    if($.inArray(item, items[item._parent]) == -1) {
                        items[item._parent]._layers.push(item)
                    }
                } else {
                    items[item._parent]._layers = [item]
                }
            }
        });
        return treeStructure;
    };

    this.updateStructure = function(tree) {
        var to_update = [];
        _this._action = 'updateStructure';
        angular.forEach(tree, function(layer, idx) {
            _this.prepareLayer(to_update, layer, idx);
        });
        to_update = new _this._resource({'tree': to_update});
        to_update.$update({action: _this._section}, function(result) {
            _this._successMessageHandler(_this._localize.getLocalizedString('Structure successful updated'));
        }, _this._errorMessageHandler);
    };

    this.return_dict['tree'] = _this.tree;
    this.return_dict['updateStructure'] = _this.updateStructure;
};

WMSSourceService = function(_section) {
    MapproxyBaseService.call(this, _section);
    var _this = this;

    this._addSourceURL = function(layer, sourceURL) {
        layer.sourceURL = sourceURL;
        if(angular.isDefined(layer.layers)) {
            angular.forEach(layer.layers, function(layer) {
                _this._addSourceURL(layer, sourceURL);
            });
        }
    };
    this.list = function() {
        var result = [];
        angular.forEach(_this._items, function(item) {
            var sourceURL = item.data.url;
            angular.forEach(item.data.layer.layers, function(layer) {
                _this._addSourceURL(layer, sourceURL)
            });
        });
        for(var key in _this._items) {
            result.push(_this._items[key]);
        }
        return result;
    };
    this._identifySource = function(url) {
        var source = false;
        angular.forEach(_this._items, function(_source) {
            if(_source.data.url == url) {
                source = _source;
            }
        });
        return source;
    };
    this._identifyLayer = function(layers, layerName) {
        var layer = false;
        angular.forEach(layers, function(_layer) {
            if(!layer) {
                if(_layer.name == layerName) {
                    layer = _layer;
                } else if(angular.isDefined(_layer.layers)) {
                    layer = _this._identifyLayer(_layer.layers, layerName);
                }
            }
        });
        return layer;
    };

    this.layerTitle = function(url, layerName) {
        var source = _this._identifySource(url);
        if(source) {
            var layer = _this._identifyLayer(source.data.layer.layers, layerName);
            if(layer) {
                return layer.title;
            }
        }
        return false;
    };

    this.coverage = function(url) {
        var source = _this._identifySource(url);
        if(source) {
            return source.data.layer.llbbox;
        }
        return false;
    };

    this.srs = function(url) {
        var source = _this._identifySource(url);
        if(source) {
            return source.data.layer.srs;
        }
        return false;
    };

    this.refresh = function(_item) {
        var item = new _this._resource(_item);
        _this._action = 'update';
        item.$update({action: _this._section, id: item._id}, function(result) {
            _this._items[result._id] = result;
            _this._last = result;
            _this._successMessageHandler(_this._localize.getLocalizedString('Successful updated'));
        }, _this._errorMessageHandler);
    };

    this.allURLs = function() {
        var result = [];
        angular.forEach(_this._items, function(wms) {
            result.push(wms.url);
        });
        return result;
    };

    this.return_dict['list'] = _this.list;
    this.return_dict['layerTitle'] = _this.layerTitle;
    this.return_dict['refresh'] = _this.refresh;
    this.return_dict['allURLs'] = _this.allURLs;
    this.return_dict['coverage'] = _this.coverage;
    this.return_dict['srs'] = _this.srs;
};

var layerModel = {
    'name': undefined,
    'title': undefined,
    'sources': [],
    'min_res': undefined,
    'max_res': undefined,
    'min_res_scale': undefined,
    'max_res_scale': undefined
};
var globalsModel = {
    'cache': {
        'meta_size': [],
        'meta_buffer': undefined
    },
    'image': {
        'resampling_method': undefined,
        'paletted': undefined
    }
};
var cacheModel = {
    'name': undefined,
    'sources': [],
    'grids': [],
    'format': undefined,
    'request_format': undefined
};
var gridModel = {
    'name': undefined,
    'srs': undefined,
    'bbox': [],
    'bbox_srs': undefined,
    'origin': undefined,
    'res': [],
    'scales': []
};
var sourceModel = {
    'name': undefined,
    'req': {
        'url': undefined,
        'layers': [],
        'transparent': undefined
    },
    'coverage': {
        'bbox': undefined,
        'srs': undefined
    },
    'supported_formats': []
};
var defaultsModel = {
    'dpi': undefined,
    'srs': []
};

var layerService = new MapproxyLayerService('layers', layerModel);
var globalsService = new MapproxyBaseService('globals', globalsModel);
var servicesService = new MapproxyBaseService('services');
var cacheService = new MapproxyBaseService('caches', cacheModel, [layerService]);
var gridService = new MapproxyBaseService('grids', gridModel, [cacheService]);
var sourceService = new MapproxyBaseService('sources', sourceModel, [cacheService, layerService]);
var wmsService = new WMSSourceService('wms_capabilities');
var defaultsService = new MapproxyBaseService('defaults', defaultsModel);

angular.module('mapproxy_gui.services', ['mapproxy_gui.resources']).

service('WMSSources', wmsService.return_func).
service('MapproxySources', sourceService.return_func).
service('MapproxyCaches', cacheService.return_func).
service('MapproxyGrids', gridService.return_func).
service('MapproxyLayers', layerService.return_func).
service('MapproxyGlobals', globalsService.return_func).
service('MapproxyServices', servicesService.return_func).
service('ProjectDefaults', defaultsService.return_func).

service('DataShareService', function($rootScope) {
    var _this = this;
    this._data = {};

    return {
        data: function(key, value) {
            if(angular.isDefined(value)) {
                _this._data[key] = value;
                $rootScope.$broadcast('dss.' + key);
            } else {
                if(angular.isDefined(_this._data[key])) {
                    return _this._data[key];
                } else {
                    return undefined;
                }
            }
        }
    }
});
<|endoftext|>


<commit_before>'use strict';

var nopt = require('nopt');
var parser = module.exports = {};

//  0       1           2          3
// ['node', __filename, <command>, [options] ]
parser.PARSE_ARGV_OFFSET = 2;

// cwd: {
//     short: 'c',
//     // '-c' is equivalent to '--cwd <default-short-value>'
//     short_pattern: ['--cwd', '<default-short-value>'],

//     // @type {mixed|function()} default value or generator
//     // - {function()}
//     value: process.cwd(),
//     type: node_path,
//     required: true
// }

// @param {Object} options
// - rules: {Object}
parser.parse = function(argv, options) {
    var parsed_rules = parser._parse_rules(options.rules);
    var parsed = parser._parse_argv(argv, parsed_rules, options.offset || parser.PARSE_ARGV_OFFSET);

    return parser._(parsed, parsed_rules.defaults);
};

// Clean the given data object according to the rules
// @param {Object} options
// - rules: {Object}
// - types: {Object} type definitions
parser.clean = function(data, options) {
    var parsed_rules = parser._parse_rules(options.rules);
    nopt.clean(data, parsed_rules.types, options.type_defs || parser.TYPES);

    return parser._(data, parsed_rules.defaults);
};

// {
//     String: {
//         type: String,

//         // function(data, key, value)
//         validate: validateString
//     }
// }

// So that we will not
parser.TYPES = Object.create(nopt.typeDefs);

parser.TYPES.html = {
    type: 'html',
    validate: function(data, key, value) {
        data[key] = String(value);
    }
};

parser.TYPES.String = {
    type: String,

    // If is normal string, strip html tags to prevent XSS attack
    validate: function (data, key, value) {
        if(value){
            data[key] = String(value).replace(/<[^>]+>/g, '');
        }
    }
};

parser._parse_rules = function(rules) {
    var opt_types = {};
    var short_hands = {};
    var default_values = {};

    var opts = Object.keys(rules);

    opts.forEach(function(key) {
        var option = rules[key];

        opt_types[key] = option.type;

        if(option.short){
            short_hands[option.short] = option.short_pattern || ('--' + key);
        }

        // options.value might be unreal
        if('value' in option){
            default_values[key] = option.value;
        }
    });

    return {
        types: opt_types,
        short: short_hands,
        defaults: default_values,
        options: opts
    };
};

// Parse `process.argv` or something like `process.argv` to data object
parser._parse_argv = function(argv, rules, offset) {
    return nopt(rules.types, rules.short, argv, offset);
};

// Apply `rule.value`
parser._ = function(args, defaults) {
    defaults = defaults || {};

    var key;
    var santitizer;

    var ret = {
        warnings: {},
        errors: {},
        infos: {},
        parsed: args
    };

    for(key in defaults){
        santitizer = defaults[key];

        if(santitizer instanceof Function){
            logger._reset();
            args[key] = santitizer(args[key], args, logger);
            // console.log( require('util').inspect(logger, {
            //     showHidden: true,
            //     depth: 10,
            //     colors: true
            // }) );

            logger._get(key, ret);

            if(logger._err()){
                ret.err = true;
                break;
            }

        // default value
        }else if( !(key in args) ){
            args[key] = santitizer;
        }
    }

    return ret;
};

function is_empty_object (object) {
    return !Object.keys(object).length;
}

var logger = {
    warn: function (data) {
        this.warnings.push(data);
    },

    error: function (data) {
        this.errors.push(data);
    },

    stop: function () {
        this.stopped = true;
    }
};

Object.defineProperties(logger, {
    _reset: {
        value: function () {
            this.warnings = [];
            this.errors = [];
            this.infos = [];
        }
    },

    warnings: {
        writable: true
    },

    errors: {
        writable: true
    },

    infos: {
        writable: true
    },

    _err: {
        value: function () {
            return !!this.errors.length;
        }
    },

    _get: {
        value: function (key, host) {
            this._(key, 'warnings', host);
            this._(key, 'errors', host);
            this._(key, 'infos', host);
        }
    },

    _: {
        value: function (key, type, host) {
            if(this[type].length){
                host[type][key] = this[type];
            }
        }
    }
});

<commit_msg>bug fixes<commit_after>'use strict';

var nopt = require('nopt');
var parser = module.exports = {};

//  0       1           2          3
// ['node', __filename, <command>, [options] ]
parser.PARSE_ARGV_OFFSET = 2;

// cwd: {
//     short: 'c',
//     // '-c' is equivalent to '--cwd <default-short-value>'
//     short_pattern: ['--cwd', '<default-short-value>'],

//     // @type {mixed|function()} default value or generator
//     // - {function()}
//     value: process.cwd(),
//     type: node_path,
//     required: true
// }

// @param {Object} options
// - rules: {Object}
parser.parse = function(argv, options) {
    var parsed_rules = parser._parse_rules(options.rules);
    var parsed = parser._parse_argv(argv, parsed_rules, options.offset || parser.PARSE_ARGV_OFFSET);

    return parser._(parsed, parsed_rules.defaults);
};

// Clean the given data object according to the rules
// @param {Object} options
// - rules: {Object}
// - types: {Object} type definitions
parser.clean = function(data, options) {
    var parsed_rules = parser._parse_rules(options.rules);
    nopt.clean(data, parsed_rules.types, options.type_defs || parser.TYPES);

    return parser._(data, parsed_rules.defaults);
};

// {
//     String: {
//         type: String,

//         // function(data, key, value)
//         validate: validateString
//     }
// }

// So that we will not
parser.TYPES = Object.create(nopt.typeDefs);

parser.TYPES.html = {
    type: 'html',
    validate: function(data, key, value) {
        data[key] = String(value);
    }
};

parser.TYPES.String = {
    type: String,

    // If is normal string, strip html tags to prevent XSS attack
    validate: function (data, key, value) {
        if(value){
            data[key] = String(value).replace(/<[^>]+>/g, '');
        }
    }
};

parser._parse_rules = function(rules) {
    var opt_types = {};
    var short_hands = {};
    var default_values = {};

    var opts = Object.keys(rules);

    opts.forEach(function(key) {
        var option = rules[key];

        opt_types[key] = option.type;

        if(option.short){
            short_hands[option.short] = option.short_pattern || ('--' + key);
        }

        // options.value might be unreal
        if('value' in option){
            default_values[key] = option.value;
        }
    });

    return {
        types: opt_types,
        short: short_hands,
        defaults: default_values,
        options: opts
    };
};

// Parse `process.argv` or something like `process.argv` to data object
parser._parse_argv = function(argv, rules, offset) {
    return nopt(rules.types, rules.short, argv, offset);
};

// Apply `rule.value`
parser._ = function(args, defaults) {
    defaults = defaults || {};

    var key;
    var santitizer;

    var ret = {
        warnings: {},
        errors: {},
        infos: {},
        parsed: args
    };

    for(key in defaults){
        santitizer = defaults[key];

        if(santitizer instanceof Function){
            logger._reset();
            args[key] = santitizer(args[key], args, logger);
            // console.log( require('util').inspect(logger, {
            //     showHidden: true,
            //     depth: 10,
            //     colors: true
            // }) );

            logger._get(key, ret);

            if(logger._err()){
                ret.err = true;
                break;
            }

        // default value
        }else if( !(key in args) ){
            args[key] = santitizer;
        }
    }

    return ret;
};

function is_empty_object (object) {
    return !Object.keys(object).length;
}

var logger = {
    warn: function (data) {
        this.warnings.push(data);
    },

    error: function (data) {
        this.errors.push(data);
    },

    info: function (data) {
        this.infos.push(data);
    }
};

Object.defineProperties(logger, {
    _reset: {
        value: function () {
            this.warnings = [];
            this.errors = [];
            this.infos = [];
        }
    },

    warnings: {
        writable: true
    },

    errors: {
        writable: true
    },

    infos: {
        writable: true
    },

    _err: {
        value: function () {
            return !!this.errors.length;
        }
    },

    _get: {
        value: function (key, host) {
            this._(key, 'warnings', host);
            this._(key, 'errors', host);
            this._(key, 'infos', host);
        }
    },

    _: {
        value: function (key, type, host) {
            if(this[type].length){
                host[type][key] = this[type];
            }
        }
    }
});

<|endoftext|>


<commit_before>describe('regression', function() {
    var uit = uitest.current;
    uit.url("../test/ui/fixtures/basic.html");

    describe('issue 8: Setting and returning hash', function() {
        it('should allow to change the hash without a reload', function() {
            uit.runs(function(window) {
                window.flag = true;
                window.location.hash = 'test';
                expect(window.location.hash).toBe('#test');
            });
            uit.runs(function(window) {
                expect(window.flag).toBe(true);
                expect(window.location.hash).toBe('#test');
            });
        });
    });
});<commit_msg>added regression spec for #7.<commit_after>describe('regression', function() {
    var uit = uitest.current,
        relPath = "../test/ui/fixtures/basic.html";

    describe('issue 8 and 9: Setting and returning hash', function() {
        it('should allow to change the hash without a reload', function() {
            uit.url(relPath);
            uit.runs(function(window) {
                window.flag = true;
                window.location.hash = 'test';
                expect(window.location.hash).toBe('#test');
            });
            uit.runs(function(window) {
                expect(window.flag).toBe(true);
                expect(window.location.hash).toBe('#test');
            });
        });
        it('should return "#/page1.html"', function() {
            uit.url( relPath + "#/page1.html");
            uit.runs(function(window) {
                expect(window.location.hash).toBe('#/page1.html');
            });
        });
    });
});<|endoftext|>