<commit_before>!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],e):"object"==typeof exports?exports["react-parallax"]=e(require("react"),require("react-dom")):t["react-parallax"]=e(t.React,t.ReactDOM)}(this,function(t,e){return function(t){function e(i){if(n[i])return n[i].exports;var o=n[i]={exports:{},id:i,loaded:!1};return t[i].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){"use strict";function i(t){return t&&t.__esModule?t:{"default":t}}Object.defineProperty(e,"__esModule",{value:!0}),e.Background=e.Parallax=void 0;var o=n(4),r=i(o),s=n(3),a=i(s);e.Parallax=r["default"],e.Background=a["default"]},function(e,n){e.exports=t},function(t,e){"use strict";function n(t,e){if(!e)return!1;var n=t.getBoundingClientRect().top,i=t.getBoundingClientRect().bottom;return 0>=n&&i>=0||n>=0&&i<=window.innerHeight||n<=window.innerHeight&&i>=window.innerHeight}function i(t){if(!t)return 0;var e=window,n=document,i=n.documentElement,o=n.getElementsByTagName("body")[0];return e.innerHeight||i.clientHeight||o.clientHeight}function o(){return!("undefined"==typeof window||!window.document||!window.document.createElement)}function r(t){for(var e=0;t;)e+=t.offsetTop-t.scrollTop+t.clientTop,t=t.offsetParent;return{y:e}}Object.defineProperty(e,"__esModule",{value:!0}),e.isScrolledIntoView=n,e.getWindowHeight=i,e.canUseDOM=o,e.getPosition=r},function(t,e,n){"use strict";function i(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function r(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0});var a=function(){function t(t,e){for(var n=0;n<e.length;n++){var i=e[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,n,i){return n&&t(e.prototype,n),i&&t(e,i),e}}(),l=n(1),u=i(l),c=function(t){function e(){return o(this,e),r(this,Object.getPrototypeOf(e).apply(this,arguments))}return s(e,t),a(e,[{key:"isParallaxBackground",value:function(){return!0}},{key:"render",value:function(){return u["default"].createElement("div",{className:"react-parallax-background"},this.props.children)}}]),e}(u["default"].Component);e["default"]=c},function(t,e,n){"use strict";function i(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function r(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0});var a=function(){function t(t,e){for(var n=0;n<e.length;n++){var i=e[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,n,i){return n&&t(e.prototype,n),i&&t(e,i),e}}(),l=n(1),u=i(l),c=n(5),d=i(c),h=n(2),p=function(t){function e(t){o(this,e);var n=r(this,Object.getPrototypeOf(e).call(this,t));return n.canUseDOM=(0,h.canUseDOM)(),n.ReactDOM=d["default"].findDOMNode?d["default"]:u["default"],n.node=null,n.state={splitChildren:n.getSplitChildren(t)},n.windowHeight=(0,h.getWindowHeight)(n.canUseDOM),n.childStyle=n.getChildStyle(),n.timestamp=Date.now(),n.autobind(),n}return s(e,t),a(e,[{key:"componentWillReceiveProps",value:function(t){this.setState({splitChildren:this.getSplitChildren(t)})}},{key:"autobind",value:function(){this.onScroll=this.onScroll.bind(this),this.onWindowResize=this.onWindowResize.bind(this),this.updatePosition=this.updatePosition.bind(this),this.onWindowLoad=this.onWindowLoad.bind(this)}},{key:"render",value:function(){var t=this;return console.log("render"),u["default"].createElement("div",{className:"react-parallax "+(this.props.className?this.props.className:"")},this.props.bgImage?u["default"].createElement("img",{className:"react-parallax-bgimage",src:this.props.bgImage,ref:"bgImage",alt:""}):"",this.state.splitChildren.bgChildren.length>0?u["default"].createElement("div",{className:"react-parallax-background-children",ref:function(e){return t.bgMounted(e)}},this.state.splitChildren.bgChildren):"",u["default"].createElement("div",{className:"react-parallax-content",style:this.childStyle,ref:"content"},this.state.splitChildren.children))}},{key:"componentWillUnmount",value:function(){this.canUseDOM&&(document.removeEventListener("scroll",this.onScroll,!1),window.removeEventListener("resize",this.onWindowResize,!1),window.removeEventListener("load",this.onWindowLoad,!1))}},{key:"componentDidMount",value:function(){this.canUseDOM&&(document.addEventListener("scroll",this.onScroll,!1),window.addEventListener("resize",this.onWindowResize,!1),window.addEventListener("load",this.onWindowLoad,!1)),this.node=this.ReactDOM.findDOMNode(this),this.img=this.refs.bgImage?this.ReactDOM.findDOMNode(this.refs.bgImage):null,this.updatePosition(),this.setParallaxStyle(),this.setInitialBackgroundStyles(this.img),this.setInitialBackgroundStyles(this.bg)}},{key:"bgMounted",value:function(t){this.bg=this.ReactDOM.findDOMNode(t)}},{key:"onScroll",value:function(t){if(this.canUseDOM){var e=Date.now();e-this.timestamp>=10&&(0,h.isScrolledIntoView)(this.node,this.canUseDOM)&&(window.requestAnimationFrame(this.updatePosition),this.timestamp=e)}}},{key:"onWindowLoad",value:function(){this.updatePosition()}},{key:"getSplitChildren",value:function(t){var e=[],n=u["default"].Children.toArray(t.children);return n.forEach(function(t,i){t.type&&t.type.prototype&&t.type.prototype.isParallaxBackground&&(e=e.concat(n.splice(i,1)))}),{bgChildren:e,children:n}}},{key:"updatePosition",value:function(){var t=!1,e=this.ReactDOM.findDOMNode(this.refs.content);this.contentHeight=e.getBoundingClientRect().height,this.contentWidth=this.node.getBoundingClientRect().width,this.img&&this.img.naturalWidth/this.img.naturalHeight<this.contentWidth/(this.contentHeight+this.props.strength)&&(t=!0);var n=this.node.getBoundingClientRect();n&&this.img&&this.setImagePosition(n.top,t),n&&this.bg&&this.state.splitChildren.bgChildren.length>0&&this.setBackgroundPosition(n.top)}},{key:"setImagePosition",value:function(t){var e=arguments.length<=1||void 0===arguments[1]?!1:arguments[1],n=this.props.bgHeight||(e?"auto":Math.floor(this.contentHeight+Math.abs(this.props.strength))+"px"),i=this.props.bgWidth||(e?this.contentWidth+"px":"auto");if(this.props.disabled!==!0){var o=o=-1*Math.floor((t+this.contentHeight-.25*this.props.strength)/this.windowHeight*this.props.strength);this.img.style.WebkitTransform="translate3d(-50%, "+o+"px, 0)",this.img.style.transform="translate3d(-50%, "+o+"px, 0)",this.img.style.height=n,this.img.style.width=i,this.props.blur&&(this.img.style.WebkitFilter="blur("+this.props.blur+"px)",this.img.style.filter="blur("+this.props.blur+"px)")}}},{key:"setBackgroundPosition",value:function(t){var e=e=-1*Math.floor((t+this.contentHeight-.25*this.props.strength)/this.windowHeight*this.props.strength);this.bg.style.WebkitTransform="translate3d(-50%, "+e+"px, 0)",this.bg.style.transform="translate3d(-50%, "+e+"px, 0)"}},{key:"setInitialBackgroundStyles",value:function(t){t&&(t.style.position="absolute",t.style.left="50%",t.style.WebkitTransformStyle="preserve-3d",t.style.WebkitBackfaceVisibility="hidden",t.style.MozBackfaceVisibility="hidden",t.style.MsBackfaceVisibility="hidden")}},{key:"onWindowResize",value:function(){this.windowHeight=(0,h.getWindowHeight)(this.canUseDOM),this.updatePosition()}},{key:"setParallaxStyle",value:function(){this.node&&(this.node.style.position="relative",this.node.style.overflow="hidden")}},{key:"getChildStyle",value:function(){return{position:"relative"}}},{key:"log",value:function(){this.props.log&&console.log(arguments)}}]),e}(u["default"].Component);p.propTypes={bgImage:u["default"].PropTypes.string,bgWidth:u["default"].PropTypes.string,bgHeight:u["default"].PropTypes.string,strength:u["default"].PropTypes.number,blur:u["default"].PropTypes.number},p.defaultProps={strength:100,blur:0,log:!1,disabled:!1},e["default"]=p},function(t,n){t.exports=e}])});<commit_msg>new dist<commit_after>!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],e):"object"==typeof exports?exports["react-parallax"]=e(require("react"),require("react-dom")):t["react-parallax"]=e(t.React,t.ReactDOM)}(this,function(t,e){return function(t){function e(i){if(n[i])return n[i].exports;var o=n[i]={exports:{},id:i,loaded:!1};return t[i].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){"use strict";function i(t){return t&&t.__esModule?t:{"default":t}}Object.defineProperty(e,"__esModule",{value:!0}),e.Background=e.Parallax=void 0;var o=n(4),r=i(o),s=n(3),a=i(s);e.Parallax=r["default"],e.Background=a["default"]},function(e,n){e.exports=t},function(t,e){"use strict";function n(t,e){if(!e)return!1;var n=t.getBoundingClientRect().top,i=t.getBoundingClientRect().bottom;return 0>=n&&i>=0||n>=0&&i<=window.innerHeight||n<=window.innerHeight&&i>=window.innerHeight}function i(t){if(!t)return 0;var e=window,n=document,i=n.documentElement,o=n.getElementsByTagName("body")[0];return e.innerHeight||i.clientHeight||o.clientHeight}function o(){return!("undefined"==typeof window||!window.document||!window.document.createElement)}function r(t){for(var e=0;t;)e+=t.offsetTop-t.scrollTop+t.clientTop,t=t.offsetParent;return{y:e}}Object.defineProperty(e,"__esModule",{value:!0}),e.isScrolledIntoView=n,e.getWindowHeight=i,e.canUseDOM=o,e.getPosition=r},function(t,e,n){"use strict";function i(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function r(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0});var a=function(){function t(t,e){for(var n=0;n<e.length;n++){var i=e[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,n,i){return n&&t(e.prototype,n),i&&t(e,i),e}}(),l=n(1),u=i(l),c=function(t){function e(){return o(this,e),r(this,Object.getPrototypeOf(e).apply(this,arguments))}return s(e,t),a(e,[{key:"isParallaxBackground",value:function(){return!0}},{key:"render",value:function(){return u["default"].createElement("div",{className:"react-parallax-background"},this.props.children)}}]),e}(u["default"].Component);e["default"]=c},function(t,e,n){"use strict";function i(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function r(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0});var a=function(){function t(t,e){for(var n=0;n<e.length;n++){var i=e[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,n,i){return n&&t(e.prototype,n),i&&t(e,i),e}}(),l=n(1),u=i(l),c=n(5),d=i(c),h=n(2),p=function(t){function e(t){o(this,e);var n=r(this,Object.getPrototypeOf(e).call(this,t));return n.canUseDOM=(0,h.canUseDOM)(),n.ReactDOM=d["default"].findDOMNode?d["default"]:u["default"],n.node=null,n.state={splitChildren:n.getSplitChildren(t)},n.windowHeight=(0,h.getWindowHeight)(n.canUseDOM),n.childStyle=n.getChildStyle(),n.timestamp=Date.now(),n.autobind(),n}return s(e,t),a(e,[{key:"componentWillReceiveProps",value:function(t){this.setState({splitChildren:this.getSplitChildren(t)})}},{key:"autobind",value:function(){this.onScroll=this.onScroll.bind(this),this.onWindowResize=this.onWindowResize.bind(this),this.updatePosition=this.updatePosition.bind(this),this.onWindowLoad=this.onWindowLoad.bind(this)}},{key:"render",value:function(){var t=this;return u["default"].createElement("div",{className:"react-parallax "+(this.props.className?this.props.className:"")},this.props.bgImage?u["default"].createElement("img",{className:"react-parallax-bgimage",src:this.props.bgImage,ref:"bgImage",alt:""}):"",this.state.splitChildren.bgChildren.length>0?u["default"].createElement("div",{className:"react-parallax-background-children",ref:function(e){return t.bgMounted(e)}},this.state.splitChildren.bgChildren):"",u["default"].createElement("div",{className:"react-parallax-content",style:this.childStyle,ref:"content"},this.state.splitChildren.children))}},{key:"componentWillUnmount",value:function(){this.canUseDOM&&(document.removeEventListener("scroll",this.onScroll,!1),window.removeEventListener("resize",this.onWindowResize,!1),window.removeEventListener("load",this.onWindowLoad,!1))}},{key:"componentDidMount",value:function(){this.canUseDOM&&(document.addEventListener("scroll",this.onScroll,!1),window.addEventListener("resize",this.onWindowResize,!1),window.addEventListener("load",this.onWindowLoad,!1)),this.node=this.ReactDOM.findDOMNode(this),this.img=this.refs.bgImage?this.ReactDOM.findDOMNode(this.refs.bgImage):null,this.updatePosition(),this.setParallaxStyle(),this.setInitialBackgroundStyles(this.img),this.setInitialBackgroundStyles(this.bg)}},{key:"bgMounted",value:function(t){this.bg=this.ReactDOM.findDOMNode(t)}},{key:"onScroll",value:function(t){if(this.canUseDOM){var e=Date.now();e-this.timestamp>=10&&(0,h.isScrolledIntoView)(this.node,this.canUseDOM)&&(window.requestAnimationFrame(this.updatePosition),this.timestamp=e)}}},{key:"onWindowLoad",value:function(){this.updatePosition()}},{key:"getSplitChildren",value:function(t){var e=[],n=u["default"].Children.toArray(t.children);return n.forEach(function(t,i){t.type&&t.type.prototype&&t.type.prototype.isParallaxBackground&&(e=e.concat(n.splice(i,1)))}),{bgChildren:e,children:n}}},{key:"updatePosition",value:function(){var t=!1,e=this.ReactDOM.findDOMNode(this.refs.content);this.contentHeight=e.getBoundingClientRect().height,this.contentWidth=this.node.getBoundingClientRect().width,this.img&&this.img.naturalWidth/this.img.naturalHeight<this.contentWidth/(this.contentHeight+this.props.strength)&&(t=!0);var n=this.node.getBoundingClientRect();n&&this.img&&this.setImagePosition(n.top,t),n&&this.bg&&this.state.splitChildren.bgChildren.length>0&&this.setBackgroundPosition(n.top)}},{key:"setImagePosition",value:function(t){var e=arguments.length<=1||void 0===arguments[1]?!1:arguments[1],n=this.props.bgHeight||(e?"auto":Math.floor(this.contentHeight+Math.abs(this.props.strength))+"px"),i=this.props.bgWidth||(e?this.contentWidth+"px":"auto");if(this.props.disabled!==!0){var o=o=-1*Math.floor((t+this.contentHeight-.25*this.props.strength)/this.windowHeight*this.props.strength);this.img.style.WebkitTransform="translate3d(-50%, "+o+"px, 0)",this.img.style.transform="translate3d(-50%, "+o+"px, 0)",this.img.style.height=n,this.img.style.width=i,this.props.blur&&(this.img.style.WebkitFilter="blur("+this.props.blur+"px)",this.img.style.filter="blur("+this.props.blur+"px)")}}},{key:"setBackgroundPosition",value:function(t){var e=e=-1*Math.floor((t+this.contentHeight-.25*this.props.strength)/this.windowHeight*this.props.strength);this.bg.style.WebkitTransform="translate3d(-50%, "+e+"px, 0)",this.bg.style.transform="translate3d(-50%, "+e+"px, 0)"}},{key:"setInitialBackgroundStyles",value:function(t){t&&(t.style.position="absolute",t.style.left="50%",t.style.WebkitTransformStyle="preserve-3d",t.style.WebkitBackfaceVisibility="hidden",t.style.MozBackfaceVisibility="hidden",t.style.MsBackfaceVisibility="hidden")}},{key:"onWindowResize",value:function(){this.windowHeight=(0,h.getWindowHeight)(this.canUseDOM),this.updatePosition()}},{key:"setParallaxStyle",value:function(){this.node&&(this.node.style.position="relative",this.node.style.overflow="hidden")}},{key:"getChildStyle",value:function(){return{position:"relative"}}},{key:"log",value:function(){this.props.log&&console.log(arguments)}}]),e}(u["default"].Component);p.propTypes={bgImage:u["default"].PropTypes.string,bgWidth:u["default"].PropTypes.string,bgHeight:u["default"].PropTypes.string,strength:u["default"].PropTypes.number,blur:u["default"].PropTypes.number},p.defaultProps={strength:100,blur:0,log:!1,disabled:!1},e["default"]=p},function(t,n){t.exports=e}])});<|endoftext|>


<commit_before><commit_msg>updated build.<commit_after><|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Geocell = mongoose.model('Geocell');
var zips = require('./zip.json');
var constants = require('../constants.json');
var geolib = require('geolib');
var lib = require('../lib');
var fs = require('fs');
var writer = fs.createWriteStream('cells.json');
writer.write('[');

function convertToGeoCoordinates(shpCoordinates) {
  return shpCoordinates.map(function (point) {
    return { latitude: point[0], longitude: point[1] };
  });
}

function maxmin(coordinates, fn) {
  return coordinates.reduce(function (a, b) {
    return { latitude: fn(a.latitude, b.latitude), longitude: fn(a.longitude, b.longitude) };
  });
}

function latDivisions() {
  return (constants.latitude.max - constants.latitude.min) / Math.pow(4, constants.granularity);
}

function lngDivisions() {
  return (constants.longitude.max - constants.longitude.min) / Math.pow(4, constants.granularity);
}

var take10 = zips.slice(0, 20);

take10.forEach(function (obj) {
  console.log(obj.zip);
  var coords = convertToGeoCoordinates(obj.coordinates[0]);
  var min = maxmin(coords, Math.min);
  var max = maxmin(coords, Math.max);
  var latDiv = latDivisions();
  var lngDiv = lngDivisions();
  var cells = [];
  for (var lat = min.latitude; lat < max.latitude; lat += latDiv) {
    for (var lng = min.longitude; lng < max.longitude; lng += lngDiv) {
      var cell = lib.getCell(lat, lng, constants.granularity);
      if (geolib.isPointInside(cell.min, coords) || geolib.isPointInside(cell.max, coords)) {
        cells.push(cell);
      }
    }
  }

  // instead of writing to a file this could be commited to db
  if (cells.length > 0) { // don't add empty cells
    var zipCell = { zip: obj.zip, geocells: cells };
    var stream = JSON.stringify(zipCell, null, 2);
    stream += ',';
    writer.write(stream);
    zipCell.save(function (err) {
      if (err) {
        console.log('Failed to save geocell for:', obj.zip);
      }
    });
  }
});

writer.write(']');
writer.end();
<commit_msg>Move db connection to the script.<commit_after>var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/geocell_dev');
var Geocell = mongoose.model('Geocell');
var zips = require('./zip.json');
var constants = require('../constants.json');
var geolib = require('geolib');
var lib = require('../lib');
var fs = require('fs');
var writer = fs.createWriteStream('cells.json');
writer.write('[');

function convertToGeoCoordinates(shpCoordinates) {
  return shpCoordinates.map(function (point) {
    return { latitude: point[0], longitude: point[1] };
  });
}

function maxmin(coordinates, fn) {
  return coordinates.reduce(function (a, b) {
    return { latitude: fn(a.latitude, b.latitude), longitude: fn(a.longitude, b.longitude) };
  });
}

function latDivisions() {
  return (constants.latitude.max - constants.latitude.min) / Math.pow(4, constants.granularity);
}

function lngDivisions() {
  return (constants.longitude.max - constants.longitude.min) / Math.pow(4, constants.granularity);
}

var take10 = zips.slice(0, 20);

take10.forEach(function (obj) {
  console.log(obj.zip);
  var coords = convertToGeoCoordinates(obj.coordinates[0]);
  var min = maxmin(coords, Math.min);
  var max = maxmin(coords, Math.max);
  var latDiv = latDivisions();
  var lngDiv = lngDivisions();
  var cells = [];
  for (var lat = min.latitude; lat < max.latitude; lat += latDiv) {
    for (var lng = min.longitude; lng < max.longitude; lng += lngDiv) {
      var cell = lib.getCell(lat, lng, constants.granularity);
      if (geolib.isPointInside(cell.min, coords) || geolib.isPointInside(cell.max, coords)) {
        cells.push(cell);
      }
    }
  }

  // instead of writing to a file this could be commited to db
  if (cells.length > 0) { // don't add empty cells
    var zipCell = { zip: obj.zip, geocells: cells };
    var stream = JSON.stringify(zipCell, null, 2);
    stream += ',';
    writer.write(stream);
    zipCell.save(function (err) {
      if (err) {
        console.log('Failed to save geocell for:', obj.zip);
      }
    });
  }
});

writer.write(']');
writer.end();
<|endoftext|>


<commit_before>'use strict';
const net = require('net');
const EventEmitter = require('events').EventEmitter;

String.prototype.withTerminator = function withTerminator () {
    return `${this.toString()}\n`;
};

String.prototype.sanitized = function sanitized () {
    return this.toString().trim().toLowerCase().replace('\r', '');
};

const getMillisecondsTillNextTurnFromServerResponse = (waitingResponse) => {
    const waitingRegex = /^waiting (.+)$/;
    const [, timeTillNextTurnInSeconds] = waitingRegex.exec(waitingResponse);

    return parseFloat(timeTillNextTurnInSeconds) * 1000;
};

const getErrorFromServerResponse = (errorResponse) => {
    const errorRegex = /^failed (\d+) ([\w|\s]+)$/;
    const [, code, message] = errorRegex.exec(errorResponse);

    return {
        code,
        message
    };
};

let turn = 1;

const dl24client = ({port, host, username, password}, gameLoop) => {
    const eventEmitter = new EventEmitter();
    const connection = net.createConnection(port, host);
    connection.setEncoding('utf8');

    const emitDebug = (debugData, description) => {
        eventEmitter.emit('debug', {
            description,
            debugData
        });
    };

    const startGameLoop = (service) => {
        console.log(`turn ${turn++}`);
        gameLoop(service);
    };

    const service = {
        singleLineResponseQuery (query, callback) {
            let responseLine = '';
            let waitingTillNextTurn = false;

            connection.on('data', function commandHandler (data) {
                if (data === '\n') {
                    return;
                }

                const saneData = data.sanitized();

                if (saneData.startsWith('failed')) {
                    connection.removeListener('data', commandHandler);

                    setTimeout(startGameLoop.bind(null, service), 1000);
                    eventEmitter.emit('error', getErrorFromServerResponse(saneData));

                    return;
                }

                if (waitingTillNextTurn && saneData === 'ok') {
                    connection.removeListener('data', commandHandler);
                    startGameLoop(service);

                    return;
                }

                if (saneData.startsWith('ok')) {
                    responseLine = saneData.split('\n').map((line) => line.sanitized()).slice(1)[0];
                } else {
                    responseLine = saneData;
                }

                if (responseLine && responseLine.startsWith('waiting')) {
                    emitDebug({d: 'waitingTillNextTurn', responseLine});
                    waitingTillNextTurn = true;
                    const millisecondsTillNextTurn = getMillisecondsTillNextTurnFromServerResponse(responseLine);

                    eventEmitter.emit('waiting', millisecondsTillNextTurn);

                    return;
                }

                if (responseLine) {
                    connection.removeListener('data', commandHandler);
                    eventEmitter.emit('receivedFromServer', responseLine, query);
                    callback(responseLine);

                    return;
                }
            });

            connection.write(query.withTerminator(), () => eventEmitter.emit('sentToServer', query));
        },
        multilineResponseQuery (query, expectedNumberOfLines, callback) {
            let lines = [];

            connection.on('data', function commandHandler (data) {
                if (data === '\n') {
                    return;
                }

                const saneData = data.sanitized();

                if (saneData.startsWith('failed')) {
                    connection.removeListener('data', commandHandler);

                    setTimeout(gameLoop.bind(null, service), 1000);
                    eventEmitter.emit('error', getErrorFromServerResponse(saneData));

                    return;
                }

                if (saneData.startsWith('ok')) {
                    const responseLines = saneData.split('\n').map((line) => line.sanitized()).slice(1);
                    const numberOfExpectedLines = parseInt(
                        expectedNumberOfLines || responseLines[0], 10);
                    if (numberOfExpectedLines === 0) {
                        connection.removeListener('data', commandHandler);
                        eventEmitter.emit('receivedFromServer', lines, query);
                        callback(lines);
                    }
                    if (!expectedNumberOfLines) {
                        lines = responseLines.slice(1);
                    } else {
                        lines = responseLines;
                    }
                } else {
                    const responseLines = saneData.split('\n').map((line) => line.sanitized());
                    const numberOfExpectedLines = parseInt(
                        expectedNumberOfLines || responseLines[0],
                        10);
                    if (numberOfExpectedLines === 0) {
                        connection.removeListener('data', commandHandler);
                        eventEmitter.emit('receivedFromServer', lines, query);
                        callback(lines);
                    }
                    if (!expectedNumberOfLines) {
                        lines = responseLines.slice(1);
                    } else {
                        lines = responseLines;
                    }
                }

                if (lines.length) {
                    connection.removeListener('data', commandHandler);
                    eventEmitter.emit('receivedFromServer', lines, query);
                    callback(lines);

                    return;
                }
            });

            connection.write(query.withTerminator(), () => eventEmitter.emit('sentToServer', query));
        },
        nextTurn () {
            this.singleLineResponseQuery('wait', () => {});
        },
        command ({serverCommand, args}, callback) {
            if (!args.length) {
                callback();

                return;
            }

            let expectedOks = args.length;
            let waitingTillNextTurn = false;

            connection.on('data', function commandHandler (data) {
                if (data === '\n') {
                    return;
                }

                const saneData = data.sanitized();

                if (saneData.startsWith('failed')) {
                    connection.removeListener('data', commandHandler);

                    setTimeout(startGameLoop.bind(null, service), 1000);
                    eventEmitter.emit('error', getErrorFromServerResponse(saneData));

                    return;
                }

                if (waitingTillNextTurn && saneData === 'ok') {
                    connection.removeListener('data', commandHandler);
                    startGameLoop(service);

                    return;
                }

                if (saneData.startsWith('waiting')) {
                    emitDebug({d: 'waitingTillNextTurn', saneData});
                    waitingTillNextTurn = true;
                    const millisecondsTillNextTurn = getMillisecondsTillNextTurnFromServerResponse(saneData);

                    eventEmitter.emit('waiting', millisecondsTillNextTurn);

                    return;
                }

                const oks = saneData.split('\n').map((line) => line.sanitized());

                if (oks.find(ok => ok !== 'ok')) {
                    eventEmitter.emit('error', {description: 'expected only oks after command wtf, fuck that, starting next turn immediately xD', oks});

                    connection.removeListener('data', commandHandler);
                    startGameLoop(service);
                }

                expectedOks -= oks.length;

                if (expectedOks === 0) {
                    connection.removeListener('data', commandHandler);
                    callback();

                    return;
                }
            });

            args.forEach(arg => {
                const commandWithArgs = `${serverCommand} ${arg}`;
                connection.write(commandWithArgs.withTerminator(), () => eventEmitter.emit('sentToServer', commandWithArgs));
            });
        },
        weirdShit ({serverCommand, args, expectedNumberOfLines}, callback) {

        }
    };

    connection.on('data', function loginHandler (data) {
        if (data.sanitized() === 'login') {
            connection.write(username.withTerminator(), () => eventEmitter.emit('sentToServer', username));

            return;
        }

        if (data.sanitized() === 'pass') {
            connection.write(password.withTerminator(), () => eventEmitter.emit('sentToServer', password));

            return;
        }

        if (data.sanitized() === 'ok') {
            connection.removeListener('data', loginHandler);
            startGameLoop(service);
        }
    });

    connection.on('data', (data) => {
        eventEmitter.emit('rawData', {rawData: data, sanitized: data.sanitized()});
    });

    connection.on('error', (error) => {
        console.log('error', error);
    });

    connection.on('close', () => {
        console.log('connection closed wtf');
    });

    return eventEmitter;
};

module.exports = dl24client;
<commit_msg>refactored the singleQuery to use multipleQuery with argument`1`<commit_after>'use strict';
const net = require('net');
const EventEmitter = require('events').EventEmitter;

String.prototype.withTerminator = function withTerminator () {
    return `${this.toString()}\n`;
};

String.prototype.sanitized = function sanitized () {
    return this.toString().trim().toLowerCase().replace('\r', '');
};

const getMillisecondsTillNextTurnFromServerResponse = (waitingResponse) => {
    const waitingRegex = /^waiting (.+)$/;
    const [, timeTillNextTurnInSeconds] = waitingRegex.exec(waitingResponse);

    return parseFloat(timeTillNextTurnInSeconds) * 1000;
};

const getErrorFromServerResponse = (errorResponse) => {
    const errorRegex = /^failed (\d+) ([\w|\s]+)$/;
    const [, code, message] = errorRegex.exec(errorResponse);

    return {
        code,
        message
    };
};

let turn = 1;

const dl24client = ({port, host, username, password}, gameLoop) => {
    const eventEmitter = new EventEmitter();
    const waitTillNextTurn = (waitResponse, connection, commandHandler, callback) => {
        connection.removeListener('data', commandHandler);
        const millisecondsTillNextTurn = getMillisecondsTillNextTurnFromServerResponse(waitResponse);

        eventEmitter.emit('waiting', millisecondsTillNextTurn);

        connection.on('data', function waitingHandler (waitingData) {
            if (waitingData === '\n') {
                return;
            }

            connection.removeListener('data', waitingHandler);
            if (waitingData.sanitized() !== 'ok') {
                eventEmitter.emit('error', `was waiting for next turn, got ${waitingData}`);
            }

            callback();
        });

        return;
    };

    const connection = net.createConnection(port, host);
    connection.setEncoding('utf8');

    const emitDebug = (debugData, description) => {
        eventEmitter.emit('debug', {
            description,
            debugData
        });
    };

    const startGameLoop = (service) => {
        console.log(`turn ${turn++}`);
        gameLoop(service);
    };

    const service = {
        singleLineResponseQuery (query, callback) {
            this.multilineResponseQuery(query, 1, arrayResponse => {
                const [response] = arrayResponse;

                callback(response);
            });
        },
        multilineResponseQuery (query, expectedNumberOfLines, callback) {
            let lines = [];

            connection.on('data', function commandHandler (data) {
                if (data === '\n') {
                    return;
                }

                const saneData = data.sanitized();

                if (saneData.startsWith('waiting')) {
                    waitTillNextTurn(saneData, connection, commandHandler, startGameLoop.bind(null, service));

                    return;
                }

                if (saneData.startsWith('failed')) {
                    connection.removeListener('data', commandHandler);

                    setTimeout(gameLoop.bind(null, service), 1000);
                    eventEmitter.emit('error', getErrorFromServerResponse(saneData));

                    return;
                }

                const handleMultipleLines = (responseLines) => {
                    const waitResponse = responseLines.find(line => line.startsWith('waiting'));

                    if (waitResponse) {
                        waitTillNextTurn(waitResponse, connection, commandHandler, startGameLoop.bind(null, service));
                    }

                    const numberOfExpectedLines = parseInt(expectedNumberOfLines || responseLines[0], 10);
                    if (numberOfExpectedLines === 0) {
                        connection.removeListener('data', commandHandler);
                        eventEmitter.emit('receivedFromServer', lines, query);
                        callback(lines);
                    }
                    if (!expectedNumberOfLines) {
                        lines = responseLines.slice(1);
                    } else {
                        lines = responseLines;
                    }
                };

                if (saneData.startsWith('ok')) {
                    handleMultipleLines(
                        saneData.split('\n').map((line) => line.sanitized()).slice(1)
                    );
                } else {
                    handleMultipleLines(
                        saneData.split('\n').map((line) => line.sanitized())
                    );
                }

                if (lines.length) {
                    connection.removeListener('data', commandHandler);
                    eventEmitter.emit('receivedFromServer', lines, query);
                    callback(lines);

                    return;
                }
            });

            connection.write(query.withTerminator(), () => eventEmitter.emit('sentToServer', query));
        },
        nextTurn () {
            this.singleLineResponseQuery('wait', () => {});
        },
        command ({serverCommand, args}, callback) {
            if (!args.length) {
                callback();

                return;
            }

            let expectedOks = args.length;

            connection.on('data', function commandHandler (data) {
                if (data === '\n') {
                    return;
                }

                const saneData = data.sanitized();

                if (saneData.startsWith('failed')) {
                    connection.removeListener('data', commandHandler);

                    setTimeout(startGameLoop.bind(null, service), 1000);
                    eventEmitter.emit('error', getErrorFromServerResponse(saneData));

                    return;
                }

                if (saneData.startsWith('waiting')) {
                    waitTillNextTurn(saneData, connection, commandHandler, startGameLoop.bind(null, service));
                    return;
                }

                const oks = saneData.split('\n').map((line) => line.sanitized());

                if (oks.find(ok => ok !== 'ok')) {
                    eventEmitter.emit('error', {description: 'expected only oks after command wtf, fuck that, starting next turn immediately xD', oks});

                    connection.removeListener('data', commandHandler);
                    startGameLoop(service);
                }

                expectedOks -= oks.length;

                if (expectedOks === 0) {
                    connection.removeListener('data', commandHandler);
                    callback();

                    return;
                }
            });

            args.forEach(arg => {
                const commandWithArgs = `${serverCommand} ${arg}`;
                connection.write(commandWithArgs.withTerminator(), () => eventEmitter.emit('sentToServer', commandWithArgs));
            });
        },
        weirdShit ({serverCommand, args, expectedNumberOfLines}, callback) {

        }
    };

    connection.on('data', function loginHandler (data) {
        if (data.sanitized() === 'login') {
            connection.write(username.withTerminator(), () => eventEmitter.emit('sentToServer', username));

            return;
        }

        if (data.sanitized() === 'pass') {
            connection.write(password.withTerminator(), () => eventEmitter.emit('sentToServer', password));

            return;
        }

        if (data.sanitized() === 'ok') {
            connection.removeListener('data', loginHandler);
            startGameLoop(service);
        }
    });

    connection.on('data', (data) => {
        eventEmitter.emit('rawData', {rawData: data, sanitized: data.sanitized()});
    });

    connection.on('error', (error) => {
        console.log('error', error);
    });

    connection.on('close', () => {
        console.log('connection closed wtf');
    });

    return eventEmitter;
};

module.exports = dl24client;
<|endoftext|>


<commit_before>var OsomDatepicker = (function(){

	"use strict";

	var OsomDatepickerPrivate = function(options){
		this.options = options;
		this.selectedDates = this.options.selectedDates || [new Date()];
		this.selectedDates.forEach(function(date){
			Helper.resetTime(date);
		});
		this.currentMonth = 0;
		this.centralMonth = 0;
		this.firstMonth = -1;
		this.lastMonth = 1;
		this.multipleDays = this.selectedDates.length > 1 ? true : false;
		this.uniqueId = Date.now();
	};

	OsomDatepickerPrivate.prototype = {

		wrapperClass: 'osom-datepicker-wrapper',
		containerClass: 'osom-datepicker-container',
		sliderClass: 'osom-datepicker-slider',
		monthClass: 'osom-datepicker-month',
		dayClass: 'osom-datepicker-day',
		dayDisabledClass: 'osom-datepicker-daydisabled',
		selectedDayClass: 'osom-datepicker-selectedday',
		animatedClass: 'osom-datepicker-animated',
		upButtonClass: 'osom-datepicker-upbutton',
		downButtonClass: 'osom-datepicker-downbutton',
		multipleDaysClass: 'osom-datepicker-multipledays',
		layoutVerticalClass: 'osom-datepicker-layoutvertical',
		layoutHorizontalClass: 'osom-datepicker-layouthorizontal',

		events: {
			DATE_SELECTED: 'DATE_SELECTED'
		},

		initialize: function(){
			var html = '';
			this.el = document.querySelector(this.options.selector);

			this.el.classList.add(this.wrapperClass);
			if(this.options.animation === 'horizontal'){
				this.el.classList.add(this.layoutHorizontalClass);
			}else{
				this.el.classList.add(this.layoutVerticalClass);
			}

			html += '
';

			html += '<input type="checkbox" class="' + this.multipleDaysClass + '" name="' + this.multipleDaysClass + '" id="' + this.multipleDaysClass + '-' + this.uniqueId + '" ' + (this.multipleDays ? 'checked="checked"' : '') + ' />';

			html += 'Multiple Days';
			if(this.options.animation === 'horizontal'){
				html += '<button class="' + this.upButtonClass + '">◄</button>';
				html += '<button class="' + this.downButtonClass + '">►</button>';
			}else{
				html += '<button class="' + this.upButtonClass + '">▲</button>';
				html += '<button class="' + this.downButtonClass + '">▼</button>';
			}
			html += '
';

			html += '
';
			html += '
';
			for(var i = -1; i <= 1; i++){
				var date = Helper.addMonth(this.selectedDates[0], i);
				html += this.renderMonth(date);
			}
			html += '
';
			html += '
';

			this.el.innerHTML = html;

			this.bindEvents();
		},

		renderMonth: function(date){
			var html = '';
			var year = date.getMonth()+1 <= 11 ? date.getFullYear() : date.getFullYear()+1;
			var month = date.getMonth()+1 <= 11 ? date.getMonth()+1 : 0;
			var auxDate = new Date(year, month, 0);

			html += '
' + Helper.getMonthName(date.getMonth()) + ' ' + date.getFullYear() + '
';

			html += '
';
			html += 'Mon	Tue	Wed	Thu	Fri	Sat	Sun	';
			html += '
';

			html += '
';
			var dayNumber = 0;
			for(var week = 1; week <= 6; week++){
				var dayOfWeek = 0;
				html += '
';
				do{
					var day = new Date(date.getFullYear(), date.getMonth(), dayNumber+1);
					if(day.getDay() === dayOfWeek && dayNumber <= day.getDate()){
						var classes = this.dayClass;
						html += '';

						if(this.options.fromDate){
							Helper.resetTime(this.options.fromDate);
							if(day < this.options.fromDate){
								classes += ' ' + this.dayDisabledClass;
							}
						}

						if(this.selectedDates.map(Number).indexOf(+day) !== -1){
							classes += ' ' + this.selectedDayClass;
						}

						html += '<button class="' + classes + '" data-date="' + day.getTime() + '">' + day.getDate() + '</button>';
						html += '	';
						dayNumber++;
					}else{
						html += ' 	';
					}
					dayOfWeek++;
				}while(dayOfWeek <= 6);
				html += '
';
			}
			html += '
';
			html += '

';

			return html;
		},

		prevMonth: function(){
			if(!this.animating){
				var self = this;
				this.animating = true;

				this.currentMonth--;
				var slider = this.el.querySelector('.' + this.sliderClass);
				var monthWidth = slider.offsetWidth / slider.children.length;
				var monthHeight = slider.offsetHeight / slider.children.length;
				var sliderStyle = window.getComputedStyle(slider, null);

				if(this.currentMonth < this.firstMonth){
					this.firstMonth = this.currentMonth;

					var date = Helper.addMonth(this.selectedDates[0], this.currentMonth);
					slider.insertAdjacentHTML('afterbegin', this.renderMonth(date));
					if(this.options.animation === 'horizontal'){
						slider.style.left = (parseInt(sliderStyle.left, 10) - monthWidth) + 'px';
						//FORCING REPAINT
						slider.offsetWidth;
					}else{
						slider.style.top = (parseInt(sliderStyle.top, 10) - monthHeight) + 'px';
						//FORCING REPAINT
						slider.offsetHeight;
					}
				}

				slider.classList.add(this.animatedClass);
				if(this.options.animation === 'horizontal'){
					slider.style.left = parseInt(slider.style.left || sliderStyle.left, 10) + monthWidth + 'px';
				}else{
					slider.style.top = parseInt(slider.style.top || sliderStyle.top, 10) + monthHeight + 'px';
				}

				setTimeout(function(){
					self.animating = false;
					slider.classList.remove(self.animatedClass);
				}, 1000);
			}
		},

		nextMonth: function(){
			if(!this.animating){
				var self = this;
				this.animating = true;

				this.currentMonth++;
				var slider = this.el.querySelector('.' + this.sliderClass);
				var monthWidth = slider.offsetWidth / slider.children.length;
				var monthHeight = slider.offsetHeight / slider.children.length;
				var sliderStyle = window.getComputedStyle(slider, null);

				if(this.currentMonth > this.lastMonth){
					this.lastMonth = this.currentMonth;

					var date = Helper.addMonth(this.selectedDates[0], this.currentMonth);
					slider.insertAdjacentHTML('beforeend', this.renderMonth(date));
				}

				slider.classList.add(this.animatedClass);
				if(this.options.animation === 'horizontal'){
					slider.style.left = parseInt(slider.style.left || sliderStyle.left, 10) - monthWidth + 'px';
				}else{
					slider.style.top = parseInt(slider.style.top || sliderStyle.top, 10) - monthHeight + 'px';
				}
				setTimeout(function(){
					self.animating = false;
					slider.classList.remove(self.animatedClass);
				}, 800);
			}
		},

		bindEvents: function(){
			var self = this;
			var upButton = this.el.querySelector('.'+this.upButtonClass);
			var downButton = this.el.querySelector('.'+this.downButtonClass);
			var slider = this.el.querySelector('.' + this.sliderClass);
			var multipleDays = this.el.querySelector('.' + this.multipleDaysClass);

			upButton.addEventListener('click', function(){
				self.prevMonth();
			});

			downButton.addEventListener('click', function(){
				self.nextMonth();
			});

			multipleDays.addEventListener('change', function(){
				self.toggleMultipleDays();
			});

			slider.addEventListener('click', function(e){
				if(e.target.classList.contains(self.dayClass) && !e.target.classList.contains(self.dayDisabledClass)){
					self.handleDayClick(e.target);
				}
			});
		},

		handleDayClick: function(day){
			var self = this;

			if(!this.multipleDays){
				var days = this.el.querySelectorAll('.' + this.selectedDayClass);

				Array.prototype.forEach.call(days, function(d){
					d.classList.remove(self.selectedDayClass);
				});

				this.selectedDates = [new Date(parseInt(day.dataset.date, 10))];
			}else{
				this.selectedDates.push(new Date(parseInt(day.dataset.date, 10)));
			}

			day.classList.toggle(this.selectedDayClass);

			this.dispatchEvent(this.events.DATE_SELECTED, this.selectedDates);
		},

		toggleMultipleDays: function(){
			this.multipleDays = !this.multipleDays;

			if(this.selectedDates.length > 1){
				var day = this.el.querySelector('button[data-date="' + this.selectedDates[0].getTime() + '"]');
				this.handleDayClick(day);
			}
		},

		dispatchEvent: function(type, data){
			var e = new CustomEvent(type, {
				detail: data
			});
			this.el.dispatchEvent(e);
		},

		on: function(type, callback){
			this.el.addEventListener(type, callback);
		},

		off: function(type, callback){
			this.el.removeEventListener(type, callback);
		},

		setDates: function(dates){
			var self = this;
			var checkbox = this.el.querySelector('.' + this.multipleDaysClass);
			var days = this.el.querySelectorAll('.' + this.selectedDayClass);

			Array.prototype.forEach.call(days, function(d){
				d.classList.remove(self.selectedDayClass);
			});

			if(dates.length > 1){
				this.multipleDays = true;
				checkbox.checked = true;
			}else{
				this.multipleDays = false;
				checkbox.checked = false;
			}
			this.selectedDates = dates;

			this.selectedDates.forEach(function(date){
				Helper.resetTime(date);
				var day = self.el.querySelector('button[data-date="' + date.getTime() + '"]');
				day.classList.toggle(self.selectedDayClass);
			});

			this.dispatchEvent(this.events.DATE_SELECTED, this.selectedDates);
		}

	};

	//HELPER
	var Helper = {
		addMonth: function(date, add){
			var newDate = new Date(date.getTime());
			newDate.setDate(1);
			newDate.setMonth(date.getMonth()+add);
			newDate.setDate(date.getDate());

			return newDate;
		},

		getMonthName: function(month){
			var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
			return monthNames[month];
		},

		resetTime: function(date){
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			date.setMilliseconds(0);
		}
	};

	//PUBLIC API
	var datepickerInstance = null;
	var OsomDatepickerPublic = function(options){
		datepickerInstance = new OsomDatepickerPrivate(options);
	}

	OsomDatepickerPublic.prototype = {

		initialize: function(){
			datepickerInstance.initialize();
		},

		on: function(type, callback){
			datepickerInstance.on(type, callback);
		},

		off: function(type, callback){
			datepickerInstance.off(type, callback);
		},

		setDates: function(dates){
			datepickerInstance.setDates(dates);
		}

	};

	return OsomDatepickerPublic;

});

if ( typeof define === "function" && define.amd ) {
	define( "osom-datepicker", [], function() {
		return OsomDatepicker();
	});
}else{
	OsomDatepicker = OsomDatepicker();
}<commit_msg>Fixing - thing<commit_after>var OsomDatepicker = (function(){

	"use strict";

	var OsomDatepickerPrivate = function(options){
		this.options = options;
		this.selectedDates = this.options.selectedDates || [new Date()];
		this.selectedDates.forEach(function(date){
			Helper.resetTime(date);
		});
		this.currentMonth = 0;
		this.centralMonth = 0;
		this.firstMonth = -1;
		this.lastMonth = 1;
		this.multipleDays = this.selectedDates.length > 1 ? true : false;
		this.uniqueId = Date.now();
	};

	OsomDatepickerPrivate.prototype = {

		wrapperClass: 'osom-datepicker-wrapper',
		containerClass: 'osom-datepicker-container',
		sliderClass: 'osom-datepicker-slider',
		monthClass: 'osom-datepicker-month',
		dayClass: 'osom-datepicker-day',
		dayDisabledClass: 'osom-datepicker-daydisabled',
		selectedDayClass: 'osom-datepicker-selectedday',
		animatedClass: 'osom-datepicker-animated',
		upButtonClass: 'osom-datepicker-upbutton',
		downButtonClass: 'osom-datepicker-downbutton',
		multipleDaysClass: 'osom-datepicker-multipledays',
		layoutVerticalClass: 'osom-datepicker-layoutvertical',
		layoutHorizontalClass: 'osom-datepicker-layouthorizontal',

		events: {
			DATE_SELECTED: 'DATE_SELECTED'
		},

		initialize: function(){
			var html = '';
			this.el = document.querySelector(this.options.selector);

			this.el.classList.add(this.wrapperClass);
			if(this.options.animation === 'horizontal'){
				this.el.classList.add(this.layoutHorizontalClass);
			}else{
				this.el.classList.add(this.layoutVerticalClass);
			}

			html += '
';

			html += '<input type="checkbox" class="' + this.multipleDaysClass + '" name="' + this.multipleDaysClass + '" id="' + this.multipleDaysClass + '-' + this.uniqueId + '" ' + (this.multipleDays ? 'checked="checked"' : '') + ' />';

			html += 'Multiple Days';
			if(this.options.animation === 'horizontal'){
				html += '<button class="' + this.upButtonClass + '">◄</button>';
				html += '<button class="' + this.downButtonClass + '">►</button>';
			}else{
				html += '<button class="' + this.upButtonClass + '">▲</button>';
				html += '<button class="' + this.downButtonClass + '">▼</button>';
			}
			html += '
';

			html += '
';
			html += '
';
			for(var i = -1; i <= 1; i++){
				var date = Helper.addMonth(this.selectedDates[0], i);
				html += this.renderMonth(date);
			}
			html += '
';
			html += '
';

			this.el.innerHTML = html;

			this.bindEvents();
		},

		renderMonth: function(date){
			var html = '';
			var year = date.getMonth()+1 <= 11 ? date.getFullYear() : date.getFullYear()+1;
			var month = date.getMonth()+1 <= 11 ? date.getMonth()+1 : 0;
			var auxDate = new Date(year, month, 0);

			html += '
' + Helper.getMonthName(date.getMonth()) + ' ' + date.getFullYear() + '
';

			html += '
';
			html += 'Mon	Tue	Wed	Thu	Fri	Sat	Sun	';
			html += '
';

			html += '
';
			var dayNumber = 0;
			for(var week = 1; week <= 6; week++){
				var dayOfWeek = 0;
				html += '
';
				do{
					var day = new Date(date.getFullYear(), date.getMonth(), dayNumber+1);
					if(day.getDay() === dayOfWeek && dayNumber <= day.getDate()){
						var classes = this.dayClass;
						html += '';

						if(this.options.fromDate){
							Helper.resetTime(this.options.fromDate);
							if(day < this.options.fromDate){
								classes += ' ' + this.dayDisabledClass;
							}
						}

						if(this.selectedDates.map(Number).indexOf(+day) !== -1){
							classes += ' ' + this.selectedDayClass;
						}

						html += '<button class="' + classes + '" data-date="' + day.getTime() + '">' + day.getDate() + '</button>';
						html += '	';
						dayNumber++;
					}else{
						html += ' 	';
					}
					dayOfWeek++;
				}while(dayOfWeek <= 6);
				html += '
';
			}
			html += '
';
			html += '

';

			return html;
		},

		prevMonth: function(){
			if(!this.animating){
				var self = this;
				this.animating = true;

				this.currentMonth--;
				var slider = this.el.querySelector('.' + this.sliderClass);
				var monthWidth = slider.offsetWidth / slider.children.length;
				var monthHeight = slider.offsetHeight / slider.children.length;
				var sliderStyle = window.getComputedStyle(slider, null);

				if(this.currentMonth < this.firstMonth){
					this.firstMonth = this.currentMonth;

					var date = Helper.addMonth(this.selectedDates[0], this.currentMonth);
					slider.insertAdjacentHTML('afterbegin', this.renderMonth(date));
					if(this.options.animation === 'horizontal'){
						slider.style.left = (parseInt(sliderStyle.left, 10) - monthWidth) + 'px';
						//FORCING REPAINT
						slider.offsetWidth;
					}else{
						slider.style.top = (parseInt(sliderStyle.top, 10) - monthHeight) + 'px';
						//FORCING REPAINT
						slider.offsetHeight;
					}
				}

				slider.classList.add(this.animatedClass);
				if(this.options.animation === 'horizontal'){
					slider.style.left = parseInt(slider.style.left || sliderStyle.left, 10) + monthWidth + 'px';
				}else{
					slider.style.top = parseInt(slider.style.top || sliderStyle.top, 10) + monthHeight + 'px';
				}

				setTimeout(function(){
					self.animating = false;
					slider.classList.remove(self.animatedClass);
				}, 1000);
			}
		},

		nextMonth: function(){
			if(!this.animating){
				var self = this;
				this.animating = true;

				this.currentMonth++;
				var slider = this.el.querySelector('.' + this.sliderClass);
				var monthWidth = slider.offsetWidth / slider.children.length;
				var monthHeight = slider.offsetHeight / slider.children.length;
				var sliderStyle = window.getComputedStyle(slider, null);

				if(this.currentMonth > this.lastMonth){
					this.lastMonth = this.currentMonth;

					var date = Helper.addMonth(this.selectedDates[0], this.currentMonth);
					slider.insertAdjacentHTML('beforeend', this.renderMonth(date));
				}

				slider.classList.add(this.animatedClass);
				if(this.options.animation === 'horizontal'){
					slider.style.left = parseInt(slider.style.left || sliderStyle.left, 10) - monthWidth + 'px';
				}else{
					slider.style.top = parseInt(slider.style.top || sliderStyle.top, 10) - monthHeight + 'px';
				}
				setTimeout(function(){
					self.animating = false;
					slider.classList.remove(self.animatedClass);
				}, 800);
			}
		},

		bindEvents: function(){
			var self = this;
			var upButton = this.el.querySelector('.'+this.upButtonClass);
			var downButton = this.el.querySelector('.'+this.downButtonClass);
			var slider = this.el.querySelector('.' + this.sliderClass);
			var multipleDays = this.el.querySelector('.' + this.multipleDaysClass);

			upButton.addEventListener('click', function(){
				self.prevMonth();
			});

			downButton.addEventListener('click', function(){
				self.nextMonth();
			});

			multipleDays.addEventListener('change', function(){
				self.toggleMultipleDays();
			});

			slider.addEventListener('click', function(e){
				if(e.target.classList.contains(self.dayClass) && !e.target.classList.contains(self.dayDisabledClass)){
					self.handleDayClick(e.target);
				}
			});
		},

		handleDayClick: function(day){
			var self = this;

			if(!this.multipleDays){
				var days = this.el.querySelectorAll('.' + this.selectedDayClass);

				Array.prototype.forEach.call(days, function(d){
					d.classList.remove(self.selectedDayClass);
				});

				this.selectedDates = [new Date(parseInt(day.dataset.date, 10))];
			}else{
				this.selectedDates.push(new Date(parseInt(day.dataset.date, 10)));
			}

			day.classList.toggle(this.selectedDayClass);

			this.dispatchEvent(this.events.DATE_SELECTED, this.selectedDates);
		},

		toggleMultipleDays: function(){
			this.multipleDays = !this.multipleDays;

			if(this.selectedDates.length > 1){
				var day = this.el.querySelector('button[data-date="' + this.selectedDates[0].getTime() + '"]');
				this.handleDayClick(day);
			}
		},

		dispatchEvent: function(type, data){
			var e = new CustomEvent(type, {
				detail: data
			});
			this.el.dispatchEvent(e);
		},

		on: function(type, callback){
			this.el.addEventListener(type, callback);
		},

		off: function(type, callback){
			this.el.removeEventListener(type, callback);
		},

		setDates: function(dates){
			var self = this;
			var checkbox = this.el.querySelector('.' + this.multipleDaysClass);
			var days = this.el.querySelectorAll('.' + this.selectedDayClass);

			Array.prototype.forEach.call(days, function(d){
				d.classList.remove(self.selectedDayClass);
			});

			if(dates.length > 1){
				this.multipleDays = true;
				checkbox.checked = true;
			}else{
				this.multipleDays = false;
				checkbox.checked = false;
			}
			this.selectedDates = dates;

			this.selectedDates.forEach(function(date){
				Helper.resetTime(date);
				var day = self.el.querySelector('button[data-date="' + date.getTime() + '"]');
				day.classList.toggle(self.selectedDayClass);
			});

			this.dispatchEvent(this.events.DATE_SELECTED, this.selectedDates);
		}

	};

	//HELPER
	var Helper = {
		addMonth: function(date, add){
			var newDate = new Date(date.getTime());
			newDate.setDate(1);
			newDate.setMonth(date.getMonth()+add);
			newDate.setDate(date.getDate());

			return newDate;
		},

		getMonthName: function(month){
			var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
			return monthNames[month];
		},

		resetTime: function(date){
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			date.setMilliseconds(0);
		}
	};

	//PUBLIC API
	var datepickerInstance = null;
	var OsomDatepickerPublic = function(options){
		datepickerInstance = new OsomDatepickerPrivate(options);
	}

	OsomDatepickerPublic.prototype = {

		initialize: function(){
			datepickerInstance.initialize();
		},

		on: function(type, callback){
			datepickerInstance.on(type, callback);
		},

		off: function(type, callback){
			datepickerInstance.off(type, callback);
		},

		setDates: function(dates){
			datepickerInstance.setDates(dates);
		}

	};

	return OsomDatepickerPublic;

});

if ( typeof define === "function" && define.amd ) {
	define( "osomdatepicker", [], function() {
		return OsomDatepicker();
	});
}else{
	OsomDatepicker = OsomDatepicker();
}<|endoftext|>


<commit_before>(function (window, smoothScroll) {
  'use strict';

  // Support RequireJS and CommonJS/NodeJS module formats.
  // Attach smoothScroll to the `window` when executed as a <script>.

  // RequireJS
  if (typeof define === 'function' && define.amd) {
    define(smoothScroll);

  // CommonJS
  } else if (typeof exports === 'object' && typeof module === 'object') {
    module.exports = smoothScroll();

  // <script>
  } else if (typeof window === 'object') {
    window.smoothScroll = smoothScroll();

  // Do not initialize smoothScroll when running server side, handle it in client:
  } else {
    return;
  }

})(window, function(){
'use strict';

// We do not want this script to be applied in browsers that do not support those
// That means no smoothscroll on IE9 and below.
if(document.querySelectorAll === void 0 || window.pageYOffset === void 0 || history.pushState === void 0) { return; }

// Get the top position of an element in the document
var getTop = function(element) {
    // return value of html.getBoundingClientRect().top ... IE : 0, other browsers : -pageYOffset
    if(element.nodeName === 'HTML') return -window.pageYOffset
    return element.getBoundingClientRect().top + window.pageYOffset;
}
// ease in out function thanks to:
// http://blog.greweb.fr/2012/02/bezier-curve-based-easing-functions-from-concept-to-implementation/
var easeInOutCubic = function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1 }

// calculate the scroll position we should be in
// given the start and end point of the scroll
// the time elapsed from the beginning of the scroll
// and the total duration of the scroll (default 500ms)
var position = function(start, end, elapsed, duration) {
    if (elapsed > duration) return end;
    return start + (end - start) * easeInOutCubic(elapsed / duration); // <-- you can change the easing funtion there
    // return start + (end - start) * (elapsed / duration); // <-- this would give a linear scroll
}

// we use requestAnimationFrame to be called by the browser before every repaint
// if the first argument is an element then scroll to the top of this element
// if the first argument is numeric then scroll to this location
// if the callback exist, it is called when the scrolling is finished
var smoothScroll = function(el, duration, callback){
    duration = duration || 500;
    var start = window.pageYOffset;

    if (typeof el === 'number') {
      var end = parseInt(el);
    } else {
      var end = getTop(el);
    }

    var clock = Date.now();
    var requestAnimationFrame = window.requestAnimationFrame ||
        window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ||
        function(fn){window.setTimeout(fn, 15);};

    var step = function(){
        var elapsed = Date.now() - clock;
        window.scroll(0, position(start, end, elapsed, duration));
        if (elapsed > duration) {
            if (typeof callback === 'function') {
                callback(el);
            }
        } else {
            requestAnimationFrame(step);
        }
    }
    step();
}

var linkHandler = function(ev) {
    ev.preventDefault();

    if (location.hash !== this.hash) window.history.pushState(null, null, this.hash)
    // using the history api to solve issue #1 - back doesn't work
    // most browser don't update :target when the history api is used:
    // THIS IS A BUG FROM THE BROWSERS.
    // change the scrolling duration in this call
    smoothScroll(document.getElementById(this.hash.substring(1)), 500, function(el) {
        location.replace('#' + el.id)
        // this will cause the :target to be activated.
    });
}

// We look for all the internal links in the documents and attach the smoothscroll function
document.addEventListener("DOMContentLoaded", function () {
    var internal = document.querySelectorAll('a[href^="#"]:not([href="#"])'), a;
    for(var i=internal.length; a=internal[--i];){
        a.addEventListener("click", linkHandler, false);
    }
});

// return smoothscroll API
return smoothScroll;

});
<commit_msg>Fix isomorphic support<commit_after>(function (window, smoothScroll) {
  'use strict';

  // Support RequireJS and CommonJS/NodeJS module formats.
  // Attach smoothScroll to the `window` when executed as a <script>.

  // RequireJS
  if (typeof define === 'function' && define.amd) {
    define(smoothScroll);

  // CommonJS
  } else if (typeof exports === 'object' && typeof module === 'object') {
    module.exports = smoothScroll();

  // <script>
  } else if (typeof window === 'object') {
    window.smoothScroll = smoothScroll();

  // Do not initialize smoothScroll when running server side, handle it in client:
  } else {
    return;
  }

})(this, function(){
'use strict';

// Do not initialize smoothScroll when running server side, handle it in client:
if (typeof window !== 'object') return;

// We do not want this script to be applied in browsers that do not support those
// That means no smoothscroll on IE9 and below.
if(document.querySelectorAll === void 0 || window.pageYOffset === void 0 || history.pushState === void 0) { return; }

// Get the top position of an element in the document
var getTop = function(element) {
    // return value of html.getBoundingClientRect().top ... IE : 0, other browsers : -pageYOffset
    if(element.nodeName === 'HTML') return -window.pageYOffset
    return element.getBoundingClientRect().top + window.pageYOffset;
}
// ease in out function thanks to:
// http://blog.greweb.fr/2012/02/bezier-curve-based-easing-functions-from-concept-to-implementation/
var easeInOutCubic = function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1 }

// calculate the scroll position we should be in
// given the start and end point of the scroll
// the time elapsed from the beginning of the scroll
// and the total duration of the scroll (default 500ms)
var position = function(start, end, elapsed, duration) {
    if (elapsed > duration) return end;
    return start + (end - start) * easeInOutCubic(elapsed / duration); // <-- you can change the easing funtion there
    // return start + (end - start) * (elapsed / duration); // <-- this would give a linear scroll
}

// we use requestAnimationFrame to be called by the browser before every repaint
// if the first argument is an element then scroll to the top of this element
// if the first argument is numeric then scroll to this location
// if the callback exist, it is called when the scrolling is finished
var smoothScroll = function(el, duration, callback){
    duration = duration || 500;
    var start = window.pageYOffset;

    if (typeof el === 'number') {
      var end = parseInt(el);
    } else {
      var end = getTop(el);
    }

    var clock = Date.now();
    var requestAnimationFrame = window.requestAnimationFrame ||
        window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ||
        function(fn){window.setTimeout(fn, 15);};

    var step = function(){
        var elapsed = Date.now() - clock;
        window.scroll(0, position(start, end, elapsed, duration));
        if (elapsed > duration) {
            if (typeof callback === 'function') {
                callback(el);
            }
        } else {
            requestAnimationFrame(step);
        }
    }
    step();
}

var linkHandler = function(ev) {
    ev.preventDefault();

    if (location.hash !== this.hash) window.history.pushState(null, null, this.hash)
    // using the history api to solve issue #1 - back doesn't work
    // most browser don't update :target when the history api is used:
    // THIS IS A BUG FROM THE BROWSERS.
    // change the scrolling duration in this call
    smoothScroll(document.getElementById(this.hash.substring(1)), 500, function(el) {
        location.replace('#' + el.id)
        // this will cause the :target to be activated.
    });
}

// We look for all the internal links in the documents and attach the smoothscroll function
document.addEventListener("DOMContentLoaded", function () {
    var internal = document.querySelectorAll('a[href^="#"]:not([href="#"])'), a;
    for(var i=internal.length; a=internal[--i];){
        a.addEventListener("click", linkHandler, false);
    }
});

// return smoothscroll API
return smoothScroll;

});
<|endoftext|>


<commit_before>'use strict';

window.setImmediate || Object.assign(window, new function () {

    var id = 0,
        storage = {},
        firstCall = true,
        message = 'setImmediatePolyfillMessage';

    function fastApply(args) {
        var func = args[0];
        switch (args.length) {
            case 1:
                return func();
            case 2:
                return func(args[1]);
            case 3:
                return func(args[1], args[2]);
        }
        return func.apply(window, Array.prototype.slice.call(args, 1));
    }

    function callback(event) {
        var data,
            key = event.data;
        if ('string' == typeof key && key.startsWith(message)) {
            data = storage[key];
            if (data) {
                delete storage[key];
                fastApply(data);
            }
        }
    }

    return {

        setImmediate: function () {
            var key = message + ++id;
            storage[key] = arguments;
            if (firstCall) {
                firstCall = false;
                window.addEventListener('message', callback);
            }
            window.postMessage(key, '*');
            return id;
        },

        clearImmediate: function (id) {
            delete storage[message + id];
        }

    };

});
<commit_msg>split local and global UIDs<commit_after>'use strict';

window.setImmediate || Object.assign(window, new function () {

    var uid = 0,
        storage = {},
        firstCall = true,
        message = 'setImmediatePolyfillMessage';

    function fastApply(args) {
        var func = args[0];
        switch (args.length) {
            case 1:
                return func();
            case 2:
                return func(args[1]);
            case 3:
                return func(args[1], args[2]);
        }
        return func.apply(window, Array.prototype.slice.call(args, 1));
    }

    function callback(event) {
        var data,
            key = event.data;
        if ('string' == typeof key && key.startsWith(message)) {
            data = storage[key];
            if (data) {
                delete storage[key];
                fastApply(data);
            }
        }
    }

    return {

        setImmediate: function () {
            var id = uid++,
                key = message + id;
            storage[key] = arguments;
            if (firstCall) {
                firstCall = false;
                window.addEventListener('message', callback);
            }
            window.postMessage(key, '*');
            return id;
        },

        clearImmediate: function (id) {
            delete storage[message + id];
        }

    };

});
<|endoftext|>


<commit_before>
EducationalMaterials = new Mongo.Collection('educational_materials');
<commit_msg>Cleanup<commit_after><|endoftext|>


<commit_before>define([
  'common/collections/single-timeseries'
],
function (Collection) {
  return {
    requiresSvg: true,
    hasDatePicker: true,
    collectionClass: Collection,

    collectionOptions: function () {
      var options = {};
      options.numeratorMatcher = new RegExp(this.model.get('numerator-matcher')),
      options.denominatorMatcher = new RegExp(this.model.get('denominator-matcher')),
      options.matchingAttribute = this.model.get('group-by'),
      options.valueAttr = this.model.get('value-attribute') || 'uniqueEvents',
      options.axisPeriod = this.model.get('axis-period') || this.model.get('period'),
      options.axes = _.merge({
        x: {
          label: 'Date of Application',
          key: ['_start_at', '_end_at'],
          format: 'date'
        },
        y: [
          {
            label: 'Number of applications',
            key: 'uniqueEvents',
            format: this.model.get('format-options') || 'integer'
          }
        ]
      }, this.model.get('axes')),

      options.defaultValue = this.model.get('default-value')
      return options;
    },

    visualisationOptions: function () {
      return {
        valueAttr: 'uniqueEvents',
        totalAttr: 'mean',
        formatOptions: this.model.get('format-options') || { type: 'number', magnitude: true, pad: true }
      };
    }

  };
});
<commit_msg>Switches single-timeseries to using flat data<commit_after>define([
  'common/collections/single-timeseries'
],
function (Collection) {
  return {
    requiresSvg: true,
    hasDatePicker: true,
    collectionClass: Collection,

    collectionOptions: function () {
      var options = {};
      options.numeratorMatcher = new RegExp(this.model.get('numerator-matcher')),
      options.denominatorMatcher = new RegExp(this.model.get('denominator-matcher')),
      options.matchingAttribute = this.model.get('group-by'),
      options.valueAttr = this.model.get('value-attribute') || 'uniqueEvents',
      options.axisPeriod = this.model.get('axis-period') || this.model.get('period'),
      options.axes = _.merge({
        x: {
          label: 'Date of Application',
          key: ['_start_at', '_end_at'],
          format: 'date'
        },
        y: [
          {
            label: 'Number of applications',
            key: 'uniqueEvents',
            format: this.model.get('format-options') || 'integer'
          }
        ]
      }, this.model.get('axes')),
      options.dataSource = this.model.get('data-source');
      options.dataSource['query-params'] = _.extend(options.dataSource['query-params'], {
        flatten:true
      });
      options.defaultValue = this.model.get('default-value');
      return options;
    },

    visualisationOptions: function () {
      return {
        valueAttr: 'uniqueEvents',
        totalAttr: 'mean',
        formatOptions: this.model.get('format-options') || { type: 'number', magnitude: true, pad: true }
      };
    }

  };
});
<|endoftext|>


<commit_before>require('script!3Dmol/release/3Dmol.js');

angular.module('mongochemApp')
    .filter('mongochemUnderscores', function() {
        return function(text) {
            var str = text.replace(/_/g, ' ');
            return str.charAt(0).toUpperCase() + str.substr(1);
        }
    })
    .controller('mongochemMoleculeHome', ['mongochem.Molecule', '$scope', function(Molecule, $scope) {
        $scope.mol = Molecule.getByInchiKey({moleculeId: 'TYQCGQRIZGCHNB-DUZGATOHSA-N'}, function(mol) {
            $scope.molXyz = mol.xyz;
            $scope.viewer.addModel(mol.xyz, 'xyz');
            $scope.viewer.setStyle({}, {stick:{}});
            $scope.viewer.zoomTo();
            $scope.viewer.render();
        });

        $scope.setViewStyle = function(style) {
            if (style == 'ball')
              $scope.viewer.setStyle({}, {sphere:{}});
            else if (style == 'stick')
                $scope.viewer.setStyle({}, {stick:{}});
            else
                $scope.viewer.setStyle({}, {line:{}});
            // It seems that the model is not retained, add it back.
            $scope.viewer.addModel($scope.molXyz, 'xyz');
            $scope.viewer.render();
        };
    }])
    .controller('mongochemMoleculeDetail', ['mongochem.Molecule', '$scope', '$stateParams', function(Molecule, $scope, $stateParams) {
        $scope.mol = Molecule.getByInchiKey({moleculeId: $stateParams.moleculeId}, function(mol) {
            $scope.viewer.addModel(mol.xyz, 'xyz');
            $scope.viewer.setStyle({}, {stick:{}});
            $scope.viewer.zoomTo();
            $scope.viewer.render();
        });
    }])
    .controller('mongochemMolecules', ['Molecules', '$scope', function(Molecules, $scope) {
        $scope.molecules = Molecules.query();
    }])
    .directive('mongochem3dmol', ['$timeout', function($timeout) {
        return {
            link: function postLink($scope, $element) {
                // Run in next digest so we get the right element size
                $timeout(function() {
                    // Viewer config - properties 'defaultcolors' and 'callback'
                    var config = {defaultcolors: $3Dmol.rasmolElementColors };

                    // Create GLViewer within $element
                    $scope.viewer = $3Dmol.createViewer($($element), config);
                    $scope.viewer.setBackgroundColor(0xefefef);
                    $scope.viewer.resize();
                });
            }
        };
    }]);
<commit_msg>Clean up formatting<commit_after>require('script!3Dmol/release/3Dmol.js');

angular.module('mongochemApp')
    .filter('mongochemUnderscores', function() {
        return function(text) {
            var str = text.replace(/_/g, ' ');
            return str.charAt(0).toUpperCase() + str.substr(1);
        };
    })
    .controller('mongochemMoleculeHome', ['mongochem.Molecule', '$scope', function(Molecule, $scope) {
        $scope.mol = Molecule.getByInchiKey({moleculeId: 'TYQCGQRIZGCHNB-DUZGATOHSA-N'}, function(mol) {
            $scope.molXyz = mol.xyz;
            $scope.viewer.addModel(mol.xyz, 'xyz');
            $scope.viewer.setStyle({}, {stick:{}});
            $scope.viewer.zoomTo();
            $scope.viewer.render();
        });

        $scope.setViewStyle = function(style) {
            if (style == 'ball') {
              $scope.viewer.setStyle({}, {sphere:{}});
            }
            else if (style == 'stick') {
                $scope.viewer.setStyle({}, {stick:{}});
            }
            else {
                $scope.viewer.setStyle({}, {line:{}});
            }
            // It seems that the model is not retained, add it back.
            $scope.viewer.addModel($scope.molXyz, 'xyz');
            $scope.viewer.render();
        };
    }])
    .controller('mongochemMoleculeDetail', ['mongochem.Molecule', '$scope', '$stateParams', function(Molecule, $scope, $stateParams) {
        $scope.mol = Molecule.getByInchiKey({moleculeId: $stateParams.moleculeId}, function(mol) {
            $scope.viewer.addModel(mol.xyz, 'xyz');
            $scope.viewer.setStyle({}, {stick:{}});
            $scope.viewer.zoomTo();
            $scope.viewer.render();
        });
    }])
    .controller('mongochemMolecules', ['Molecules', '$scope', function(Molecules, $scope) {
        $scope.molecules = Molecules.query();
    }])
    .directive('mongochem3dmol', ['$timeout', function($timeout) {
        return {
            link: function postLink($scope, $element) {
                // Run in next digest so we get the right element size
                $timeout(function() {
                    // Viewer config - properties 'defaultcolors' and 'callback'
                    var config = {defaultcolors: $3Dmol.rasmolElementColors };

                    // Create GLViewer within $element
                    $scope.viewer = $3Dmol.createViewer($($element), config);
                    $scope.viewer.setBackgroundColor(0xefefef);
                    $scope.viewer.resize();
                });
            }
        };
    }]);
<|endoftext|>


<commit_before>import styled from 'styled-components';

const Wrapper = styled.div`
  svg {
    cursor: pointer;
    color: #dd5555;
    margin-bottom: 11px;
    margin-right: 7px;
  }
  span {
    display: inline-block;
  }
  margin: 10px auto;
  @media (max-width: 414px) {
    svg {
      margin-bottom: 10px;
      height: 20px;
    }
    h1 {
      font-size: 1.6em;
    }
    p {
      font-size: 17px;
    }
  }

  @media (max-width: 360px) {
    h1 {
      font-size: 1.5em;
    }
    p {
      font-size: 0.85em;
    }
  }

`;

export default Wrapper;
<commit_msg>icon size in mobile view;<commit_after>import styled from 'styled-components';

const Wrapper = styled.div`
  svg {
    cursor: pointer;
    color: #dd5555;
    margin-bottom: 11px;
    margin-right: 7px;
  }
  span {
    display: inline-block;
  }
  margin: 10px auto;
  @media (max-width: 414px) {
    svg {
      margin-bottom: 8px;
      height: 18px;
    }
    h1 {
      font-size: 1.6em;
    }
    p {
      font-size: 17px;
    }
  }

  @media (max-width: 360px) {
    h1 {
      font-size: 1.5em;
    }
    p {
      font-size: 0.85em;
    }
  }

`;

export default Wrapper;
<|endoftext|>


<commit_before>/**
 * TagSpaces - universal file and folder organizer
 * Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License (version 3) as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * @flow
 */

import React from 'react';
import Button from '@material-ui/core/Button';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContentText from '@material-ui/core/DialogContentText';
import { withStyles } from '@material-ui/core/styles';
import GenericDialog from './GenericDialog';
import i18n from '../../services/i18n';

const styles = theme => ({});

type Props = {
  open: boolean,
  title: string,
  content: string,
  cancelDialogTID: string,
  confirmDialogTID: string,
  confirmDialogContentTID: string,
  list: Array<string>,
  confirmCallback: (result: boolean) => void,
  onClose: () => void
};

class ConfirmDialog extends React.Component<Props> {
  onConfirm = (result) => {
    this.props.confirmCallback(result);
    this.props.onClose();
  };

  renderTitle = () => (
    <DialogTitle>{this.props.title}</DialogTitle>
  );

  renderContent = () => (
    <DialogContent>
      <DialogContentText data-tid={this.props.confirmDialogContentTID}>
        {this.props.content}
        {this.props.list && this.props.list.map((listItem) =>
{listItem}
)}
      </DialogContentText>
    </DialogContent>
  );

  renderActions = () => (
    <DialogActions>
      <Button
        onClick={() => this.onConfirm(false)}
        color="primary"
        data-tid={this.props.cancelDialogTID}
      >
        {i18n.t('core:no')}
      </Button>
      <Button
        data-tid={this.props.confirmDialogTID}
        onClick={() => this.onConfirm(true)}
        color="primary"
      >
        {i18n.t('core:yes')}
      </Button>
    </DialogActions>
  );

  render() {
    return (
      <GenericDialog
        open={this.props.open}
        onClose={this.props.onClose}
        renderTitle={this.renderTitle}
        renderContent={this.renderContent}
        renderActions={this.renderActions}
      />
    );
  }
}

export default withStyles(styles)(ConfirmDialog);
<commit_msg>refactoring dialogs<commit_after>/**
 * TagSpaces - universal file and folder organizer
 * Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License (version 3) as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * @flow
 */

import React from 'react';
import Button from '@material-ui/core/Button';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContentText from '@material-ui/core/DialogContentText';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import Typography from '@material-ui/core/Typography';
import { withStyles } from '@material-ui/core/styles';
import GenericDialog from './GenericDialog';
import i18n from '../../services/i18n';

const styles = theme => ({});

type Props = {
  open: boolean,
  title: string,
  content: string,
  cancelDialogTID: string,
  confirmDialogTID: string,
  confirmDialogContentTID: string,
  list: Array<string>,
  confirmCallback: (result: boolean) => void,
  onClose: () => void
};

class ConfirmDialog extends React.Component<Props> {
  onConfirm = (result) => {
    this.props.confirmCallback(result);
    this.props.onClose();
  };

  renderTitle = () => (
    <DialogTitle>{this.props.title}</DialogTitle>
  );

  renderContent = () => (
    <DialogContent>
      <DialogContentText data-tid={this.props.confirmDialogContentTID}>
        {this.props.content}
        {this.props.list && this.props.list.map((listItem) => (
          <ListItem title={listItem}>
            <Typography variant="inherit" noWrap>{listItem}</Typography>
          </ListItem>
        ))}
      </DialogContentText>
    </DialogContent>
  );

  renderActions = () => (
    <DialogActions>
      <Button
        onClick={() => this.onConfirm(false)}
        color="primary"
        data-tid={this.props.cancelDialogTID}
      >
        {i18n.t('core:no')}
      </Button>
      <Button
        data-tid={this.props.confirmDialogTID}
        onClick={() => this.onConfirm(true)}
        color="primary"
      >
        {i18n.t('core:yes')}
      </Button>
    </DialogActions>
  );

  render() {
    return (
      <GenericDialog
        open={this.props.open}
        onClose={this.props.onClose}
        renderTitle={this.renderTitle}
        renderContent={this.renderContent}
        renderActions={this.renderActions}
      />
    );
  }
}

export default withStyles(styles)(ConfirmDialog);
<|endoftext|>


<commit_before>'use strict';

angular.module('snotes30App')
  .controller('LiveListCtrl', function ($scope, $state, $timeout, Restangular, DocumentService) {
    $scope.episodes = [];

    Restangular.all('soonepisodes').getList().then(
      function (episodes) {
        $scope.episodes = episodes;
      }
    );

    $scope.isPast = function (ep) {
      var today = new Date().setHours(0,0,0,0);
      return ep.date < today;
    };

    $scope.openDoc = function (ep) {
      var name = (typeof ep === 'string') ? ep : ep.document.name;
      $state.go('document-edit', { name: name }, { inherit: false });
    };

    $scope.create = function (index, nonumber) {
      var ep = $scope.episodes[index];

      if(ep.number || nonumber) {
        var _doc;
        DocumentService.createFromEpisode(ep).then(function (doc) {
          _doc = doc;
          return DocumentService.setNumber(doc, ep.number);
        }).then(function () {
          $scope.openDoc(_doc.name);
        });
      } else {
        $scope.setNumber = ep;
        $timeout(function () { angular.element("#addNumber_" + index).focus(); }, 0);
      }
    };
  });
<commit_msg>livelist: don't know button<commit_after>'use strict';

angular.module('snotes30App')
  .controller('LiveListCtrl', function ($scope, $state, $timeout, Restangular, DocumentService) {
    $scope.episodes = [];

    Restangular.all('soonepisodes').getList().then(
      function (episodes) {
        $scope.episodes = episodes;
      }
    );

    $scope.isPast = function (ep) {
      var today = new Date().setHours(0,0,0,0);
      return ep.date < today;
    };

    $scope.openDoc = function (ep) {
      var name = (typeof ep === 'string') ? ep : ep.document.name;
      $state.go('document-edit', { name: name }, { inherit: false });
    };

    $scope.create = function (index, nonumber) {
      var ep = $scope.episodes[index];

      if(ep.number || nonumber) {
        var _doc;
        DocumentService.createFromEpisode(ep).then(function (doc) {
          _doc = doc;
          if(!nonumber) {
            return DocumentService.setNumber(doc, ep.number);
          }
        }).then(function () {
          $scope.openDoc(_doc.name);
        });
      } else {
        $scope.setNumber = ep;
        $timeout(function () { angular.element("#addNumber_" + index).focus(); }, 0);
      }
    };
  });
<|endoftext|>