<commit_before>'use strict'

var DOMAIN = 'http://molgenis27.target.rug.nl'

var _ = require('lodash')
var color = require('../js/color')
var htmlutil = require('./htmlutil')

var React = require('react')
var ReactDOM = require('react-dom')
var ReactRouter = require('react-router')
var Router = ReactRouter.Router
var Route = ReactRouter.Route
var Link = ReactRouter.Link
var createBrowserHistory = require('history/lib/createBrowserHistory')

var Select = require('react-select')
var DocumentTitle = require('react-document-title')

var Logo = require('./ReactComponents/Logo')
var API = require('./ReactComponents/API')
var ManyGenesMaster = require('./ReactComponents/ManyGenesMaster')
var Gene = require('./ReactComponents/Gene/Gene')
var Term = require('./ReactComponents/Term')
var Ontology = require('./ReactComponents/Ontology')
var Diagnosis = require('./ReactComponents/Diagnosis')
var Footer = require('./ReactComponents/Footer')

var GN = {}
window.GN = GN
GN.menuItems = [{
    name: 'HOME',
    route: '/'
}, {
    name: 'HOW IT WORKS',
    route: '/how'
}, {
    name: 'ABOUT',
    route: '/about'
}, {
    name: 'API',
    route: '/api'
}]

GN.urls = {

    main: DOMAIN,
    gene: DOMAIN + '/api/v1/gene',
    pathway: DOMAIN + '/api/v1/pathway',
    coregulation: DOMAIN + '/api/v1/coregulation',
    tissues: DOMAIN + '/api/v1/tissues',
    cofunction: DOMAIN + '/api/v1/cofunction',
    pc: DOMAIN + '/api/v1/pc',

    suggest: DOMAIN + '/socketapi/suggest',
    pathwayanalysis: DOMAIN + '/socketapi/pathwayanalysis',
    geneprediction: DOMAIN + '/socketapi/geneprediction',
    genescores: DOMAIN + '/socketapi/genescores',
    genevsnetwork: DOMAIN + '/socketapi/genevsnetwork',

    prioritization: DOMAIN + '/api/v1/prioritization',

    genePage: DOMAIN + '/gene/',
    termPage: DOMAIN + '/term/',
    networkPage: DOMAIN + '/network/',

    svg2pdf: DOMAIN + '/api/v1/svg2pdf',
    tabdelim: DOMAIN + '/api/v1/tabdelim',
}

GN.pageTitleSuffix = ' - Gene Network'

var MenuBar = React.createClass({
    render: function() {
        var that = this
        var items = _.map(that.props.items, function(item, i) {
            // return (<Link key={item.name} className={'menuitem ' + (i === 0 ? 'first' : i === that.props.items.length - 1 ? 'last' : '')} to={item.route}>{item.name}</Link>)
            return (<Link key={item.name} className={'menuitem ' + (i === 0 ? 'first' : i === that.props.items.length - 1 ? 'last' : '')} to={item.route}>{item.name}</Link>)
        })
        return (
{items}
)
    }
})

var About = React.createClass({
    render: function() {
        return ({'about'})
    }
})

var How = React.createClass({

    render: function() {

        return (

1

2

3

        )
        return (
                {'how'}
        )
    }
})

var Api = React.createClass({
    render: function() {
        return (<API />)
    }
})

var GeneMain = React.createClass({
    render: function() {
        return (
perhaps gene list ?
)
    }
})

var Landing = React.createClass({

    mixins: [ReactRouter.History],

    getInitialState: function() {
        return {}
    },

    componentWillReceiveProps: function() {
        //this.loadData()
    },

    componentDidMount: function() {
      //this.loadData()
    },

    // TODO socket listener
    getSuggestions: function(input, callback) {
        if (!input || input.length < 2) {
            return callback(null, {})
        }
        var ts = new Date()
        io.socket.get(GN.urls.suggest,
                      {
                          q: input
                      },
                      function(res, jwres) {
                          var options = _.map(res, function(o) {
                              return {value: o.text, label: o.text}
                          })
                          console.debug('%d ms suggest: %d options', new Date() - ts, res.length)
                          callback(null, {options: options, complete: true})
                      })
        io.socket.on('suggestions', function(msg) {
            console.debug('%d ms socket suggest: %d options', new Date() - ts, msg.length)
        })
    },

    onSelectChange: function(value, options) {
        console.log('select ' + value)
    },

    onLogoClick: function() {
        this.history.pushState(null, '/')
    },

    render: function() {

        var topSearch = (
)
        var topBanner = null
        if (_.size(this.props.params) === 0) {
            topBanner = (

                          Predict gene functions. Discover novel disease genes.

                         <Select
                         name='search'
                         value={'Search here'}
                         matchPos='any'
                         matchProp='label'
                         placeholder=''
                         autoload={false}
                         asyncOptions={this.getSuggestions}
                         onChange={this.onSelectChange} />

For example:
                          <Link className='clickable' title='MYOM1' to='/gene/MYOM1'>MYOM1</Link>,
                          <Link className='clickable' title='Interferon signaling' to='/term/REACTOME_INTERFERON_SIGNALING'>Interferon signaling</Link>,
                          <Link className='clickable' title='Schizophrenia' to='network' params={{ids: 'Schizophrenia'}}>Schizophrenia</Link>

)
        } else {
            topSearch = (

                         <Select name='search' value={'Search here'}
                         matchProp='label' placeholder='' autoload={false} asyncOptions={this.getSuggestions} onChange={this.onSelectChange} />

)
        }
        var that = this
        // 'Enter your search or paste a gene list here'
        return (

                <Logo w={33} h={60} mirrored={true} style={{float: 'left', paddingRight: '10px'}} />

                GENE
NETWORK

                {topSearch}
                <MenuBar items={GN.menuItems} style={{backgroundColor: color.colors.gnwhite, padding: '20px'}} />

                {topBanner}
                {this.props.children}

        )
    }
})

var FormMixin = {
    handleSubmit: function(e) {
        e.preventDefault()
        var query = this.refs.query.getDOMNode().value.trim()
        console.log(e)
        if (query) {
            this.props.onQuerySubmit(query)
        }
    },
}

var SearchFormTextField = React.createClass({

    mixins: [FormMixin],

    render: function() {
        return (<form className='searchform' onSubmit={this.handleSubmit}>
                  <input type='text' placeholder={this.props.placeholder} ref='query' defaultValue=''></input>
                  <input type='submit' value='Go!'></input>
                </form>)
    }
})

var SearchFormTextArea = React.createClass({

    mixins: [FormMixin],

    render: function() {
        return (<form className='textareasearchform' onSubmit={this.handleSubmit}>
                <textarea id='manytextarea' placeholder={this.props.placeholder} ref='query' defaultValue={this.props.ids} />

<input className='gobutton' type='submit' value='Go!' />

                </form>)
    }
})

GN.routes = (
        <Route path='/' component = {Landing}>
        <Route path='/how' component = {How} />
        <Route path='/about' component = {About} />
        <Route path='/api' component = {Api} />
        <Route path='/gene/:geneId' component={Gene} />
        <Route path='/term/:termId' component = {Term} />
        <Route path='/network/:ids' component = {ManyGenesMaster} />
        <Route path='/ontology/:id' component = {Ontology} />
        <Route path='/diagnosis/:id' component = {Diagnosis} />
        </Route>
)

var history = createBrowserHistory()
ReactDOM.render(<Router history={history}>
                {GN.routes}
                </Router>,
                document.getElementById('reactcontainer')
               )
<commit_msg>Changed colors organs (gray inbetween)<commit_after>'use strict'

var DOMAIN = 'http://molgenis58.target.rug.nl'

var _ = require('lodash')
var color = require('../js/color')
var htmlutil = require('./htmlutil')

var React = require('react')
var ReactDOM = require('react-dom')
var ReactRouter = require('react-router')
var Router = ReactRouter.Router
var Route = ReactRouter.Route
var Link = ReactRouter.Link
var createBrowserHistory = require('history/lib/createBrowserHistory')

var Select = require('react-select')
var DocumentTitle = require('react-document-title')

var Logo = require('./ReactComponents/Logo')
var API = require('./ReactComponents/API')
var ManyGenesMaster = require('./ReactComponents/ManyGenesMaster')
var Gene = require('./ReactComponents/Gene/Gene')
var Term = require('./ReactComponents/Term')
var Ontology = require('./ReactComponents/Ontology')
var Diagnosis = require('./ReactComponents/Diagnosis')
var Footer = require('./ReactComponents/Footer')

var GN = {}
window.GN = GN
GN.menuItems = [{
    name: 'HOME',
    route: '/'
}, {
    name: 'HOW IT WORKS',
    route: '/how'
}, {
    name: 'ABOUT',
    route: '/about'
}, {
    name: 'API',
    route: '/api'
}]

GN.urls = {

    main: DOMAIN,
    gene: DOMAIN + '/api/v1/gene',
    pathway: DOMAIN + '/api/v1/pathway',
    coregulation: DOMAIN + '/api/v1/coregulation',
    tissues: DOMAIN + '/api/v1/tissues',
    cofunction: DOMAIN + '/api/v1/cofunction',
    pc: DOMAIN + '/api/v1/pc',

    suggest: DOMAIN + '/socketapi/suggest',
    pathwayanalysis: DOMAIN + '/socketapi/pathwayanalysis',
    geneprediction: DOMAIN + '/socketapi/geneprediction',
    genescores: DOMAIN + '/socketapi/genescores',
    genevsnetwork: DOMAIN + '/socketapi/genevsnetwork',

    prioritization: DOMAIN + '/api/v1/prioritization',

    genePage: DOMAIN + '/gene/',
    termPage: DOMAIN + '/term/',
    networkPage: DOMAIN + '/network/',

    svg2pdf: DOMAIN + '/api/v1/svg2pdf',
    tabdelim: DOMAIN + '/api/v1/tabdelim',
}

GN.pageTitleSuffix = ' - Gene Network'

var MenuBar = React.createClass({
    render: function() {
        var that = this
        var items = _.map(that.props.items, function(item, i) {
            // return (<Link key={item.name} className={'menuitem ' + (i === 0 ? 'first' : i === that.props.items.length - 1 ? 'last' : '')} to={item.route}>{item.name}</Link>)
            return (<Link key={item.name} className={'menuitem ' + (i === 0 ? 'first' : i === that.props.items.length - 1 ? 'last' : '')} to={item.route}>{item.name}</Link>)
        })
        return (
{items}
)
    }
})

var About = React.createClass({
    render: function() {
        return ({'about'})
    }
})

var How = React.createClass({

    render: function() {

        return (

1

2

3

        )
        return (
                {'how'}
        )
    }
})

var Api = React.createClass({
    render: function() {
        return (<API />)
    }
})

var GeneMain = React.createClass({
    render: function() {
        return (
perhaps gene list ?
)
    }
})

var Landing = React.createClass({

    mixins: [ReactRouter.History],

    getInitialState: function() {
        return {}
    },

    componentWillReceiveProps: function() {
        //this.loadData()
    },

    componentDidMount: function() {
      //this.loadData()
    },

    // TODO socket listener
    getSuggestions: function(input, callback) {
        if (!input || input.length < 2) {
            return callback(null, {})
        }
        var ts = new Date()
        io.socket.get(GN.urls.suggest,
                      {
                          q: input
                      },
                      function(res, jwres) {
                          var options = _.map(res, function(o) {
                              return {value: o.text, label: o.text}
                          })
                          console.debug('%d ms suggest: %d options', new Date() - ts, res.length)
                          callback(null, {options: options, complete: true})
                      })
        io.socket.on('suggestions', function(msg) {
            console.debug('%d ms socket suggest: %d options', new Date() - ts, msg.length)
        })
    },

    onSelectChange: function(value, options) {
        console.log('select ' + value)
    },

    onLogoClick: function() {
        this.history.pushState(null, '/')
    },

    render: function() {

        var topSearch = (
)
        var topBanner = null
        if (_.size(this.props.params) === 0) {
            topBanner = (

                          Predict gene functions. Discover novel disease genes.

                         <Select
                         name='search'
                         value={'Search here'}
                         matchPos='any'
                         matchProp='label'
                         placeholder=''
                         autoload={false}
                         asyncOptions={this.getSuggestions}
                         onChange={this.onSelectChange} />

For example:
                          <Link className='clickable' title='MYOM1' to='/gene/MYOM1'>MYOM1</Link>,
                          <Link className='clickable' title='Interferon signaling' to='/term/REACTOME_INTERFERON_SIGNALING'>Interferon signaling</Link>,
                          <Link className='clickable' title='Schizophrenia' to='network' params={{ids: 'Schizophrenia'}}>Schizophrenia</Link>

)
        } else {
            topSearch = (

                         <Select name='search' value={'Search here'}
                         matchProp='label' placeholder='' autoload={false} asyncOptions={this.getSuggestions} onChange={this.onSelectChange} />

)
        }
        var that = this
        // 'Enter your search or paste a gene list here'
        return (

                <Logo w={33} h={60} mirrored={true} style={{float: 'left', paddingRight: '10px'}} />

                GENE
NETWORK

                {topSearch}
                <MenuBar items={GN.menuItems} style={{backgroundColor: color.colors.gnwhite, padding: '20px'}} />

                {topBanner}
                {this.props.children}

        )
    }
})

var FormMixin = {
    handleSubmit: function(e) {
        e.preventDefault()
        var query = this.refs.query.getDOMNode().value.trim()
        console.log(e)
        if (query) {
            this.props.onQuerySubmit(query)
        }
    },
}

var SearchFormTextField = React.createClass({

    mixins: [FormMixin],

    render: function() {
        return (<form className='searchform' onSubmit={this.handleSubmit}>
                  <input type='text' placeholder={this.props.placeholder} ref='query' defaultValue=''></input>
                  <input type='submit' value='Go!'></input>
                </form>)
    }
})

var SearchFormTextArea = React.createClass({

    mixins: [FormMixin],

    render: function() {
        return (<form className='textareasearchform' onSubmit={this.handleSubmit}>
                <textarea id='manytextarea' placeholder={this.props.placeholder} ref='query' defaultValue={this.props.ids} />

<input className='gobutton' type='submit' value='Go!' />

                </form>)
    }
})

GN.routes = (
        <Route path='/' component = {Landing}>
        <Route path='/how' component = {How} />
        <Route path='/about' component = {About} />
        <Route path='/api' component = {Api} />
        <Route path='/gene/:geneId' component={Gene} />
        <Route path='/term/:termId' component = {Term} />
        <Route path='/network/:ids' component = {ManyGenesMaster} />
        <Route path='/ontology/:id' component = {Ontology} />
        <Route path='/diagnosis/:id' component = {Diagnosis} />
        </Route>
)

var history = createBrowserHistory()
ReactDOM.render(<Router history={history}>
                {GN.routes}
                </Router>,
                document.getElementById('reactcontainer')
               )
<|endoftext|>


<commit_before>var apiURL = typeof (apiURL) == 'undefined' ? 'http://localhost:8080/' : apiURL

var app = new Vue({
  el: '#app',
  data: {
    queries: [],
    numDomains: 0,
    blocked: 0,
    percentageBlocked: 0,
    loading: true,
    loadingText: "loading data...",
    active: false,
    timeout: 300,
    highWater: -1,
    autoUpdate: false,
    autoUpdateId: 0,
  },
  created: function () {
    this.fetchQueries()
    this.fetchDomains()
    this.getActive()
    //this.pollActive()
  },
  methods: {
    fetchQueriesIncremental: function () {
      var self = this
      $.get(apiURL + 'questioncache?highWater=' + self.highWater, function (data) {
        // the second check is a rough way to drop the data if we keep getting the whole list
        // which would happen if the server does not support the highWater parameter
        if (data.items.length > 0 && data.items.length != self.queries.length) {
          data.items.reverse()
          self.queries = data.items.concat(self.queries)
          self.generateStats()
        }
      })
    },
    fetchQueries: function () {
      var self = this
      $.get(apiURL + 'questioncache', function (data) {
        data.items.reverse()
        self.queries = data.items
        self.generateStats()
      })
    },
    fetchDomains: function () {
      var self = this
      $.get(apiURL + 'blockcache/length', function (data) {
        self.numDomains = data.length
      })
    },
    generateStats: function () {
      var self = this
      var blocked = []

      if (self.queries) {
        self.queries.forEach(function (item, index) {
          var key = item.query.name + '-' + item.query.type
          if (item.blocked && blocked.indexOf(key) == -1) {
            blocked.push(key)
          }
          if (item.date >= self.highWater) {
            self.highWater = item.date
          }
        })
      }

      self.blocked = blocked.length > 0 ? blocked.length : 0
      self.percentageBlocked = (self.queries ) ? (blocked.length / self.queries.length * 100) : 0

      if (self.queries) {
        self.generateChart()
      } else {
        self.loading = false
      }
    },
    generateChart: function () {
      var self = this
      var cols = []
      var clients = []
      var xPlot = ['x']
      var labels = {}

      self.queries.forEach(function (item) {
        var d = new Date(item.date * 1000)
        var hour = Math.floor(item.date / 3600)
        var tag = d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear() + ' ' + d.getHours()

        if (clients[item.client]) {
          if (clients[item.client].hours[hour]) {
            clients[item.client].hours[hour]++
          } else {
            clients[item.client].hours[hour] = 1
          }
        } else {
          clients[item.client] = {
            hours: []
          }
        }

        if (xPlot.indexOf(hour) == -1) {
          xPlot.push(hour)
          labels[hour] = tag
        }
      })

      cols.push(xPlot)

      for (var i in clients) {
        var obj = clients[i]
        var newYPlot = [i]
        obj.hours.forEach(function (num) {
          newYPlot.push(num)
        })
        Array.prototype.push.apply(cols, [newYPlot])
      }

      var chart = c3.generate({
        bindto: '#chart',
        padding: {
          right: 50
        },
        data: {
          x: 'x',
          columns: cols
        },
        axis: {
          x: {
            label: {
              text: 'time',
              position: 'outer-middle'
            },
            tick: {
              format: function (hour) { return labels[hour]; }
            }
          },
          y: {
            label: {
              text: 'queries',
              position: 'outer-middle'
            }
          }
        }
      })

      self.loading = false
      $('#chart').show()
    },
    clearCache: function () {
      var self = this
      self.loadingText = "clearing cache..."
      self.loading = true
      $('#chart').hide()
      $.get(apiURL + 'questioncache/clear', function (data) {
        self.fetchQueries()
      })
    },
    getActive: function () {
      var self = this
      $.get(apiURL + 'application/active', function (data) {
        self.active = data.active
      })
    },
    setActive: function (state) {
      var self = this
      state = state ? "On" : "Off"
      $.ajax({
        url: apiURL + 'application/active?v=1&state=' + state,
        type: 'PUT',
        success: function (data) {
          self.active = data.active
        }
      })
    },
    snooze: function () {
      var self = this
      $.ajax({
        url: apiURL + 'application/active?v=1&state=Snooze&timeout=' + self.timeout,
        type: 'PUT',
        success: function (data) {
          self.active = data.active
        }
      })
    },
    reload_config: function () {
      var self = this
      $.ajax({
        url: apiURL + 'blocklist/update',
        type: 'POST',
      })
    },
    pollActive: function () {
      var self = this
      setInterval(self.getActive, 1000)
    },
    toggle_autoupdate: function () {
      var self = this
      self.autoUpdate = !self.autoUpdate
      if (self.autoUpdate == true) {
        self.autoUpdateId = setInterval(function () {
          self.fetchQueriesIncremental()
        }.bind(self), 1000);
      } else {
        if (self.autoUpdateId != 0) {
          clearInterval(self.autoUpdateId)
        }
      }
    }
  }
})

Vue.filter('formatUnix', function (value) {
  var d = new Date(value * 1000),
    yyyy = d.getFullYear().toString().substr(2, 2),
    mm = ('0' + (d.getMonth() + 1)).slice(-2),
    dd = ('0' + d.getDate()).slice(-2),
    hh = d.getHours(),
    h = hh,
    min = ('0' + d.getMinutes()).slice(-2),
    ampm = 'am',
    time

  if (hh > 12) {
    h = hh - 12
    ampm = 'pm'
  } else if (hh === 12) {
    h = 12
    ampm = 'pm'
  } else if (hh == 0) {
    h = 12
  }

  return time = mm + '/' + dd + '/' + yyyy + ' ' + h + ':' + min + ' ' + ampm;
})
<commit_msg>Higher time resolution for the graph<commit_after>var apiURL = typeof (apiURL) == 'undefined' ? 'http://localhost:8080/' : apiURL

var minutes_per_interval = 5
function getInterval(timestamp) {
  return Math.floor(timestamp / 3600 * (60 / minutes_per_interval))
}
var app = new Vue({
  el: '#app',
  data: {
    queries: [],
    numDomains: 0,
    blocked: 0,
    percentageBlocked: 0,
    loading: true,
    loadingText: "loading data...",
    active: false,
    timeout: 300,
    highWater: -1,
    autoUpdate: false,
    autoUpdateId: 0,
  },
  created: function () {
    this.fetchQueries()
    this.fetchDomains()
    this.getActive()
    //this.pollActive()
  },
  methods: {
    fetchQueriesIncremental: function () {
      var self = this
      $.get(apiURL + 'questioncache?highWater=' + self.highWater, function (data) {
        // the second check is a rough way to drop the data if we keep getting the whole list
        // which would happen if the server does not support the highWater parameter
        if (data.items.length > 0 && data.items.length != self.queries.length) {
          data.items.reverse()
          self.queries = data.items.concat(self.queries)
          self.generateStats()
        }
      })
    },
    fetchQueries: function () {
      var self = this
      $.get(apiURL + 'questioncache', function (data) {
        data.items.reverse()
        self.queries = data.items
        self.generateStats()
      })
    },
    fetchDomains: function () {
      var self = this
      $.get(apiURL + 'blockcache/length', function (data) {
        self.numDomains = data.length
      })
    },
    generateStats: function () {
      var self = this
      var blocked = []

      if (self.queries) {
        self.queries.forEach(function (item, index) {
          var key = item.query.name + '-' + item.query.type
          if (item.blocked && blocked.indexOf(key) == -1) {
            blocked.push(key)
          }
          if (item.date >= self.highWater) {
            self.highWater = item.date
          }
        })
      }

      self.blocked = blocked.length > 0 ? blocked.length : 0
      self.percentageBlocked = (self.queries) ? (blocked.length / self.queries.length * 100) : 0

      if (self.queries) {
        self.generateChart()
      } else {
        self.loading = false
      }
    },
    generateChart: function () {
      var self = this
      var cols = []
      var clients = []
      var xPlot = ['x']
      var labels = {}
      var firstPoint = null

      self.queries.forEach(function (item) {
        var d = new Date(item.date * 1000)
        var interval = getInterval(item.date)

        if (clients[item.client]) {
          if (clients[item.client].intervals[interval]) {
            clients[item.client].intervals[interval]++
          } else {
            clients[item.client].intervals[interval] = 1
          }
        } else {
          clients[item.client] = {
            intervals: []
          }
        }

        if (firstPoint == null || firstPoint > item.date) {
          firstPoint = item.date
        }
        if (xPlot.indexOf(interval) == -1) {
          xPlot.push(interval)
          minutes = minutes_per_interval * Math.floor(d.getMinutes() / minutes_per_interval)
          if (d.getHours() == 0 && minutes == 0) {
            var tag = d.getDate() + '/' + (d.getMonth() + 1)
          } else if (minutes == 0) {
            var tag = d.getHours() + ":00"
          } else {
            var tag = ":" + minutes
          }
          labels[interval] = tag
        }
      })

      var d = new Date(firstPoint * 1000)
      minutes = minutes_per_interval * Math.floor(d.getMinutes() / minutes_per_interval)
      var tag = d.getDate() + '/' + (d.getMonth() + 1) + ' ' + d.getHours() + ":" + minutes
      var pos = getInterval(firstPoint)
      labels[pos] = tag

      cols.push(xPlot)

      for (var i in clients) {
        var obj = clients[i]
        var newYPlot = [i]
        obj.intervals.forEach(function (num) {
          newYPlot.push(num)
        })
        Array.prototype.push.apply(cols, [newYPlot])
      }

      var chart = c3.generate({
        bindto: '#chart',
        padding: {
          right: 50
        },
        data: {
          x: 'x',
          columns: cols
        },
        axis: {
          x: {
            label: {
              text: 'time',
              position: 'outer-middle'
            },
            tick: {
              format: function (hour) { return labels[hour]; }
            }
          },
          y: {
            label: {
              text: 'queries',
              position: 'outer-middle'
            }
          }
        }
      })

      self.loading = false
      $('#chart').show()
    },
    clearCache: function () {
      var self = this
      self.loadingText = "clearing cache..."
      self.loading = true
      $('#chart').hide()
      $.get(apiURL + 'questioncache/clear', function (data) {
        self.fetchQueries()
      })
    },
    getActive: function () {
      var self = this
      $.get(apiURL + 'application/active', function (data) {
        self.active = data.active
      })
    },
    setActive: function (state) {
      var self = this
      state = state ? "On" : "Off"
      $.ajax({
        url: apiURL + 'application/active?v=1&state=' + state,
        type: 'PUT',
        success: function (data) {
          self.active = data.active
        }
      })
    },
    snooze: function () {
      var self = this
      $.ajax({
        url: apiURL + 'application/active?v=1&state=Snooze&timeout=' + self.timeout,
        type: 'PUT',
        success: function (data) {
          self.active = data.active
        }
      })
    },
    reload_config: function () {
      var self = this
      $.ajax({
        url: apiURL + 'blocklist/update',
        type: 'POST',
      })
    },
    pollActive: function () {
      var self = this
      setInterval(self.getActive, 1000)
    },
    toggle_autoupdate: function () {
      var self = this
      self.autoUpdate = !self.autoUpdate
      if (self.autoUpdate == true) {
        self.autoUpdateId = setInterval(function () {
          self.fetchQueriesIncremental()
        }.bind(self), 1000);
      } else {
        if (self.autoUpdateId != 0) {
          clearInterval(self.autoUpdateId)
        }
      }
    }
  }
})

Vue.filter('formatUnix', function (value) {
  var d = new Date(value * 1000),
    yyyy = d.getFullYear().toString().substr(2, 2),
    mm = ('0' + (d.getMonth() + 1)).slice(-2),
    dd = ('0' + d.getDate()).slice(-2),
    hh = d.getHours(),
    h = hh,
    min = ('0' + d.getMinutes()).slice(-2),
    ampm = 'am',
    time

  if (hh > 12) {
    h = hh - 12
    ampm = 'pm'
  } else if (hh === 12) {
    h = 12
    ampm = 'pm'
  } else if (hh == 0) {
    h = 12
  }

  return time = mm + '/' + dd + '/' + yyyy + ' ' + h + ':' + min + ' ' + ampm;
})
<|endoftext|>


<commit_before>#!/usr/node/bin/node
// Copyright (c) 2013, Joyent, Inc. All rights reserved.

/* BEGIN JSSTYLED */
/*
 * sample muskie audit record
 *
 * {
 *   "name": "audit",
 *   "hostname": "fb07e9ec-5137-418e-aff2-01d00aff1a49",
 *   "pid": 4400,
 *   "audit": true,
 *   "level": 30,
 *   "remoteAddress": "10.2.201.70",
 *   "remotePort": 36387,
 *   "reqHeaderLength": 818,
 *   "req": {
 *     "method": "PUT",
 *     "url": "/poseidon/stor/graphs/assets/manowar.tar.gz",
 *     "headers": {
 *       "accept": "application/json",
 *       "content-length": "6880413",
 *       "content-type": "application/octet-stream",
 *       "date": "Wed, 28 Nov 2012 21:46:00 GMT",
 *       "expect": "100-continue",
 *       "x-request-id": "cbc3e1ce-f863-4942-839b-1d30542ad31d",
 *       "x-durability-level": "2",
 *       "authorization": ELIDED FOR READABILITY
 *       "user-agent": "restify/1.0 (ia32-sunos; v8/3.11.10.22; OpenSSL/0.9.8w) node/0.8.12",
 *       "accept-version": "~1.0",
 *       "host": "manta.joyent.us",
 *       "connection": "keep-alive",
 *       "x-forwarded-for": "10.2.201.57"
 *     },
 *     "httpVersion": "1.1",
 *     "trailers": {},
 *     "owner": "eba7f07c-d57c-48f6-8072-f75db963e9d6"
 *   },
 *   "resHeaderLength": 241,
 *   "res": {
 *     "statusCode": 204,
 *     "headers": {
 *       "etag": "d5c7ee35-e232-4bb9-b239-1ef93daffcaf",
 *       "last-modified": "Wed, 28 Nov 2012 21:46:00 GMT",
 *       "date": "Wed, 28 Nov 2012 21:46:00 GMT",
 *       "server": "Manta",
 *       "x-request-id": "cbc3e1ce-f863-4942-839b-1d30542ad31d",
 *       "x-response-time": 212,
 *       "x-server-name": "fb07e9ec-5137-418e-aff2-01d00aff1a49"
 *     },
 *     "trailer": false
 *   },
 *   "latency": 212,
 *   "_audit": true,
 *   "msg": "handled: 204",
 *   "time": "2012-11-28T21:46:00.933Z",
 *   "v": 0
 * }
 */

/*
 * sample GET record req and res
 *
 * "req": {
 *   "method": "GET",
 *   "url": "/poseidon/stor/manta_gc/moray?limit=1024",
 *   "headers": {
 *     "accept": "application/x-json-stream",
 *     "date": "Wed, 28 Nov 2012 21:49:01 GMT",
 *     "x-request-id": "2e878928-eaf3-4ce2-8922-62d604d04c9c",
 *     "authorization": ELIDED FOR READABILITY
 *     "user-agent": "restify/1.0 (ia32-sunos; v8/3.11.10.22; OpenSSL/0.9.8w) node/0.8.12",
 *     "accept-version": "~1.0",
 *     "host": "manta.joyent.us",
 *     "connection": "close",
 *     "x-forwarded-for": "10.2.201.57"
 *   },
 *   "httpVersion": "1.1",
 *   "trailers": {},
 *   "owner": "eba7f07c-d57c-48f6-8072-f75db963e9d6"
 * },
 * "res": {
 *   "statusCode": 404,
 *   "headers": {
 *     "content-type": "application/json",
 *     "content-length": 83,
 *     "content-md5": "fP8EF/9kmhUAFV1y+WkEEA==",
 *     "date": "Wed, 28 Nov 2012 21:49:01 GMT",
 *     "server": "Manta",
 *     "x-request-id": "2e878928-eaf3-4ce2-8922-62d604d04c9c",
 *     "x-response-time": 8,
 *     "x-server-name": "fb07e9ec-5137-418e-aff2-01d00aff1a49"
 *   },
 *   "trailer": false
 * },
 */
/* END JSSTYLED */

var mod_carrier = require('carrier');
var Big = require('big.js');
var ERROR = false;

var LOG = require('bunyan').createLogger({
        name: 'request-map.js',
        stream: process.stderr,
        level: process.env['LOG_LEVEL'] || 'info'
});

function shouldProcess(record) {
        return (record.audit &&
                record.req.url !== '/ping' &&
                typeof (record.req.owner) !== 'undefined');
}

function okStatus(code) {
        return (code >= 200 && code <= 204);
}

function count(record, aggr) {
        var owner = record.req.owner;
        var operation = record.billable_operation;
        var method = record.req.method;
        var resHeaderLength = record.resHeaderLength;
        var reqHeaderLength = record.reqHeaderLength;
        var statusCode = record.res.statusCode;

        // get the content-length if it exists
        var contentLength = +record.res.headers['content-length'] ||
                +record.req.headers['content-length'] || 0;

        aggr[owner] = aggr[owner] || {
                owner: owner,
                requests: {
                        type: {
                                DELETE: 0,
                                GET: 0,
                                HEAD: 0,
                                LIST: 0,
                                OPTIONS: 0,
                                POST: 0,
                                PUT: 0
                        },
                        bandwidth: {
                                in: new Big(0),
                                out: new Big(0),
                                headerIn: new Big(0),
                                headerOut: new Big(0)
                        }
                }
        };

        if (operation) {
                aggr[owner].requests.type[operation]++;
        }

        var bw = aggr[owner].requests.bandwidth;
        bw.headerIn = bw.headerIn.plus(reqHeaderLength);
        bw.headerOut = bw.headerOut.plus(resHeaderLength);

        // only count bandwidth for successful GET & PUT
        if (method === 'GET' && okStatus(statusCode)) {
                bw.out = bw.out.plus(contentLength);
        }

        if (method === 'PUT' && okStatus(statusCode)) {
                bw.in = bw.in.plus(contentLength);
        }
}

function printResults(aggr) {
        Object.keys(aggr).forEach(function (owner) {
                console.log(JSON.stringify(aggr[owner], function (key, value) {
                        if (value instanceof Big) {
                                return (value.toString());
                        }
                        return (value);
                }));
        });
}

function main() {
        var carry = mod_carrier.carry(process.openStdin());
        var aggr = {};
        var lineCount = 0;
        carry.on('line', function onLine(line) {
                lineCount++;
                var record;

                // since bunyan logs may contain lines such as
                // [ Nov 28 21:35:27 Enabled. ]
                // we need to ignore them
                if (line[0] != '{') {
                        return;
                }

                try {
                        record = JSON.parse(line);
                } catch (e) {
                        LOG.error(e, 'Error on line ' + lineCount);
                        ERROR = true;
                        return;
                }

                // only process audit records, and ignore pings
                if (!shouldProcess(record)) {
                        return;
                }

                count(record, aggr);
        });

        carry.once('end', function onEnd() {
                printResults(aggr);
        });
}
main();
<commit_msg>handle empty headers block<commit_after>#!/usr/node/bin/node
// Copyright (c) 2013, Joyent, Inc. All rights reserved.

/* BEGIN JSSTYLED */
/*
 * sample muskie audit record
 *
 * {
 *   "name": "audit",
 *   "hostname": "fb07e9ec-5137-418e-aff2-01d00aff1a49",
 *   "pid": 4400,
 *   "audit": true,
 *   "level": 30,
 *   "remoteAddress": "10.2.201.70",
 *   "remotePort": 36387,
 *   "reqHeaderLength": 818,
 *   "req": {
 *     "method": "PUT",
 *     "url": "/poseidon/stor/graphs/assets/manowar.tar.gz",
 *     "headers": {
 *       "accept": "application/json",
 *       "content-length": "6880413",
 *       "content-type": "application/octet-stream",
 *       "date": "Wed, 28 Nov 2012 21:46:00 GMT",
 *       "expect": "100-continue",
 *       "x-request-id": "cbc3e1ce-f863-4942-839b-1d30542ad31d",
 *       "x-durability-level": "2",
 *       "authorization": ELIDED FOR READABILITY
 *       "user-agent": "restify/1.0 (ia32-sunos; v8/3.11.10.22; OpenSSL/0.9.8w) node/0.8.12",
 *       "accept-version": "~1.0",
 *       "host": "manta.joyent.us",
 *       "connection": "keep-alive",
 *       "x-forwarded-for": "10.2.201.57"
 *     },
 *     "httpVersion": "1.1",
 *     "trailers": {},
 *     "owner": "eba7f07c-d57c-48f6-8072-f75db963e9d6"
 *   },
 *   "resHeaderLength": 241,
 *   "res": {
 *     "statusCode": 204,
 *     "headers": {
 *       "etag": "d5c7ee35-e232-4bb9-b239-1ef93daffcaf",
 *       "last-modified": "Wed, 28 Nov 2012 21:46:00 GMT",
 *       "date": "Wed, 28 Nov 2012 21:46:00 GMT",
 *       "server": "Manta",
 *       "x-request-id": "cbc3e1ce-f863-4942-839b-1d30542ad31d",
 *       "x-response-time": 212,
 *       "x-server-name": "fb07e9ec-5137-418e-aff2-01d00aff1a49"
 *     },
 *     "trailer": false
 *   },
 *   "latency": 212,
 *   "_audit": true,
 *   "msg": "handled: 204",
 *   "time": "2012-11-28T21:46:00.933Z",
 *   "v": 0
 * }
 */

/*
 * sample GET record req and res
 *
 * "req": {
 *   "method": "GET",
 *   "url": "/poseidon/stor/manta_gc/moray?limit=1024",
 *   "headers": {
 *     "accept": "application/x-json-stream",
 *     "date": "Wed, 28 Nov 2012 21:49:01 GMT",
 *     "x-request-id": "2e878928-eaf3-4ce2-8922-62d604d04c9c",
 *     "authorization": ELIDED FOR READABILITY
 *     "user-agent": "restify/1.0 (ia32-sunos; v8/3.11.10.22; OpenSSL/0.9.8w) node/0.8.12",
 *     "accept-version": "~1.0",
 *     "host": "manta.joyent.us",
 *     "connection": "close",
 *     "x-forwarded-for": "10.2.201.57"
 *   },
 *   "httpVersion": "1.1",
 *   "trailers": {},
 *   "owner": "eba7f07c-d57c-48f6-8072-f75db963e9d6"
 * },
 * "res": {
 *   "statusCode": 404,
 *   "headers": {
 *     "content-type": "application/json",
 *     "content-length": 83,
 *     "content-md5": "fP8EF/9kmhUAFV1y+WkEEA==",
 *     "date": "Wed, 28 Nov 2012 21:49:01 GMT",
 *     "server": "Manta",
 *     "x-request-id": "2e878928-eaf3-4ce2-8922-62d604d04c9c",
 *     "x-response-time": 8,
 *     "x-server-name": "fb07e9ec-5137-418e-aff2-01d00aff1a49"
 *   },
 *   "trailer": false
 * },
 */
/* END JSSTYLED */

var mod_carrier = require('carrier');
var Big = require('big.js');
var ERROR = false;

var LOG = require('bunyan').createLogger({
        name: 'request-map.js',
        stream: process.stderr,
        level: process.env['LOG_LEVEL'] || 'info'
});

function shouldProcess(record) {
        return (record.audit &&
                record.req.url !== '/ping' &&
                typeof (record.req.owner) !== 'undefined');
}

function okStatus(code) {
        return (code >= 200 && code <= 204);
}

function count(record, aggr) {
        var owner = record.req.owner;
        var operation = record.billable_operation;
        var method = record.req.method;
        var resHeaderLength = record.resHeaderLength;
        var reqHeaderLength = record.reqHeaderLength;
        var statusCode = record.res.statusCode;

        // get the content-length if it exists
        var contentLength = 0;
        if (record.res.headers && record.res.headers['content-length']) {
                contentLength = +record.res.headers['content-length'];
        } else if (record.req.headers && record.req.headers['content-length']) {
                contentLength = +record.req.headers['content-length'];
        }

        aggr[owner] = aggr[owner] || {
                owner: owner,
                requests: {
                        type: {
                                DELETE: 0,
                                GET: 0,
                                HEAD: 0,
                                LIST: 0,
                                OPTIONS: 0,
                                POST: 0,
                                PUT: 0
                        },
                        bandwidth: {
                                in: new Big(0),
                                out: new Big(0),
                                headerIn: new Big(0),
                                headerOut: new Big(0)
                        }
                }
        };

        if (operation) {
                aggr[owner].requests.type[operation]++;
        }

        var bw = aggr[owner].requests.bandwidth;
        bw.headerIn = bw.headerIn.plus(reqHeaderLength);
        bw.headerOut = bw.headerOut.plus(resHeaderLength);

        // only count bandwidth for successful GET & PUT
        if (method === 'GET' && okStatus(statusCode)) {
                bw.out = bw.out.plus(contentLength);
        }

        if (method === 'PUT' && okStatus(statusCode)) {
                bw.in = bw.in.plus(contentLength);
        }
}

function printResults(aggr) {
        Object.keys(aggr).forEach(function (owner) {
                console.log(JSON.stringify(aggr[owner], function (key, value) {
                        if (value instanceof Big) {
                                return (value.toString());
                        }
                        return (value);
                }));
        });
}

function main() {
        var carry = mod_carrier.carry(process.openStdin());
        var aggr = {};
        var lineCount = 0;
        carry.on('line', function onLine(line) {
                lineCount++;
                var record;

                // since bunyan logs may contain lines such as
                // [ Nov 28 21:35:27 Enabled. ]
                // we need to ignore them
                if (line[0] != '{') {
                        return;
                }

                try {
                        record = JSON.parse(line);
                } catch (e) {
                        LOG.error(e, 'Error on line ' + lineCount);
                        ERROR = true;
                        return;
                }

                // only process audit records, and ignore pings
                if (!shouldProcess(record)) {
                        return;
                }

                count(record, aggr);
        });

        carry.once('end', function onEnd() {
                printResults(aggr);
        });
}
main();
<|endoftext|>


<commit_before>$( document ).ready(function() {

  $('a[href$="portfolio.html"]').on('click', function(event) {
		$('.home').remove();
		event.preventDefault();
		$(".below-head").load("portfolio.html .portfolio");
	});

	$('a[href$="contact.html"]').on('click', function(event) {
		$('.home').remove();
		event.preventDefault();
		$(".below-head").load("contact.html .contact");
	});
	$('a[href$="index.html"]').on('click', function(event) {
		$('.home').remove();
		event.preventDefault();
		$(".below-head").load("index.html .home");
	});

		$('a.gallery').featherlightGallery({
    previousIcon: '&#9664',
    nextIcon: '&#965',
    galleryFadeIn: 300,

    openSpeed: 300
	});
})
<commit_msg>changed to .html<commit_after>$( document ).ready(function() {

  $('a[href$="portfolio.html"]').on('click', function(event) {
		$('.home').remove();
		event.preventDefault();
		$(".below-head").html("portfolio.html .portfolio");
	});

	$('a[href$="contact.html"]').on('click', function(event) {
		$('.home').remove();
		event.preventDefault();
		$(".below-head").load("contact.html .contact");
	});
	$('a[href$="index.html"]').on('click', function(event) {
		$('.home').remove();
		event.preventDefault();
		$(".below-head").load("index.html .home");
	});

		$('a.gallery').featherlightGallery({
    previousIcon: '&#9664',
    nextIcon: '&#965',
    galleryFadeIn: 300,

    openSpeed: 300
	});
})
<|endoftext|>


<commit_before>function airline_init_pre() {
  prop.airline = {};
  prop.airline.airlines = {};
}

/**
 * An aircrcraft operating agency
 */
zlsa.atc.Airline = Fiber.extend(function() {
  return {
    /**
     * Create new airline
     */
    init: function (icao, options) {
      /** ICAO airline designation */
      this.icao = "YYY";

      /** Agency name */
      this.name = "Default airline";

      /** Radio callsign */
      this.callsign = 'Default';

      /** Parameters for flight number generation */
      this.flightNumberGeneration = {
        /** How many characters in the flight number */
        length: 3,
        /** Whether to use alphabetical characters */
        alpha: false,
      };

      /** Named weighted sets of aircraft */
      this.fleets = {
        default: [],
      };

      this.parse(icao, options);
    },

    /**
     * Initialize object from data
     */
    parse: function (icao, data) {
      if (data.icao)
        this.icao = data.icao;
      else
        this.icao = icao;

      this.name = data.name;
      this.callsign = data.callsign.name;
      this.flightNumberGeneration.length = data.callsign.length;
      this.flightNumberGeneration.alpha = (data.callsign.alpha === true);
      if (data.fleets)
        this.fleets = data.fleets;
      else
        this.fleets.default = data.aircraft;

      for (var f in this.fleets) {
        for (var j=0;j<this.fleets[f].length;j++) {
          this.fleets[f][j][0] = this.fleets[f][j][0].toLowerCase();
        }
      }
    },

    /**
     * Return a random ICAO aircraft designator from the given fleet
     *
     * If no fleet is specified the default fleet is used
     */
    chooseAircraft: function (fleet) {
      if (!fleet)
        fleet = 'default';

      try {
        return choose_weight(this.fleets[fleet.toLowerCase()]);
      }
      catch (e) {
        console.log("Unable to find fleet " + fleet
                    + " for airline " + this.icao);
        throw e;
      }
    },

    /**
     * Create a flight number/identifier
     */
    generateFlightNumber: function () {
      var flightNumberLength = this.flightNumberGeneration.length;
      var flightNumber = "";

      var list = "0123456789";

      // Start with a number other than zero
      flightNumber += choose(list.substr(1));

      if (this.flightNumberGeneration.alpha) {
        for (var i=0; i<flightNumberLength - 3; i++)
          flightNumber += choose(list);
        list = "abcdefghijklmnopqrstuvwxyz";
        for (var i=0; i<2; i++)
          flightNumber += choose(list);
      } else {
        for (var i=1; i<flightNumberLength;i++)
          flightNumber += choose(list);
      }
      return flightNumber;
    },

    /**
     * Checks all fleets for valid aircraft identifiers and log errors
     */
    validateFleets: function () {
      for (var f in this.fleets) {
        for (var j=0;j<this.fleets[f].length;j++) {
          if (!(this.fleets[f][j][0] in prop.aircraft.models)) {
            console.warn("Airline " + this.icao.toUpperCase()
                         + " uses nonexistent aircraft " + this.fleets[f][j][0]
                         + ", expect errors");
          }

          if (typeof this.fleets[f][j][1] != "number") {
            console.warn("Airline " + this.icao.toUpperCase()
                         + " uses non numeric weight for aircraft " +
                         this.fleets[f][j][0] + ", expect errors");
          }
        }
      }
    },
  };
});

function airline_init() {
  airline_load("AAL");
  airline_load("ACA");
  airline_load("AEA");
  airline_load("AFL");
  airline_load("AFR");
  airline_load("AIC");
  airline_load("AIRTAXI");
  airline_load("AMX");
  airline_load("ARG");
  airline_load("ASA");
  airline_load("ASQ");
  airline_load("AUA");
  airline_load("AVA");
  airline_load("AWE");
  airline_load("AWI");
  airline_load("AWQ");
  airline_load("AXB");
  airline_load("AZA");
  airline_load("AZU");
  airline_load("BAW");
  airline_load("BCY");
  airline_load("BEE");
  airline_load("BEL");
  airline_load("BER");
  airline_load("BTK");
  airline_load("BWA");
  airline_load("CCA");
  airline_load("CES");
  airline_load("CESSNA");
  airline_load("CFG");
  airline_load("CFS");
  airline_load("CPA");
  airline_load("CPZ");
  airline_load("CSN");
  airline_load("CTV");
  airline_load("CWC");
  airline_load("DAL");
  airline_load("DLH");
  airline_load("EIN");
  airline_load("EMBRAER");
  airline_load("ENY");
  airline_load("ETD");
  airline_load("EXS");
  airline_load("EVA");
  airline_load("EZY");
  airline_load("FAB");
  airline_load("FASTGA");
  airline_load("FDB");
  airline_load("FDX");
  airline_load("FFT");
  airline_load("FLG");
  airline_load("FWI");
  airline_load("GIA");
  airline_load("GJS");
  airline_load("GLO");
  airline_load("GOW");
  airline_load("GWI");
  airline_load("HAL");
  airline_load("HDA");
  airline_load("IAD");
  airline_load("IBE");
  airline_load("IGO");
  airline_load("INC");
  airline_load("JAI");
  airline_load("JAL");
  airline_load("JBU");
  airline_load("JIA");
  airline_load("KAL");
  airline_load("KAP");
  airline_load("KLC");
  airline_load("KLM");
  airline_load("LAN");
  airline_load("LIGHTGA");
  airline_load("LLR");
  airline_load("LNI");
  airline_load("MON");
  airline_load("MOV");
  airline_load("NAX");
  airline_load("NKS");
  airline_load("ONE");
  airline_load("PAA");
  airline_load("PDT");
  airline_load("QFA");
  airline_load("QXE");
  airline_load("RFF");
  airline_load("RLU");
  airline_load("RPA");
  airline_load("RYR");
  airline_load("SAS");
  airline_load("SBI");
  airline_load("SCX");
  airline_load("SEJ");
  airline_load("SJY");
  airline_load("SKW");
  airline_load("SLK");
  airline_load("SVR");
  airline_load("SWA");
  airline_load("SWR");
  airline_load("SXD");
  airline_load("TAM");
  airline_load("TCF");
  airline_load("TCX");
  airline_load("THY");
  airline_load("TOM");
  airline_load("TSO");
  airline_load("TUI");
  airline_load("TWA");
  airline_load("TYA");
  airline_load("UAE");
  airline_load("UAL");
  airline_load("UPS");
  airline_load("USAF");
  airline_load("VIR");
  airline_load("VRD");
  airline_load("VTI");
  airline_load("WIA");
  airline_load("XAX");
}

function airline_load(icao) {
  icao = icao.toLowerCase();
  new Content({
    type: "json",
    url: "assets/airlines/"+icao+".json",
    payload: icao.toLowerCase(),
    callback: function(status, data, payload) {
      if(status == "ok") {
        prop.airline.airlines[payload] = new zlsa.atc.Airline(payload, data);
      }
    }
  });
}

function airline_get(icao) {
  icao = icao.toLowerCase();
  return prop.airline.airlines[icao];
}

function airline_ready() {
  for(var i in prop.airline.airlines) {
    prop.airline.airlines[i].validateFleets();
  }
}
<commit_msg>Load QTR<commit_after>function airline_init_pre() {
  prop.airline = {};
  prop.airline.airlines = {};
}

/**
 * An aircrcraft operating agency
 */
zlsa.atc.Airline = Fiber.extend(function() {
  return {
    /**
     * Create new airline
     */
    init: function (icao, options) {
      /** ICAO airline designation */
      this.icao = "YYY";

      /** Agency name */
      this.name = "Default airline";

      /** Radio callsign */
      this.callsign = 'Default';

      /** Parameters for flight number generation */
      this.flightNumberGeneration = {
        /** How many characters in the flight number */
        length: 3,
        /** Whether to use alphabetical characters */
        alpha: false,
      };

      /** Named weighted sets of aircraft */
      this.fleets = {
        default: [],
      };

      this.parse(icao, options);
    },

    /**
     * Initialize object from data
     */
    parse: function (icao, data) {
      if (data.icao)
        this.icao = data.icao;
      else
        this.icao = icao;

      this.name = data.name;
      this.callsign = data.callsign.name;
      this.flightNumberGeneration.length = data.callsign.length;
      this.flightNumberGeneration.alpha = (data.callsign.alpha === true);
      if (data.fleets)
        this.fleets = data.fleets;
      else
        this.fleets.default = data.aircraft;

      for (var f in this.fleets) {
        for (var j=0;j<this.fleets[f].length;j++) {
          this.fleets[f][j][0] = this.fleets[f][j][0].toLowerCase();
        }
      }
    },

    /**
     * Return a random ICAO aircraft designator from the given fleet
     *
     * If no fleet is specified the default fleet is used
     */
    chooseAircraft: function (fleet) {
      if (!fleet)
        fleet = 'default';

      try {
        return choose_weight(this.fleets[fleet.toLowerCase()]);
      }
      catch (e) {
        console.log("Unable to find fleet " + fleet
                    + " for airline " + this.icao);
        throw e;
      }
    },

    /**
     * Create a flight number/identifier
     */
    generateFlightNumber: function () {
      var flightNumberLength = this.flightNumberGeneration.length;
      var flightNumber = "";

      var list = "0123456789";

      // Start with a number other than zero
      flightNumber += choose(list.substr(1));

      if (this.flightNumberGeneration.alpha) {
        for (var i=0; i<flightNumberLength - 3; i++)
          flightNumber += choose(list);
        list = "abcdefghijklmnopqrstuvwxyz";
        for (var i=0; i<2; i++)
          flightNumber += choose(list);
      } else {
        for (var i=1; i<flightNumberLength;i++)
          flightNumber += choose(list);
      }
      return flightNumber;
    },

    /**
     * Checks all fleets for valid aircraft identifiers and log errors
     */
    validateFleets: function () {
      for (var f in this.fleets) {
        for (var j=0;j<this.fleets[f].length;j++) {
          if (!(this.fleets[f][j][0] in prop.aircraft.models)) {
            console.warn("Airline " + this.icao.toUpperCase()
                         + " uses nonexistent aircraft " + this.fleets[f][j][0]
                         + ", expect errors");
          }

          if (typeof this.fleets[f][j][1] != "number") {
            console.warn("Airline " + this.icao.toUpperCase()
                         + " uses non numeric weight for aircraft " +
                         this.fleets[f][j][0] + ", expect errors");
          }
        }
      }
    },
  };
});

function airline_init() {
  airline_load("AAL");
  airline_load("ACA");
  airline_load("AEA");
  airline_load("AFL");
  airline_load("AFR");
  airline_load("AIC");
  airline_load("AIRTAXI");
  airline_load("AMX");
  airline_load("ARG");
  airline_load("ASA");
  airline_load("ASQ");
  airline_load("AUA");
  airline_load("AVA");
  airline_load("AWE");
  airline_load("AWI");
  airline_load("AWQ");
  airline_load("AXB");
  airline_load("AZA");
  airline_load("AZU");
  airline_load("BAW");
  airline_load("BCY");
  airline_load("BEE");
  airline_load("BEL");
  airline_load("BER");
  airline_load("BTK");
  airline_load("BWA");
  airline_load("CCA");
  airline_load("CES");
  airline_load("CESSNA");
  airline_load("CFG");
  airline_load("CFS");
  airline_load("CPA");
  airline_load("CPZ");
  airline_load("CSN");
  airline_load("CTV");
  airline_load("CWC");
  airline_load("DAL");
  airline_load("DLH");
  airline_load("EIN");
  airline_load("EMBRAER");
  airline_load("ENY");
  airline_load("ETD");
  airline_load("EXS");
  airline_load("EVA");
  airline_load("EZY");
  airline_load("FAB");
  airline_load("FASTGA");
  airline_load("FDB");
  airline_load("FDX");
  airline_load("FFT");
  airline_load("FLG");
  airline_load("FWI");
  airline_load("GIA");
  airline_load("GJS");
  airline_load("GLO");
  airline_load("GOW");
  airline_load("GWI");
  airline_load("HAL");
  airline_load("HDA");
  airline_load("IAD");
  airline_load("IBE");
  airline_load("IGO");
  airline_load("INC");
  airline_load("JAI");
  airline_load("JAL");
  airline_load("JBU");
  airline_load("JIA");
  airline_load("KAL");
  airline_load("KAP");
  airline_load("KLC");
  airline_load("KLM");
  airline_load("LAN");
  airline_load("LIGHTGA");
  airline_load("LLR");
  airline_load("LNI");
  airline_load("MON");
  airline_load("MOV");
  airline_load("NAX");
  airline_load("NKS");
  airline_load("ONE");
  airline_load("PAA");
  airline_load("PDT");
  airline_load("QFA");
  airline_load("QTR");
  airline_load("QXE");
  airline_load("RFF");
  airline_load("RLU");
  airline_load("RPA");
  airline_load("RYR");
  airline_load("SAS");
  airline_load("SBI");
  airline_load("SCX");
  airline_load("SEJ");
  airline_load("SJY");
  airline_load("SKW");
  airline_load("SLK");
  airline_load("SVR");
  airline_load("SWA");
  airline_load("SWR");
  airline_load("SXD");
  airline_load("TAM");
  airline_load("TCF");
  airline_load("TCX");
  airline_load("THY");
  airline_load("TOM");
  airline_load("TSO");
  airline_load("TUI");
  airline_load("TWA");
  airline_load("TYA");
  airline_load("UAE");
  airline_load("UAL");
  airline_load("UPS");
  airline_load("USAF");
  airline_load("VIR");
  airline_load("VRD");
  airline_load("VTI");
  airline_load("WIA");
  airline_load("XAX");
}

function airline_load(icao) {
  icao = icao.toLowerCase();
  new Content({
    type: "json",
    url: "assets/airlines/"+icao+".json",
    payload: icao.toLowerCase(),
    callback: function(status, data, payload) {
      if(status == "ok") {
        prop.airline.airlines[payload] = new zlsa.atc.Airline(payload, data);
      }
    }
  });
}

function airline_get(icao) {
  icao = icao.toLowerCase();
  return prop.airline.airlines[icao];
}

function airline_ready() {
  for(var i in prop.airline.airlines) {
    prop.airline.airlines[i].validateFleets();
  }
}
<|endoftext|>


<commit_before>/*
 * Test runner
 * =============================================================================
 */

/*
 * Require modules
 * -----------------------------------------------------------------------------
 */
var webdriverjs = require('webdriverjs');
var os = require('os');
var path = require('path');
var _ = require('lodash');
var shell = require('shelljs');
global.should = require('chai').should();//exposed as global for the suites

/*
 * Require all test suites
 * -----------------------------------------------------------------------------
 * - uses https://www.npmjs.org/package/require-directory
 */
var suites = require('./suites');

/*
 * Require browser configurations
 * -----------------------------------------------------------------------------
 */
var browsers = require('./browsers.json');

/*
 * Detect if PhantomJS mode is called
 * -----------------------------------------------------------------------------
 */
var phantom = process.env.HEADLESS_PHANTOM || false;

if (phantom) {

  browsers = [
    {
      "browserName"   : "phantom",
      "version"       : String(shell.exec('phantomjs -v', {silent:true}).output).trim() || 'version unknown',
      "os"            : os.type()+' '+os.arch(),
      "os_version"    : os.release(),
      "resolution"    : "headless"
    }
  ]

}

/*
 * Check Browserstack username & access key (if not in PhantomJS mode)
 * -----------------------------------------------------------------------------
 */
if (!phantom && process.env.BROWSERSTACK_USERNAME == null) {
  throw 'You need to set your BrowserStack username as BROWSERSTACK_USERNAME enviroment variable!';
}

if (!phantom && process.env.BROWSERSTACK_ACCESS_KEY == null) {
  throw 'You need to set your BrowserStack access key as BROWSERSTACK_ACCESS_KEY enviroment variable!';
}

/*
 * Helper function for building human readable browser name/version/os string
 * -----------------------------------------------------------------------------
 * - It's one damn ugly function, but who cares...
 */
function generateBrowserLabel(browser) {
  var labelString = '';
  labelString += String(browser['browserName']).trim().toLowerCase() == 'ie' ? 'Internet Explorer' : browser['browserName'];
  if(browser['version'] ){
    labelString += ' ['+browser['version']+']';
  } else if(!browser['device']) {
    labelString += ' [latest stable version]';
  }
  labelString += ' '+browser['os'];
  labelString += browser['os_version'] ? ' '+browser['os_version'] : '';
  labelString += browser['device'] ? ' '+browser['device'] : '';
  labelString += browser['deviceOrientation'] ? ' '+browser['deviceOrientation'] : '';
  labelString += browser['resolution'] ? ' '+browser['resolution'] : '';
  return labelString;
}

/*
 * Helper function to setup the webdriver.io client
 * -----------------------------------------------------------------------------
 */
function setupClient(browser) {

  var client = {};

  if (phantom) {

    client = webdriverjs.remote({
      desiredCapabilities: {
        browserName: 'phantomjs'
      },
      logLevel: 'silent'//change to 'verbose' if having problems...
    });
  } else {

    client = webdriverjs.remote({
      desiredCapabilities: browser,
      host: 'hub.browserstack.com',
      port: 80,
      user : process.env.BROWSERSTACK_USERNAME,
      key: process.env.BROWSERSTACK_ACCESS_KEY,
      logLevel: 'silent'//change to 'verbose' if having problems...
    });
  }

  return client;
}

/*
 * Run all tests recursively on all browsers
 * -----------------------------------------------------------------------------
 */
_.each(browsers, function(browser) {

  var client = setupClient(browser);

  var browserLabel = generateBrowserLabel(browser);

  describe(browserLabel, function(){

    /*
     * Set time out for all suites (within on browser)
     * -------------------------------------------------------------------------
     * - Be generous, you shouldn't be running e2e tests every minute...
     */
    this.timeout(60*60*1000);

    /*
     * Reset browser after each suite
     * -------------------------------------------------------------------------
     * - TODO: delete all cookies as well: https://github.com/webdriverio/webdriverio/issues/262
     * - resets the client to url about:blank after every test suite
     * - patch "afterEachDescribe"
     *   - stolen from: https://github.com/visionmedia/mocha/issues/911
     *   - iterates over all suites and attaches afterAll listener manually
     */
    before(function(){
      var that = this;
      client.init(function callbackAfterClientInit(){
        _.each(that.test.parent.suites, function process(suite){
          suite.afterAll(function resetClient(){
            client.url('about:blank');
          });
        });
      });
    });

    /*
     * Check that there are some tests to be run
     * -------------------------------------------------------------------------
     */
    if(Object.keys(suites).length<1) throw new Error('No test suites found.');

    /*
     * Run all test suites recursively
     * -------------------------------------------------------------------------
     * - Actually generates the test suites runtime
     * - TODO: figure out if there's some "classy" way of looping the tests...
     */
    _.each(suites, function(suite){
      if (typeof suite === 'function') return suite(client);
      _.each(suite, function(suiteItem){
        if (typeof suiteItem === 'function') return suiteItem(client);
        _.each(suiteItem, function(suiteSubItem){
          if (typeof suiteSubItem === 'function') return suiteSubItem(client);
        });
      });
    });

    /*
     * Close the browser after all suites have been tested
     * -------------------------------------------------------------------------
     * - To prevent BrowserStack sessions hanging we first call end() and then
     *   endAll just to be sure
     */
    after(function(done){
      client.end(function callbackAfterClientEnd(err){
        if(err) console.log(err);
        client.endAll(function callbackAfterClientEndAll(err){
          if(err) console.log(err);
          client.call(done);
        })
      });
    });

  });

});

<commit_msg>Delete cookies after each test suite. Closes #1<commit_after>/*
 * Test runner
 * =============================================================================
 */

/*
 * Require modules
 * -----------------------------------------------------------------------------
 */
var webdriverjs = require('webdriverjs');
var os = require('os');
var path = require('path');
var _ = require('lodash');
var shell = require('shelljs');
global.should = require('chai').should();//exposed as global for the suites

/*
 * Require all test suites
 * -----------------------------------------------------------------------------
 * - uses https://www.npmjs.org/package/require-directory
 */
var suites = require('./suites');

/*
 * Require browser configurations
 * -----------------------------------------------------------------------------
 */
var browsers = require('./browsers.json');

/*
 * Detect if PhantomJS mode is called
 * -----------------------------------------------------------------------------
 */
var phantom = process.env.HEADLESS_PHANTOM || false;

if (phantom) {

  browsers = [
    {
      "browserName"   : "phantom",
      "version"       : String(shell.exec('phantomjs -v', {silent:true}).output).trim() || 'version unknown',
      "os"            : os.type()+' '+os.arch(),
      "os_version"    : os.release(),
      "resolution"    : "headless"
    }
  ]

}

/*
 * Check Browserstack username & access key (if not in PhantomJS mode)
 * -----------------------------------------------------------------------------
 */
if (!phantom && process.env.BROWSERSTACK_USERNAME == null) {
  throw 'You need to set your BrowserStack username as BROWSERSTACK_USERNAME enviroment variable!';
}

if (!phantom && process.env.BROWSERSTACK_ACCESS_KEY == null) {
  throw 'You need to set your BrowserStack access key as BROWSERSTACK_ACCESS_KEY enviroment variable!';
}

/*
 * Helper function for building human readable browser name/version/os string
 * -----------------------------------------------------------------------------
 * - It's one damn ugly function, but who cares...
 */
function generateBrowserLabel(browser) {
  var labelString = '';
  labelString += String(browser['browserName']).trim().toLowerCase() == 'ie' ? 'Internet Explorer' : browser['browserName'];
  if(browser['version'] ){
    labelString += ' ['+browser['version']+']';
  } else if(!browser['device']) {
    labelString += ' [latest stable version]';
  }
  labelString += ' '+browser['os'];
  labelString += browser['os_version'] ? ' '+browser['os_version'] : '';
  labelString += browser['device'] ? ' '+browser['device'] : '';
  labelString += browser['deviceOrientation'] ? ' '+browser['deviceOrientation'] : '';
  labelString += browser['resolution'] ? ' '+browser['resolution'] : '';
  return labelString;
}

/*
 * Helper function to setup the webdriver.io client
 * -----------------------------------------------------------------------------
 */
function setupClient(browser) {

  var client = {};

  if (phantom) {

    client = webdriverjs.remote({
      desiredCapabilities: {
        browserName: 'phantomjs'
      },
      logLevel: 'silent'//change to 'verbose' if having problems...
    });
  } else {

    client = webdriverjs.remote({
      desiredCapabilities: browser,
      host: 'hub.browserstack.com',
      port: 80,
      user : process.env.BROWSERSTACK_USERNAME,
      key: process.env.BROWSERSTACK_ACCESS_KEY,
      logLevel: 'silent'//change to 'verbose' if having problems...
    });
  }

  return client;
}

/*
 * Run all tests recursively on all browsers
 * -----------------------------------------------------------------------------
 */
_.each(browsers, function(browser) {

  var client = setupClient(browser);

  var browserLabel = generateBrowserLabel(browser);

  describe(browserLabel, function(){

    /*
     * Set time out for all suites (within on browser)
     * -------------------------------------------------------------------------
     * - Be generous, you shouldn't be running e2e tests every minute...
     */
    this.timeout(60*60*1000);

    /*
     * Reset browser after each suite
     * -------------------------------------------------------------------------
     * - TODO: delete all cookies as well: https://github.com/webdriverio/webdriverio/issues/262
     * - resets the client to url about:blank after every test suite
     * - patch "afterEachDescribe"
     *   - stolen from: https://github.com/visionmedia/mocha/issues/911
     *   - iterates over all suites and attaches afterAll listener manually
     */
    before(function(){
      var that = this;
      client.init(function callbackAfterClientInit(){
        _.each(that.test.parent.suites, function process(suite){
          suite.afterAll(function resetClient(){
            client.deleteCookie();
            client.url('about:blank');
          });
        });
      });
    });

    /*
     * Check that there are some tests to be run
     * -------------------------------------------------------------------------
     */
    if(Object.keys(suites).length<1) throw new Error('No test suites found.');

    /*
     * Run all test suites recursively
     * -------------------------------------------------------------------------
     * - Actually generates the test suites runtime
     * - TODO: figure out if there's some "classy" way of looping the tests...
     */
    _.each(suites, function(suite){
      if (typeof suite === 'function') return suite(client);
      _.each(suite, function(suiteItem){
        if (typeof suiteItem === 'function') return suiteItem(client);
        _.each(suiteItem, function(suiteSubItem){
          if (typeof suiteSubItem === 'function') return suiteSubItem(client);
        });
      });
    });

    /*
     * Close the browser after all suites have been tested
     * -------------------------------------------------------------------------
     * - To prevent BrowserStack sessions hanging we first call end() and then
     *   endAll just to be sure
     */
    after(function(done){
      client.end(function callbackAfterClientEnd(err){
        if(err) console.log(err);
        client.endAll(function callbackAfterClientEndAll(err){
          if(err) console.log(err);
          client.call(done);
        })
      });
    });

  });

});

<|endoftext|>


<commit_before>test('Test App: Empty', function*(t) {
	rmdir('test/apps/empty', false, ['.gitignore', 'index.js'])

	global.app = aero('test/apps/empty')
	fs.unlinkSync(app.cacheFile)
	yield app.run()

	appOk(t, app)
	t.ok((yield fetch(app, '/')).body, '/')

	yield app.stop()
})

test('Test App: Demo', function*(t) {
	global.app = aero('test/apps/demo')
	yield app.run()

	appOk(t, app)

	let frontPage = yield fetch(app, '/')
	t.ok(frontPage.body, '/')
	t.equal(frontPage.statusCode, 200, '/ [200]')

	t.ok((yield fetch(app, '/_/')).body, '/_/')
	t.ok((yield fetch(app, '/api')).body, '/api')
	t.ok((yield fetch(app, '/_/api')).body, '/_/api')
	t.equal((yield fetch(app, '/favicon.ico')).statusCode, 404, '/favicon.ico [404]')
	t.equal((yield fetch(app, '/redirect')).body, (yield fetch(app, '/')).body, '/redirect')
	t.equal((yield fetch(app, '/sendfile')).body, require('fs').readFileSync('package.json', 'utf8'), '/sendfile')

	let syntaxError = yield fetch(app, '/error/syntax')
	t.ok(syntaxError.body.startsWith('SyntaxError'), '/error/syntax')
	t.equal(syntaxError.statusCode, 500, '/error/syntax [500]')

	let controllerError = yield fetch(app, '/error/controller')
	t.ok(controllerError.body.startsWith('ReferenceError'), '/error/controller')
	t.equal(controllerError.statusCode, 500, '/error/controller [500]')

	t.ok((yield fetch(app, '/?layout=1')).body, '/?layout=1')

	let manifest = JSON.parse((yield fetch(app, '/manifest.json')).body)
	t.ok(manifest, 'manifest')
	t.ok(manifest.name, 'manifest.name')
	t.ok(manifest.display, 'manifest.display')

	// Live modification
	let testPath = 'test/apps/demo/pages/home/home.jade'
	let contents = fs.readFileSync(testPath, 'utf8')
	fs.writeFileSync(testPath, contents.replace('Work', 'Chaos'), 'utf8')
	yield Promise.delay(250)
	let newFrontPage = yield fetch(app, '/')
	fs.writeFileSync(testPath, contents, 'utf8')

	t.notEqual(frontPage.body, newFrontPage.body, 'LiveReload (template)')

	// HTTP
	let redirectedFrontPage = yield requester.getAsync({
		url: app.localURL('/').replace('https', 'http').replace(':' + app.config.ports.https, ':' + app.config.ports.http),
		rejectUnauthorized: false
	})
	t.equal(redirectedFrontPage.statusCode, 200, 'HTTP redirect [200]')
	t.equal(redirectedFrontPage.body, newFrontPage.body, 'HTTP redirect')

	app.liveReload.broadcast({})

	yield app.stop()
})<commit_msg>Fixed cache deletion in tests<commit_after>test('Test App: Empty', function*(t) {
	rmdir('test/apps/empty', false, ['.gitignore', 'index.js'])

	global.app = aero('test/apps/empty')
	fs.unlink(app.cacheFile, error => null)
	yield app.run()

	appOk(t, app)
	t.ok((yield fetch(app, '/')).body, '/')

	yield app.stop()
})

test('Test App: Demo', function*(t) {
	global.app = aero('test/apps/demo')
	yield app.run()

	appOk(t, app)

	let frontPage = yield fetch(app, '/')
	t.ok(frontPage.body, '/')
	t.equal(frontPage.statusCode, 200, '/ [200]')

	t.ok((yield fetch(app, '/_/')).body, '/_/')
	t.ok((yield fetch(app, '/api')).body, '/api')
	t.ok((yield fetch(app, '/_/api')).body, '/_/api')
	t.equal((yield fetch(app, '/favicon.ico')).statusCode, 404, '/favicon.ico [404]')
	t.equal((yield fetch(app, '/redirect')).body, (yield fetch(app, '/')).body, '/redirect')
	t.equal((yield fetch(app, '/sendfile')).body, require('fs').readFileSync('package.json', 'utf8'), '/sendfile')

	let syntaxError = yield fetch(app, '/error/syntax')
	t.ok(syntaxError.body.startsWith('SyntaxError'), '/error/syntax')
	t.equal(syntaxError.statusCode, 500, '/error/syntax [500]')

	let controllerError = yield fetch(app, '/error/controller')
	t.ok(controllerError.body.startsWith('ReferenceError'), '/error/controller')
	t.equal(controllerError.statusCode, 500, '/error/controller [500]')

	t.ok((yield fetch(app, '/?layout=1')).body, '/?layout=1')

	let manifest = JSON.parse((yield fetch(app, '/manifest.json')).body)
	t.ok(manifest, 'manifest')
	t.ok(manifest.name, 'manifest.name')
	t.ok(manifest.display, 'manifest.display')

	// Live modification
	let testPath = 'test/apps/demo/pages/home/home.jade'
	let contents = fs.readFileSync(testPath, 'utf8')
	fs.writeFileSync(testPath, contents.replace('Work', 'Chaos'), 'utf8')
	yield Promise.delay(250)
	let newFrontPage = yield fetch(app, '/')
	fs.writeFileSync(testPath, contents, 'utf8')

	t.notEqual(frontPage.body, newFrontPage.body, 'LiveReload (template)')

	// HTTP
	let redirectedFrontPage = yield requester.getAsync({
		url: app.localURL('/').replace('https', 'http').replace(':' + app.config.ports.https, ':' + app.config.ports.http),
		rejectUnauthorized: false
	})
	t.equal(redirectedFrontPage.statusCode, 200, 'HTTP redirect [200]')
	t.equal(redirectedFrontPage.body, newFrontPage.body, 'HTTP redirect')

	app.liveReload.broadcast({})

	yield app.stop()
})<|endoftext|>


<commit_before>var posts = ["s"];
var post_index = 0;
var post_count = 1;
var map;  // Google map object (global variable)

var lat;
var lng;

function left_card() {
  post_index = (post_index + post_count - 1) % post_count;
  retrieve_comments();
  retrieve_map();
}

function right_card() {
  post_index = (post_index + post_count + 1) % post_count;
  if(post_index == post_count - 3) {
    retrieve_posts();
  }
  retrieve_comments();
  retrieve_map();
}

function retrieve_map() {
  $.get("http://bounce9833.azurewebsites.net/api/post_bounces", {post_id: posts[post_index]._id}, function(bounces) {
    console.log(bounces);
    console.log(bounces[0]);
    console.log(bounces[0].loc);
    // Create a Google coordinate object for where to center the map
    var latlngCenter = new google.maps.LatLng( -123.1207, 49.2827 ); // Coordinates of Washington, DC (area centroid)

    // Map options for how to display the Google map
    var mapOptions = { zoom: 12, center: latlngCenter  };

    // Show the Google map in the div with the attribute id 'map-canvas'.
    map = new google.maps.Map(document.getElementById(posts[post_index]._id + 'right'), mapOptions);

    for(var i = 0; i < bounces.length; i++) {
      var latlng = {lat: bounces[i].loc[1], lng: bounces[i].loc[0]};
      var marker = new google.maps.Marker({
        position: latlng,
        map: map,
      });
    }
  });
}

function retrieve_comments() {
  $.get("http://bounce9833.azurewebsites.net/api/comment", {post_id: posts[post_index]._id}, function(comments) {
    var commentString = "";
    for (var i=0; i<comments.length; i++) {
      commentString += '
' + comments[i].text + '
';
    }
    commentString += "
<input type='text' id='" + posts[post_index]._id + "comment' placeholder='Comment'></input> Send";
    $('#' + posts[post_index]._id + 'left').html(commentString);
    return comments;
  });
}

function retrieve_posts() {
  navigator.geolocation.getCurrentPosition(function(geoloc) {
    var lat = parseInt(geoloc.coords.latitude);
    var lng = parseInt(geoloc.coords.longitude);
    $.get("http://bounce9833.azurewebsites.net/api/post", {lat: lat, lng: lng, offset: post_count}, function(new_posts) {
      posts = posts.concat(new_posts);
      post_count = posts.length;
      for(var i = 0; i < new_posts.length; i++) {
        $("#card-view").append("
" +
                                 "
" +
                                  "
" +
                                    "
" + new_posts[i].text + "
" +
                                    "
Left
" +
                                  "
" +
                                  "
Right
" +
                                "
" +
                              "
");
      }
    });
  });
}

function new_text_post() {
  navigator.geolocation.getCurrentPosition(function(geoloc) {
    var lat = parseInt(geoloc.coords.latitude);
    var lng = parseInt(geoloc.coords.longitude);
    var text = document.getElementById('text').value;
    new_post(text, document.cookie, lat, lng);
  });
}

function new_post(text, uid, lat, lng) {
  $.post("http://bounce9833.azurewebsites.net/api/post", {text: text, user_id: uid, lat: lat, lng: lng}, function(message) {
    console.log(message);
  });
}

function add_comment() {
  var text = document.getElementById(posts[post_index]._id + 'comment').value;
  $.post("http://bounce9833.azurewebsites.net/api/comment", {post_id: posts[post_index]._id, user_id: document.cookie, text: text}, function(message) {
    console.log(message);
  })
  retrieve_comments();
}

function bounce() {
  navigator.geolocation.getCurrentPosition(function(geoloc) {
    var lat = parseInt(geoloc.coords.latitude);
    var lng = parseInt(geoloc.coords.longitude);
    $.post("http://bounce9833.azurewebsites.net/api/bounce", {lat: lat, lng: lng, user_id: document.cookie, post_id: posts[post_index]._id}, function(message) {
      console.log(message);
    })
  });
}

function set_latlng() {
  navigator.geolocation.getCurrentPosition(function(geoloc) {
    lat = geoloc.coords.latitude;
    lng = geoloc.coords.longitude;
  });

}

$(document).ready(function() {
  retrieve_posts();
})<commit_msg>attempt at fixing lat/lng issue<commit_after>var posts = ["s"];
var post_index = 0;
var post_count = 1;
var map;  // Google map object (global variable)

var lat;
var lng;

function left_card() {
  post_index = (post_index + post_count - 1) % post_count;
  retrieve_comments();
  retrieve_map();
}

function right_card() {
  post_index = (post_index + post_count + 1) % post_count;
  if(post_index == post_count - 3) {
    retrieve_posts();
  }
  retrieve_comments();
  retrieve_map();
}

function retrieve_map() {
  $.get("http://bounce9833.azurewebsites.net/api/post_bounces", {post_id: posts[post_index]._id}, function(bounces) {
    console.log(bounces);
    console.log(bounces[0]);
    console.log(bounces[0].loc);
    // Create a Google coordinate object for where to center the map
    var latlngCenter = new google.maps.LatLng({lng: -123.1207, lat: 49.2827 }); // Coordinates of Washington, DC (area centroid)

    // Map options for how to display the Google map
    var mapOptions = { zoom: 12, center: latlngCenter  };

    // Show the Google map in the div with the attribute id 'map-canvas'.
    map = new google.maps.Map(document.getElementById(posts[post_index]._id + 'right'), mapOptions);

    for(var i = 0; i < bounces.length; i++) {
      var latlng = {lat: bounces[i].loc[1], lng: bounces[i].loc[0]};
      var marker = new google.maps.Marker({
        position: latlng,
        map: map,
      });
    }
  });
}

function retrieve_comments() {
  $.get("http://bounce9833.azurewebsites.net/api/comment", {post_id: posts[post_index]._id}, function(comments) {
    var commentString = "";
    for (var i=0; i<comments.length; i++) {
      commentString += '
' + comments[i].text + '
';
    }
    commentString += "
<input type='text' id='" + posts[post_index]._id + "comment' placeholder='Comment'></input> Send";
    $('#' + posts[post_index]._id + 'left').html(commentString);
    return comments;
  });
}

function retrieve_posts() {
  navigator.geolocation.getCurrentPosition(function(geoloc) {
    var lat = parseInt(geoloc.coords.latitude);
    var lng = parseInt(geoloc.coords.longitude);
    $.get("http://bounce9833.azurewebsites.net/api/post", {lat: lat, lng: lng, offset: post_count}, function(new_posts) {
      posts = posts.concat(new_posts);
      post_count = posts.length;
      for(var i = 0; i < new_posts.length; i++) {
        $("#card-view").append("
" +
                                 "
" +
                                  "
" +
                                    "
" + new_posts[i].text + "
" +
                                    "
Left
" +
                                  "
" +
                                  "
Right
" +
                                "
" +
                              "
");
      }
    });
  });
}

function new_text_post() {
  navigator.geolocation.getCurrentPosition(function(geoloc) {
    var lat = parseInt(geoloc.coords.latitude);
    var lng = parseInt(geoloc.coords.longitude);
    var text = document.getElementById('text').value;
    new_post(text, document.cookie, lat, lng);
  });
}

function new_post(text, uid, lat, lng) {
  $.post("http://bounce9833.azurewebsites.net/api/post", {text: text, user_id: uid, lat: lat, lng: lng}, function(message) {
    console.log(message);
  });
}

function add_comment() {
  var text = document.getElementById(posts[post_index]._id + 'comment').value;
  $.post("http://bounce9833.azurewebsites.net/api/comment", {post_id: posts[post_index]._id, user_id: document.cookie, text: text}, function(message) {
    console.log(message);
  })
  retrieve_comments();
}

function bounce() {
  navigator.geolocation.getCurrentPosition(function(geoloc) {
    var lat = parseInt(geoloc.coords.latitude);
    var lng = parseInt(geoloc.coords.longitude);
    $.post("http://bounce9833.azurewebsites.net/api/bounce", {lat: lat, lng: lng, user_id: document.cookie, post_id: posts[post_index]._id}, function(message) {
      console.log(message);
    })
  });
}

function set_latlng() {
  navigator.geolocation.getCurrentPosition(function(geoloc) {
    lat = geoloc.coords.latitude;
    lng = geoloc.coords.longitude;
  });

}

$(document).ready(function() {
  retrieve_posts();
})<|endoftext|>


<commit_before>var xmlhttp = new XMLHttpRequest();

function Message () {
	this.from;
	this.to;
	this.subject;
	this.message;
}

function changeTitle () {
	var subject = document.getElementById('mail_subject').value;

	if ((subject == null) || (subject == "")) {
		document.title = "SendMail";
		document.getElementById('message_title').innerHTML = "New Message";
	}
	else {
		document.title = "SendMail - " + subject;
		document.getElementById('message_title').innerHTML = subject;
	}
}

function showSignature () {
	document.getElementById('overlay_background').style.display = "block";
	document.getElementById('overlay_body').style.display = "block";
}

function hideSignature () {
	var signature = document.getElementById('signature_text').value;
	var message = document.getElementById('message_text').value;

	if (!((message == null) || (message == ""))) {
		document.getElementById('message_text').value = message + "\n\n" + signature;
	}

	document.getElementById('overlay_background').style.display = "none";
	document.getElementById('overlay_body').style.display = "none";
}

function messageSend () {
	var message_form = document.getElementById('message_form');
	var email = new Message();

	email.from = message_form.elements[0].value;
	email.to = message_form.elements[1].value;
	email.subject = message_form.elements[2].value;
	email.message = message_form.elements[3].value;

	var jsonified = JSON.stringify(email);

	xmlhttp.onreadystatechange = dataPosted();
	xmlhttp.open("POST", "scripts/sendmail.php", true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.send("json=" + jsonified);

	document.getElementById('response_message_div').style.display = "block";
}

function dataPosted () {
	if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
		document.getElementById("response_message").innerHTML = xmlhttp.responseText;
	}
 }<commit_msg>Trying to make javascript post data work.<commit_after>var xmlhttp = new XMLHttpRequest();

function Message () {
	this.from;
	this.to;
	this.subject;
	this.message;
}

function changeTitle () {
	var subject = document.getElementById('mail_subject').value;

	if ((subject == null) || (subject == "")) {
		document.title = "SendMail";
		document.getElementById('message_title').innerHTML = "New Message";
	}
	else {
		document.title = "SendMail - " + subject;
		document.getElementById('message_title').innerHTML = subject;
	}
}

function showSignature () {
	document.getElementById('overlay_background').style.display = "block";
	document.getElementById('overlay_body').style.display = "block";
}

function hideSignature () {
	var signature = document.getElementById('signature_text').value;
	var message = document.getElementById('message_text').value;

	if (!((message == null) || (message == ""))) {
		document.getElementById('message_text').value = message + "\n\n" + signature;
	}

	document.getElementById('overlay_background').style.display = "none";
	document.getElementById('overlay_body').style.display = "none";
}

function messageSend () {
	var message_form = document.getElementById('message_form');
	var email = new Message();

	email.from = message_form.elements[0].value;
	email.to = message_form.elements[1].value;
	email.subject = message_form.elements[2].value;
	email.message = message_form.elements[3].value;

	var jsonified = JSON.stringify(email);

	var params = "json=" + jsonified;
	xmlhttp.open("POST", "scripts/sendmail.php", true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.setRequestHeader("Connection", "close");
	xmlhttp.onreadystatechange = dataPosted();
	xmlhttp.send(params);

	document.getElementById('response_message_div').style.display = "block";
}

function dataPosted () {
	if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
		document.getElementById("response_message").innerHTML = xmlhttp.responseText;
	}
 }<|endoftext|>


<commit_before>function render(tmpl_name, tmpl_data) {
	if ( !render.tmpl_cache ) {
		render.tmpl_cache = {};
	}

	if ( ! render.tmpl_cache[tmpl_name] ) {
		var tmpl_dir = 'js/templates';
		var tmpl_url = tmpl_dir + '/' + tmpl_name + '.html';

		var tmpl_string;
		$.ajax({
			url: tmpl_url,
			method: 'GET',
			async: false,
			success: function(data) {
				tmpl_string = data;
			}
		});

		render.tmpl_cache[tmpl_name] = _.template(tmpl_string);
	}

	var rendered = render.tmpl_cache[tmpl_name](tmpl_data);
	$('#maincontainer').html(rendered);
}

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();

	this.registerURL = /^#register/;
	this.overviewURL = /^#overview/;

	self.route();
    },

    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },

    onDeviceReady: function() {
        $(window).on('hashchange', $.proxy(this.route, this));
    },

    route: function() {
	    var hash = window.location.hash;
	    if (!hash) {
	        render('home', {});
	        return;
	    }
	    var match = hash.match(app.registerURL);
	    if (match) {
	        render('register', {});
	    }
	    var match = hash.match(app.overviewURL);
	    if (match) {
	        render('overview', {});
	    }
    }
};
<commit_msg>Update index.js<commit_after>function render(tmpl_name, tmpl_data) {
	if ( !render.tmpl_cache ) {
		render.tmpl_cache = {};
	}

	if ( ! render.tmpl_cache[tmpl_name] ) {
		var tmpl_dir = 'js/templates';
		var tmpl_url = tmpl_dir + '/' + tmpl_name + '.html';

		var tmpl_string;
		$.ajax({
			url: tmpl_url,
			method: 'GET',
			async: false,
			success: function(data) {
				tmpl_string = data;
			}
		});

		render.tmpl_cache[tmpl_name] = _.template(tmpl_string);
	}

	var rendered = render.tmpl_cache[tmpl_name](tmpl_data);
	$('#maincontainer').html(rendered);
}

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();

	this.registerURL = /^#register/;
	this.overviewURL = /^#overview/;

	self.route();
    },

    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },

    onDeviceReady: function() {
        $(window).on('hashchange', $.proxy(this.route, this));
    },

    route: function() {
	    var hash = window.location.hash;
	    if (!hash) {
	        render('home', {});
	        return;
	    }
	    var match = hash.match(app.registerURL);
	    if (match) {
	        render('register', {});
	        return;
	    }
	    var match = hash.match(app.overviewURL);
	    if (match) {
	        render('overview', {});
	        return;
	    }
    }
};
<|endoftext|>


<commit_before>$('#member li').click(function() {
	$('#member-value').text(this.children[0].text).append('');
});

$('#job li').click(function() {
	$('#job-value').text(this.children[0].text).append('');
	switch(this.children[0].text) {
		case '在職':
			$('#salary-value').attr('disabled', false);
			break;
		default:
			$('#salary-value').attr('disabled', true);
			displayError(false, {'id':'salary'});
	}
});

$('#addmember').click(function() {
	// validation
	var member = $('#member-value').text();
	if (member == '稱謂') {
		displayError(true, {'msg':'尚未選擇家庭成員！'});
		return false;
	}

	var age = new Date().getFullYear() - (!isNaN($('#birthday-value').val()) && $('#birthday-value').val() != "" ? 1911 + parseInt($('#birthday-value').val()) : new Date().getFullYear());
	if (age == 0) {
		displayError(true, {'id':'birthday', 'msg':'出生年次填寫錯誤！'});
		return false;
	} else {
		displayError(false, {'id':'birthday'});
	}

	var job = $('#job-value').text();
	var salary = parseInt($('#salary-value').val())
	if (job == '職業') {
		displayError(true, {'msg': '尚未選擇職業！'});
		return false;
	} else if (job == '在職' && isNaN(salary)) {
		displayError(true, {'id':'salary', 'msg':'每月薪資填寫錯誤！'});
		return false;
	} else {
		displayError(false, {'id':'salary'});
	}

	var disability = $('#disability').prop('checked');
	var comment = '';

	// append to table
	$('#family tbody:last').after('
' + member + '	'
					+ '' + age + '	'
					+ '' + salary * 12 + '	'
					+ '' + disability ? '有' : '無' + '	'
					+ '' + comment + '
');

	// clear input area
	clearValue();
});

function clearValue() {
	$('#member-value').text('稱謂').append('');
	$('#job-value').text('職業').append('');
	$('#birthday-value').val('');
	$('#salary-value').val('');
	$('#salary-value').attr('disabled', true);
	$('#disability').prop('checked', false);
	$('#errormsg').hide();
}

function displayError(b, args) {
	if (b) {
		$('#' + args['id']).addClass('has-error');
		$('#errormsg').text(args['msg']).show();
	} else {
		$('#' + args['id']).removeClass('has-error');
		$('#errormsg').hide();
	}
}<commit_msg>修正資料新增至表格的功能<commit_after>$('#member li').click(function() {
	$('#member-value').text(this.children[0].text).append('');
});

$('#job li').click(function() {
	$('#job-value').text(this.children[0].text).append('');
	switch(this.children[0].text) {
		case '在職':
			$('#salary-value').attr('disabled', false);
			break;
		default:
			$('#salary-value').attr('disabled', true);
			displayError(false, {'id':'salary'});
	}
});

$('#addmember').click(function() {
	// validation
	var member = $('#member-value').text();
	if (member == '稱謂') {
		displayError(true, {'msg':'尚未選擇家庭成員！'});
		return false;
	}

	var age = new Date().getFullYear() - (!isNaN($('#birthday-value').val()) && $('#birthday-value').val() != "" ? 1911 + parseInt($('#birthday-value').val()) : new Date().getFullYear());
	if (age == 0) {
		displayError(true, {'id':'birthday', 'msg':'出生年次填寫錯誤！'});
		return false;
	} else {
		displayError(false, {'id':'birthday'});
	}

	var job = $('#job-value').text();
	var salary = parseInt($('#salary-value').val())
	if (job == '職業') {
		displayError(true, {'msg': '尚未選擇職業！'});
		return false;
	} else if (job == '在職' && isNaN(salary)) {
		displayError(true, {'id':'salary', 'msg':'每月薪資填寫錯誤！'});
		return false;
	} else {
		displayError(false, {'id':'salary'});
	}

	var disability = $('#disability').prop('checked');
	var comment = '';

	// append to table
	$('#family tbody').append('
' + member + '	'
					+ '' + age + '	'
					+ '' + salary * 12 + '	'
					+ '' + (disability ? '有' : '無') + '	'
					+ '' + comment + '
');

	// clear input area
	clearValue();
});

function clearValue() {
	$('#member-value').text('稱謂').append('');
	$('#job-value').text('職業').append('');
	$('#birthday-value').val('');
	$('#salary-value').val('');
	$('#salary-value').attr('disabled', true);
	$('#disability').prop('checked', false);
	$('#errormsg').hide();
}

function displayError(b, args) {
	if (b) {
		$('#' + args['id']).addClass('has-error');
		$('#errormsg').text(args['msg']).show();
	} else {
		$('#' + args['id']).removeClass('has-error');
		$('#errormsg').hide();
	}
}<|endoftext|>