<commit_before>import Ember from 'ember';
import config from './config/environment';

export default function (prefix) {
	var seen = Ember.keys(requirejs._eak_seen);

	seen.filter(function (key) {
		return key.test('^' + config.modulePrefix + '/locales/').length > 0;
	}).forEach(function (moduleName) {
		try {
			var module = require(moduleName, null, null, true);
			//
			// register this into the service?
			//
		} catch (err) {
			/**
			NOTE: Silently fail on helpers that could not be registered.
			This is because we have some helpers in the helper folder
			that are not actual helpers.  There is a github issue opened to
			move these to utils, and then we can remove this in favor of

			Ember.Logger.error(err);
			*/
		}
	});
}
<commit_msg>[Enhancement] Removing register-locales<commit_after><|endoftext|>


<commit_before>// // ===============================================================================
// // LOAD DATA
// // We are linking our routes to a series of "data" sources.
// // These data sources hold arrays of information on beer data, beer add list, etc.
// // ===============================================================================

// const beerData = require("../data/_____[PLACEHOLDER]");
// const beerAddData = require("../data/_____[PLACEHOLDER]");

// // ===============================================================================
// // ROUTING
// // ===============================================================================
var axios = require('axios');
var router = require('express').Router();
var BreweryDb = require('brewerydb-node');
var brewdb = new BreweryDb('3f1612c064ffbdbd5925f006fa955076');

  // API GET Requests
  // Below code handles when users "visit" a page.
  // In each of the below cases when a user visits a link
  // (ex: localhost:PORT/api/admin... they are shown a JSON of the data)
  // ---------------------------------------------------------------------------

  router.get("/beers", function(req, res) {
  	var search = 'English Pale';
  	var nameArray = [];
	brewdb.search.all({q: search}, function(err, data) {
		for(var i = 0; i < data.length; i++) {
			nameArray.push(data[i].name);
		}
	    res.json(nameArray);
	});

  });

  // app.get("/api/beerAdd", function(req, res) {
  //   res.json(waitListData);
  // });

  // API POST Requests
  // Below code handles when a user submits a form and thus submits data to the server.
  // In each of the below cases, when a user submits form data (a JSON object)
  // ...the JSON is pushed to the appropriate JS array
  // (ex. User fills out a beer [_________]... this data is then sent to the server...
  // Then the server saves the data to the beerData array)
  // ---------------------------------------------------------------------------

  // app.post("/api/beers", function(req, res) {
  //   // Note the code here. Our "server" will respond to requests and let users know if they have a table or not.
  //   // It will do this by sending out the value "true" have a beer
  //   if (beerData.length < ___[PLACEHOLDER]) {
  //     beerData.push(req.body);
  //     res.json(true);
  //   }
  //   else {
  //     beerAddData.push(req.body);
  //     res.json(false);
  //   }
  // });

  // ---------------------------------------------------------------------------
// I added this below code so you could clear out the beerData while working with the functionality.
//   // Don't worry too much about it!

//   app.post("/api/clear", function() {
//     // Empty out the arrays of data
//     beerData = [];
//     beerAddData = [];

//     console.log(beerData);
//   });

module.exports = router;

// Database:
// brewdb.search.all() - finds every parent category of types of beers<commit_msg>renaming<commit_after>// // ===============================================================================
// // LOAD DATA
// // We are linking our routes to a series of "data" sources.
// // These data sources hold arrays of information on beer data, beer add list, etc.
// // ===============================================================================

// const beerData = require("../data/_____[PLACEHOLDER]");
// const beerAddData = require("../data/_____[PLACEHOLDER]");

// // ===============================================================================
// // ROUTING
// // ===============================================================================
var axios = require('axios');
var router = require('express').Router();
var BreweryDb = require('brewerydb-node');
var brewdb = new BreweryDb('3f1612c064ffbdbd5925f006fa955076');

  // API GET Requests
  // Below code handles when users "visit" a page.
  // In each of the below cases when a user visits a link
  // (ex: localhost:PORT/api/admin... they are shown a JSON of the data)
  // ---------------------------------------------------------------------------

  router.get("/beers", function(req, res) {
  	var search = 'English Pale';
  	var beerQuery = [];
	brewdb.search.all({q: search}, function(err, data) {
		for(var i = 0; i < data.length; i++) {
			beerQuery.push({
				name: data[i].name,
				description: data[i].description
			});
		}
	    res.json(nameArray);
	});

  });

  // app.get("/api/beerAdd", function(req, res) {
  //   res.json(waitListData);
  // });

  // API POST Requests
  // Below code handles when a user submits a form and thus submits data to the server.
  // In each of the below cases, when a user submits form data (a JSON object)
  // ...the JSON is pushed to the appropriate JS array
  // (ex. User fills out a beer [_________]... this data is then sent to the server...
  // Then the server saves the data to the beerData array)
  // ---------------------------------------------------------------------------

  // app.post("/api/beers", function(req, res) {
  //   // Note the code here. Our "server" will respond to requests and let users know if they have a table or not.
  //   // It will do this by sending out the value "true" have a beer
  //   if (beerData.length < ___[PLACEHOLDER]) {
  //     beerData.push(req.body);
  //     res.json(true);
  //   }
  //   else {
  //     beerAddData.push(req.body);
  //     res.json(false);
  //   }
  // });

  // ---------------------------------------------------------------------------
// I added this below code so you could clear out the beerData while working with the functionality.
//   // Don't worry too much about it!

//   app.post("/api/clear", function() {
//     // Empty out the arrays of data
//     beerData = [];
//     beerAddData = [];

//     console.log(beerData);
//   });

module.exports = router;

// Database:
// brewdb.search.all() - finds every parent category of types of beers<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var Campaign = require('../models/campaign');

/* GET home page. */
router.get('/', function(req, res, next) {
    res.json("Default route for campaigns");

});

router.post('/', function (req, res) {
    console.log(req.body);

    if(!req.body.name || !req.body.type || !req.body.description || !req.body.enabled || !req.body.expiring || !req.body.likes
        || !req.body.image || !req.body.tags || !req.body.wantin)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the reuired parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else
    {
        const campaign = new Campaign({
            name: req.body.name,
            type: req.body.type,
            description: req.body.description,
            enabled : req.body.enabled,
            expiring : req.body.expiring,
            likes : req.body.likes,
            image : req.body.image,
            tags : req.body.tags,
            wantin: req.body.wantin
        });

        console.log('Saving Campaign :  ' + req.body.name);

        campaign.save(function(err){
            if(err)
            {
                console.log(err);
                return res.status(400).json({ success: false, message: 'An error occurred on trying to save campaign, please try again later ' + err});
            }

            res.status(201).json({ success: true, message: 'Successfully created Campaign ' + req.body.name });
        })
    }

});

router.post('/createCampaign', function (req, res) {

    res.sendStatus(200);

});

//Get the top trending campaigns on Shoppa
router.get('/getTopCampaigns', function (req, res) {

    res.sendStatus(200);

});

/*
Get campaigns that users have opt in for on Shoppa

*/
router.get('/getUserCampaigns', function (req, res) {

    res.sendStatus(200);

});

/*
Get expiring campaigns by number of days

*/

router.get('/getExpiringCampaigns', function (req, res) {

    res.sendStatus(200);

});

module.exports = router;
<commit_msg>Get All and Top Campaigns<commit_after>var express = require('express');
var router = express.Router();
var Campaign = require('../models/campaign');

/* GET home page. */
router.get('/', function(req, res, next) {
    res.json("Default route for campaigns");

});

router.post('/', function (req, res) {
    console.log(req.body);

    if(!req.body.name || !req.body.type || !req.body.description || !req.body.enabled || !req.body.expiring || !req.body.likes
        || !req.body.image || !req.body.tags || !req.body.wantin)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the reuired parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else
    {
        const campaign = new Campaign({
            name: req.body.name,
            type: req.body.type,
            description: req.body.description,
            enabled : req.body.enabled,
            expiring : req.body.expiring,
            likes : req.body.likes,
            image : req.body.image,
            tags : req.body.tags,
            wantin: req.body.wantin
        });

        console.log('Saving Campaign :  ' + req.body.name);

        campaign.save(function(err){
            if(err)
            {
                console.log(err);
                return res.status(400).json({ success: false, message: 'An error occurred on trying to save campaign, please try again later ' + err});
            }

            res.status(201).json({ success: true, message: 'Successfully created Campaign ' + req.body.name });
        })
    }

});

router.get('/', function (req, res) {
    console.log(req);

    Campaign.find({}, function(err,result){
        res.status(201).json({ success: true,result:result, message: 'Successfully created Campaign ' + req.body.name });
    })

});

//Get the top trending campaigns on Shoppa
router.get('/getTopCampaigns', function (req, res) {
    console.log(req);

    Campaign.find({likes: { $gte: 10 }}, function(err,result){
        res.status(201).json({ success: true,result:result, message: 'Successfully created Campaign ' + req.body.name });
    })

});

/*
Get campaigns that users have opt in for on Shoppa

*/
router.get('/getUserCampaigns', function (req, res) {

    res.sendStatus(200);

});

/*
Get expiring campaigns by number of days

*/

router.get('/getExpiringCampaigns', function (req, res) {

    res.sendStatus(200);

});

module.exports = router;
<|endoftext|>


<commit_before>import { scaleLinear, scaleLog } from 'd3-scale';

import HorizontalLine1DPixiTrack from './HorizontalLine1DPixiTrack';

// Utils
import { colorToHex, dictValues } from './utils';

class BarTrack extends HorizontalLine1DPixiTrack {
  initTile(tile) {
    /**
         * Create whatever is needed to draw this tile.
         */
    super.initTile(tile);

    // this.drawTile(tile);
    this.renderTile(tile);
  }

  drawTile(tile) {
    // empty function so that the superclass's drawTile
    // doesn't do anything
  }

  updateTile(tile) {
    // console.log('tile.valueScale', tile.valueScale, 'this.scale', this.scale);
    if (tile.valueScale && this.scale &&
      this.scale.minValue == tile.scale.minValue &&
      this.scale.maxValue == tile.scale.maxValue) {
      // already rendered properly, no need to rerender
    } else {
      // not rendered using the current scale, so we need to rerender
      this.renderTile(tile);
    }
  }

  renderTile(tile) {
    //super.drawTile(tile);

    if (!tile.graphics) { return; }

    const graphics = tile.graphics;

    const { tileX, tileWidth } = this.getTilePosAndDimensions(tile.tileData.zoomLevel,
      tile.tileData.tilePos,
      this.tilesetInfo.bins_per_dimension || this.tilesetInfo.tile_size);
    const tileValues = tile.tileData.dense;

    if (tileValues.length == 0) { return; }

    // equal to the smallest non-zero value
    const [vs, pseudocount] = this.makeValueScale(this.minVisibleValue(), this.medianVisibleValue,
      this.maxValue(), 0);
    this.valueScale = vs;
    // console.log('pseudocount:', pseudocount, this.valueScale.domain());

    graphics.clear();

    this.drawAxis(this.valueScale);

    if (this.options.valueScaling == 'log' && this.valueScale.domain()[1] < 0) {
      console.warn('Negative values present when using a log scale', this.valueScale.domain());
      return;
    }

    const stroke = colorToHex(this.options.lineStrokeColor ? this.options.lineStrokeColor : 'blue');
    // this scale should go from an index in the data array to
    // a position in the genome coordinates
    const tileXScale = scaleLinear().domain([0, this.tilesetInfo.tile_size || this.tilesetInfo.bins_per_dimension])
      .range([tileX, tileX + tileWidth]);

    // let strokeWidth = this.options.lineStrokeWidth ? this.options.lineStrokeWidth : 1;

    const strokeWidth = 0;
    graphics.lineStyle(strokeWidth, stroke, 1);

    const color = this.options.barFillColor ? this.options.barFillColor : 'grey'
    const colorHex = colorToHex(color);

    const opacity = 'barOpacity' in this.options ? this.options.barOpacity : 1;

    graphics.beginFill(colorHex, opacity);

    const j = 0;
    tile.drawnAtScale = this._xScale.copy();

    for (let i = 0; i < tileValues.length; i++) {
      const xPos = this._xScale(tileXScale(i));
      const yPos = this.valueScale(tileValues[i] + pseudocount);
      // console.log('tileValues[i]', tileValues[i], yPos, this.valueScale.domain(), this.valueScale.range());

      const width = this._xScale(tileXScale(i + 1)) - xPos;
      const height = this.dimensions[1] - yPos;

      this.addSVGInfo(tile, xPos, yPos, width, height, color);

      if (tileXScale(i) > this.tilesetInfo.max_pos[0])
      // this data is in the last tile and extends beyond the length
      // of the coordinate system
      { break; }

      graphics.drawRect(xPos,
        yPos,
        width,
        height);
    }
  }

  draw() {
    // we don't want to call HorizontalLine1DPixiTrack's draw function
    // but rather its parent's
    super.draw();

    for (const tile of dictValues(this.fetchedTiles)) {
      // scaling between tiles
      const tileK = (tile.drawnAtScale.domain()[1] - tile.drawnAtScale.domain()[0]) / (this._xScale.domain()[1] - this._xScale.domain()[0]);

      // let posOffset = newRange[0];

      const newRange = this._xScale.domain().map(tile.drawnAtScale);

      const posOffset = newRange[0];
      tile.graphics.scale.x = tileK;
      tile.graphics.position.x = -posOffset * tileK;
    }
  }

  zoomed(newXScale, newYScale, k, tx, ty) {
    super.zoomed(newXScale, newYScale);
  }

  /**
   * Adds information to recreate the track in SVG to the tile
   *
   * @param tile
   * @param x x value of bar
   * @param y y value of bar
   * @param width width of bar
   * @param height height of bar
   * @param color color of bar (not converted to hex)
   */
  addSVGInfo(tile, x, y, width, height, color) {
    if (tile.hasOwnProperty('svgData')) {
      tile.svgData.barXValues.push(x);
      tile.svgData.barYValues.push(y);
      tile.svgData.barWidths.push(width);
      tile.svgData.barHeights.push(height);
      tile.svgData.barColors.push(color);
    }
    else {
      tile.svgData  = {
        barXValues: [x],
        barYValues: [y],
        barWidths: [width],
        barHeights: [height],
        barColors: [color]
      };
    }
  }

  /**
   * Export an SVG representation of this track
   *
   * @returns {[DOMNode,DOMNode]} The two returned DOM nodes are both SVG
   * elements [base,track]. Base is a parent which contains track as a
   * child. Track is clipped with a clipping rectangle contained in base.
   *
   */
  exportSVG() {
    let track = null;
    let base = null;

    [base, track] = super.superSVG();

    base.setAttribute('class', 'exported-line-track');
    const output = document.createElement('g');

    track.appendChild(output);
    output.setAttribute('transform',
      `translate(${this.position[0]},${this.position[1]})`);

    const stroke = this.options.lineStrokeColor ? this.options.lineStrokeColor : 'blue';

    for (const tile of this.visibleAndFetchedTiles()) {
      const data = tile.svgData;
      if (!data || !data.barXValues)
        continue;

      for (let i = 0; i < data.barXValues.length; i++) {
        const rect = document.createElement('rect');
        rect.setAttribute('fill', data.barColors[i]);
        rect.setAttribute('stroke', data.barColors[i]);

        rect.setAttribute('x', data.barXValues[i]);
        rect.setAttribute('y', data.barYValues[i]);
        rect.setAttribute('height', data.barHeights[i]);
        rect.setAttribute('width', data.barWidths[i]);
        if (tile.barBorders) {
          rect.setAttribute('stroke-width', '0.1');
          rect.setAttribute('stroke', 'black');
        }

        output.appendChild(rect);
      }
    }

    const gAxis = document.createElement('g');
    gAxis.setAttribute('id', 'axis');

    // append the axis to base so that it's not clipped
    base.appendChild(gAxis);
    gAxis.setAttribute('transform',
      `translate(${this.axis.pAxis.position.x}, ${this.axis.pAxis.position.y})`);

    // add the axis to the export
    if (
      this.options.axisPositionHorizontal === 'left' ||
      this.options.axisPositionVertical === 'top'
    ) {
      // left axis are shown at the beginning of the plot
      const gDrawnAxis = this.axis.exportAxisLeftSVG(this.valueScale, this.dimensions[1]);
      gAxis.appendChild(gDrawnAxis);
    } else if (
      this.options.axisPositionHorizontal === 'right' ||
      this.options.axisPositionVertical === 'bottom'
    ) {
      const gDrawnAxis = this.axis.exportAxisRightSVG(this.valueScale, this.dimensions[1]);
      gAxis.appendChild(gDrawnAxis);
    }

    return [base, track];
  }
}

export default BarTrack;
<commit_msg>Reformat + cleanup<commit_after>import { scaleLinear } from 'd3-scale';

import HorizontalLine1DPixiTrack from './HorizontalLine1DPixiTrack';

// Utils
import { colorToHex } from './utils';

class BarTrack extends HorizontalLine1DPixiTrack {
  initTile(tile) {
    /**
         * Create whatever is needed to draw this tile.
         */
    super.initTile(tile);

    // this.drawTile(tile);
    this.renderTile(tile);
  }

  drawTile() {
    // empty function so that the superclass's drawTile
    // doesn't do anything
  }

  updateTile(tile) {
    if (
      !tile.valueScale
      || !this.scale
      || this.scale.minValue !== tile.scale.minValue
      || this.scale.maxValue !== tile.scale.maxValue
    ) {
      // not rendered using the current scale, so we need to rerender
      this.renderTile(tile);
    }
  }

  renderTile(tile) {
    if (!tile.graphics) { return; }

    const graphics = tile.graphics;

    const { tileX, tileWidth } = this.getTilePosAndDimensions(
      tile.tileData.zoomLevel,
      tile.tileData.tilePos,
      this.tilesetInfo.bins_per_dimension || this.tilesetInfo.tile_size
    );
    const tileValues = tile.tileData.dense;

    if (tileValues.length === 0) return;

    // equal to the smallest non-zero value
    const [vs, pseudocount] = this.makeValueScale(
      this.minVisibleValue(),
      this.medianVisibleValue,
      this.maxValue(),
      0
    );
    this.valueScale = vs;
    // console.log('pseudocount:', pseudocount, this.valueScale.domain());

    graphics.clear();

    this.drawAxis(this.valueScale);

    if (
      this.options.valueScaling === 'log'
      && this.valueScale.domain()[1] < 0
    ) {
      console.warn(
        'Negative values present when using a log scale',
        this.valueScale.domain()
      );
      return;
    }

    const stroke = colorToHex(
      this.options.lineStrokeColor ? this.options.lineStrokeColor : 'blue'
    );
    // this scale should go from an index in the data array to
    // a position in the genome coordinates
    const tileXScale = scaleLinear()
      .domain([
        0, this.tilesetInfo.tile_size || this.tilesetInfo.bins_per_dimension
      ])
      .range([tileX, tileX + tileWidth]);

    // let strokeWidth = this.options.lineStrokeWidth ? this.options.lineStrokeWidth : 1;

    const strokeWidth = 0;
    graphics.lineStyle(strokeWidth, stroke, 1);

    const color = this.options.barFillColor ? this.options.barFillColor : 'grey';
    const colorHex = colorToHex(color);

    const opacity = 'barOpacity' in this.options ? this.options.barOpacity : 1;

    graphics.beginFill(colorHex, opacity);

    tile.drawnAtScale = this._xScale.copy();

    for (let i = 0; i < tileValues.length; i++) {
      const xPos = this._xScale(tileXScale(i));
      const yPos = this.valueScale(tileValues[i] + pseudocount);

      const width = this._xScale(tileXScale(i + 1)) - xPos;
      const height = this.dimensions[1] - yPos;

      this.addSVGInfo(tile, xPos, yPos, width, height, color);

      // this data is in the last tile and extends beyond the length
      // of the coordinate system
      if (tileXScale(i) > this.tilesetInfo.max_pos[0]) break;

      graphics.drawRect(
        xPos,
        yPos,
        width,
        height
      );
    }
  }

  draw() {
    // we don't want to call HorizontalLine1DPixiTrack's draw function
    // but rather its parent's
    super.draw();

    Object.values(this.fetchedTiles).forEach((tile) => {
      // scaling between tiles
      const tileK = (
        (tile.drawnAtScale.domain()[1] - tile.drawnAtScale.domain()[0]) /
        (this._xScale.domain()[1] - this._xScale.domain()[0])
      );

      // let posOffset = newRange[0];

      const newRange = this._xScale.domain().map(tile.drawnAtScale);

      const posOffset = newRange[0];
      tile.graphics.scale.x = tileK;
      tile.graphics.position.x = -posOffset * tileK;
    });
  }

  zoomed(newXScale, newYScale) {
    super.zoomed(newXScale, newYScale);
  }

  /**
   * Adds information to recreate the track in SVG to the tile
   *
   * @param tile
   * @param x x value of bar
   * @param y y value of bar
   * @param width width of bar
   * @param height height of bar
   * @param color color of bar (not converted to hex)
   */
  addSVGInfo(tile, x, y, width, height, color) {
    if (tile['svgData']) {
      tile.svgData.barXValues.push(x);
      tile.svgData.barYValues.push(y);
      tile.svgData.barWidths.push(width);
      tile.svgData.barHeights.push(height);
      tile.svgData.barColors.push(color);
    } else {
      tile.svgData = {
        barXValues: [x],
        barYValues: [y],
        barWidths: [width],
        barHeights: [height],
        barColors: [color]
      };
    }
  }

  /**
   * Export an SVG representation of this track
   *
   * @returns {[DOMNode,DOMNode]} The two returned DOM nodes are both SVG
   * elements [base,track]. Base is a parent which contains track as a
   * child. Track is clipped with a clipping rectangle contained in base.
   *
   */
  exportSVG() {
    let track = null;
    let base = null;

    [base, track] = super.superSVG();

    base.setAttribute('class', 'exported-line-track');
    const output = document.createElement('g');

    track.appendChild(output);
    output.setAttribute('transform',
      `translate(${this.position[0]},${this.position[1]})`);

    this.visibleAndFetchedTiles()
      .filter(tile => tile.svgData && tile.svgData.barXValues)
      .forEach((tile) => {
        const data = tile.svgData;

        for (let i = 0; i < data.barXValues.length; i++) {
          const rect = document.createElement('rect');
          rect.setAttribute('fill', data.barColors[i]);
          rect.setAttribute('stroke', data.barColors[i]);

          rect.setAttribute('x', data.barXValues[i]);
          rect.setAttribute('y', data.barYValues[i]);
          rect.setAttribute('height', data.barHeights[i]);
          rect.setAttribute('width', data.barWidths[i]);
          if (tile.barBorders) {
            rect.setAttribute('stroke-width', '0.1');
            rect.setAttribute('stroke', 'black');
          }

          output.appendChild(rect);
        }
      });

    const gAxis = document.createElement('g');
    gAxis.setAttribute('id', 'axis');

    // append the axis to base so that it's not clipped
    base.appendChild(gAxis);
    gAxis.setAttribute(
      'transform',
      `translate(${this.axis.pAxis.position.x}, ${this.axis.pAxis.position.y})`
    );

    // add the axis to the export
    if (
      this.options.axisPositionHorizontal === 'left' ||
      this.options.axisPositionVertical === 'top'
    ) {
      // left axis are shown at the beginning of the plot
      const gDrawnAxis = this.axis.exportAxisLeftSVG(
        this.valueScale, this.dimensions[1]
      );
      gAxis.appendChild(gDrawnAxis);
    } else if (
      this.options.axisPositionHorizontal === 'right' ||
      this.options.axisPositionVertical === 'bottom'
    ) {
      const gDrawnAxis = this.axis.exportAxisRightSVG(
        this.valueScale, this.dimensions[1]
      );
      gAxis.appendChild(gDrawnAxis);
    }

    return [base, track];
  }
}

export default BarTrack;
<|endoftext|>


<commit_before>
'use strict';

var constants = require('../config/constants');

module.exports = function (req, res) {
	res.send(404);
};
<commit_msg>Removed unnecessary import.<commit_after>
'use strict';

module.exports = function (req, res) {
	res.send(404);
};
<|endoftext|>


<commit_before>window.onload = function() {
  var video = document.getElementById('video');
  var canvas = document.getElementById('canvas');
  var context = canvas.getContext('2d');
  var tracker = new tracking.ObjectTracker('face');
  tracker.setInitialScale(4);
  tracker.setStepSize(2);
  tracker.setEdgesDensity(0.1);
  tracking.track('#video', tracker, { camera: true });
  var imageObj = new Image();
  var rect;
  imageObj.src = "/images/sprites/santahat.png";
  tracker.on('track', trackHandle);

  var capture = document.getElementById('capture-btn');
  capture.addEventListener('click', function () {
    draw(video, context, canvas.width, canvas.height);
    context.drawImage(imageObj, rect.x, rect.y - rect.height + 20, rect.width, rect.height);
    tracker.removeListener('track', trackHandle);
  });

  function draw(v,c,w,h) {
    if(v.paused || v.ended ) return false;
    c.drawImage(v,0,0,w,h);
    //setTimeout(draw, 20, v,c,w,h);
  };

  function trackHandle(event) {
    //context.clearRect(0, 0, canvas.width, canvas.height);
    event.data.forEach(function(r) {
      rect = r;
      context.strokeStyle = '#a64ceb';
      context.strokeRect(rect.x, rect.y, rect.width, rect.height);
      context.font = '11px Helvetica';
      context.fillStyle = "#fff";
      context.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11);
      context.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22);
      context.drawImage(imageObj, rect.x, rect.y - rect.height + 20, rect.width, rect.height);
    });
  }
};<commit_msg>remove unused file<commit_after><|endoftext|>


<commit_before>import Ember from "ember";
import config from '../config/environment';
import AjaxPromise from '../utils/ajax-promise';

export default Ember.Service.extend({
  session: Ember.inject.service(),
  logger: Ember.inject.service(),
  store: Ember.inject.service(),
  messagesUtil: Ember.inject.service("messages"),

  appLoad: function () {
    if (!config.cordova.enabled) { return; }

    var pushNotification, _this = this;

    function onDeviceReady() {
      if (config.staging && typeof TestFairy != 'undefined') {
        TestFairy.begin('a362fd4ae199930a7a1a1b6daa6f729ac923b506');
      }

      var push = PushNotification.init({
        android: { senderID: config.cordova.GcmSenderId, badge: false },
        ios: {
          alert: true,
          sound: true
        },
        windows: {}
      });

      push.on('registration', function(data) {
        sendToken(data.registrationId, platformCode());
      });

      push.on('notification', function(data) {
        if(!data.additionalData.foreground) {
          if (device.platform === "iOS") {
            processTappedNotification(data.additionalData.payload)
          } else {
            processTappedNotification(data.additionalData);
          }

        }
      });
    }

    function sendToken(handle, platform) {
      return new AjaxPromise("/auth/register_device", "POST", _this.get("session.authToken"), {handle: handle, platform: platform});
    }

    function isAndroid(){
      return ["android", "Android", "amazon-fireos"].indexOf(device.platform) >= 0;
    }

    function platformCode(){
      var platform;
      if (isAndroid()) { platform = "gcm"; }
      else if (device.platform === "iOS") { platform = "aps"; }
      else if (device.platform === "windows") { platform = "wns"; }
      return platform;
    }

    function processTappedNotification(payload) {
      var notifications = _this.container.lookup("controller:notifications");
      if (payload.category === "incoming_call") {
        notifications.acceptCall(payload);
      }

      notifications.setRoute(payload);

      if(payload.category === "message") {
        var hasMessage = _this.get("store").peekRecord("message", payload.message_id);
        if(hasMessage) {
          notifications.transitionToRoute.apply(notifications, payload.route);
        } else {
          var loadingView = _this.container.lookup('component:loading').append();
          var messageUrl = payload.item_id ? `/messages?item_id=${payload.item_id}` : `/messages?offer_id=${payload.offer_id}`
          new AjaxPromise(messageUrl, "GET", _this.get("session.authToken"), {})
            .then(function(data) {
              _this.get("store").pushPayload(data);
              notifications.transitionToRoute.apply(notifications, payload.route);
            })
            .finally(() => loadingView.destroy());
        }
      } else {
        notifications.transitionToRoute.apply(notifications, payload.route);
      }
    }

    document.addEventListener('deviceready', onDeviceReady, true);
  }
});
<commit_msg>fixed undefined device error<commit_after>import Ember from "ember";
import config from '../config/environment';
import AjaxPromise from '../utils/ajax-promise';

export default Ember.Service.extend({
  session: Ember.inject.service(),
  logger: Ember.inject.service(),
  store: Ember.inject.service(),
  messagesUtil: Ember.inject.service("messages"),

  appLoad: function () {
    if (!config.cordova.enabled) { return; }

    var pushNotification, _this = this;

    function onDeviceReady() {
      if (config.staging && typeof TestFairy != 'undefined') {
        TestFairy.begin('a362fd4ae199930a7a1a1b6daa6f729ac923b506');
      }

      var push = PushNotification.init({
        android: { senderID: config.cordova.GcmSenderId, badge: false },
        ios: {
          alert: true,
          sound: true
        },
        windows: {}
      });

      push.on('registration', function(data) {
        sendToken(data.registrationId, platformCode());
      });

      push.on('notification', function(data) {
        if(!data.additionalData.foreground) {
          if (window.device.platform === "iOS") {
            processTappedNotification(data.additionalData.payload)
          } else {
            processTappedNotification(data.additionalData);
          }

        }
      });
    }

    function sendToken(handle, platform) {
      return new AjaxPromise("/auth/register_device", "POST", _this.get("session.authToken"), {handle: handle, platform: platform});
    }

    function isAndroid(){
      return ["android", "Android", "amazon-fireos"].indexOf(window.device.platform) >= 0;
    }

    function platformCode(){
      var platform;
      if (isAndroid()) { platform = "gcm"; }
      else if (window.device.platform === "iOS") { platform = "aps"; }
      else if (window.device.platform === "windows") { platform = "wns"; }
      return platform;
    }

    function processTappedNotification(payload) {
      var notifications = _this.container.lookup("controller:notifications");
      if (payload.category === "incoming_call") {
        notifications.acceptCall(payload);
      }

      notifications.setRoute(payload);

      if(payload.category === "message") {
        var hasMessage = _this.get("store").peekRecord("message", payload.message_id);
        if(hasMessage) {
          notifications.transitionToRoute.apply(notifications, payload.route);
        } else {
          var loadingView = _this.container.lookup('component:loading').append();
          var messageUrl = payload.item_id ? `/messages?item_id=${payload.item_id}` : `/messages?offer_id=${payload.offer_id}`
          new AjaxPromise(messageUrl, "GET", _this.get("session.authToken"), {})
            .then(function(data) {
              _this.get("store").pushPayload(data);
              notifications.transitionToRoute.apply(notifications, payload.route);
            })
            .finally(() => loadingView.destroy());
        }
      } else {
        notifications.transitionToRoute.apply(notifications, payload.route);
      }
    }

    document.addEventListener('deviceready', onDeviceReady, true);
  }
});
<|endoftext|>


<commit_before>//routes.js

var exports = module.exports = {};

var _  = require('lodash'),
fuzzy  = require('fuzzy'),
os     = require('os'),

moment = require('moment'),
parse  = require('app/shiftswap/parse'),

sms    = require('app/shiftswap/sms'),
db     = require('app/shiftswap/db'),

serverConfig = require('app/_config/server.json')
;

exports.home = {
    welcome: (req, res)=>{
        res.send("\"Welcome. You have connected to the Shiftswap API.\"");
        //res.send(JSON.stringify(parse.date.unixToday()));
    },
    time: (req, res)=>{
        var m = moment.utc();
        res.send({
            human:   m.format('dddd, MMMM Do YYYY, h:mm:ss a'),
            unix:    m.valueOf(),
            iso8601: m.toISOString(),
        });
    },
    echo: (req, res)=>{
        res.send(req.params.str);
    },
    whoami: (req, res)=>{
        res.send({
            ip:     req.connection.remoteAddress || req.ip,
            host:   req.headers['user-agent'],
            cookie: req.headers['cookie'],
            dnt:    req.headers['dnt'],
        });
    },
};
exports.user = {
    post: (req, res)=>{
        var post = req.body;
        console.log("POST user");

        //Validate
        post.access = post.access || "f";

        //Parsing
        post.access = minifyAccess(post.access, post.spectator);

        if(post.spectator)
            post.access.push("s");

        function createUserDB(err, uid){
            new model.User({
                name:   post.full   || "",
                nick:   post.nick   || "",
                access: post.access || ["f"],
                period: post.period || [Date.now()],
            }).save(callback);
        }
        function callback(err, obj){
            res.send({stat:201,res:"Created"});
            logHistory("Normal|Created user "+obj.name, obj, null);
        }
    },
    del: (req, res)=>{
        var uid = JSON.parse(req.params.uid);
        console.log('DELETE user '+uid);
        logHistory("Very High|Deleted user "+uid, null, {_id: uid}, callback);

        function callback(){
            model.User.remove({_id: uid}, () => res.send({state:200, res:'Ok'}) );
        }
    },
    all: (req, res)=>{
        console.log('GET users');
        db.users.getAll(callback);

        function callback(err, list){
            list = parse.json.cleanArray(list);
            res.send(list);
        }
    },
    patch: (req, res)=>{
        var uid;
        try{
            uid = JSON.parse(req.params.uid) || req.params.uid;
        }
        catch(e){
            uid = req.params.uid;
        }

        var patch = req.body;
        console.log('PATCH user '+uid);

        patch.access = minifyAccess(patch.access);

        model.User.findOneAndUpdate({_id: uid}, patch, {upsert: false}, function(err, doc){
            if(err){
                res.send({state:500, res:'Internal error: '+err});
                return console.error(err);
            }

            res.send({state:200, res:'Ok'});
            logHistory("Normal|Editted user "+doc.name, patch, doc);
        });
    },

    userid: (req, res)=>{

        var userid = JSON.parse(req.params.uid);
        if(!users.some( obj => {
                if(obj.userid === userid){
                    res.send('
'+JSON.stringify(obj)+'
');
                    return true;
                }
        })){
            res.send('
No userid matches '+userid+'
');
        }
    },
};
exports.stats = {
    get: (req, res)=>{
        var a = parse.military.pad(14, 30);
        console.log(a);
        res.send(a);
    },
    put: (req, res)=>{

    },
    delete: (req, res)=>{

    },
};
exports.schedule = {
    post: (req, res)=>{
        console.log('POST schedule');
        var post = req.body || {};

        if(Array.isArray(post.body)){
            return db.schedule.insert(post.body, callbackSave);
        };

        if(!post.time || !post.uid || !post.date || !post.access)
            return res.status(400).send('Body must include uid, date, access, and time.');
        if(!Array.isArray(post.time))
            return res.status(400).send('time must be an array');
        if(typeof post.uid != 'number')
            return res.status(400).send('uid must be a number');
        if(post.detail && typeof post.uid != 'string')
            return res.status(400).send('detail must be a string');
        if(post.access != 'm' && post.access != 'f')
            return res.status(400).send('access must be a string either m or f, for manager and floor');

        db.schedule.insert({
            uid:    post.uid,
            time:   post.time,
            detail: post.type,
            date:   post.date,
            access: getAccess(post.type),
        }, callbackSave);

        function getAccess(type){
            type = typeof type==='string'? type : '';
            if(type.includes('manager')) return 'm';
            return 'f';
        }

        function callbackSave(err, doc){
            if(err){
                console.error(err);
                return res.send(err);
            }

            res.send(JSON.stringify('saved'));
        };
    },
    userid: (req, res)=>{

    },
    get: (req, res)=>{
        var day = req.params.day;
        var uid = req.params.uid;
        var access = req.params.access;

        if(day === undefined || day === ''){
            //No day selected, send full list.
            console.log('day empty');
            find = {};
        }
        else{
            //Day found, send partial.
            if(day){
                console.log('GET schedule',day.human, day.unix);
                find = {'date.unix': day.unix};
            }else{
                console.log('GET schedule default');
            }

        }

        var find = {};
        if(!day)
            day = parse.date.unixToday();
        if(uid)
            find.uid = uid;
        if(access)
            find.access = access[0];

        db.schedule.find(day, -7, find, function(err, docs){
            var list = [];

            if(err)
                return console.error(err);

            docs.forEach((d)=>{
                d=parse.json.clean(d); //clean
                list.push(d); //copy
            });

            res.send(list); //send
        });

    },
    delete: (req, res)=>{

    },
};
exports.logged = {
    never: (req, res)=>{

    },
    last: (req, res)=>{

    },
};
exports.trade = {
    all: (req, res)=>{
        model.Trade.find({}, (err, docs)=>{
            if(err)
                return console.error(err);

            sortByStatus(docs);
        });

        function sortByStatus(docs){
            docs = docs || [];
            var statusList = {
                pending:  [],
                complete: [],
                fail:     [],
            };
            for(var i = 0, len = docs.length; i < len; i++){
                var obj = docs[i];
                switch(obj.status){
                    case 0: statusList.pending.push(obj);  break;
                    case 1: statusList.complete.push(obj); break;
                    case 2: statusList.fail.push(obj);     break;
                }
            }
            res.send(statusList);
        }
    },
    post: (req, res)=>{
        var post = req.body || {sid: -1, uid: -1};

        if(!post.sid) return console.error('scheduleId is required');
        if(!post.uid) return console.error('userId is required');

        new model.Trade({
            sid: post.sid,
            uid: post.uid,
            term: post.term,
            status: 0,
        }).save(callback);

        function callback(err, doc){
            if(err){
                res.send({state: 500, res: err});
                return console.error(err);
            }

            res.send({state: 200, res: 'Ok', doc: doc});
        }
    },
    take: (req, res)=>{
        var tid = parse.json.loose(req.params.tid);
    },
    admin: (req, res)=>{
        var tid = parse.json.loose(req.params.tid);
    },
};
exports.history = {
    all: (req, res)=>{
        console.log('GET history');
        model.History.find({}, (err, docs)=>{
            if(err)
                return console.error(err);

            res.send(docs);
        });

    },
    comment: (req, res)=>{

    },
    self: (req, res)=>{

    },
    userid: (req, res)=>{

    },
};
exports.reward = {
    all: (req, res)=>{

    },
    take: (req, res)=>{

    },
    edit: (req, res)=>{

    },
};
exports.sms = {
    poll: (req, res)=>{
        console.log('POST sms');

        var number = req.body.From;
        var body   = req.body.Body;

        if(!number){
            var msg = 'SMS rejected because no phone number given.';
            res.status(400).send(msg);
            return console.error(msg);
        }

        var sent = sms.parseIncoming(req, res, db, parse, {
            number: number,
            body: body,
        });
        console.log(`Num: ${number}, Recv: ${body}, Send: ${sent}`);

        res.sendStatus(200);
    },
    send: (req, res)=>{
        console.log('GET sms');
        var body   = req.params.msg;
        //var body   = JSON.parse(req.params.msg);
        var number = JSON.parse(req.params.number);
        sms.send(number, body, function(err, smsRes){
            if(err)
                return console.error('Sms failure', err);
            console.log('sms successful.');
        });
    },
}
exports.voice = {

}

function getUserFromName(name, callback){
    name = (typeof name==='string')? name : '';

    name = name.toLowerCase();
    var names = [];

    getUsers(f1);
    function f1(list){
        names = list;
        var results = fuzzy.filter(name, names, {extract: e=>e.name});

        if(results[0] && results[0].original)
            results = results[0].original;

        if(callback)
            callback(results);
    }
}
function getUsers(callback){
    var list = [];
    model.User.find(function(err, users){
        if(err)
            return console.error(err);

        users.forEach((user)=>list.push(user));
        callback(list);
    });
}

function minifyAccess(str1, str2, str3){
    str = str1 + str2 + str3;
    var types = ["floor","manager","gm","admin","spec"];
    var out = [];
    //Must contain one of these types
    types.forEach(function(ty){
        if(str.toLowerCase().includes(ty)){
            var small = ty[0];
            out.push(small);
        }
    });
    return out;
}
function createID(type, callback){
    console.log('create ID type ',type);
    var t = this;
    var id, found, update;
    type = type.toLowerCase();
    callback = callback || function(){};

    if(!['u','s','h'].some(o=>type===o))
         return console.error('In createID type '+type+' does not match an ID type.  Types are u,s,h.');

    model.Site.find({}, function(err, f){

        if(err)
            return console.error(err);

        //is empty, make new IDs
        if(f.length === 0){
            new model.Site({
                uidCount: 1,
                hidCount: 1,
                sidCount: 1,
            }).save();
            callback(null, 0);

        //is not empty, return ID and increment it.
        }else{
            f = f[0];

            id = ++f[type+'idCount'];
            update = {[type+'idCount']: f[type+'idCount']};

            callback(null, id);
        }

    }).then(doc=>{
        model.Site.findOneAndUpdate(doc, update, {upsert: false}, function(err, doc){
            if(err)
                return console.error('Couldn\'t update site IDs ', err);
        });
    });
}

function logHistory(typedescr, change, undo, callback){

    //Split description and weight
    typedescr  = typedescr.split("|");
    var weight = typedescr.shift();
    var descr  = typedescr.join("|");
    console.log(typedescr);

    //Convert undo id's to actual data
    if(_.find(Object.keys(undo || {}), p => p === '_id')){ //undo is a user id, find the user.
        model.User.findOne(undo, function(err, found){
            if(err)
                return console.error(err);
            createDoc(found);
        });
    }
    else{
        createDoc();
    }

    //Save the history change
    function createDoc(altUndo){
        new model.History({
            //hid:    getID.h();
            //uid:      Schema.Types.ObjectId,
            time:     Date.now(),
            weight: weight,
            descr: descr,
            comment: "",
            change: change,  //the data after the change
            undo: altUndo || undo,
        }).save(callback);
    }

    //Converts MM-DD-YYYY and MM-DD to Unix timestamps
    function HumanToUNIX(human){
        human = string(human);
        if(human.length <= 4){ //MM-DD format
            human = human+String(new Date().getFullYear()); //append year
        }

        if(human.length <= 8){ //MM-DD-YYYY format
            human = String(Date.parse(human)); //convert to UNIX timestamp
        }

        return human;
    }
}
<commit_msg>moving logic to db.js<commit_after>//routes.js

var exports = module.exports = {};

var _  = require('lodash'),
fuzzy  = require('fuzzy'),
os     = require('os'),

moment = require('moment'),
parse  = require('app/shiftswap/parse'),

sms    = require('app/shiftswap/sms'),
db     = require('app/shiftswap/db'),

serverConfig = require('app/_config/server.json')
;

exports.home = {
    welcome: (req, res)=>{
        res.send("\"Welcome. You have connected to the Shiftswap API.\"");
        //res.send(JSON.stringify(parse.date.unixToday()));
    },
    time: (req, res)=>{
        var m = moment.utc();
        res.send({
            human:   m.format('dddd, MMMM Do YYYY, h:mm:ss a'),
            unix:    m.valueOf(),
            iso8601: m.toISOString(),
        });
    },
    echo: (req, res)=>{
        res.send(req.params.str);
    },
    whoami: (req, res)=>{
        res.send({
            ip:     req.connection.remoteAddress || req.ip,
            host:   req.headers['user-agent'],
            cookie: req.headers['cookie'],
            dnt:    req.headers['dnt'],
        });
    },
};
exports.user = {
    post: (req, res)=>{
        var post = req.body;
        console.log("POST user");

        //Validate
        post.access = post.access || "f";

        //Parsing
        post.access = minifyAccess(post.access, post.spectator);

        if(post.spectator)
            post.access.push("s");

        function createUserDB(err, uid){
            new model.User({
                name:   post.full   || "",
                nick:   post.nick   || "",
                access: post.access || ["f"],
                period: post.period || [Date.now()],
            }).save(callback);
        }
        function callback(err, obj){
            res.send({stat:201,res:"Created"});
            logHistory("Normal|Created user "+obj.name, obj, null);
        }
    },
    del: (req, res)=>{
        var uid = JSON.parse(req.params.uid);
        console.log('DELETE user '+uid);
        logHistory("Very High|Deleted user "+uid, null, {_id: uid}, callback);

        function callback(){
            model.User.remove({_id: uid}, () => res.send({state:200, res:'Ok'}) );
        }
    },
    all: (req, res)=>{
        console.log('GET users');
        db.users.getAll(callback);

        function callback(err, list){
            list = parse.json.cleanArray(list);
            res.send(list);
        }
    },
    patch: (req, res)=>{
        var uid;
        try{
            uid = JSON.parse(req.params.uid) || req.params.uid;
        }
        catch(e){
            uid = req.params.uid;
        }

        var patch = req.body;
        console.log('PATCH user '+uid);

        patch.access = minifyAccess(patch.access);

        model.User.findOneAndUpdate({_id: uid}, patch, {upsert: false}, function(err, doc){
            if(err){
                res.send({state:500, res:'Internal error: '+err});
                return console.error(err);
            }

            res.send({state:200, res:'Ok'});
            logHistory("Normal|Editted user "+doc.name, patch, doc);
        });
    },

    userid: (req, res)=>{

        var userid = JSON.parse(req.params.uid);
        if(!users.some( obj => {
                if(obj.userid === userid){
                    res.send('
'+JSON.stringify(obj)+'
');
                    return true;
                }
        })){
            res.send('
No userid matches '+userid+'
');
        }
    },
};
exports.stats = {
    get: (req, res)=>{
        var a = parse.military.pad(14, 30);
        console.log(a);
        res.send(a);
    },
    put: (req, res)=>{

    },
    delete: (req, res)=>{

    },
};
exports.schedule = {
    post: (req, res)=>{
        console.log('POST schedule');
        var post = req.body || {};

        if(post.jquery){
            post = post.jquery;
        }

        db.schedule.insert(post, (err, doc)=>{
            if(err){
                console.error(err);
                return res.send(JSON.stringify(err));
            }

            res.send(JSON.stringify('saved'));
        });
    },
    userid: (req, res)=>{

    },
    get: (req, res)=>{
        var day = req.params.day;
        var uid = req.params.uid;
        var access = req.params.access;

        var find;

        if(!day){
            //No day selected, send full list.
            console.log('day empty');
            find = {};
        }
        else{
            //Day found, send partial.
            console.log('GET schedule',day.human, day.unix);
            find = {'date.unix': day.unix};
        }

        if(!day)
            day = parse.date.unixToday();
        if(uid)
            find.uid = uid;
        if(access)
            find.access = access[0];

        db.schedule.find(day, -7, find, function(err, docs){
            var list = [];

            if(err)
                return console.error(err);

            docs.forEach((d)=>{
                d=parse.json.clean(d); //clean
                list.push(d); //copy
            });

            res.send(list); //send
        });

    },
    delete: (req, res)=>{

    },
};
exports.logged = {
    never: (req, res)=>{

    },
    last: (req, res)=>{

    },
};
exports.trade = {
    all: (req, res)=>{
        model.Trade.find({}, (err, docs)=>{
            if(err)
                return console.error(err);

            sortByStatus(docs);
        });

        function sortByStatus(docs){
            docs = docs || [];
            var statusList = {
                pending:  [],
                complete: [],
                fail:     [],
            };
            for(var i = 0, len = docs.length; i < len; i++){
                var obj = docs[i];
                switch(obj.status){
                    case 0: statusList.pending.push(obj);  break;
                    case 1: statusList.complete.push(obj); break;
                    case 2: statusList.fail.push(obj);     break;
                }
            }
            res.send(statusList);
        }
    },
    post: (req, res)=>{
        var post = req.body || {sid: -1, uid: -1};

        if(!post.sid) return console.error('scheduleId is required');
        if(!post.uid) return console.error('userId is required');

        new model.Trade({
            sid: post.sid,
            uid: post.uid,
            term: post.term,
            status: 0,
        }).save(callback);

        function callback(err, doc){
            if(err){
                res.send({state: 500, res: err});
                return console.error(err);
            }

            res.send({state: 200, res: 'Ok', doc: doc});
        }
    },
    take: (req, res)=>{
        var tid = parse.json.loose(req.params.tid);
    },
    admin: (req, res)=>{
        var tid = parse.json.loose(req.params.tid);
    },
};
exports.history = {
    all: (req, res)=>{
        console.log('GET history');
        model.History.find({}, (err, docs)=>{
            if(err)
                return console.error(err);

            res.send(docs);
        });

    },
    comment: (req, res)=>{

    },
    self: (req, res)=>{

    },
    userid: (req, res)=>{

    },
};
exports.reward = {
    all: (req, res)=>{

    },
    take: (req, res)=>{

    },
    edit: (req, res)=>{

    },
};
exports.sms = {
    poll: (req, res)=>{
        console.log('POST sms');

        var number = req.body.From;
        var body   = req.body.Body;

        if(!number){
            var msg = 'SMS rejected because no phone number given.';
            res.status(400).send(msg);
            return console.error(msg);
        }

        var sent = sms.parseIncoming(req, res, db, parse, {
            number: number,
            body: body,
        });
        console.log(`Num: ${number}, Recv: ${body}, Send: ${sent}`);

        res.sendStatus(200);
    },
    send: (req, res)=>{
        console.log('GET sms');
        var body   = req.params.msg;
        //var body   = JSON.parse(req.params.msg);
        var number = JSON.parse(req.params.number);
        sms.send(number, body, function(err, smsRes){
            if(err)
                return console.error('Sms failure', err);
            console.log('sms successful.');
        });
    },
}
exports.voice = {

}

function getUserFromName(name, callback){
    name = (typeof name==='string')? name : '';

    name = name.toLowerCase();
    var names = [];

    getUsers(f1);
    function f1(list){
        names = list;
        var results = fuzzy.filter(name, names, {extract: e=>e.name});

        if(results[0] && results[0].original)
            results = results[0].original;

        if(callback)
            callback(results);
    }
}
function getUsers(callback){
    var list = [];
    model.User.find(function(err, users){
        if(err)
            return console.error(err);

        users.forEach((user)=>list.push(user));
        callback(list);
    });
}

function minifyAccess(str1, str2, str3){
    str = str1 + str2 + str3;
    var types = ["floor","manager","gm","admin","spec"];
    var out = [];
    //Must contain one of these types
    types.forEach(function(ty){
        if(str.toLowerCase().includes(ty)){
            var small = ty[0];
            out.push(small);
        }
    });
    return out;
}
function createID(type, callback){
    console.log('create ID type ',type);
    var t = this;
    var id, found, update;
    type = type.toLowerCase();
    callback = callback || function(){};

    if(!['u','s','h'].some(o=>type===o))
         return console.error('In createID type '+type+' does not match an ID type.  Types are u,s,h.');

    model.Site.find({}, function(err, f){

        if(err)
            return console.error(err);

        //is empty, make new IDs
        if(f.length === 0){
            new model.Site({
                uidCount: 1,
                hidCount: 1,
                sidCount: 1,
            }).save();
            callback(null, 0);

        //is not empty, return ID and increment it.
        }else{
            f = f[0];

            id = ++f[type+'idCount'];
            update = {[type+'idCount']: f[type+'idCount']};

            callback(null, id);
        }

    }).then(doc=>{
        model.Site.findOneAndUpdate(doc, update, {upsert: false}, function(err, doc){
            if(err)
                return console.error('Couldn\'t update site IDs ', err);
        });
    });
}

function logHistory(typedescr, change, undo, callback){

    //Split description and weight
    typedescr  = typedescr.split("|");
    var weight = typedescr.shift();
    var descr  = typedescr.join("|");
    console.log(typedescr);

    //Convert undo id's to actual data
    if(_.find(Object.keys(undo || {}), p => p === '_id')){ //undo is a user id, find the user.
        model.User.findOne(undo, function(err, found){
            if(err)
                return console.error(err);
            createDoc(found);
        });
    }
    else{
        createDoc();
    }

    //Save the history change
    function createDoc(altUndo){
        new model.History({
            //hid:    getID.h();
            //uid:      Schema.Types.ObjectId,
            time:     Date.now(),
            weight: weight,
            descr: descr,
            comment: "",
            change: change,  //the data after the change
            undo: altUndo || undo,
        }).save(callback);
    }

    //Converts MM-DD-YYYY and MM-DD to Unix timestamps
    function HumanToUNIX(human){
        human = string(human);
        if(human.length <= 4){ //MM-DD format
            human = human+String(new Date().getFullYear()); //append year
        }

        if(human.length <= 8){ //MM-DD-YYYY format
            human = String(Date.parse(human)); //convert to UNIX timestamp
        }

        return human;
    }
}
<|endoftext|>


<commit_before>define([
  'adminApp',
  'marked',
  'highlightjs'
], function (adminApp, marked, hljs) {

  adminApp.directive('markd', function () {
    return {
      restrict: 'E',
      replace: true,
      scope: {
        markurl: '@',
        markData: '@'
      },
      template: '

',
      controller: ['$scope', '$sce', '$http', function ($scope, $sce, $http) {
        marked.setOptions({
          highlight: function (code) {
            return hljs.highlightAuto(code).value;
          }
        });
        if ($scope.markData != undefined) {
          $scope.markdownHtml = $sce.trustAsHtml(marked($scope.markData));
          $scope.$watch(function () {
            return $scope.markData;
          }, function () {
            $scope.markdownHtml = $sce.trustAsHtml(marked($scope.markData));
          });
        }

        if($scope.markData == undefined || $scope.markurl != undefined){
          $http.get($scope.markurl)
            .success(function(data) {
              $scope.markdownHtml = $sce.trustAsHtml(marked(data));
            });
        }
      }]
    };
  });
});
<commit_msg>remove highlight<commit_after>define([
  'adminApp',
  'marked'
  // 'highlightjs'
], function (adminApp, marked) {

  adminApp.directive('markd', function () {
    return {
      restrict: 'E',
      replace: true,
      scope: {
        markurl: '@',
        markData: '@'
      },
      template: '

',
      controller: ['$scope', '$sce', '$http', function ($scope, $sce, $http) {
        // marked.setOptions({
        //   highlight: function (code) {
        //     return hljs.highlightAuto(code).value;
        //   }
        // });
        if ($scope.markData != undefined) {
          $scope.markdownHtml = $sce.trustAsHtml(marked($scope.markData));
          $scope.$watch(function () {
            return $scope.markData;
          }, function () {
            $scope.markdownHtml = $sce.trustAsHtml(marked($scope.markData));
          });
        }

        if($scope.markData == undefined || $scope.markurl != undefined){
          $http.get($scope.markurl)
            .success(function(data) {
              $scope.markdownHtml = $sce.trustAsHtml(marked(data));
            });
        }
      }]
    };
  });
});
<|endoftext|>


<commit_before>var nodeca = require('nodeca-lib'),
    Store = nodeca.Settings.Store,
    _ = nodeca.Underscore;

var Promise = require('simple-promise');

module.exports = (function (app, callback) {
  var UserGroupStore = function UserGroupStore() {
    Store.call(this);

    var STORE_KEY = '__usergroup_store__',
        UserGroup = app.model('UserGroup');

    this.__.preloader = function (env, callback) {
      // environment was preloaded before
      if (env[STORE_KEY]) {
        callback();
        return;
      }

      // env.groups was neither specified directly nor found in user
      if (!Array.isArray(env.groups) || 0 == env.groups.length) {
        callback(Error("Can't find list of groups"));
        return;
      }

      UserGroup.find({_id: {$in: env.groups}}, function (err, groups) {
        env[STORE_KEY] = groups;
        callback(err);
      });
    };

    this.__.setter = function (data, env, callback) {
      var settings = {};

      // Getter works with multiple groups.
      // Setter NEVER work with moe than one for integrity reasons.
      if (1 != env.groups.length) {
        callback(Error("Can't set on multiple groups"));
        return;
      }

      _.each(data, function (val, key) {
        settings['settings.' + key] = val;
      });

      UserGroup.update({_id: env.groups[0]}, settings, callback);
    };

    this.__.getter = function (keys, env, callback) {
      var result = {};

      keys.forEach(function (key) {
        var chains;

        if (1 == env[STORE_KEY].length) {
          result[key] = env[STORE_KEY].settings[key];
          return;
        }

        // TODO: rework to support non-boolean vals as well

        // separate strict and non-strict values
        chains = {OR: [], AND: []};
        env[STORE_KEY].forEach(function (g) {
          var op = g.settings[key].strict ? 'AND' : 'OR';
          chains[op].push(!!g.settings[key].value);
        });

        result[key] = {strict: false, value: false};

        if (0 < chains.AND.length) {
          result[key].strict = true;
        }

        if (0 == chains.OR.length) {
          result[key].value = !_.include(chains.AND, false));
        } else {
          result[key].value = _.include(chains.OR, true) && !_.includes(chains.AND, false);
        }
      });

      callback(null, result);
    };
  };

  Store.adopts(UserGroupStore);

  callback(null, new UserGroupStore());
});

////////////////////////////////////////////////////////////////////////////////
// vim:ts=2:sw=2
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Get `strict` flag from UserGroup<commit_after>var nodeca = require('nodeca-lib'),
    Store = nodeca.Settings.Store,
    _ = nodeca.Underscore;

var Promise = require('simple-promise');

module.exports = (function (app, callback) {
  var UserGroupStore = function UserGroupStore() {
    Store.call(this);

    var STORE_KEY = '__usergroup_store__',
        UserGroup = app.model('UserGroup');

    this.__.preloader = function (env, callback) {
      // environment was preloaded before
      if (env[STORE_KEY]) {
        callback();
        return;
      }

      // env.groups was neither specified directly nor found in user
      if (!Array.isArray(env.groups) || 0 == env.groups.length) {
        callback(Error("Can't find list of groups"));
        return;
      }

      UserGroup.find({_id: {$in: env.groups}}, function (err, groups) {
        env[STORE_KEY] = groups;
        callback(err);
      });
    };

    this.__.setter = function (data, env, callback) {
      var settings = {};

      // Getter works with multiple groups.
      // Setter NEVER work with moe than one for integrity reasons.
      if (1 != env.groups.length) {
        callback(Error("Can't set on multiple groups"));
        return;
      }

      _.each(data, function (val, key) {
        // remove strict flag as we keep it in usergroup
        if ('object' === typeof val) {
          delete val.strict;
        }
        settings['settings.' + key] = val;
      });

      UserGroup.update({_id: env.groups[0]}, settings, callback);
    };

    this.__.getter = function (keys, env, callback) {
      var result = {};

      keys.forEach(function (key) {
        var chains;

        if (1 == env[STORE_KEY].length) {
          result[key] = env[STORE_KEY].settings[key];
          result[key].strict = env[STORE_KEY][0].restrictive;
          return;
        }

        // TODO: rework to support non-boolean vals as well

        // separate strict and non-strict values
        chains = {OR: [], AND: []};
        env[STORE_KEY].forEach(function (g) {
          var op = g.restrictive ? 'AND' : 'OR';
          chains[op].push(!!g.settings[key].value);
        });

        result[key] = {strict: false, value: false};

        if (0 < chains.AND.length) {
          result[key].strict = true;
        }

        if (0 == chains.OR.length) {
          result[key].value = !_.include(chains.AND, false);
        } else {
          result[key].value = _.include(chains.OR, true) && !_.includes(chains.AND, false);
        }
      });

      callback(null, result);
    };
  };

  Store.adopts(UserGroupStore);

  callback(null, new UserGroupStore());
});

////////////////////////////////////////////////////////////////////////////////
// vim:ts=2:sw=2
////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>var util = require('util');

exports.init = function (y, config, messages, cron, logger) {
	messages.add('spaghetti_opening', "Spaghetti for lunch? Superzise? Like this message if you'd like to join.");
	messages.add('spaghetti_opening', "Spaghetti for lunch? Like this message if you'd like to join.");

	messages.add('spaghetti_closing', "Mamma mia ramba zamba! [count] hungry monkeys?? \nThe following are registered for lunch: [joiners]");
	messages.add('spaghetti_closing', "Ooooohh! [count] hungry monkeys?? \nThe following are registered for lunch: [joiners]");

	messages.add('spaghetti_notenough', "Ooh, [count] is not enough. A minimum of 5 joiners is required to justify the effort of making spaghetti. There will be no spaghetti today. Sorry");
	messages.add('spaghetti_noone', "Noone?? Alright then... ;(");

	messages.add('spaghetti_chef', "[chef_name], [count] mouths to feed! Hurry!!");

	messages.add('spaghetti_threadclosed', "Sorry, you're to late.");

	var yammer_account = config.yammer[config.yammer_account];

	new cron.CronJob(config.spaghetti.cron_open, function () {
		var openingMessage = messages.get('spaghetti_opening');

		y.sendMessage(function (error, msg) {
			logger.info('spaghetti opening message OK: ' + msg.id());
			var thread = y.thread(msg.threadId());
			thread.setProperty('type', 'spaghetti');
			thread.setProperty('status', 'open');
			thread.setProperty('joiners', []);
			y.persistThread(thread);
		}, openingMessage);
	});

	new cron.CronJob(config.spaghetti.cron_close, function () {
		for (var threadId in y.threads()) {
			(function (thId) {
				var th = y.thread(thId);

				if (th.property('status') == 'open' && th.property('type') == 'spaghetti') {
					th.setProperty('status', 'closed');
					y.persistThread(th);

					y.updateThreadMessages(th, function (th) {
						var message = y.message(th.messageId());
						var joinersCount = message.likes();
						var joinerNames = message.likers();
						var joiners = [];
						var joinerIds = [];
						var joinersList = '';

						for (var i = 0; i < joinerNames.length; i++) {
							joiners.push(y.userByName(joinerNames[i]));
						}

						for (var i in joiners) {
							var user = joiners[i];
							joinerIds.push(user.id());

							if (i > 0) {
								joinersList += ', ';
							}

							joinersList += user.username();
						}

						if (joinerIds.length == 0) {
							var nooneMessage = messages.get('spaghetti_noone');
							y.sendMessage(function (error, message) {
								logger.info('spaghetti noone message OK: ' + message.id());

								th.setProperty('joiners', joinerIds);
								th.setProperty('status', 'closed');
								th.setProperty('charged', true);
								y.persistThread(th);
							}, nooneMessage, { 'reply_to' : th.messageId() });

						} else if (joinerIds.length < 5) {
							var notenoughMessage = messages.get('spaghetti_notenough', {
								'count' : joiners.length
							});
							y.sendMessage(function (error, message) {
								logger.info('spaghetti notenough message OK: ' + message.id());

								th.setProperty('joiners', joinerIds);
								th.setProperty('status', 'closed');
								th.setProperty('charged', true);
								y.persistThread(th);
							}, notenoughMessage, { 'reply_to' : th.messageId() });

						} else {

							var closingMessage = messages.get('spaghetti_closing', {
								'count' : joiners.length,
								'joiners' : joinersList
							});

							y.sendMessage(function (error, message) {
								logger.info('spaghetti closing message OK: ' + message.id());

								th.setProperty('joiners', joinerIds);
								th.setProperty('status', 'closed');
								y.persistThread(th);
							}, closingMessage, { 'reply_to' : th.messageId() });

						}

					});
				}

			})(threadId);
		}
	});
};
<commit_msg>Messages<commit_after>var util = require('util');

exports.init = function (y, config, messages, cron, logger) {
	messages.add('spaghetti_opening', "Spaghetti for lunch? Superzise? Like this message if you'd like to join.");
	messages.add('spaghetti_opening', "Spaghetti for lunch? Like this message if you'd like to join.");
	messages.add('spaghetti_opening', "Who's a hungry monkey? Press the 'like' button to register for spaghetti.");

	messages.add('spaghetti_closing', "Mamma mia ramba zamba! [count] hungry monkeys?? \nThe following are registered for lunch: [joiners]");
	messages.add('spaghetti_closing', "Ooooohh! [count] hungry monkeys?? \nThe following are registered for lunch: [joiners]");
	messages.add('spaghetti_closing', "Wow, so many! Hasn't happened in a long time! [count] plates of worms for the birds. \n[joiners] are in for lunch.");

	messages.add('spaghetti_notenough', "Ooh, [count] is not enough. A minimum of 5 joiners is required to justify the effort of making spaghetti. There will be no spaghetti today. Sorry");
	messages.add('spaghetti_noone', "Noone?? Alright then... ;(");

	messages.add('spaghetti_chef', "[chef_name], [count] mouths to feed! Hurry!!");

	messages.add('spaghetti_threadclosed', "Sorry, you're to late.");

	var yammer_account = config.yammer[config.yammer_account];

	new cron.CronJob(config.spaghetti.cron_open, function () {
		var openingMessage = messages.get('spaghetti_opening');

		y.sendMessage(function (error, msg) {
			logger.info('spaghetti opening message OK: ' + msg.id());
			var thread = y.thread(msg.threadId());
			thread.setProperty('type', 'spaghetti');
			thread.setProperty('status', 'open');
			thread.setProperty('joiners', []);
			y.persistThread(thread);
		}, openingMessage);
	});

	new cron.CronJob(config.spaghetti.cron_close, function () {
		for (var threadId in y.threads()) {
			(function (thId) {
				var th = y.thread(thId);

				if (th.property('status') == 'open' && th.property('type') == 'spaghetti') {
					th.setProperty('status', 'closed');
					y.persistThread(th);

					y.updateThreadMessages(th, function (th) {
						var message = y.message(th.messageId());
						var joinersCount = message.likes();
						var joinerNames = message.likers();
						var joiners = [];
						var joinerIds = [];
						var joinersList = '';

						for (var i = 0; i < joinerNames.length; i++) {
							joiners.push(y.userByName(joinerNames[i]));
						}

						for (var i in joiners) {
							var user = joiners[i];
							joinerIds.push(user.id());

							if (i > 0) {
								joinersList += ', ';
							}

							joinersList += user.username();
						}

						if (joinerIds.length == 0) {
							var nooneMessage = messages.get('spaghetti_noone');
							y.sendMessage(function (error, message) {
								logger.info('spaghetti noone message OK: ' + message.id());

								th.setProperty('joiners', joinerIds);
								th.setProperty('status', 'closed');
								th.setProperty('charged', true);
								y.persistThread(th);
							}, nooneMessage, { 'reply_to' : th.messageId() });

						} else if (joinerIds.length < 5) {
							var notenoughMessage = messages.get('spaghetti_notenough', {
								'count' : joiners.length
							});
							y.sendMessage(function (error, message) {
								logger.info('spaghetti notenough message OK: ' + message.id());

								th.setProperty('joiners', joinerIds);
								th.setProperty('status', 'closed');
								th.setProperty('charged', true);
								y.persistThread(th);
							}, notenoughMessage, { 'reply_to' : th.messageId() });

						} else {

							var closingMessage = messages.get('spaghetti_closing', {
								'count' : joiners.length,
								'joiners' : joinersList
							});

							y.sendMessage(function (error, message) {
								logger.info('spaghetti closing message OK: ' + message.id());

								th.setProperty('joiners', joinerIds);
								th.setProperty('status', 'closed');
								y.persistThread(th);
							}, closingMessage, { 'reply_to' : th.messageId() });

						}

					});
				}

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


<commit_before>window.tidepoolPlatform = function(host, api, auth){
  var log = bows('tidepoolplatform.js');

  var sessionTokenHeader = 'x-tidepool-session-token';
  var token = null;
  var userid = null;

  function makeUrl(path) {
    return host + path;
  }

  function setupUser(api) {
    api.get = function(cb) {
      if (token == null || userid == null) {
        cb({ message: 'Not logged in' });
      }

      app.api.patient.get(userid, cb);
    };

    api.put = function(user, cb) {
      if (token == null || userid == null) {
        cb({ message: 'Not logged in' });
      }

      app.api.patient.put(userid, user, cb);
    };
  }

  function setupPatient(api) {
    api.getAll = function(cb) {
      if (token == null || userid == null) {
        cb({ message: 'Not logged in' });
      }

      superagent.get(makeUrl('/metadata/' + userid + '/groups'))
        .set(sessionTokenHeader, token)
        .end(
        function(err, res){
          if (err != null) {
            return cb(err);
          }

          if (res.status !== 200) {
            return cb({ message: 'Unknown response code from metadata ' + res.status });
          } else {
            if (res.body == null || res.body.patients == null) {
              return cb(null, []);
            }

            var patientsGroup = res.body.patients;
            superagent.get(makeUrl('/groups/' + patientsGroup + '/members'))
              .set(sessionTokenHeader)
              .end(
              function(membersErr, membersResult){
                if (membersErr != null) {
                  return cb(membersErr);
                }

                if (membersResult.status === 200) {
                  return cb(null, membersResult.body.groups);
                }
                else {
                  return cb({ message: 'Unknown response code from groups ' + res.status });
                }
              });
          }
        });
    };

    api.get = function(patientId, cb) {
      if (token == null || userid == null) {
        cb({ message: 'Not logged in' });
      }

      superagent.get(makeUrl('/metadata/' + patientId + '/profile'))
        .set(sessionTokenHeader, token)
        .end(
        function(err, res){
          if (err != null) {
            return cb(err);
          }

          if (res.status === 200) {
            cb(null, res.body);
          } else {
            cb(null, null);
          }
        });
    };

    api.put = function(patientId, patient, cb) {
      superagent.post(makeUrl('/metadata/' + patientId + '/profile'))
        .set(sessionTokenHeader, token)
        .send(patient)
        .end(
        function(err, res){
          if (err != null) {
            return cb(err);
          }

          if (res.status === 200) {
            return cb(null, res.body);
          } else {
            return cb({ message: 'Couldn\'t POST new user metadata: ' + res.status });
          }
        });
    };
  }

  function setupAuth(api) {
    function saveSession(newUserid, newToken) {
      token = newToken;
      userid = newUserid;
      if (newToken != null) {
        setTimeout(
          function(){
            if (token == null || newUserid !== userid) {
              return;
            }

            superagent.get(makeUrl('/auth/login'))
              .set(sessionTokenHeader, token)
              .end(
              function(err, res){
                if (err) {
                  log(err);
                  return;
                }

                if (res.status === 200) {
                  saveSession(newUserid, res.headers[sessionTokenHeader]);
                } else {
                  log('Unknown response when refreshing token' + res.status);
                }
              });
          },
          10 * 60 * 1000
        );
      }
    }

    api.init = function(cb) { return cb(); };

    api.login = function(user, cb) {
      if (user.username == null) {
        return cb({ message: 'Must specify an username' });
      }
      if (user.password == null) {
        return cb({ message: 'Must specify a password' });
      }

      superagent.post(makeUrl('/auth/login'))
        .auth(user.username, user.password)
        .end(
        function(err, res) {
          if (err != null) {
            return cb(err);
          }

          if (res.status === 200) {
            saveSession(res.body.userid, res.headers[sessionTokenHeader]);
            cb(null, res.body);
          } else if (res.status === 401) {
            cb({ message: 'Unauthorized' });
          } else {
            cb({ message: 'Unknown status code ' + res.status });
          }
        });
    };

    api.logout = function(cb) {
      if (token == null) {
        cb(null);
      }

      var oldToken = token;
      saveSession(null, null);
      superagent.post(makeUrl('/auth/logout'))
        .set(sessionTokenHeader, oldToken)
        .end(function(err, res){ cb(err); });
    };

    api.signup = function(user, cb) {
      if (user.username == null) {
        return cb({ message: 'Must specify a username' });
      }
      if (user.password == null) {
        return cb({ message: 'Must specify a password' });
      }

      var userApiUser = _.assign({}, _.pick(user, 'username', 'password'), { emails: [user.username] });
      superagent.post(makeUrl('/auth/user'))
        .send(userApiUser)
        .end(
        function(err, res){
          if (err != null) {
            return cb(err);
          }

          if (res.status === 201) {
            var userApiBody = res.body;
            saveSession(userApiBody.userid, res.headers[sessionTokenHeader]);
            app.api.user.put(_.omit(user, 'username', 'password', 'email'), function(err, profile){
              if (err != null) {
                return cb(err);
              }

              return cb(null, _.assign({}, userApiBody, profile));
            });
          } else if (res.status === 401) {
            cb({ message: 'Unauthorized' });
          } else {
            cb({ message: 'Unknown response code ' + res.status });
          }
        });
    };
  }

  setupUser(api.user);
  setupPatient(api.patient);
  setupAuth(auth);
};<commit_msg>Rename logger to be human-friendly<commit_after>window.tidepoolPlatform = function(host, api, auth){
  var log = bows('tidepoolplatform');

  var sessionTokenHeader = 'x-tidepool-session-token';
  var token = null;
  var userid = null;

  function makeUrl(path) {
    return host + path;
  }

  function setupUser(api) {
    api.get = function(cb) {
      if (token == null || userid == null) {
        cb({ message: 'Not logged in' });
      }

      app.api.patient.get(userid, cb);
    };

    api.put = function(user, cb) {
      if (token == null || userid == null) {
        cb({ message: 'Not logged in' });
      }

      app.api.patient.put(userid, user, cb);
    };
  }

  function setupPatient(api) {
    api.getAll = function(cb) {
      if (token == null || userid == null) {
        cb({ message: 'Not logged in' });
      }

      superagent.get(makeUrl('/metadata/' + userid + '/groups'))
        .set(sessionTokenHeader, token)
        .end(
        function(err, res){
          if (err != null) {
            return cb(err);
          }

          if (res.status !== 200) {
            return cb({ message: 'Unknown response code from metadata ' + res.status });
          } else {
            if (res.body == null || res.body.patients == null) {
              return cb(null, []);
            }

            var patientsGroup = res.body.patients;
            superagent.get(makeUrl('/groups/' + patientsGroup + '/members'))
              .set(sessionTokenHeader)
              .end(
              function(membersErr, membersResult){
                if (membersErr != null) {
                  return cb(membersErr);
                }

                if (membersResult.status === 200) {
                  return cb(null, membersResult.body.groups);
                }
                else {
                  return cb({ message: 'Unknown response code from groups ' + res.status });
                }
              });
          }
        });
    };

    api.get = function(patientId, cb) {
      if (token == null || userid == null) {
        cb({ message: 'Not logged in' });
      }

      superagent.get(makeUrl('/metadata/' + patientId + '/profile'))
        .set(sessionTokenHeader, token)
        .end(
        function(err, res){
          if (err != null) {
            return cb(err);
          }

          if (res.status === 200) {
            cb(null, res.body);
          } else {
            cb(null, null);
          }
        });
    };

    api.put = function(patientId, patient, cb) {
      superagent.post(makeUrl('/metadata/' + patientId + '/profile'))
        .set(sessionTokenHeader, token)
        .send(patient)
        .end(
        function(err, res){
          if (err != null) {
            return cb(err);
          }

          if (res.status === 200) {
            return cb(null, res.body);
          } else {
            return cb({ message: 'Couldn\'t POST new user metadata: ' + res.status });
          }
        });
    };
  }

  function setupAuth(api) {
    function saveSession(newUserid, newToken) {
      token = newToken;
      userid = newUserid;
      if (newToken != null) {
        setTimeout(
          function(){
            if (token == null || newUserid !== userid) {
              return;
            }

            superagent.get(makeUrl('/auth/login'))
              .set(sessionTokenHeader, token)
              .end(
              function(err, res){
                if (err) {
                  log(err);
                  return;
                }

                if (res.status === 200) {
                  saveSession(newUserid, res.headers[sessionTokenHeader]);
                } else {
                  log('Unknown response when refreshing token' + res.status);
                }
              });
          },
          10 * 60 * 1000
        );
      }
    }

    api.init = function(cb) { return cb(); };

    api.login = function(user, cb) {
      if (user.username == null) {
        return cb({ message: 'Must specify an username' });
      }
      if (user.password == null) {
        return cb({ message: 'Must specify a password' });
      }

      superagent.post(makeUrl('/auth/login'))
        .auth(user.username, user.password)
        .end(
        function(err, res) {
          if (err != null) {
            return cb(err);
          }

          if (res.status === 200) {
            saveSession(res.body.userid, res.headers[sessionTokenHeader]);
            cb(null, res.body);
          } else if (res.status === 401) {
            cb({ message: 'Unauthorized' });
          } else {
            cb({ message: 'Unknown status code ' + res.status });
          }
        });
    };

    api.logout = function(cb) {
      if (token == null) {
        cb(null);
      }

      var oldToken = token;
      saveSession(null, null);
      superagent.post(makeUrl('/auth/logout'))
        .set(sessionTokenHeader, oldToken)
        .end(function(err, res){ cb(err); });
    };

    api.signup = function(user, cb) {
      if (user.username == null) {
        return cb({ message: 'Must specify a username' });
      }
      if (user.password == null) {
        return cb({ message: 'Must specify a password' });
      }

      var userApiUser = _.assign({}, _.pick(user, 'username', 'password'), { emails: [user.username] });
      superagent.post(makeUrl('/auth/user'))
        .send(userApiUser)
        .end(
        function(err, res){
          if (err != null) {
            return cb(err);
          }

          if (res.status === 201) {
            var userApiBody = res.body;
            saveSession(userApiBody.userid, res.headers[sessionTokenHeader]);
            app.api.user.put(_.omit(user, 'username', 'password', 'email'), function(err, profile){
              if (err != null) {
                return cb(err);
              }

              return cb(null, _.assign({}, userApiBody, profile));
            });
          } else if (res.status === 401) {
            cb({ message: 'Unauthorized' });
          } else {
            cb({ message: 'Unknown response code ' + res.status });
          }
        });
    };
  }

  setupUser(api.user);
  setupPatient(api.patient);
  setupAuth(auth);
};<|endoftext|>


<commit_before>'use strict';

import React from 'react';
import {
	View,
	WebView
} from 'react-native';

var css = require('../styles/css');
var logger = require('../util/logger');

var WebWrapper = React.createClass({

	getInitialState: function() {
		var title = this.props.route.title;

		var scriptInjectStr = '';

		if (title === 'Feedback') {
			scriptInjectStr =  	'var elem = document.querySelector("#form_container h1"); elem.parentNode.removeChild(elem);';
		} else if (title === 'Welcome Week') {
			scriptInjectStr =  	'document.querySelector("#header").style.display = "none";'+
								'document.querySelector(".center.content-padded").style.display = "none";'+
								'document.querySelector("#ww-button-ucsd").style.display = "none";'+
								'document.querySelector("#footer").style.display = "none";';
		}

		return {
			scriptInject: scriptInjectStr
		}
	},

	render: function() {
		return this.renderScene();
	},

	renderScene: function() {
		return (
			<View style={[css.main_container, css.whitebg]}>
				<WebView
					injectedJavaScript={ this.state.scriptInject }
					ref={'webview'}
					style={css.webview_container}
					startInLoadingState={true}
					source={{uri: this.props.route.webViewURL }}  />
			</View>
		);
	},

});

module.exports = WebWrapper;<commit_msg>Added injection to fix styling<commit_after>'use strict';

import React from 'react';
import {
	View,
	WebView
} from 'react-native';

var css = require('../styles/css');
var logger = require('../util/logger');

var WebWrapper = React.createClass({

	getInitialState: function() {
		var title = this.props.route.title;

		var scriptInjectStr = '';

		if (title === 'Feedback') {
			scriptInjectStr =  'var elem = document.querySelector("#form_container h1"); elem.parentNode.removeChild(elem);';
			scriptInjectStr += 'document.documentElement.style.background = "white";';
			scriptInjectStr += 'document.querySelector("#form_container").style.boxShadow=null;'
		} else if (title === 'Welcome Week') {
			scriptInjectStr =  	'document.querySelector("#header").style.display = "none";'+
								'document.querySelector(".center.content-padded").style.display = "none";'+
								'document.querySelector("#ww-button-ucsd").style.display = "none";'+
								'document.querySelector("#footer").style.display = "none";';
		}

		return {
			scriptInject: scriptInjectStr
		}
	},

	render: function() {
		return this.renderScene();
	},

	renderScene: function() {
		return (
			<View style={[css.main_container, css.whitebg]}>
				<WebView
					injectedJavaScript={ this.state.scriptInject }
					ref={'webview'}
					style={css.webview_container}
					startInLoadingState={true}
					source={{uri: this.props.route.webViewURL }}  />
			</View>
		);
	},

});

module.exports = WebWrapper;<|endoftext|>


<commit_before>var timeoutID1;
var timeoutID2;

/**
 * Prints the given error message.
 * @param {string} msg - The error message to print.
 */
function error(msg) {  // eslint-disable-line no-unused-vars
  if (timeoutID1) {
    window.clearTimeout(timeoutID1);
  }
  if (timeoutID2) {
    window.clearTimeout(timeoutID2);
  }
  var element = document.getElementById('msg');
  element.innerHTML = msg;
  element.className = 'error';
  timeoutID1 = window.setTimeout(function() {
    if (element.className !== 'error') {
      return;
    }
    element.className = 'error-hide';
    timeoutID2 = window.setTimeout(function() {
      element.innerHTML = '';
      element.className = '';
    }, 500);
  }, 10000);
}

/**
 * Prints the given informational message.
 * @param {string} msg - The information message to print.
 */
function info(msg) {
  var element = document.getElementById('msg');
  element.innerHTML = msg;
  element.className = 'info';
}

/**
 * Converts an address object into a dictionary.
 * @param {PaymentAddress} addr - The address to convert.
 * @return {object} The resulting dictionary.
 */
function toDictionary(addr) {  // eslint-disable-line no-unused-vars
  var dict = {};
  if (addr) {
    dict.country = addr.country;
    dict.region = addr.region;
    dict.city = addr.city;
    dict.dependentLocality = addr.dependentLocality;
    dict.addressLine = addr.addressLine;
    dict.postalCode = addr.postalCode;
    dict.sortingCode = addr.sortingCode;
    dict.languageCode = addr.languageCode;
    dict.organization = addr.organization;
    dict.recipient = addr.recipient;
    dict.careOf = addr.careOf;
    dict.phone = addr.phone;
  }
  return dict;
}

/**
 * Called when the payment request is complete.
 * @param {string} message - The human readable message to display.
 * @param {ShippingAddress} shippingAddress - User's shipping address.
 * @param {string} shippingOption - User's preferred shipping opion.
 * @param {string} methodName - The type of payment instrument the user is
 *                              providing.
 * @param {object} instrumentDetails - The payment instrument data to charge.
 * @param {object} totalAmount - The total amount to charge.
 * @param {string} payerEmail - User's preferred contact email address.
 * @param {string} payerPhone - User's preferred contact phone number.
 */
function done(message, shippingAddress, shippingOption, methodName, instrumentDetails, totalAmount, payerEmail, payerPhone) {  // eslint-disable-line no-unused-vars
  var element = document.getElementById('contents');
  element.innerHTML = message;
  info('method: ' + methodName +
    '
' +
    'shipping option: ' + shippingOption +
    '
' +
    '
' +
    'email: ' + payerEmail +
    '
' +
    'phone: ' + payerPhone +
    '
' +
    'total:
' +
    JSON.stringify(totalAmount, undefined, 2) +
    '
' +
    'instrument:
' +
    JSON.stringify(instrumentDetails, undefined, 2) +
    '
' +
    'shipping address:
' +
    JSON.stringify(toDictionary(shippingAddress), undefined, 2));
}
<commit_msg>Remove extra break<commit_after>var timeoutID1;
var timeoutID2;

/**
 * Prints the given error message.
 * @param {string} msg - The error message to print.
 */
function error(msg) {  // eslint-disable-line no-unused-vars
  if (timeoutID1) {
    window.clearTimeout(timeoutID1);
  }
  if (timeoutID2) {
    window.clearTimeout(timeoutID2);
  }
  var element = document.getElementById('msg');
  element.innerHTML = msg;
  element.className = 'error';
  timeoutID1 = window.setTimeout(function() {
    if (element.className !== 'error') {
      return;
    }
    element.className = 'error-hide';
    timeoutID2 = window.setTimeout(function() {
      element.innerHTML = '';
      element.className = '';
    }, 500);
  }, 10000);
}

/**
 * Prints the given informational message.
 * @param {string} msg - The information message to print.
 */
function info(msg) {
  var element = document.getElementById('msg');
  element.innerHTML = msg;
  element.className = 'info';
}

/**
 * Converts an address object into a dictionary.
 * @param {PaymentAddress} addr - The address to convert.
 * @return {object} The resulting dictionary.
 */
function toDictionary(addr) {  // eslint-disable-line no-unused-vars
  var dict = {};
  if (addr) {
    dict.country = addr.country;
    dict.region = addr.region;
    dict.city = addr.city;
    dict.dependentLocality = addr.dependentLocality;
    dict.addressLine = addr.addressLine;
    dict.postalCode = addr.postalCode;
    dict.sortingCode = addr.sortingCode;
    dict.languageCode = addr.languageCode;
    dict.organization = addr.organization;
    dict.recipient = addr.recipient;
    dict.careOf = addr.careOf;
    dict.phone = addr.phone;
  }
  return dict;
}

/**
 * Called when the payment request is complete.
 * @param {string} message - The human readable message to display.
 * @param {ShippingAddress} shippingAddress - User's shipping address.
 * @param {string} shippingOption - User's preferred shipping opion.
 * @param {string} methodName - The type of payment instrument the user is
 *                              providing.
 * @param {object} instrumentDetails - The payment instrument data to charge.
 * @param {object} totalAmount - The total amount to charge.
 * @param {string} payerEmail - User's preferred contact email address.
 * @param {string} payerPhone - User's preferred contact phone number.
 */
function done(message, shippingAddress, shippingOption, methodName, instrumentDetails, totalAmount, payerEmail, payerPhone) {  // eslint-disable-line no-unused-vars
  var element = document.getElementById('contents');
  element.innerHTML = message;
  info('method: ' + methodName +
    '
' +
    'shipping option: ' + shippingOption +
    '
' +
    'email: ' + payerEmail +
    '
' +
    'phone: ' + payerPhone +
    '
' +
    'total:
' +
    JSON.stringify(totalAmount, undefined, 2) +
    '
' +
    'instrument:
' +
    JSON.stringify(instrumentDetails, undefined, 2) +
    '
' +
    'shipping address:
' +
    JSON.stringify(toDictionary(shippingAddress), undefined, 2));
}
<|endoftext|>