<commit_before>var express = require('express')
var router = express.Router()

// Load internal modules
var auth = require('./authentication.js')
var courseModel = require('./course.js')
var semesterModel = require('./semester.js')
var instructorModel = require('./instructor.js')

// Check that the user is authenticated
router.all('*', function (req, res, next) {
  if (!auth.userIsAuthenticated(req)) {
    res.sendStatus(403)
  } else {
    next()
  }
})

// Intelligent searching for both courses and instructors
router.get('/search/:query', function (req, res) {
    // Validate that the request is correct
  if (typeof (req.params.query) === 'undefined') {
    res.sendStatus(400)
    return
  }

  // Basic query that performs a full-text-search with the search string
  const initialQuery = {
    $text: {
      $search: req.params.query
    }
  }

  // The basic projection that inserts the document's relevance into each returned document
  const initialProjection = {
    relevance: {
      $meta: 'textScore'
    }
  }

  // Prepare the courses collection search query and projection
  var courseQuery = {}
  var courseProjection = {}
  Object.assign(courseQuery, initialQuery)
  Object.assign(courseProjection, initialProjection)

  // Filter courses by semester
  if (typeof (req.query.semester) !== 'undefined' && !isNaN(req.query.semester)) {
    courseQuery.semester = req.query.semester
  }

  // Remove in-depth course information if the client requests "brief" results
  if (typeof (req.query.detailed) !== 'string' || (typeof (req.query.detailed) === 'string' && JSON.parse(req.query.detailed) !== false)) {
    // Merge the existing projection parameters with the parameters filtering-out all of these attributes
    Object.assign(courseProjection, {
      'evaluations.studentComments': 0,
      assignments: 0,
      grading: 0,
      classes: 0,
      description: 0,
      otherinformation: 0,
      otherrequirements: 0,
      prerequisites: 0,
      semesters: 0,
      instructors: 0
    })
  }

  // Construct the courseModel database query as a promise
  var coursePromise = courseModel.find(courseQuery, courseProjection).exec()

  // Prepare the instructors collection search query and projection
  var instructorQuery = {}
  var instructorProjection = {}
  Object.assign(instructorQuery, initialQuery)
  Object.assign(instructorProjection, initialProjection)

  // Construct the courseModel database query as a promise
  var instructorPromise = instructorModel.find(instructorQuery, instructorProjection).exec()

  // Trigger both promises and wait for them to both return
  Promise.all([coursePromise, instructorPromise]).then(values => {
    // Merge the results from the courses and instructors collections
    var combinedResult = values[0].concat(values[1])

    // Convert from the Mongoose objects into regular objects
    for (var i in combinedResult) {
      combinedResult[i] = combinedResult[i].toObject()
    }

    // Determine sort parameter
    var sortKey = 'relevance'
    if (typeof (req.query.sort) !== 'undefined') {
      sortKey = req.query.sort
    }

    // Invert the sort order if the sort key is relevance (for which we want the most relevant result first)
    var invertSortOrder = Math.pow(-1, sortKey === 'relevance')

    // Sort the results
    combinedResult.sort(function (a, b) {
      // First sort by the specified sort key
      if (sortKey !== 'rating') {
        if (a[sortKey] > b[sortKey]) {
          return 1 * invertSortOrder
        } else if (a[sortKey] < b[sortKey]) {
          return -1 * invertSortOrder
        }
      }

      // Then sort by course rating
      if (a.hasOwnProperty('evaluations') && b.hasOwnProperty('evaluations') && a.evaluations.hasOwnProperty('scores') && b.evaluations.hasOwnProperty('scores') && a.evaluations.scores.hasOwnProperty('Overall Quality of the Course') && b.evaluations.scores.hasOwnProperty('Overall Quality of the Course')) {
        return b.evaluations.scores['Overall Quality of the Course'] - a.evaluations.scores['Overall Quality of the Course']
      } else {
        return 0
      }
    })

    // Send the result to the client
    res.json(combinedResult)
  }).catch(reason => {
    console.log(reason)
    res.sendStatus(500)
  })
})

// Respond to requests for an instructor
router.get('/course/:id', function (req, res) {
  // Validate that the request is correct
  if ((typeof (req.params.id) === 'undefined') || isNaN(req.params.id)) {
    res.sendStatus(400)
    return
  }

  // Search for the instructor in the database
  courseModel.findOne({_id: req.params.id}, function (err, course) {
    if (err) {
      console.log(err)
      res.send(500)
    } else {
      if (course === null) {
        res.sendStatus(404)
      } else {
        res.json(course)
      }
    }
  })
})

// Respond to requests for course listings
router.post('/courses', function (req, res) {
  // Check the request contains a query
  if (typeof (req.body.query) === 'undefined') {
    res.sendStatus(400)
  }

  var query = {}
  var projection = {}
  var sort = {}

  // Parse the request's query
  // If the request's query is a string, use this in a full-text search for courses.
  // If the request's query is an object treat this as the database query
  // Otherwise the request is malformed and this is an error
  var parsedRequestQuery = JSON.parse(req.body.query)
  if (typeof (parsedRequestQuery) === 'string') {
    query = {
      $text: {
        $search: parsedRequestQuery
      }
    }
    projection = {
      relevance: {
        $meta: 'textScore'
      }
    }
  } else if (typeof (parsedRequestQuery) === 'object') {
    query = parsedRequestQuery
    if (typeof (parsedRequestQuery['$text']) !== 'undefined') {
      projection = {
        relevance: {
          $meta: 'textScore'
        }
      }
    }
  } else {
    res.sendStatus(400)
    return
  }

  // By default, sort by relevance. Allow sorting by title or department
  sort = {
    relevance: {
      $meta: 'textScore'
    },
    department: 1,
    catalogNumber: 1
  }
  if (typeof (req.body.sort) === 'string') {
    if (['title', 'department'].indexOf(req.body.sort) > -1) {
      sort = {}
      sort[req.body.sort] = 1
    } else if (req.body.sort === 'rating') {
      sort = {
        'evaluations.scores.Overall Quality of the Course': -1
      }
    } else if (req.body.sort === 'code') {
      sort = {
        department: 1,
        catalogNumber: 1
      }
    }
  }

  // Remove in-depth course information if the client requests "brief" results
  if (typeof (req.body.brief) !== 'undefined' && JSON.parse(req.body.brief) === true) {
    // Merge the existing projection parameters with the parameters filtering-out all of these attributes
    Object.assign(projection, {
      'evaluations.studentComments': 0,
      assignments: 0,
      grading: 0,
      classes: 0,
      description: 0,
      otherinformation: 0,
      otherrequirements: 0,
      prerequisites: 0,
      semesters: 0,
      instructors: 0
    })
  }

  // Send the query to the database and return a JSON array of the results
  courseModel.find(query, projection).sort(sort).exec(function (err, courses) {
    if (err) {
      console.log(err)
      res.sendStatus(500)
    } else {
      res.json(courses)
    }
  })
})

// Respond to requests for an instructor
router.get('/instructor/:id', function (req, res) {
  // Validate that the request is correct
  if ((typeof (req.params.id) === 'undefined') || isNaN(req.params.id)) {
    res.sendStatus(400)
    return
  }

  // Search for the instructor in the database
  instructorModel.findOne({_id: req.params.id}).populate('courses').exec(function (err, instructor) {
    if (err) {
      console.log(err)
      res.send(500)
    } else {
      if (instructor === null) {
        res.sendStatus(404)
      } else {
        res.json(instructor)
      }
    }
  })
})

// Respond to requests to add a course to the user's favoriteCourses list
router.put('/user/favorite', function (req, res) {
  var user = req.app.get('user')

  // Check that the request contains a course to delete
  if (typeof (req.body.course) === 'undefined') {
    res.sendStatus(400)
    return
  }

  // Check that this user has a favoriteCourses array
  if (typeof (user.favoriteCourses) === 'undefined') {
    user.favoriteCourses = []
  }

  // If this course is not already in the favoriteCourses array, add it
  if (user.favoriteCourses.indexOf(req.body.course) === -1) {
    user.favoriteCourses.push(req.body.course)

    user.save(function (error) {
      if (error) {
        console.log(error)
        res.sendStatus(500)
      }
      res.sendStatus(201)
    })
  } else {
    res.sendStatus(200)
  }
})

// Respond requests to delete a course from the user's favoriteCourses list
router.delete('/user/favorite', function (req, res) {
  var user = req.app.get('user')

  // Check that this user has a favoriteCourses array
  if (typeof (user.favoriteCourses) === 'undefined') {
    res.sendStatus(200)
    return
  }

  // Check that the request contains a course to delete
  if (typeof (req.body.course) === 'undefined') {
    res.sendStatus(400)
    return
  }

  // If the requested course is in the favoriteCourses array, remove it
  var i = user.favoriteCourses.indexOf(req.body.course)
  if (i !== -1) {
    user.favoriteCourses.splice(i, 1)

    user.save(function (error) {
      if (error) {
        console.log(error)
        res.sendStatus(500)
        return
      }
      res.sendStatus(200)
      return
    })
  } else {
    res.sendStatus(200)
  }
})

// Respond to a request for a list of this user's favorite courses
router.get('/user/favorites', function (req, res) {
  req.app.get('user').populate('favoriteCourses', function (err, user) {
    if (err) {
      console.log(err)
      res.sendStatus(500)
    } else {
      if (typeof (user.favoriteCourses) !== 'undefined') {
        res.status(200).json(user.favoriteCourses)
      } else {
        res.status(200).json({})
      }
    }
  })
})

// Respond to requests for semester listings
router.get('/semesters', function (req, res) {
  semesterModel.find().sort({code: -1}).exec(function (err, semesters) {
    if (err) {
      console.log(err)
      res.status(500)
    } else {
      res.status(200).json(semesters)
    }
  })
})

// Export the routes on this router
module.exports.router = router
<commit_msg>Insert "type" into search results<commit_after>var express = require('express')
var router = express.Router()

// Load internal modules
var auth = require('./authentication.js')
var courseModel = require('./course.js')
var semesterModel = require('./semester.js')
var instructorModel = require('./instructor.js')

// Check that the user is authenticated
router.all('*', function (req, res, next) {
  if (!auth.userIsAuthenticated(req)) {
    res.sendStatus(403)
  } else {
    next()
  }
})

// Intelligent searching for both courses and instructors
router.get('/search/:query', function (req, res) {
    // Validate that the request is correct
  if (typeof (req.params.query) === 'undefined') {
    res.sendStatus(400)
    return
  }

  // Basic query that performs a full-text-search with the search string
  const initialQuery = {
    $text: {
      $search: req.params.query
    }
  }

  // The basic projection that inserts the document's relevance into each returned document
  const initialProjection = {
    relevance: {
      $meta: 'textScore'
    }
  }

  // Prepare the courses collection search query and projection
  var courseQuery = {}
  var courseProjection = {}
  Object.assign(courseQuery, initialQuery)
  Object.assign(courseProjection, initialProjection)

  // Filter courses by semester
  if (typeof (req.query.semester) !== 'undefined' && !isNaN(req.query.semester)) {
    courseQuery.semester = req.query.semester
  }

  // Remove in-depth course information if the client requests "brief" results
  if (typeof (req.query.detailed) !== 'string' || (typeof (req.query.detailed) === 'string' && JSON.parse(req.query.detailed) !== false)) {
    // Merge the existing projection parameters with the parameters filtering-out all of these attributes
    Object.assign(courseProjection, {
      'evaluations.studentComments': 0,
      assignments: 0,
      grading: 0,
      classes: 0,
      description: 0,
      otherinformation: 0,
      otherrequirements: 0,
      prerequisites: 0,
      semesters: 0,
      instructors: 0
    })
  }

  // Construct the courseModel database query as a promise
  var coursePromise = courseModel.find(courseQuery, courseProjection).exec()

  // Prepare the instructors collection search query and projection
  var instructorQuery = {}
  var instructorProjection = {}
  Object.assign(instructorQuery, initialQuery)
  Object.assign(instructorProjection, initialProjection)

  // Construct the courseModel database query as a promise
  var instructorPromise = instructorModel.find(instructorQuery, instructorProjection).exec()

  // Trigger both promises and wait for them to both return
  Promise.all([coursePromise, instructorPromise]).then(values => {
    var courses = values[0]
    var instructors = values[1]

    // Insert into the course or instructor object its type
    for (var i in values[0]) {
      courses[i] = courses[i].toObject()
      courses[i].type = 'course'
    }
    for (var j in instructors) {
      instructors[j] = instructors[j].toObject()
      instructors[j].type = 'instructor'
    }

    // Merge the results from the courses and instructors collections
    var combinedResult = courses.concat(instructors)

    // Determine sort parameter
    var sortKey = 'relevance'
    if (typeof (req.query.sort) !== 'undefined') {
      sortKey = req.query.sort
    }

    // Invert the sort order if the sort key is relevance (for which we want the most relevant result first)
    var invertSortOrder = Math.pow(-1, sortKey === 'relevance')

    // Sort the results
    combinedResult.sort(function (a, b) {
      // First sort by the specified sort key
      if (sortKey !== 'rating') {
        if (a[sortKey] > b[sortKey]) {
          return 1 * invertSortOrder
        } else if (a[sortKey] < b[sortKey]) {
          return -1 * invertSortOrder
        }
      }

      // Then sort by course rating
      if (a.hasOwnProperty('evaluations') && b.hasOwnProperty('evaluations') && a.evaluations.hasOwnProperty('scores') && b.evaluations.hasOwnProperty('scores') && a.evaluations.scores.hasOwnProperty('Overall Quality of the Course') && b.evaluations.scores.hasOwnProperty('Overall Quality of the Course')) {
        return b.evaluations.scores['Overall Quality of the Course'] - a.evaluations.scores['Overall Quality of the Course']
      } else {
        return 0
      }
    })

    // Send the result to the client
    res.json(combinedResult)
  }).catch(reason => {
    console.log(reason)
    res.sendStatus(500)
  })
})

// Respond to requests for an instructor
router.get('/course/:id', function (req, res) {
  // Validate that the request is correct
  if ((typeof (req.params.id) === 'undefined') || isNaN(req.params.id)) {
    res.sendStatus(400)
    return
  }

  // Search for the instructor in the database
  courseModel.findOne({_id: req.params.id}, function (err, course) {
    if (err) {
      console.log(err)
      res.send(500)
    } else {
      if (course === null) {
        res.sendStatus(404)
      } else {
        res.json(course)
      }
    }
  })
})

// Respond to requests for course listings
router.post('/courses', function (req, res) {
  // Check the request contains a query
  if (typeof (req.body.query) === 'undefined') {
    res.sendStatus(400)
  }

  var query = {}
  var projection = {}
  var sort = {}

  // Parse the request's query
  // If the request's query is a string, use this in a full-text search for courses.
  // If the request's query is an object treat this as the database query
  // Otherwise the request is malformed and this is an error
  var parsedRequestQuery = JSON.parse(req.body.query)
  if (typeof (parsedRequestQuery) === 'string') {
    query = {
      $text: {
        $search: parsedRequestQuery
      }
    }
    projection = {
      relevance: {
        $meta: 'textScore'
      }
    }
  } else if (typeof (parsedRequestQuery) === 'object') {
    query = parsedRequestQuery
    if (typeof (parsedRequestQuery['$text']) !== 'undefined') {
      projection = {
        relevance: {
          $meta: 'textScore'
        }
      }
    }
  } else {
    res.sendStatus(400)
    return
  }

  // By default, sort by relevance. Allow sorting by title or department
  sort = {
    relevance: {
      $meta: 'textScore'
    },
    department: 1,
    catalogNumber: 1
  }
  if (typeof (req.body.sort) === 'string') {
    if (['title', 'department'].indexOf(req.body.sort) > -1) {
      sort = {}
      sort[req.body.sort] = 1
    } else if (req.body.sort === 'rating') {
      sort = {
        'evaluations.scores.Overall Quality of the Course': -1
      }
    } else if (req.body.sort === 'code') {
      sort = {
        department: 1,
        catalogNumber: 1
      }
    }
  }

  // Remove in-depth course information if the client requests "brief" results
  if (typeof (req.body.brief) !== 'undefined' && JSON.parse(req.body.brief) === true) {
    // Merge the existing projection parameters with the parameters filtering-out all of these attributes
    Object.assign(projection, {
      'evaluations.studentComments': 0,
      assignments: 0,
      grading: 0,
      classes: 0,
      description: 0,
      otherinformation: 0,
      otherrequirements: 0,
      prerequisites: 0,
      semesters: 0,
      instructors: 0
    })
  }

  // Send the query to the database and return a JSON array of the results
  courseModel.find(query, projection).sort(sort).exec(function (err, courses) {
    if (err) {
      console.log(err)
      res.sendStatus(500)
    } else {
      res.json(courses)
    }
  })
})

// Respond to requests for an instructor
router.get('/instructor/:id', function (req, res) {
  // Validate that the request is correct
  if ((typeof (req.params.id) === 'undefined') || isNaN(req.params.id)) {
    res.sendStatus(400)
    return
  }

  // Search for the instructor in the database
  instructorModel.findOne({_id: req.params.id}).populate('courses').exec(function (err, instructor) {
    if (err) {
      console.log(err)
      res.send(500)
    } else {
      if (instructor === null) {
        res.sendStatus(404)
      } else {
        res.json(instructor)
      }
    }
  })
})

// Respond to requests to add a course to the user's favoriteCourses list
router.put('/user/favorite', function (req, res) {
  var user = req.app.get('user')

  // Check that the request contains a course to delete
  if (typeof (req.body.course) === 'undefined') {
    res.sendStatus(400)
    return
  }

  // Check that this user has a favoriteCourses array
  if (typeof (user.favoriteCourses) === 'undefined') {
    user.favoriteCourses = []
  }

  // If this course is not already in the favoriteCourses array, add it
  if (user.favoriteCourses.indexOf(req.body.course) === -1) {
    user.favoriteCourses.push(req.body.course)

    user.save(function (error) {
      if (error) {
        console.log(error)
        res.sendStatus(500)
      }
      res.sendStatus(201)
    })
  } else {
    res.sendStatus(200)
  }
})

// Respond requests to delete a course from the user's favoriteCourses list
router.delete('/user/favorite', function (req, res) {
  var user = req.app.get('user')

  // Check that this user has a favoriteCourses array
  if (typeof (user.favoriteCourses) === 'undefined') {
    res.sendStatus(200)
    return
  }

  // Check that the request contains a course to delete
  if (typeof (req.body.course) === 'undefined') {
    res.sendStatus(400)
    return
  }

  // If the requested course is in the favoriteCourses array, remove it
  var i = user.favoriteCourses.indexOf(req.body.course)
  if (i !== -1) {
    user.favoriteCourses.splice(i, 1)

    user.save(function (error) {
      if (error) {
        console.log(error)
        res.sendStatus(500)
        return
      }
      res.sendStatus(200)
      return
    })
  } else {
    res.sendStatus(200)
  }
})

// Respond to a request for a list of this user's favorite courses
router.get('/user/favorites', function (req, res) {
  req.app.get('user').populate('favoriteCourses', function (err, user) {
    if (err) {
      console.log(err)
      res.sendStatus(500)
    } else {
      if (typeof (user.favoriteCourses) !== 'undefined') {
        res.status(200).json(user.favoriteCourses)
      } else {
        res.status(200).json({})
      }
    }
  })
})

// Respond to requests for semester listings
router.get('/semesters', function (req, res) {
  semesterModel.find().sort({code: -1}).exec(function (err, semesters) {
    if (err) {
      console.log(err)
      res.status(500)
    } else {
      res.status(200).json(semesters)
    }
  })
})

// Export the routes on this router
module.exports.router = router
<|endoftext|>


<commit_before>var express = require('express')
var router = express.Router()

// Load internal modules
var auth = require('./authentication.js')
var courseModel = require('./course.js')
var semesterModel = require('./semester.js')
var instructorModel = require('./instructor.js')

// Check that the user is authenticated
router.all('*', function (req, res, next) {
  if (!auth.userIsAuthenticated(req)) {
    res.sendStatus(403)
  } else {
    next()
  }
})

// Respond to requests for an instructor
router.get('/course/:id', function (req, res) {
  // Validate that the request is correct
  if ((typeof (req.params.id) === 'undefined') || isNaN(req.params.id)) {
    res.sendStatus(400)
    return
  }

  // Search for the instructor in the database
  courseModel.findOne({_id: req.params.id}, function (err, course) {
    if (err) {
      console.log(err)
      res.send(500)
    } else {
      if (course === null) {
        res.sendStatus(404)
      } else {
        res.json(course)
      }
    }
  })
})

// Respond to requests for course listings
router.post('/courses', function (req, res) {
  // Check the request contains a query
  if (typeof (req.body.query) === 'undefined') {
    res.sendStatus(400)
  }

  var query = {}
  var projection = {}
  var sort = {}

  // Parse the request's query
  // If the request's query is a string, use this in a full-text search for courses.
  // If the request's query is an object treat this as the database query
  // Otherwise the request is malformed and this is an error
  var parsedRequestQuery = JSON.parse(req.body.query)
  if (typeof (parsedRequestQuery) === 'string') {
    query = {
      $text: {
        $search: parsedRequestQuery
      }
    }
    projection = {
      relevance: {
        $meta: 'textScore'
      }
    }
  } else if (typeof (parsedRequestQuery) === 'object') {
    query = parsedRequestQuery
    if (typeof (parsedRequestQuery['$text']) !== 'undefined') {
      projection = {
        relevance: {
          $meta: 'textScore'
        }
      }
    }
  } else {
    res.sendStatus(400)
    return
  }

  // By default, sort by relevance. Allow sorting by title or department
  sort = {
    relevance: {
      $meta: 'textScore'
    },
    department: 1,
    catalogNumber: 1
  }
  if (typeof (req.body.sort) === 'string') {
    if (['title', 'department'].indexOf(req.body.sort) > -1) {
      sort = {}
      sort[req.body.sort] = 1
    } else if (req.body.sort === 'rating') {
      sort = {
        'evaluations.scores.Overall Quality of the Course': -1
      }
    } else if (req.body.sort === 'code') {
      sort = {
        department: 1,
        catalogNumber: 1
      }
    }
  }

  // Remove in-depth course information if the client requests "brief" results
  if (typeof (req.body.brief) !== 'undefined' && JSON.parse(req.body.brief) === true) {
    // Merge the existing projection parameters with the parameters filtering-out all of these attributes
    Object.assign(projection, {
      'evaluations.studentComments': 0,
      assignments: 0,
      grading: 0,
      classes: 0,
      description: 0,
      otherinformation: 0,
      otherrequirements: 0,
      prerequisites: 0,
      semesters: 0,
      instructors: 0
    })
  }

  // Send the query to the database and return a JSON array of the results
  courseModel.find(query, projection).sort(sort).exec(function (err, courses) {
    if (err) {
      console.log(err)
      res.sendStatus(500)
    } else {
      res.json(courses)
    }
  })
})

// Respond to requests for an instructor
router.get('/instructor/:id', function (req, res) {
  // Validate that the request is correct
  if ((typeof (req.params.id) === 'undefined') || isNaN(req.params.id)) {
    res.sendStatus(400)
    return
  }

  // Search for the instructor in the database
  instructorModel.findOne({_id: req.params.id}).populate('courses').exec(function (err, instructor) {
    if (err) {
      console.log(err)
      res.send(500)
    } else {
      if (instructor === null) {
        res.sendStatus(404)
      } else {
        res.json(instructor)
      }
    }
  })
})

// Respond to requests to add a course to the user's favoriteCourses list
router.put('/user/favorite', function (req, res) {
  var user = req.app.get('user')

  // Check that the request contains a course to delete
  if (typeof (req.body.course) === 'undefined') {
    res.sendStatus(400)
    return
  }

  // Check that this user has a favoriteCourses array
  if (typeof (user.favoriteCourses) === 'undefined') {
    user.favoriteCourses = []
  }

  // If this course is not already in the favoriteCourses array, add it
  if (user.favoriteCourses.indexOf(req.body.course) === -1) {
    user.favoriteCourses.push(req.body.course)

    user.save(function (error) {
      if (error) {
        console.log(error)
        res.sendStatus(500)
      }
      res.sendStatus(201)
    })
  } else {
    res.sendStatus(200)
  }
})

// Respond requests to delete a course from the user's favoriteCourses list
router.delete('/user/favorite', function (req, res) {
  var user = req.app.get('user')

  // Check that this user has a favoriteCourses array
  if (typeof (user.favoriteCourses) === 'undefined') {
    res.sendStatus(200)
    return
  }

  // Check that the request contains a course to delete
  if (typeof (req.body.course) === 'undefined') {
    res.sendStatus(400)
    return
  }

  // If the requested course is in the favoriteCourses array, remove it
  var i = user.favoriteCourses.indexOf(req.body.course)
  if (i !== -1) {
    user.favoriteCourses.splice(i, 1)

    user.save(function (error) {
      if (error) {
        console.log(error)
        res.sendStatus(500)
        return
      }
      res.sendStatus(200)
      return
    })
  } else {
    res.sendStatus(200)
  }
})

// Respond to a request for a list of this user's favorite courses
router.get('/user/favorites', function (req, res) {
  req.app.get('user').populate('favoriteCourses', function (err, user) {
    if (err) {
      console.log(err)
      res.sendStatus(500)
    } else {
      if (typeof (user.favoriteCourses) !== 'undefined') {
        res.status(200).json(user.favoriteCourses)
      } else {
        res.status(200).json({})
      }
    }
  })
})

// Respond to requests for semester listings
router.get('/semesters', function (req, res) {
  semesterModel.find().sort({code: -1}).exec(function (err, semesters) {
    if (err) {
      console.log(err)
      res.status(500)
    } else {
      res.status(200).json(semesters)
    }
  })
})

// Export the routes on this router (/login, /verify, and /logout)
module.exports.router = router
<commit_msg>Tidying comment<commit_after>var express = require('express')
var router = express.Router()

// Load internal modules
var auth = require('./authentication.js')
var courseModel = require('./course.js')
var semesterModel = require('./semester.js')
var instructorModel = require('./instructor.js')

// Check that the user is authenticated
router.all('*', function (req, res, next) {
  if (!auth.userIsAuthenticated(req)) {
    res.sendStatus(403)
  } else {
    next()
  }
})

// Respond to requests for an instructor
router.get('/course/:id', function (req, res) {
  // Validate that the request is correct
  if ((typeof (req.params.id) === 'undefined') || isNaN(req.params.id)) {
    res.sendStatus(400)
    return
  }

  // Search for the instructor in the database
  courseModel.findOne({_id: req.params.id}, function (err, course) {
    if (err) {
      console.log(err)
      res.send(500)
    } else {
      if (course === null) {
        res.sendStatus(404)
      } else {
        res.json(course)
      }
    }
  })
})

// Respond to requests for course listings
router.post('/courses', function (req, res) {
  // Check the request contains a query
  if (typeof (req.body.query) === 'undefined') {
    res.sendStatus(400)
  }

  var query = {}
  var projection = {}
  var sort = {}

  // Parse the request's query
  // If the request's query is a string, use this in a full-text search for courses.
  // If the request's query is an object treat this as the database query
  // Otherwise the request is malformed and this is an error
  var parsedRequestQuery = JSON.parse(req.body.query)
  if (typeof (parsedRequestQuery) === 'string') {
    query = {
      $text: {
        $search: parsedRequestQuery
      }
    }
    projection = {
      relevance: {
        $meta: 'textScore'
      }
    }
  } else if (typeof (parsedRequestQuery) === 'object') {
    query = parsedRequestQuery
    if (typeof (parsedRequestQuery['$text']) !== 'undefined') {
      projection = {
        relevance: {
          $meta: 'textScore'
        }
      }
    }
  } else {
    res.sendStatus(400)
    return
  }

  // By default, sort by relevance. Allow sorting by title or department
  sort = {
    relevance: {
      $meta: 'textScore'
    },
    department: 1,
    catalogNumber: 1
  }
  if (typeof (req.body.sort) === 'string') {
    if (['title', 'department'].indexOf(req.body.sort) > -1) {
      sort = {}
      sort[req.body.sort] = 1
    } else if (req.body.sort === 'rating') {
      sort = {
        'evaluations.scores.Overall Quality of the Course': -1
      }
    } else if (req.body.sort === 'code') {
      sort = {
        department: 1,
        catalogNumber: 1
      }
    }
  }

  // Remove in-depth course information if the client requests "brief" results
  if (typeof (req.body.brief) !== 'undefined' && JSON.parse(req.body.brief) === true) {
    // Merge the existing projection parameters with the parameters filtering-out all of these attributes
    Object.assign(projection, {
      'evaluations.studentComments': 0,
      assignments: 0,
      grading: 0,
      classes: 0,
      description: 0,
      otherinformation: 0,
      otherrequirements: 0,
      prerequisites: 0,
      semesters: 0,
      instructors: 0
    })
  }

  // Send the query to the database and return a JSON array of the results
  courseModel.find(query, projection).sort(sort).exec(function (err, courses) {
    if (err) {
      console.log(err)
      res.sendStatus(500)
    } else {
      res.json(courses)
    }
  })
})

// Respond to requests for an instructor
router.get('/instructor/:id', function (req, res) {
  // Validate that the request is correct
  if ((typeof (req.params.id) === 'undefined') || isNaN(req.params.id)) {
    res.sendStatus(400)
    return
  }

  // Search for the instructor in the database
  instructorModel.findOne({_id: req.params.id}).populate('courses').exec(function (err, instructor) {
    if (err) {
      console.log(err)
      res.send(500)
    } else {
      if (instructor === null) {
        res.sendStatus(404)
      } else {
        res.json(instructor)
      }
    }
  })
})

// Respond to requests to add a course to the user's favoriteCourses list
router.put('/user/favorite', function (req, res) {
  var user = req.app.get('user')

  // Check that the request contains a course to delete
  if (typeof (req.body.course) === 'undefined') {
    res.sendStatus(400)
    return
  }

  // Check that this user has a favoriteCourses array
  if (typeof (user.favoriteCourses) === 'undefined') {
    user.favoriteCourses = []
  }

  // If this course is not already in the favoriteCourses array, add it
  if (user.favoriteCourses.indexOf(req.body.course) === -1) {
    user.favoriteCourses.push(req.body.course)

    user.save(function (error) {
      if (error) {
        console.log(error)
        res.sendStatus(500)
      }
      res.sendStatus(201)
    })
  } else {
    res.sendStatus(200)
  }
})

// Respond requests to delete a course from the user's favoriteCourses list
router.delete('/user/favorite', function (req, res) {
  var user = req.app.get('user')

  // Check that this user has a favoriteCourses array
  if (typeof (user.favoriteCourses) === 'undefined') {
    res.sendStatus(200)
    return
  }

  // Check that the request contains a course to delete
  if (typeof (req.body.course) === 'undefined') {
    res.sendStatus(400)
    return
  }

  // If the requested course is in the favoriteCourses array, remove it
  var i = user.favoriteCourses.indexOf(req.body.course)
  if (i !== -1) {
    user.favoriteCourses.splice(i, 1)

    user.save(function (error) {
      if (error) {
        console.log(error)
        res.sendStatus(500)
        return
      }
      res.sendStatus(200)
      return
    })
  } else {
    res.sendStatus(200)
  }
})

// Respond to a request for a list of this user's favorite courses
router.get('/user/favorites', function (req, res) {
  req.app.get('user').populate('favoriteCourses', function (err, user) {
    if (err) {
      console.log(err)
      res.sendStatus(500)
    } else {
      if (typeof (user.favoriteCourses) !== 'undefined') {
        res.status(200).json(user.favoriteCourses)
      } else {
        res.status(200).json({})
      }
    }
  })
})

// Respond to requests for semester listings
router.get('/semesters', function (req, res) {
  semesterModel.find().sort({code: -1}).exec(function (err, semesters) {
    if (err) {
      console.log(err)
      res.status(500)
    } else {
      res.status(200).json(semesters)
    }
  })
})

// Export the routes on this router
module.exports.router = router
<|endoftext|>


<commit_before>/**
 * @file removeAllRoles command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

exports.exec = async (Bastion, message, args) => {
  if (args.id) {
    return Bastion.emit('commandUsage', message, this.help);
  }

  let user;
  if (message.mentions.users.size) {
    user = message.mentions.users.first();
  }
  else if (args.id) {
    user = await Bastion.utils.fetchMember(message.guild, args.id);
    if (user) {
      user = user.user;
    }
  }
  if (!user) {
    user = message.author;
  }

  let member = await Bastion.utils.fetchMember(message.guild, user.id);
  if (message.author.id !== message.guild.ownerID && message.member.highestRole.comparePositionTo(member.highestRole) <= 0) return Bastion.log.info(Bastion.i18n.error(message.guild.language, 'lowerRole'));

  await member.removeRoles(member.roles);

  await message.channel.send({
    embed: {
      color: Bastion.colors.RED,
      description: Bastion.i18n.info(message.guild.language, 'removeAllRoles', message.author.tag, user.tag)
    }
  }).catch(e => {
    Bastion.log.error(e);
  });

  Bastion.emit('moderationLog', message, this.help.name, user);
};

exports.config = {
  aliases: [ 'removeallr' ],
  enabled: true,
  argsDefinitions: [
    { name: 'id', type: String, defaultOption: true }
  ]
};

exports.help = {
  name: 'removeAllRoles',
  description: 'Removes all the roles from the specified user of your Discord server.',
  botPermission: 'MANAGE_ROLES',
  userTextPermission: 'MANAGE_ROLES',
  userVoicePermission: '',
  usage: 'removeAllRoles [ @USER_MENTION | USER_ID ]',
  example: [ 'removeAllRoles @user#0001', 'removeAllRoles 282424753565461211', 'removeAllRoles' ]
};
<commit_msg>commands(moderation): fix removeAllRoles command<commit_after>/**
 * @file removeAllRoles command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

exports.exec = async (Bastion, message, args) => {
  if (!args.id) {
    return Bastion.emit('commandUsage', message, this.help);
  }

  let user;
  if (message.mentions.users.size) {
    user = message.mentions.users.first();
  }
  else if (args.id) {
    user = await Bastion.utils.fetchMember(message.guild, args.id);
    if (user) {
      user = user.user;
    }
  }
  if (!user) {
    user = message.author;
  }

  let member = await Bastion.utils.fetchMember(message.guild, user.id);
  if (message.author.id !== message.guild.ownerID && message.member.highestRole.comparePositionTo(member.highestRole) <= 0) return Bastion.log.info(Bastion.i18n.error(message.guild.language, 'lowerRole'));

  await member.removeRoles(member.roles);

  await message.channel.send({
    embed: {
      color: Bastion.colors.RED,
      description: Bastion.i18n.info(message.guild.language, 'removeAllRoles', message.author.tag, user.tag)
    }
  }).catch(e => {
    Bastion.log.error(e);
  });

  Bastion.emit('moderationLog', message, this.help.name, user);
};

exports.config = {
  aliases: [ 'removeallr' ],
  enabled: true,
  argsDefinitions: [
    { name: 'id', type: String, defaultOption: true }
  ]
};

exports.help = {
  name: 'removeAllRoles',
  description: 'Removes all the roles from the specified user of your Discord server.',
  botPermission: 'MANAGE_ROLES',
  userTextPermission: 'MANAGE_ROLES',
  userVoicePermission: '',
  usage: 'removeAllRoles [ @USER_MENTION | USER_ID ]',
  example: [ 'removeAllRoles @user#0001', 'removeAllRoles 282424753565461211', 'removeAllRoles' ]
};
<|endoftext|>


<commit_before>'use strict';
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var diff = require('./routes/diff');
var log = require('./routes/log');

var app = express();

app.locals.moment = require('moment');
app.locals.momentFormat = 'YYYY-M-D H:m:s UTC';
app.locals.baseURL = process.env.BASE_URL || 'https://diffofhtmls.herokuapp.com';

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/diff', diff);
app.use('/log', log);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
<commit_msg>Change dateformat<commit_after>'use strict';
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var diff = require('./routes/diff');
var log = require('./routes/log');

var app = express();

app.locals.moment = require('moment');
app.locals.momentFormat = 'YYYY-M-D (UTC)';
app.locals.baseURL = process.env.BASE_URL || 'https://diffofhtmls.herokuapp.com';

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/diff', diff);
app.use('/log', log);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
<|endoftext|>


<commit_before>// set up ======================================================================
/*var express  = require('express');
var app      = express(); 								// create our app w/ express
var mongoose = require('mongoose'); 					// mongoose for mongodb
var port  	 = process.env.PORT || 8080; 				// set the port
var database = require('./config/database'); 			// load the database config
var morgan   = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');

// configuration ===============================================================
mongoose.connect(database.url); 	// connect to mongoDB database on modulus.io

app.use(express.static(__dirname + '/public')); 		// set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request

// routes ======================================================================
require('./app/routes.js')(app);

// listen (start app with node server.js) ======================================
app.listen(port);
console.log("App listening on port " + port);*/

const http = require('http'),
  fs = require('fs'),
  path = require('path'),
  contentTypes = require('./utils/content-types'),
  sysInfo = require('./utils/sys-info'),
  express  = require('express'),
  bodyParser = require('body-parser'),
  cron = require('node-cron'),
  morgan   = require('morgan'),
  methodOverride = require('method-override'),
  env = process.env;

// timezone setting
process.env.TZ= 'Europe/Rome'

var app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use( require('./express/static'))
/*app.use( require('./express/api/messageInterceptor'))
app.use( require('./express/api/operateOnMessages'))
app.use( require('./express/api/operateOnIncomes'))
app.use( require('./express/api/operateOnMachines'))
app.use( require('./express/api/operateOnErrorMaps'))
app.use( require('./express/api/cron'))
app.use( require('./express/api/getTotalMoneyInstaneous'))*/

app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
app.use(morgan('dev')); // log every request to the console

var server = app.listen(process.env.NODE_PORT || process.env.PORT || 3000,  process.env.NODE_IP || 'localhost', function () {
    console.log('Server listening on', 3000)
})

exports.closeServer = function(){
  server.close();
};
<commit_msg>8080 port<commit_after>// set up ======================================================================
/*var express  = require('express');
var app      = express(); 								// create our app w/ express
var mongoose = require('mongoose'); 					// mongoose for mongodb
var port  	 = process.env.PORT || 8080; 				// set the port
var database = require('./config/database'); 			// load the database config
var morgan   = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');

// configuration ===============================================================
mongoose.connect(database.url); 	// connect to mongoDB database on modulus.io

app.use(express.static(__dirname + '/public')); 		// set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request

// routes ======================================================================
require('./app/routes.js')(app);

// listen (start app with node server.js) ======================================
app.listen(port);
console.log("App listening on port " + port);*/

const http = require('http'),
  fs = require('fs'),
  path = require('path'),
  contentTypes = require('./utils/content-types'),
  sysInfo = require('./utils/sys-info'),
  express  = require('express'),
  bodyParser = require('body-parser'),
  cron = require('node-cron'),
  morgan   = require('morgan'),
  methodOverride = require('method-override'),
  env = process.env;

// timezone setting
process.env.TZ= 'Europe/Rome'

var app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use( require('./express/static'))
/*app.use( require('./express/api/messageInterceptor'))
app.use( require('./express/api/operateOnMessages'))
app.use( require('./express/api/operateOnIncomes'))
app.use( require('./express/api/operateOnMachines'))
app.use( require('./express/api/operateOnErrorMaps'))
app.use( require('./express/api/cron'))
app.use( require('./express/api/getTotalMoneyInstaneous'))*/

app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
app.use(morgan('dev')); // log every request to the console

var server = app.listen(process.env.NODE_PORT || process.env.PORT || 8080,  process.env.NODE_IP || 'localhost', function () {
    console.log('Server listening on', 8080)
})

exports.closeServer = function(){
  server.close();
};
<|endoftext|>


<commit_before>var SavedVariantView = Backbone.View.extend({
    template: _.template($('#tpl-saved-variant').html()),
    initialize: function(options) {
        this.variant = options.variant;
        this.family = options.family;
        this.hbc = options.hbc;
    },
    render: function(event) {
        var that = this;

        $(this.el).html(this.template({
            flags: that.variant.extras.family_notes,
            tags: that.variant.extras.family_tags,
            variant: that.variant,
            family_id: that.variant.extras.family_id,
            project_id: that.family.attributes.project_id,
        }));
        var view = new BasicVariantView({
            hbc: that.hbc,
            variant: this.variant,
            allow_saving: true,
            context: 'family',
            context_obj: that.family,
        });
        view.on('updated', function(variant) {
            that.variant = variant;
            that.render();
        });
        this.$('.variant-container').html(view.render().el);
        return this;
    },
});

var SavedVariantsView = Backbone.View.extend({

    initialize: function(options) {
        this.hbc = options.hbc;
        this.families = options.families;
        this.variants = options.variants;
    },

    render: function() {
        var that = this;
        if (this.variants.length == 0) {
            $(this.el).html('
No saved variants
');
        } else {
            _.each(this.variants, function(variant) {
                var family = new Family(_.find(that.families, function(f) { return f.family_id==variant.extras.family_id}));
                var view = new SavedVariantView({
                    variant: variant,
                    hbc: that.hbc,
                    family: family,
                });
                that.$el.append(view.render().el);
            });
        }
        return this;
    },

});

var SavedVariantsHBC = HeadBallCoach.extend({

    initialize: function(options) {

        // caller must provide these
        this.variants = options.variants;
        this.families = options.families;

        this.saved_variants_view = new SavedVariantsView({
            hbc: this,
            families: this.families,
            variants: this.variants,
        });

    },

    bind_to_dom: function() {
        $('#variants-container').html(this.saved_variants_view.render().el);
    },

    add_variant_flag: function(variant) {
        var that = this;
        function after_finished(variant) {
            var variant_i = -1;
            for (var i=0; i<that.variants.length; i++) {
                var v = that.variants[i];
                if (v.xpos == variant.xpos && v.ref == variant.ref && v.alt == variant.alt) {
                    variant_i = i;
                    break;
                }
            }
            that.variants[variant_i] = variant;
            that.resetModal();
            that.saved_variants_view.render();
        }

        var family = that.families[variant.extras.family_id];
        var flag_view = new AddFamilySearchFlagView({
            family: new Family(family),
            search_hash: "",
            variant: variant,
            suggested_inheritance: "",
            after_finished: after_finished,
        });
        this.pushModal("Flag Variant", flag_view);
    },

});

$(document).ready(function() {
    var hbc = new SavedVariantsHBC({
        families: FAMILIES,
        variants: VARIANTS,
    });

    hbc.bind_to_dom();
    window.hbc = hbc // remove

    Backbone.history.start();

});

<commit_msg>Add genotypes to tagged variants page and downloadable file<commit_after>var SavedVariantView = Backbone.View.extend({
    template: _.template($('#tpl-saved-variant').html()),
    initialize: function(options) {
        this.variant = options.variant;
        this.family = options.family;
        this.hbc = options.hbc;
    },
    render: function(event) {
        var that = this;

        $(this.el).html(this.template({
            flags: that.variant.extras.family_notes,
            tags: that.variant.extras.family_tags,
            variant: that.variant,
            family_id: that.variant.extras.family_id,
            project_id: that.family.attributes.project_id,
        }));
        var view = new BasicVariantView({
            hbc: that.hbc,
            variant: this.variant,
            allow_saving: true,
            context: 'family',
            context_obj: that.family,
	    individuals: that.family.attributes.individuals,
	    show_genotypes: true,
        });
        view.on('updated', function(variant) {
            that.variant = variant;
            that.render();
        });
        this.$('.variant-container').html(view.render().el);
        return this;
    },
});

var SavedVariantsView = Backbone.View.extend({

    initialize: function(options) {
        this.hbc = options.hbc;
        this.families = options.families;
        this.variants = options.variants;
    },

    render: function() {
        var that = this;
        if (this.variants.length == 0) {
            $(this.el).html('
No saved variants
');
        } else {
            _.each(this.variants, function(variant) {
                var family = new Family(_.find(that.families, function(f) { return f.family_id==variant.extras.family_id}));
                var view = new SavedVariantView({
                    variant: variant,
                    hbc: that.hbc,
                    family: family,
                });
                that.$el.append(view.render().el);
            });
        }
        return this;
    },

});

var SavedVariantsHBC = HeadBallCoach.extend({

    initialize: function(options) {

        // caller must provide these
        this.variants = options.variants;
        this.families = options.families;

        this.saved_variants_view = new SavedVariantsView({
            hbc: this,
            families: this.families,
            variants: this.variants,
        });

    },

    bind_to_dom: function() {
        $('#variants-container').html(this.saved_variants_view.render().el);
    },

    add_variant_flag: function(variant) {
        var that = this;
        function after_finished(variant) {
            var variant_i = -1;
            for (var i=0; i<that.variants.length; i++) {
                var v = that.variants[i];
                if (v.xpos == variant.xpos && v.ref == variant.ref && v.alt == variant.alt) {
                    variant_i = i;
                    break;
                }
            }
            that.variants[variant_i] = variant;
            that.resetModal();
            that.saved_variants_view.render();
        }

        var family = that.families[variant.extras.family_id];
        var flag_view = new AddFamilySearchFlagView({
            family: new Family(family),
            search_hash: "",
            variant: variant,
            suggested_inheritance: "",
            after_finished: after_finished,
        });
        this.pushModal("Flag Variant", flag_view);
    },

});

$(document).ready(function() {
    var hbc = new SavedVariantsHBC({
        families: FAMILIES,
        variants: VARIANTS,
    });

    hbc.bind_to_dom();
    window.hbc = hbc // remove

    Backbone.history.start();

});

<|endoftext|>


<commit_before>"use strict";

const CONNECTION_PORT = 9050;

const net = require('net');
const util = require('util');
const EventEmitter = require('events');

function gateway(config) {
    this.idleTimeout = 3000;
    this.host = config.host;
    this.name = config.name || config.host;
    this.id = config.mac || config.name;

    this.client = new net.Socket();
    this.connected = false;
    this.data = '';

    this.client.on('close', function() {
        this.connected = false;
        this.emit('gateway', null, null);
//        console.log('gateway close');
    }.bind(this));

    this.client.on('error', function (err) {
        this.connected = false;
        this.emit('gateway', err, null);
//        console.log('gateway error');
    }.bind(this));

    this.client.on('data', function(data) {
        this.data += data;
        var arr = this.data.split("\r\n\r\n");

        this.data = arr[arr.length-1];

        for (var i = 0; i < arr.length-1; ++i) {
            try{
                var json=JSON.parse(arr[i]);

                // Check for channel messages
                // {"PROTOCOL":"0.03","TIMESTAMP":"08154711","CMD":"ITEM_UPDATE_IND","VALUES":[{"NUMBER":"16","VALUE":"1","STATE":"ON","SETPOINT":"255"}]}
                if (json && (json.CMD == "ITEM_UPDATE_IND") && Array.isArray(json.VALUES)) {
                    json.VALUES.forEach(function(obj) {
                        if (obj.NUMBER){
                            this.emit(obj.NUMBER.toString(), null, obj);
                        }
                    }.bind(this));
                }
                else {
                    this.emit('gateway', null, json);
                }
            }catch(e){
                this.emit('gateway', e, null);
            }
        }
    }.bind(this));
}

util.inherits(gateway, EventEmitter);

module.exports = function (config) {
    return new gateway(config);
}

gateway.prototype.connect = function() {
    if (this.connected) return;
    if (!this.host) return;
    this.connected = true;

    this.client.connect(CONNECTION_PORT, this.host, function() {
            this.client.setTimeout(this.idleTimeout, function() {
                this.disconnect();
            }.bind(this))
        }.bind(this));
}

gateway.prototype.disconnect = function() {
    this.client.end();
    this.connected = false;
}

gateway.prototype.send = function(data) {
    this.client.write(data);
}

////////////////////////////////////////////////////////////////////////////////
//
//  Gateway commands
//

gateway.prototype.getVersion = function(callback){
    var l;

    if (callback) l = new responseListener(this, "VERSION_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"CMD":"VERSION_REQ","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}"}\r\n\r\n`;
    this.client.write(msg);

// response: {"PROTOCOL":"0.03","TIMESTAMP":"08154711","CMD":"VERSION_RES","FIRMWARE":"0.91","HARDWARE":"73355700","ENET":"45068305","PROTOCOL":"0.03"}
}

gateway.prototype.getBlockList = function(callback){
    var l;

    if (callback) l = new responseListener(this, "BLOCK_LIST_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"CMD":"BLOCK_LIST_REQ","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}","LIST-RANGE":1}\r\n\r\n`;
    this.client.write(msg);

// response: {"PROTOCOL":"0.03","TIMESTAMP":"08154711","CMD":"BLOCK_LIST_RES","STATE":0,"LIST-RANGE":1,"LIST-SIZE":[36,227,76,35,51,313,97,13,0,0],"DATA-IDS":[1,6,1,1,1,10,1,1,0,0]}
}

gateway.prototype.getChannelInfo = function(callback){
    var l;

    if (callback) l = new responseListener(this, "GET_CHANNEL_INFO_ALL_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"CMD":"GET_CHANNEL_INFO_ALL_REQ","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}"}\r\n\r\n`;
    this.client.write(msg);

// response: {"PROTOCOL":"0.03","TIMESTAMP":"08154711","CMD":"GET_CHANNEL_INFO_ALL_RES","DEVICES":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}
}

gateway.prototype.getProjectList = function(callback){
    var l;

    if (callback) l = new responseListener(this, "PROJECT_LIST_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"CMD":"PROJECT_LIST_GET","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}"}\r\n\r\n`;
    this.client.write(msg);
}

////////////////////////////////////////////////////////////////////////////////
//
//  Channel commands
//

gateway.prototype.signOut = function(channels, callback){
    var l;

    if (!Array.isArray(channels))
    {
        callback && callback(new Error('signOut needs a channels array.'));
        return;
    }

    if (callback) l = new responseListener(this, "ITEM_VALUE_SIGN_OUT_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"ITEMS":${JSON.stringify(channels)},"CMD":"ITEM_VALUE_SIGN_OUT_REQ","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}"}\r\n\r\n`;
    this.client.write(msg);

// response: {"PROTOCOL":"0.03","TIMESTAMP":"08154711","CMD":"ITEM_VALUE_SIGN_OUT_RES"}
}

gateway.prototype.signIn = function(channels, callback){
    var l;

    if (!Array.isArray(channels))
    {
        if (callback) callback(new Error('signIn needs a channels array.'));
        return;
    }

    if (callback) l = new responseListener(this, "ITEM_VALUE_SIGN_IN_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"ITEMS":${JSON.stringify(channels)},"CMD":"ITEM_VALUE_SIGN_IN_REQ","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}"}\r\n\r\n`;
    this.client.write(msg);

// response: {"PROTOCOL":"0.03","TIMESTAMP":"08154711","CMD":"ITEM_VALUE_SIGN_IN_RES","ITEMS":[16]}
}

gateway.prototype.setValue = function(channel, on, long, callback){
    var l;

    if (callback) l = new channelResponseListener(this, channel, "ITEM_VALUE_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"CMD":"ITEM_VALUE_SET","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}","VALUES":[{"STATE":"${on ? "ON":"OFF"}"${long ? ",\"LONG_CLICK\":\"ON\"" : ""},"NUMBER":${channel}}]}\r\n\r\n`;
//    var msg = `{"CMD":"ITEM_VALUE_SET","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}","VALUES":[{"STATE":"${on ? "ON":"OFF"}","LONG_CLICK":"${long ? "ON":"OFF"}","NUMBER":${channel}}]}\r\n\r\n`;

    this.client.write(msg);

// response: {"CMD":"ITEM_VALUE_RES","PROTOCOL":"0.03","TIMESTAMP":"1467998383","VALUES":[{"NUMBER":16,"STATE":"OFF"}]}
}

gateway.prototype.setValueDim = function(channel, dimVal, callback){
    var l;

    if (callback) l = new channelResponseListener(this, channel, "ITEM_VALUE_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"CMD":"ITEM_VALUE_SET","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}","VALUES":[{"STATE":"VALUE_DIMM","VALUE":${dimVal},"NUMBER":${channel}}]}\r\n\r\n`;

    this.client.write(msg);
}

gateway.prototype.setValueBlind = function(channel, blindVal, callback){
    var l;

    if (callback) l = new channelResponseListener(this, channel, "ITEM_VALUE_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"CMD":"ITEM_VALUE_SET","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}","VALUES":[{"STATE":"VALUE_BLINDS","VALUE":${blindVal},"NUMBER":${channel}}]}\r\n\r\n`;

    this.client.write(msg);
}

function responseListener(gateway, response, callback) {
    this.gateway = gateway;
    this.cb = function(err, msg) {
        if (err)
        {
            gateway.removeListener('gateway', this.cb);
            callback(err);
        }
        else {
            if (!msg) {
                gateway.removeListener('gateway', this.cb);
                callback(new Error("Gateway disconnected."));
                return;
            }

            if (msg.CMD === response){
                gateway.removeListener('gateway', this.cb);
                callback(null, msg);
            }
        }
    };

    gateway.on('gateway', this.cb.bind(this));
}

function channelResponseListener(gateway, channel, response, callback) {
    this.gateway = gateway;
    this.listening = true;

    this.cb = function(err, msg) {
        if (err)
        {
            gateway.removeListener('gateway', this.cb);
            callback(err);
        }
        else {
            if (!msg) {
                gateway.removeListener('gateway', this.cb);
                callback(new Error("Gateway disconnected."));
                return;
            }
            if ((msg.CMD === response) && Array.isArray(msg.VALUES)) {
                msg.VALUES.forEach(function(obj) {
                    if (obj.NUMBER === channel.toString()){
                        gateway.removeListener('gateway', this.cb);
                        callback(null, obj);
                    }
                }.bind(this));
            }
        }
    };

    gateway.on('gateway', this.cb.bind(this));
}
<commit_msg>bugfixes<commit_after>"use strict";

const CONNECTION_PORT = 9050;

const net = require('net');
const util = require('util');
const EventEmitter = require('events');

function gateway(config) {
    this.idleTimeout = 3000;
    this.host = config.host;
    this.name = config.name || config.host;
    this.id = config.mac || config.name;

    this.client = new net.Socket();
    this.connected = false;
    this.data = '';

    this.client.on('close', function() {
        this.connected = false;
        this.emit('gateway', null, null);
//        console.log('gateway close');
    }.bind(this));

    this.client.on('error', function (err) {
        this.connected = false;
        this.emit('gateway', err, null);
//        console.log('gateway error');
    }.bind(this));

    this.client.on('data', function(data) {
        this.data += data;
        var arr = this.data.split("\r\n\r\n");

        this.data = arr[arr.length-1];

        for (var i = 0; i < arr.length-1; ++i) {
            try{
                var json=JSON.parse(arr[i]);

                // Check for channel messages
                // {"PROTOCOL":"0.03","TIMESTAMP":"08154711","CMD":"ITEM_UPDATE_IND","VALUES":[{"NUMBER":"16","VALUE":"1","STATE":"ON","SETPOINT":"255"}]}
                if (json && (json.CMD == "ITEM_UPDATE_IND") && Array.isArray(json.VALUES)) {
                    json.VALUES.forEach(function(obj) {
                        if (obj.NUMBER){
                            this.emit(obj.NUMBER.toString(), null, obj);
                        }
                    }.bind(this));
                }
                else {
                    this.emit('gateway', null, json);
                }
            }catch(e){
                this.emit('gateway', e, null);
            }
        }
    }.bind(this));
}

util.inherits(gateway, EventEmitter);

module.exports = function (config) {
    return new gateway(config);
}

gateway.prototype.connect = function() {
    if (this.connected) return;
    if (!this.host) return;
    this.connected = true;

    this.client.connect(CONNECTION_PORT, this.host, function() {
            this.client.setTimeout(this.idleTimeout, function() {
                this.disconnect();
            }.bind(this))
        }.bind(this));
}

gateway.prototype.disconnect = function() {
    this.client.end();
    this.connected = false;
}

gateway.prototype.send = function(data) {
    this.client.write(data);
}

////////////////////////////////////////////////////////////////////////////////
//
//  Gateway commands
//

gateway.prototype.getVersion = function(callback){
    var l;

    if (callback) l = new responseListener(this, "VERSION_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"CMD":"VERSION_REQ","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}"}\r\n\r\n`;
    this.client.write(msg);

// response: {"PROTOCOL":"0.03","TIMESTAMP":"08154711","CMD":"VERSION_RES","FIRMWARE":"0.91","HARDWARE":"73355700","ENET":"45068305","PROTOCOL":"0.03"}
}

gateway.prototype.getBlockList = function(callback){
    var l;

    if (callback) l = new responseListener(this, "BLOCK_LIST_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"CMD":"BLOCK_LIST_REQ","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}","LIST-RANGE":1}\r\n\r\n`;
    this.client.write(msg);

// response: {"PROTOCOL":"0.03","TIMESTAMP":"08154711","CMD":"BLOCK_LIST_RES","STATE":0,"LIST-RANGE":1,"LIST-SIZE":[36,227,76,35,51,313,97,13,0,0],"DATA-IDS":[1,6,1,1,1,10,1,1,0,0]}
}

gateway.prototype.getChannelInfo = function(callback){
    var l;

    if (callback) l = new responseListener(this, "GET_CHANNEL_INFO_ALL_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"CMD":"GET_CHANNEL_INFO_ALL_REQ","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}"}\r\n\r\n`;
    this.client.write(msg);

// response: {"PROTOCOL":"0.03","TIMESTAMP":"08154711","CMD":"GET_CHANNEL_INFO_ALL_RES","DEVICES":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}
}

gateway.prototype.getProjectList = function(callback){
    var l;

    if (callback) l = new responseListener(this, "PROJECT_LIST_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"CMD":"PROJECT_LIST_GET","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}"}\r\n\r\n`;
    this.client.write(msg);
}

////////////////////////////////////////////////////////////////////////////////
//
//  Channel commands
//

gateway.prototype.signOut = function(channels, callback){
    var l;

    if (!Array.isArray(channels))
    {
        callback && callback(new Error('signOut needs a channels array.'));
        return;
    }

    if (callback) l = new responseListener(this, "ITEM_VALUE_SIGN_OUT_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"ITEMS":${JSON.stringify(channels)},"CMD":"ITEM_VALUE_SIGN_OUT_REQ","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}"}\r\n\r\n`;
    this.client.write(msg);

// response: {"PROTOCOL":"0.03","TIMESTAMP":"08154711","CMD":"ITEM_VALUE_SIGN_OUT_RES"}
}

gateway.prototype.signIn = function(channels, callback){
    var l;

    if (!Array.isArray(channels))
    {
        if (callback) callback(new Error('signIn needs a channels array.'));
        return;
    }

    if (callback) l = new responseListener(this, "ITEM_VALUE_SIGN_IN_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"ITEMS":${JSON.stringify(channels)},"CMD":"ITEM_VALUE_SIGN_IN_REQ","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}"}\r\n\r\n`;
    this.client.write(msg);

// response: {"PROTOCOL":"0.03","TIMESTAMP":"08154711","CMD":"ITEM_VALUE_SIGN_IN_RES","ITEMS":[16]}
}

gateway.prototype.setValue = function(channel, on, long, callback){
    var l;

    if (callback) l = new channelResponseListener(this, channel, "ITEM_VALUE_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"CMD":"ITEM_VALUE_SET","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}","VALUES":[{"STATE":"${on ? "ON":"OFF"}"${long ? ",\"LONG_CLICK\":\"ON\"" : ""},"NUMBER":${channel}}]}\r\n\r\n`;
//    var msg = `{"CMD":"ITEM_VALUE_SET","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}","VALUES":[{"STATE":"${on ? "ON":"OFF"}","LONG_CLICK":"${long ? "ON":"OFF"}","NUMBER":${channel}}]}\r\n\r\n`;

    this.client.write(msg);

// response: {"CMD":"ITEM_VALUE_RES","PROTOCOL":"0.03","TIMESTAMP":"1467998383","VALUES":[{"NUMBER":16,"STATE":"OFF"}]}
}

gateway.prototype.setValueDim = function(channel, dimVal, callback){
    var l;

    if (callback) l = new channelResponseListener(this, channel, "ITEM_VALUE_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"CMD":"ITEM_VALUE_SET","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}","VALUES":[{"STATE":"VALUE_DIMM","VALUE":${dimVal},"NUMBER":${channel}}]}\r\n\r\n`;

    this.client.write(msg);
}

gateway.prototype.setValueBlind = function(channel, blindVal, callback){
    var l;

    if (callback) l = new channelResponseListener(this, channel, "ITEM_VALUE_RES", callback);

    if (!this.connected) this.connect();

    var msg = `{"CMD":"ITEM_VALUE_SET","PROTOCOL":"0.03","TIMESTAMP":"${Math.floor(Date.now()/1000)}","VALUES":[{"STATE":"VALUE_BLINDS","VALUE":${blindVal},"NUMBER":${channel}}]}\r\n\r\n`;

    this.client.write(msg);
}

function responseListener(gateway, response, callback) {
    this.gateway = gateway;

    this.cb = function(err, msg) {
        if (err)
        {
            gateway.removeListener('gateway', this.cb);
            callback(err);
        }
        else {
            if (!msg) {
                gateway.removeListener('gateway', this.cb);
                callback(new Error("Gateway disconnected."));
                return;
            }

            if (msg.CMD === response){
                gateway.removeListener('gateway', this.cb);
                callback(null, msg);
            }
        }
    }.bind(this);

    gateway.on('gateway', this.cb);
}

function channelResponseListener(gateway, channel, response, callback) {
    this.gateway = gateway;
    this.listening = true;

    this.cb = function(err, msg) {
        if (err)
        {
            gateway.removeListener('gateway', this.cb);
            callback(err);
        }
        else {
            if (!msg) {
                gateway.removeListener('gateway', this.cb);
                callback(new Error("Gateway disconnected."));
                return;
            }
            if ((msg.CMD === response) && Array.isArray(msg.VALUES)) {
                msg.VALUES.forEach(function(obj) {
                    if (obj.NUMBER === channel.toString()){
                        gateway.removeListener('gateway', this.cb);
                        callback(null, obj);
                    }
                }.bind(this));
            }
        }
    }.bind(this);

    gateway.on('gateway', this.cb);
}
<|endoftext|>


<commit_before>// GNU LGPL v2.1+: http://www.gnu.org/licenses/lgpl.html
'use strict';

// assert Vue is present
console.assert (Vue !== undefined);

// load utilities
require ('./hotkeys.js'); // adds $.click_hotkey()
const Util = require ('./utilities.js');
Vue.mixin (Util.vue_mixins.data_tmpl); // Allow automatic `data` construction (cloning) from `data_tmpl`

// load Vue components
const vue_components = [
  require ('./button.vue'),
  require ('./button-bar.vue'),
  require ('./color-picker.vue'),
  require ('./icon-button.vue'),
  require ('./piano-roll.vue'),
  require ('./playcontrols.vue'),
  require ('./part-thumb.vue'),
  require ('./modaldialog.vue'),
  require ('./aboutdialog.vue'),
  require ('./hscrollbar.vue'),
  require ('./track-list.vue'),
  require ('./track-view.vue'),
  require ('./projectshell.vue'),
];

// register components
vue_components.forEach (c => {
  Vue.component (c.name, c);
});
<commit_msg>EBEAST: vc/bundle.js: add very basic ebeast<->bse communication startup test<commit_after>// GNU LGPL v2.1+: http://www.gnu.org/licenses/lgpl.html
'use strict';

// assert Vue is present
console.assert (Vue !== undefined);

// load utilities
require ('./hotkeys.js'); // adds $.click_hotkey()
const Util = require ('./utilities.js');
Vue.mixin (Util.vue_mixins.data_tmpl); // Allow automatic `data` construction (cloning) from `data_tmpl`

// load Vue components
const vue_components = [
  require ('./button.vue'),
  require ('./button-bar.vue'),
  require ('./color-picker.vue'),
  require ('./icon-button.vue'),
  require ('./piano-roll.vue'),
  require ('./playcontrols.vue'),
  require ('./part-thumb.vue'),
  require ('./modaldialog.vue'),
  require ('./aboutdialog.vue'),
  require ('./hscrollbar.vue'),
  require ('./track-list.vue'),
  require ('./track-view.vue'),
  require ('./projectshell.vue'),
];

// register components
vue_components.forEach (c => {
  Vue.component (c.name, c);
});

// run BSE JS unit tests
function ebeast_test_bse_basics() {
  console.assert (Bse.server);
  const proj = Bse.server.create_project ('ebeast_test_bse_basics-A');
  console.assert (proj);
  console.assert (proj.get_name() == 'ebeast_test_bse_basics-A');
  console.assert (proj.get_prop ('uname') == 'ebeast_test_bse_basics-A');
  proj.set_prop ('uname', 'ebeast_test_bse_basics-B2');
  console.assert (proj.get_name() == 'ebeast_test_bse_basics-B2');
  console.assert (proj.get_prop ('uname') == 'ebeast_test_bse_basics-B2');
  let icon = proj.get_prop ('icon');
  console.assert (icon && icon.width == 0 && icon.height == 0);
  proj.set_prop ('icon', { width: 2, height: 2, pixels: [1, "", "3", 4] });
  icon = proj.get_prop ('icon');
  console.assert (icon && icon.width == 2 && icon.height == 2);
  console.assert (JSON.stringify (icon.pixels) == JSON.stringify ([1, 0, 1, 4]));
  console.log ("  COMPLETE  " + 'ebeast_test_bse_basics');
}
ebeast_test_bse_basics();

<|endoftext|>


<commit_before><commit_msg>cache navigator.userAgent.toLowerCase()<commit_after><|endoftext|>


<commit_before>var hours = ['10am','11am','12pm','1pm','2pm','3pm','4pm','5pm',];

var pikePlaceMarket = {
  minPeeps: 17,
  maxPeeps: 88,
  avgCookies: 5.2,
  total: [],

customerPerHour: function(min, max) {
  return Math.random() * (this.maxPeeps - this.minPeeps + 1) + this.minPeeps;
},

cookiesPerHour: function() {
  for(i = 0; i < hours.length; i++) {
    var totalCookies = Math.floor(this.customerPerHour() * this.avgCookies);
    this.total.push(totalCookies)
    console.log(this.total)
    }
  },

render: function() {
  var ulElement = document.getElementById('pike-place');
  for (i = 0; i < 8; i++) {
  var li = document.createElement('li');
    li.textContent = hours[i] + ' ' + this.total[i] + ' cookies';
    ulElement.appendChild(li);
    }
  }
}

pikePlaceMarket.customerPerHour();
pikePlaceMarket.cookiesPerHour();
pikePlaceMarket.render();
<commit_msg>showing average and totals<commit_after>var hours = ['10am','11am','12pm','1pm','2pm','3pm','4pm','5pm',];

var pikePlaceMarket = {
  minPeeps: 17,
  maxPeeps: 88,
  avgCookies: 5.2,
  total: 0,
  totalArr: [],

customerPerHour: function(min, max) {
  return Math.random() * (this.maxPeeps - this.minPeeps + 1) + this.minPeeps;
},

cookiesPerHour: function() {
  for(i = 0; i < hours.length; i++) {
    var totalCookies = Math.floor(this.customerPerHour() * this.avgCookies);
    this.totalArr.push(totalCookies)
    this.total += totalCookies
    console.log(this.totalArr)
    }
  },

render: function() {
  var ulElement = document.getElementById('pike-place');
  for (i = 0; i < 8; i++) {
  var li = document.createElement('li');
    li.textContent = hours[i] + ' ' + this.totalArr[i] + ' ' + ' cookies';
    ulElement.appendChild(li);
    }
    li.textContent = 'Totals ' + this.total;
    ulElement.appendChild[i];
  }
}

pikePlaceMarket.customerPerHour();
pikePlaceMarket.cookiesPerHour();
pikePlaceMarket.render();
<|endoftext|>


<commit_before>var exampleApp = angular.module('exampleApp', []);

exampleApp
  .controller('CustomerController', function ($scope) {
    $scope.customers = [
      { name: 'Dave', city: 'Phoenix'},
      { name: 'Napur', city: 'Denver' },
      { name: 'Heedy', city: 'Dallas'}
    ];
  });

<commit_msg>Use modules (ES6).<commit_after>var exampleApp = angular.module('exampleApp', []);

exampleApp
  .controller({
    CustomerController($scope) {
      $scope.customers = [
        { name: 'Dave', city: 'Phoenix'},
        { name: 'Napur', city: 'Denver' },
        { name: 'Heedy', city: 'Dallas'}
      ];
    }
  });
<|endoftext|>


<commit_before>var express = require('express')
var url = require('url')
var telldus = require('telldus')
var ws = require("nodejs-websocket")

var port = process.env.PORT || 9000
var portWs = 9001

var app = express()
app.set('port', port)
app.use(express.static(__dirname + '/public'))

app.get('/api/on', function(request, response) {
  var query = url.parse(request.url, true).query
  if (query && query.id) {
    console.log("Turning on id " + query.id)
    telldus.turnOn(parseInt(query.id), function(err) {
      var res = "OK: turn on id:" + query.id
      console.log(res)
      response.send(res)
    })
  }
})

app.get('/api/off', function(request, response) {
  var query = url.parse(request.url, true).query
  if (query && query.id) {
    console.log("Turning off id " + query.id)
    telldus.turnOff(parseInt(query.id), function(err) {
      var res = "OK: turn off id:" + query.id
      console.log(res)
      response.send(res)
    })
  }
})

app.get("/api/list", function(request, response) {
  telldus.getDevices(function(err,devices) {
    if (err) {
      console.log('Error: ' + err)
    } else {
      console.log(devices)
      response.send(devices)
    }
  })
})

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'))
})

var server = ws.createServer(function (conn) {
  sendState(conn)

  conn.on("text", function (str) {
    console.log("Received "+str)
  })
  conn.on("close", function (code, reason) {
    console.log("Connection closed")
  })
})
server.listen(portWs)

var sensorState = { temp1: "", humidity1: "", temp2: "", humidity2: "" }

var listener = telldus.addSensorEventListener(function(deviceId,protocol,model,type,value,timestamp) {
  console.log('New sensor event received: ',deviceId,protocol,model,type,value,timestamp)
  updateSensorState(deviceId, type, value)

  server.connections.forEach(function (conn) { sendState(conn) })
})

function updateSensorState(deviceId, type, value) {
  if (deviceId == "11" && type == 1) sensorState.temp1 = value
  else if (deviceId == "11" && type == 2) sensorState.humidity1 = value
  else if (deviceId == "21" && type == 1) sensorState.temp2 = value
  else if (deviceId == "21" && type == 2) sensorState.humidity2 = value
  else console.log("unknown sensor info: " + deviceId + "," + type + "," + value)
}

function sendState(conn) {
  conn.sendText(JSON.stringify(sensorState))
}<commit_msg>lister devices statuses<commit_after>var express = require('express')
var url = require('url')
var telldus = require('telldus')
var ws = require("nodejs-websocket")

var port = process.env.PORT || 9000
var portWs = 9001

var app = express()
app.set('port', port)
app.use(express.static(__dirname + '/public'))

app.get('/api/on', function(request, response) {
  var query = url.parse(request.url, true).query
  if (query && query.id) {
    console.log("Turning on id " + query.id)
    telldus.turnOn(parseInt(query.id), function(err) {
      var res = "OK: turn on id:" + query.id
      console.log(res)
      response.send(res)
    })
  }
})

app.get('/api/off', function(request, response) {
  var query = url.parse(request.url, true).query
  if (query && query.id) {
    console.log("Turning off id " + query.id)
    telldus.turnOff(parseInt(query.id), function(err) {
      var res = "OK: turn off id:" + query.id
      console.log(res)
      response.send(res)
    })
  }
})

app.get("/api/list", function(request, response) {
  telldus.getDevices(function(err,devices) {
    if (err) {
      console.log('Error: ' + err)
    } else {
      console.log(devices)
      response.send(devices)
    }
  })
})

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'))
})

var server = ws.createServer(function (conn) {
  sendState(conn)

  conn.on("text", function (str) {
    console.log("Received "+str)
  })
  conn.on("close", function (code, reason) {
    console.log("Connection closed")
  })
})
server.listen(portWs)

var sensorState = { temp1: "", humidity1: "", temp2: "", humidity2: "" }

var listener = telldus.addSensorEventListener(function(deviceId,protocol,model,type,value,timestamp) {
  updateSensorState(deviceId, type, value)
  server.connections.forEach(function (conn) { sendState(conn) })
})

var deviceListener = telldus.addDeviceEventListener(function(deviceId, status) {
  console.log('Device ' + deviceId + ' is now ' + status.name)
});

function updateSensorState(deviceId, type, value) {
  if (deviceId == "11" && type == 1) sensorState.temp1 = value
  else if (deviceId == "11" && type == 2) sensorState.humidity1 = value
  else if (deviceId == "21" && type == 1) sensorState.temp2 = value
  else if (deviceId == "21" && type == 2) sensorState.humidity2 = value
  else console.log("unknown sensor info: " + deviceId + "," + type + "," + value)
}

function sendState(conn) {
  conn.sendText(JSON.stringify(sensorState))
}<|endoftext|>


<commit_before>// This script is the main app script that powers Princeton Courses
// This script is run when the app is launched

// Greet the world!
console.log('Launching Princeton Courses.')

// Load Node.js components
const path = require('path')

// Load external dependencies
require('mongoose')
var express = require('express')
var session = require('cookie-session')
var CentralAuthenticationService = require('cas')
var app = express()

app.set('port', (process.env.PORT || 5000))
app.set('host', (process.env.HOST || 'http://localhost:5000'))

// Load internal models
// var courseModel = require('./course.js')
var UserModel = require('./user.js')
// var auth = require('./authentication.js')

// Connect to the database
require('./database.js')

// Configure CAS authentication
var casURL = 'https://fed.princeton.edu/cas/'
var cas = new CentralAuthenticationService({
  base_url: casURL,
  service: app.get('host') + '/verify'
})
app.use(session({ keys: ['key1', 'key2'] }))

// If the user is authenticated, load the user for the lifetime of this req
app.use('*', function (req, res, next) {
  if (req.session.cas) {
    UserModel.findByNetid(req.session.cas.netid, function (doc) {
      if (doc != null) {
        app.set('user', doc)
      }
      next()
    })
  } else {
    next()
  }
})

// Route a req for the homepage
app.get('/', function (req, res) {
    // Check whether the user has authenticated
  if (!req.session.cas) {
        // The user in unauthenticated. Display a splash page.
    res.render('pages/splash')
  } else {
        // The user has authenticated. Display the app
    res.render('pages/app', {
      netid: app.get('user').netid
    })
  }
})

// Handle replies from CAS server about authentication
app.get('/verify', function (req, res) {
  if (!req.session.cas) {
    var ticket = req.param('ticket')
    if (ticket) {
            // Check if the user has a valid ticket
      cas.validate(ticket, function (err, status, netid) {
        if (err) {
          res.send({ error: err })
        } else {
          req.session.cas = {
            status: status,
            netid: netid
          }

          console.log('Searching the database for a user with netid %s', netid)
          UserModel.findByNetid(req.session.cas.netid, function (user) {
            if (user == null) {
              var User = new UserModel({
                netid: netid
              })
              User.save(function (error) {
                if (error) {
                  console.log('An error occured saving a user: %s', error)
                }
              })
            }
            app.set('user', user)
          })

          res.redirect('/')
        }
      })
    } else {
      res.redirect('/')
    }
  } else {
    res.redirect('/')
  }
})

app.get('/login', function (req, res) {
  res.redirect(casURL + 'login?service=' + app.get('host') + '/verify')
})

app.get('/logout', function (req, res) {
  req.session = null
  res.redirect('/')
})

app.use(express.static(path.join(__dirname, '/public')))

// views is directory for all template files
app.set('views', path.join(__dirname, '/views'))
app.set('view engine', 'ejs')

// Start listening for reqs
app.listen(app.get('port'), function () {
  console.log('Listening for reqs on port %d.', app.get('port'))
})
<commit_msg>Comments<commit_after>// This script is the main app script that powers Princeton Courses
// This script is run when the app is launched

// Greet the world!
console.log('Launching Princeton Courses.')

// Load Node.js components
const path = require('path')

// Load external dependencies
require('mongoose')
var express = require('express')
var session = require('cookie-session')
var CentralAuthenticationService = require('cas')
var app = express()

app.set('port', (process.env.PORT || 5000))
app.set('host', (process.env.HOST || 'http://localhost:5000'))

// Load internal models
// var courseModel = require('./course.js')
var UserModel = require('./user.js')
// var auth = require('./authentication.js')

// Connect to the database
require('./database.js')

// Configure CAS authentication
var casURL = 'https://fed.princeton.edu/cas/'
var cas = new CentralAuthenticationService({
  base_url: casURL,
  service: app.get('host') + '/verify'
})
app.use(session({ keys: ['key1', 'key2'] }))

//OMG I WROTE SOME COMMENTS DOPE
// If the user is authenticated, load the user for the lifetime of this req
app.use('*', function (req, res, next) {
  if (req.session.cas) {
    UserModel.findByNetid(req.session.cas.netid, function (doc) {
      if (doc != null) {
        app.set('user', doc)
      }
      next()
    })
  } else {
    next()
  }
})

// Route a req for the homepage
app.get('/', function (req, res) {
    // Check whether the user has authenticated
  if (!req.session.cas) {
        // The user in unauthenticated. Display a splash page.
    res.render('pages/splash')
  } else {
        // The user has authenticated. Display the app
    res.render('pages/app', {
      netid: app.get('user').netid
    })
  }
})

// Handle replies from CAS server about authentication
app.get('/verify', function (req, res) {
  if (!req.session.cas) {
    var ticket = req.param('ticket')
    if (ticket) {
            // Check if the user has a valid ticket
      cas.validate(ticket, function (err, status, netid) {
        if (err) {
          res.send({ error: err })
        } else {
          req.session.cas = {
            status: status,
            netid: netid
          }

          console.log('Searching the database for a user with netid %s', netid)
          UserModel.findByNetid(req.session.cas.netid, function (user) {
            if (user == null) {
              var User = new UserModel({
                netid: netid
              })
              User.save(function (error) {
                if (error) {
                  console.log('An error occured saving a user: %s', error)
                }
              })
            }
            app.set('user', user)
          })

          res.redirect('/')
        }
      })
    } else {
      res.redirect('/')
    }
  } else {
    res.redirect('/')
  }
})

app.get('/login', function (req, res) {
  res.redirect(casURL + 'login?service=' + app.get('host') + '/verify')
})

app.get('/logout', function (req, res) {
  req.session = null
  res.redirect('/')
})

app.use(express.static(path.join(__dirname, '/public')))

// views is directory for all template files
app.set('views', path.join(__dirname, '/views'))
app.set('view engine', 'ejs')

// Start listening for reqs
app.listen(app.get('port'), function () {
  console.log('Listening for reqs on port %d.', app.get('port'))
})
<|endoftext|>