<commit_before>var React = require('react-native');
var Util = require('./../common/util');
var ServiceURL = require('./../common/service');
var BookItem = require('./book_item');
var Header = require('./../common/header');

var {
  StyleSheet,
  Text,
  View,
  ListView,
  Image,
  ScrollView,
  TouchableOpacity
  } = React;

module.exports = React.createClass({
  getInitialState: function(){
    return{
      data: null
    };
  },
  render: function(){
    return(
      <ScrollView style={styles.m10}>
        {
          this.state.data ?
            <View>
              <Header
                navigator={this.props.navigator}
                initObj={{
                    backName: '图书',
                    title: this.state.data.title
                }}/>
              <BookItem row={this.state.data}/>
              <View>
                <Text style={[styles.title]}>图书简介</Text>
                <Text style={styles.text}>{this.state.data.summary}</Text>
              </View>

              <View>
                <Text style={[styles.title]}>作者简介</Text>
                <Text style={styles.text}>{this.state.data.author_intro}</Text>
              </View>
              <View style={{height:50}}></View>
            </View>
            : Util.loading
        }
      </ScrollView>
    );
  },

  componentDidMount: function(){
    var id = this.props.id;
    var that = this;
    var url = ServiceURL.book_search_id + '/' + id;
    Util.get(url, function(data){
      that.setState({
        data: data
      });
    }, function(err){
      alert(err);
    });
  }
});

var styles = StyleSheet.create({
  m10:{
    flex:1
  },
  title:{
    fontSize:16,
    marginLeft:10,
    marginTop:10,
    marginBottom:10
  },
  text:{
    marginLeft:10,
    marginRight:10,
    color:'#000D22'
  }
});

<commit_msg>固定Header<commit_after>var React = require('react-native');
var Util = require('./../common/util');
var ServiceURL = require('./../common/service');
var BookItem = require('./book_item');
var Header = require('./../common/header');

var {
  StyleSheet,
  Text,
  View,
  ListView,
  Image,
  ScrollView,
  TouchableOpacity
  } = React;

module.exports = React.createClass({
  getInitialState: function(){
    return{
      data: null
    };
  },
  render: function(){
    return(
        <View style={[styles.m10]}>
            <Header
                navigator={this.props.navigator}
                initObj={{
                    backName: '图书',
                    title: this.state.data?this.state.data.title:'',
                }}/>
          <ScrollView style={styles.m10} >
            {
              this.state.data ?
                  <View>
                    <BookItem row={this.state.data}/>
                    <View>
                      <Text style={[styles.title]}>图书简介</Text>
                      <Text style={styles.text}>{this.state.data.summary}</Text>
                    </View>

                    <View>
                      <Text style={[styles.title]}>作者简介</Text>
                      <Text style={styles.text}>{this.state.data.author_intro}</Text>
                    </View>
                    <View style={{height:50}}></View>
                  </View>
                  : Util.loading
            }
          </ScrollView>
        </View>

    );
  },

  componentDidMount: function(){
    var id = this.props.id;
    var that = this;
    var url = ServiceURL.book_search_id + '/' + id;
    Util.get(url, function(data){
      that.setState({
        data: data
      });
    }, function(err){
      alert(err);
    });
  }
});

var styles = StyleSheet.create({
  m10:{
    flex:1,
    top:0,
  },
  title:{
    fontSize:16,
    marginLeft:10,
    marginTop:10,
    marginBottom:10
  },
  text:{
    marginLeft:10,
    marginRight:10,
    color:'#000D22'
  }
});

<|endoftext|>


<commit_before>'use strict'

function SettingsWorld() {
    this.__init__()
}

SettingsWorld.prototype = {

    __init__: function() {

        var position = new THREE.Vector3(900, 500, 1500)
        this.normal = new THREE.Vector3(-.5, 0, -.85)
        this.normal.normalize()
        this.current_entity_editor = new FloatingWall(512, 1024, position, this.normal, this)

        // Inherit world properties.
        World.call(this, 'SettingsWorld')

        var lightr = new THREE.PointLight(0xff8579, .8, 0)
        lightr.position.set(1000, 100, 0)
        this.add_to_scene(lightr)

        var lightg = new THREE.PointLight(0xb1ff90, .8, 0)
        lightg.position.set(0, 100, 1000)
        this.add_to_scene(lightg)

        var lightb = new THREE.PointLight(0x84b5ff, .8, 0)
        lightb.position.set(500, 100, 500)
        this.add_to_scene(lightb)

    },

    update: function() {
        this.update_interactive_objects()
    },

    key_down_event: function(event) {
        this.key_down_event_for_interactive_objects(event)
    },

    enter_world: function() {
        this.player.disengage()
        this.player.enable_controls()
        this.current_world = true

        this.player.set_position(new THREE.Vector3(0, 0, 0))
    },

    exit_world: function() {
        this.current_world = false
    }
}<commit_msg>general updating 42<commit_after>'use strict'

function SettingsWorld() {
    this.__init__()
}

SettingsWorld.prototype = {

    __init__: function() {

        // Inherit world properties.
        World.call(this, 'SettingsWorld')

        var position = new THREE.Vector3(900, 500, 1500)
        this.normal = new THREE.Vector3(-.5, 0, -.85)
        this.normal.normalize()
        this.current_entity_editor = new FloatingWall(512, 1024, position, this.normal, this)

        var lightr = new THREE.PointLight(0xff8579, .8, 0)
        lightr.position.set(1000, 100, 0)
        this.add_to_scene(lightr)

        var lightg = new THREE.PointLight(0xb1ff90, .8, 0)
        lightg.position.set(0, 100, 1000)
        this.add_to_scene(lightg)

        var lightb = new THREE.PointLight(0x84b5ff, .8, 0)
        lightb.position.set(500, 100, 500)
        this.add_to_scene(lightb)

    },

    update: function() {
        this.update_interactive_objects()
    },

    key_down_event: function(event) {
        this.key_down_event_for_interactive_objects(event)
    },

    enter_world: function() {
        this.player.disengage()
        this.player.enable_controls()
        this.current_world = true

        this.player.set_position(new THREE.Vector3(0, 0, 0))
    },

    exit_world: function() {
        this.current_world = false
    }
}<|endoftext|>


<commit_before>function typeLiteral$meta($$targs$$,targ$2) {
  if ($$targs$$ === undefined || $$targs$$.Type$typeLiteral === undefined) {
    throw new Error("Missing type argument 'Type' " + /*require('util').inspect(*/$$targs$$);
  } else if ($$targs$$.Type$typeLiteral.$crtmm$ == undefined) {
    //closed type
    var t = $$targs$$.Type$typeLiteral.t
    if (t === undefined) {
      t = $$targs$$.Type$typeLiteral.setter;
      if (t && t.$crtmm$) {
        var mm = getrtmm$$(t);
        var _m=typeof(mm.mod)==='function'?mm.mod():mm.mod;
        var _mod = modules$meta().find(_m['$mod-name'],_m['$mod-version']);
        return OpenSetter(OpenValue$jsint(_mod.findPackage(mm.d[0]), t));
      }
      throw new Error("'Type' argument should be an open or closed type");
    } else if (t==='u' || t==='i') {
      return (t==='u'?applyUnionType:applyIntersectionType)($$targs$$.Type$typeLiteral,targ$2);
    } else if (t==='T') {
      //TODO arguments
      var _tt=retpl$($$targs$$.Type$typeLiteral);
      return AppliedClass$jsint(Tuple,{Type$AppliedClass:$$targs$$.Type$typeLiteral,Arguments$AppliedClass:{t:'T',l:[_tt.a.First$Tuple,_tt.a.Rest$Tuple]}});
    } else if (t.$crtmm$ === undefined) {
      throw new Error("JS Interop not supported / incomplete metamodel for " + /*require('util').inspect(*/t);
    } else {
      var mm = getrtmm$$(t);
      var mdl = get_model(mm);
      if (mdl.mt==='c' || mdl.mt==='o') {
        //TODO tupleize Arguments
        var acargs={t:Sequential,a:{Element$Iterable:{t:Anything}}};
        var r=mm.$cont?AppliedMemberClass$jsint(t,{Container$AppliedMemberClass:{t:mm.$cont},Type$AppliedMemberClass:$$targs$$.Type$typeLiteral,Arguments$AppliedMemberClass:acargs})
          : AppliedClass$jsint(t,{Type$AppliedClass:$$targs$$.Type$typeLiteral,Arguments$AppliedClass:acargs});
        if ($$targs$$.Type$typeLiteral.a)r.$targs=$$targs$$.Type$typeLiteral.a;
        return r;
      } else if (mdl['mt'] === 'i') {
        var r=AppliedInterface$jsint(t,{Type$Interface:$$targs$$.Type$typeLiteral});
        if ($$targs$$.Type$typeLiteral.a)r.$targs=$$targs$$.Type$typeLiteral.a;
        return r;
      } else if (mdl['mt'] === 'm') {
        return AppliedFunction$jsint(t,{Type$AppliedFunction:$$targs$$.Type$typeLiteral,
               Arguments$AppliedFunction:{t:Sequential,a:{Element$Iterable:{t:Anything}}}});
      } else if (mdl['mt'] === 'a' || mdl['mt'] === 'g' || mdl.mt==='s') {
        return AppliedValue$jsint(undefined,t,{Container$Value:{t:mm.$cont},Get$Value:mm.$t,Set$Value:mdl['var']?mm.$t:{t:Nothing}});
      } else {
        console.log("WTF is a metatype " + mdl['mt'] + " on a closed type???????");
      }
      console.log("typeLiteral<" + t.getT$name() + "> (closed type)");
    }
  } else {
    //open type
    var t = $$targs$$.Type$typeLiteral;
    var mm = getrtmm$$(t);
    var mdl = get_model(mm);
    var _m = typeof(mm.mod)==='function'?mm.mod():mm.mod;
    //We need the module
    var _mod = modules$meta().find(_m['$mod-name'],_m['$mod-version']);
    var _pkg = _mod.findPackage(mm.d[0]);
    if (mdl.mt==='c' || mdl.mt==='o') {
      return OpenClass$jsint(_pkg, t);
    } else if (mdl['mt'] === 'i') {
      return OpenInterface$jsint(_pkg, t);
    } else if (mdl['mt'] === 'm') {
      return OpenFunction(_pkg, t);
    } else if (mdl['mt'] === 'a' || mdl['mt'] === 'g') {
      return OpenValue$jsint(_pkg, t);
    } else if (mdl.mt==='s') {
      return OpenSetter(OpenValue$jsint(_pkg, t));
    } else {
      console.log("WTF is a metatype " + mdl['mt'] + " on an open type???????");
    }
    console.log("typeLiteral<" + t.getT$name() + "> (open type)");
  }
  throw new Error("typeLiteral UNIMPLEMENTED for " + /*require('util').inspect(*/$$targs$$);
}
<commit_msg>missing case: Empty<commit_after>function typeLiteral$meta($$targs$$,targ$2) {
  if ($$targs$$ === undefined || $$targs$$.Type$typeLiteral === undefined) {
    throw new Error("Missing type argument 'Type' " + /*require('util').inspect(*/$$targs$$);
  } else if ($$targs$$.Type$typeLiteral.$crtmm$ == undefined) {
    //closed type
    var t = $$targs$$.Type$typeLiteral.t
    if (t === undefined) {
      t = $$targs$$.Type$typeLiteral.setter;
      if (t && t.$crtmm$) {
        var mm = getrtmm$$(t);
        var _m=typeof(mm.mod)==='function'?mm.mod():mm.mod;
        var _mod = modules$meta().find(_m['$mod-name'],_m['$mod-version']);
        return OpenSetter(OpenValue$jsint(_mod.findPackage(mm.d[0]), t));
      }
      throw new Error("'Type' argument should be an open or closed type");
    } else if (t==='u' || t==='i') {
      return (t==='u'?applyUnionType:applyIntersectionType)($$targs$$.Type$typeLiteral,targ$2);
    } else if (t==='T') {
      //TODO arguments
      var _tt=retpl$($$targs$$.Type$typeLiteral);
      if (_tt.t===Empty) {
        return AppliedClass$jsint(Tuple,{Type$AppliedClass:$$targs$$.Type$typeLiteral,Arguments$AppliedClass:{t:Empty}});
      }
      return AppliedClass$jsint(Tuple,{Type$AppliedClass:$$targs$$.Type$typeLiteral,Arguments$AppliedClass:{t:'T',l:[_tt.a.First$Tuple,_tt.a.Rest$Tuple]}});
    } else if (t.$crtmm$ === undefined) {
      throw new Error("JS Interop not supported / incomplete metamodel for " + /*require('util').inspect(*/t);
    } else {
      var mm = getrtmm$$(t);
      var mdl = get_model(mm);
      if (mdl.mt==='c' || mdl.mt==='o') {
        //TODO tupleize Arguments
        var acargs={t:Sequential,a:{Element$Iterable:{t:Anything}}};
        var r=mm.$cont?AppliedMemberClass$jsint(t,{Container$AppliedMemberClass:{t:mm.$cont},Type$AppliedMemberClass:$$targs$$.Type$typeLiteral,Arguments$AppliedMemberClass:acargs})
          : AppliedClass$jsint(t,{Type$AppliedClass:$$targs$$.Type$typeLiteral,Arguments$AppliedClass:acargs});
        if ($$targs$$.Type$typeLiteral.a)r.$targs=$$targs$$.Type$typeLiteral.a;
        return r;
      } else if (mdl['mt'] === 'i') {
        var r=AppliedInterface$jsint(t,{Type$Interface:$$targs$$.Type$typeLiteral});
        if ($$targs$$.Type$typeLiteral.a)r.$targs=$$targs$$.Type$typeLiteral.a;
        return r;
      } else if (mdl['mt'] === 'm') {
        return AppliedFunction$jsint(t,{Type$AppliedFunction:$$targs$$.Type$typeLiteral,
               Arguments$AppliedFunction:{t:Sequential,a:{Element$Iterable:{t:Anything}}}});
      } else if (mdl['mt'] === 'a' || mdl['mt'] === 'g' || mdl.mt==='s') {
        return AppliedValue$jsint(undefined,t,{Container$Value:{t:mm.$cont},Get$Value:mm.$t,Set$Value:mdl['var']?mm.$t:{t:Nothing}});
      } else {
        console.log("WTF is a metatype " + mdl['mt'] + " on a closed type???????");
      }
      console.log("typeLiteral<" + t.getT$name() + "> (closed type)");
    }
  } else {
    //open type
    var t = $$targs$$.Type$typeLiteral;
    var mm = getrtmm$$(t);
    var mdl = get_model(mm);
    var _m = typeof(mm.mod)==='function'?mm.mod():mm.mod;
    //We need the module
    var _mod = modules$meta().find(_m['$mod-name'],_m['$mod-version']);
    var _pkg = _mod.findPackage(mm.d[0]);
    if (mdl.mt==='c' || mdl.mt==='o') {
      return OpenClass$jsint(_pkg, t);
    } else if (mdl['mt'] === 'i') {
      return OpenInterface$jsint(_pkg, t);
    } else if (mdl['mt'] === 'm') {
      return OpenFunction(_pkg, t);
    } else if (mdl['mt'] === 'a' || mdl['mt'] === 'g') {
      return OpenValue$jsint(_pkg, t);
    } else if (mdl.mt==='s') {
      return OpenSetter(OpenValue$jsint(_pkg, t));
    } else {
      console.log("WTF is a metatype " + mdl['mt'] + " on an open type???????");
    }
    console.log("typeLiteral<" + t.getT$name() + "> (open type)");
  }
  throw new Error("typeLiteral UNIMPLEMENTED for " + /*require('util').inspect(*/$$targs$$);
}
<|endoftext|>


<commit_before>/* jshint -W097 */
/* globals require, module */
'use strict';

const Message = require('./message.js'),
    MessageType = require('../../lookups/messagetype.js'),
    util = require('util');

const PACKET_VERSION = 1;

/*
 * Authenticate and open a session with the FUB
 * @param {String} secret an encrypted secret
 * @class
 * @constructor
 * @see {@link https://github.com/lukevenediger/firebase-udp-bridge/wiki#authenticate|Authenticate}
 */
function Authenticate(secret) {
    Message.call(this, MessageType.AUTHENTICATE, PACKET_VERSION);

    this.secret = secret;
}

Authenticate.prototype.toString = function() {
    return MessageType.getMessageTypeName(this.type) + 'secret=' + this.secret;
};

util.inherits(Authenticate, Message);

module.exports = Authenticate;
<commit_msg>Added 'id' property to Authenticate packet.<commit_after>/* jshint -W097 */
/* globals require, module */
'use strict';

const Message = require('./message.js'),
    MessageType = require('../../lookups/messagetype.js'),
    util = require('util');

const PACKET_VERSION = 1;

/*
 * Authenticate and open a session with the FUB
 * @param {String} id the device ID
 * @param {String} secret an encrypted secret
 * @class
 * @constructor
 * @see {@link https://github.com/lukevenediger/firebase-udp-bridge/wiki#authenticate|Authenticate}
 */
function Authenticate(id, secret) {
    Message.call(this, MessageType.AUTHENTICATE, PACKET_VERSION);

    this.id = id;
    this.secret = secret;
}

Authenticate.prototype.toString = function() {
    return MessageType.getMessageTypeName(this.type) + 'id=' + this.id +
        ', secret=' + this.secret;
};

util.inherits(Authenticate, Message);

module.exports = Authenticate;
<|endoftext|>


<commit_before>/**
 * Copyright 2014 Netsend.
 *
 * This file is part of Mastersync.
 *
 * Mastersync is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Affero General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * Mastersync 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 Mastersync. If not, see <https://www.gnu.org/licenses/>.
 */

'use strict';

var Readable = require('stream').Readable;
var util = require('util');

var async = require('async');
var mongodb = require('mongodb');
var BSON = mongodb.BSON;
var match = require('match-object');

var runHooks = require('./run_hooks');
var walkBranch = require('./walk_branch');

/**
 * VersionedCollectionReader
 *
 * Read the versioned collection reader, optionally starting at a certain offset.
 *
 * @param {Object} snapshotCollection  a mongodb.Collection object
 * @param {Object} [opts]  object containing configurable parameters
 *
 * opts:
 *   localPerspective {String, default _local}  name of the local perspective, remotes can't be named like this.
 *   debug {Boolean, default false}  whether to do extra console logging or not
 *   hide {Boolean, default false}  whether to suppress errors or not (used in tests)
 *   raw  {Boolean, default false}  whether to emit JavaScript objects or raw Buffers
 *   filter {Object}  conditions a document should hold
 *   offset {String}  version to start tailing after
 *   follow {Boolean, default: true}  whether to keep the tail open or not
 *   tailableRetryInterval {Number, default 2000}  set tailableRetryInterval
 *   hooks {Array}  array of asynchronous functions to execute, each hook has the following signature: db, object, options,
 *                  callback and should callback with an error object, the new item and possibly extra data.
 *   hooksOpts {Object}  options to pass to a hook
 *
 * @event "data" {Object}  emits one object at a time
 * @event "end"  emitted once the underlying cursor is closed
 *
 * @class represents a VersionedCollectionReader for a certain database.collection
 */
function VersionedCollectionReader(snapshotCollection, opts) {
  /* jshint maxcomplexity: 24 */ /* lot's of parameter checking */

  if (typeof snapshotCollection !== 'object') { throw new TypeError('snapshotCollection must be an object'); }

  if (typeof opts !== 'undefined' && typeof opts !== 'object') { throw new TypeError('opts must be an object'); }
  opts = opts || {};

  if (typeof opts.localPerspective !== 'undefined' && typeof opts.localPerspective !== 'string') { throw new TypeError('opts.localPerspective must be a string'); }
  if (typeof opts.debug !== 'undefined' && typeof opts.debug !== 'boolean') { throw new TypeError('opts.debug must be a boolean'); }
  if (typeof opts.hide !== 'undefined' && typeof opts.hide !== 'boolean') { throw new TypeError('opts.hide must be a boolean'); }
  if (typeof opts.raw !== 'undefined' && typeof opts.raw !== 'boolean') { throw new TypeError('opts.raw must be a boolean'); }
  if (typeof opts.filter !== 'undefined' && typeof opts.filter !== 'object') { throw new TypeError('opts.filter must be an object'); }
  if (typeof opts.offset !== 'undefined' && typeof opts.offset !== 'string') { throw new TypeError('opts.offset must be a string'); }
  if (typeof opts.follow !== 'undefined' && typeof opts.follow !== 'boolean') { throw new TypeError('opts.follow must be a boolean'); }
  if (typeof opts.tailableRetryInterval !== 'undefined' && typeof opts.tailableRetryInterval !== 'number') { throw new TypeError('opts.tailableRetryInterval must be a number'); }
  if (typeof opts.hooks !== 'undefined' && !(opts.hooks instanceof Array)) { throw new TypeError('opts.hooks must be an array'); }
  if (typeof opts.hooksOpts !== 'undefined' && typeof opts.hooksOpts !== 'object') { throw new TypeError('opts.hooksOpts must be an object'); }

  this._snapshotCollection = snapshotCollection;

  this._db = snapshotCollection.db;

  this._snapshotCollectionName = snapshotCollection.collectionName;

  this._localPerspective = opts.localPerspective || '_local';
  this._debug = opts.debug || false;
  this._hide = opts.hide || false;
  this._raw = opts.raw || false;
  this._filter = opts.filter || {};
  this._offset = opts.offset || '';

  this._debugName = this._db.databaseName + '.' + this._snapshotCollectionName;

  if (typeof opts.follow === 'boolean') {
    this._follow = opts.follow;
  } else {
    this._follow = true;
  }
  this._hooks = opts.hooks || [];
  this._hooksOpts = opts.hooksOpts || {};

  Readable.call(this, { objectMode: !this._raw });

  var selector = { '_id._pe': this._localPerspective };
  var mongoOpts = { sort: { '$natural': 1 }, tailable: this._follow, comment: 'tail' };
  mongoOpts.tailableRetryInterval = opts.tailableRetryInterval || 2000;

  if (this._debug) { console.log('vcr %s: selector %s filter %s opts %s', this._debugName, JSON.stringify(selector), JSON.stringify(this._filter), JSON.stringify(mongoOpts)); }

  this._source = this._snapshotCollection.find(selector, mongoOpts).stream();

  var that = this;

  // pause _source to determine maxTries
  this._source.pause();

  // determine the maximum number of versions to examine before the offset must have been encountered
  this._maxTries = 0;
  this._snapshotCollection.count(function(err, count) {
    if (err) { throw err; }
    that._maxTries = count;
    that._source.resume();
  });

  // emit a connected graph by making sure every parent of any filtered item is filtered
  var heads = {};
  var offsetReached = false;
  if (!this._offset) {
    offsetReached = true;
  }
  var i = 0;

  function handleData(item) {
    if (that._debug && offsetReached) { console.log('vcr %s: _read %s', that._debugName, JSON.stringify(item._id)); }

    // only start emitting after the offset is encountered
    if (!offsetReached) {
      if (item._id._v === that._offset) {
        if (that._debug) { console.log('vcr %s: _read offset reached %s', that._debugName, JSON.stringify(item._id)); }
        offsetReached = true;
      } else {
        // the offset should be encountered within maxTries
        i++;
        if (i >= that._maxTries) {
          if (!that._hide) { console.error('vcr %s: _read offset not found %s %s %s', that._debugName, that._offset, i, that._maxTries); }
          if (that._source.destroy()) { throw new Error('offset not found'); }
        }
      }
    }

    heads[item._id._v] = [];

    // move previously emitted parents along with this new branch head
    that._source.pause();
    async.eachSeries(item._id._pa, function(p, callback) {
      if (heads[p]) {
        // ff and takeover parent references from old head
        Array.prototype.push.apply(heads[item._id._v], heads[p]);
        delete heads[p];
        process.nextTick(callback);
      } else {
        // branched off, find the lowest filtered ancestor of this item and save it as parent reference
        var lastEmitted = {};
        lastEmitted['_id._id'] = item._id._id;
        lastEmitted['_id._pe'] = that._localPerspective;

        walkBranch(lastEmitted, p, that._localPerspective, that._snapshotCollection, function(anItem, cb) {
          // skip if not all criteria hold on this item
          if (!match(that._filter, anItem)) {
            cb();
            return;
          }

          // make sure the ancestor is not already in the array, this can happen on merge items.
          if (!heads[item._id._v].some(function(pp) { return pp === anItem._id._v; })) {
            heads[item._id._v].push(anItem._id._v);
          }
          cb(null, true);
        }, function(err) {
          if (err) {
            if (!that._hide) { console.error('vcr %s %s could not determine last emitted version before %s %s %s', p, lastEmitted, err); }
            callback(err);
            return;
          }
          callback();
        });
      }
    }, function(err) {
      if (err) {
        that._source.destroy();
        that.emit('error', err);
        return;
      }

      // don't emit if not all criteria hold on this item
      if (!match(that._filter, item)) {
        that._source.resume();
        return;
      }

      // load all hooks on this item, then, if offset is reached, callback
      runHooks(that._hooks, that._db, item, that._hooksOpts, function(err, afterItem) {
        if (err) { return that.emit('error', err); }

        // if hooks filter out the item, do not callback since that would signal the end
        if (!afterItem) {
          if (that._debug && offsetReached) { console.log('vcr %s: vcr hook filtered %s', that._debugName, JSON.stringify(item._id)); }
          that._source.resume();
          return;
        }

        // set parents to last returned version of this branch
        item._id._pa = heads[item._id._v];

        // then update branch with _id of this item
        heads[item._id._v] = [item._id._v];

        // all criteria hold, so return this item if offset is reached
        if (offsetReached) {
          item = afterItem;

          // remove perspective and local state and run any transformation
          delete item._id._pe;
          delete item._id._lo;
          delete item._id._i;
          delete item._m3._op;
          delete item._m3._ack;

          // push the raw or parsed item out to the reader, and resume if not flooded
          if (that._debug) { console.log('vcr %s: push %s', that._debugName, JSON.stringify(item._id)); }
          if (that.push(that._raw ? BSON.serialize(item) : item)) { that._source.resume(); }
        } else {
          that._source.resume();
        }
      });
    });
  }

  this._source.on('data', handleData);

  // proxy error
  this._source.on('error', function(err) {
    if (!that._hide) { console.error('vcr %s: cursor stream error %s', that._debugName, err); }
    that.emit('error', err);
  });

  this._source.on('close', function() {
    if (that._debug) { console.log('vcr %s: cursor stream closed', that._debugName); }
    that.push(null);
  });
}
util.inherits(VersionedCollectionReader, Readable);

module.exports = VersionedCollectionReader;

/**
 * Stop the stream reader. An "end" event will be emitted.
 */
VersionedCollectionReader.prototype.close = function close() {
  if (this._debug) { console.log('vcr %s: closing cursor', this._debugName); }
  this._source.destroy();
};

/////////////////////
//// PRIVATE API ////
/////////////////////

/**
 * Implementation of _read method of Readable stream. This method is not called
 * directly. In this implementation size of read buffer is ignored
 */
VersionedCollectionReader.prototype._read = function() {
  this._source.resume();
};
<commit_msg>fixes #33 vcr: use async queue to prevent races<commit_after>/**
 * Copyright 2014 Netsend.
 *
 * This file is part of Mastersync.
 *
 * Mastersync is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Affero General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * Mastersync 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 Mastersync. If not, see <https://www.gnu.org/licenses/>.
 */

'use strict';

var Readable = require('stream').Readable;
var util = require('util');

var async = require('async');
var mongodb = require('mongodb');
var BSON = mongodb.BSON;
var match = require('match-object');

var runHooks = require('./run_hooks');
var walkBranch = require('./walk_branch');

/**
 * VersionedCollectionReader
 *
 * Read the versioned collection reader, optionally starting at a certain offset.
 *
 * @param {Object} snapshotCollection  a mongodb.Collection object
 * @param {Object} [opts]  object containing configurable parameters
 *
 * opts:
 *   localPerspective {String, default _local}  name of the local perspective, remotes can't be named like this.
 *   debug {Boolean, default false}  whether to do extra console logging or not
 *   hide {Boolean, default false}  whether to suppress errors or not (used in tests)
 *   raw  {Boolean, default false}  whether to emit JavaScript objects or raw Buffers
 *   filter {Object}  conditions a document should hold
 *   offset {String}  version to start tailing after
 *   follow {Boolean, default: true}  whether to keep the tail open or not
 *   tailableRetryInterval {Number, default 2000}  set tailableRetryInterval
 *   hooks {Array}  array of asynchronous functions to execute, each hook has the following signature: db, object, options,
 *                  callback and should callback with an error object, the new item and possibly extra data.
 *   hooksOpts {Object}  options to pass to a hook
 *
 * @event "data" {Object}  emits one object at a time
 * @event "end"  emitted once the underlying cursor is closed
 *
 * @class represents a VersionedCollectionReader for a certain database.collection
 */
function VersionedCollectionReader(snapshotCollection, opts) {
  /* jshint maxcomplexity: 24 */ /* lot's of parameter checking */

  if (typeof snapshotCollection !== 'object') { throw new TypeError('snapshotCollection must be an object'); }

  if (typeof opts !== 'undefined' && typeof opts !== 'object') { throw new TypeError('opts must be an object'); }
  opts = opts || {};

  if (typeof opts.localPerspective !== 'undefined' && typeof opts.localPerspective !== 'string') { throw new TypeError('opts.localPerspective must be a string'); }
  if (typeof opts.debug !== 'undefined' && typeof opts.debug !== 'boolean') { throw new TypeError('opts.debug must be a boolean'); }
  if (typeof opts.hide !== 'undefined' && typeof opts.hide !== 'boolean') { throw new TypeError('opts.hide must be a boolean'); }
  if (typeof opts.raw !== 'undefined' && typeof opts.raw !== 'boolean') { throw new TypeError('opts.raw must be a boolean'); }
  if (typeof opts.filter !== 'undefined' && typeof opts.filter !== 'object') { throw new TypeError('opts.filter must be an object'); }
  if (typeof opts.offset !== 'undefined' && typeof opts.offset !== 'string') { throw new TypeError('opts.offset must be a string'); }
  if (typeof opts.follow !== 'undefined' && typeof opts.follow !== 'boolean') { throw new TypeError('opts.follow must be a boolean'); }
  if (typeof opts.tailableRetryInterval !== 'undefined' && typeof opts.tailableRetryInterval !== 'number') { throw new TypeError('opts.tailableRetryInterval must be a number'); }
  if (typeof opts.hooks !== 'undefined' && !(opts.hooks instanceof Array)) { throw new TypeError('opts.hooks must be an array'); }
  if (typeof opts.hooksOpts !== 'undefined' && typeof opts.hooksOpts !== 'object') { throw new TypeError('opts.hooksOpts must be an object'); }

  this._snapshotCollection = snapshotCollection;

  this._db = snapshotCollection.db;

  this._snapshotCollectionName = snapshotCollection.collectionName;

  this._localPerspective = opts.localPerspective || '_local';
  this._debug = opts.debug || false;
  this._hide = opts.hide || false;
  this._raw = opts.raw || false;
  this._filter = opts.filter || {};
  this._offset = opts.offset || '';

  this._debugName = this._db.databaseName + '.' + this._snapshotCollectionName;

  if (typeof opts.follow === 'boolean') {
    this._follow = opts.follow;
  } else {
    this._follow = true;
  }
  this._hooks = opts.hooks || [];
  this._hooksOpts = opts.hooksOpts || {};

  Readable.call(this, { objectMode: !this._raw });

  var selector = { '_id._pe': this._localPerspective };
  var mongoOpts = { sort: { '$natural': 1 }, tailable: this._follow, comment: 'tail' };
  mongoOpts.tailableRetryInterval = opts.tailableRetryInterval || 2000;

  if (this._debug) { console.log('vcr %s: selector %s filter %s opts %s', this._debugName, JSON.stringify(selector), JSON.stringify(this._filter), JSON.stringify(mongoOpts)); }

  this._source = this._snapshotCollection.find(selector, mongoOpts).stream();

  var that = this;

  this._maxTries = 0;

  // emit a connected graph by making sure every parent of any filtered item is filtered
  var heads = {};
  var offsetReached = false;
  if (!this._offset) {
    offsetReached = true;
  }
  var i = 0;

  function handleData(item, cb) {
    if (that._debug && offsetReached) { console.log('vcr %s: _read %s', that._debugName, JSON.stringify(item._id)); }

    // only start emitting after the offset is encountered
    if (!offsetReached) {
      if (item._id._v === that._offset) {
        if (that._debug) { console.log('vcr %s: _read offset reached %s', that._debugName, JSON.stringify(item._id)); }
        offsetReached = true;
      } else {
        // the offset should be encountered within maxTries
        i++;
        if (i >= that._maxTries) {
          if (!that._hide) { console.error('vcr %s: _read offset not found %s %s %s', that._debugName, that._offset, i, that._maxTries); }
          cb(new Error('offset not found'));
          return;
        }
      }
    }

    heads[item._id._v] = [];

    // move previously emitted parents along with this new branch head
    async.eachSeries(item._id._pa, function(p, cb2) {
      if (heads[p]) {
        // ff and takeover parent references from old head
        Array.prototype.push.apply(heads[item._id._v], heads[p]);
        delete heads[p];
        process.nextTick(cb2);
      } else {
        // branched off, find the lowest filtered ancestor of this item and save it as parent reference
        var lastEmitted = {};
        lastEmitted['_id._id'] = item._id._id;
        lastEmitted['_id._pe'] = that._localPerspective;

        walkBranch(lastEmitted, p, that._localPerspective, that._snapshotCollection, function(anItem, cb3) {
          // skip if not all criteria hold on this item
          if (!match(that._filter, anItem)) {
            cb3();
            return;
          }

          // make sure the ancestor is not already in the array, this can happen on merge items.
          if (!heads[item._id._v].some(function(pp) { return pp === anItem._id._v; })) {
            heads[item._id._v].push(anItem._id._v);
          }
          cb3(null, true);
        }, function(err) {
          if (err) {
            if (!that._hide) { console.error('vcr %s %s could not determine last emitted version before %s %s %s', p, lastEmitted, err); }
            cb2(err);
            return;
          }
          cb2();
        });
      }
    }, function(err) {
      if (err) { cb(err); return; }

      // don't emit if not all criteria hold on this item
      if (!match(that._filter, item)) { cb(); return; }

      // load all hooks on this item, then, if offset is reached, callback
      runHooks(that._hooks, that._db, item, that._hooksOpts, function(err, afterItem) {
        if (err) { cb(err); return; }

        // return if hooks filter out the item
        if (!afterItem) {
          if (that._debug && offsetReached) { console.log('vcr %s: vcr hook filtered %s', that._debugName, JSON.stringify(item._id)); }
          cb();
          return;
        }

        // set parents to last returned version of this branch
        item._id._pa = heads[item._id._v];

        // then update branch with _id of this item
        heads[item._id._v] = [item._id._v];

        // all criteria hold, so return this item if offset is reached
        if (offsetReached) {
          item = afterItem;

          // remove perspective and local state and run any transformation
          delete item._id._pe;
          delete item._id._lo;
          delete item._id._i;
          delete item._m3._op;
          delete item._m3._ack;

          // push the raw or parsed item out to the reader, and resume if not flooded
          if (that._debug) { console.log('vcr %s: push %s', that._debugName, JSON.stringify(item._id)); }
          var proceed = that.push(that._raw ? BSON.serialize(item) : item);
          if (!proceed) { that._queue.pause(); }
        }
        cb();
      });
    });
  }

  this._queue = async.queue(handleData, 1);

  this._queue.saturated = function() {
    that._source.pause();
  };

  this._queue.empty = function() {
    that._source.resume();
  };

  // pause queue to determine maxTries
  this._queue.pause();

  // determine the maximum number of versions to examine before the offset must have been encountered
  this._snapshotCollection.count(function(err, count) {
    if (err) { throw err; }
    that._maxTries = count;
    that._queue.resume();
  });

  this._source.on('data', function(item) {
    that._queue.push(item, function(err) {
      if (err) {
        that._queue.kill();
        that._source.destroy();
        that.emit('error', err);
      }
    });
  });

  // proxy error
  this._source.on('error', function(err) {
    if (!that._hide) { console.error('vcr %s: cursor stream error %s', that._debugName, err); }
    that._queue.kill();
    that.emit('error', err);
  });

  this._source.on('close', function() {
    if (that._debug) { console.log('vcr %s: cursor stream closed', that._debugName); }

    // end this stream as soon as the queue is completely processed
    if (that._queue.idle()) {
      that.push(null);
    } else {
      that._queue.drain = function() {
        that.push(null);
      };
    }
  });
}
util.inherits(VersionedCollectionReader, Readable);

module.exports = VersionedCollectionReader;

/**
 * Stop the stream reader. An "end" event will be emitted.
 */
VersionedCollectionReader.prototype.close = function close() {
  if (this._debug) { console.log('vcr %s: closing cursor', this._debugName); }
  this._queue.kill();
  this._source.destroy();
};

/////////////////////
//// PRIVATE API ////
/////////////////////

/**
 * Implementation of _read method of Readable stream. This method is not called
 * directly. In this implementation size of read buffer is ignored
 */
VersionedCollectionReader.prototype._read = function() {
  this._queue.resume();
};
<|endoftext|>


<commit_before>function CacheEntry()
{
    this.ready = false;
    this.err = null;
    this.renderer = null;
    this.ctime = this.atime = Date.now(); // last access time
    this.cb = [];
    this._refcount = 0;
    this.id = ('' + Math.random()).substr(5, 4); // this is for debugging only
    /*
     console.log("CacheEntry " + this.id + " created");
     */
}

CacheEntry.prototype = Object.create(require('events').EventEmitter.prototype);

CacheEntry.prototype.pushCallback = function(cb) {
    this._addRef();
    if ( this.ready ) {
        cb(this.err, this, true);
        this.setLastUsed(Date.now()); // update last access time;
    } else {
        this.cb.push(cb);
    }
};

// Get one tile from the service
CacheEntry.prototype.getTile = function(z, x, y, cb) {
    this.renderer.getTile.apply(this.renderer, [z, x, y, cb]);
};

CacheEntry.prototype.getMetadata = function(z, x, y, cb) {
    this.renderer.getMetadata.apply(this.renderer, [z, x, y, cb]);
};

// Get the contained entry
CacheEntry.prototype.get = function() {
    return this.renderer.get();
};

CacheEntry.prototype.setReady = function(err, renderer) {
    // consistency check
    if ( this.ready ) {
        throw new Error("Invalid call to CacheEntry.setReady on an ready entry");
    }
    this.ready = true;
    this.err = err;
    this.renderer = renderer;

    var cached = false;
    var cb = this.cb.shift();
    while (cb) {
        cb(err, this, cached);
        cached = true;
        cb = this.cb.shift();
    }

    // TODO: update last access time here ?
    this.emit('ready', this);

    if ( err ) {
        this.emit('error', err);
    }
};

// Call this as soon as you get a reference to the object
// if you plan to use it for longer than the current tick.
// Call dropRef when finished with it.
CacheEntry.prototype._addRef = function() {
    ++this._refcount;
};

CacheEntry.prototype.release = function() {
    this._dropRef();
};

CacheEntry.prototype._dropRef = function() {
    if ( ! --this._refcount ) {
        this._destroy();
    }
};

CacheEntry.prototype.setLastUsed = function(t) {
    this.atime = t;
};

CacheEntry.prototype.timeSinceLastAccess = function(now) {
    var age = ( now - this.atime );
    return age;
};

// Destroy (now or ASAP) a CacheEntry
//
// TODO: accept a callback ?
//
CacheEntry.prototype._destroy = function() {

    // integrity checks
    if ( this.cb.length ) {
        throw new Error("CacheEntry._destroy was called while still having " + this.cb.length + " callbacks pending");
    }
    if ( this._refcount ) {
        throw new Error("CacheEntry._destroy was called while still having " + this._refcount + " references");
    }

    if ( ! this.ready ) {
        // not ready yet, try later
        //console.log("cache_entry " + this.id + " isn't ready yet, scheduling destruction on 'ready' event");
        this.on('ready', this._destroy.bind(this));
    }
    else if ( ! this.renderer ) {
        // nothing to do
        //console.log("This cache entry is ready but has no renderer, so nothing to do");
    }
    else {
        //console.log("Calling .close on cache_entry " + this.id);
        // TODO: fixme: we can't modify the renderer here because
        //       tilelive-mapnik is keeping an internal cache and
        //       so modifying an object we'd be modifying something
        //       which will possibly be reused later.
        //       See https://github.com/mapbox/tilelive-mapnik/issues/47
        //
        //this.renderer._pool.destroyAllNow();
        this.renderer.close(function() {}); // TODO: accept a callback ?
    }
};

module.exports = CacheEntry;
<commit_msg>Call getRenderer just with the only argument, the callback<commit_after>function CacheEntry()
{
    this.ready = false;
    this.err = null;
    this.renderer = null;
    this.ctime = this.atime = Date.now(); // last access time
    this.cb = [];
    this._refcount = 0;
    this.id = ('' + Math.random()).substr(5, 4); // this is for debugging only
    /*
     console.log("CacheEntry " + this.id + " created");
     */
}

CacheEntry.prototype = Object.create(require('events').EventEmitter.prototype);

CacheEntry.prototype.pushCallback = function(cb) {
    this._addRef();
    if ( this.ready ) {
        cb(this.err, this, true);
        this.setLastUsed(Date.now()); // update last access time;
    } else {
        this.cb.push(cb);
    }
};

// Get one tile from the service
CacheEntry.prototype.getTile = function(z, x, y, cb) {
    this.renderer.getTile.apply(this.renderer, [z, x, y, cb]);
};

CacheEntry.prototype.getMetadata = function(cb) {
    this.renderer.getMetadata.apply(this.renderer, [cb]);
};

// Get the contained entry
CacheEntry.prototype.get = function() {
    return this.renderer.get();
};

CacheEntry.prototype.setReady = function(err, renderer) {
    // consistency check
    if ( this.ready ) {
        throw new Error("Invalid call to CacheEntry.setReady on an ready entry");
    }
    this.ready = true;
    this.err = err;
    this.renderer = renderer;

    var cached = false;
    var cb = this.cb.shift();
    while (cb) {
        cb(err, this, cached);
        cached = true;
        cb = this.cb.shift();
    }

    // TODO: update last access time here ?
    this.emit('ready', this);

    if ( err ) {
        this.emit('error', err);
    }
};

// Call this as soon as you get a reference to the object
// if you plan to use it for longer than the current tick.
// Call dropRef when finished with it.
CacheEntry.prototype._addRef = function() {
    ++this._refcount;
};

CacheEntry.prototype.release = function() {
    this._dropRef();
};

CacheEntry.prototype._dropRef = function() {
    if ( ! --this._refcount ) {
        this._destroy();
    }
};

CacheEntry.prototype.setLastUsed = function(t) {
    this.atime = t;
};

CacheEntry.prototype.timeSinceLastAccess = function(now) {
    var age = ( now - this.atime );
    return age;
};

// Destroy (now or ASAP) a CacheEntry
//
// TODO: accept a callback ?
//
CacheEntry.prototype._destroy = function() {

    // integrity checks
    if ( this.cb.length ) {
        throw new Error("CacheEntry._destroy was called while still having " + this.cb.length + " callbacks pending");
    }
    if ( this._refcount ) {
        throw new Error("CacheEntry._destroy was called while still having " + this._refcount + " references");
    }

    if ( ! this.ready ) {
        // not ready yet, try later
        //console.log("cache_entry " + this.id + " isn't ready yet, scheduling destruction on 'ready' event");
        this.on('ready', this._destroy.bind(this));
    }
    else if ( ! this.renderer ) {
        // nothing to do
        //console.log("This cache entry is ready but has no renderer, so nothing to do");
    }
    else {
        //console.log("Calling .close on cache_entry " + this.id);
        // TODO: fixme: we can't modify the renderer here because
        //       tilelive-mapnik is keeping an internal cache and
        //       so modifying an object we'd be modifying something
        //       which will possibly be reused later.
        //       See https://github.com/mapbox/tilelive-mapnik/issues/47
        //
        //this.renderer._pool.destroyAllNow();
        this.renderer.close(function() {}); // TODO: accept a callback ?
    }
};

module.exports = CacheEntry;
<|endoftext|>


<commit_before>module.exports = [
  {
    collection: 'entries',
    spec: { locationId: 1 },
    options: {},
  },
  {
    collection: 'events',
    spec: { time: 1 },
    options: {},
  },
  {
    collection: 'events',
    spec: { locationId: 1 },
    options: {},
  },
  {
    collection: 'locations',
    spec: { geom: '2dsphere' },
    options: {},
  },
  {
    collection: 'locations',
    spec: { layer: 1 },
    options: {},
  },
  {
    // Text index
    collection: 'locations',
    spec: {
      text1: 'text',  // primary
      text2: 'text',  // secondary
    },
    options: {
      weights: {
        text1: 3,
        text2: 1,
      },
      name: 'TextIndex',
    },
  },
  {
    collection: 'users',
    spec: { email: 1 },
    options: { unique: true },
  },
  {
    collection: 'users',
    spec: { name: 1 },
    options: { unique: true },
  },
];
<commit_msg>Create a compound index for status and type<commit_after>module.exports = [
  {
    collection: 'entries',
    spec: { locationId: 1 },
    options: {},
  },
  {
    collection: 'events',
    spec: { time: 1 },
    options: {},
  },
  {
    collection: 'events',
    spec: { locationId: 1 },
    options: {},
  },
  {
    collection: 'locations',
    spec: { geom: '2dsphere' },
    options: {},
  },
  {
    collection: 'locations',
    spec: { layer: 1 },
    options: {},
  },
  {
    collection: 'locations',
    spec: { status: 1, type: 1 },
    options: {},
  },
  {
    // Text index
    collection: 'locations',
    spec: {
      text1: 'text',  // primary
      text2: 'text',  // secondary
    },
    options: {
      weights: {
        text1: 3,
        text2: 1,
      },
      name: 'TextIndex',
    },
  },
  {
    collection: 'users',
    spec: { email: 1 },
    options: { unique: true },
  },
  {
    collection: 'users',
    spec: { name: 1 },
    options: { unique: true },
  },
];
<|endoftext|>


<commit_before>/* eslint-disable no-var */

exports.locationTypeToSymbolUrl = function (type) {
  var baseUrl = '/assets/images/markers/symbols/'
  return baseUrl + type + '.png'
}

exports.markerIconUrl = function (templateName, symbolName) {
  var iconName = templateName + '-' + symbolName + '.png'
  return '/api/icons/' + iconName
}
<commit_msg>Ensure only client side usage<commit_after>/* eslint-disable no-var */

if (!tresdb.config) {
  throw new Error(
    'No client-side configuration detected. ' +
    'Ensure the urls module is called from client-side code ' +
    'and after configuration is set.'
  )
}

var staticUrl = tresdb.config.staticUrl

exports.locationTypeToSymbolUrl = function (type) {
  var baseUrl = staticUrl + '/images/markers/symbols/'
  return baseUrl + type + '.png'
}

exports.markerIconUrl = function (templateName, symbolName) {
  var iconName = templateName + '-' + symbolName + '.png'
  return '/api/icons/' + iconName
}
<|endoftext|>


<commit_before>var log = require('../../utils/logger');
var toJson = require('../../utils/to_json');
var async = require('async');
var path = require('path');
var EmailTemplate = require('email-templates').EmailTemplate;
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var ejs = require('ejs');
var i18n = require('../../utils/i18n');
var airbrake = null;
if(process.env.AIRBRAKE_PROJECT_ID) {
  airbrake = require('../../utils/airbrake');
}
var fs = require('fs');

var templatesDir = path.resolve(__dirname, '..', '..', 'email_templates', 'notifications');

var DEBUG_EMAILS_TO_TEMP_FIlE = false;

var queue = require('../../workers/queue');
var models = require("../../../models");

var i18nFilter = function(text) {
  return i18n.t(text);
};

var transport = null;

if( process.env.SENDGRID_USERNAME ) {
  transport = nodemailer.createTransport({
    service: 'sendgrid',
    auth: {
      user: process.env.SENDGRID_USERNAME,
      pass: process.env.SENDGRID_PASSWORD
    }
  });
} else if( process.env.SMTP_USERNAME ) {
  var smtpConfig = {
    host: process.env.SMTP_SERVER,
    port: process.env.SMTP_PORT,
    secure: false, // upgrade later with STARTTLS
    auth: {
      user: process.env.SMTP_USERNAME,
      pass: process.env.SMTP_PASSWORD
    }
  };

  transport = nodemailer.createTransport(smtpTransport(smtpConfig));

  console.log('SMTP Configured');

  transport.verify(function(error, success) {
    if (error) {
      console.warn('ERROR');
      console.warn(error);
    } else {
      console.log('Server is ready to take our messages');
    }
  });
}

var translateSubject = function (subjectHash) {
  var subject = i18n.t(subjectHash.translateToken);
  if (subjectHash.contentName) {
    subject += ": "+subjectHash.contentName
  }
  return subject;
};

var linkTo = function (url) {
  return ''+url+'';
};

var filterNotificationForDelivery = function (notification, user, template, subject, callback) {
  var method = user.notifications_settings[notification.from_notification_setting].method;
  var frequency = user.notifications_settings[notification.from_notification_setting].frequency;

  //TODO: Switch from FREQUENCY_AS_IT_HAPPENS if user has had a lot of emails > 25 in the hour or something

  console.log("Notification Email Processing", {email: user.email, notification_settings_type: notification.notification_setting_type,
                                                method: method, frequency: frequency});

  if (method !== models.AcNotification.METHOD_MUTED) {
    if (frequency === models.AcNotification.FREQUENCY_AS_IT_HAPPENS) {
      console.log("Notification Email Processing Sending eMail", {email: user.email, method: method, frequency: frequency});
      queue.create('send-one-email', {
        subject: subject,
        template: template,
        user: user,
        domain: notification.AcActivities[0].Domain,
        group: (notification.AcActivities[0].Point && notification.AcActivities[0].Point.Group && notification.AcActivities[0].Point.Group.name!="hidden_public_group_for_domain_level_points") ?
          notification.AcActivities[0].Point.Group : notification.AcActivities[0].Group,
        community: notification.AcActivities[0].Community,
        activity: notification.AcActivities[0],
        post: notification.AcActivities[0].Post,
        point: notification.AcActivities[0].Point
      }).priority('critical').removeOnComplete(true).save();
      callback();
    } else if (method !== models.AcNotification.METHOD_MUTED) {
      models.AcDelayedNotification.findOrCreate({
        where: {
          user_id: user.id,
          method: method,
          frequency: frequency
        },
        defaults: {
          user_id: user.id,
          method: method,
          frequency: frequency,
          type: notification.from_notification_setting
        }
      }).spread(function(delayedNotification, created) {
        if (created) {
          log.info('Notification Email Processing AcDelayedNotification Created', { delayedNotification: toJson(delayedNotification), context: 'create' });
        } else {
          log.info('Notification Email Processing AcDelayedNotification Loaded', { delayedNotification: toJson(delayedNotification), context: 'loaded' });
        }
        delayedNotification.addAcNotifications(notification).then(function (results) {
          if (delayedNotification.delivered) {
            log.info('Notification Email Processing AcDelayedNotification already delivered resetting');
            delayedNotification.delivered = false;
            delayedNotification.save().then(function (results) {
              callback();
            });
          } else {
            callback();
          }
        });
      }).catch(function (error) {
        callback(error);
      });
    }
  } else {
    callback();
  }
};

var sendOneEmail = function (emailLocals, callback) {
  var template, fromEmail;

  async.series([
    function (seriesCallback) {
      if (emailLocals.domain && emailLocals.domain.domain_name) {
        seriesCallback();
      } else {
        log.error("EmailWorker Can't find domain for email", {emailLocals: emailLocals});
        seriesCallback("Can't find domain for email");
      }
    },

    function (seriesCallback) {
      log.info("EmailWorker Started Setup", {});

      template = new EmailTemplate(path.join(templatesDir, emailLocals.template));

      emailLocals['t'] = i18nFilter;
      emailLocals['linkTo'] = linkTo;

      if (!emailLocals['community']) {
        emailLocals['community'] = {hostname: 'www'}
      }

      if (emailLocals.domain.domain_name.indexOf('betrireykjavik.is') > -1) {
        fromEmail = 'Betri Reykjavík <betrireykjavik@ibuar.is>';
      } else if (emailLocals.domain.domain_name.indexOf('betraisland.is') > -1) {
        fromEmail = 'Betra Ísland <betraisland@ibuar.is>';
      } else if (emailLocals.domain.domain_name.indexOf('forbrukerradet.no') > -1) {
        fromEmail = 'Mine idéer Forbrukerrådet <mineideer@forbrukerradet.no>';
      } else {
        fromEmail = 'Your Priorities <admin@yrpri.org>';
      }

      emailLocals.headerImageUrl = "";
      seriesCallback();
    },

    function (seriesCallback) {
      log.info("EmailWorker Started Locale", {});
      var locale;

      if (emailLocals.user.default_locale && emailLocals.user.default_locale != "") {
        locale = emailLocals.user.default_locale;
      } else if (emailLocals.community && emailLocals.community.default_locale && emailLocals.community.default_locale != "") {
        locale = emailLocals.community.default_locale;
      } else if (emailLocals.domain && emailLocals.domain.default_locale && emailLocals.domain.default_locale != "") {
        locale = emailLocals.domain.default_locale;
      } else {
        locale = 'en';
      }

      log.info("EmailWorker Selected locale", {locale: locale});

      i18n.changeLanguage(locale, function (err, t) {
        seriesCallback(err);
      });
    },

    function (seriesCallback) {
      log.info("EmailWorker Started Sending", {});

      template.render(emailLocals, function (error, results) {
        if (error) {
          log.error('EmailWorker Error', { err: error, userId: emailLocals.user.id });
          seriesCallback(error);
        } else {
          var translatedSubject = translateSubject(emailLocals.subject);

          if (transport) {
            transport.sendMail({
              from: fromEmail, // emailLocals.community.admin_email,
              to: emailLocals.user.email,
              bcc: 'robert@citizens.is',
              subject: translatedSubject,
              html: results.html,
              text: results.text
            }, function (error, responseStatus) {
              if (error) {
                log.error('EmailWorker', { err: error, user: emailLocals.user });
                seriesCallback(error);
              } else {
                log.info('EmailWorker Completed', { responseStatusMessage: responseStatus.message, email: emailLocals.user.email, userId: emailLocals.user.id });
                seriesCallback();
              }
            })
          } else {
            log.warn('EmailWorker no email configured.', { subject: translatedSubject, userId: emailLocals.user.id, resultsHtml: results.html , resultsText: results.text });
            if (DEBUG_EMAILS_TO_TEMP_FIlE) {
              var fileName = "/tmp/testHtml_"+parseInt(Math.random() * (423432432432 - 1232) + 1232)+".html";
              fs.unlink(fileName, function (err) {
                fs.writeFile(fileName, results.html, function(err) {
                  if(err) {
                    console.log(err);
                  }
                  seriesCallback();
                });
              });
            } else {
              seriesCallback();
            }
          }
        }
      });
    }
  ], function (error) {
    if (error) {
      log.error("EmailWorker Error", {err: error});
      if(airbrake) {
        airbrake.notify(error, function(airbrakeErr, url) {
          if (airbrakeErr) {
            log.error("AirBrake Error", { context: 'airbrake', err: airbrakeErr, errorStatus: 500 });
          }
          callback(error);
        });
      }
    } else {
      callback();
    }
  });
};

module.exports = {
  filterNotificationForDelivery: filterNotificationForDelivery,
  sendOneEmail: sendOneEmail
};
<commit_msg>Email layout<commit_after>var DEBUG_EMAILS_TO_TEMP_FIlE = false;

var log = require('../../utils/logger');
var toJson = require('../../utils/to_json');
var async = require('async');
var path = require('path');
var EmailTemplate = require('email-templates').EmailTemplate;
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var ejs = require('ejs');
var i18n = require('../../utils/i18n');
var airbrake = null;
if(process.env.AIRBRAKE_PROJECT_ID) {
  airbrake = require('../../utils/airbrake');
}
var fs = require('fs');

var templatesDir = path.resolve(__dirname, '..', '..', 'email_templates', 'notifications');

var queue = require('../../workers/queue');
var models = require("../../../models");

var i18nFilter = function(text) {
  return i18n.t(text);
};

var transport = null;

if( process.env.SENDGRID_USERNAME ) {
  transport = nodemailer.createTransport({
    service: 'sendgrid',
    auth: {
      user: process.env.SENDGRID_USERNAME,
      pass: process.env.SENDGRID_PASSWORD
    }
  });
} else if( process.env.SMTP_USERNAME ) {
  var smtpConfig = {
    host: process.env.SMTP_SERVER,
    port: process.env.SMTP_PORT,
    secure: false, // upgrade later with STARTTLS
    auth: {
      user: process.env.SMTP_USERNAME,
      pass: process.env.SMTP_PASSWORD
    }
  };

  transport = nodemailer.createTransport(smtpTransport(smtpConfig));

  console.log('SMTP Configured');

  transport.verify(function(error, success) {
    if (error) {
      console.warn('ERROR');
      console.warn(error);
    } else {
      console.log('Server is ready to take our messages');
    }
  });
}

var translateSubject = function (subjectHash) {
  var subject = i18n.t(subjectHash.translateToken);
  if (subjectHash.contentName) {
    subject += ": "+subjectHash.contentName
  }
  return subject;
};

var linkTo = function (url) {
  return ''+url+'';
};

var filterNotificationForDelivery = function (notification, user, template, subject, callback) {
  var method = user.notifications_settings[notification.from_notification_setting].method;
  var frequency = user.notifications_settings[notification.from_notification_setting].frequency;

  //TODO: Switch from FREQUENCY_AS_IT_HAPPENS if user has had a lot of emails > 25 in the hour or something

  console.log("Notification Email Processing", {email: user.email, notification_settings_type: notification.notification_setting_type,
                                                method: method, frequency: frequency});

  if (method !== models.AcNotification.METHOD_MUTED) {
    if (frequency === models.AcNotification.FREQUENCY_AS_IT_HAPPENS) {
      console.log("Notification Email Processing Sending eMail", {email: user.email, method: method, frequency: frequency});
      queue.create('send-one-email', {
        subject: subject,
        template: template,
        user: user,
        domain: notification.AcActivities[0].Domain,
        group: (notification.AcActivities[0].Point && notification.AcActivities[0].Point.Group && notification.AcActivities[0].Point.Group.name!="hidden_public_group_for_domain_level_points") ?
          notification.AcActivities[0].Point.Group : notification.AcActivities[0].Group,
        community: notification.AcActivities[0].Community,
        activity: notification.AcActivities[0],
        post: notification.AcActivities[0].Post,
        point: notification.AcActivities[0].Point
      }).priority('critical').removeOnComplete(true).save();
      callback();
    } else if (method !== models.AcNotification.METHOD_MUTED) {
      models.AcDelayedNotification.findOrCreate({
        where: {
          user_id: user.id,
          method: method,
          frequency: frequency
        },
        defaults: {
          user_id: user.id,
          method: method,
          frequency: frequency,
          type: notification.from_notification_setting
        }
      }).spread(function(delayedNotification, created) {
        if (created) {
          log.info('Notification Email Processing AcDelayedNotification Created', { delayedNotification: toJson(delayedNotification), context: 'create' });
        } else {
          log.info('Notification Email Processing AcDelayedNotification Loaded', { delayedNotification: toJson(delayedNotification), context: 'loaded' });
        }
        delayedNotification.addAcNotifications(notification).then(function (results) {
          if (delayedNotification.delivered) {
            log.info('Notification Email Processing AcDelayedNotification already delivered resetting');
            delayedNotification.delivered = false;
            delayedNotification.save().then(function (results) {
              callback();
            });
          } else {
            callback();
          }
        });
      }).catch(function (error) {
        callback(error);
      });
    }
  } else {
    callback();
  }
};

var sendOneEmail = function (emailLocals, callback) {
  var template, fromEmail;

  async.series([
    function (seriesCallback) {
      if (emailLocals.domain && emailLocals.domain.domain_name) {
        seriesCallback();
      } else {
        log.error("EmailWorker Can't find domain for email", {emailLocals: emailLocals});
        seriesCallback("Can't find domain for email");
      }
    },

    function (seriesCallback) {
      log.info("EmailWorker Started Setup", {});

      template = new EmailTemplate(path.join(templatesDir, emailLocals.template));

      emailLocals['t'] = i18nFilter;
      emailLocals['linkTo'] = linkTo;

      if (!emailLocals['community']) {
        emailLocals['community'] = {hostname: 'www'}
      }

      if (emailLocals.domain.domain_name.indexOf('betrireykjavik.is') > -1) {
        fromEmail = 'Betri Reykjavík <betrireykjavik@ibuar.is>';
      } else if (emailLocals.domain.domain_name.indexOf('betraisland.is') > -1) {
        fromEmail = 'Betra Ísland <betraisland@ibuar.is>';
      } else if (emailLocals.domain.domain_name.indexOf('forbrukerradet.no') > -1) {
        fromEmail = 'Mine idéer Forbrukerrådet <mineideer@forbrukerradet.no>';
      } else {
        fromEmail = 'Your Priorities <admin@yrpri.org>';
      }

      emailLocals.headerImageUrl = "";
      seriesCallback();
    },

    function (seriesCallback) {
      log.info("EmailWorker Started Locale", {});
      var locale;

      if (emailLocals.user.default_locale && emailLocals.user.default_locale != "") {
        locale = emailLocals.user.default_locale;
      } else if (emailLocals.community && emailLocals.community.default_locale && emailLocals.community.default_locale != "") {
        locale = emailLocals.community.default_locale;
      } else if (emailLocals.domain && emailLocals.domain.default_locale && emailLocals.domain.default_locale != "") {
        locale = emailLocals.domain.default_locale;
      } else {
        locale = 'en';
      }

      log.info("EmailWorker Selected locale", {locale: locale});

      i18n.changeLanguage(locale, function (err, t) {
        seriesCallback(err);
      });
    },

    function (seriesCallback) {
      log.info("EmailWorker Started Sending", {});

      template.render(emailLocals, function (error, results) {
        if (error) {
          log.error('EmailWorker Error', { err: error, userId: emailLocals.user.id });
          seriesCallback(error);
        } else {
          var translatedSubject = translateSubject(emailLocals.subject);

          if (transport) {
            transport.sendMail({
              from: fromEmail, // emailLocals.community.admin_email,
              to: emailLocals.user.email,
              bcc: 'robert@citizens.is',
              subject: translatedSubject,
              html: results.html,
              text: results.text
            }, function (error, responseStatus) {
              if (error) {
                log.error('EmailWorker', { err: error, user: emailLocals.user });
                seriesCallback(error);
              } else {
                log.info('EmailWorker Completed', { responseStatusMessage: responseStatus.message, email: emailLocals.user.email, userId: emailLocals.user.id });
                seriesCallback();
              }
            })
          } else {
            log.warn('EmailWorker no email configured.', { subject: translatedSubject, userId: emailLocals.user.id, resultsHtml: results.html , resultsText: results.text });
            if (DEBUG_EMAILS_TO_TEMP_FIlE) {
              var fileName = "/tmp/testHtml_"+parseInt(Math.random() * (423432432432 - 1232) + 1232)+".html";
              fs.unlink(fileName, function (err) {
                fs.writeFile(fileName, results.html, function(err) {
                  if(err) {
                    console.log(err);
                  }
                  seriesCallback();
                });
              });
            } else {
              seriesCallback();
            }
          }
        }
      });
    }
  ], function (error) {
    if (error) {
      log.error("EmailWorker Error", {err: error});
      if(airbrake) {
        airbrake.notify(error, function(airbrakeErr, url) {
          if (airbrakeErr) {
            log.error("AirBrake Error", { context: 'airbrake', err: airbrakeErr, errorStatus: 500 });
          }
          callback(error);
        });
      }
    } else {
      callback();
    }
  });
};

module.exports = {
  filterNotificationForDelivery: filterNotificationForDelivery,
  sendOneEmail: sendOneEmail
};
<|endoftext|>


<commit_before>/**
* The `Matter.MouseConstraint` module contains methods for creating mouse constraints.
* Mouse constraints are used for allowing user interaction, providing the ability to move bodies via the mouse or touch.
*
* See [Demo.js](https://github.com/liabru/matter-js/blob/master/demo/js/Demo.js)
* and [DemoMobile.js](https://github.com/liabru/matter-js/blob/master/demo/js/DemoMobile.js) for usage examples.
*
* @class MouseConstraint
*/

var MouseConstraint = {};

(function() {

    /**
     * Creates a new mouse constraint.
     * All properties have default values, and many are pre-calculated automatically based on other properties.
     * See the properites section below for detailed information on what you can pass via the `options` object.
     * @method create
     * @param {engine} engine
     * @param {} options
     * @return {MouseConstraint} A new MouseConstraint
     */
    MouseConstraint.create = function(engine, options) {
        var mouse = (engine ? engine.mouse : null) || (options ? options.mouse : null);

        if (!mouse && engine && engine.render && engine.render.canvas) {
            mouse = Mouse.create(engine.render.canvas);
        } else {
            mouse = Mouse.create();
            Common.log('MouseConstraint.create: options.mouse was undefined, engine.render.canvas was undefined, may not function as expected', 'warn');
        }

        var constraint = Constraint.create({
            label: 'Mouse Constraint',
            pointA: mouse.position,
            pointB: { x: 0, y: 0 },
            length: 0.01,
            stiffness: 0.1,
            angularStiffness: 1,
            render: {
                strokeStyle: '#90EE90',
                lineWidth: 3
            }
        });

        var defaults = {
            type: 'mouseConstraint',
            mouse: mouse,
            body: null,
            constraint: constraint,
            collisionFilter: {
                category: 0x0001,
                mask: 0xFFFFFFFF,
                group: 0
            }
        };

        var mouseConstraint = Common.extend(defaults, options);

        Events.on(engine, 'tick', function() {
            var allBodies = Composite.allBodies(engine.world);
            MouseConstraint.update(mouseConstraint, allBodies);
            _triggerEvents(mouseConstraint);
        });

        return mouseConstraint;
    };

    /**
     * Updates the given mouse constraint.
     * @private
     * @method update
     * @param {MouseConstraint} mouseConstraint
     * @param {body[]} bodies
     */
    MouseConstraint.update = function(mouseConstraint, bodies) {
        var mouse = mouseConstraint.mouse,
            constraint = mouseConstraint.constraint,
            body = mouseConstraint.body;

        if (mouse.button === 0) {
            if (!constraint.bodyB) {
                for (var i = 0; i < bodies.length; i++) {
                    body = bodies[i];
                    if (Bounds.contains(body.bounds, mouse.position)
                            && Vertices.contains(body.vertices, mouse.position)
                            && Detector.canCollide(body.collisionFilter, mouseConstraint.collisionFilter)) {

                        constraint.pointA = mouse.position;
                        constraint.bodyB = mouseConstraint.body = body;
                        constraint.pointB = { x: mouse.position.x - body.position.x, y: mouse.position.y - body.position.y };
                        constraint.angleB = body.angle;

                        Sleeping.set(body, false);
                        Events.trigger(mouseConstraint, 'startdrag', { mouse: mouse, body: body });
                    }
                }
            } else {
                Sleeping.set(constraint.bodyB, false);
                constraint.pointA = mouse.position;
            }
        } else {
            constraint.bodyB = mouseConstraint.body = null;
            constraint.pointB = null;

            if (body)
                Events.trigger(mouseConstraint, 'enddrag', { mouse: mouse, body: body });
        }
    };

    /**
     * Triggers mouse constraint events
     * @method _triggerEvents
     * @private
     * @param {mouse} mouse
     */
    var _triggerEvents = function(mouseConstraint) {
        var mouse = mouseConstraint.mouse,
            mouseEvents = mouse.sourceEvents;

        if (mouseEvents.mousemove)
            Events.trigger(mouseConstraint, 'mousemove', { mouse: mouse });

        if (mouseEvents.mousedown)
            Events.trigger(mouseConstraint, 'mousedown', { mouse: mouse });

        if (mouseEvents.mouseup)
            Events.trigger(mouseConstraint, 'mouseup', { mouse: mouse });

        // reset the mouse state ready for the next step
        Mouse.clearSourceEvents(mouse);
    };

    /*
    *
    *  Events Documentation
    *
    */

    /**
    * Fired when the mouse has moved (or a touch moves) during the last step
    *
    * @event mousemove
    * @param {} event An event object
    * @param {mouse} event.mouse The engine's mouse instance
    * @param {} event.source The source object of the event
    * @param {} event.name The name of the event
    */

    /**
    * Fired when the mouse is down (or a touch has started) during the last step
    *
    * @event mousedown
    * @param {} event An event object
    * @param {mouse} event.mouse The engine's mouse instance
    * @param {} event.source The source object of the event
    * @param {} event.name The name of the event
    */

    /**
    * Fired when the mouse is up (or a touch has ended) during the last step
    *
    * @event mouseup
    * @param {} event An event object
    * @param {mouse} event.mouse The engine's mouse instance
    * @param {} event.source The source object of the event
    * @param {} event.name The name of the event
    */

    /**
    * Fired when the user starts dragging a body
    *
    * @event startdrag
    * @param {} event An event object
    * @param {mouse} event.mouse The engine's mouse instance
    * @param {body} event.body The body being dragged
    * @param {} event.source The source object of the event
    * @param {} event.name The name of the event
    */

    /**
    * Fired when the user ends dragging a body
    *
    * @event enddrag
    * @param {} event An event object
    * @param {mouse} event.mouse The engine's mouse instance
    * @param {body} event.body The body that has stopped being dragged
    * @param {} event.source The source object of the event
    * @param {} event.name The name of the event
    */

    /*
    *
    *  Properties Documentation
    *
    */

    /**
     * A `String` denoting the type of object.
     *
     * @property type
     * @type string
     * @default "constraint"
     */

    /**
     * The `Mouse` instance in use. If not supplied in `MouseConstraint.create`, one will be created.
     *
     * @property mouse
     * @type mouse
     * @default mouse
     */

    /**
     * The `Body` that is currently being moved by the user, or `null` if no body.
     *
     * @property body
     * @type body
     * @default null
     */

    /**
     * The `Constraint` object that is used to move the body during interaction.
     *
     * @property constraint
     * @type constraint
     */

    /**
     * An `Object` that specifies the collision filter properties.
     * The collision filter allows the user to define which types of body this mouse constraint can interact with.
     * See `body.collisionFilter` for more information.
     *
     * @property collisionFilter
     * @type object
     */

})();
<commit_msg>added support for compound bodies in MouseConstraint<commit_after>/**
* The `Matter.MouseConstraint` module contains methods for creating mouse constraints.
* Mouse constraints are used for allowing user interaction, providing the ability to move bodies via the mouse or touch.
*
* See [Demo.js](https://github.com/liabru/matter-js/blob/master/demo/js/Demo.js)
* and [DemoMobile.js](https://github.com/liabru/matter-js/blob/master/demo/js/DemoMobile.js) for usage examples.
*
* @class MouseConstraint
*/

var MouseConstraint = {};

(function() {

    /**
     * Creates a new mouse constraint.
     * All properties have default values, and many are pre-calculated automatically based on other properties.
     * See the properites section below for detailed information on what you can pass via the `options` object.
     * @method create
     * @param {engine} engine
     * @param {} options
     * @return {MouseConstraint} A new MouseConstraint
     */
    MouseConstraint.create = function(engine, options) {
        var mouse = (engine ? engine.mouse : null) || (options ? options.mouse : null);

        if (!mouse && engine && engine.render && engine.render.canvas) {
            mouse = Mouse.create(engine.render.canvas);
        } else {
            mouse = Mouse.create();
            Common.log('MouseConstraint.create: options.mouse was undefined, engine.render.canvas was undefined, may not function as expected', 'warn');
        }

        var constraint = Constraint.create({
            label: 'Mouse Constraint',
            pointA: mouse.position,
            pointB: { x: 0, y: 0 },
            length: 0.01,
            stiffness: 0.1,
            angularStiffness: 1,
            render: {
                strokeStyle: '#90EE90',
                lineWidth: 3
            }
        });

        var defaults = {
            type: 'mouseConstraint',
            mouse: mouse,
            body: null,
            constraint: constraint,
            collisionFilter: {
                category: 0x0001,
                mask: 0xFFFFFFFF,
                group: 0
            }
        };

        var mouseConstraint = Common.extend(defaults, options);

        Events.on(engine, 'tick', function() {
            var allBodies = Composite.allBodies(engine.world);
            MouseConstraint.update(mouseConstraint, allBodies);
            _triggerEvents(mouseConstraint);
        });

        return mouseConstraint;
    };

    /**
     * Updates the given mouse constraint.
     * @private
     * @method update
     * @param {MouseConstraint} mouseConstraint
     * @param {body[]} bodies
     */
    MouseConstraint.update = function(mouseConstraint, bodies) {
        var mouse = mouseConstraint.mouse,
            constraint = mouseConstraint.constraint,
            body = mouseConstraint.body;

        if (mouse.button === 0) {
            if (!constraint.bodyB) {
                for (var i = 0; i < bodies.length; i++) {
                    body = bodies[i];
                    if (Bounds.contains(body.bounds, mouse.position)
                            && Detector.canCollide(body.collisionFilter, mouseConstraint.collisionFilter)) {
                        for (var j = body.parts.length > 1 ? 1 : 0; j < body.parts.length; j++) {
                            var part = body.parts[j];
                            if (Vertices.contains(part.vertices, mouse.position)) {
                                constraint.pointA = mouse.position;
                                constraint.bodyB = mouseConstraint.body = body;
                                constraint.pointB = { x: mouse.position.x - body.position.x, y: mouse.position.y - body.position.y };
                                constraint.angleB = body.angle;

                                Sleeping.set(body, false);
                                Events.trigger(mouseConstraint, 'startdrag', { mouse: mouse, body: body });

                                break;
                            }
                        }
                    }
                }
            } else {
                Sleeping.set(constraint.bodyB, false);
                constraint.pointA = mouse.position;
            }
        } else {
            constraint.bodyB = mouseConstraint.body = null;
            constraint.pointB = null;

            if (body)
                Events.trigger(mouseConstraint, 'enddrag', { mouse: mouse, body: body });
        }
    };

    /**
     * Triggers mouse constraint events
     * @method _triggerEvents
     * @private
     * @param {mouse} mouse
     */
    var _triggerEvents = function(mouseConstraint) {
        var mouse = mouseConstraint.mouse,
            mouseEvents = mouse.sourceEvents;

        if (mouseEvents.mousemove)
            Events.trigger(mouseConstraint, 'mousemove', { mouse: mouse });

        if (mouseEvents.mousedown)
            Events.trigger(mouseConstraint, 'mousedown', { mouse: mouse });

        if (mouseEvents.mouseup)
            Events.trigger(mouseConstraint, 'mouseup', { mouse: mouse });

        // reset the mouse state ready for the next step
        Mouse.clearSourceEvents(mouse);
    };

    /*
    *
    *  Events Documentation
    *
    */

    /**
    * Fired when the mouse has moved (or a touch moves) during the last step
    *
    * @event mousemove
    * @param {} event An event object
    * @param {mouse} event.mouse The engine's mouse instance
    * @param {} event.source The source object of the event
    * @param {} event.name The name of the event
    */

    /**
    * Fired when the mouse is down (or a touch has started) during the last step
    *
    * @event mousedown
    * @param {} event An event object
    * @param {mouse} event.mouse The engine's mouse instance
    * @param {} event.source The source object of the event
    * @param {} event.name The name of the event
    */

    /**
    * Fired when the mouse is up (or a touch has ended) during the last step
    *
    * @event mouseup
    * @param {} event An event object
    * @param {mouse} event.mouse The engine's mouse instance
    * @param {} event.source The source object of the event
    * @param {} event.name The name of the event
    */

    /**
    * Fired when the user starts dragging a body
    *
    * @event startdrag
    * @param {} event An event object
    * @param {mouse} event.mouse The engine's mouse instance
    * @param {body} event.body The body being dragged
    * @param {} event.source The source object of the event
    * @param {} event.name The name of the event
    */

    /**
    * Fired when the user ends dragging a body
    *
    * @event enddrag
    * @param {} event An event object
    * @param {mouse} event.mouse The engine's mouse instance
    * @param {body} event.body The body that has stopped being dragged
    * @param {} event.source The source object of the event
    * @param {} event.name The name of the event
    */

    /*
    *
    *  Properties Documentation
    *
    */

    /**
     * A `String` denoting the type of object.
     *
     * @property type
     * @type string
     * @default "constraint"
     */

    /**
     * The `Mouse` instance in use. If not supplied in `MouseConstraint.create`, one will be created.
     *
     * @property mouse
     * @type mouse
     * @default mouse
     */

    /**
     * The `Body` that is currently being moved by the user, or `null` if no body.
     *
     * @property body
     * @type body
     * @default null
     */

    /**
     * The `Constraint` object that is used to move the body during interaction.
     *
     * @property constraint
     * @type constraint
     */

    /**
     * An `Object` that specifies the collision filter properties.
     * The collision filter allows the user to define which types of body this mouse constraint can interact with.
     * See `body.collisionFilter` for more information.
     *
     * @property collisionFilter
     * @type object
     */

})();
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { connect } from 'react-redux'

import { incrementCounter, decrementCounter, incrementCounterAsync } from '../../actions/counter'

import {} from './counter.scss'

class Counter {
  render() {
    return (

{this.props.counter}

        <button onClick={this.props.onIncrementCounter}
          className="counter__button">
          +
        </button>

        <button onClick={this.props.onDecrementCounter}
          className="counter__button">
          -
        </button>

        <button onClick={this.props.onIncrementCounterAsync}
          className="counter__button counter__button--async">
          async
        </button>

    )
  }
}

Counter.propTypes = {
  counter: PropTypes.number.isRequired,
  onIncrementCounter: PropTypes.func.isRequired,
  onDecrementCounter: PropTypes.func.isRequired,
  onIncrementCounterAsync: PropTypes.func.isRequired
}

const mapStateToProps = (state) => {
  return {
    counter: state.counter
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onIncrementCounter () {
      dispatch(incrementCounter())
    },
    onDecrementCounter () {
      dispatch(decrementCounter())
    },
    onIncrementCounterAsync () {
      dispatch(incrementCounterAsync())
    }
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Counter)
<commit_msg>Extends from React.Component<commit_after>import React, { PropTypes, Component } from 'react'
import { connect } from 'react-redux'

import { incrementCounter, decrementCounter, incrementCounterAsync } from '../../actions/counter'

import {} from './counter.scss'

class Counter extends Component {
  render () {
    return (

{this.props.counter}

        <button onClick={this.props.onIncrementCounter}
          className="counter__button">
          +
        </button>

        <button onClick={this.props.onDecrementCounter}
          className="counter__button">
          -
        </button>

        <button onClick={this.props.onIncrementCounterAsync}
          className="counter__button counter__button--async">
          async
        </button>

    )
  }
}

Counter.propTypes = {
  counter: PropTypes.number.isRequired,
  onIncrementCounter: PropTypes.func.isRequired,
  onDecrementCounter: PropTypes.func.isRequired,
  onIncrementCounterAsync: PropTypes.func.isRequired
}

const mapStateToProps = (state) => {
  return {
    counter: state.counter
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onIncrementCounter () {
      dispatch(incrementCounter())
    },
    onDecrementCounter () {
      dispatch(decrementCounter())
    },
    onIncrementCounterAsync () {
      dispatch(incrementCounterAsync())
    }
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Counter)
<|endoftext|>


<commit_before>Checklist.AppendixFormView = Ember.CollectionView.extend({
  tagName: 'ul',
  content: [],
  itemViewClass: Ember.View.extend({
    contextBinding: 'content',
    templateName: 'appendix_form',

    classNameBindings: ['classes'],
    classes: function() {
      var filtersController = Checklist.get('router').get('filtersController');
      var abbreviation      = this.get('context').get('abbreviation');

      var classes = [];

      switch(abbreviation) {
        case "I":
          classes.push("blue");
          break;
        case "II":
          classes.push("green");
          break;
        case "III":
          classes.push("orange");
          break;
      }

      if ($.inArray(abbreviation, filtersController.get('appendices').mapProperty('abbreviation')) < 0) {
        classes.push("inactive");
      }

      return classes.join(" ");
    }.property().volatile(),

    click: function(event) {
      var filtersController = Checklist.get('router').get('filtersController');

      // Add the selected appendice to the appendice filter array
      // Equivalent to a selectionBinding in a dropdown list
      appendices = filtersController.get('appendices');
      if (!appendices.contains(this.get('context'))) {
        appendices.push(this.get('context'))
      }

      $(event.target).parent().toggleClass('inactive');
    }
  }),
});
<commit_msg>Fixed click binding bug and the fact that it was not actually storing the appendices back in the filters controller<commit_after>Checklist.AppendixFormView = Ember.CollectionView.extend({
  tagName: 'ul',
  content: [],
  itemViewClass: Ember.View.extend({
    contextBinding: 'content',
    templateName: 'appendix_form',

    classNameBindings: ['classes'],
    classes: function() {
      var filtersController = Checklist.get('router').get('filtersController');
      var abbreviation      = this.get('context').get('abbreviation');

      var classes = [];

      switch(abbreviation) {
        case "I":
          classes.push("blue");
          break;
        case "II":
          classes.push("green");
          break;
        case "III":
          classes.push("orange");
          break;
      }

      if ($.inArray(abbreviation, filtersController.get('appendices').mapProperty('abbreviation')) < 0) {
        classes.push("inactive");
      }

      return classes.join(" ");
    }.property().volatile(),

    click: function(event) {
      // The click event fires for list items as well as circles,
      // this is a bit of a hacky method of ignoring list item clicks
      if ($(event.target).not('div').length > 0) return;

      var filtersController = Checklist.get('router').get('filtersController');

      // Add the selected appendice to the appendice filter array
      // Equivalent to a selectionBinding in a dropdown list
      appendices = filtersController.get('appendices');
      if (appendices.contains(this.get('context'))) {
        appendices.splice(appendices.indexOf(this.get('context')), 1);
      } else {
        appendices.push(this.get('context'))
      }

      filtersController.set('appendices', appendices);

      $(event.target).parent().toggleClass('inactive');
    }
  }),
});
<|endoftext|>


<commit_before>import React from "react";
import "./Contact.css";
import "../../components/githubProfileCard/GithubProfileCard.css";
import "../../containers/blogs/Blog.css";
import "../../index.css";
import SocialMedia from "../../components/socialMedia/SocialMedia";
import {contactInfo} from "../../portfolio";
import { Fade } from "react-reveal";

export default function Contact() {
    return (
        <Fade bottom duration={1000} distance="20px">

Reach Out to me!

Discuss a project or just want to say hi? My Inbox is open for all.

"x Microsoft Azure" | x Alibaba Cloud

                                <svg viewBox="0 0 12 16" version="1.1" width="20" height="18" aria-hidden="true">
                                    <path fill-rule="evenodd" d="M6 0C2.69 0 0 2.5 0 5.5 0 10.02 6 16 6 16s6-5.98 6-10.5C12 2.5 9.31 0 6 0zm0 14.55C4.14 12.52 1 8.44 1 5.5 1 3.02 3.25 1 6 1c1.34 0 2.61.48 3.56 1.36.92.86 1.44 1.97 1.44 3.14 0 2.94-3.14 7.02-5 9.05zM8 5.5c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"></path>
                                </svg>
                                Pune , India

Open for opportunities: Yes

                            {contactInfo.number}

                            {contactInfo.email_address}

                            <SocialMedia/>

        </Fade>
    );
}
<commit_msg>Code changes<commit_after>import React from "react";
import "./Contact.css";
import SocialMedia from "../../components/socialMedia/SocialMedia";
import {contactInfo} from "../../portfolio";
import { Fade } from "react-reveal";

export default function Contact() {
    return (
        <Fade bottom duration={1000} distance="20px">

{contactInfo.title}

{contactInfo.subtitle}

                        {contactInfo.number}

                        {contactInfo.email_address}

                        <SocialMedia/>

        </Fade>
    );
}<|endoftext|>


<commit_before>var GridLayout = require("ui/layouts/grid-layout").GridLayout;
module.exports = {

	process : function(c) {
		c.comp = new GridLayout();
	}
}<commit_msg>gridLayout process columns row<commit_after>var GridLayout = require("ui/layouts/grid-layout").GridLayout;
module.exports = {

	process : function(c) {
		c.comp = new GridLayout();
		if(c.columns) {
			var arr = c.columns.split(',');
			for(var i in arr) {
				var k = arr[i].trim();
				if(k == '*') {
					gridLayout.addColumn(new ItemSpec(1, 'star'));
				}
				else if(k == 'auto') {
					gridLayout.addColumn(new ItemSpec(1, 'auto'));
				}
				else {
					gridLayout.addColumn(new ItemSpec(parseInt(k), 'pixel'));
				}
			}
		}
		if(c.rows) {
			var arr = c.rows.split(',');
			for(var i in arr) {
				var k = arr[i].trim();
				if(k == '*') {
					gridLayout.addRow(new ItemSpec(1, 'star'));
				}
				else if(k == 'auto') {
					gridLayout.addRow(new ItemSpec(1, 'auto'));
				}
				else {
					gridLayout.addRow(new ItemSpec(parseInt(k), 'pixel'));
				}
			}
		}
	}
}<|endoftext|>


<commit_before>var gridLayoutModule = require("ui/layouts/grid-layout");
module.exports = {

	process : function(c) {
		c.comp = new gridLayoutModule.GridLayout();
		var ItemSpec = gridLayoutModule.ItemSpec;
		var gridLayout = c.comp;
		c._innerItems = [];
		if(c.columns) {
			var arr = c.columns.split(',');
			for(var i in arr) {
				var k = arr[i].trim();
				if(k == '*') {
					var item = new ItemSpec(1, 'star');
					gridLayout.addColumn(item);
					c._innerItems.push(['column',item]);
				}
				else if(k == 'auto') {
					var item = new ItemSpec(1, 'auto');
					gridLayout.addColumn(item);
					c._innerItems.push(['column',item]);
				}
				else {
					var item = new ItemSpec(parseInt(k), 'pixel');
					gridLayout.addColumn(item);
					c._innerItems.push(['column',item]);
				}
			}
		}
		if(c.rows) {
			var arr = c.rows.split(',');
			for(var i in arr) {
				var k = arr[i].trim();
				if(k == '*') {
					var item = new ItemSpec(1, 'star');
					gridLayout.addRow(item);
					c._innerItems.push(['row',item]);
				}
				else if(k == 'auto') {
					var item = new ItemSpec(1, 'auto');
					gridLayout.addRow(item);
					c._innerItems.push(['row',item]);
				}
				else {
					var item = new ItemSpec(parseInt(k), 'pixel');
					gridLayout.addRow(item);
					c._innerItems.push(['row',item]);
				}
			}
		}
	}
	,
	postComponentProcess : function(c) {
		var gridLayout = c.comp;
		for(var i in c._innerItems) {
			var arr = c._innerItems[i];
			var type = arr[0];
			var item = arr[1];

		}
	}
}<commit_msg>gridLayout postComponentProcess to process childs row col<commit_after>var gridLayoutModule = require("ui/layouts/grid-layout");
module.exports = {

	process : function(c) {
		c.comp = new gridLayoutModule.GridLayout();
		var ItemSpec = gridLayoutModule.ItemSpec;
		var gridLayout = c.comp;
		c._innerItems = [];
		if(c.columns) {
			var arr = c.columns.split(',');
			for(var i in arr) {
				var k = arr[i].trim();
				if(k == '*') {
					var item = new ItemSpec(1, 'star');
					gridLayout.addColumn(item);
					c._innerItems.push(['column',item]);
				}
				else if(k == 'auto') {
					var item = new ItemSpec(1, 'auto');
					gridLayout.addColumn(item);
					c._innerItems.push(['column',item]);
				}
				else {
					var item = new ItemSpec(parseInt(k), 'pixel');
					gridLayout.addColumn(item);
					c._innerItems.push(['column',item]);
				}
			}
		}
		if(c.rows) {
			var arr = c.rows.split(',');
			for(var i in arr) {
				var k = arr[i].trim();
				if(k == '*') {
					var item = new ItemSpec(1, 'star');
					gridLayout.addRow(item);
					c._innerItems.push(['row',item]);
				}
				else if(k == 'auto') {
					var item = new ItemSpec(1, 'auto');
					gridLayout.addRow(item);
					c._innerItems.push(['row',item]);
				}
				else {
					var item = new ItemSpec(parseInt(k), 'pixel');
					gridLayout.addRow(item);
					c._innerItems.push(['row',item]);
				}
			}
		}
	}
	,
	postComponentProcess : function(c) {
		var gridLayout = c.comp;
		if(c.childs && c.childs.length) {
			c.childs.forEach(function(child) {
				var row = child.row;
				var col = child.col;
				if(typeof row != 'undefined') {
					gridLayoutModule.GridLayout.setRow(child.comp, row);
				}
				if(typeof col != 'undefined') {
					gridLayoutModule.GridLayout.setColumn(child.comp, col);
				}
			});
		}
	}
}<|endoftext|>


<commit_before>/* @flow */

import { callHook } from 'core/instance/lifecycle'
import { getFirstComponentChild } from 'core/vdom/helpers/index'

const patternTypes = [String, RegExp]

function matches (pattern: string | RegExp, name: string): boolean {
  if (typeof pattern === 'string') {
    return pattern.split(',').indexOf(name) > -1
  } else {
    return pattern.test(name)
  }
}

export default {
  name: 'keep-alive',
  abstract: true,
  props: {
    include: patternTypes,
    exclude: patternTypes
  },
  created () {
    this.cache = Object.create(null)
  },
  render () {
    const vnode: VNode = getFirstComponentChild(this.$slots.default)
    if (vnode && vnode.componentOptions) {
      const opts: VNodeComponentOptions = vnode.componentOptions
      // check pattern
      const name = opts.tag || opts.Ctor.options.name
      if (name && (
        (this.include && !matches(this.include, name)) ||
        (this.exclude && matches(this.exclude, name))
      )) {
        return vnode
      }
      const key = vnode.key == null
        // same constructor may get registered as different local components
        // so cid alone is not enough (#3269)
        ? opts.Ctor.cid + (opts.tag ? `::${opts.tag}` : '')
        : vnode.key
      if (this.cache[key]) {
        vnode.child = this.cache[key].child
      } else {
        this.cache[key] = vnode
      }
      vnode.data.keepAlive = true
    }
    return vnode
  },
  destroyed () {
    for (const key in this.cache) {
      const vnode = this.cache[key]
      callHook(vnode.child, 'deactivated')
      vnode.child.$destroy()
    }
  }
}
<commit_msg>adjust keep-alive name matching priority<commit_after>/* @flow */

import { callHook } from 'core/instance/lifecycle'
import { getFirstComponentChild } from 'core/vdom/helpers/index'

const patternTypes = [String, RegExp]

function matches (pattern: string | RegExp, name: string): boolean {
  if (typeof pattern === 'string') {
    return pattern.split(',').indexOf(name) > -1
  } else {
    return pattern.test(name)
  }
}

export default {
  name: 'keep-alive',
  abstract: true,
  props: {
    include: patternTypes,
    exclude: patternTypes
  },
  created () {
    this.cache = Object.create(null)
  },
  render () {
    const vnode: VNode = getFirstComponentChild(this.$slots.default)
    if (vnode && vnode.componentOptions) {
      const opts: VNodeComponentOptions = vnode.componentOptions
      // check pattern
      const name = opts.Ctor.options.name || opts.tag
      if (name && (
        (this.include && !matches(this.include, name)) ||
        (this.exclude && matches(this.exclude, name))
      )) {
        return vnode
      }
      const key = vnode.key == null
        // same constructor may get registered as different local components
        // so cid alone is not enough (#3269)
        ? opts.Ctor.cid + (opts.tag ? `::${opts.tag}` : '')
        : vnode.key
      if (this.cache[key]) {
        vnode.child = this.cache[key].child
      } else {
        this.cache[key] = vnode
      }
      vnode.data.keepAlive = true
    }
    return vnode
  },
  destroyed () {
    for (const key in this.cache) {
      const vnode = this.cache[key]
      callHook(vnode.child, 'deactivated')
      vnode.child.$destroy()
    }
  }
}
<|endoftext|>