<commit_before>/**
 * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You
 * may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

var AWS = require('./core');
var inherit = AWS.util.inherit;

/**
 * @api private
 */
AWS.ResourceWaiter = inherit({
  /**
   * Waits for a given state on a service object
   * @param service [Service] the service object to wait on
   * @param state [String] the state (defined in waiter configuration) to wait
   *   for.
   * @example Create a waiter for running EC2 instances
   *   var ec2 = new AWS.EC2;
   *   var waiter = new AWS.ResourceWaiter(ec2, 'instanceRunning');
   */
  constructor: function constructor(service, state) {
    this.service = service;
    this.state = state;
    this.config = {};

    if (typeof this.state === 'object') {
      AWS.util.each.call(this, this.state, function (key, value) {
        this.state = key;
        this.expectedValue = value;
      });
    }

    this.loadWaiterConfig(this.state);
    if (!this.expectedValue) {
      this.expectedValue = this.config.successValue;
    }
  },

  service: null,

  state: null,

  expectedValue: null,

  config: null,

  /**
   * @return [AWS.Request]
   */
  wait: function wait(params, callback) {
    if (typeof params === 'function') {
      callback = params; params = undefined;
    }

    var request = this.service.makeRequest(this.config.operation, params);
    this.setupRequest(request);

    if (callback) request.send(callback);
    return request;
  },

  setupRequest: function setupRequest(request) {
    var waiter = this;

    var retryDelay = request.retryDelay;
    request.retryDelay = function(resp) {
      if (resp.error.code === 'ResourceNotReady') {
        return waiter.config.interval * 1000;
      } else {
        return retryDelay.call(request, resp);
      }
    };

    request.removeListener('extractError', AWS.EventListeners.Core.SETUP_ERROR);
    if (waiter.config.successType === 'error') {
      request.on('extractError', function (resp) {
        var success = waiter.checkError(resp);
        if (!success) {
          resp.data = null;
          resp.error = AWS.util.error(new Error(), {
            code: 'ResourceNotReady',
            message: 'Resource is not in the state ' + waiter.state,
            originalError: resp.error,
            retryable: success === null ? false : true
          });
        } else {
          resp.error = null;
        }
      });
    } else {
      request.removeAllListeners('extractError');
      request.on('extractData', function (resp) {
        var success = waiter.checkSuccess(resp);
        if (!success) {
          resp.data = null;
          resp.error = AWS.util.error(new Error(), {
            code: 'ResourceNotReady',
            message: 'Resource is not in the state ' + waiter.state,
            originalError: resp.error,
            retryable: success === null ? false : true
          });
        }
      });
    }

    var retryCheck = AWS.EventListeners.Core.RETRY_CHECK;
    var index = request._events['retry'].indexOf(retryCheck);
    request._events['retry'][index] = function newRetryCheck(resp) {
      var e = resp.error;
      resp.waiterRetryCount = resp.waiterRetryCount || 0;
      if (e && e.retryable && e.code === 'ResourceNotReady') {
        if (resp.waiterRetryCount < waiter.config.maxAttempts) {
          resp.waiterRetryCount++;
        } else {
          throw e;
        }
      } else {
        retryCheck.call(resp.request, resp);
      }
    };
  },

  /**
   * Checks if the terminal expected success state has been met
   * @return [Boolean]
   */
  checkSuccess: function checkSuccess(resp) {
    if (!this.config.successPath) {
      return resp.httpResponse.statusCode < 300;
    }

    var r = AWS.util.jamespath.find(this.config.successPath, resp.data);

    if (this.config.failureValue &&
        this.config.failureValue.indexOf(r) >= 0) {
      return null; // fast fail
    }

    if (this.expectedValue) {
      return r === this.expectedValue;
    } else {
      return r ? true : false;
    }
  },

  /**
   * Checks if the terminal expected error state has been met
   * @return [Boolean]
   */
  checkError: function checkError(resp) {
    return resp.httpResponse.statusCode === this.config.successValue;
  },

  /**
   * Loads waiter configuration from API configuration and deals with inherited
   * properties.
   *
   * @api private
   */
  loadWaiterConfig: function loadWaiterConfig(state, noException) {
    if (!this.service.api.waiters[state]) {
      if (noException) return;
      throw new AWS.util.error(new Error(), {
        code: 'StateNotFoundError',
        message: 'State ' + state + ' not found.'
      });
    }

    if (state !== '__default__') {
      var superState = this.service.api.waiters[state]['extends'];
      superState = superState || '__default__';
      this.loadWaiterConfig(superState, true);
    }

    var config = this.config;
    AWS.util.update(config, this.service.api.waiters[state]);

    // inherit acceptor data
    (function () { // anonymous function to avoid max complexity count
      config.successType = config.successType || config.acceptorType;
      config.successPath = config.successPath || config.acceptorPath;
      config.successValue = config.successValue || config.acceptorValue;
      config.failureType = config.failureType || config.acceptorType;
      config.failurePath = config.failurePath || config.acceptorPath;
      config.failureValue = config.failureValue || config.acceptorValue;
    })();
  }
});
<commit_msg>Make retry event replacement code more robust when retry is removed<commit_after>/**
 * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You
 * may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

var AWS = require('./core');
var inherit = AWS.util.inherit;

/**
 * @api private
 */
AWS.ResourceWaiter = inherit({
  /**
   * Waits for a given state on a service object
   * @param service [Service] the service object to wait on
   * @param state [String] the state (defined in waiter configuration) to wait
   *   for.
   * @example Create a waiter for running EC2 instances
   *   var ec2 = new AWS.EC2;
   *   var waiter = new AWS.ResourceWaiter(ec2, 'instanceRunning');
   */
  constructor: function constructor(service, state) {
    this.service = service;
    this.state = state;
    this.config = {};

    if (typeof this.state === 'object') {
      AWS.util.each.call(this, this.state, function (key, value) {
        this.state = key;
        this.expectedValue = value;
      });
    }

    this.loadWaiterConfig(this.state);
    if (!this.expectedValue) {
      this.expectedValue = this.config.successValue;
    }
  },

  service: null,

  state: null,

  expectedValue: null,

  config: null,

  /**
   * @return [AWS.Request]
   */
  wait: function wait(params, callback) {
    if (typeof params === 'function') {
      callback = params; params = undefined;
    }

    var request = this.service.makeRequest(this.config.operation, params);
    this.setupRequest(request);

    if (callback) request.send(callback);
    return request;
  },

  setupRequest: function setupRequest(request) {
    var waiter = this;

    var retryDelay = request.retryDelay;
    request.retryDelay = function(resp) {
      if (resp.error.code === 'ResourceNotReady') {
        return waiter.config.interval * 1000;
      } else {
        return retryDelay.call(request, resp);
      }
    };

    request.removeListener('extractError', AWS.EventListeners.Core.SETUP_ERROR);
    if (waiter.config.successType === 'error') {
      request.on('extractError', function (resp) {
        var success = waiter.checkError(resp);
        if (!success) {
          resp.data = null;
          resp.error = AWS.util.error(new Error(), {
            code: 'ResourceNotReady',
            message: 'Resource is not in the state ' + waiter.state,
            originalError: resp.error,
            retryable: success === null ? false : true
          });
        } else {
          resp.error = null;
        }
      });
    } else {
      request.removeAllListeners('extractError');
      request.on('extractData', function (resp) {
        var success = waiter.checkSuccess(resp);
        if (!success) {
          resp.data = null;
          resp.error = AWS.util.error(new Error(), {
            code: 'ResourceNotReady',
            message: 'Resource is not in the state ' + waiter.state,
            originalError: resp.error,
            retryable: success === null ? false : true
          });
        }
      });
    }

    var retryCheck = AWS.EventListeners.Core.RETRY_CHECK;
    function newRetryCheck(resp) {
      var e = resp.error;
      resp.waiterRetryCount = resp.waiterRetryCount || 0;
      if (e && e.retryable && e.code === 'ResourceNotReady') {
        if (resp.waiterRetryCount < waiter.config.maxAttempts) {
          resp.waiterRetryCount++;
        } else {
          throw e;
        }
      } else if (retryCheck) {
        retryCheck.call(resp.request, resp);
      }
    }

    request._events['retry'] = request._events['retry'] || [];
    var index = request._events['retry'].indexOf(retryCheck);
    if (index < 0) {
      retryCheck = null;
      request.on('retry', newRetryCheck);
    } else {
      request._events['retry'][index] = newRetryCheck;
    }
  },

  /**
   * Checks if the terminal expected success state has been met
   * @return [Boolean]
   */
  checkSuccess: function checkSuccess(resp) {
    if (!this.config.successPath) {
      return resp.httpResponse.statusCode < 300;
    }

    var r = AWS.util.jamespath.find(this.config.successPath, resp.data);

    if (this.config.failureValue &&
        this.config.failureValue.indexOf(r) >= 0) {
      return null; // fast fail
    }

    if (this.expectedValue) {
      return r === this.expectedValue;
    } else {
      return r ? true : false;
    }
  },

  /**
   * Checks if the terminal expected error state has been met
   * @return [Boolean]
   */
  checkError: function checkError(resp) {
    return resp.httpResponse.statusCode === this.config.successValue;
  },

  /**
   * Loads waiter configuration from API configuration and deals with inherited
   * properties.
   *
   * @api private
   */
  loadWaiterConfig: function loadWaiterConfig(state, noException) {
    if (!this.service.api.waiters[state]) {
      if (noException) return;
      throw new AWS.util.error(new Error(), {
        code: 'StateNotFoundError',
        message: 'State ' + state + ' not found.'
      });
    }

    if (state !== '__default__') {
      var superState = this.service.api.waiters[state]['extends'];
      superState = superState || '__default__';
      this.loadWaiterConfig(superState, true);
    }

    var config = this.config;
    AWS.util.update(config, this.service.api.waiters[state]);

    // inherit acceptor data
    (function () { // anonymous function to avoid max complexity count
      config.successType = config.successType || config.acceptorType;
      config.successPath = config.successPath || config.acceptorPath;
      config.successValue = config.successValue || config.acceptorValue;
      config.failureType = config.failureType || config.acceptorType;
      config.failurePath = config.failurePath || config.acceptorPath;
      config.failureValue = config.failureValue || config.acceptorValue;
    })();
  }
});
<|endoftext|>


<commit_before>import Actions from '../actions/actions';
import mapStore from '../stores/mapStore';
import { ModeConstants } from '../constants/constants';

export default class Marker {
  constructor(latLng, icon) {
    this.icon = icon;
    let options = {
      icon,
      draggable: true
    }
    let marker = new L.Marker(latLng, options);
    return this.withHooks(marker);
  }

  withHooks(marker) {
    let iconMargin = 0;
    let icon = this.icon;

    marker.on('click', (e) => {
      e.target.getPopup()._isOpen = false;
      $(e.target.getPopup()._container).css('display', 'block');
    })

    marker.on('add', () => {
      $('.leaflet-popup').css('display', 'none')
    });

    marker.on('dragstart', (e) => {
      let icon = e.target._icon;

      if (!iconMargin) {
        iconMargin = parseInt(L.DomUtil.getStyle(icon, 'marginTop'));
      }

      icon.style.marginTop = (iconMargin - 15)  + 'px';
    });

    marker.on('dragend', (e) => {
      e.target._icon.style.marginTop = iconMargin + 'px';
    });

    return marker;
  }
}
<commit_msg>Fix dragging on icon bounding box.<commit_after>import L from 'leaflet';
import Actions from '../actions/actions';
import mapStore from '../stores/mapStore';
import { ModeConstants } from '../constants/constants';

export default class Marker {
  constructor(latLng, icon) {
    this.icon = icon;
    let options = {
      icon,
      draggable: true
    }
    let marker = new L.Marker(latLng, options);
    return this.withHooks(marker);
  }

  withHooks(marker) {
    let iconMargin = 0;
    let icon = this.icon;
    let mode = null;
    let map = mapStore.getState().map;

    marker.on('click', (e) => {
      e.target.getPopup()._isOpen = false;
      $(e.target.getPopup()._container).css('display', 'block');
    })

    marker.on('add', () => {
      $('.leaflet-popup').css('display', 'none')
    });

    marker.on('dragstart', (e) => {
      let icon = e.target._icon;

      mode = mapStore.getState().mode;
      Actions.changeMode(ModeConstants);

      if (!iconMargin) {
        iconMargin = parseInt(L.DomUtil.getStyle(icon, 'marginTop'));
      }

      icon.style.marginTop = `${iconMargin - 15}px`;
    });

    marker.on('dragend', (e) => {
      let map = mapStore.getState().map;
      e.target._icon.style.marginTop = `${iconMargin}px`;

      map.once('click', () => {
        Actions.changeMode(mode);
      })
    });

    return marker;
  }
}
<|endoftext|>


<commit_before>/*global ares, enyo */

enyo.kind({
	name: "Harmonia",
	kind:"FittableColumns",
	events: {
		onRegisterMe: "",
		onMovePanel: ""
	},
	components: [
		{kind:"FittableRows", classes:"enyo-fit", components:[
			{kind: "onyx.Toolbar", classes: "ares-top-toolbar", components: [
				{kind: "onyx.Grabber", classes: "ares-grabber" , name: "filePanelGrabber", showing: false, ontap: "activePanel", components: [
					{kind: "aresGrabber", name: "aresGrabberDirection"}
				]},
				{classes:"ares-logo-container", name:"logoContainer", components:[
					{name:"logo", kind:"Ares.Logo"}
				]}
			]},
			{kind: "HermesFileTree", dragAllowed: true, menuAllowed: true}
		]},
		{classes:"hangar"}
	],
	debug: false,
	published: {
		// harcoded until ENYO-2755 is fixed
		panelIndex: 1
	},
	create: function() {
		ares.setupTraceLogger(this);	// Setup this.trace() function according to this.debug value
		this.inherited(arguments);
		this.doRegisterMe({name:"harmonia", reference:this});
	},
	handleSelectProvider: function(inSender, inEvent) {
		this.trace("sender:", inSender, ", event:", inEvent);
		if (inEvent.service) {
			this.$.hermesFileTree.connectService(inEvent.service);
		}
		this.$.hermesFileTree.hideFileOpButtons();
		return true; //Stop event propagation
	},
	setProject: function(project, next) {
		this.trace("project:", project);
		if (project !== null) {
			this.$.hermesFileTree.connectProject(project, next).showFileOpButtons();
		} else {
			this.$.hermesFileTree.hideFileOpButtons().clear();
			if (next) { next(); }
		}
	},
	showGrabber:function(){
		this.$.filePanelGrabber.show();
	},
	hideGrabber:function(){
		this.$.filePanelGrabber.hide();
	},
	switchGrabberDirection: function(active){
		this.$.aresGrabberDirection.switchGrabberDirection(active);
	},
	/**
	 * Refresh the {HermesFileTree}
	 * @param {Object} changedFile
	 * @param {Function} callback
	 */
	refreshFileTree: function(toSelectId,next) {
		// the inversion of parameter is not an error.
		this.$.hermesFileTree.refreshFileTree(next, toSelectId);
	},
	activePanel : function(){
		this.doMovePanel({panelIndex:this.panelIndex});
	},
	showLogo:function(){
		this.$.logoContainer.show();
	},
	hideLogo:function(){
		this.$.logoContainer.hide();
	},
});
<commit_msg>ENYO-3082: documented optional callback of harmonia.refreshFileTree<commit_after>/*global ares, enyo */

enyo.kind({
	name: "Harmonia",
	kind:"FittableColumns",
	events: {
		onRegisterMe: "",
		onMovePanel: ""
	},
	components: [
		{kind:"FittableRows", classes:"enyo-fit", components:[
			{kind: "onyx.Toolbar", classes: "ares-top-toolbar", components: [
				{kind: "onyx.Grabber", classes: "ares-grabber" , name: "filePanelGrabber", showing: false, ontap: "activePanel", components: [
					{kind: "aresGrabber", name: "aresGrabberDirection"}
				]},
				{classes:"ares-logo-container", name:"logoContainer", components:[
					{name:"logo", kind:"Ares.Logo"}
				]}
			]},
			{kind: "HermesFileTree", dragAllowed: true, menuAllowed: true}
		]},
		{classes:"hangar"}
	],
	debug: false,
	published: {
		// harcoded until ENYO-2755 is fixed
		panelIndex: 1
	},
	create: function() {
		ares.setupTraceLogger(this);	// Setup this.trace() function according to this.debug value
		this.inherited(arguments);
		this.doRegisterMe({name:"harmonia", reference:this});
	},
	handleSelectProvider: function(inSender, inEvent) {
		this.trace("sender:", inSender, ", event:", inEvent);
		if (inEvent.service) {
			this.$.hermesFileTree.connectService(inEvent.service);
		}
		this.$.hermesFileTree.hideFileOpButtons();
		return true; //Stop event propagation
	},
	setProject: function(project, next) {
		this.trace("project:", project);
		if (project !== null) {
			this.$.hermesFileTree.connectProject(project, next).showFileOpButtons();
		} else {
			this.$.hermesFileTree.hideFileOpButtons().clear();
			if (next) { next(); }
		}
	},
	showGrabber:function(){
		this.$.filePanelGrabber.show();
	},
	hideGrabber:function(){
		this.$.filePanelGrabber.hide();
	},
	switchGrabberDirection: function(active){
		this.$.aresGrabberDirection.switchGrabberDirection(active);
	},
	/**
	 * Refresh the {HermesFileTree}
	 * @param {Object} toSelectId - changed file id
	 * @param {Function} [callback] - optional callback
	 */
	refreshFileTree: function(toSelectId,next) {
		// the inversion of parameter is not an error.
		// next parameter is optional (can be null or undef)
		this.$.hermesFileTree.refreshFileTree(next, toSelectId);
	},
	activePanel : function(){
		this.doMovePanel({panelIndex:this.panelIndex});
	},
	showLogo:function(){
		this.$.logoContainer.show();
	},
	hideLogo:function(){
		this.$.logoContainer.hide();
	},
});
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var express = require('express');
var http = require('http');
var path = require('path');
var os = require('os');

var racerBrowserChannel = require('racer-browserchannel');
var liveDbMongo = require('livedb-mongo');
var redis = require('redis').createClient();
var racer = require('racer');

var sizeOf = require('image-size');

var wams = require('wams.js-server');

var store = racer.createStore({
   db: liveDbMongo('localhost:27017/wams?auto_reconnect', { safe: true }),
   redis: redis
});

var app = express();

var iface = os.networkInterfaces().wlp3s0;
var IP;
iface && iface.forEach(function(connection) {
   if (connection.family === 'IPv4') {
      IP = connection.address;
   }
});

// all environments
app.set('ip', process.argv[2] || process.env.IP || IP || '127.0.0.1');
app.set('port', process.argv[3] || process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// app.set('env', 'development');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(racerBrowserChannel(store));
app.use(store.modelMiddleware());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' === app.get('env')) {
  app.use(express.errorHandler());
}

store.on('bundle', function(browserify) {
   browserify.require('./public/js/lib/jquery-1.10.2.js', { expose: 'jquery' });
   browserify.require('./public/js/lib/hammer.js', { expose: 'hammerjs' });
   browserify.require('socket.io-client', { expose: 'socket.io-client' });
   browserify.require('./public/js/lib/wams.js', { expose: 'wams' });
});

var model = store.createModel();
var roomPath = 'sharedWorkspace';

var resetUsers = true;
var resetBalls = true;
var showElementsOnMinimap = true;
var gapBetweenClients = true;

model.subscribe(roomPath, function(err) {
   if (err) { throw err; }

   if (resetUsers) {
      model.set(roomPath + '.users', {});
      model.set(roomPath + '.screens', {});
      model.set(roomPath + '.workspace', {});
   }

   model.set(roomPath + '.settings.minimap.showElements', showElementsOnMinimap);
   model.set(roomPath + '.settings.minimap.gapBetweenClients', gapBetweenClients);

   if (resetBalls || model.get(roomPath + ".elements") === undefined) {
      var elements = [];
      for (var i = 1; i <= 4; i++) {
         var element = {
            tag: 'div',
            attributes: {
               id: 'ball' + i,
               class: 'ball',
               'data-lock': ''
            },
            type: 'ball',
            x: (i - 1 - 2 * Math.floor((i - 1) / 2)) * 125 + 100,
            y: Math.floor((i - 1) / 2) * 125 + 300,
            w: 100,
            h: 100,
            s: 100
         };
         elements.push(element);
      }
      var imageSize = sizeOf('public/img/img0.jpg');
      elements.push({
         tag: 'img',
         attributes: {
            src: '/img/img0.jpg',
            id: 'img0',
            class: 'drag_img no_body_rescale',
            'data-lock': ''
         },
         type: 'image',
         x: 500,
         y: 500,
         w: imageSize.width,
         h: imageSize.height,
         s: 100
      });
      model.set(roomPath + '.elements', elements);
   }

   model.fn('workspaceBorder', function(screens) {
      if (isEmpty(screens)) { return { x: 0, y: 0, w: 0, h: 0 }; }

      var id, screen, screen_x2, screen_y2, w, h,
         x = Infinity, y = Infinity, x2 = -Infinity, y2 = -Infinity;

      for (id in screens) {
         if (screens.hasOwnProperty(id)) {
            screen = screens[id];
            screen_x2 = screen.x + screen.w * screen.s / 100;
            screen_y2 = screen.y + screen.h * screen.s / 100;

            if (screen.x < x) {
               x = screen.x;
            }
            if (screen.y < y) {
               y = screen.y;
            }
            if (screen_x2 > x2) {
               x2 = screen_x2;
            }
            if (screen_y2 > y2) {
               y2 = screen_y2;
            }
         }
      }

      w = x2 - x;
      h = y2 - y;

      return {x: x, y: y, w: w, h: h};
   });
   model.on('change', roomPath + '.screens**', function() {
      var workspace = model.evaluate('workspaceBorder', roomPath + '.screens');
      model.set(roomPath + '.workspace', workspace);
   });
});

function createBundle(req, res, next) {
   store.bundle(__dirname + '/public/js/sharedWorkspaceWithRacer.js',
      function(err, js) {
         if (err) { return next(err); }
         res.type('js');
         res.send(js);
      }
   );
}

function isEmpty(map) {
   for(var key in map) {
      if (map.hasOwnProperty(key)) {
         return false;
      }
   }
   return true;
}

function renderRacer(req, res, next) {
   model.bundle(function(err, bundle) {
      if (err) { return next(err); }

      var settings = {
         title: 'Shared space between clients with racer',
         bundle: JSON.stringify(bundle)
      };
      console.log(settings.bundle);
      res.render('sharedWorkspaceWithRacer', settings);
   });
}

app.get('/js/sharedWorkspaceWithRacer.js', createBundle);
app.get('/', renderRacer);

var server = http.createServer(app);
server.listen(app.get('port'), function(){
  console.log('Express server listening on ' + app.get('ip') + ':' + app.get('port'));
});

wams.listen(server);
<commit_msg>feat(circles): provide the way to turn off balls on the page<commit_after>
/**
 * Module dependencies.
 */

var express = require('express');
var http = require('http');
var path = require('path');
var os = require('os');

var racerBrowserChannel = require('racer-browserchannel');
var liveDbMongo = require('livedb-mongo');
var redis = require('redis').createClient();
var racer = require('racer');

var sizeOf = require('image-size');

var wams = require('wams.js-server');

var store = racer.createStore({
   db: liveDbMongo('localhost:27017/wams?auto_reconnect', { safe: true }),
   redis: redis
});

var app = express();

var iface = os.networkInterfaces().wlp3s0;
var IP;
iface && iface.forEach(function(connection) {
   if (connection.family === 'IPv4') {
      IP = connection.address;
   }
});

// all environments
app.set('ip', process.argv[2] || process.env.IP || IP || '127.0.0.1');
app.set('port', process.argv[3] || process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// app.set('env', 'development');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(racerBrowserChannel(store));
app.use(store.modelMiddleware());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' === app.get('env')) {
  app.use(express.errorHandler());
}

store.on('bundle', function(browserify) {
   browserify.require('./public/js/lib/jquery-1.10.2.js', { expose: 'jquery' });
   browserify.require('./public/js/lib/hammer.js', { expose: 'hammerjs' });
   browserify.require('socket.io-client', { expose: 'socket.io-client' });
   browserify.require('./public/js/lib/wams.js', { expose: 'wams' });
});

var model = store.createModel();
var roomPath = 'sharedWorkspace';

var resetUsers = true;
var resetBalls = true;
var showElementsOnMinimap = true;
var gapBetweenClients = true;
var enableBalls = false;

model.subscribe(roomPath, function(err) {
   if (err) { throw err; }

   if (resetUsers) {
      model.set(roomPath + '.users', {});
      model.set(roomPath + '.screens', {});
      model.set(roomPath + '.workspace', {});
   }

   model.set(roomPath + '.settings.minimap.showElements', showElementsOnMinimap);
   model.set(roomPath + '.settings.minimap.gapBetweenClients', gapBetweenClients);

   if (resetBalls || model.get(roomPath + ".elements") === undefined) {
      var elements = [];
      if (enableBalls) {
         for (var i = 1; i <= 4; i++) {
            var element = {
               tag: 'div',
               attributes: {
                  id: 'ball' + i,
                  class: 'ball',
                  'data-lock': ''
               },
               type: 'ball',
               x: (i - 1 - 2 * Math.floor((i - 1) / 2)) * 125 + 100,
               y: Math.floor((i - 1) / 2) * 125 + 300,
               w: 100,
               h: 100,
               s: 100
            };
            elements.push(element);
         }
      }
      var imageSize = sizeOf('public/img/img0.jpg');
      elements.push({
         tag: 'img',
         attributes: {
            src: '/img/img0.jpg',
            id: 'img0',
            class: 'drag_img no_body_rescale',
            'data-lock': ''
         },
         type: 'image',
         x: 500,
         y: 500,
         w: imageSize.width,
         h: imageSize.height,
         s: 100
      });
      model.set(roomPath + '.elements', elements);
   }

   model.fn('workspaceBorder', function(screens) {
      if (isEmpty(screens)) { return { x: 0, y: 0, w: 0, h: 0 }; }

      var id, screen, screen_x2, screen_y2, w, h,
         x = Infinity, y = Infinity, x2 = -Infinity, y2 = -Infinity;

      for (id in screens) {
         if (screens.hasOwnProperty(id)) {
            screen = screens[id];
            screen_x2 = screen.x + screen.w * screen.s / 100;
            screen_y2 = screen.y + screen.h * screen.s / 100;

            if (screen.x < x) {
               x = screen.x;
            }
            if (screen.y < y) {
               y = screen.y;
            }
            if (screen_x2 > x2) {
               x2 = screen_x2;
            }
            if (screen_y2 > y2) {
               y2 = screen_y2;
            }
         }
      }

      w = x2 - x;
      h = y2 - y;

      return {x: x, y: y, w: w, h: h};
   });
   model.on('change', roomPath + '.screens**', function() {
      var workspace = model.evaluate('workspaceBorder', roomPath + '.screens');
      model.set(roomPath + '.workspace', workspace);
   });
});

function createBundle(req, res, next) {
   store.bundle(__dirname + '/public/js/sharedWorkspaceWithRacer.js',
      function(err, js) {
         if (err) { return next(err); }
         res.type('js');
         res.send(js);
      }
   );
}

function isEmpty(map) {
   for(var key in map) {
      if (map.hasOwnProperty(key)) {
         return false;
      }
   }
   return true;
}

function renderRacer(req, res, next) {
   model.bundle(function(err, bundle) {
      if (err) { return next(err); }

      var settings = {
         title: 'Shared space between clients with racer',
         bundle: JSON.stringify(bundle)
      };
      console.log(settings.bundle);
      res.render('sharedWorkspaceWithRacer', settings);
   });
}

app.get('/js/sharedWorkspaceWithRacer.js', createBundle);
app.get('/', renderRacer);

var server = http.createServer(app);
server.listen(app.get('port'), function(){
  console.log('Express server listening on ' + app.get('ip') + ':' + app.get('port'));
});

wams.listen(server);
<|endoftext|>


<commit_before>import AppNavigator from '../navigators/AppNavigator'

export default function (state, action) {
  let nextState = AppNavigator.router.getStateForAction(action, state)

  return nextState || state
}
<commit_msg>fix: try to solve duplicated navigation issue<commit_after>import AppNavigator from '../navigators/AppNavigator'

export default function (state, action) {
  if (action.type.startsWith('Navigation/')) {
    const {routeName, params} = action
    const {routes, index} = state
    const currentTab = routes[index]
    const lastScreen = currentTab.routes[currentTab.routes.length - 1]
    if (lastScreen.routeName === routeName /* &&
      lastScreen.params === params */) {
      return state
    }
  }
  return AppNavigator.router.getStateForAction(action, state) || state
}
<|endoftext|>


<commit_before>/*jslint nomen: true */
/*globals define: true */

define([
  'jquery',
  'lib/lodash',
  'backbone',
  'settings',
  'api',

  // Templates
  'text!templates/export.html'
],

function($, _, Backbone, settings, api, exportTemplate) {
  'use strict';

  var exportTimeout = 2 * 60 * 1000; // 2 minutes

  var ExportView = Backbone.View.extend({
    el: '#export-view-container',

    template: _.template(exportTemplate),

    events: {
      'click .shapefile': 'getShapefile',
      'click .kml': 'getKML',
      'click .csv': 'getCSV',
      'click .csvLatest': 'getCSVLatest'
    },

    initialize: function(options) {
      _.bindAll(this, 'render', 'pingExport');

      // Show a given survey
      this.survey = options.survey;
      this.survey.on('change', this.render);
    },

    render: function() {
      // Set the context & render the page
      var context = {
        surveyId: this.survey.get('id'),
        baseurl: settings.api.baseurl,
        loading: this.loading
      };

      this.$el.html(this.template(context));
    },

    loading: {},

    // When we're done with the shapefile export process, we should reset our
    // in-progress indication.
    exportDone: function exportDone(error) {
      this.render(false);
      if (error) {
        console.log(error);
        this.$('.error').show();
      }
    },

    // Ping the API to see if an export is ready. When it's ready, download it.
    pingExport: function pingExport(type, url) {
      var expiration = Date.now() + exportTimeout;

      // We may need to pass in some optional parameters
      var options = {};
      if(type === 'csvLatest') {
        options.latest = true;
      }
      if(this.survey.has('timezone')) {
        options.timezone = this.survey.get('timezone');
      }

      // Paramterize the options and add to the URL
      var params = $.param(options);
      if (params) {
        url += '?' + params;
      }

      var self = this;

      this.loading[type] = true;
      this.render();

      var ping;

      function pingRaw() {
        if (Date.now() > expiration) {
          self.loading[type] = false;
          self.exportDone(new Error(type + 'export timed out.'));
          return;
        }

        // See if the ping cycle has been stopped.
        if (!self.loading[type]) {
          return;
        }

        $.ajax({
          url: url,
          cache: false
        }).done(function (data, textStatus, jqXHR) {
          if (jqXHR.status === 202 && self.loading[type]) {
            ping();
            return;
          }
          self.loading[type] = false;
          self.render();
          window.location = data.href;
        }).fail(function () {
          self.exportDone(new Error(type + ' export failed.'));
        });
      }

      ping = _.throttle(pingRaw, 500, { trailing: true });
      ping();
    },

    // Ask the API to generate a CSV export.
    getCSV: function getCSV() {
      var url = settings.api.baseurl + '/surveys/' + this.survey.get('id') + '/responses.csv';
      this.pingExport('csv', url);
    },

    // Ask the API to generate a CSV export.
    getCSVLatest: function getCSVLatest() {
      var url = settings.api.baseurl + '/surveys/' + this.survey.get('id') + '/responses.csv';
      this.pingExport('csvLatest', url);
    },

    // Ask the API to generate a KML export.
    getKML: function getKML() {
      var url = settings.api.baseurl + '/surveys/' + this.survey.get('id') + '/responses.kml';
      this.pingExport('kml', url);
    },

    // Ask the API to generate a shapefile export.
    getShapefile: function getShapefile() {
      var url = settings.api.baseurl + '/surveys/' + this.survey.get('id') + '/responses.zip';
      this.pingExport('shapefile', url);
    }
  });

  return ExportView;

});
<commit_msg>Use $.ajax to construct GET parameters for export options<commit_after>/*jslint nomen: true */
/*globals define: true */

define([
  'jquery',
  'lib/lodash',
  'backbone',
  'settings',
  'api',

  // Templates
  'text!templates/export.html'
],

function($, _, Backbone, settings, api, exportTemplate) {
  'use strict';

  var exportTimeout = 2 * 60 * 1000; // 2 minutes

  var ExportView = Backbone.View.extend({
    el: '#export-view-container',

    template: _.template(exportTemplate),

    events: {
      'click .shapefile': 'getShapefile',
      'click .kml': 'getKML',
      'click .csv': 'getCSV',
      'click .csvLatest': 'getCSVLatest'
    },

    initialize: function(options) {
      _.bindAll(this, 'render', 'pingExport');

      // Show a given survey
      this.survey = options.survey;
      this.survey.on('change', this.render);
    },

    render: function() {
      // Set the context & render the page
      var context = {
        surveyId: this.survey.get('id'),
        baseurl: settings.api.baseurl,
        loading: this.loading
      };

      this.$el.html(this.template(context));
    },

    loading: {},

    // When we're done with the shapefile export process, we should reset our
    // in-progress indication.
    exportDone: function exportDone(error) {
      this.render(false);
      if (error) {
        console.log(error);
        this.$('.error').show();
      }
    },

    // Ping the API to see if an export is ready. When it's ready, download it.
    pingExport: function pingExport(type, url) {
      var expiration = Date.now() + exportTimeout;

      // We may need to pass in some optional parameters
      var options = {};
      if(type === 'csvLatest') {
        options.latest = true;
      }
      if(this.survey.has('timezone')) {
        options.timezone = this.survey.get('timezone');
      }

      var self = this;

      this.loading[type] = true;
      this.render();

      var ping;

      function pingRaw() {
        if (Date.now() > expiration) {
          self.loading[type] = false;
          self.exportDone(new Error(type + 'export timed out.'));
          return;
        }

        // See if the ping cycle has been stopped.
        if (!self.loading[type]) {
          return;
        }

        $.ajax({
          url: url,
          data: options,
          cache: false
        }).done(function (data, textStatus, jqXHR) {
          if (jqXHR.status === 202 && self.loading[type]) {
            ping();
            return;
          }
          self.loading[type] = false;
          self.render();
          window.location = data.href;
        }).fail(function () {
          self.exportDone(new Error(type + ' export failed.'));
        });
      }

      ping = _.throttle(pingRaw, 500, { trailing: true });
      ping();
    },

    // Ask the API to generate a CSV export.
    getCSV: function getCSV() {
      var url = settings.api.baseurl + '/surveys/' + this.survey.get('id') + '/responses.csv';
      this.pingExport('csv', url);
    },

    // Ask the API to generate a CSV export.
    getCSVLatest: function getCSVLatest() {
      var url = settings.api.baseurl + '/surveys/' + this.survey.get('id') + '/responses.csv';
      this.pingExport('csvLatest', url);
    },

    // Ask the API to generate a KML export.
    getKML: function getKML() {
      var url = settings.api.baseurl + '/surveys/' + this.survey.get('id') + '/responses.kml';
      this.pingExport('kml', url);
    },

    // Ask the API to generate a shapefile export.
    getShapefile: function getShapefile() {
      var url = settings.api.baseurl + '/surveys/' + this.survey.get('id') + '/responses.zip';
      this.pingExport('shapefile', url);
    }
  });

  return ExportView;

});
<|endoftext|>


<commit_before>/*#ifndef(UMD)*/
(function () { /* Begin of privacy scope */
    "use strict";
/*#endif*/

    /**
     * Error object, contains error information
     *
     * @class gpf.Error
     */
    gpf.define("gpf.Error", {

        public: {

            /**
             * Error code
             *
             * @type {Number}
             */
            code: 0,

            /**
             * Error name
             *
             * @type {String}
             */
            name: "Error",

            /**
             * Error message
             *
             * @type {String}
             */
            message: ""
        }

    });

    var
        ERRORS = {
            // boot.js
            "NotImplemented":
                "Not implemented",
            "AssertionFailed":
                "Assertion failed: {message}",

            // class.js
            "ClassMemberOverloadWithTypeChange":
                "You can't overload a member to change its type",
            "ClassInvalidVisibility":
                "Invalid visibility keyword",

            // interface.js
            "InterfaceExpected":
                "Expected interface not implemented: {name}",

            // i_enumerable.js
            "EnumerableInvalidMember":
                "$Enumerable can be associated to arrays only",

            // parser.js
            "PatternUnexpected":
                "Invalid syntax (unexpected)",
            "PatternEmpty":
                "Empty pattern",
            "PatternInvalidSyntax":
                "Invalid syntax",
            "PatternEmptyGroup":
                "Syntax error (empty group)",

            // html.js
            "HtmlHandlerMultiplicityError":
                "Too many $HtmlHandler attributes for '{member}'",
            "HtmlHandlerMissing":
                "No $HtmlHandler attributes",
            "HtmlHandlerNoDefault":
                "No default $HtmlHandler attribute",

            // engine.js
            "EngineStackUnderflow":
                "Stack underflow",
            "EngineTypeCheck":
                "Type check",

            // encoding.js
            "EncodingNotSupported":
                "Encoding not supported",

            // xml.js
            "XmlInvalidName":
                "Invalid XML name"
        },

        /**
         * Generates an error function
         *
         * @param {Number} code
         * @param {String} name
         * @return {Function}
         * @closure
         */
        genThrowError = function (code, name) {
            return function (context) {
                var
                    error = new gpf.Error(),
                    replacements,
                    key;
                error.code = code;
                error.name = name;
                if (context) {
                    replacements = {};
                    for (key in context) {
                        if (context.hasOwnProperty(key)) {
                            replacements["{" + key + "}"] =
                                context[key].toString();
                        }
                    }
                    error.message = gpf.replaceEx(ERRORS[name], replacements);
                } else {
                    error.message = ERRORS[name];
                }
                throw error;
            };
        },

        name,
        code = 0;
    for (name in ERRORS) {
        if (ERRORS.hasOwnProperty(name)) {
            ++code;
            gpf.Error["CODE_" + name.toUpperCase()] = code;
            gpf.Error[name] = genThrowError(code, name);
        }
    }

/*#ifndef(UMD)*/
}()); /* End of privacy scope */
/*#endif*/<commit_msg>Added Abstract error<commit_after>/*#ifndef(UMD)*/
(function () { /* Begin of privacy scope */
    "use strict";
/*#endif*/

    /**
     * Error object, contains error information
     *
     * @class gpf.Error
     */
    gpf.define("gpf.Error", {

        public: {

            /**
             * Error code
             *
             * @type {Number}
             */
            code: 0,

            /**
             * Error name
             *
             * @type {String}
             */
            name: "Error",

            /**
             * Error message
             *
             * @type {String}
             */
            message: ""
        }

    });

    var
        ERRORS = {
            // boot.js
            "NotImplemented":
                "Not implemented",
            "Abstract":
                "Abstract",
            "AssertionFailed":
                "Assertion failed: {message}",

            // class.js
            "ClassMemberOverloadWithTypeChange":
                "You can't overload a member to change its type",
            "ClassInvalidVisibility":
                "Invalid visibility keyword",

            // interface.js
            "InterfaceExpected":
                "Expected interface not implemented: {name}",

            // i_enumerable.js
            "EnumerableInvalidMember":
                "$Enumerable can be associated to arrays only",

            // parser.js
            "PatternUnexpected":
                "Invalid syntax (unexpected)",
            "PatternEmpty":
                "Empty pattern",
            "PatternInvalidSyntax":
                "Invalid syntax",
            "PatternEmptyGroup":
                "Syntax error (empty group)",

            // html.js
            "HtmlHandlerMultiplicityError":
                "Too many $HtmlHandler attributes for '{member}'",
            "HtmlHandlerMissing":
                "No $HtmlHandler attributes",
            "HtmlHandlerNoDefault":
                "No default $HtmlHandler attribute",

            // engine.js
            "EngineStackUnderflow":
                "Stack underflow",
            "EngineTypeCheck":
                "Type check",

            // encoding.js
            "EncodingNotSupported":
                "Encoding not supported",

            // xml.js
            "XmlInvalidName":
                "Invalid XML name"
        },

        /**
         * Generates an error function
         *
         * @param {Number} code
         * @param {String} name
         * @return {Function}
         * @closure
         */
        genThrowError = function (code, name) {
            return function (context) {
                var
                    error = new gpf.Error(),
                    replacements,
                    key;
                error.code = code;
                error.name = name;
                if (context) {
                    replacements = {};
                    for (key in context) {
                        if (context.hasOwnProperty(key)) {
                            replacements["{" + key + "}"] =
                                context[key].toString();
                        }
                    }
                    error.message = gpf.replaceEx(ERRORS[name], replacements);
                } else {
                    error.message = ERRORS[name];
                }
                throw error;
            };
        },

        name,
        code = 0;
    for (name in ERRORS) {
        if (ERRORS.hasOwnProperty(name)) {
            ++code;
            gpf.Error["CODE_" + name.toUpperCase()] = code;
            gpf.Error[name] = genThrowError(code, name);
        }
    }

/*#ifndef(UMD)*/
}()); /* End of privacy scope */
/*#endif*/<|endoftext|>


<commit_before>// Tally Votes in JavaScript Pairing Challenge.

// I worked on this challenge with: Juian Lesse
// This challenge took me [2.5] hours.

// These are the votes cast by each student. Do not alter these objects here.
var votes = {
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
  "Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
  "Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
  "Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
  "Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
  "Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
  "Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
  "Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
  "Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
  "Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
  "Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
  "Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}

// Tally the votes in voteCount.
var voteCount = {
  president: {},
  vicePresident: {},
  secretary: {},
  treasurer: {}
}

/* The name of each student receiving a vote for an office should become a property
of the respective office in voteCount.  After Alex's votes have been tallied,
voteCount would be ...

  var voteCount = {
    president: { Bob: 1 },
    vicePresident: { Devin: 1 },
    secretary: { Gail: 1 },
    treasurer: { Kerry: 1 }
  }

*/

/* Once the votes have been tallied, assign each officer position the name of the
student who received the most votes. */
var officers = {
  president: undefined,
  vicePresident: undefined,
  secretary: undefined,
  treasurer: undefined
}

// __________________________________________

// Pseudocode
/*
Create function named countVote that takes no parameters
  create a for loop that iterates through each voter name
    create an inner for loop that iterates through each office and candidate name pair
      IF (candidate name is alrady in corresponding office property of votecount)
        increment votecount[officename].candiatename by 1
      ELSE
        add candidate name to votecount[officename] with value 1
    end inner for loop
  end outer foorloop.
end function

create function name findWinner that takes no parameters
  for each job in voteCount
    find the property with the highest value
    store the  found property name in Officer[job].
  end for loop
end function

*/

// __________________________________________
// Initial Solution
// --> findWinner
// function findWinner(){
//   for (job in voteCount){
//     var max = 0
//     var winner;
//     for (name in voteCount[job]){
//       //console.log(name);
//       if(voteCount[job][name] > max){
//         max = voteCount[job][name];
//         winner = name;
//       }
//     }
//     officers[job] = winner;
//   }
// }

// function addvote(job, name){
//     if (voteCount.hasOwnProperty(job)){

//       if(voteCount[job].hasOwnProperty(name)){
//         voteCount[job][name] += 1;
//       }
//       else{
//         voteCount[job][name] = 1;
//       }
//     }
// }

// function countVote(){
//   for (var voterName in votes){
//     if (votes.hasOwnProperty(voterName)) {
//      for (var vote in votes[voterName]){
//         //console.log(vote);
//         // console.log(voterName + ": " + vote + ": " + votes[voterName][vote]);
//         // console.log(votes[voterName]);
//         addvote(vote, votes[voterName][vote]);
//      }
//     }
//   }
// }

// __________________________________________
// Refactored Solution

function findWinner(){
  for (job in voteCount){
    var maxNumberOfVotes = 0;
    var winner;
    for (candidate in voteCount[job]){
      if(voteCount[job][candidate] > maxNumberOfVotes){
        maxNumberOfVotes = voteCount[job][candidate];
        winner = candidate;
      }
    }
    officers[job] = winner;
  }
}

function addVote(job, candidate){
    if (voteCount.hasOwnProperty(job)){
      voteCount[job].hasOwnProperty(candidate) ? voteCount[job][candidate] += 1 : voteCount[job][candidate] = 1;
    }

function countVote(){
  for (var voterName in votes){
    if (votes.hasOwnProperty(voterName)) {
     for (var job in votes[voterName]){
        addVote(job, votes[voterName][job]);
     }
    }
  }
}

}

countVote();
findWinner();
console.log(officers);

// __________________________________________
// Refactored Solution

// __________________________________________
// Reflection

// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (voteCount.president["Bob"] === 3),
  "Bob should receive three votes for President.",
  "1. "
)

assert(
  (voteCount.vicePresident["Bob"] === 2),
  "Bob should receive two votes for Vice President.",
  "2. "
)

assert(
  (voteCount.secretary["Bob"] === 2),
  "Bob should receive two votes for Secretary.",
  "3. "
)

assert(
  (voteCount.treasurer["Bob"] === 4),
  "Bob should receive four votes for Treasurer.",
  "4. "
)

assert(
  (officers.president === "Louise"),
  "Louise should be elected President.",
  "5. "
)

assert(
  (officers.vicePresident === "Hermann"),
  "Hermann should be elected Vice President.",
  "6. "
)

assert(
  (officers.secretary === "Fred"),
  "Fred should be elected Secretary.",
  "7. "
)

assert(
  (officers.treasurer === "Ivy"),
  "Ivy should be elected Treasurer.",
  "8. "
)<commit_msg>Reflect on tally_votes<commit_after>// Tally Votes in JavaScript Pairing Challenge.

// I worked on this challenge with: Juian Lesse
// This challenge took me [2.5] hours.

// These are the votes cast by each student. Do not alter these objects here.
var votes = {
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
  "Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
  "Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
  "Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
  "Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
  "Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
  "Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
  "Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
  "Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
  "Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
  "Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
  "Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}

// Tally the votes in voteCount.
var voteCount = {
  president: {},
  vicePresident: {},
  secretary: {},
  treasurer: {}
}

/* The name of each student receiving a vote for an office should become a property
of the respective office in voteCount.  After Alex's votes have been tallied,
voteCount would be ...

  var voteCount = {
    president: { Bob: 1 },
    vicePresident: { Devin: 1 },
    secretary: { Gail: 1 },
    treasurer: { Kerry: 1 }
  }

*/

/* Once the votes have been tallied, assign each officer position the name of the
student who received the most votes. */
var officers = {
  president: undefined,
  vicePresident: undefined,
  secretary: undefined,
  treasurer: undefined
}

// __________________________________________

// Pseudocode
/*
Create function named countVote that takes no parameters
  create a for loop that iterates through each voter name
    create an inner for loop that iterates through each office and candidate name pair
      IF (candidate name is alrady in corresponding office property of votecount)
        increment votecount[officename].candiatename by 1
      ELSE
        add candidate name to votecount[officename] with value 1
    end inner for loop
  end outer foorloop.
end function

create function name findWinner that takes no parameters
  for each job in voteCount
    find the property with the highest value
    store the  found property name in Officer[job].
  end for loop
end function

*/

// __________________________________________
// Initial Solution
// --> findWinner
// function findWinner(){
//   for (job in voteCount){
//     var max = 0
//     var winner;
//     for (name in voteCount[job]){
//       //console.log(name);
//       if(voteCount[job][name] > max){
//         max = voteCount[job][name];
//         winner = name;
//       }
//     }
//     officers[job] = winner;
//   }
// }

// function addvote(job, name){
//     if (voteCount.hasOwnProperty(job)){

//       if(voteCount[job].hasOwnProperty(name)){
//         voteCount[job][name] += 1;
//       }
//       else{
//         voteCount[job][name] = 1;
//       }
//     }
// }

// function countVote(){
//   for (var voterName in votes){
//     if (votes.hasOwnProperty(voterName)) {
//      for (var vote in votes[voterName]){
//         //console.log(vote);
//         // console.log(voterName + ": " + vote + ": " + votes[voterName][vote]);
//         // console.log(votes[voterName]);
//         addvote(vote, votes[voterName][vote]);
//      }
//     }
//   }
// }

// __________________________________________
// Refactored Solution

function findWinner(){
  for (job in voteCount){
    var maxNumberOfVotes = 0;
    var winner;
    for (candidate in voteCount[job]){
      if(voteCount[job][candidate] > maxNumberOfVotes){
        maxNumberOfVotes = voteCount[job][candidate];
        winner = candidate;
      }
    }
    officers[job] = winner;
  }
}

function addVote(job, candidate){
    if (voteCount.hasOwnProperty(job)){
      voteCount[job].hasOwnProperty(candidate) ?
      voteCount[job][candidate] += 1 : voteCount[job][candidate] = 1;
    }
}

function countVote(){
  for (voterName in votes){
    if (votes.hasOwnProperty(voterName)) {
     for (job in votes[voterName]){
        addVote(job, votes[voterName][job]);
     }
    }
  }
}

countVote();
findWinner();
console.log(officers);
console.log(voterName + " voted for " + votes[voterName][job] + " for " + job + ". " );

// __________________________________________
// Reflection
/*
What did you learn about iterating over nested objects in JavaScript?
  We used a lot of for and for..in constructions since the order of the array items was not important.

Were you able to find useful methods to help you with this?
  There were a few other options, but we wanted to stick to something
  pretty simple to help solidify our understanding. I think we could have used the
  prototype.forEach() method but it wasn't necessary.

What concepts were solidified in the process of working through this challenge?
  Before this challenge I spent quite a while making my own nested objects and playing with them.
  But until I worked on this, I thought "hasOwnProperty" was just a made up variable,
  rather than an entire method. That was a big help. We re-factored one part of
  the code to have a ternary operator, which I had done in Ruby but not yet in JS.

*/
// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (voteCount.president["Bob"] === 3),
  "Bob should receive three votes for President.",
  "1. "
)

assert(
  (voteCount.vicePresident["Bob"] === 2),
  "Bob should receive two votes for Vice President.",
  "2. "
)

assert(
  (voteCount.secretary["Bob"] === 2),
  "Bob should receive two votes for Secretary.",
  "3. "
)

assert(
  (voteCount.treasurer["Bob"] === 4),
  "Bob should receive four votes for Treasurer.",
  "4. "
)

assert(
  (officers.president === "Louise"),
  "Louise should be elected President.",
  "5. "
)

assert(
  (officers.vicePresident === "Hermann"),
  "Hermann should be elected Vice President.",
  "6. "
)

assert(
  (officers.secretary === "Fred"),
  "Fred should be elected Secretary.",
  "7. "
)

assert(
  (officers.treasurer === "Ivy"),
  "Ivy should be elected Treasurer.",
  "8. "
)<|endoftext|>


<commit_before>function Point(x,y){
	this.x = x;
	this.y = y;
}

function Shape(elem, points){
	this.lines = [];
	this.points = points || [];
	this.elem = elem;
	this.init();
}

Shape.prototype = {
	constructor:Shape,
	init:function(){
		this.context = this.context || document.getElementById(this.elem).getContext('2d');
	},
	draw:function(){
		var ctx = this.context;
		ctx.fillStyle = 'green';
		ctx.beginPath();

		ctx.moveTo(this.points[0].x,this.points[0].y);
		for (var idx = 1; idx < this.points.length; idx++) {
			ctx.lineTo(this.points[idx].x,this.points[idx].y);ctx.fill();
		}

		ctx.stroke();
		ctx.closePath();
	}
};

function extend(Child, Parent){
	Child.prototype = Object.create(Parent.prototype);
	Child.prototype.constructor = Child;
}

function Square(elem, points){
	Shape.apply(this, arguments);
}

extend(Square,Shape);
// Square.prototype = Object.create(Shape.prototype);
// Square.prototype.constructor = Square;

function Rectangle(elem, points){
	Square.apply(this, arguments);	//Note here Square instead of Shape
}

function Triangle(elem, points){
	Shape.apply(this, arguments);
}

extend(Triangle,Shape);
// Triangle.prototype = Object.create(Shape.prototype);
// Triangle.prototype.constructor = Triangle;

function Circle(elem, points){
	Shape.apply(this, arguments);
	this.points = points;
}

extend(Circle,Shape);
// Circle.prototype = Object.create(Shape.prototype);
// Circle.prototype.constructor = Circle;
Circle.prototype.draw = function(){
	var ctx = this.context;
	ctx.beginPath();
	ctx.fillStyle = 'red';
	ctx.arc(this.points.centerX, this.points.centerY, this.points.radius, 0, Math.PI*2, true);
	ctx.fill();
};

var p1  = new Point(100,100);
var p2  = new Point(200,100);
var p3  = new Point(200,200);
var p4  = new Point(100,200);

var shape1 = new Shape('canvas',[p1,p2,p3,p4]);
shape1.draw();

var circle1 = new Circle('canvas1',{
	centerX:150,
	centerY:150,
	radius:60
});

circle1.draw();

var p1  = new Point(100,100);
var p2  = new Point(130,200);
var p3  = new Point(200,100);

var triangle1 = new Triangle('canvas2',[p1,p2,p3]);
triangle1.draw();

<commit_msg>IFEE added and commented<commit_after>/**
	@author Raja Jaganathan
*/

(function() {

    'use strict';

    function Point(x, y) {
        this.x = x;
        this.y = y;
    }

    function Shape(elem, points) {
        this.lines = [];
        this.points = points || [];
        this.elem = elem;
        this.init();
    }

    Shape.prototype = {
        constructor: Shape,
        init: function() {
            this.context = this.context || document.getElementById(this.elem).getContext('2d');
        },
        draw: function() {
            var ctx = this.context;
            ctx.fillStyle = 'green';
            ctx.beginPath();

            ctx.moveTo(this.points[0].x, this.points[0].y);
            for (var idx = 1; idx < this.points.length; idx++) {
                ctx.lineTo(this.points[idx].x, this.points[idx].y);
                ctx.fill();
            }

            ctx.stroke();
            ctx.closePath();
        }
    };

    function extend(Child, Parent) {
        Child.prototype = Object.create(Parent.prototype);
        Child.prototype.constructor = Child;
    }

    function Square(elem, points) {
        Shape.apply(this, arguments);
    }

    extend(Square, Shape);
    // Square.prototype = Object.create(Shape.prototype);
    // Square.prototype.constructor = Square;

    function Rectangle(elem, points) {
        Square.apply(this, arguments); //Note here Square instead of Shape
    }

    function Triangle(elem, points) {
        Shape.apply(this, arguments);
    }

    extend(Triangle, Shape);
    // Triangle.prototype = Object.create(Shape.prototype);
    // Triangle.prototype.constructor = Triangle;

    function Circle(elem, points) {
        Shape.apply(this, arguments);
        this.points = points;
    }

    extend(Circle, Shape);
    // Circle.prototype = Object.create(Shape.prototype);
    // Circle.prototype.constructor = Circle;
    Circle.prototype.draw = function() {
        var ctx = this.context;
        ctx.beginPath();
        ctx.fillStyle = 'red';
        ctx.arc(this.points.centerX, this.points.centerY, this.points.radius, 0, Math.PI * 2, true);
        ctx.fill();
    };

    //For Square
    var p1 = new Point(100, 100);
    var p2 = new Point(200, 100);
    var p3 = new Point(200, 200);
    var p4 = new Point(100, 200);

    var squareInstance = new Square('canvas', [p1, p2, p3, p4]);
    squareInstance.draw();

    //For Circle
    var circleInstance = new Circle('canvas1', {
        centerX: 150,
        centerY: 150,
        radius: 60
    });

    circleInstance.draw();

    //For Triangle
    p1 = new Point(100, 100);
    p2 = new Point(130, 200);
    p3 = new Point(200, 100);

    var triangleInstance = new Triangle('canvas2', [p1, p2, p3]);
    triangleInstance.draw();

}());
<|endoftext|>


<commit_before>const express = require('express');
const router = express.Router();
const yahooFinance = require('yahoo-finance');
const bodyParser = require('body-parser').json();
const url = require('url');
const qs = require('querystring');

router

    .get('/', bodyParser, (req, res, next) => {
        const stocks = qs.parse(url.parse(req.url).query).stocks;
        const stockSplit = stocks.split(',');
        yahooFinance.snapshot({
            symbols: stockSplit,
            fields: [ 'n', 's', 'a', 'g', 'h', 'y', 'd', 'r', 'b4', 'e', 'j4', 'r6', 's7' ] // s is symbol, a is ask price
        })
        .then(snapshot => res.send(snapshot))
        .catch(next);
    });

module.exports = router;
<commit_msg>changes on new route for dailyupdate<commit_after>const express = require('express');
const router = express.Router();
const yahooFinance = require('yahoo-finance');
const bodyParser = require('body-parser').json();
const url = require('url');
const qs = require('querystring');
const stockstore = require('../models/stockstore');

router

    .get('/', bodyParser, (req, res, next) => {
        const stocks = qs.parse(url.parse(req.url).query).stocks;
        const stockSplit = stocks.split(',');
        yahooFinance.snapshot({
            symbols: stockSplit,
            fields: [ 'n', 's', 'a', 'g', 'h', 'y', 'd', 'r', 'b4', 'e', 'j4', 'r6', 's7' ] // s is symbol, a is ask price
        })
        .then(snapshot => res.send(snapshot))
        .catch(next);
    })

    .get('/dailyUpdate', bodyParser, (req, res, next) => {
        const stockValueMap = {};
        stockstore.find()
          .then(stocks => {
              const stockTickers = Object.keys(stocks[0].stocks);
              yahooFinance.snapshot({
                  symbols: stockTickers,
                  fields: [ 'n', 's', 'a', 'g', 'h', 'y', 'd', 'r', 'b4', 'e', 'j4', 'r6', 's7' ] // s is symbol, a is ask price
              })
              .then(snapshot =>
                snapshot.forEach(snapshot => {
                    stockValueMap[snapshot.symbol] = snapshot.ask;
                })
                portfolio.find()
                  .then(portfolios => {})
              );

          });

    });

module.exports = router;
<|endoftext|>


<commit_before>(function (root, factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define([], factory);
	} else {
		// Browser globals
		root.cling = factory();
	}
}(this, function () {

	var win = window,
		doc = document;

	// Utilities

	// function between (min, num, max) {
	// 	return Math.max(min, Math.min(max, num));
	// }

	function extend (target) {
		var o = arguments,
			l = o.length,
			x = 1,
			y;
		for (; x < l; x++) {
			for (y in o[x]) {
				target[y] = o[x][y];
			}
		}
		return target;
	}

	function toNumber (num) {
		return isFinite(num = parseFloat(num)) ? num : 0;
	}

	function indexOf (array, search) {
		if ( array.indexOf ) {
			return array.indexOf(search);
		}
		for (var i = 0, l = array.length; i < l; i++) {
			if (search === array[i]) {
				return i;
			}
		}
		return -1;
	}

	// function proxy (fn, context) {
	// 	return function () {
	// 		return fn.apply(context, arguments);
	// 	};
	// }

	function throttle ( fn ) {
		var timer = false;
		return function () {
			var c = this, a = arguments;
			if (false === timer)
				timer = win.requestAnimationFrame(function () {
					fn.apply(c, a);
					timer = false;
				});
		};
	}

	// DOM Utilities

	function on (element, event, callback) {
		if (element.addEventListener) {
			element.addEventListener(event, callback, false);
		} else if (element.attachEvent) {
			element.attachEvent('on' + event, callback);
		}
	}

	function off (element, event, callback) {
		if (element.removeEventListener) {
			element.removeEventListener(event, callback, false);
		} else if (element.detachEvent) {
			element.detachEvent('on' + event, callback);
		}
	}

	function getStyle (element, property) {
		if (win.getComputedStyle) {
			return win.getComputedStyle(element, null).getPropertyValue(property);
		}
		if (element.currentStyle) {
			return element.currentStyle[property];
		}
	}

	// Cling

	var optionsDefault     = {from: '', to: '', offset: ''},
		positionMultiplier = {left: 0, top: 0, right: 1, bottom: 1, center: 0.5},

		instances = [];

	var updateAll = throttle(function () {
		var i = instances.length;
		while (i--) {
			instances[i].update();
		}
	});

	function normalizePosition (position) {
		position = position.match(/(left|right|center)\s*(top|bottom|center)?/);
		return [(position[1] || 'center'), (position[2] || 'center')];
	}

	function normalizeOffset (offset) {
		offset = offset.match(/(-?\d+)\s*(-?\d+)?/);
		return [toNumber(offset[1]), toNumber(offset[2])];
	}

	on(win, 'scroll'   , updateAll);
	on(win, 'resize'   , updateAll);
	on(win, 'touchmove', updateAll);

	function Cling (element, target, options) {
		this.e = element;
		this.t = target;
		return this.options(options).enable();
	}

	Cling.prototype = {

		options: function (options) {
			options        = extend(optionsDefault, options);
			options.from   = normalizePosition(options.from);
			options.to     = normalizePosition(options.to);
			options.offset = normalizeOffset(options.offset);
			this.o = options;
			return this;
		},

		update: function () {
			var element = this.e,
				target  = this.t,
				options = this.o,

				elementBounding = element.getBoundingClientRect(),
				targetBounding  = target.getBoundingClientRect(),

				left = (targetBounding.width * positionMultiplier[options.from[0]])  // target point
				     - (elementBounding.width * positionMultiplier[options.to[0]])   // element point
				     + (targetBounding.left - elementBounding.left)                  // target-element offset
				     + options.offset[0]                                             // defined offset
				     + toNumber(getStyle(element, 'left')),                          // recalculate position

				top  = (targetBounding.height * positionMultiplier[options.from[1]]) // target point
				     - (elementBounding.height * positionMultiplier[options.to[1]])  // element point
				     + (targetBounding.top - elementBounding.top)                    // target-element offset
				     + options.offset[1]                                             // defined offset
				     + toNumber(getStyle(element, 'top'));                           // recalculate position

			element.style.left = Math.round(left) + 'px';
			element.style.top  = Math.round(top)  + 'px';

			return this;
		},

		enable: function () {
			if (indexOf(instances, this) < 0) {
				instances.push(this);
				this.e.style.position = 'absolute';
			}
			return this.update();
		},

		disable: function () {
			var index = indexOf(instances, this);
			if (index > -1) {
				instances.splice(index, 1);
				this.e.style.position = this.e.style.top = this.e.style.left = '';
			}
			return this;
		}

	};

	return function (element, target, options) {
		return new Cling(element, target, options);
	};

}));<commit_msg>Works with \!<commit_after>(function (root, factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define([], factory);
	} else {
		// Browser globals
		root.cling = factory();
	}
}(this, function () {

	var win = window,
		doc = document;

	// Utilities

	// function between (min, num, max) {
	// 	return Math.max(min, Math.min(max, num));
	// }

	function extend (target) {
		var o = arguments,
			l = o.length,
			x = 1,
			y;
		for (; x < l; x++) {
			for (y in o[x]) {
				target[y] = o[x][y];
			}
		}
		return target;
	}

	function toNumber (num) {
		return isFinite(num = parseFloat(num)) ? num : 0;
	}

	function indexOf (array, search) {
		if ( array.indexOf ) {
			return array.indexOf(search);
		}
		for (var i = 0, l = array.length; i < l; i++) {
			if (search === array[i]) {
				return i;
			}
		}
		return -1;
	}

	// function proxy (fn, context) {
	// 	return function () {
	// 		return fn.apply(context, arguments);
	// 	};
	// }

	function throttle ( fn ) {
		var timer = false;
		return function () {
			var c = this, a = arguments;
			if (false === timer)
				timer = win.requestAnimationFrame(function () {
					fn.apply(c, a);
					timer = false;
				});
		};
	}

	// DOM Utilities

	function on (element, event, callback) {
		if (element.addEventListener) {
			element.addEventListener(event, callback, false);
		} else if (element.attachEvent) {
			element.attachEvent('on' + event, callback);
		}
	}

	function off (element, event, callback) {
		if (element.removeEventListener) {
			element.removeEventListener(event, callback, false);
		} else if (element.detachEvent) {
			element.detachEvent('on' + event, callback);
		}
	}

	function getStyle (element, property) {
		if (win.getComputedStyle) {
			return win.getComputedStyle(element, null).getPropertyValue(property);
		}
		if (element.currentStyle) {
			return element.currentStyle[property];
		}
	}

	// Cling

	var optionsDefault     = {from: '', to: '', offset: ''},
		positionMultiplier = {left: 0, top: 0, right: 1, bottom: 1, center: 0.5},

		instances = [];

	var updateAll = throttle(function () {
		var i = instances.length;
		while (i--) {
			instances[i].update();
		}
	});

	function normalizePosition (position) {
		position = position.match(/(left|right|center)\s*(top|bottom|center)?/);
		return [(position[1] || 'center'), (position[2] || 'center')];
	}

	function normalizeOffset (offset) {
		offset = offset.match(/(-?\d+)\s*(-?\d+)?/);
		return [toNumber(offset[1]), toNumber(offset[2])];
	}

	on(win, 'scroll'   , updateAll);
	on(win, 'resize'   , updateAll);
	on(win, 'touchmove', updateAll);

	function Cling (element, target, options) {
		this.e = element;
		this.t = target;
		return this.options(options).enable();
	}

	Cling.prototype = {

		options: function (options) {
			options        = extend(optionsDefault, options);
			options.from   = normalizePosition(options.from);
			options.to     = normalizePosition(options.to);
			options.offset = normalizeOffset(options.offset);
			this.o = options;
			return this;
		},

		update: function () {
			var element = this.e,
				target  = this.t,
				options = this.o,

				elementBounding = element.getBoundingClientRect(),
				targetBounding  = target.getBoundingClientRect(),

				left = (targetBounding.width * positionMultiplier[options.from[0]])  // target point
				     - (elementBounding.width * positionMultiplier[options.to[0]])   // element point
				     + (targetBounding.left - elementBounding.left)                  // target-element offset
				     + options.offset[0]                                             // defined offset
				     + toNumber(getStyle(element, 'left')),                          // recalculate position

				top  = (targetBounding.height * positionMultiplier[options.from[1]]) // target point
				     - (elementBounding.height * positionMultiplier[options.to[1]])  // element point
				     + (targetBounding.top - elementBounding.top)                    // target-element offset
				     + options.offset[1]                                             // defined offset
				     + toNumber(getStyle(element, 'top'));                           // recalculate position

			element.style.left = Math.round(left) + 'px';
			element.style.top  = Math.round(top)  + 'px';

			return this;
		},

		enable: function () {
			var element = this.e;
			if (indexOf(instances, this) < 0) {
				instances.push(this);
			}
			if (!getStyle(element, 'position').match(/absolute|fixed/)) {
				element.style.position = 'absolute';
			}
			return this.update();
		},

		disable: function () {
			var index = indexOf(instances, this);
			if (index > -1) {
				instances.splice(index, 1);
				this.e.style.position = this.e.style.top = this.e.style.left = '';
			}
			return this;
		}

	};

	return function (element, target, options) {
		return new Cling(element, target, options);
	};

}));<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 * @emails oncall+draft_js
 */

const DraftEntity = jest.genMockFromModule('DraftEntity');

const DraftEntityInstance = {
  getType: jest.fn(() => ''),
  getMutability: jest.fn(() => ''),
  getData: jest.fn(() => ({})),
};

let count = 0;

DraftEntity.create = jest.fn(function () {
  count++;
  return '' + count;
});

DraftEntity.get = jest.fn(function () {
  return DraftEntityInstance;
});

module.exports = DraftEntity;
<commit_msg>Autofix ESLint Rule fb-www/format-docblock: html/shared/draft-js/model/entity/__mocks__<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails oncall+draft_js
 * @format
 */

const DraftEntity = jest.genMockFromModule('DraftEntity');

const DraftEntityInstance = {
  getType: jest.fn(() => ''),
  getMutability: jest.fn(() => ''),
  getData: jest.fn(() => ({})),
};

let count = 0;

DraftEntity.create = jest.fn(function () {
  count++;
  return '' + count;
});

DraftEntity.get = jest.fn(function () {
  return DraftEntityInstance;
});

module.exports = DraftEntity;
<|endoftext|>


<commit_before><commit_msg>allow socket.io to run on the correct http protocol<commit_after><|endoftext|>


<commit_before>// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// lib:  jssyncml.router
// auth: griffin <griffin@uberdev.org>
// date: 2012/11/04
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

// for node compatibility...
if ( typeof(define) !== 'function')
  var define = require('amdefine')(module);

define([
  'underscore',
  'elementtree',
  './logging',
  './common',
  './constant',
  './ctype',
  './storage'
], function(
  _,
  ET,
  logging,
  common,
  constant,
  ctype,
  storage
) {

  var log = logging.getLogger('jssyncml.router');
  var exports = {};

  //---------------------------------------------------------------------------
  exports.Router = common.Base.extend({

    //-------------------------------------------------------------------------
    constructor: function(options) {
    },

    //-------------------------------------------------------------------------
    getTargetUri: function(adapter, peer, sourceUri) {

      log.critical('TODO ::: Router.getTargetUri() NOT IMPLEMENTED');

      return null;
    },

    //-------------------------------------------------------------------------
    recalculate: function(adapter, peer, cb) {
      // the default recalculate does nothing - it requires that all routes
      // be set up manually.
      return cb();
    },

  });

  //---------------------------------------------------------------------------
  exports.SmartRouter = exports.Router.extend({

    //-------------------------------------------------------------------------
    recalculate: function(adapter, peer, cb) {

      log.critical('TODO ::: SmartRouter.recalculate() NOT IMPLEMENTED');

      return cb();
    },

  });

  return exports;

});

//-----------------------------------------------------------------------------
// end of $Id$
//-----------------------------------------------------------------------------
<commit_msg>implemented basic (non-"smart") route recalculator<commit_after>// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// lib:  jssyncml.router
// auth: griffin <griffin@uberdev.org>
// date: 2012/11/04
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

// for node compatibility...
if ( typeof(define) !== 'function')
  var define = require('amdefine')(module);

define([
  'underscore',
  'elementtree',
  './logging',
  './common',
  './constant',
  './ctype',
  './storage'
], function(
  _,
  ET,
  logging,
  common,
  constant,
  ctype,
  storage
) {

  var log = logging.getLogger('jssyncml.router');
  var exports = {};

  //---------------------------------------------------------------------------
  exports.Router = common.Base.extend({

    //-------------------------------------------------------------------------
    constructor: function(options) {
    },

    //-------------------------------------------------------------------------
    getTargetUri: function(adapter, peer, sourceUri) {
      var pmodel = peer._getModel();
      for ( var idx=0 ; idx<pmodel.routes.length ; idx++ )
      {
        var route = pmodel.routes[idx];
        if ( route.localUri == sourceUri )
          return route.remoteUri;
      }
      for ( var idx=0 ; idx<pmodel.stores.length ; idx++ )
      {
        var store = pmodel.stores[idx];
        if ( store.binding && store.binding.uri == sourceUri )
          return store.uri;
      }
      return null;
    },

    //-------------------------------------------------------------------------
    recalculate: function(adapter, peer, cb) {
      // the non-"SmartRouter" only connects manually-configured routes...

      // available local URIs
      var lset = _.map(adapter._model.stores,
                       function(s) { return adapter.normUri(s.uri); });
      // available remote URIs
      var rset = _.map(peer._getModel().stores,
                       function(s) { return peer.normUri(s.uri); });
      // manual routes
      var routes = _.filter(peer._getModel().routes,
                            function(r) { return ! r.autoMapped; });

      var err = null;
      _.each(routes, function(route) {
        if ( err )
          return;

        route.localUri  = adapter.normUri(route.localUri);
        route.remoteUri = peer.normUri(route.remoteUri);

        if ( _.indexOf(rset, route.remoteUri) < 0
             || _.indexOf(lset, route.localUri) < 0 )
        {
          err = 'unable to route from "' + route.localUri
            + '" to "' + route.remoteUri
            + '": no such stores or already routed elsewhere';
          return;
        }

        lset = _.filter(lset, function(uri) { return uri != route.localUri; });
        rset = _.filter(rset, function(uri) { return uri != route.remoteUri; });

        log.debug('setting up route from "' + route.localUri + '" to "'
                  + route.remoteUri + '"');

        var smodel = peer.getStore(route.remoteUri)._getModel();
        if ( smodel.binding && smodel.binding.uri == route.localUri )
          return;
        smodel.binding = {
          uri          : route.localUri,
          autoMapped   : false,
          localAnchor  : null,
          remoteAnchor : null
        };
      });

      if ( err )
        return cb(err);

      return cb();
    },

    getBestTransmitContentType: function(session, uri) {
      log.critical('TODO ::: Router.getBestTransmitContentType NOT IMPLEMENTED');
      return ['text/plain', '1.1'];
    },

  });

  //---------------------------------------------------------------------------
  exports.SmartRouter = exports.Router.extend({

    //-------------------------------------------------------------------------
    recalculate: function(adapter, peer, cb) {

      log.critical('TODO ::: SmartRouter.recalculate() NOT IMPLEMENTED');
      return exports.Router.prototype.recalculate.call(this, adapter, peer, cb);

    },

  });

  return exports;

});

//-----------------------------------------------------------------------------
// end of $Id$
//-----------------------------------------------------------------------------
<|endoftext|>