<commit_before>// Description:
//   Turn up!
//
// Dependencies:
//   None
//
// Configuration:
//   None
//
// Commands:
//   .* turn up.*
//   .* turnup.*
//   .* turnip.*
//
// Author:
//   Various Artists

var images = [
    'https://68.media.tumblr.com/4ea21ce02dd015ee9f1057524ec6e5ca/tumblr_o39ceghovA1sgl0ajo1_400.gif',
    'https://media.giphy.com/media/dLPTwfYtmuLF6/giphy.gif',
    'http://i1.kym-cdn.com/photos/images/original/000/708/752/6f5.gif',
    'http://www.lovethispic.com/uploaded_images/143705-Lisa-Simpson-Dancing.gif',
    'http://i.imgur.com/arTwCW7.gif'
    'http://i.imgur.com/m6VRS8u.gif',
    'http://i.imgur.com/MiC6C6l.gif',
    'https://media.giphy.com/media/olAik8MhYOB9K/giphy.gif',
    'https://media.giphy.com/media/BoPUZQRQEPogo/giphy.gif',
    'https://media.giphy.com/media/wqPWKOtW2AD9S/giphy.gif',
    'http://akns-images.eonline.com/eol_images/Entire_Site/2015810/rs_470x314-150910120306-giphy_3.gif',
    'http://public.articles.mtv.com/wp-content/uploads/style/2014/01/bombs-shimmy.gif',
    'http://cdn3-www.musicfeeds.com.au/assets/uploads/5d73c185050fc72385ead151133f2364.gif',
    'https://media.tenor.co/images/541b4abe6eb9f9545139bb2e0767009b/raw',
    'http://o.aolcdn.com/hss/storage/midas/6bc81f4958f714d71db568487588928c/202849138/1.gif',
    'https://media.giphy.com/media/3o6ozw9w2pPU8ndp0k/giphy.gif',
    'https://s3.amazonaws.com/rapgenius/kenan-and-kel-aw-here-it-goes-awh-here-goes-intro-kel-1352766252e.gif',
    'https://ddppchicago.files.wordpress.com/2017/02/overcoming.gif?w=665'
];

function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

function send (msg, howMany) {
    var items = shuffle(images);
    howMany = howMany || 1;
    for (i = 0; i < howMany; i++) {
        //This way there are no duplicates unless you've asked for more than we have
        msg.send(items[i % items.length] + "?_=" + (Math.ceil(Math.random() * 1000)));
    }
}

module.exports = function(robot) {

    robot.hear(/(turn up|turnup|turnip)/i, function (msg) {
        send(msg);
    });

};
<commit_msg>rick morty turnt<commit_after>// Description:
//   Turn up!
//
// Dependencies:
//   None
//
// Configuration:
//   None
//
// Commands:
//   .* turn up.*
//   .* turnup.*
//   .* turnip.*
//
// Author:
//   Various Artists

var images = [
    'https://68.media.tumblr.com/4ea21ce02dd015ee9f1057524ec6e5ca/tumblr_o39ceghovA1sgl0ajo1_400.gif',
    'https://media.giphy.com/media/dLPTwfYtmuLF6/giphy.gif',
    'http://i1.kym-cdn.com/photos/images/original/000/708/752/6f5.gif',
    'http://www.lovethispic.com/uploaded_images/143705-Lisa-Simpson-Dancing.gif',
    'http://i.imgur.com/arTwCW7.gif'
    'http://i.imgur.com/m6VRS8u.gif',
    'http://i.imgur.com/MiC6C6l.gif',
    'https://media.giphy.com/media/olAik8MhYOB9K/giphy.gif',
    'https://media.giphy.com/media/BoPUZQRQEPogo/giphy.gif',
    'https://media.giphy.com/media/wqPWKOtW2AD9S/giphy.gif',
    'http://akns-images.eonline.com/eol_images/Entire_Site/2015810/rs_470x314-150910120306-giphy_3.gif',
    'http://public.articles.mtv.com/wp-content/uploads/style/2014/01/bombs-shimmy.gif',
    'http://cdn3-www.musicfeeds.com.au/assets/uploads/5d73c185050fc72385ead151133f2364.gif',
    'https://media.tenor.co/images/541b4abe6eb9f9545139bb2e0767009b/raw',
    'http://o.aolcdn.com/hss/storage/midas/6bc81f4958f714d71db568487588928c/202849138/1.gif',
    'https://media.giphy.com/media/3o6ozw9w2pPU8ndp0k/giphy.gif',
    'https://s3.amazonaws.com/rapgenius/kenan-and-kel-aw-here-it-goes-awh-here-goes-intro-kel-1352766252e.gif',
    'https://ddppchicago.files.wordpress.com/2017/02/overcoming.gif?w=665',
    'http://i.imgur.com/qK0BMiH.gif',
    'https://media.giphy.com/media/i2dE5VvBNxBw4/giphy.gif',
    'http://i.imgur.com/aZvNY8S.gif',
    'http://a.fod4.com/images/GifGuide/dancing/tumblr_lit5wdB6j21qcfba3o1_500.gif',
    'https://33.media.tumblr.com/6800b0da8ced43a3d142441d033b34a8/tumblr_nm568diaWN1rxw730o1_500.gif'
];

function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

function send (msg, howMany) {
    var items = shuffle(images);
    howMany = howMany || 1;
    for (i = 0; i < howMany; i++) {
        //This way there are no duplicates unless you've asked for more than we have
        msg.send(items[i % items.length] + "?_=" + (Math.ceil(Math.random() * 1000)));
    }
}

module.exports = function(robot) {

    robot.hear(/(turn up|turnup|turnip)/i, function (msg) {
        send(msg);
    });

};
<|endoftext|>


<commit_before>import fetch from 'isomorphic-fetch'
import queue from 'async/queue'
import values from 'lodash/values'

import rlrankapi, { TRACKER } from '../lib/rocket-league-rank-api'

/* eslint-disable no-console */

if (!process.env.ROCKETLEAGUE_TRACKER_NETWORK_API_KEY || !process.env.RLTRACKER_PRO_API_KEY) {
  console.log('Please set the ROCKETLEAGUE_TRACKER_NETWORK_API_KEY and RLTRACKER_PRO_API_KEY env')
  process.exit(-1)
}

const PRIORITY_UNIT = 15 // minutes difference between priorities

const LOCAL_API = 'http://192.241.250.100:8080/api/v1'

const TRACKER_NAME = []
TRACKER_NAME[TRACKER.RLTRACKER_PRO] = 'rltracker.pro'
TRACKER_NAME[TRACKER.ROCKETLEAGUE_TRACKER_NETWORK] = 'Rocket League Tracker Network'

const RATE = []
RATE[TRACKER.RLTRACKER_PRO] = 9.8
RATE[TRACKER.ROCKETLEAGUE_TRACKER_NETWORK] = 1.8

const lastRequest = []
lastRequest[TRACKER.RLTRACKER_PRO] = 0
lastRequest[TRACKER.ROCKETLEAGUE_TRACKER_NETWORK] = 0

const isUp = []
isUp[TRACKER.RLTRACKER_PRO] = true
isUp[TRACKER.ROCKETLEAGUE_TRACKER_NETWORK] = true

const API_KEY = []
API_KEY[TRACKER.RLTRACKER_PRO] = process.env.RLTRACKER_PRO_API_KEY
API_KEY[TRACKER.ROCKETLEAGUE_TRACKER_NETWORK] = process.env.ROCKETLEAGUE_TRACKER_NETWORK_API_KEY

const getAdjustedTime = (time, priority) =>
  time + (priority * PRIORITY_UNIT * 60 * 1000)

// should update every PRIORITY * 60 min
const shouldUpdate = (player) => {
  const timeDelta = Date.now() - (new Date(player.last_update)).getTime()
  const minTimeToUpdate = getAdjustedTime(0, player.priority)
  const justCreated = player.last_update === player.created_at
  return (timeDelta > minTimeToUpdate && player.priority > 0) || justCreated
}

const timeToWaitBeforeNextRequest = (rate, lastRequestTime) => {
  const time = ((60 * 1000) / rate) - (Date.now() - lastRequestTime)
  return time < 0 ? 0 : time
}

const update = () => {
  console.log(`Starting full update at ${new Date().toISOString()}...`)

  console.log('Pulling players...')

  // set trackers as up
  isUp.map(() => true)

  fetch(`${LOCAL_API}/player`)
    .then((response) => {
      response.json()
        .then((jsonData) => {
          console.log('Pulled players')

          const playersToUpdate = jsonData.data.filter((p) => shouldUpdate(p))

          // sort by update time
          playersToUpdate.sort((a, b) =>
            getAdjustedTime((new Date(a.last_update).getTime()), a.priority) -
            getAdjustedTime((new Date(b.last_update)).getTime(), b.priority))

          console.log('Players to update:')
          console.log(playersToUpdate.map((p) => p.name))

          q.push(playersToUpdate, (err) => { if (err) console.log(err) })
        })
    })
    .catch((err) => console.log(`Error fetching players ${err}`))
}

const updatePlayer = (player, tracker) => new Promise((resolve, reject) => {
  rlrankapi.getPlayerInformation(player.platform, player.id, API_KEY[tracker], tracker)
      .then((stats) => {
        console.log(`${LOCAL_API}/player/${player.platform}/${player.id}/update`)

        fetch(`${LOCAL_API}/player/${player.platform}/${player.id}/update`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(stats),
        })
          .then((res) => {
            if (res.status === 200) {
              resolve(`Updated player: ${player.name}`)
            }
            reject(`Error status from local api: ${res.status}`)
          })
          .catch((err) =>
            reject(`Error updating ${player.name} with local api: ${err}`)
          )
      })
      .catch((err) =>
        reject(`Error updating ${player.name} with external api: ${err}`)
      )
})

let q = queue((player, callback) => {
  let timesToWait = values(TRACKER).map((trackerId) => ({
    trackerId,
    timeToWait: timeToWaitBeforeNextRequest(RATE[trackerId], lastRequest[trackerId]),
  }))

  // rltracker doesn't support xbox
  if (player.platform === 2) {
    timesToWait = timesToWait.filter((t) => t.trackerId !== TRACKER.RLTRACKER_PRO)
  }

  // sort by timeToWaitBeforeNextRequest
  timesToWait.sort((a, b) => a.timeToWait - b.timeToWait)

  const trackerId = timesToWait[0].trackerId
  const trackerTimeToWait = timesToWait[0].timeToWait
  const trackerName = TRACKER_NAME[trackerId]

  console.log(`Waiting ${trackerTimeToWait} ms for next request using ${trackerName}...`)
  setTimeout(() => {
    lastRequest[trackerId] = Date.now()
    console.log(`Starting update for player: ${player.name} using ${trackerName}`)
    updatePlayer(player, trackerId, trackerTimeToWait)
      .then((result) => {
        console.log(result)
        callback()
      })
      .catch((err) => {
        isUp[trackerId] = false
        console.log(err)
        callback(err)
      })
  }, trackerTimeToWait)
}, 2)

q.drain = () => setTimeout(update, 60 * 1000)

update()
<commit_msg>Fix LOCAL_API url<commit_after>import fetch from 'isomorphic-fetch'
import queue from 'async/queue'
import values from 'lodash/values'

import rlrankapi, { TRACKER } from '../lib/rocket-league-rank-api'

/* eslint-disable no-console */

if (!process.env.ROCKETLEAGUE_TRACKER_NETWORK_API_KEY || !process.env.RLTRACKER_PRO_API_KEY) {
  console.log('Please set the ROCKETLEAGUE_TRACKER_NETWORK_API_KEY and RLTRACKER_PRO_API_KEY env')
  process.exit(-1)
}

const PRIORITY_UNIT = 15 // minutes difference between priorities

const LOCAL_API = 'http://127.0.0.1:8080/api/v1'

const TRACKER_NAME = []
TRACKER_NAME[TRACKER.RLTRACKER_PRO] = 'rltracker.pro'
TRACKER_NAME[TRACKER.ROCKETLEAGUE_TRACKER_NETWORK] = 'Rocket League Tracker Network'

const RATE = []
RATE[TRACKER.RLTRACKER_PRO] = 9.8
RATE[TRACKER.ROCKETLEAGUE_TRACKER_NETWORK] = 1.8

const lastRequest = []
lastRequest[TRACKER.RLTRACKER_PRO] = 0
lastRequest[TRACKER.ROCKETLEAGUE_TRACKER_NETWORK] = 0

const isUp = []
isUp[TRACKER.RLTRACKER_PRO] = true
isUp[TRACKER.ROCKETLEAGUE_TRACKER_NETWORK] = true

const API_KEY = []
API_KEY[TRACKER.RLTRACKER_PRO] = process.env.RLTRACKER_PRO_API_KEY
API_KEY[TRACKER.ROCKETLEAGUE_TRACKER_NETWORK] = process.env.ROCKETLEAGUE_TRACKER_NETWORK_API_KEY

const getAdjustedTime = (time, priority) =>
  time + (priority * PRIORITY_UNIT * 60 * 1000)

// should update every PRIORITY * 60 min
const shouldUpdate = (player) => {
  const timeDelta = Date.now() - (new Date(player.last_update)).getTime()
  const minTimeToUpdate = getAdjustedTime(0, player.priority)
  const justCreated = player.last_update === player.created_at
  return (timeDelta > minTimeToUpdate && player.priority > 0) || justCreated
}

const timeToWaitBeforeNextRequest = (rate, lastRequestTime) => {
  const time = ((60 * 1000) / rate) - (Date.now() - lastRequestTime)
  return time < 0 ? 0 : time
}

const update = () => {
  console.log(`Starting full update at ${new Date().toISOString()}...`)

  console.log('Pulling players...')

  // set trackers as up
  isUp.map(() => true)

  fetch(`${LOCAL_API}/player`)
    .then((response) => {
      response.json()
        .then((jsonData) => {
          console.log('Pulled players')

          const playersToUpdate = jsonData.data.filter((p) => shouldUpdate(p))

          // sort by update time
          playersToUpdate.sort((a, b) =>
            getAdjustedTime((new Date(a.last_update).getTime()), a.priority) -
            getAdjustedTime((new Date(b.last_update)).getTime(), b.priority))

          console.log('Players to update:')
          console.log(playersToUpdate.map((p) => p.name))

          q.push(playersToUpdate, (err) => { if (err) console.log(err) })
        })
    })
    .catch((err) => console.log(`Error fetching players ${err}`))
}

const updatePlayer = (player, tracker) => new Promise((resolve, reject) => {
  rlrankapi.getPlayerInformation(player.platform, player.id, API_KEY[tracker], tracker)
      .then((stats) => {
        console.log(`${LOCAL_API}/player/${player.platform}/${player.id}/update`)

        fetch(`${LOCAL_API}/player/${player.platform}/${player.id}/update`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(stats),
        })
          .then((res) => {
            if (res.status === 200) {
              resolve(`Updated player: ${player.name}`)
            }
            reject(`Error status from local api: ${res.status}`)
          })
          .catch((err) =>
            reject(`Error updating ${player.name} with local api: ${err}`)
          )
      })
      .catch((err) =>
        reject(`Error updating ${player.name} with external api: ${err}`)
      )
})

let q = queue((player, callback) => {
  let timesToWait = values(TRACKER).map((trackerId) => ({
    trackerId,
    timeToWait: timeToWaitBeforeNextRequest(RATE[trackerId], lastRequest[trackerId]),
  }))

  // rltracker doesn't support xbox
  if (player.platform === 2) {
    timesToWait = timesToWait.filter((t) => t.trackerId !== TRACKER.RLTRACKER_PRO)
  }

  // sort by timeToWaitBeforeNextRequest
  timesToWait.sort((a, b) => a.timeToWait - b.timeToWait)

  const trackerId = timesToWait[0].trackerId
  const trackerTimeToWait = timesToWait[0].timeToWait
  const trackerName = TRACKER_NAME[trackerId]

  console.log(`Waiting ${trackerTimeToWait} ms for next request using ${trackerName}...`)
  setTimeout(() => {
    lastRequest[trackerId] = Date.now()
    console.log(`Starting update for player: ${player.name} using ${trackerName}`)
    updatePlayer(player, trackerId, trackerTimeToWait)
      .then((result) => {
        console.log(result)
        callback()
      })
      .catch((err) => {
        isUp[trackerId] = false
        console.log(err)
        callback(err)
      })
  }, trackerTimeToWait)
}, 2)

q.drain = () => setTimeout(update, 60 * 1000)

update()
<|endoftext|>


<commit_before>var _ = require('lodash');
var constants = require('../public/shared/gj_constants');

var GameObject = require('./game_object');
var Bloodsplosion = require('./bloodsplosion');
var Axe = require('./axe');
var Lazer = require('./lazer');

var SPAWN_COUNTDOWN = 30;
var INVULNERABLE_COUNTDOWN = 30;

var Player = function(id, color) {

    Player.superclass.call(this, id);

    this.type = 'player';
    this.color = color;
    this.x = 400;
    this.y = 320;
    this.w = 16;
    this.h = 24;

    this.kills = 0;
    this.deaths = 0;
    this.facex = 1;

    this.dead = false;

    this.spawnCountdown = SPAWN_COUNTDOWN;
    this.invulnerableCountdown = INVULNERABLE_COUNTDOWN;

    this._keysDown = {};
    this._prevKeysDown = {};
    this._mousePos = { x: null, y: null };
    this._mouseDown = false;
    this._mouseWasDown = false;
    this._standing = 0; // When greater than zero, the player is on the ground.  Counts down every frame. Reset every time a ground collision is detected.
    this._roofing = 0; // same as standing but for roof
    this._droppingKick = false;

    this._cachedMap = null;
    this._fireDelay = 400;
    this._lastFireTime = null;
};

Player.superclass = GameObject;

_.extend(
    Player.prototype,
    GameObject.prototype,
    {
        update: function(state) {
            this._cachedMap = state.maps[state.era];

            if (this.spawnCountdown > 0) {
                if (--this.spawnCountdown <= 0) {
                    this.dead = false;
                    this.moveToSpawnPoint();
                } else return;
            }

            if (this.invulnerableCountdown > 0) {
                --this.invulnerableCountdown;
            }

            if (this._keysDown[constants.keys.MOVE_LEFT]) {
                this.facex = -1;
            } else if (this._keysDown[constants.keys.MOVE_RIGHT]) {
                this.facex = 1;
            }

            if (this._standing > 0) this._standing--;
            if (this._roofing > 0) this._roofing--;

            switch (state.era) {
                case constants.eras.JUNGLE:
                    this.moveSelf_jungle(state);
                    break;
                case constants.eras.TUNDRA:
                    this.moveSelf_tundra(state);
                    break;
                case constants.eras.FUTURE:
                    this.moveSelf_future(state);
                    break;
            }

            if (this._mouseDown) {
                if (!this._lastFireTime || (new Date().getTime() - this._lastFireTime) > this._fireDelay) {
                    this._lastFireTime = new Date().getTime();
                    this.fireWeapon(state);
                }
            }

            // Integrate velocity in to position.
            Player.superclass.prototype.update.call(this, state);

            // Collide with the map.
            this.collideWithMap(state.maps[state.era], this.takeDamage.bind(this,null,state));

            this._prevKeysDown = _.clone(this._keysDown);
        },

        _moveX: function (turnx, accx, decayx, maxx) {
            if (this._keysDown[constants.keys.MOVE_LEFT]) {
                this.vx += this.vx > 0 ? -turnx : -accx;
            } else if (this._keysDown[constants.keys.MOVE_RIGHT]) {
                this.vx += this.vx < 0 ? turnx : accx;
            } else {
                this.vx *= decayx;
            }
            if (this.vx > maxx) {
                this.vx = maxx;
            } else if (this.vx < -maxx) {
                this.vx = -maxx;
            }
        },

        moveSelf_future: function(state) {
            var JET_UP = 1.2;
            var JET_SAVE = 1.6;

            if (this._standing) {
                this._moveX( 2, 0.5, 0.8, 4 );// Ground
            } else {
                this._moveX( 0.5, 0.3, 1, 6 );// Air
            }

            if (this._keysDown[constants.keys.JUMP]) {
                this._standing = 0;
                this.vy -= this.vy >= 0 ? JET_SAVE : JET_UP;
                this.vy -= 0.3;
            }
            this.vy += 0.8;

            if (this._roofing > 0) {
                this.vy = 4;
            }

            if (this.vy > 12) {
                this.vy = 12;
            }
            else if (this.vy < -6) {
                this.vy = -6;
            }
        },

        moveSelf_basic: function(state) {
            if (this._standing) {
                this._moveX( 2, 0.5, 0.8, 6 );// Ground
            } else {
                this._moveX( 1, 0.3, 0.9, 6 );// Air
            }

            if (this._keysDown[constants.keys.JUMP]) {
                if (this._standing > 0) {
                    this._standing = 0;
                    this.vy = -10;
                }
                if (this.vy < 0) {
                    this.vy -= 0.5;
                    this.y -= 0.3;
                }
            }

            this.vy += 1.0;

            if (this.vy > 12) {
                this.vy = 12;
            }
        },

        _startKick: function() {
            var theta = Math.atan2(this._mousePos.y - (this.y - this.h/2), this._mousePos.x - this.x);
            if (theta > 0) {
                if      (theta <   Math.PI/4) theta =   Math.PI/4;
                else if (theta > 3*Math.PI/4) theta = 3*Math.PI/4;
            } else {
                if (theta > -Math.PI/2) theta =   Math.PI/4;
                else                    theta = 3*Math.PI/4;
            }
            this.vx = 15 * Math.cos (theta);
            this.vy = 15 * Math.sin (theta);
        },

        moveSelf_jungle: function(state) {
            if (this._standing) {
                this._droppingKick = false;
            } else if (!this._mouseWasDown && this._mouseDown && !this._droppingKick) {
                this._droppingKick = true;
                this._startKick();
            }

            if (!this._droppingKick) {
                this.moveSelf_basic(state);
            }
        },

        moveSelf_tundra: function(state) {
            this.moveSelf_basic(state);
        },

        fireWeapon: function(state) {
            var projectile;

            switch (state.era) {
                case constants.eras.TUNDRA:
                    projectile = Axe;
                    break;
                case constants.eras.FUTURE:
                    projectile = Lazer;
                    break;
            }

            if (projectile) {
                projectile = new projectile(this, { x: this._mousePos.x, y: this._mousePos.y  });

                state.addObject(projectile);
            }
        },

        moveToSpawnPoint: function() {
            var map = this._cachedMap;
            var spawnPoint = _.sample(map._spawnPoints);
            this.x = constants.TILE_SIZE * spawnPoint[0];
            this.y = constants.TILE_SIZE * spawnPoint[1];
        },

        takeDamage: function(other, state) {
            if (other && other._owner) {
                other._owner.kills++;
            }
            this.deaths++;

            var emitter = new Bloodsplosion(this.x, this.y - this.h / 2);
            state.addObject(emitter);

            this.dead = true;
            this.vx = this.vy = 0;
            this.spawnCountdown = SPAWN_COUNTDOWN;
            this.invulnerableCountdown = INVULNERABLE_COUNTDOWN;
        },

        handleInput: function(input) {
            switch (input.type) {
                case 'keydown':
                    this._keysDown[input.key] = true;
                    break;
                case 'keyup':
                    delete this._keysDown[input.key];
                    break;
                case 'mousemove':
                    this._mousePos.x = input.x;
                    this._mousePos.y = input.y;
                    break;
                case 'mousedown':
                    this._mouseWasDown = this._mouseDown;
                    this._mouseDown = true;
                    break;
                case 'mouseup':
                    this._mouseDown = false;
                    break;
            }
        },

        collideWithMap: function(map,damaged) {
            map._sampledFatalTile = false;

            if (map.sampleAtPixel(this.x - this.w/2, this.y - this.h/2)
             || map.sampleAtPixel(this.x - this.w/2, this.y - 2 - (this.vy>0?this.vy:0))
             || map.sampleAtPixel(this.x - this.w/2, this.y - this.h + 2)) {
                this.x = constants.TILE_SIZE / 2 + constants.TILE_SIZE * Math.floor(this.x / constants.TILE_SIZE);
                if (this._droppingKick) {
                    this._droppingKick = false;
                    this.vx = Math.abs(this.vx)/2;
                } else {
                    this.vx = 0;
                }
            }
            if (map.sampleAtPixel(this.x + this.w/2, this.y - this.h/2)
             || map.sampleAtPixel(this.x + this.w/2, this.y - 2 - (this.vy>0?this.vy:0))
             || map.sampleAtPixel(this.x + this.w/2, this.y - this.h + 2)) {
                this.x = constants.TILE_SIZE / 2 + constants.TILE_SIZE * Math.floor(this.x / constants.TILE_SIZE);
                if (this._droppingKick) {
                    this._droppingKick = false;
                    this.vx = -Math.abs(this.vx)/2;
                } else {
                    this.vx = 0;
                }
            }
            if (map.sampleAtPixel(this.x + this.w/2 - 2, this.y, this.vy>0)
             || map.sampleAtPixel(this.x - this.w/2 + 2, this.y, this.vy>0)) {
                this.y = constants.TILE_SIZE * Math.floor(this.y / constants.TILE_SIZE);
                this.vy = 0;
                this._standing = 2;
            }
            if (map.sampleAtPixel(this.x + this.w/2 - 2, this.y - this.h)
             || map.sampleAtPixel(this.x - this.w/2 + 2, this.y - this.h)) {
                this.y = constants.TILE_SIZE * Math.ceil(this.y / constants.TILE_SIZE);
                if (this.vy < 0) this.vy = 0;
                this._roofing = 2;
            }

            // TODO make sure taking damage here doesnt allow double death
            if (map._sampledFatalTile && damaged && !this.invulnerableCountdown) damaged();
        }
    }
);

module.exports = Player;
<commit_msg>Fixed clipping in to wall<commit_after>var _ = require('lodash');
var constants = require('../public/shared/gj_constants');

var GameObject = require('./game_object');
var Bloodsplosion = require('./bloodsplosion');
var Axe = require('./axe');
var Lazer = require('./lazer');

var SPAWN_COUNTDOWN = 30;
var INVULNERABLE_COUNTDOWN = 30;

var Player = function(id, color) {

    Player.superclass.call(this, id);

    this.type = 'player';
    this.color = color;
    this.x = 400;
    this.y = 320;
    this.w = 16;
    this.h = 24;

    this.kills = 0;
    this.deaths = 0;
    this.facex = 1;

    this.dead = false;

    this.spawnCountdown = SPAWN_COUNTDOWN;
    this.invulnerableCountdown = INVULNERABLE_COUNTDOWN;

    this._keysDown = {};
    this._prevKeysDown = {};
    this._mousePos = { x: null, y: null };
    this._mouseDown = false;
    this._mouseWasDown = false;
    this._standing = 0; // When greater than zero, the player is on the ground.  Counts down every frame. Reset every time a ground collision is detected.
    this._roofing = 0; // same as standing but for roof
    this._droppingKick = false;

    this._cachedMap = null;
    this._fireDelay = 400;
    this._lastFireTime = null;
};

Player.superclass = GameObject;

_.extend(
    Player.prototype,
    GameObject.prototype,
    {
        update: function(state) {
            this._cachedMap = state.maps[state.era];

            if (this.spawnCountdown > 0) {
                if (--this.spawnCountdown <= 0) {
                    this.dead = false;
                    this.moveToSpawnPoint();
                } else return;
            }

            if (this.invulnerableCountdown > 0) {
                --this.invulnerableCountdown;
            }

            if (this._keysDown[constants.keys.MOVE_LEFT]) {
                this.facex = -1;
            } else if (this._keysDown[constants.keys.MOVE_RIGHT]) {
                this.facex = 1;
            }

            if (this._standing > 0) this._standing--;
            if (this._roofing > 0) this._roofing--;

            switch (state.era) {
                case constants.eras.JUNGLE:
                    this.moveSelf_jungle(state);
                    break;
                case constants.eras.TUNDRA:
                    this.moveSelf_tundra(state);
                    break;
                case constants.eras.FUTURE:
                    this.moveSelf_future(state);
                    break;
            }

            if (this._mouseDown) {
                if (!this._lastFireTime || (new Date().getTime() - this._lastFireTime) > this._fireDelay) {
                    this._lastFireTime = new Date().getTime();
                    this.fireWeapon(state);
                }
            }

            // Integrate velocity in to position and collide with the map.
            this.x += this.vx/2;
            this.y += this.vy/2;
            this.collideWithMap(state.maps[state.era], this.takeDamage.bind(this,null,state));
            this.x += this.vx/2;
            this.y += this.vy/2;
            this.collideWithMap(state.maps[state.era], this.takeDamage.bind(this,null,state));

            this._prevKeysDown = _.clone(this._keysDown);
        },

        _moveX: function (turnx, accx, decayx, maxx) {
            if (this._keysDown[constants.keys.MOVE_LEFT]) {
                this.vx += this.vx > 0 ? -turnx : -accx;
            } else if (this._keysDown[constants.keys.MOVE_RIGHT]) {
                this.vx += this.vx < 0 ? turnx : accx;
            } else {
                this.vx *= decayx;
            }
            if (this.vx > maxx) {
                this.vx = maxx;
            } else if (this.vx < -maxx) {
                this.vx = -maxx;
            }
        },

        moveSelf_future: function(state) {
            var JET_UP = 1.2;
            var JET_SAVE = 1.6;

            if (this._standing) {
                this._moveX( 2, 0.5, 0.8, 4 );// Ground
            } else {
                this._moveX( 0.5, 0.3, 1, 6 );// Air
            }

            if (this._keysDown[constants.keys.JUMP]) {
                this._standing = 0;
                this.vy -= this.vy >= 0 ? JET_SAVE : JET_UP;
                this.vy -= 0.3;
            }
            this.vy += 0.8;

            if (this._roofing > 0) {
                this.vy = 4;
            }

            if (this.vy > 12) {
                this.vy = 12;
            }
            else if (this.vy < -6) {
                this.vy = -6;
            }
        },

        moveSelf_basic: function(state) {
            if (this._standing) {
                this._moveX( 2, 0.5, 0.8, 6 );// Ground
            } else {
                this._moveX( 1, 0.3, 0.9, 6 );// Air
            }

            if (this._keysDown[constants.keys.JUMP]) {
                if (this._standing > 0) {
                    this._standing = 0;
                    this.vy = -10;
                }
                if (this.vy < 0) {
                    this.vy -= 0.5;
                    this.y -= 0.3;
                }
            }

            this.vy += 1.0;

            if (this.vy > 12) {
                this.vy = 12;
            }
        },

        _startKick: function() {
            var theta = Math.atan2(this._mousePos.y - (this.y - this.h/2), this._mousePos.x - this.x);
            if (theta > 0) {
                if      (theta <   Math.PI/4) theta =   Math.PI/4;
                else if (theta > 3*Math.PI/4) theta = 3*Math.PI/4;
            } else {
                if (theta > -Math.PI/2) theta =   Math.PI/4;
                else                    theta = 3*Math.PI/4;
            }
            this.vx = 15 * Math.cos (theta);
            this.vy = 15 * Math.sin (theta);
        },

        moveSelf_jungle: function(state) {
            if (this._standing) {
                this._droppingKick = false;
            } else if (!this._mouseWasDown && this._mouseDown && !this._droppingKick) {
                this._droppingKick = true;
                this._startKick();
            }

            if (!this._droppingKick) {
                this.moveSelf_basic(state);
            }
        },

        moveSelf_tundra: function(state) {
            this.moveSelf_basic(state);
        },

        fireWeapon: function(state) {
            var projectile;

            switch (state.era) {
                case constants.eras.TUNDRA:
                    projectile = Axe;
                    break;
                case constants.eras.FUTURE:
                    projectile = Lazer;
                    break;
            }

            if (projectile) {
                projectile = new projectile(this, { x: this._mousePos.x, y: this._mousePos.y  });

                state.addObject(projectile);
            }
        },

        moveToSpawnPoint: function() {
            var map = this._cachedMap;
            var spawnPoint = _.sample(map._spawnPoints);
            this.x = constants.TILE_SIZE * spawnPoint[0];
            this.y = constants.TILE_SIZE * spawnPoint[1];
        },

        takeDamage: function(other, state) {
            if (other && other._owner) {
                other._owner.kills++;
            }
            this.deaths++;

            var emitter = new Bloodsplosion(this.x, this.y - this.h / 2);
            state.addObject(emitter);

            this.dead = true;
            this.vx = this.vy = 0;
            this.spawnCountdown = SPAWN_COUNTDOWN;
            this.invulnerableCountdown = INVULNERABLE_COUNTDOWN;
        },

        handleInput: function(input) {
            switch (input.type) {
                case 'keydown':
                    this._keysDown[input.key] = true;
                    break;
                case 'keyup':
                    delete this._keysDown[input.key];
                    break;
                case 'mousemove':
                    this._mousePos.x = input.x;
                    this._mousePos.y = input.y;
                    break;
                case 'mousedown':
                    this._mouseWasDown = this._mouseDown;
                    this._mouseDown = true;
                    break;
                case 'mouseup':
                    this._mouseDown = false;
                    break;
            }
        },

        collideWithMap: function(map,damaged) {
            map._sampledFatalTile = false;

            if (map.sampleAtPixel(this.x - this.w/2, this.y - this.h/2)
             || map.sampleAtPixel(this.x - this.w/2, this.y - 2 - (this.vy>0?this.vy:0))
             || map.sampleAtPixel(this.x - this.w/2, this.y - this.h + 2)) {
                this.x = constants.TILE_SIZE / 2 + constants.TILE_SIZE * Math.floor(this.x / constants.TILE_SIZE);
                if (this._droppingKick) {
                    this._droppingKick = false;
                    this.vx = Math.abs(this.vx)/2;
                } else {
                    this.vx = 0;
                }
            }
            if (map.sampleAtPixel(this.x + this.w/2, this.y - this.h/2)
             || map.sampleAtPixel(this.x + this.w/2, this.y - 2 - (this.vy>0?this.vy:0))
             || map.sampleAtPixel(this.x + this.w/2, this.y - this.h + 2)) {
                this.x = constants.TILE_SIZE / 2 + constants.TILE_SIZE * Math.floor(this.x / constants.TILE_SIZE);
                if (this._droppingKick) {
                    this._droppingKick = false;
                    this.vx = -Math.abs(this.vx)/2;
                } else {
                    this.vx = 0;
                }
            }
            if (map.sampleAtPixel(this.x + this.w/2 - 2, this.y, this.vy>0)
             || map.sampleAtPixel(this.x - this.w/2 + 2, this.y, this.vy>0)) {
                this.y = constants.TILE_SIZE * Math.floor(this.y / constants.TILE_SIZE);
                this.vy = 0;
                this._standing = 2;
            }
            if (map.sampleAtPixel(this.x + this.w/2 - 2, this.y - this.h)
             || map.sampleAtPixel(this.x - this.w/2 + 2, this.y - this.h)) {
                this.y = constants.TILE_SIZE * Math.ceil(this.y / constants.TILE_SIZE);
                if (this.vy < 0) this.vy = 0;
                this._roofing = 2;
            }

            // TODO make sure taking damage here doesnt allow double death
            if (map._sampledFatalTile && damaged && !this.invulnerableCountdown) damaged();
        }
    }
);

module.exports = Player;
<|endoftext|>


<commit_before>'use strict';

var Hapi = require('hapi');

var server = new Hapi.Server();
server.connection({
    port: 3000
});

/* Register the MrHorse Plugin, and feed it an initial list of policies */
server.register({
        register: require('..'),
        options: {
            policyDirectory: __dirname + '/policies'
        }
    },
    function (err) {

        if (err) {
            return console.log(err);
        }
    });

/* Register another plugin to show how Mr Horse is used by other plugins. */
server.register({
        register: require('./another_plugin'),
        options: {}
    },
    function (err) {

        if (err) {
            return console.log(err);
        }
    });

/* Make a couple routes for example purposes. */
server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {

        reply('MrHorse ' +
            '
Try these:' +
            '
http://localhost:3000/loggedin - This will give a 403' +
            '
http://localhost:3000/loggedin?loggedin=true' +
            '
http://localhost:3000/admin - This will give a 403' +
            '
http://localhost:3000/admin?loggedin=true - This will give a 403 with a special message' +
            '
http://localhost:3000/admin?loggedin=true&admin=true - mixing multiple policies' +
            '
http://localhost:3000/adminnight?loggedin=true&admin=true - using parallel policies' +
            '
http://localhost:3000/addanalytics - Part of this JSON data is injected in a post handler' +
            '
http://localhost:3000/otherplugin - This route comes from a plugin, which can also use Mr Horse.  This will give a 403.' +
            '
http://localhost:3000/otherplugin?loggedin=true - Here is that route, logged in');
    }
});

/*
Try http://localhost:3000/loggedin, and
http://localhost:3000/loggedin?loggedin=true
 */
server.route({
    method: 'GET',
    path: '/loggedin',
    handler: function (request, reply) {

        reply('You are logged in.');
    },
    config: {
        plugins: {
            policies: ['isLoggedIn']
        }
    }
});

/*
Try http://localhost:3000/admin, and
http://localhost:3000/admin?loggedin=true, and
http://localhost:3000/admin?loggedin=true&admin=true
 */
server.route({
    method: 'GET',
    path: '/admin',
    handler: function (request, reply) {

        reply('You are logged in AND an admin.');
    },
    config: {
        plugins: {
            policies: ['isLoggedIn', 'isAnAdmin']
        }
    }
});

/*
Try http://localhost:3000/addanalytics
 */
server.route({
    method: 'GET',
    path: '/addanalytics',
    handler: function (request, reply) {

        reply({
            data: 'this could be cached'
        });
    },
    config: {
        plugins: {
            policies: ['addAnalytics']
        }
    }
});

/*
Try http://localhost:3000/adminnight, and
http://localhost:3000/adminnight?loggedin=true, and
http://localhost:3000/adminnight?loggedin=true&admin=true

Then try them again (with an internet connection) on a night when the moon is a waxing crescent.
 */
server.route({
    method: 'GET',
    path: '/adminnight',
    handler: function (request, reply) {

        reply('You are logged in AND an admin AND the moon is in phase.');
    },
    config: {
        plugins: {
            policies: [
                ['moonInPhase', 'isLoggedIn'], // Check these in parallel
                'isAnAdmin'
            ]
        }
    }
});

server.start(function (err) {

    console.log('Server started at: ' + server.info.uri);
});
<commit_msg>fix example comment.<commit_after>'use strict';

var Hapi = require('hapi');

var server = new Hapi.Server();
server.connection({
    port: 3000
});

/* Register the MrHorse Plugin, and feed it an initial list of policies */
server.register({
        register: require('..'),
        options: {
            policyDirectory: __dirname + '/policies'
        }
    },
    function (err) {

        if (err) {
            return console.log(err);
        }
    });

/* Register another plugin to show how Mr Horse is used by other plugins. */
server.register({
        register: require('./another_plugin'),
        options: {}
    },
    function (err) {

        if (err) {
            return console.log(err);
        }
    });

/* Make a couple routes for example purposes. */
server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {

        reply('MrHorse ' +
            '
Try these:' +
            '
http://localhost:3000/loggedin - This will give a 403' +
            '
http://localhost:3000/loggedin?loggedin=true' +
            '
http://localhost:3000/admin - This will give a 403' +
            '
http://localhost:3000/admin?loggedin=true - This will give a 403 with a special message' +
            '
http://localhost:3000/admin?loggedin=true&admin=true - mixing multiple policies' +
            '
http://localhost:3000/adminnight?loggedin=true&admin=true - using parallel policies' +
            '
http://localhost:3000/addanalytics - Part of this JSON data is injected in a post handler' +
            '
http://localhost:3000/otherplugin - This route comes from a plugin, which can also use Mr Horse.  This will give a 403.' +
            '
http://localhost:3000/otherplugin?loggedin=true - Here is that route, logged in');
    }
});

/*
Try http://localhost:3000/loggedin, and
http://localhost:3000/loggedin?loggedin=true
 */
server.route({
    method: 'GET',
    path: '/loggedin',
    handler: function (request, reply) {

        reply('You are logged in.');
    },
    config: {
        plugins: {
            policies: ['isLoggedIn']
        }
    }
});

/*
Try http://localhost:3000/admin, and
http://localhost:3000/admin?loggedin=true, and
http://localhost:3000/admin?loggedin=true&admin=true
 */
server.route({
    method: 'GET',
    path: '/admin',
    handler: function (request, reply) {

        reply('You are logged in AND an admin.');
    },
    config: {
        plugins: {
            policies: ['isLoggedIn', 'isAnAdmin']
        }
    }
});

/*
Try http://localhost:3000/addanalytics
 */
server.route({
    method: 'GET',
    path: '/addanalytics',
    handler: function (request, reply) {

        reply({
            data: 'this could be cached'
        });
    },
    config: {
        plugins: {
            policies: ['addAnalytics']
        }
    }
});

/*
Try http://localhost:3000/adminnight, and
http://localhost:3000/adminnight?loggedin=true, and
http://localhost:3000/adminnight?loggedin=true&admin=true

Then try them again (with an internet connection) on a night when the moon is a waning crescent.
 */
server.route({
    method: 'GET',
    path: '/adminnight',
    handler: function (request, reply) {

        reply('You are logged in AND an admin AND the moon is in phase.');
    },
    config: {
        plugins: {
            policies: [
                ['moonInPhase', 'isLoggedIn'], // Check these in parallel
                'isAnAdmin'
            ]
        }
    }
});

server.start(function (err) {

    console.log('Server started at: ' + server.info.uri);
});
<|endoftext|>


<commit_before>// Dependencies
var Cobol = require("../lib");

// Execute some COBOL snippets
Cobol(function () { /*
       IDENTIFICATION DIVISION.
       PROGRAM-ID. HELLO.
       ENVIRONMENT DIVISION.
       DATA DIVISION.
       PROCEDURE DIVISION.

       PROGRAM-BEGIN.
           DISPLAY "Hello world".

       PROGRAM-DONE.
           STOP RUN.
*/ }, function (err, data) {
    console.log(err || data);
});
// => "Hello World"

Cobol(__dirname + "/args.cbl", {
    args: ["Alice"]
}, function (err, data) {
    console.log(err || data);
});
// => "Your name is: Alice"

// This will read data from stdin
Cobol(function () { /*
       IDENTIFICATION DIVISION.
       PROGRAM-ID. APP.
      *> http://stackoverflow.com/q/938760/1420197

       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
       SELECT SYSIN ASSIGN TO KEYBOARD ORGANIZATION LINE SEQUENTIAL.

       DATA DIVISION.
       FILE SECTION.
       FD SYSIN.
       01 ln PIC X(64).
          88 EOF VALUE HIGH-VALUES.
       WORKING-STORAGE SECTION.
       PROCEDURE DIVISION.
       DISPLAY "Write something and then press the <Enter> key"
       OPEN INPUT SYSIN
       READ SYSIN
       AT END SET EOF TO TRUE
       END-READ
       PERFORM UNTIL EOF
       DISPLAY "You wrote: ", ln
       DISPLAY "------------"
       READ SYSIN
       AT END SET EOF TO TRUE
       END-READ
       END-PERFORM
       CLOSE SYSIN
       STOP RUN.
*/ }, {
    stdin: process.stdin
  , stdout: process.stdout
}, function (err) {
    if (err) {
        console.log(err);
    }
});
// => "Hello World"
<commit_msg>Fixed example output<commit_after>// Dependencies
var Cobol = require("../lib");

// Execute some COBOL snippets
Cobol(function () { /*
       IDENTIFICATION DIVISION.
       PROGRAM-ID. HELLO.
       ENVIRONMENT DIVISION.
       DATA DIVISION.
       PROCEDURE DIVISION.

       PROGRAM-BEGIN.
           DISPLAY "Hello world".

       PROGRAM-DONE.
           STOP RUN.
*/ }, function (err, data) {
    console.log(err || data);
});
// => "Hello World"

Cobol(__dirname + "/args.cbl", {
    args: ["Alice"]
}, function (err, data) {
    console.log(err || data);
});
// => "Your name is: Alice"

// This will read data from stdin
Cobol(function () { /*
       IDENTIFICATION DIVISION.
       PROGRAM-ID. APP.
      *> http://stackoverflow.com/q/938760/1420197

       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
       SELECT SYSIN ASSIGN TO KEYBOARD ORGANIZATION LINE SEQUENTIAL.

       DATA DIVISION.
       FILE SECTION.
       FD SYSIN.
       01 ln PIC X(64).
          88 EOF VALUE HIGH-VALUES.
       WORKING-STORAGE SECTION.
       PROCEDURE DIVISION.
       DISPLAY "Write something and then press the <Enter> key"
       OPEN INPUT SYSIN
       READ SYSIN
       AT END SET EOF TO TRUE
       END-READ
       PERFORM UNTIL EOF
       DISPLAY "You wrote: ", ln
       DISPLAY "------------"
       READ SYSIN
       AT END SET EOF TO TRUE
       END-READ
       END-PERFORM
       CLOSE SYSIN
       STOP RUN.
*/ }, {
    stdin: process.stdin
  , stdout: process.stdout
}, function (err) {
    if (err) {
        console.log(err);
    }
});
// => Write something and then press the <Enter> key
// <= Hi there!
// => You wrote: Hi there!
// => ------------
<|endoftext|>


<commit_before>'use strict';

var rangeLookup = require('../');

var lookup = function (query) {
  var selection = window.getSelection();
  selection.removeAllRanges();
  rangeLookup(query).forEach(selection.addRange.bind(selection));
};

document.addEventListener('DOMContentLoaded', function () {
  var queryEl = document.querySelector('input');
  queryEl.addEventListener('keyup', function () {
    lookup(queryEl.value);
  });
});
<commit_msg>(example) Remove DOMContentLoaded wrapper<commit_after>'use strict';

var rangeLookup = require('../');

var lookup = function (query) {
  var selection = window.getSelection();
  selection.removeAllRanges();
  rangeLookup(query).forEach(selection.addRange.bind(selection));
};

(function () {
  var queryEl = document.querySelector('input');
  queryEl.addEventListener('keyup', function () {
    lookup(queryEl.value);
  });
}());
<|endoftext|>


<commit_before>/**
 * @copyright © 2013 Environmental Systems Research Institute, Inc. (Esri)
 *
 * @license
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 *

 *     {@link http://www.apache.org/licenses/LICENSE-2.0}

 *

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

// NOTE: Modules that are not compatible with asynchronous module loading
// (AMD) are included in the webapp's HTML file to prevent issues.
require(["cmwapi/cmwapi", "esri/dijit/Gauge", "dojo/parser", "dojo/domReady!"], function(CMWAPI, Gauge, parser) {
    parser.parse();

    var knownMaps = {};
    var mapLayers = {};

    var selectedMapId;
    var selectedOverlayId;
    var selectedFeatureId;
    var selectedSubfeatureId;
    var selectedEventType = 'mouse-over';

    var gauge;

    var checkMapResponse = function(callerId, data){
        var mapSelector = $(".map_selector");

        var formats = data.formats;
        for(var i = 0; i < formats.length; i++) {
            if(formats[i] === "arcgis-dynamicmapservice" ||
                formats[i] === "arcgis-imageservice" ||
                formats[i] === "arcgis-feature" ) {

                //if its not in the list and drop down then add it
                if(typeof(knownMaps[callerId]) === "undefined") {
                    knownMaps[callerId] = {};
                    mapSelector.append("<option mapId=" + callerId + ">" + callerId + "</option>");
                }
                break;
            }
        }
    };

    var handleMapSelected = function() {
        CMWAPI.feature.status.request.send();
    }

    var handleReceivedLayers = function(sender, overlayId, overlayName, featureId, featureName, subfeatureId) {
        var selected = $(".map_selector option:selected");
        var mapWidgetId = selected.attr("mapId");

        var layerSelector = $('.sublayer_selector');

        if(!CMWAPI.validator.isArray(layers)) {
            layers = [layers];
        }

        for(var i = 0; i < layers.length; i++) {
            if(sender === mapWidgetId) {

                layerSelector.append('<option overlayId="' + layers[i].overlayId +
                    '" featureId="' + layers[i].featureId +
                    '" sublayerId="' + layers[i].sublayerId +
                    '">' + layers[i].overlayName + " - " + layers[i].featureName + " - " +
                    layers[i].sublayerId + '</option>');
            }
        }
    }

    var handleChangeSelection = function() {
        //send message to stop reporting old
        if(selectedOverlayId && selectedFeatureId) {
            CMWAPI.feature.status.stop.send({
                type: selectedEventType,
                overlayId: selectedOverlayId,
                featureId: selectedFeatureId,
                subfeatureId: selectedSubfeatureId
            });
        }

        var selected = $('.sublayer_selector option:selected');

        selectedOverlayId = selected.attr("overlayId");
        selectedFeatureId = selected.attr("featureId");
        selectedSubfeatureId = selected.attr("sublayerId");

        //send message to setup on event to new
        CMWAPI.feature.status.start.send({
            type: selectedEventType,
            overlayId: selectedOverlayId,
            featureId: selectedFeatureId,
            subfeatureId: selectedSubfeatureId
        });
    };

    var handleReport = function(sender, overlayId, featureId, subfeatureId, value) {
        if(overlayId === selectedOverlayId &&
            featureId === selectedFeatureId &&
            subfeatureId === selectedSubfeatureId) {
            gauge.set('value', value);
            gauge.set('caption', value);
        }
    }

    if(OWF.Util.isRunningInOWF()) {
        OWF.ready(function() {
            gauge = new Gauge({}, 'gauge');
            gauge.startup();

            CMWAPI.status.format.addHandler(checkMapResponse);

            CMWAPI.status.request.send({types: ["format"]});

            $(".map_selector").on('change', handleMapSelected);
            $(".sublayer_selector").on('change', handleChangeSelection);

            CMWAPI.feature.status.sublayers.addHandler(handleReceivedLayers);
            CMWAPI.feature.status.report.addHandler(handleReport);
        });
    }
});
<commit_msg>Filtering reports from non-selected mapId in gauge widget<commit_after>/**
 * @copyright © 2013 Environmental Systems Research Institute, Inc. (Esri)
 *
 * @license
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 *

 *     {@link http://www.apache.org/licenses/LICENSE-2.0}

 *

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

// NOTE: Modules that are not compatible with asynchronous module loading
// (AMD) are included in the webapp's HTML file to prevent issues.
require(["cmwapi/cmwapi", "esri/dijit/Gauge", "dojo/parser", "dojo/domReady!"], function(CMWAPI, Gauge, parser) {
    parser.parse();

    var knownMaps = {};
    var mapLayers = {};

    var selectedMapId;
    var selectedOverlayId;
    var selectedFeatureId;
    var selectedSubfeatureId;
    var selectedEventType = 'mouse-over';

    var gauge;

    var checkMapResponse = function(callerId, data){
        var mapSelector = $(".map_selector");

        var formats = data.formats;
        for(var i = 0; i < formats.length; i++) {
            if(formats[i] === "arcgis-dynamicmapservice" ||
                formats[i] === "arcgis-imageservice" ||
                formats[i] === "arcgis-feature" ) {

                //if its not in the list and drop down then add it
                if(typeof(knownMaps[callerId]) === "undefined") {
                    knownMaps[callerId] = {};
                    mapSelector.append("<option mapId=" + callerId + ">" + callerId + "</option>");
                }
                break;
            }
        }
    };

    var handleMapSelected = function() {
        var selected = $(".map_selector option:selected");
        selectedMapId = selected.attr("mapId");
        CMWAPI.feature.status.request.send();
    }

    var handleReceivedLayers = function(sender, overlayId, overlayName, featureId, featureName, subfeatureId) {
        var selected = $(".map_selector option:selected");
        var mapWidgetId = selected.attr("mapId");

        var layerSelector = $('.sublayer_selector');

        if(!CMWAPI.validator.isArray(layers)) {
            layers = [layers];
        }

        for(var i = 0; i < layers.length; i++) {
            if(sender === mapWidgetId) {

                layerSelector.append('<option overlayId="' + layers[i].overlayId +
                    '" featureId="' + layers[i].featureId +
                    '" sublayerId="' + layers[i].sublayerId +
                    '">' + layers[i].overlayName + " - " + layers[i].featureName + " - " +
                    layers[i].sublayerId + '</option>');
            }
        }
    }

    var handleChangeSelection = function() {
        //send message to stop reporting old
        if(selectedOverlayId && selectedFeatureId) {
            CMWAPI.feature.status.stop.send({
                type: selectedEventType,
                overlayId: selectedOverlayId,
                featureId: selectedFeatureId,
                subfeatureId: selectedSubfeatureId
            });
        }

        var selected = $('.sublayer_selector option:selected');

        selectedOverlayId = selected.attr("overlayId");
        selectedFeatureId = selected.attr("featureId");
        selectedSubfeatureId = selected.attr("sublayerId");

        //send message to setup on event to new
        CMWAPI.feature.status.start.send({
            type: selectedEventType,
            overlayId: selectedOverlayId,
            featureId: selectedFeatureId,
            subfeatureId: selectedSubfeatureId
        });
    };

    var handleReport = function(sender, overlayId, featureId, subfeatureId, value) {
        if(sender === selectedMapId &&
            overlayId === selectedOverlayId &&
            featureId === selectedFeatureId &&
            subfeatureId === selectedSubfeatureId) {
            gauge.set('value', value);
            gauge.set('caption', value);
        }
    }

    if(OWF.Util.isRunningInOWF()) {
        OWF.ready(function() {
            gauge = new Gauge({}, 'gauge');
            gauge.startup();

            CMWAPI.status.format.addHandler(checkMapResponse);

            CMWAPI.status.request.send({types: ["format"]});

            $(".map_selector").on('change', handleMapSelected);
            $(".sublayer_selector").on('change', handleChangeSelection);

            CMWAPI.feature.status.sublayers.addHandler(handleReceivedLayers);
            CMWAPI.feature.status.report.addHandler(handleReport);
        });
    }
});
<|endoftext|>


<commit_before>angular.module('ts.sheets').provider('$media', function(){

  var SHEET_ID = "$$sheetId";

  //TODO:  support automatic interpolation of values between transitions?
  //       and/or support manual interpolation with custom function passing
  var OBSERVER_CONF = {
    attributes: true,
    childList: true
  };

  function _mutationCallback(records, observer){
    angular.forEach(records, function(record){
      //TODO:  this could probably be optimized by
      //       digging into record.type and breaking out
      //       behavior for record.type === "attributes" vs "childList"
      //       but for now, just reapply to entire parent element's subtree
      //TODO:  double-check if record.target (in case of record.type === "attributes") is the parent node or specific child node
      //       If it's the child node, we'll still need to update the parent tree instead of the child, which might require some
      //       passing of the element ID by closure when creating the mutuationCallback
      console.log('mutation observed', record);
      if(record.type === "attributes") console.warn("ensure that record.target is the parent node, not a child node", record)

      _updateElement(record.target);
    });
  }

  var _windowSizeDirty = true;

  function _windowResizeCallback(){
    _windowSizeDirty = true;
    _updateEverything();
  }

  var _cachedResolvedMediaQueries = [];

  //determines all registered media queries that are true, caches results
  function _resolveMediaQueries(){
    if(!_windowSizeDirty) return _cachedResolvedMediaQueries;

    var matched = [];
    angular.forEach(_registeredMediaQueries, function(mediaQuery){
      if(mediaQuery.conditionFn()) matched.push(mediaQuery);
    });

    if(!matched.length) throw new Error('$media assumes at least one media query will be matched (by default this is \'xs\').')

    //sort media queries descendingly by priority
    matched.sort(function(a, b){return b.priority - a.priority});

    _windowSizeDirty = false;
    _cachedResolvedMediaQueries = matched;
    return _cachedResolvedMediaQueries;
  }

  //reevaluate every element (may be expensive)
  function _updateEverything(){
    var elementIds = Object.keys(_elements);
    angular.forEach(elementIds, function(id){
      _updateElement(_elements[id]);
    });
  }

  //naively and greedily test depth by probing first subtree
  function _getObjectDepth(obj, acc){
    var keys = !Array.isArray(obj) && Object.keys(obj);
    if(keys && keys.length) return _getObjectDepth(obj[keys[0]], ++acc);
    return acc;
  }

  //update element and its subtree, applying all relevant sheets
  function _updateElement(element){
    var id = element.data(SHEET_ID);
    var sheets = _elementSheets[id];

    var matchedQueries = _resolveMediaQueries();

    angular.forEach(sheets, function(sheet){

      //support having media queries or omitting them
      //probe depth:  if depth === 3, we have media queries;
      //              if depth === 2, we don't.

      var depth = _getObjectDepth(sheet, 0);
      var matchedLayout;
      if(depth === 2){
        matchedLayout = sheet;
      }else if(depth === 3){
        var found = false;
        //loop through the matched queries by descending priority, finding the first query
        //that exists in obj
        angular.forEach(matchedQueries, function(query){
          if(found) return;
          if(sheet[query.name]){
            found = true;
            matchedLayout = sheet[query.name];

          }
        });
      }else{
        throw new Error('Malformed Sheet.  Object depth of 2 or 3 expected.  Actual depth was ' + depth);
      }

      //nothing to see here
      if(!matchedLayout) return;

      var selectors = Object.keys(matchedLayout);

      angular.forEach(selectors, function(selector){
        var fields = Object.keys(matchedLayout[selector]);
        var elements = element[0].querySelectorAll(selector);

        angular.forEach(elements, function(childElement){
          angular.forEach(fields, function(field){
            var payload = matchedLayout[selector][field];
            _fieldHandlers[field](childElement, payload);
          });
        });

      })

    });
  }

  //cross-browser addEvent from http://stackoverflow.com/questions/641857/javascript-window-resize-event
  var _addEvent = function(elem, type, eventHandle) {
    if (elem == null || typeof(elem) == 'undefined') return;
    if ( elem.addEventListener ) {
      elem.addEventListener( type, eventHandle, false );
    } else if ( elem.attachEvent ) {
      elem.attachEvent( "on" + type, eventHandle );
    } else {
      elem["on"+type]=eventHandle;
    }
  };

  var _registeredMediaQueries = [],
      _registeredMediaQueriesByName = {},
      _sheets = {},
      _elementSheets = {},
      _elements = {},
      _fieldHandlers = {},
      _observers = {};

  var _registerMediaQuery = this.$registerMediaQuery = function(name, conditionFn, priority){
      _registeredMediaQueries[priority] = {name: name, conditionFn: conditionFn, priority: priority};
      _registeredMediaQueriesByName[name] = {name: name, conditionFn: conditionFn, priority: priority};
  };
  var _registerFieldHandler = this.$registerFieldHandler = function(fieldName, handlerFn){
      //TODO:  support passing an array of supported elements
      //       or even a function to determine if a given element is supported
      _fieldHandlers[fieldName] = handlerFn;
  };

  var $media = {

    //declare a sheet in a controller/presenter
    $sheet: function(name, spec){
      if(_sheets[name] !== undefined) console.warn('Sheet name \''+name+'\' is already defined.  The latest declaration will overwrite previous declarations.')
      _sheets[name] = spec;
    },

    //apply a sheet by name, called at least by ts-sheet directive
    $applySheet: function(element, name){
      element.data(SHEET_ID, element.data(SHEET_ID) || Math.random()); //TODO:  better uniqueid?
      var id = element.data(SHEET_ID);
      var spec = _sheets[name];
      if(spec === undefined) throw new Error('Sheet \'' + name + '\' is undefined.  Sheets must be defined using $media.$sheet before they can be applied with ts-sheet.');

      _elements[id] = element;

      _elementSheets[id] = _elementSheets[id] || [];
      _elementSheets[id].push(spec);

      var observer = _observers[id] = _observers[id] || new MutationObserver(_mutationCallback);
      observer.observe(element[0], OBSERVER_CONF);

      //kick off initial action
      _updateElement(element);
    },

    //used for clean-up in ts-sheet directive
    //detaches all sheets from an element and stops an element from being updated
    //does NOT automatically undo whatever logic is declared in payload functions
    $clearSheets: function(element, name) {
      //TODO: test that this works
      var id = element.data(SHEET_ID);

      delete _sheets[name];
      delete _elementSheets[id];
      delete _elements[id]
      _observers[id].disconnect();
    },

    //test whether the mediaQuery of the given name is currently fulfilled
    $query: function(mediaQueryName){
      return _registeredMediaQueriesByName[mediaQueryName]();
    }
  };

  //expose $media service
  this.$get = function($window){
    //note that this will trigger several times per actual resize in some browsers
    _addEvent($window, "resize", _windowResizeCallback);

    var DEFAULT_MEDIA_QUERIES = [
      {
        name: 'xs',
        conditionFn: function(){
          return true;
        },
        priority: 0
      },
      {
        name: 'sm',
        conditionFn: function(){
          return $window.innerWidth >= 768;
        },
        priority: 1
      },
      {
        name: 'md',
        conditionFn: function(){
          return $window.innerWidth >= 992;
        },
        priority: 2
      },
      {
        name: 'lg',
        conditionFn: function(){
          return $window.innerWidth >= 1200;
        },
        priority: 3
      }
    ];

    //TODO:  support different field names by element type
    //       (e.g. different behavior for 'color' for a div vs a span)
    var DEFAULT_FIELD_HANDLERS = [];

    angular.forEach(DEFAULT_MEDIA_QUERIES, function(mediaQuery){
      _registerMediaQuery(mediaQuery.name, mediaQuery.conditionFn, mediaQuery.priority);
    });

    angular.forEach(DEFAULT_FIELD_HANDLERS, function(fieldHandler){
      _registerFieldHandler(fieldHandler.field, fieldHandler.handlerFn);
    });

    return $media;
  }

});<commit_msg>call conditionFn() for the media query when calling $media.$query()<commit_after>angular.module('ts.sheets').provider('$media', function(){

  var SHEET_ID = "$$sheetId";

  //TODO:  support automatic interpolation of values between transitions?
  //       and/or support manual interpolation with custom function passing
  var OBSERVER_CONF = {
    attributes: true,
    childList: true
  };

  function _mutationCallback(records, observer){
    angular.forEach(records, function(record){
      //TODO:  this could probably be optimized by
      //       digging into record.type and breaking out
      //       behavior for record.type === "attributes" vs "childList"
      //       but for now, just reapply to entire parent element's subtree
      //TODO:  double-check if record.target (in case of record.type === "attributes") is the parent node or specific child node
      //       If it's the child node, we'll still need to update the parent tree instead of the child, which might require some
      //       passing of the element ID by closure when creating the mutuationCallback
      console.log('mutation observed', record);
      if(record.type === "attributes") console.warn("ensure that record.target is the parent node, not a child node", record)

      _updateElement(record.target);
    });
  }

  var _windowSizeDirty = true;

  function _windowResizeCallback(){
    _windowSizeDirty = true;
    _updateEverything();
  }

  var _cachedResolvedMediaQueries = [];

  //determines all registered media queries that are true, caches results
  function _resolveMediaQueries(){
    if(!_windowSizeDirty) return _cachedResolvedMediaQueries;

    var matched = [];
    angular.forEach(_registeredMediaQueries, function(mediaQuery){
      if(mediaQuery.conditionFn()) matched.push(mediaQuery);
    });

    if(!matched.length) throw new Error('$media assumes at least one media query will be matched (by default this is \'xs\').')

    //sort media queries descendingly by priority
    matched.sort(function(a, b){return b.priority - a.priority});

    _windowSizeDirty = false;
    _cachedResolvedMediaQueries = matched;
    return _cachedResolvedMediaQueries;
  }

  //reevaluate every element (may be expensive)
  function _updateEverything(){
    var elementIds = Object.keys(_elements);
    angular.forEach(elementIds, function(id){
      _updateElement(_elements[id]);
    });
  }

  //naively and greedily test depth by probing first subtree
  function _getObjectDepth(obj, acc){
    var keys = !Array.isArray(obj) && Object.keys(obj);
    if(keys && keys.length) return _getObjectDepth(obj[keys[0]], ++acc);
    return acc;
  }

  //update element and its subtree, applying all relevant sheets
  function _updateElement(element){
    var id = element.data(SHEET_ID);
    var sheets = _elementSheets[id];

    var matchedQueries = _resolveMediaQueries();

    angular.forEach(sheets, function(sheet){

      //support having media queries or omitting them
      //probe depth:  if depth === 3, we have media queries;
      //              if depth === 2, we don't.

      var depth = _getObjectDepth(sheet, 0);
      var matchedLayout;
      if(depth === 2){
        matchedLayout = sheet;
      }else if(depth === 3){
        var found = false;
        //loop through the matched queries by descending priority, finding the first query
        //that exists in obj
        angular.forEach(matchedQueries, function(query){
          if(found) return;
          if(sheet[query.name]){
            found = true;
            matchedLayout = sheet[query.name];

          }
        });
      }else{
        throw new Error('Malformed Sheet.  Object depth of 2 or 3 expected.  Actual depth was ' + depth);
      }

      //nothing to see here
      if(!matchedLayout) return;

      var selectors = Object.keys(matchedLayout);

      angular.forEach(selectors, function(selector){
        var fields = Object.keys(matchedLayout[selector]);
        var elements = element[0].querySelectorAll(selector);

        angular.forEach(elements, function(childElement){
          angular.forEach(fields, function(field){
            var payload = matchedLayout[selector][field];
            _fieldHandlers[field](childElement, payload);
          });
        });

      })

    });
  }

  //cross-browser addEvent from http://stackoverflow.com/questions/641857/javascript-window-resize-event
  var _addEvent = function(elem, type, eventHandle) {
    if (elem == null || typeof(elem) == 'undefined') return;
    if ( elem.addEventListener ) {
      elem.addEventListener( type, eventHandle, false );
    } else if ( elem.attachEvent ) {
      elem.attachEvent( "on" + type, eventHandle );
    } else {
      elem["on"+type]=eventHandle;
    }
  };

  var _registeredMediaQueries = [],
      _registeredMediaQueriesByName = {},
      _sheets = {},
      _elementSheets = {},
      _elements = {},
      _fieldHandlers = {},
      _observers = {};

  var _registerMediaQuery = this.$registerMediaQuery = function(name, conditionFn, priority){
      _registeredMediaQueries[priority] = {name: name, conditionFn: conditionFn, priority: priority};
      _registeredMediaQueriesByName[name] = {name: name, conditionFn: conditionFn, priority: priority};
  };
  var _registerFieldHandler = this.$registerFieldHandler = function(fieldName, handlerFn){
      //TODO:  support passing an array of supported elements
      //       or even a function to determine if a given element is supported
      _fieldHandlers[fieldName] = handlerFn;
  };

  var $media = {

    //declare a sheet in a controller/presenter
    $sheet: function(name, spec){
      if(_sheets[name] !== undefined) console.warn('Sheet name \''+name+'\' is already defined.  The latest declaration will overwrite previous declarations.')
      _sheets[name] = spec;
    },

    //apply a sheet by name, called at least by ts-sheet directive
    $applySheet: function(element, name){
      element.data(SHEET_ID, element.data(SHEET_ID) || Math.random()); //TODO:  better uniqueid?
      var id = element.data(SHEET_ID);
      var spec = _sheets[name];
      if(spec === undefined) throw new Error('Sheet \'' + name + '\' is undefined.  Sheets must be defined using $media.$sheet before they can be applied with ts-sheet.');

      _elements[id] = element;

      _elementSheets[id] = _elementSheets[id] || [];
      _elementSheets[id].push(spec);

      var observer = _observers[id] = _observers[id] || new MutationObserver(_mutationCallback);
      observer.observe(element[0], OBSERVER_CONF);

      //kick off initial action
      _updateElement(element);
    },

    //used for clean-up in ts-sheet directive
    //detaches all sheets from an element and stops an element from being updated
    //does NOT automatically undo whatever logic is declared in payload functions
    $clearSheets: function(element, name) {
      //TODO: test that this works
      var id = element.data(SHEET_ID);

      delete _sheets[name];
      delete _elementSheets[id];
      delete _elements[id]
      _observers[id].disconnect();
    },

    //test whether the mediaQuery of the given name is currently fulfilled
    $query: function(mediaQueryName){
      return _registeredMediaQueriesByName[mediaQueryName].conditionFn();
    }
  };

  //expose $media service
  this.$get = function($window){
    //note that this will trigger several times per actual resize in some browsers
    _addEvent($window, "resize", _windowResizeCallback);

    var DEFAULT_MEDIA_QUERIES = [
      {
        name: 'xs',
        conditionFn: function(){
          return true;
        },
        priority: 0
      },
      {
        name: 'sm',
        conditionFn: function(){
          return $window.innerWidth >= 768;
        },
        priority: 1
      },
      {
        name: 'md',
        conditionFn: function(){
          return $window.innerWidth >= 992;
        },
        priority: 2
      },
      {
        name: 'lg',
        conditionFn: function(){
          return $window.innerWidth >= 1200;
        },
        priority: 3
      }
    ];

    //TODO:  support different field names by element type
    //       (e.g. different behavior for 'color' for a div vs a span)
    var DEFAULT_FIELD_HANDLERS = [];

    angular.forEach(DEFAULT_MEDIA_QUERIES, function(mediaQuery){
      _registerMediaQuery(mediaQuery.name, mediaQuery.conditionFn, mediaQuery.priority);
    });

    angular.forEach(DEFAULT_FIELD_HANDLERS, function(fieldHandler){
      _registerFieldHandler(fieldHandler.field, fieldHandler.handlerFn);
    });

    return $media;
  }

});
<|endoftext|>


<commit_before>const Promise = require('bluebird')
const MongoClient = require('mongodb').MongoClient;
const t = require('tcomb-validation');
const inputs = require('../models/inputs.js');

function connect(url, callback) {
    MongoClient.connect(url, function (err, db) {
        if (err) {
            console.log(err)
        }
        console.log('db is conected');
        callback(db)
    })
}

function insert(db, collection, stuff, done) {
    if (Array.isArray(stuff)) {
        db.collection(collection).insertMany(stuff, function (err, r) {
            if (err) {
                done({ status: 500, message: err })
            }

            done({ status: 200, message: r })
        });
    } else {
        db.collection(collection).insertOne(stuff, function (err, r) {
            if (err) {
                done({ status: 500, message: err })
            }

            done({ status: 200, message: r })
        });
    }
}

function updatePassport(db, collection, select, stuff, done) {

    const entry = {
        location: stuff.location,
        date: Math.round((new Date()).getTime() / 1000),
        facilityName: stuff.supplier,
        condition: stuff.condition,
        rating: stuff.rating
    }

    const result = t.validate(entry, input.stamp)

    if (result.isValid()) {
        db.collection(collection).updateOne({ itemID: select }, { $push: { stamp: entry } }, (err, doc) => {
            if (err) {
                done({ status: 500, message: err })
            }
            done({ status: 200, message: doc })
        })
    } else {
        done({ status: 400, message: result.errors })
    }
}

function getPassport(db, collection, select, done) {
    console.log({"itemId":select})
    db.collection(collection).findOne({"itemId":select}, (err, doc) => {
        if (err) {
            done({ status: 500, message: err })
        }
        done({ status: 200, message: doc })
    })
}

function createPassport(db, collection, stuff, done) {
    db.collection(collection).insertOne(stuff, (err, doc) => {
        if (err) {
            done({ status: 500, message: err })
        }
        done({ status: 200, message: doc })
    })
}

module.exports = {
    insert: insert,
    connect: connect,
    getPassport: getPassport,
    updatePassport: updatePassport,
    createPassport: createPassport
}<commit_msg>debugging<commit_after>const Promise = require('bluebird')
const MongoClient = require('mongodb').MongoClient;
const t = require('tcomb-validation');
const inputs = require('../models/inputs.js');

function connect(url, callback) {
    MongoClient.connect(url, function (err, db) {
        if (err) {
            console.log(err)
        }
        console.log('db is conected');
        callback(db)
    })
}

function insert(db, collection, stuff, done) {
    if (Array.isArray(stuff)) {
        db.collection(collection).insertMany(stuff, function (err, r) {
            if (err) {
                done({ status: 500, message: err })
            }

            done({ status: 200, message: r })
        });
    } else {
        db.collection(collection).insertOne(stuff, function (err, r) {
            if (err) {
                done({ status: 500, message: err })
            }

            done({ status: 200, message: r })
        });
    }
}

function updatePassport(db, collection, select, stuff, done) {

    const entry = {
        location: stuff.location,
        date: Math.round((new Date()).getTime() / 1000),
        facilityName: stuff.supplier,
        condition: stuff.condition,
        rating: stuff.rating
    }

    const result = t.validate(entry, input.stamp)

    if (result.isValid()) {
        db.collection(collection).updateOne({ itemID: select }, { $push: { stamp: entry } }, (err, doc) => {
            if (err) {
                done({ status: 500, message: err })
            }
            done({ status: 200, message: doc })
        })
    } else {
        done({ status: 400, message: result.errors })
    }
}

function getPassport(db, collection, select, done) {
    console.log({"itemId":select})
    db.collection(collection).findOne({"itemId":select}, (err, doc) => {
        if (err) {
            done({ status: 500, message: err })
        }
        console.log(doc)
        done({ status: 200, message: doc })
    })
}

function createPassport(db, collection, stuff, done) {
    db.collection(collection).insertOne(stuff, (err, doc) => {
        if (err) {
            done({ status: 500, message: err })
        }
        done({ status: 200, message: doc })
    })
}

module.exports = {
    insert: insert,
    connect: connect,
    getPassport: getPassport,
    updatePassport: updatePassport,
    createPassport: createPassport
}<|endoftext|>