<commit_before>'use strict'

import React, {
  Component,
  View,
  PropTypes,
  TouchableWithoutFeedback,
  Animated
} from 'react-native'

import S from './Style.js'

export default class FlipCard extends Component {
  constructor (props) {
    super(props)
    this.state = {
      isFlipped: props.flipped,
      isFlipping: false,
      rotate: new Animated.Value(Number(props.flipped))
    }
  }
  _toggleCard () {
    this.setState({isFlipping: true})
    this._animation(!this.state.isFlipped)
  }
  _animation (isFlipped) {
    if (!this.timer) {
      this.timer = setTimeout(() => {
        this.setState({isFlipped: !this.state.isFlipped})
        this.timer = null
      }, 120)
    }
    Animated.spring(this.state.rotate,
      {
        toValue: Number(isFlipped),
        friction: this.props.friction
      }
    ).start((param) => {
      this.setState({isFlipping: false})
      this.props.onFlipped(this.state.isFlipped)
    })
  }
  render () {
    var c = this.props.children
    var transform = []
    var render_side = false

    if (this.props.flipHorizontal) {
      transform.push(
        {rotateY: this.state.rotate.interpolate({
          inputRange: [0, 1],
          outputRange: [ '0deg', '180deg' ]
        })}
      )
    }
    if (this.props.flipVertical) {
      transform.push(
        {rotateX: this.state.rotate.interpolate({
          inputRange: [0, 1],
          outputRange: [ '0deg', '180deg' ]
        })}
      )
    }

    if (this.state.isFlipped) {
      render_side = (
        <Back
          flipHorizontal={this.props.flipHorizontal}
          flipVertical={this.props.flipVertical}
        >
          {c[1]}
        </Back>
      )
    } else {
      render_side = (
        <Face>
          {c[0]}
        </Face>
      )
    }
    return (
      <TouchableWithoutFeedback
        onPress={this.props.clickable && this._toggleCard.bind(this)}
      >
        <Animated.View
          {...this.props}
          style={[S.flipCard,
          {transform: transform},
          this.props.style
          ]}
        >
          {render_side}
        </Animated.View>
      </TouchableWithoutFeedback>
    )
  }
}
FlipCard.propTypes = {
  flipped: PropTypes.bool,
  friction: PropTypes.number,
  flipHorizontal: PropTypes.bool,
  flipVertical: PropTypes.bool,
  clickable: PropTypes.bool,
  onFlipped: PropTypes.func,
  style: View.propTypes.style,
  children (props, propName, componentName) {
    const prop = props[propName]
    if (React.Children.count(prop) !== 2) {
      return new Error(
        '`' + componentName + '` ' +
        'should contain exactly two children. ' +
        'The first child represents the front of the card. ' +
        'The second child represents the back of the card.'
      )
    }
  }
}

FlipCard.defaultProps = {
  flipped: false,
  friction: 6,
  flipHorizontal: false,
  flipVertical: true,
  clickable: true,
  onFlipped: () => {}
}

export class Face extends Component {
  render () {
    return (
      <View style={[S.face]}>
        {this.props.children}
      </View>
    )
  }
}

Face.propTypes = {
  children (props, propName, componentName) {
  }
}

export class Back extends Component {
  render () {
    var transform = []
    if (this.props.flipHorizontal) {
      transform.push({skewY: '180deg'})
    }
    if (this.props.flipVertical) {
      transform.push({skewX: '180deg'})
    }

    return (
      <View style={[
        S.back,
        {transform: transform}
      ]}>
        {this.props.children}
      </View>
    )
  }
}

Back.defaultProps = {
  flipHorizontal: false,
  flipVertical: true
}

Back.propTypes = {
  flipHorizontal: PropTypes.bool,
  flipVertical: PropTypes.bool,
  children (props, propName, componentName) {
  }
}

<commit_msg>added a flip prop to make the card flip without clicking on it, when clickable prop is false<commit_after>'use strict'

import React, {
  Component,
  View,
  PropTypes,
  TouchableWithoutFeedback,
  Animated
} from 'react-native'

import S from './Style.js'

export default class FlipCard extends Component {
  constructor (props) {
    super(props)
    this.state = {
      isFlipped: props.flipped,
      isFlipping: false,
      rotate: new Animated.Value(Number(props.flipped))
    }
  }
  componentWillReceiveProps (nextProps) {
      if (!this.props.clickable && this.props.flip !== nextProps.flip) {
          this._toggleCard();
      }
  }
  _toggleCard () {
    this.setState({isFlipping: true})
    this._animation(!this.state.isFlipped)
  }
  _animation (isFlipped) {
    if (!this.timer) {
      this.timer = setTimeout(() => {
        this.setState({isFlipped: !this.state.isFlipped})
        this.timer = null
      }, 120)
    }
    Animated.spring(this.state.rotate,
      {
        toValue: Number(isFlipped),
        friction: this.props.friction
      }
    ).start((param) => {
      this.setState({isFlipping: false})
      this.props.onFlipped(this.state.isFlipped)
    })
  }
  render () {
    var c = this.props.children
    var transform = []
    var render_side = false

    if (this.props.flipHorizontal) {
      transform.push(
        {rotateY: this.state.rotate.interpolate({
          inputRange: [0, 1],
          outputRange: [ '0deg', '180deg' ]
        })}
      )
    }
    if (this.props.flipVertical) {
      transform.push(
        {rotateX: this.state.rotate.interpolate({
          inputRange: [0, 1],
          outputRange: [ '0deg', '180deg' ]
        })}
      )
    }

    if (this.state.isFlipped) {
      render_side = (
        <Back
          flipHorizontal={this.props.flipHorizontal}
          flipVertical={this.props.flipVertical}
        >
          {c[1]}
        </Back>
      )
    } else {
      render_side = (
        <Face>
          {c[0]}
        </Face>
      )
    }
    return (
      <TouchableWithoutFeedback
        onPress={() => {
            if (this.props.clickable) {
                this._toggleCard();
            }
        }}
      >
        <Animated.View
          {...this.props}
          style={[S.flipCard,
          {transform: transform},
          this.props.style
          ]}
        >
          {render_side}
        </Animated.View>
      </TouchableWithoutFeedback>
    )
  }
}
FlipCard.propTypes = {
  flipped: PropTypes.bool,
  friction: PropTypes.number,
  flipHorizontal: PropTypes.bool,
  flipVertical: PropTypes.bool,
  clickable: PropTypes.bool,
  onFlipped: PropTypes.func,
  style: View.propTypes.style,
  children (props, propName, componentName) {
    const prop = props[propName]
    if (React.Children.count(prop) !== 2) {
      return new Error(
        '`' + componentName + '` ' +
        'should contain exactly two children. ' +
        'The first child represents the front of the card. ' +
        'The second child represents the back of the card.'
      )
    }
  }
}

FlipCard.defaultProps = {
  flipped: false,
  friction: 6,
  flipHorizontal: false,
  flipVertical: true,
  clickable: true,
  onFlipped: () => {}
}

export class Face extends Component {
  render () {
    return (
      <View style={[S.face]}>
        {this.props.children}
      </View>
    )
  }
}

Face.propTypes = {
  children (props, propName, componentName) {
  }
}

export class Back extends Component {
  render () {
    var transform = []
    if (this.props.flipHorizontal) {
      transform.push({skewY: '180deg'})
    }
    if (this.props.flipVertical) {
      transform.push({skewX: '180deg'})
    }

    return (
      <View style={[
        S.back,
        {transform: transform}
      ]}>
        {this.props.children}
      </View>
    )
  }
}

Back.defaultProps = {
  flipHorizontal: false,
  flipVertical: true
}

Back.propTypes = {
  flipHorizontal: PropTypes.bool,
  flipVertical: PropTypes.bool,
  children (props, propName, componentName) {
  }
}
<|endoftext|>


<commit_before>describe("About Expects", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should expect true", function() {
    expect(false).toBeTruthy(); //This should be true
  });

  //To understand reality, we must compare our expectations against reality.
  it("should expect equality", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

	  expect(actualValue === expectedValue).toBeTruthy();
  });

  //Some ways of asserting equality are better than others.
  it("should assert equality a better way", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

  // toEqual() compares using common sense equality.
	  expect(actualValue).toEqual(expectedValue);
  });

  //Sometimes you need to be really exact about what you "type".
  it("should assert equality with ===", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = (1 + 1).toString();

  // toBe() will always use === to compare.
	  expect(actualValue).toBe(expectedValue);
  });

  //Sometimes we will ask you to fill in the values.
  it("should have filled in values", function () {
	  expect(1 + 1).toEqual(FILL_ME_IN);
  });
});
<commit_msg>Completed "About Expects" koans<commit_after>describe("About Expects", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should expect true", function() {
    expect(true).toBeTruthy(); //This should be true
  });

  //To understand reality, we must compare our expectations against reality.
  it("should expect equality", function () {
	  var expectedValue = 2;
	  var actualValue = 1 + 1;

	  expect(actualValue === expectedValue).toBeTruthy();
  });

  //Some ways of asserting equality are better than others.
  it("should assert equality a better way", function () {
	  var expectedValue = 1 + 1;
	  var actualValue = 1 + 1;

  // toEqual() compares using common sense equality.
	  expect(actualValue).toEqual(expectedValue);
  });

  //Sometimes you need to be really exact about what you "type".
  it("should assert equality with ===", function () {
	  var expectedValue = (1 + 1).toString();;
	  var actualValue = (1 + 1).toString();

  // toBe() will always use === to compare.
	  expect(actualValue).toBe(expectedValue);
  });

  //Sometimes we will ask you to fill in the values.
  it("should have filled in values", function () {
	  expect(1 + 1).toEqual(1 + 1);
  });
});
<|endoftext|>


<commit_before>// COLLECTION SECURTY ARGUMENTS
PERMIT_LIST_ALL = [ 'insert', 'update', 'remove' ];

// SECUR METHODS FUNCTION NAMES
METHODS = ['start', 'stop', 'destroy'];

USERS_FIELDS = {
  fields: {
    'username': 1,
    'profile.fullname': 1,
    'profile.avatarUrl': 1,
    'roles': 1
  }
};

// if application member list search found then return.
Security.defineMethod("ifMemberAdmin", {
  fetch: [],
  transform: null,
  deny: function (type, arg, userId, doc, fields, modifier) {

    // IF UPDATED FIELD MEMBER THEN
    if (_.contains(fields, 'memberIds')) {

      // NOT ADMIN THEN DENY.
      if (!Roles.userIsInRole(userId, 'admin')) {
        return true;
      }

      // IF MODIFIER $push THEN
      if (_.has(modifier, '$push')) {
        const $userId = modifier.$push.memberIds;

        // IF MEMBERS THEN DENY
        if (_.contains(doc.memberIds, $userId)) {
          return true;
        }

        // IF REAL USER?
        if (_.isUndefined(Users.findOne($userId))) {
          return true;
        }
      }
    }
  }
});
<commit_msg>ifMemberAdmin define method else admin role secur.<commit_after>// COLLECTION SECURTY ARGUMENTS
PERMIT_LIST_ALL = [ 'insert', 'update', 'remove' ];

// SECUR METHODS FUNCTION NAMES
METHODS = ['start', 'stop', 'destroy'];

// USERS FIELDS PUBLISH
USERS_FIELDS = {
  fields: {
    'username': 1,
    'profile.fullname': 1,
    'profile.avatarUrl': 1,
    'roles': 1
  }
};

// if application member list search found then return.
Security.defineMethod("ifMemberAdmin", {
  fetch: [],
  transform: null,
  deny: function (type, arg, userId, doc, fields, modifier) {

    // IF UPDATED FIELD MEMBER THEN
    if (_.contains(fields, 'memberIds')) {

      // NOT ADMIN THEN DENY.
      if (!Roles.userIsInRole(userId, 'admin')) {
        return true;
      }

      // IF MODIFIER $push THEN
      if (_.has(modifier, '$push')) {
        const $userId = modifier.$push.memberIds;

        // IF MEMBERS THEN DENY
        if (_.contains(doc.memberIds, $userId)) {
          return true;
        }

        // IF REAL USER?
        if (_.isUndefined(Users.findOne($userId))) {
          return true;
        }
      }
    }

    // ELSE MEMBERIDS NOT ADMIN THEN DENY.
    if (!Roles.userIsInRole(userId, 'admin')) {
      return true;
    }
  }
});
<|endoftext|>


<commit_before>var Map = require('./Map');

function MultiMap() {
	this._map = new Map();
}
MultiMap.prototype = {
	'getValues': function getValues(key) {
		var val;
		if (arguments.length === 0) {
			// return all values for all keys.
			val = [];
			this._map.forEach(function(values) {
				val.push.apply(val, values);
			});
		} else {
			// return all the values for the provided key.
			val = this._map.get(key);
			if (val === undefined) {
				val = [];
				this._map.set(key, val);
			}
		}
		return val;
	},
	'clear': function clear() {
		this._map = new Map();
	},
	'add': function add(key, value) {
		this.getValues(key).push(value);
	},
	'filter': function filter(key, filterFunction) {
		if (this._map.has(key) === false) { return; }
		var values = this._map.get(key).filter(filterFunction);

		if (values.length === 0) {
			this._map['delete'](key);
		} else {
			this._map.set(key, values);
		}
	},
	'filterAll': function(filterFunction) {
		this._map.forEach(function(values, key, map) {
			var newValues = values.filter(filterFunction);
			if (newValues.length === 0) {
				map['delete'](key);
			} else {
				map.set(key, newValues);
			}
		});
	},
	'removeLastMatch': function removeLast(key, matchFunction) {
		if (this._map.has(key) === false) { return false; }
		var values = this._map.get(key);
		for (var i = values.length - 1; i >= 0; --i) {
			if (matchFunction(values[i])) {
				values.splice(i, 1);
				return true;
			}
		}
		return false;
	},
	'hasAny': function has(key) {
		return this._map.has(key);
	},
	'delete': function del(key) {
		this._map['delete'](key);
	}
};

module.exports = MultiMap;<commit_msg>The latest webkit supports ES6 maps, but doesn’t seem to pass the third ‘map’ parameter back to a forEach function.<commit_after>var Map = require('./Map');

function MultiMap() {
	this._map = new Map();
}
MultiMap.prototype = {
	'getValues': function getValues(key) {
		var val;
		if (arguments.length === 0) {
			// return all values for all keys.
			val = [];
			this._map.forEach(function(values) {
				val.push.apply(val, values);
			});
		} else {
			// return all the values for the provided key.
			val = this._map.get(key);
			if (val === undefined) {
				val = [];
				this._map.set(key, val);
			}
		}
		return val;
	},
	'clear': function clear() {
		this._map = new Map();
	},
	'add': function add(key, value) {
		this.getValues(key).push(value);
	},
	'filter': function filter(key, filterFunction) {
		if (this._map.has(key) === false) { return; }
		var values = this._map.get(key).filter(filterFunction);

		if (values.length === 0) {
			this._map['delete'](key);
		} else {
			this._map.set(key, values);
		}
	},
	'filterAll': function(filterFunction) {
		var map = this._map;
		this._map.forEach(function(values, key) {
			var newValues = values.filter(filterFunction);
			if (newValues.length === 0) {
				map['delete'](key);
			} else {
				map.set(key, newValues);
			}
		});
	},
	'removeLastMatch': function removeLast(key, matchFunction) {
		if (this._map.has(key) === false) { return false; }
		var values = this._map.get(key);
		for (var i = values.length - 1; i >= 0; --i) {
			if (matchFunction(values[i])) {
				values.splice(i, 1);
				return true;
			}
		}
		return false;
	},
	'hasAny': function has(key) {
		return this._map.has(key);
	},
	'delete': function del(key) {
		this._map['delete'](key);
	}
};

module.exports = MultiMap;<|endoftext|>


<commit_before>describe("About Objects", function () {

  describe("Properties", function () {
    var megalomaniac;

    beforeEach(function () {
       megalomaniac = {  mastermind: "Joker", henchwoman: "Harley" };
    });

    it("should confirm objects are collections of properties", function () {
      expect(megalomaniac.mastermind).toBe('Joker');
    });

    it("should confirm that properties are case sensitive", function () {
      expect(megalomaniac.henchwoman).toBe('Harley');
      expect(megalomaniac.henchWoman).toBe(undefined);
    });
  });

  it("should know properties that are functions act like methods", function () {
    var megalomaniac = {
      mastermind : "Brain",
      henchman: "Pinky",
      battleCry: function (noOfBrains) {
        return "They are " + this.henchman + " and the" +
          Array(noOfBrains + 1).join(" " + this.mastermind);
      }
    };

    var battleCry = megalomaniac.battleCry(4);
    expect("They are Pinky and the Brain Brain Brain Brain").toMatch(battleCry);
  });

  it("should confirm that when a function is attached to an object, 'this' refers to the object", function () {
    var currentDate = new Date();
    var currentYear = (currentDate.getFullYear());
    var megalomaniac = {
      mastermind: "James Wood",
      henchman: "Adam West",
      birthYear: 1970,
      calculateAge: function () {
        return currentYear - this.birthYear;
      }
    };

    expect(currentYear).toBe(2015);
    expect(megalomaniac.calculateAge()).toBe(45);
  });

  describe("'in' keyword", function () {
    var megalomaniac;
    beforeEach(function () {
      megalomaniac = {
        mastermind: "The Monarch",
        henchwoman: "Dr Girlfriend",
        theBomb: true
      };
    });

    it("should have the bomb", function () {

      var hasBomb = "theBomb" in megalomaniac;

      expect(hasBomb).toBe(FILL_ME_IN);
    });

    it("should not have the detonator however", function () {

      var hasDetonator = "theDetonator" in megalomaniac;

      expect(hasDetonator).toBe(FILL_ME_IN);
    });
  });

  it("should know that properties can be added and deleted", function () {
    var megalomaniac = { mastermind : "Agent Smith", henchman: "Agent Smith" };

    expect("secretary" in megalomaniac).toBe(FILL_ME_IN);

    megalomaniac.secretary = "Agent Smith";
    expect("secretary" in megalomaniac).toBe(FILL_ME_IN);

    delete megalomaniac.henchman;
    expect("henchman" in megalomaniac).toBe(FILL_ME_IN);
  });

  it("should use prototype to add to all objects", function () {
      function Circle(radius)
      {
        this.radius = radius;
      }

      var simpleCircle = new Circle(10);
      var colouredCircle = new Circle(5);
      colouredCircle.colour = "red";

      expect(simpleCircle.colour).toBe(FILL_ME_IN);
      expect(colouredCircle.colour).toBe(FILL_ME_IN);

      Circle.prototype.describe = function () {
        return "This circle has a radius of: " + this.radius;
      };

      expect(simpleCircle.describe()).toBe(FILL_ME_IN);
      expect(colouredCircle.describe()).toBe(FILL_ME_IN);
  });
});
<commit_msg>Solve the 23rd koan<commit_after>describe("About Objects", function () {

  describe("Properties", function () {
    var megalomaniac;

    beforeEach(function () {
       megalomaniac = {  mastermind: "Joker", henchwoman: "Harley" };
    });

    it("should confirm objects are collections of properties", function () {
      expect(megalomaniac.mastermind).toBe('Joker');
    });

    it("should confirm that properties are case sensitive", function () {
      expect(megalomaniac.henchwoman).toBe('Harley');
      expect(megalomaniac.henchWoman).toBe(undefined);
    });
  });

  it("should know properties that are functions act like methods", function () {
    var megalomaniac = {
      mastermind : "Brain",
      henchman: "Pinky",
      battleCry: function (noOfBrains) {
        return "They are " + this.henchman + " and the" +
          Array(noOfBrains + 1).join(" " + this.mastermind);
      }
    };

    var battleCry = megalomaniac.battleCry(4);
    expect("They are Pinky and the Brain Brain Brain Brain").toMatch(battleCry);
  });

  it("should confirm that when a function is attached to an object, 'this' refers to the object", function () {
    var currentDate = new Date();
    var currentYear = (currentDate.getFullYear());
    var megalomaniac = {
      mastermind: "James Wood",
      henchman: "Adam West",
      birthYear: 1970,
      calculateAge: function () {
        return currentYear - this.birthYear;
      }
    };

    expect(currentYear).toBe(2015);
    expect(megalomaniac.calculateAge()).toBe(45);
  });

  describe("'in' keyword", function () {
    var megalomaniac;
    beforeEach(function () {
      megalomaniac = {
        mastermind: "The Monarch",
        henchwoman: "Dr Girlfriend",
        theBomb: true
      };
    });

    it("should have the bomb", function () {

      var hasBomb = "theBomb" in megalomaniac;

      expect(hasBomb).toBe(true);
    });

    it("should not have the detonator however", function () {

      var hasDetonator = "theDetonator" in megalomaniac;

      expect(hasDetonator).toBe(FILL_ME_IN);
    });
  });

  it("should know that properties can be added and deleted", function () {
    var megalomaniac = { mastermind : "Agent Smith", henchman: "Agent Smith" };

    expect("secretary" in megalomaniac).toBe(FILL_ME_IN);

    megalomaniac.secretary = "Agent Smith";
    expect("secretary" in megalomaniac).toBe(FILL_ME_IN);

    delete megalomaniac.henchman;
    expect("henchman" in megalomaniac).toBe(FILL_ME_IN);
  });

  it("should use prototype to add to all objects", function () {
      function Circle(radius)
      {
        this.radius = radius;
      }

      var simpleCircle = new Circle(10);
      var colouredCircle = new Circle(5);
      colouredCircle.colour = "red";

      expect(simpleCircle.colour).toBe(FILL_ME_IN);
      expect(colouredCircle.colour).toBe(FILL_ME_IN);

      Circle.prototype.describe = function () {
        return "This circle has a radius of: " + this.radius;
      };

      expect(simpleCircle.describe()).toBe(FILL_ME_IN);
      expect(colouredCircle.describe()).toBe(FILL_ME_IN);
  });
});
<|endoftext|>


<commit_before>describe("About Objects", function () {

  describe("Properties", function () {
    var megalomaniac;

    beforeEach(function () {
       megalomaniac = {  mastermind: "Joker", henchwoman: "Harley" };
    });

    it("should confirm objects are collections of properties", function () {
      expect(megalomaniac.mastermind).toBe(FILL_ME_IN);
    });

    it("should confirm that properties are case sensitive", function () {
      expect(megalomaniac.henchwoman).toBe(FILL_ME_IN);
      expect(megalomaniac.henchWoman).toBe(FILL_ME_IN);
    });
  });

  it("should know properties that are functions act like methods", function () {
    var megalomaniac = {
      mastermind : "Brain",
      henchman: "Pinky",
      battleCry: function (noOfBrains) {
        return "They are " + this.henchman + " and the" +
          Array(noOfBrains + 1).join(" " + this.mastermind);
      }
    };

    var battleCry = megalomaniac.battleCry(4);
    expect(FILL_ME_IN).toMatch(battleCry);
  });

  it("should confirm that when a function is attached to an object, 'this' refers to the object", function () {
    var currentDate = new Date();
    var currentYear = (currentDate.getFullYear());
    var megalomaniac = {
      mastermind: "James Wood",
      henchman: "Adam West",
      birthYear: 1970,
      calculateAge: function () {
        return currentYear - this.birthYear;
      }
    };

    expect(currentYear).toBe(FILL_ME_IN);
    expect(megalomaniac.calculateAge()).toBe(FILL_ME_IN);
  });

  describe("'in' keyword", function () {
    var megalomaniac;
    beforeEach(function () {
      megalomaniac = {
        mastermind: "The Monarch",
        henchwoman: "Dr Girlfriend",
        theBomb: true
      };
    });

    it("should have the bomb", function () {

      var hasBomb = "theBomb" in megalomaniac;

      expect(hasBomb).toBe(FILL_ME_IN);
    });

    it("should not have the detonator however", function () {

      var hasDetonator = "theDetonator" in megalomaniac;

      expect(hasDetonator).toBe(FILL_ME_IN);
    });
  });

  it("should know that properties can be added and deleted", function () {
    var megalomaniac = { mastermind : "Agent Smith", henchman: "Agent Smith" };

    expect("secretary" in megalomaniac).toBe(FILL_ME_IN);

    megalomaniac.secretary = "Agent Smith";
    expect("secretary" in megalomaniac).toBe(FILL_ME_IN);

    delete megalomaniac.henchman;
    expect("henchman" in megalomaniac).toBe(FILL_ME_IN);
  });

  it("should use prototype to add to all objects", function () {
      function Circle(radius)
      {
        this.radius = radius;
      }

      var simpleCircle = new Circle(10);
      var colouredCircle = new Circle(5);
      colouredCircle.colour = "red";

      expect(simpleCircle.colour).toBe(FILL_ME_IN);
      expect(colouredCircle.colour).toBe(FILL_ME_IN);

      Circle.prototype.describe = function () {
        return "This circle has a radius of: " + this.radius;
      };

      expect(simpleCircle.describe()).toBe(FILL_ME_IN);
      expect(colouredCircle.describe()).toBe(FILL_ME_IN);
  });
});
<commit_msg>About Objects<commit_after>describe("clear", function () {

  describe("Properties", function () {
    var megalomaniac;

    beforeEach(function () {
       megalomaniac = {  mastermind: "Joker", henchwoman: "Harley" };
    });

    it("should confirm objects are collections of properties", function () {
      expect(megalomaniac.mastermind).toBe('Joker');
    });

    it("should confirm that properties are case sensitive", function () {
      expect(megalomaniac.henchwoman).toBe('Harley');
      expect(megalomaniac.henchWoman).toBe(undefined);
    });
  });

  it("should know properties that are functions act like methods", function () {
    var megalomaniac = {
      mastermind : "Brain",
      henchman: "Pinky",
      battleCry: function (noOfBrains) {
        return "They are " + this.henchman + " and the" +
          Array(noOfBrains + 1).join(" " + this.mastermind);
      }
    };

    var battleCry = megalomaniac.battleCry(4);
    expect('They are Pinky and the Brain Brain Brain Brain').toMatch(battleCry);
  });

  it("should confirm that when a function is attached to an object, 'this' refers to the object", function () {
    var currentDate = new Date();
    var currentYear = (currentDate.getFullYear());
    var megalomaniac = {
      mastermind: "James Wood",
      henchman: "Adam West",
      birthYear: 1970,
      calculateAge: function () {
        return currentYear - this.birthYear;
      }
    };

    expect(currentYear).toBe(2015);
    expect(megalomaniac.calculateAge()).toBe(45);
  });

  describe("'in' keyword", function () {
    var megalomaniac;
    beforeEach(function () {
      megalomaniac = {
        mastermind: "The Monarch",
        henchwoman: "Dr Girlfriend",
        theBomb: true
      };
    });

    it("should have the bomb", function () {

      var hasBomb = "theBomb" in megalomaniac;

      expect(hasBomb).toBe(true);
    });

    it("should not have the detonator however", function () {

      var hasDetonator = "theDetonator" in megalomaniac;

      expect(hasDetonator).toBe(false);
    });
  });

  it("should know that properties can be added and deleted", function () {
    var megalomaniac = { mastermind : "Agent Smith", henchman: "Agent Smith" };

    expect("secretary" in megalomaniac).toBe(false);

    megalomaniac.secretary = "Agent Smith";
    expect("secretary" in megalomaniac).toBe(true);

    delete megalomaniac.henchman;
    expect("henchman" in megalomaniac).toBe(false);
  });

  it("should use prototype to add to all objects", function () {
      function Circle(radius)
      {
        this.radius = radius;
      }

      var simpleCircle = new Circle(10);
      var colouredCircle = new Circle(5);
      colouredCircle.colour = "red";

      expect(simpleCircle.colour).toBe(undefined);
      expect(colouredCircle.colour).toBe('red');

      Circle.prototype.describe = function () {
        return "This circle has a radius of: " + this.radius;
      };

      expect(simpleCircle.describe()).toBe('This circle has a radius of: 10');
      expect(colouredCircle.describe()).toBe('This circle has a radius of: 5');
  });
});
<|endoftext|>


<commit_before>describe("About Objects", function () {

  describe("Properties", function () {
    var meglomaniac;

    beforeEach(function () {
       meglomaniac = {  mastermind: "Joker", henchwoman: "Harley" };
    });

    it("should confirm objects are collections of properties", function () {
      expect(meglomaniac.mastermind).toBe('Joker');
    });

    it("should confirm that properties are case sensitive", function () {
      expect(meglomaniac.henchwoman).toBe('Harley');
      expect(meglomaniac.henchWoman).toBe(undefined);
    });
  });

  it("should know properties that are functions act like methods", function () {
    var meglomaniac = {
      mastermind : "Brain",
      henchman: "Pinky",
      battleCry: function (noOfBrains) {
        return "They are " + this.henchman + " and the" +
          Array(noOfBrains + 1).join(" " + this.mastermind);
      }
    };

    var battleCry = meglomaniac.battleCry(4);
    expect(FILL_ME_IN).toMatch(battleCry);
  });

  it("should confirm that when a function is attached to an object, 'this' refers to the object", function () {
    var currentDate = new Date()
    var currentYear = (currentDate.getFullYear());
    var meglomaniac = {
      mastermind: "James Wood",
      henchman: "Adam West",
      birthYear: 1970,
      calculateAge: function () {
        return currentYear - this.birthYear;
      }
    };

    expect(currentYear).toBe(FILL_ME_IN);
    expect(meglomaniac.calculateAge()).toBe(FILL_ME_IN);
  });

  describe("'in' keyword", function () {
    var meglomaniac;
    beforeEach(function () {
      meglomaniac = {
        mastermind: "The Monarch",
        henchwoman: "Dr Girlfriend",
        theBomb: true
      };
    });

    it("should have the bomb", function () {

      var hasBomb = "theBomb" in meglomaniac;

      expect(hasBomb).toBe(FILL_ME_IN);
    });

    it("should not have the detonator however", function () {

      var hasDetonator = "theDetonator" in meglomaniac;

      expect(hasDetonator).toBe(FILL_ME_IN);
    });
  });

  it("should know that properties can be added and deleted", function () {
    var meglomaniac = { mastermind : "Agent Smith", henchman: "Agent Smith" };

    expect("secretary" in meglomaniac).toBe(FILL_ME_IN);

    meglomaniac.secretary = "Agent Smith";
    expect("secretary" in meglomaniac).toBe(FILL_ME_IN);

    delete meglomaniac.henchman;
    expect("henchman" in meglomaniac).toBe(FILL_ME_IN);
  });

  it("should use prototype to add to all objects", function () {
    function Circle(radius)
    {
      this.radius = radius;
    }

    var simpleCircle = new Circle(10);
    var colouredCircle = new Circle(5);
    colouredCircle.colour = "red";

    expect(simpleCircle.colour).toBe(FILL_ME_IN);
    expect(colouredCircle.colour).toBe(FILL_ME_IN);

    Circle.prototype.describe = function () {
      return "This circle has a radius of: " + this.radius;
    };

    expect(simpleCircle.describe()).toBe(FILL_ME_IN);
    expect(colouredCircle.describe()).toBe(FILL_ME_IN);
  });
});
<commit_msg>Completed the "should know properties that are functions act like methods" Koan of AboutObjects.<commit_after>describe("About Objects", function () {

  describe("Properties", function () {
    var meglomaniac;

    beforeEach(function () {
       meglomaniac = {  mastermind: "Joker", henchwoman: "Harley" };
    });

    it("should confirm objects are collections of properties", function () {
      expect(meglomaniac.mastermind).toBe('Joker');
    });

    it("should confirm that properties are case sensitive", function () {
      expect(meglomaniac.henchwoman).toBe('Harley');
      expect(meglomaniac.henchWoman).toBe(undefined);
    });
  });

  it("should know properties that are functions act like methods", function () {
    var meglomaniac = {
      mastermind : "Brain",
      henchman: "Pinky",
      battleCry: function (noOfBrains) {
        return "They are " + this.henchman + " and the" +
          Array(noOfBrains + 1).join(" " + this.mastermind);
      }
    };

    var battleCry = meglomaniac.battleCry(4);
    expect('They are Pinky and the Brain Brain Brain Brain Brain').toMatch(battleCry);
  });

  it("should confirm that when a function is attached to an object, 'this' refers to the object", function () {
    var currentDate = new Date()
    var currentYear = (currentDate.getFullYear());
    var meglomaniac = {
      mastermind: "James Wood",
      henchman: "Adam West",
      birthYear: 1970,
      calculateAge: function () {
        return currentYear - this.birthYear;
      }
    };

    expect(currentYear).toBe(FILL_ME_IN);
    expect(meglomaniac.calculateAge()).toBe(FILL_ME_IN);
  });

  describe("'in' keyword", function () {
    var meglomaniac;
    beforeEach(function () {
      meglomaniac = {
        mastermind: "The Monarch",
        henchwoman: "Dr Girlfriend",
        theBomb: true
      };
    });

    it("should have the bomb", function () {

      var hasBomb = "theBomb" in meglomaniac;

      expect(hasBomb).toBe(FILL_ME_IN);
    });

    it("should not have the detonator however", function () {

      var hasDetonator = "theDetonator" in meglomaniac;

      expect(hasDetonator).toBe(FILL_ME_IN);
    });
  });

  it("should know that properties can be added and deleted", function () {
    var meglomaniac = { mastermind : "Agent Smith", henchman: "Agent Smith" };

    expect("secretary" in meglomaniac).toBe(FILL_ME_IN);

    meglomaniac.secretary = "Agent Smith";
    expect("secretary" in meglomaniac).toBe(FILL_ME_IN);

    delete meglomaniac.henchman;
    expect("henchman" in meglomaniac).toBe(FILL_ME_IN);
  });

  it("should use prototype to add to all objects", function () {
    function Circle(radius)
    {
      this.radius = radius;
    }

    var simpleCircle = new Circle(10);
    var colouredCircle = new Circle(5);
    colouredCircle.colour = "red";

    expect(simpleCircle.colour).toBe(FILL_ME_IN);
    expect(colouredCircle.colour).toBe(FILL_ME_IN);

    Circle.prototype.describe = function () {
      return "This circle has a radius of: " + this.radius;
    };

    expect(simpleCircle.describe()).toBe(FILL_ME_IN);
    expect(colouredCircle.describe()).toBe(FILL_ME_IN);
  });
});
<|endoftext|>


<commit_before>describe("About Objects", function () {

  describe("Properties", function () {
    var meglomaniac;

    beforeEach(function () {
       meglomaniac = {  mastermind: "Joker", henchwoman: "Harley" };
    });

    it("should confirm objects are collections of properties", function () {
      expect(meglomaniac.mastermind).toBe("Joker");
    });

    it("should confirm that properties are case sensitive", function () {
      expect(meglomaniac.henchwoman).toBe("Harley");
      expect(meglomaniac.henchWoman).toBe(undefined);
    });
  });

  it("should know properties that are functions act like methods", function () {
    var meglomaniac = {
      mastermind : "Brain",
      henchman: "Pinky",
      battleCry: function (noOfBrains) {
        return "They are " + this.henchman + " and the" +
          Array(noOfBrains + 1).join(" " + this.mastermind);
      }
    };

    var battleCry = meglomaniac.battleCry(4);
    expect("They are Pinky and the Brain Brain Brain Brain Brain").toMatch(battleCry);
  });

  it("should confirm that when a function is attached to an object, 'this' refers to the object", function () {
    var currentDate = new Date()
    var currentYear = (currentDate.getFullYear());
    var meglomaniac = {
      mastermind: "James Wood",
      henchman: "Adam West",
      birthYear: 1970,
      calculateAge: function () {
        return currentYear - this.birthYear;
      }
    };

    expect(currentYear).toBe(2015);
    expect(meglomaniac.calculateAge()).toBe(45);
  });

  describe("'in' keyword", function () {
    var meglomaniac;
    beforeEach(function () {
      meglomaniac = {
        mastermind: "The Monarch",
        henchwoman: "Dr Girlfriend",
        theBomb: true
      };
    });

    it("should have the bomb", function () {

      var hasBomb = "theBomb" in meglomaniac;

      expect(hasBomb).toBe(true);
    });

    it("should not have the detonator however", function () {

      var hasDetonator = "theDetonator" in meglomaniac;

      expect(hasDetonator).toBe(false);
    });
  });

  it("should know that properties can be added and deleted", function () {
    var meglomaniac = { mastermind : "Agent Smith", henchman: "Agent Smith" };

    expect("secretary" in meglomaniac).toBe(false);

    meglomaniac.secretary = "Agent Smith";
    expect("secretary" in meglomaniac).toBe(true);

    delete meglomaniac.henchman;
    expect("henchman" in meglomaniac).toBe(false);
  });

  it("should use prototype to add to all objects", function () {
    function Circle(radius)
    {
      this.radius = radius;
    }

    var simpleCircle = new Circle(10);
    var colouredCircle = new Circle(5);
    colouredCircle.colour = "red";

    expect(simpleCircle.colour).toBe(FILL_ME_IN);
    expect(colouredCircle.colour).toBe(FILL_ME_IN);

    Circle.prototype.describe = function () {
      return "This circle has a radius of: " + this.radius;
    };

    expect(simpleCircle.describe()).toBe(FILL_ME_IN);
    expect(colouredCircle.describe()).toBe(FILL_ME_IN);
  });
});
<commit_msg>AboutObjects - Fixed using prototype to add to all objects<commit_after>describe("About Objects", function () {

  describe("Properties", function () {
    var meglomaniac;

    beforeEach(function () {
       meglomaniac = {  mastermind: "Joker", henchwoman: "Harley" };
    });

    it("should confirm objects are collections of properties", function () {
      expect(meglomaniac.mastermind).toBe("Joker");
    });

    it("should confirm that properties are case sensitive", function () {
      expect(meglomaniac.henchwoman).toBe("Harley");
      expect(meglomaniac.henchWoman).toBe(undefined);
    });
  });

  it("should know properties that are functions act like methods", function () {
    var meglomaniac = {
      mastermind : "Brain",
      henchman: "Pinky",
      battleCry: function (noOfBrains) {
        return "They are " + this.henchman + " and the" +
          Array(noOfBrains + 1).join(" " + this.mastermind);
      }
    };

    var battleCry = meglomaniac.battleCry(4);
    expect("They are Pinky and the Brain Brain Brain Brain Brain").toMatch(battleCry);
  });

  it("should confirm that when a function is attached to an object, 'this' refers to the object", function () {
    var currentDate = new Date()
    var currentYear = (currentDate.getFullYear());
    var meglomaniac = {
      mastermind: "James Wood",
      henchman: "Adam West",
      birthYear: 1970,
      calculateAge: function () {
        return currentYear - this.birthYear;
      }
    };

    expect(currentYear).toBe(2015);
    expect(meglomaniac.calculateAge()).toBe(45);
  });

  describe("'in' keyword", function () {
    var meglomaniac;
    beforeEach(function () {
      meglomaniac = {
        mastermind: "The Monarch",
        henchwoman: "Dr Girlfriend",
        theBomb: true
      };
    });

    it("should have the bomb", function () {

      var hasBomb = "theBomb" in meglomaniac;

      expect(hasBomb).toBe(true);
    });

    it("should not have the detonator however", function () {

      var hasDetonator = "theDetonator" in meglomaniac;

      expect(hasDetonator).toBe(false);
    });
  });

  it("should know that properties can be added and deleted", function () {
    var meglomaniac = { mastermind : "Agent Smith", henchman: "Agent Smith" };

    expect("secretary" in meglomaniac).toBe(false);

    meglomaniac.secretary = "Agent Smith";
    expect("secretary" in meglomaniac).toBe(true);

    delete meglomaniac.henchman;
    expect("henchman" in meglomaniac).toBe(false);
  });

  it("should use prototype to add to all objects", function () {
    function Circle(radius)
    {
      this.radius = radius;
    }

    var simpleCircle = new Circle(10);
    var colouredCircle = new Circle(5);
    colouredCircle.colour = "red";

    expect(simpleCircle.colour).toBe(undefined);
    expect(colouredCircle.colour).toBe("red");

    Circle.prototype.describe = function () {
      return "This circle has a radius of: " + this.radius;
    };

    expect(simpleCircle.describe()).toBe("This circle has a radius of: 10");
    expect(colouredCircle.describe()).toBe("This circle has a radius of: 5");
  });
});
<|endoftext|>


<commit_before>var ais = require("ais");
var moment = require("moment");
var async = require("async");
var validator = require("validator");
var inreach = require("inreach");

module.exports = {

	// READ AIS POSITION
	readAISPosition: function(userId, mmsi, callback) {

		if(!mmsi) return callback(null);

		if(!validator.isNumeric(mmsi) || mmsi.trim().length !== 9) {
			return callback(null);
		}

		mmsi = mmsi.trim();

		// try cache
		global.CACHE_ais_positions.find({"_id": mmsi}).next(function(err, data) {

			// not a cache hit
			if(err || !data) {

				try {
					ais.get(mmsi, function(pos, more) {

						// store value in cache
						global.CACHE_ais_positions.insert({
							"_id": mmsi,
							"pos": pos,
							"more": more,
							"stored": moment.utc().toDate()
						});

						// store value in positions history
						try {
							global.positions.insert({
								"_id": {
									"user": userId,
									"time": more.time
								},
								"pos": pos,
								"spd": more.speed,
								"crs": more.course,
								"src": {
									"type": "AIS",
									"mmsi": mmsi,
									"name": more.name
								}
							});
						} catch (e) {

						}

						return callback(pos, more);
					});
				}
				catch(e) {
					return callback(null, null);
				}
			}
			else {
				return callback(data.pos, data.more);
			}
		});
	},

	// READ INREACH POSITION
	readInReachPosition: function(userId, username, callback) {

		if(!username || username.trim().length < 2) return callback(null);

		username = username.trim();

		// try cache
		global.CACHE_inreach_positions.find({"_id": username}).next(function(err, data) {

			// not a cache hit
			if(err || !data) {

				try {
					inreach.get(username, function(pos, more) {

						// store value in cache
						global.CACHE_inreach_positions.insert({
							"_id": username,
							"pos": pos,
							"more": more,
							"stored": moment.utc().toDate()
						});

						// store position in history
						try {
							global.positions.insert({
								"_id": {
									"user": userId,
									"time": more.time
								},
								"pos": pos,
								"spd": more.speed,
								"crs": more.course,
								"src": {
									"type": "InReach",
									"username": username,
									"name": more.name
								}
							});
						}
						catch(e) {

						}

						return callback(pos, more);
					});
				}
				catch(e) {
					return callback(null, null);
				}
			}
			else {
				return callback(data.pos, data.more);
			}
		});
	},

	// READ POSITION
	readPosition: function(user, callback) {

		var profile = user.profile;

		// check for inreach
		if(profile && "inreach" in profile && profile.inreach.length > 0) {
			module.exports.readInReachPosition(user._id, profile.inreach, function(pos, more) {

				// no position? fallback to mmsi / ais positioning
				if(pos === null) {

					if(profile && "mmsi" in profile && profile.mmsi.length > 0) {
						module.exports.readAISPosition(user._id, profile.mmsi, function(pos, more) {
							return callback(pos, more, "mmsi");
						});
					}
					else {
						return callback(null, null, null);
					}
				}
				else {
					return callback(pos, more, "inreach");
				}
			});
		}

		// check for mmsi
		else if(profile && "mmsi" in profile && profile.mmsi.length > 0) {
			module.exports.readAISPosition(user._id, profile.mmsi, function(pos, more) {
				return callback(pos, more, "mmsi");
			});
		}

		// nothing here to see
		else {
			return callback(null, null, null);
		}
	},

	// LAST
	// retriece the last n positions per channel
	last: function(req, res) {

		var n = parseInt(req.params.n);

		if(n > 0) {

			// fetch positions
			global.positions.find({
				"_id.user": req.params.id
			}).sort({
				"_id.time": -1
			}).project({
				"time": false
			}).limit(n).toArray(function(err, positions) {

				// handle the error
				if(err || !positions) {
					return res.status(500).send(err || "unable to retrieve positions");
				}

				// remap properties of array
				positions = positions.map((p) => {

					// remap time
					p["time"] = p["_id"]["time"];
					delete p["_id"];

					return p;
				});

				return res.send(positions);
			});
		}
		else {
			return res.send([]);
		}
	},

	// GEOLOCATIONS
	geolocations: function(req, res) {

		// check if there is a cached version available
		global.CACHE_geolocations.findOne({"_id": "geolocations"}, function(err, data) {

			console.log(err, data);

			if(err || !data) {

				global.videos.find({
					"geo": {
						"$exists": true
					}
				}).project({
					"_id": true,
					"geo": true
				}).toArray(function(err, locations) {

					// handle the error
					if(err || !locations) {
						return res.status(500).send(err || "unable to retrieve geolocations");
					}

					var geojson = {
						"type": "FeatureCollection",
						"features": []
					};

					// iterate over locations and build geojson
					for(var l in locations) {

						// iterate over the geometries of the locations
						for(var g in locations[l].geo.geometries)
						var feature = {
							"type": "Feature",
							"geometry": locations[l].geo.geometries[g],
							"properties": {
								"v": locations[l]["_id"]
							}
						}

						geojson.features.push(feature);
					}

					// store geolocations cache
					global.CACHE_geolocations.insert({
						"_id": "geolocations",
						"time": moment().toDate(),
						"data": geojson
					});

					return res.send(geojson);
				});
			}
			else {
				return res.send(data.data);
			}

		});

	}
};
<commit_msg>no message<commit_after>var ais = require("ais");
var moment = require("moment");
var async = require("async");
var validator = require("validator");
var inreach = require("inreach");

module.exports = {

	// READ AIS POSITION
	readAISPosition: function(userId, mmsi, callback) {

		if(!mmsi) return callback(null);

		if(!validator.isNumeric(mmsi) || mmsi.trim().length !== 9) {
			return callback(null);
		}

		mmsi = mmsi.trim();

		// try cache
		global.CACHE_ais_positions.find({"_id": mmsi}).next(function(err, data) {

			// not a cache hit
			if(err || !data) {

				try {
					ais.get(mmsi, function(pos, more) {

						// store value in cache
						global.CACHE_ais_positions.insert({
							"_id": mmsi,
							"pos": pos,
							"more": more,
							"stored": moment.utc().toDate()
						});

						// store value in positions history
						try {
							global.positions.insert({
								"_id": {
									"user": userId,
									"time": more.time
								},
								"pos": pos,
								"spd": more.speed,
								"crs": more.course,
								"src": {
									"type": "AIS",
									"mmsi": mmsi,
									"name": more.name
								}
							});
						} catch (e) {

						}

						return callback(pos, more);
					});
				}
				catch(e) {
					return callback(null, null);
				}
			}
			else {
				return callback(data.pos, data.more);
			}
		});
	},

	// READ INREACH POSITION
	readInReachPosition: function(userId, username, callback) {

		if(!username || username.trim().length < 2) return callback(null);

		username = username.trim();

		// try cache
		global.CACHE_inreach_positions.find({"_id": username}).next(function(err, data) {

			// not a cache hit
			if(err || !data) {

				try {
					inreach.get(username, function(pos, more) {

						// store value in cache
						global.CACHE_inreach_positions.insert({
							"_id": username,
							"pos": pos,
							"more": more,
							"stored": moment.utc().toDate()
						});

						// store position in history
						try {
							global.positions.insert({
								"_id": {
									"user": userId,
									"time": more.time
								},
								"pos": pos,
								"spd": more.speed,
								"crs": more.course,
								"src": {
									"type": "InReach",
									"username": username,
									"name": more.name
								}
							});
						}
						catch(e) {

						}

						return callback(pos, more);
					});
				}
				catch(e) {
					return callback(null, null);
				}
			}
			else {
				return callback(data.pos, data.more);
			}
		});
	},

	// READ POSITION
	readPosition: function(user, callback) {

		var profile = user.profile;

		// check for inreach
		if(profile && "inreach" in profile && profile.inreach.length > 0) {
			module.exports.readInReachPosition(user._id, profile.inreach, function(pos, more) {

				// no position? fallback to mmsi / ais positioning
				if(pos === null) {

					if(profile && "mmsi" in profile && profile.mmsi.length > 0) {
						module.exports.readAISPosition(user._id, profile.mmsi, function(pos, more) {
							return callback(pos, more, "mmsi");
						});
					}
					else {
						return callback(null, null, null);
					}
				}
				else {
					return callback(pos, more, "inreach");
				}
			});
		}

		// check for mmsi
		else if(profile && "mmsi" in profile && profile.mmsi.length > 0) {
			module.exports.readAISPosition(user._id, profile.mmsi, function(pos, more) {
				return callback(pos, more, "mmsi");
			});
		}

		// nothing here to see
		else {
			return callback(null, null, null);
		}
	},

	// LAST
	// retriece the last n positions per channel
	last: function(req, res) {

		var n = parseInt(req.params.n);

		if(n > 0) {

			// fetch positions
			global.positions.find({
				"_id.user": req.params.id
			}).sort({
				"_id.time": -1
			}).project({
				"time": false
			}).limit(n).toArray(function(err, positions) {

				// handle the error
				if(err || !positions) {
					return res.status(500).send(err || "unable to retrieve positions");
				}

				// remap properties of array
				positions = positions.map((p) => {

					// remap time
					p["time"] = p["_id"]["time"];
					delete p["_id"];

					return p;
				});

				return res.send(positions);
			});
		}
		else {
			return res.send([]);
		}
	},

	// GEOLOCATIONS
	geolocations: function(req, res) {

		// check if there is a cached version available
		global.CACHE_geolocations.findOne({"_id": "geolocations"}, function(err, data) {

			if(err || !data) {

				global.videos.find({
					"geo": {
						"$exists": true
					}
				}).project({
					"_id": true,
					"geo": true
				}).toArray(function(err, locations) {

					// handle the error
					if(err || !locations) {
						return res.status(500).send(err || "unable to retrieve geolocations");
					}

					var geojson = {
						"type": "FeatureCollection",
						"features": []
					};

					// iterate over locations and build geojson
					for(var l in locations) {

						// iterate over the geometries of the locations
						for(var g in locations[l].geo.geometries)
						var feature = {
							"type": "Feature",
							"geometry": locations[l].geo.geometries[g],
							"properties": {
								"v": locations[l]["_id"]
							}
						}

						geojson.features.push(feature);
					}

					// store geolocations cache
					global.CACHE_geolocations.insert({
						"_id": "geolocations",
						"time": moment().toDate(),
						"data": geojson
					});

					return res.send(geojson);
				});
			}
			else {
				return res.send(data.data);
			}

		});

	}
};
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const Tapable = require("tapable");
const ConcatSource = require("webpack-sources").ConcatSource;

const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0);
const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0);
const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1;
const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\n?|\n?\}$/g;
const INDENT_MULTILINE_REGEX = /^\t/mg;
const IDENTIFIER_NAME_REPLACE_REGEX = /^[^a-zA-Z$_]/;
const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$_]/g;
const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g;
const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/;

module.exports = class Template extends Tapable {
	constructor(outputOptions) {
		super();
		this.outputOptions = outputOptions || {};
	}

	static getFunctionContent(fn) {
		return fn.toString().replace(FUNCTION_CONTENT_REGEX, "").replace(INDENT_MULTILINE_REGEX, "");
	}

	static toIdentifier(str) {
		if(typeof str !== "string") return "";
		return str.replace(IDENTIFIER_NAME_REPLACE_REGEX, "_").replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_");
	}

	static toPath(str) {
		if(typeof str !== "string") return "";
		return str.replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-").replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, "");
	}

	// map number to a single character a-z, A-Z or <_ + number> if number is too big
	static numberToIdentifer(n) {
		// lower case
		if(n < DELTA_A_TO_Z) return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);

		// upper case
		n -= DELTA_A_TO_Z;
		if(n < DELTA_A_TO_Z) return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n);

		// fall back to _ + number
		n -= DELTA_A_TO_Z;
		return "_" + n;
	}

	indent(str) {
		if(Array.isArray(str)) {
			return str.map(this.indent.bind(this)).join("\n");
		} else {
			str = str.trimRight();
			if(!str) return "";
			var ind = (str[0] === "\n" ? "" : "\t");
			return ind + str.replace(/\n([^\n])/g, "\n\t$1");
		}
	}

	prefix(str, prefix) {
		if(Array.isArray(str)) {
			str = str.join("\n");
		}
		str = str.trim();
		if(!str) return "";
		const ind = (str[0] === "\n" ? "" : prefix);
		return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1");
	}

	asString(str) {
		if(Array.isArray(str)) {
			return str.join("\n");
		}
		return str;
	}

	getModulesArrayBounds(modules) {
		if(!modules.every(moduleIdIsNumber))
			return false;
		var maxId = -Infinity;
		var minId = Infinity;
		modules.forEach(function(module) {
			if(maxId < module.id) maxId = module.id;
			if(minId > module.id) minId = module.id;
		});
		if(minId < 16 + ("" + minId).length) {
			// add minId x ',' instead of 'Array(minId).concat(...)'
			minId = 0;
		}
		var objectOverhead = modules.map(function(module) {
			var idLength = (module.id + "").length;
			return idLength + 2;
		}).reduce(function(a, b) {
			return a + b;
		}, -1);
		var arrayOverhead = minId === 0 ? maxId : 16 + ("" + minId).length + maxId;
		return arrayOverhead < objectOverhead ? [minId, maxId] : false;
	}

	renderChunkModules(chunk, moduleTemplate, dependencyTemplates, prefix) {
		if(!prefix) prefix = "";
		var source = new ConcatSource();
		if(chunk.getNumberOfModules() === 0) {
			source.add("[]");
			return source;
		}
		var removedModules = chunk.removedModules;
		var allModules = chunk.mapModules(function(module) {
			return {
				id: module.id,
				source: moduleTemplate.render(module, dependencyTemplates, chunk)
			};
		});
		if(removedModules && removedModules.length > 0) {
			removedModules.forEach(function(id) {
				allModules.push({
					id: id,
					source: "false"
				});
			});
		}
		var bounds = this.getModulesArrayBounds(allModules);

		if(bounds) {
			// Render a spare array
			var minId = bounds[0];
			var maxId = bounds[1];
			if(minId !== 0) source.add("Array(" + minId + ").concat(");
			source.add("[\n");
			var modules = {};
			allModules.forEach(function(module) {
				modules[module.id] = module;
			});
			for(var idx = minId; idx <= maxId; idx++) {
				var module = modules[idx];
				if(idx !== minId) source.add(",\n");
				source.add("/* " + idx + " */");
				if(module) {
					source.add("\n");
					source.add(module.source);
				}
			}
			source.add("\n" + prefix + "]");
			if(minId !== 0) source.add(")");
		} else {
			// Render an object
			source.add("{\n");
			allModules
				.sort(stringifyIdSortPredicate)
				.forEach(function(module, idx) {
					if(idx !== 0) source.add(",\n");
					source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`);
					source.add(module.source);
				});
			source.add("\n\n" + prefix + "}");
		}
		return source;
	}
};

function stringifyIdSortPredicate(a, b) {
	var aId = a.id + "";
	var bId = b.id + "";
	if(aId < bId) return -1;
	if(aId > bId) return 1;
	return 0;
}

function moduleIdIsNumber(module) {
	return typeof module.id === "number";
}
<commit_msg>add g flag to regexp<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const Tapable = require("tapable");
const ConcatSource = require("webpack-sources").ConcatSource;

const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0);
const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0);
const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1;
const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\n?|\n?\}$/g;
const INDENT_MULTILINE_REGEX = /^\t/mg;
const IDENTIFIER_NAME_REPLACE_REGEX = /^[^a-zA-Z$_]/;
const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$_]/g;
const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g;
const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g;

module.exports = class Template extends Tapable {
	constructor(outputOptions) {
		super();
		this.outputOptions = outputOptions || {};
	}

	static getFunctionContent(fn) {
		return fn.toString().replace(FUNCTION_CONTENT_REGEX, "").replace(INDENT_MULTILINE_REGEX, "");
	}

	static toIdentifier(str) {
		if(typeof str !== "string") return "";
		return str.replace(IDENTIFIER_NAME_REPLACE_REGEX, "_").replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_");
	}

	static toPath(str) {
		if(typeof str !== "string") return "";
		return str.replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-").replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, "");
	}

	// map number to a single character a-z, A-Z or <_ + number> if number is too big
	static numberToIdentifer(n) {
		// lower case
		if(n < DELTA_A_TO_Z) return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);

		// upper case
		n -= DELTA_A_TO_Z;
		if(n < DELTA_A_TO_Z) return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n);

		// fall back to _ + number
		n -= DELTA_A_TO_Z;
		return "_" + n;
	}

	indent(str) {
		if(Array.isArray(str)) {
			return str.map(this.indent.bind(this)).join("\n");
		} else {
			str = str.trimRight();
			if(!str) return "";
			var ind = (str[0] === "\n" ? "" : "\t");
			return ind + str.replace(/\n([^\n])/g, "\n\t$1");
		}
	}

	prefix(str, prefix) {
		if(Array.isArray(str)) {
			str = str.join("\n");
		}
		str = str.trim();
		if(!str) return "";
		const ind = (str[0] === "\n" ? "" : prefix);
		return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1");
	}

	asString(str) {
		if(Array.isArray(str)) {
			return str.join("\n");
		}
		return str;
	}

	getModulesArrayBounds(modules) {
		if(!modules.every(moduleIdIsNumber))
			return false;
		var maxId = -Infinity;
		var minId = Infinity;
		modules.forEach(function(module) {
			if(maxId < module.id) maxId = module.id;
			if(minId > module.id) minId = module.id;
		});
		if(minId < 16 + ("" + minId).length) {
			// add minId x ',' instead of 'Array(minId).concat(...)'
			minId = 0;
		}
		var objectOverhead = modules.map(function(module) {
			var idLength = (module.id + "").length;
			return idLength + 2;
		}).reduce(function(a, b) {
			return a + b;
		}, -1);
		var arrayOverhead = minId === 0 ? maxId : 16 + ("" + minId).length + maxId;
		return arrayOverhead < objectOverhead ? [minId, maxId] : false;
	}

	renderChunkModules(chunk, moduleTemplate, dependencyTemplates, prefix) {
		if(!prefix) prefix = "";
		var source = new ConcatSource();
		if(chunk.getNumberOfModules() === 0) {
			source.add("[]");
			return source;
		}
		var removedModules = chunk.removedModules;
		var allModules = chunk.mapModules(function(module) {
			return {
				id: module.id,
				source: moduleTemplate.render(module, dependencyTemplates, chunk)
			};
		});
		if(removedModules && removedModules.length > 0) {
			removedModules.forEach(function(id) {
				allModules.push({
					id: id,
					source: "false"
				});
			});
		}
		var bounds = this.getModulesArrayBounds(allModules);

		if(bounds) {
			// Render a spare array
			var minId = bounds[0];
			var maxId = bounds[1];
			if(minId !== 0) source.add("Array(" + minId + ").concat(");
			source.add("[\n");
			var modules = {};
			allModules.forEach(function(module) {
				modules[module.id] = module;
			});
			for(var idx = minId; idx <= maxId; idx++) {
				var module = modules[idx];
				if(idx !== minId) source.add(",\n");
				source.add("/* " + idx + " */");
				if(module) {
					source.add("\n");
					source.add(module.source);
				}
			}
			source.add("\n" + prefix + "]");
			if(minId !== 0) source.add(")");
		} else {
			// Render an object
			source.add("{\n");
			allModules
				.sort(stringifyIdSortPredicate)
				.forEach(function(module, idx) {
					if(idx !== 0) source.add(",\n");
					source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`);
					source.add(module.source);
				});
			source.add("\n\n" + prefix + "}");
		}
		return source;
	}
};

function stringifyIdSortPredicate(a, b) {
	var aId = a.id + "";
	var bId = b.id + "";
	if(aId < bId) return -1;
	if(aId > bId) return 1;
	return 0;
}

function moduleIdIsNumber(module) {
	return typeof module.id === "number";
}
<|endoftext|>


<commit_before>import koa_router from 'koa-router';

const redirects = [
    // example: [/\/about(\d+)-(.+)/, '/about?$0:$1', 302],
    [/^\/recent\/?$/, '/created']
];

export default function useRedirects(app) {
    const router = koa_router();

    app.use(router.routes());

    redirects.forEach(r => {
        router.get(r[0], function *() {
            const dest = Object.keys(this.params).reduce((value, key) => value.replace('$' + key, this.params[key]), r[1]);
            console.log(`server redirect: [${r[0]}] ${this.request.url} -> ${dest}`);
            this.status = r[2] || 301;
            this.redirect(dest);
        });
    });
}
<commit_msg>add redirect route from 'ico' to 'about'<commit_after>import koa_router from 'koa-router';

const redirects = [
    // example: [/\/about(\d+)-(.+)/, '/about?$0:$1', 302],
    [/^\/ico\/?$/, '/about'],
    [/^\/recent\/?$/, '/created']
];

export default function useRedirects(app) {
    const router = koa_router();

    app.use(router.routes());

    redirects.forEach(r => {
        router.get(r[0], function *() {
            const dest = Object.keys(this.params).reduce((value, key) => value.replace('$' + key, this.params[key]), r[1]);
            console.log(`server redirect: [${r[0]}] ${this.request.url} -> ${dest}`);
            this.status = r[2] || 301;
            this.redirect(dest);
        });
    });
}
<|endoftext|>


<commit_before>const fetch = require("node-fetch");
const volumes = require("./bible-volume");
const action = /^bible-read/i;

class Bible {
    constructor() {
        this.load = this.load.bind(this);
    }
    middleware() {
        return (req, res, next) => {
            var payload = req.body;
            if (!payload.result.action.match(action) || payload.result.actionIncomplete)
                next();
            else {
                this.load(payload)
                    .then(result => {
                        res.setHeader('Content-Type', 'application/json'); //Requires application/json MIME type
                        res.send(JSON.stringify(result));
                    })
                    .catch(e => {
                        var response = e;
                        res.setHeader('Content-Type', 'application/json'); //Requires application/json MIME type
                        res.send(JSON.stringify({
                            "speech": response,
                            "displayText": response
                        }));
                    });
            }
        };
    }
    load(data) {
        var parameter = this.getParameter(data);
        var action = data.result.action;

        if (action === "bible-read-more")
            parameter.page += 1;

        return this.getVerses(parameter)
            .then(verses => {
                var outMore = {
                    "name": "bible-read-more",
                    "lifespan": 5,
                    "parameters": parameter
                };
                var outVersion = Object.assign({}, outMore);
                outVersion.name = "bible-read-version";

                return {
                    "speech": verses,
                    "displayText": verses,
                    "data": {},
                    "source": "bible-webhook",
                    "contextOut": [outMore, outVersion]
                };
            })
            .catch((e) => {
                return {
                    "speech": e,
                    "displayText": e,
                    "data": { demo: 10 },
                    "source": "bible-webhook",
                    "contextOut": []
                };
            });
    }

    getVerses(parameter) {
        var book = volumes.get(parameter.book);

        if (parameter.chapter > book.chapters.size)
            return Promise.reject(`the book of ${book.name} only contains ${book.chapters.size} chapters`);
        else {
            var chapter = book.chapters.get(parameter.chapter);
            var damId = `${parameter.version}${book.volume}2ET`;

            var from = parameter.from;
            var to = parameter.to;
            var size = parameter.size || 10;
            var page = parameter.page;

            from = parameter.from + (page - 1) * size;
            to = from + size - 1;
            to = to > parameter.to ? parameter.to : to;

            if (from > parameter.to) {
                from = parameter.to + 1 + parseInt((from - parameter.to) / size, 10) * size;
                to = from + size - 1;
            }
            // user loads more when end of chapter reached;
            if (from > chapter.length) {
                if (book.chapters.size >= parameter.chapter + 1) {
                    parameter.chapter++;
                    parameter.from = 1;
                    parameter.to = size;
                    parameter.page = 1;
                    from = parameter.from;
                    to = parameter.to;
                    chapter = book.chapters.get(parameter.chapter);
                }
                else {
                    return Promise.reject(`You have reach the end of book of ${book.name}.`);
                }
            }
            // user loads more when requested end verse reached;

            to = to > chapter.length ? chapter.length : to;

            var uri = `http://dbt.io/text/verse?key=${process.env.DBT_KEY}&dam_id=${damId}&book_id=${parameter.book}&chapter_id=${parameter.chapter}&verse_start=${from}&verse_end=${to}&v=2`;
            return fetch(uri)
                .then(result => result.json())
                .then(json => {
                    var header = `${book.name} chapter ${parameter.chapter} verse ${from} - ${to} of ${chapter.length} verses.\n`;
                    var footer = `\nsay next to show more...\npowered by bible.is`;
                    return [].concat.apply([], [
                        [header],
                        [].concat.apply([], json.map(verse => `${verse.verse_id}. ${verse.verse_text}`)), [footer]
                    ]).join("\n");
                });
        }
    }

    getParameter(data) {
        var defaultSize = 10;
        var parameters = data.result.parameters;
        var bible = data.result.parameters.bible || {};
        var version = parameters.version;
        var book = bible.book || parameters.book;
        var chapter = Math.abs(parseInt(bible.chapter || parameters.chapter || 1, 10));

        var from = Math.abs(parseInt(bible["verse-start"] || parameters.from || 1, 10));
        var to = Math.abs(parseInt(bible["verse-end"] || parameters.to || (from + defaultSize) || 1, 10));
        var arr = [from, to].sort((a, b) => a - b);

        var page = parseInt(parameters.page || 1, 10);

        var size = parameters.size ? parseInt(parameters.size, 10) : null;
        var current = parameters.current ? parseInt(parameters.current, 10) : null;

        return {
            "version": version,
            "book": book,
            "chapter": chapter,
            "from": arr[0],
            "to": arr[1],
            "page": page,
            "size": size,
            "current": current
        };
    }
}

module.exports = Bible;
<commit_msg>fix next<commit_after>const fetch = require("node-fetch");
const volumes = require("./bible-volume");
const action = /^bible-read/i;

class Bible {
    constructor() {
        this.load = this.load.bind(this);
    }
    middleware() {
        return (req, res, next) => {
            var payload = req.body;
            if (!payload.result.action.match(action) || payload.result.actionIncomplete)
                next();
            else {
                this.load(payload)
                    .then(result => {
                        res.setHeader('Content-Type', 'application/json'); //Requires application/json MIME type
                        res.send(JSON.stringify(result));
                    })
                    .catch(e => {
                        var response = e;
                        res.setHeader('Content-Type', 'application/json'); //Requires application/json MIME type
                        res.send(JSON.stringify({
                            "speech": response,
                            "displayText": response
                        }));
                    });
            }
        };
    }
    load(data) {
        var parameter = this.getParameter(data);
        var action = data.result.action;

        if (action === "bible-read-more")
            parameter.page += 1;

        return this.getVerses(parameter)
            .then(verses => {
                var outMore = {
                    "name": "bible-read-more",
                    "lifespan": 5,
                    "parameters": parameter
                };
                var outVersion = Object.assign({}, outMore);
                outVersion.name = "bible-read-version";

                return {
                    "speech": verses,
                    "displayText": verses,
                    "data": {},
                    "source": "bible-webhook",
                    "contextOut": [outMore, outVersion]
                };
            })
            .catch((e) => {
                return {
                    "speech": e,
                    "displayText": e,
                    "data": { demo: 10 },
                    "source": "bible-webhook",
                    "contextOut": []
                };
            });
    }

    getVerses(parameter) {
        var book = volumes.get(parameter.book);

        if (parameter.chapter > book.chapters.size)
            return Promise.reject(`the book of ${book.name} only contains ${book.chapters.size} chapters`);
        else {
            var chapter = book.chapters.get(parameter.chapter);
            var damId = `${parameter.version}${book.volume}2ET`;

            var from = parameter.from;
            var to = parameter.to;
            var size = parameter.size || 10;
            var page = parameter.page;

            from = parameter.from + (page - 1) * size;
            to = from + size - 1;
            to = to > parameter.to ? parameter.to : to;

            if (from >= parameter.to) {
                from = parameter.to + 1 + parseInt((from - parameter.to) / size, 10) * size;
                to = from + size - 1;
            }
            // user loads more when end of chapter reached;
            if (from > chapter.length) {
                if (book.chapters.size >= parameter.chapter + 1) {
                    parameter.chapter++;
                    parameter.from = 1;
                    parameter.to = size;
                    parameter.page = 1;
                    from = parameter.from;
                    to = parameter.to;
                    chapter = book.chapters.get(parameter.chapter);
                }
                else {
                    return Promise.reject(`You have reach the end of book of ${book.name}.`);
                }
            }
            // user loads more when requested end verse reached;

            to = to > chapter.length ? chapter.length : to;

            var uri = `http://dbt.io/text/verse?key=${process.env.DBT_KEY}&dam_id=${damId}&book_id=${parameter.book}&chapter_id=${parameter.chapter}&verse_start=${from}&verse_end=${to}&v=2`;
            return fetch(uri)
                .then(result => result.json())
                .then(json => {
                    var header = `${book.name} chapter ${parameter.chapter} verse ${from} - ${to} of ${chapter.length} verses.\n`;
                    var footer = `\nsay next to show more...\npowered by bible.is`;
                    return [].concat.apply([], [
                        [header],
                        [].concat.apply([], json.map(verse => `${verse.verse_id}. ${verse.verse_text}`)), [footer]
                    ]).join("\n");
                });
        }
    }

    getParameter(data) {
        var defaultSize = 10;
        var parameters = data.result.parameters;
        var bible = data.result.parameters.bible || {};
        var version = parameters.version;
        var book = bible.book || parameters.book;
        var chapter = Math.abs(parseInt(bible.chapter || parameters.chapter || 1, 10));

        var from = Math.abs(parseInt(bible["verse-start"] || parameters.from || 1, 10));
        var to = Math.abs(parseInt(bible["verse-end"] || parameters.to || (from + defaultSize-1) || 1, 10));
        var arr = [from, to].sort((a, b) => a - b);

        var page = parseInt(parameters.page || 1, 10);

        var size = parameters.size ? parseInt(parameters.size, 10) : null;
        var current = parameters.current ? parseInt(parameters.current, 10) : null;

        return {
            "version": version,
            "book": book,
            "chapter": chapter,
            "from": arr[0],
            "to": arr[1],
            "page": page,
            "size": size,
            "current": current
        };
    }
}

module.exports = Bible;
<|endoftext|>


<commit_before>(function () {
var sharedDataMap = {},
    visibilityMap = { 'histogram': false, 'information': false };

    var getSharedData = function (model, container) {
        if (sharedDataMap.hasOwnProperty(model.getHash())) {
            return sharedDataMap[model.getHash()];
        } else {
            var layer = new cinema.models.LayerModel(model.getDefaultPipelineSetup(), { info: model }),
                control = new cinema.models.ControlModel({
                    info: model
                }),
                histogram = new cinema.models.CompositeHistogramModel({
                    layerModel: layer,
                    basePath: model.get('basePath'),
                    analysisInfo: model.attributes.metadata.analysis
                }),
                viewpoint = new cinema.models.ViewPointModel({
                    controlModel: control
                }),
                informationWidget = new cinema.views.SearchInformationWidget({
                    el: $('.c-information-panel', container),
                    model: model,
                    controlModel: control,
                    exclude: ['layer', 'filename'],
                    layers: layer,
                    toolbarSelector: '.c-panel-toolbar'
                }),
                histogramWidget = new cinema.views.CompositeHistogramWidget({
                    el: $('.c-histogram-panel', container),
                    basePath: model.get('basePath'),
                    histogramModel: histogram,
                    viewpoint: viewpoint,
                    layerModel: layer,
                    toolbarSelector: '.c-panel-toolbar'
                }),
                compositeToolsWidget = new cinema.views.CompositeToolsWidget({
                    el: $('.c-tools-panel', container),
                    model: model,
                    controlModel: control,
                    viewpoint: viewpoint,
                    layers: layer,
                    toolbarSelector: '.c-panel-toolbar'
                }),
                searchToolsWidget = new cinema.views.SearchToolsWidget({
                    el: $('.c-tools-panel', container),
                    model: model,
                    layers: layer,
                    toolbarSelector: '.c-panel-toolbar'
                }),
                imageManager = new cinema.utilities.CompositeImageManager({
                    visModel: model
                }),
                renderView = new cinema.views.VisualizationCanvasWidget({
                    el: this.$('.c-body-container', container),
                    model: model,
                    layers: layer,
                    controls: control,
                    viewpoint: viewpoint,
                    compositeManager: imageManager
                }),
                searchView = new cinema.views.CompositeSearchPage({
                    el: $('.c-body-container', container),
                    basePath: model.get('basePath'),
                    histogramModel: histogram,
                    visModel: model,
                    layerModel: layer
                }),
                shared = {
                    control: control,
                    histogram: histogram,
                    layer: layer,
                    viewpoint: viewpoint,
                    informationWidget: informationWidget,
                    histogramWidget: histogramWidget,
                    compositeToolsWidget: compositeToolsWidget,
                    searchToolsWidget: searchToolsWidget,
                    imageManager: imageManager,
                    renderView: renderView,
                    searchView: searchView
                };
            sharedDataMap[model.getHash()] = shared;
            return shared;
        }
    };

    var visibility = function (name, value) {
        if (value === undefined) {
            return visibilityMap[name];
        } else {
            visibilityMap[name] = value;
        }
    };

    cinema.events.on('toggle-control-panel', function(event) {
        visibility(event.key, event.visible);
    });

    cinema.views.CompositeView = Backbone.View.extend({
        initialize: function (opts) {
            this.compositeModel = new cinema.decorators.Composite(this.model);
            var sharedData = getSharedData(this.compositeModel, this.$el);

            this.compositeManager = sharedData.imageManager;
            this.controlModel = sharedData.control;
            this.viewpointModel = sharedData.viewpoint;
            this.layers = sharedData.layer;
            this.renderView = sharedData.renderView;

            new cinema.utilities.RenderViewMouseInteractor({
                    renderView: this.renderView,
                    camera: this.viewpointModel
                }).enableMouseWheelZoom({
                    maxZoomLevel: 10,
                    zoomIncrement: 0.05,
                    invertControl: false
                }).enableDragPan({
                    keyModifiers: cinema.keyModifiers.SHIFT
                }).enableDragRotation({
                    keyModifiers: null
                });

            this.compositeTools = sharedData.compositeToolsWidget;

            this._hasAnalysis = _.has(this.model.get('metadata'), 'analysis');
            if (this._hasAnalysis) {
                this.histogramModel = sharedData.histogram;
                this.controlList = opts.defaultControls.slice(0);
                this.compositeHistogram = sharedData.histogramWidget;
                this.searchInformation = sharedData.informationWidget;
                this.controlList.push(
                    { position: 'left', key: 'information', icon: 'icon-help', title: 'Information' },
                    { position: 'center', key: 'histogram', icon: 'icon-chart-bar', title: 'Histogram' }
                );
            }

            this.controlModel.on('change', this.refreshCamera, this);
            this.viewpointModel.on('change', this.refreshCamera, this);
            this.listenTo(cinema.events, 'c:resetCamera', this.resetCamera);
        },

        render: function () {
            this.renderView.setElement(this.$('.c-body-container')).render().showViewpoint();
            this.compositeTools.setElement(this.$('.c-tools-panel')).render();
            if (this._hasAnalysis) {
                this.compositeHistogram.setElement(this.$('.c-histogram-panel')).render();
                this.searchInformation.setElement(this.$('.c-information-panel')).render();
                this.$('.c-histogram-panel').toggle(visibility('histogram'));
                this.$('.c-information-panel').toggle(visibility('information'));
            }

            return this;
        },

        refreshCamera: function () {
            if (this.renderView) {
                this.renderView.showViewpoint();
            }
        },

        resetCamera: function () {
            if (this.renderView) {
                this.renderView.showViewpoint();
                this.renderView.resetCamera();
            }
        }
    });

    cinema.views.CompositeSearchView = Backbone.View.extend({
        initialize: function (opts) {
            this.compositeModel = new cinema.decorators.Composite(this.model);
            var sharedData = getSharedData(this.compositeModel, this.$el);

            this.controlModel = sharedData.control;
            this.viewpointModel = sharedData.viewpoint;
            this.layers = sharedData.layer;
            this.searchView = sharedData.searchView;
            this.searchTools = sharedData.searchToolsWidget;

            this._hasAnalysis = _.has(this.model.get('metadata'), 'analysis');
            if (this._hasAnalysis) {
                this.histogramModel = sharedData.histogram;
                this.compositeHistogram = sharedData.histogramWidget;
                this.searchInformation = sharedData.informationWidget;
                this.controlList = opts.defaultControls.slice(0);
                this.controlList.push(
                    { position: 'left', key: 'information', icon: 'icon-help', title: 'Information' },
                    { position: 'center', key: 'histogram', icon: 'icon-chart-bar', title: 'Histogram' }
                );
            }

            this.controlModel.on('change', this.refreshCamera, this);
            this.viewpointModel.on('change', this.refreshCamera, this);
            this.listenTo(cinema.events, 'c:resetCamera', this.resetCamera);
        },

        render: function () {
            this.searchView.setElement(this.$('.c-body-container')).render();
            this.searchTools.setElement(this.$('.c-tools-panel')).render();
            if (this._hasAnalysis) {
                this.searchInformation.setElement(this.$('.c-information-panel')).render();
                this.compositeHistogram.setElement(this.$('.c-histogram-panel')).render();
                this.$('.c-histogram-panel').toggle(visibility('histogram'));
                this.$('.c-information-panel').toggle(visibility('information'));
            }

            return this;
        }
    });
}());

cinema.viewMapper.registerView('composite-image-stack', 'view', cinema.views.CompositeView, {
    controls: [
        { position: 'right', key: 'tools', icon: 'icon-tools', title: 'Tools' }
    ]
});

cinema.viewMapper.registerView('composite-image-stack', 'search', cinema.views.CompositeSearchView, {
    controls: [
        { position: 'right', key: 'tools', icon: 'icon-tools', title: 'Tools' },
    ]
});
<commit_msg>cleaner yet again<commit_after>(function () {
var sharedDataMap = {},
    visibilityMap = { 'histogram': false, 'information': false };

    var getSharedData = function (model, container) {
        if (sharedDataMap.hasOwnProperty(model.getHash())) {
            return sharedDataMap[model.getHash()];
        } else {
            var layer = new cinema.models.LayerModel(model.getDefaultPipelineSetup(), { info: model }),
                control = new cinema.models.ControlModel({
                    info: model
                }),
                histogram = new cinema.models.CompositeHistogramModel({
                    layerModel: layer,
                    basePath: model.get('basePath'),
                    analysisInfo: model.attributes.metadata.analysis
                }),
                viewpoint = new cinema.models.ViewPointModel({
                    controlModel: control
                }),
                informationWidget = new cinema.views.SearchInformationWidget({
                    el: $('.c-information-panel', container),
                    model: model,
                    controlModel: control,
                    exclude: ['layer', 'filename'],
                    layers: layer,
                    toolbarSelector: '.c-panel-toolbar'
                }),
                histogramWidget = new cinema.views.CompositeHistogramWidget({
                    el: $('.c-histogram-panel', container),
                    basePath: model.get('basePath'),
                    histogramModel: histogram,
                    viewpoint: viewpoint,
                    layerModel: layer,
                    toolbarSelector: '.c-panel-toolbar'
                }),
                compositeToolsWidget = new cinema.views.CompositeToolsWidget({
                    el: $('.c-tools-panel', container),
                    model: model,
                    controlModel: control,
                    viewpoint: viewpoint,
                    layers: layer,
                    toolbarSelector: '.c-panel-toolbar'
                }),
                searchToolsWidget = new cinema.views.SearchToolsWidget({
                    el: $('.c-tools-panel', container),
                    model: model,
                    layers: layer,
                    toolbarSelector: '.c-panel-toolbar'
                }),
                imageManager = new cinema.utilities.CompositeImageManager({
                    visModel: model
                }),
                renderView = new cinema.views.VisualizationCanvasWidget({
                    el: this.$('.c-body-container', container),
                    model: model,
                    layers: layer,
                    controls: control,
                    viewpoint: viewpoint,
                    compositeManager: imageManager
                }),
                searchView = new cinema.views.CompositeSearchPage({
                    el: $('.c-body-container', container),
                    basePath: model.get('basePath'),
                    histogramModel: histogram,
                    visModel: model,
                    layerModel: layer
                }),
                shared = {
                    control: control,
                    histogram: histogram,
                    layer: layer,
                    viewpoint: viewpoint,
                    informationWidget: informationWidget,
                    histogramWidget: histogramWidget,
                    compositeToolsWidget: compositeToolsWidget,
                    searchToolsWidget: searchToolsWidget,
                    imageManager: imageManager,
                    renderView: renderView,
                    searchView: searchView
                };
            sharedDataMap[model.getHash()] = shared;
            return shared;
        }
    };

    var visibility = function (name, value) {
        if (value === undefined) {
            return visibilityMap[name];
        } else {
            visibilityMap[name] = value;
        }
    };

    cinema.events.on('toggle-control-panel', function(event) {
        visibility(event.key, event.visible);
    });

    cinema.views.CompositeView = Backbone.View.extend({
        initialize: function (opts) {
            this.compositeModel = new cinema.decorators.Composite(this.model);
            var sharedData = getSharedData(this.compositeModel, this.$el);

            this.controlModel = sharedData.control;
            this.viewpointModel = sharedData.viewpoint;
            this.renderView = sharedData.renderView;

            new cinema.utilities.RenderViewMouseInteractor({
                    renderView: this.renderView,
                    camera: this.viewpointModel
                }).enableMouseWheelZoom({
                    maxZoomLevel: 10,
                    zoomIncrement: 0.05,
                    invertControl: false
                }).enableDragPan({
                    keyModifiers: cinema.keyModifiers.SHIFT
                }).enableDragRotation({
                    keyModifiers: null
                });

            this.compositeTools = sharedData.compositeToolsWidget;

            this._hasAnalysis = _.has(this.model.get('metadata'), 'analysis');
            if (this._hasAnalysis) {
                this.controlList = opts.defaultControls.slice(0);
                this.compositeHistogram = sharedData.histogramWidget;
                this.searchInformation = sharedData.informationWidget;
                this.controlList.push(
                    { position: 'left', key: 'information', icon: 'icon-help', title: 'Information' },
                    { position: 'center', key: 'histogram', icon: 'icon-chart-bar', title: 'Histogram' }
                );
            }

            this.controlModel.on('change', this.refreshCamera, this);
            this.viewpointModel.on('change', this.refreshCamera, this);
            this.listenTo(cinema.events, 'c:resetCamera', this.resetCamera);
        },

        render: function () {
            this.renderView.setElement(this.$('.c-body-container')).render().showViewpoint();
            this.compositeTools.setElement(this.$('.c-tools-panel')).render();
            if (this._hasAnalysis) {
                this.compositeHistogram.setElement(this.$('.c-histogram-panel')).render();
                this.searchInformation.setElement(this.$('.c-information-panel')).render();
                this.$('.c-histogram-panel').toggle(visibility('histogram'));
                this.$('.c-information-panel').toggle(visibility('information'));
            }

            return this;
        },

        refreshCamera: function () {
            if (this.renderView) {
                this.renderView.showViewpoint();
            }
        },

        resetCamera: function () {
            if (this.renderView) {
                this.renderView.showViewpoint();
                this.renderView.resetCamera();
            }
        }
    });

    cinema.views.CompositeSearchView = Backbone.View.extend({
        initialize: function (opts) {
            this.compositeModel = new cinema.decorators.Composite(this.model);
            var sharedData = getSharedData(this.compositeModel, this.$el);

            this.controlModel = sharedData.control;
            this.viewpointModel = sharedData.viewpoint;
            this.searchView = sharedData.searchView;
            this.searchTools = sharedData.searchToolsWidget;

            this._hasAnalysis = _.has(this.model.get('metadata'), 'analysis');
            if (this._hasAnalysis) {
                this.compositeHistogram = sharedData.histogramWidget;
                this.searchInformation = sharedData.informationWidget;
                this.controlList = opts.defaultControls.slice(0);
                this.controlList.push(
                    { position: 'left', key: 'information', icon: 'icon-help', title: 'Information' },
                    { position: 'center', key: 'histogram', icon: 'icon-chart-bar', title: 'Histogram' }
                );
            }

            this.controlModel.on('change', this.refreshCamera, this);
            this.viewpointModel.on('change', this.refreshCamera, this);
            this.listenTo(cinema.events, 'c:resetCamera', this.resetCamera);
        },

        render: function () {
            this.searchView.setElement(this.$('.c-body-container')).render();
            this.searchTools.setElement(this.$('.c-tools-panel')).render();
            if (this._hasAnalysis) {
                this.searchInformation.setElement(this.$('.c-information-panel')).render();
                this.compositeHistogram.setElement(this.$('.c-histogram-panel')).render();
                this.$('.c-histogram-panel').toggle(visibility('histogram'));
                this.$('.c-information-panel').toggle(visibility('information'));
            }

            return this;
        }
    });
}());

cinema.viewMapper.registerView('composite-image-stack', 'view', cinema.views.CompositeView, {
    controls: [
        { position: 'right', key: 'tools', icon: 'icon-tools', title: 'Tools' }
    ]
});

cinema.viewMapper.registerView('composite-image-stack', 'search', cinema.views.CompositeSearchView, {
    controls: [
        { position: 'right', key: 'tools', icon: 'icon-tools', title: 'Tools' },
    ]
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { History } from 'react-router';
import reactMixin from 'react-mixin';

// MATERIAL UI
import List from '../../node_modules/material-ui/lib/lists/list';
import Card from '../../node_modules/material-ui/lib/card/card';
import CardText from '../../node_modules/material-ui/lib/card/card-text';
import CardMedia from '../../node_modules/material-ui/lib/card/card-media';

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

  render() {
    return (
      <Card>
        <CardText>
          No Streams Are Currently Available
        </CardText>
      </Card>
    )
  }
}

var styles = {
  image:{
    'maxWidth': '300px'
  }
}
export default NoStream;
<commit_msg>Styling of No Stream Page<commit_after>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { History } from 'react-router';
import reactMixin from 'react-mixin';

// MATERIAL UI
import List from '../../node_modules/material-ui/lib/lists/list';
import Card from '../../node_modules/material-ui/lib/card/card';
import CardText from '../../node_modules/material-ui/lib/card/card-text';
import CardMedia from '../../node_modules/material-ui/lib/card/card-media';
import FlatButton from '../../node_modules/material-ui/lib/flat-button';

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

  render() {
    return (

          No Streams Are Currently Available

            <FlatButton label="Start a Broadcast" primary={true} style={styles.buttonSection}/>

    )
  }
}

var styles = {
  titleFontBlack: {
    fontWeight:'300',
    fontFamily: 'Roboto, sans-serif',
    color:'black',
    textAlign: 'center'
  },

  flexColumn: {
    display: 'flex',
    flexDirection:'column',
    justifyContent: 'center',
    flexWrap: 'wrap',
    alignItem: 'center'
  },

  boxCenter: {
    flex: 1,
    alignSelf: 'center'
  },
}
export default NoStream;
<|endoftext|>