<commit_before>var patch;
var h = 640;
var gridSize = 15;
var w = h / gridSize;

var colors, grid = [];

var setup = function () {
  // start Pure Data
  $.get('patter-synth.pd', function(patchStr) {
    patch = Pd.loadPatch(patchStr);
    Pd.start();
  });

  // start graphics
  colors = [color(0,0,255), color(0,255,0), color(255,0,0)];

  for (var i = 0; i < gridSize; i++) {
    grid[i] = [];
    for (var j = 0; j < gridSize; j++) {
      grid[i][j] = {clicked:false, color: color(0,0,0)};
    }
  }
  createCanvas(h, h);
  stroke(0);
  fill(150);
};

// Drawer function that continuously loops
var draw = function () {
  background(color(255,255,255));

  stroke(200);
  for (var i = 0; i < gridSize; i++) {
    for (var j = 0; j < gridSize; j++) {
      fill(grid[i][j].clicked ? grid[i][j].color : 255);
      rect(i*w, j*w, w-1, w-1);
    }
  }
};

var mousePressed = function () {
  grid[Math.floor(mouseX/w)][Math.floor(mouseY/w)].clicked = true;
};

var checkGrid = function (grid) {
  console.log(grid);
  return;
};

function isShape0(x,y) {
  var cellsToCheck = [
  [x-1, y-1],
  [x-1, y],
  [x-1, y+1]
  [x, y-1],
  [x, y+1],
  [x+1, y-1],
  [x+1, y],
  [x+1, y+1]];
  var tempx,tempy;
  for (var i = 0; i < cellsToCheck.length; i++) {
    tempx = cellsToCheck[i][0];
    tempy = cellsToCheck[i][1];
    if(!(grid[x][y] == "black" && grid[tempx][tempy] == "black")) return false;
  }
  return true;
}

function isShape1(x,y) {
  var cellsToCheck = [
  [x, y+1],
  [x, y+2],
  [x+1, y],
  [x+1, y+2],
  [x+2, y],
  [x+2, y+1],
  [x+2, y+2]];
  var tempx,tempy;
  for (var i = 0; i < cellsToCheck.length; i++) {
    tempx = cellsToCheck[i][0];
    tempy = cellsToCheck[i][1];
    if(!(grid[x][y] == "black" && grid[tempx][tempy] == "black")) return false;
  }
  return true;
}

function isShape2(x,y) {
  var cellsToCheck = [
  [x, y+2],
  [x+2, y],
  [x+2, y+2]];
  var tempx,tempy;
  for (var i = 0; i < cellsToCheck.length; i++) {
    tempx = cellsToCheck[i][0];
    tempy = cellsToCheck[i][1];
    if(!(grid[x][y] == "black" && grid[tempx][tempy] == "black")) return false;
  }
  return true;
}

function isShape3(x,y) {
  var cellsToCheck = [
  [x, y-1],
  [x, y+1],
  [x+2, y]];
  var tempx,tempy;
  for (var i = 0; i < cellsToCheck.length; i++) {
    tempx = cellsToCheck[i][0];
    tempy = cellsToCheck[i][1];
    if(!(grid[x][y] == "black" && grid[tempx][tempy] == "black")) return false;
  }
  return true;
}

function isShape4(x,y) {
  var cellsToCheck = [
  [x-1, y-1],
  [x-1, y+1],
  [x+1, y-1],
  [x+1, y+1]];
  var tempx,tempy;
  for (var i = 0; i < cellsToCheck.length; i++) {
    tempx = cellsToCheck[i][0];
    tempy = cellsToCheck[i][1];
    if(!(grid[x][y] == "black" && grid[tempx][tempy] == "black")) return false;
  }
  return true;
}

function isShape5(x, y) {
  var cellsToCheck = [
  [x, y+1],
  [x, y-1],
  [x+1, y],
  [x-1, y]];
  var tempx,tempy;
  for (var i = 0; i < cellsToCheck.length; i++) {
    tempx = cellsToCheck[i][0];
    tempy = cellsToCheck[i][1];
    if(!(grid[x][y] == "black" && grid[tempx][tempy] == "black")) return false;
  }
  return true;
}

var drawColor = function (x, y) {
  if (isShape0(x,y)) {
    //
  }
  else if (isShape1(x,y)) {
    //
  }
  else if (isShape2(x,y)) {
    //
  }
  else if (isShape3(x,y)) {
    //
  }
  else if (isShape4(x,y)) {
    //
  }
  else if (isShape5(x,y)) {
    //
  }
  else {
    //
  }
}
<commit_msg>changed .clicked<commit_after>var patch;
var h = 640;
var gridSize = 15;
var w = h / gridSize;

var colors, grid = [];

var setup = function () {
  // start Pure Data
  $.get('patter-synth.pd', function(patchStr) {
    patch = Pd.loadPatch(patchStr);
    Pd.start();
  });

  // start graphics
  colors = [color(0,0,255), color(0,255,0), color(255,0,0)];

  for (var i = 0; i < gridSize; i++) {
    grid[i] = [];
    for (var j = 0; j < gridSize; j++) {
      grid[i][j] = {clicked:false, color: color(0,0,0)};
    }
  }
  createCanvas(h, h);
  stroke(0);
  fill(150);
};

// Drawer function that continuously loops
var draw = function () {
  background(color(255,255,255));

  stroke(200);
  for (var i = 0; i < gridSize; i++) {
    for (var j = 0; j < gridSize; j++) {
      fill(grid[i][j].clicked ? grid[i][j].color : 255);
      rect(i*w, j*w, w-1, w-1);
    }
  }
};

var mousePressed = function () {
  grid[Math.floor(mouseX/w)][Math.floor(mouseY/w)].clicked = true;
};

var checkGrid = function (grid) {
  console.log(grid);
  return;
};

function isShape0(x,y) {
  var cellsToCheck = [
  [x-1, y-1],
  [x-1, y],
  [x-1, y+1]
  [x, y-1],
  [x, y+1],
  [x+1, y-1],
  [x+1, y],
  [x+1, y+1]];
  var tempx,tempy;
  for (var i = 0; i < cellsToCheck.length; i++) {
    tempx = cellsToCheck[i][0];
    tempy = cellsToCheck[i][1];
    if(!(grid[x][y].clicked && grid[tempx][tempy].clicked)) return false;
  }
  return true;
}

function isShape1(x,y) {
  var cellsToCheck = [
  [x, y+1],
  [x, y+2],
  [x+1, y],
  [x+1, y+2],
  [x+2, y],
  [x+2, y+1],
  [x+2, y+2]];
  var tempx,tempy;
  for (var i = 0; i < cellsToCheck.length; i++) {
    tempx = cellsToCheck[i][0];
    tempy = cellsToCheck[i][1];
    if(!(grid[x][y].clicked && grid[tempx][tempy].clicked)) return false;
  }
  return true;
}

function isShape2(x,y) {
  var cellsToCheck = [
  [x, y+2],
  [x+2, y],
  [x+2, y+2]];
  var tempx,tempy;
  for (var i = 0; i < cellsToCheck.length; i++) {
    tempx = cellsToCheck[i][0];
    tempy = cellsToCheck[i][1];
    if(!(grid[x][y].clicked && grid[tempx][tempy].clicked)) return false;
  }
  return true;
}

function isShape3(x,y) {
  var cellsToCheck = [
  [x, y-1],
  [x, y+1],
  [x+2, y]];
  var tempx,tempy;
  for (var i = 0; i < cellsToCheck.length; i++) {
    tempx = cellsToCheck[i][0];
    tempy = cellsToCheck[i][1];
    if(!(grid[x][y].clicked && grid[tempx][tempy].clicked)) return false;
  }
  return true;
}

function isShape4(x,y) {
  var cellsToCheck = [
  [x-1, y-1],
  [x-1, y+1],
  [x+1, y-1],
  [x+1, y+1]];
  var tempx,tempy;
  for (var i = 0; i < cellsToCheck.length; i++) {
    tempx = cellsToCheck[i][0];
    tempy = cellsToCheck[i][1];
    if(!(grid[x][y].clicked && grid[tempx][tempy].clicked)) return false;
  }
  return true;
}

function isShape5(x, y) {
  var cellsToCheck = [
  [x, y+1],
  [x, y-1],
  [x+1, y],
  [x-1, y]];
  var tempx,tempy;
  for (var i = 0; i < cellsToCheck.length; i++) {
    tempx = cellsToCheck[i][0];
    tempy = cellsToCheck[i][1];
    if(!(grid[x][y].clicked && grid[tempx][tempy].clicked)) return false;
  }
  return true;
}

var drawColor = function (x, y) {
  if (isShape0(x,y)) {
    //
  }
  else if (isShape1(x,y)) {
    //
  }
  else if (isShape2(x,y)) {
    //
  }
  else if (isShape3(x,y)) {
    //
  }
  else if (isShape4(x,y)) {
    //
  }
  else if (isShape5(x,y)) {
    //
  }
  else {
    //
  }
}
<|endoftext|>


<commit_before>'use strict';

var models    = require('./models'),
    passport  = require('passport');

module.exports = function(app) {

  var isAuthenticated = function (req, res, next) {
    if (req.isAuthenticated())
      return next();
    res.redirect('/login');
  }

  // home page
  app.get('/', function(req, res) {
    models.Match.table(models, req.params.season).then(function(table) {
      res.render('standings', {
        title: 'Standings',
        league: table
      });
    });;
  })

  // login
  app.route('/login')
    .get(function(req, res) {
      res.render('login', {
        title: 'Login'
      })
    })
    .post(passport.authenticate('local', {
        successRedirect: '/',
        failureRedirect: '/login',
      })
    );

  app.get('/logout', isAuthenticated, function(req, res) {
    req.logout();
    req.flash('message', 'User Logged Off');
    res.redirect('/');
  })

  // static pages
  app.get('/rules', function(req, res) {
    res.render('rules', {
      title: 'Rules'
    })
  })

  app.get('/format', function(req, res) {
    res.render('format', {
      title: 'League Format'
    })
  })

  // get the standings
  // optionally add a year to get that year's table
  app.get('/standings/:season?', function(req, res) {
    models.Match.table(models, req.params.season).then(function(table) { console.log(table);
      res.render('standings', {
        title: 'Standings',
        league: table,
        season: req.params.season || 2016
      })
    });
  })

  // get a team's result
  app.get('/teams/:id/:season?', function(req, res) {
    var team = models.Team.findById(req.params.id);
    var matches = models.Match.findAll({
      where: { $and: [{ season: req.params.season || app.locals.season }, { $or: [{ teama_id: req.params.id }, { teamb_id: req.params.id }] }] },
      raw: true,
      attributes: [
        'id',
        'score',
        'teama_id',
        'teamb_id',
        'round',
        [models.sequelize.fn('date_format', models.sequelize.col('date'), app.locals.date_format), 'date'],
      ],
      include: [{
        model: models.Team,
        as: 'TeamA',
        attributes: ['id', 'name']
      }, {
        model: models.Team,
        as: 'TeamB',
        attributes: ['id', 'name']
      }]
    });
    models.sequelize.Promise.join(
      team,
      matches,
      function(team, matches) {
        team.logo = team.name.replace(/\s|\'/g, '').toLowerCase() + '.png';
        for (var x = 0; x < matches.length; x++) {
          var scores = [], result = null;
          if (matches[x].teama_id == req.params.id) {
            matches[x].home = true;
            matches[x].logo = matches[x]['TeamB.name'].replace(/\s|\'/g, '').toLowerCase() + '.png';
          } else {
            matches[x].home = false;
            matches[x].logo = matches[x]['TeamA.name'].replace(/\s|\'/g, '').toLowerCase() + '.png';
          }

          if (matches[x].score) {
            scores = matches[x].score.split('-').map(function(e) { return e * 1; });
            if (matches[x].home) {
              matches[x].cls = (scores[0] > scores[1]) ? 'win' : 'lose';
            } else {
              matches[x].cls = (scores[0] < scores[1]) ? 'win' : 'lose';
              // if selected team is 'away' then reverse the order of the score
              matches[x].score = matches[x].score.split('-').reverse().join('-');
            }
          } else {
            matches[x].score = '-';
          }
        }
        res.render('teams', {
          title: team.name,
          team: team,
          matches: matches
        })
      })
  })

  app.get('/weeks/:id?/:season?', function(req, res) {
    models.Match.fixtures(models, req.params.id, req.params.season).then(function(data) {
      res.render('weeks', {
        title: (data.length == 1) ? 'Week ' + data[0].round : 'Fixtures',
        weeks: data
      })
    })
  })

  // handle the ajax POST of a result
  app.post('/matches/:id', function(req, res) {

    if (req.user) {
      models.Match.update({
        score: req.body.score
      }, {
        where: [{ id: req.params.id }, { season: 2016 }]
      }).then(function(rows) {
        res.send(rows == 1);
      })
    } else {
      res.sendStatus(403);
    }
  })

}<commit_msg>remove console.log in standings route<commit_after>'use strict';

var models    = require('./models'),
    passport  = require('passport');

module.exports = function(app) {

  var isAuthenticated = function (req, res, next) {
    if (req.isAuthenticated())
      return next();
    res.redirect('/login');
  }

  // home page
  app.get('/', function(req, res) {
    models.Match.table(models, req.params.season).then(function(table) {
      res.render('standings', {
        title: 'Standings',
        league: table
      });
    });;
  })

  // login
  app.route('/login')
    .get(function(req, res) {
      res.render('login', {
        title: 'Login'
      })
    })
    .post(passport.authenticate('local', {
        successRedirect: '/',
        failureRedirect: '/login',
      })
    );

  app.get('/logout', isAuthenticated, function(req, res) {
    req.logout();
    req.flash('message', 'User Logged Off');
    res.redirect('/');
  })

  // static pages
  app.get('/rules', function(req, res) {
    res.render('rules', {
      title: 'Rules'
    })
  })

  app.get('/format', function(req, res) {
    res.render('format', {
      title: 'League Format'
    })
  })

  // get the standings
  // optionally add a year to get that year's table
  app.get('/standings/:season?', function(req, res) {
    models.Match.table(models, req.params.season).then(function(table) {
      res.render('standings', {
        title: 'Standings',
        league: table,
        season: req.params.season || 2016
      })
    });
  })

  // get a team's result
  app.get('/teams/:id/:season?', function(req, res) {
    var team = models.Team.findById(req.params.id);
    var matches = models.Match.findAll({
      where: { $and: [{ season: req.params.season || app.locals.season }, { $or: [{ teama_id: req.params.id }, { teamb_id: req.params.id }] }] },
      raw: true,
      attributes: [
        'id',
        'score',
        'teama_id',
        'teamb_id',
        'round',
        [models.sequelize.fn('date_format', models.sequelize.col('date'), app.locals.date_format), 'date'],
      ],
      include: [{
        model: models.Team,
        as: 'TeamA',
        attributes: ['id', 'name']
      }, {
        model: models.Team,
        as: 'TeamB',
        attributes: ['id', 'name']
      }]
    });
    models.sequelize.Promise.join(
      team,
      matches,
      function(team, matches) {
        team.logo = team.name.replace(/\s|\'/g, '').toLowerCase() + '.png';
        for (var x = 0; x < matches.length; x++) {
          var scores = [], result = null;
          if (matches[x].teama_id == req.params.id) {
            matches[x].home = true;
            matches[x].logo = matches[x]['TeamB.name'].replace(/\s|\'/g, '').toLowerCase() + '.png';
          } else {
            matches[x].home = false;
            matches[x].logo = matches[x]['TeamA.name'].replace(/\s|\'/g, '').toLowerCase() + '.png';
          }

          if (matches[x].score) {
            scores = matches[x].score.split('-').map(function(e) { return e * 1; });
            if (matches[x].home) {
              matches[x].cls = (scores[0] > scores[1]) ? 'win' : 'lose';
            } else {
              matches[x].cls = (scores[0] < scores[1]) ? 'win' : 'lose';
              // if selected team is 'away' then reverse the order of the score
              matches[x].score = matches[x].score.split('-').reverse().join('-');
            }
          } else {
            matches[x].score = '-';
          }
        }
        res.render('teams', {
          title: team.name,
          team: team,
          matches: matches
        })
      })
  })

  app.get('/weeks/:id?/:season?', function(req, res) {
    models.Match.fixtures(models, req.params.id, req.params.season).then(function(data) {
      res.render('weeks', {
        title: (data.length == 1) ? 'Week ' + data[0].round : 'Fixtures',
        weeks: data
      })
    })
  })

  // handle the ajax POST of a result
  app.post('/matches/:id', function(req, res) {

    if (req.user) {
      models.Match.update({
        score: req.body.score
      }, {
        where: [{ id: req.params.id }, { season: 2016 }]
      }).then(function(rows) {
        res.send(rows == 1);
      })
    } else {
      res.sendStatus(403);
    }
  })

}<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')
const express = require('express')
const compile = require('lodash.template')
const rootPath = require('app-root-path').path
const resolve = file => path.resolve(rootPath, file)

const cache = require('./utils/cache-instance')
const apiStatus = require('./utils/api-status')
const HTMLContent = require('../pages/Compilation')
let config = require('config')

const compileOptions = {
  escape: /{{([^{][\s\S]+?[^}])}}/g,
  interpolate: /{{{([\s\S]+?)}}}/g
}

const isProd = process.env.NODE_ENV === 'production'
process.noDeprecation = true

const app = express()

const templatesCache = {}
let renderer
for (const tplName of Object.keys(config.ssr.templates)) {
  const fileName = resolve(config.ssr.templates[tplName])
  if (fs.existsSync(fileName)) {
    const template = fs.readFileSync(fileName, 'utf-8')
    templatesCache[tplName] = compile(template, compileOptions)
  }
}
if (isProd) {
  // In production: create server renderer using server bundle and index HTML
  // template from real fs.
  // The server bundle is generated by vue-ssr-webpack-plugin.
  const clientManifest = require(resolve('dist/vue-ssr-client-manifest.json'))
  const bundle = require(resolve('dist/vue-ssr-bundle.json'))
  // src/index.template.html is processed by html-webpack-plugin to inject
  // build assets and output as dist/index.html.
  // TODO: Add dynamic templates loading from (config based?) list
  renderer = createRenderer(bundle, clientManifest)
} else {
  // In development: setup the dev server with watch and hot-reload,
  // and create a new renderer on bundle / index template update.
  require(resolve('core/build/dev-server'))(app, (bundle, template) => {
    templatesCache['default'] = compile(template, compileOptions) // Important Notice: template switching doesn't work with dev server because of the HMR
    renderer = createRenderer(bundle)
  })
}

function createRenderer (bundle, clientManifest, template) {
  // https://github.com/vuejs/vue/blob/dev/packages/vue-server-renderer/README.md#why-use-bundlerenderer
  return require('vue-server-renderer').createBundleRenderer(bundle, {
    clientManifest,
    // runInNewContext: false,
    cache: require('lru-cache')({
      max: 1000,
      maxAge: 1000 * 60 * 15
    })
  })
}

function invalidateCache (req, res) {
  if (config.server.useOutputCache) {
    if (req.query.tag && req.query.key) { // clear cache pages for specific query tag
      if (req.query.key !== config.server.invalidateCacheKey) {
        console.error('Invalid cache invalidation key')
        apiStatus(res, 'Invalid cache invalidation key', 500)
        return
      }
      console.log(`Clear cache request for [${req.query.tag}]`)
      let tags = []
      if (req.query.tag === '*') {
        tags = config.server.availableCacheTags
      } else {
        tags = req.query.tag.split(',')
      }
      const subPromises = []
      tags.forEach(tag => {
        if (config.server.availableCacheTags.indexOf(tag) >= 0 || config.server.availableCacheTags.find(t => {
          return tag.indexOf(t) === 0
        })) {
          subPromises.push(cache.invalidate(tag).then(() => {
            console.log(`Tags invalidated successfully for [${tag}]`)
          }))
        } else {
          console.error(`Invalid tag name ${tag}`)
        }
      })
      Promise.all(subPromises).then(r => {
        apiStatus(res, `Tags invalidated successfully [${req.query.tag}]`, 200)
      }).catch(error => {
        apiStatus(res, error, 500)
        console.error(error)
      })
    } else {
      apiStatus(res, 'Invalid parameters for Clear cache request', 500)
      console.error('Invalid parameters for Clear cache request')
    }
  } else {
    apiStatus(res, 'Cache invalidation is not required, output cache is disabled', 200)
  }
}

const serve = (path, cache, options) => express.static(resolve(path), Object.assign({
  maxAge: cache && isProd ? 60 * 60 * 24 * 30 : 0
}, options))

const themeRoot = require('../build/theme-path')

app.use('/dist', serve('dist', true))
app.use('/assets', serve(themeRoot + '/assets', true))
app.use('/service-worker.js', serve('dist/service-worker.js', {
  setHeaders: {'Content-Type': 'text/javascript; charset=UTF-8'}
}))

const serverExtensions = require(resolve('src/server'))
serverExtensions.registerUserServerRoutes(app)

app.post('/invalidate', invalidateCache)

app.get('/invalidate', invalidateCache)

app.get('*', (req, res, next) => {
  const contains = (target, pattern) => {
    var value = 0
    pattern.forEach(word => {
      value = value + target.includes(word)
    })
    return (value >= 1)
  }

  if (contains(req.url, config.server.ssrDisabledFor.extensions)) {
    return
  }

  const s = Date.now()
  const errorHandler = err => {
    if (err && err.code === 404) {
      if (contains(req.url, config.server.customErrors.http404.notAllowedExtensions)) {
        console.error(`Resource not found : ${req.url}`)
        res.setHeader('Content-Type', 'text/html')
        res.status(404).end('<html lang="en">\n' +
          '    <head>\n' +
          '      <meta charset="utf-8">\n' +
          '      <title>Resource is not found</title>\n' +
          '    </head>\n' +
          '    <body>\n' +
          '      Vue Storefront: Resource is not found' +
          '    </body>\n' +
          '  </html>')
        next()
      } else {
        res.redirect('/page-not-found')
        console.error(`Redirect for resource not found : ${req.url}`)
      }
    } else {
      res.redirect('/error')
      console.error(`Error during render : ${req.url}`)
      console.error(err)
      next()
    }
  }

  const dynamicRequestHandler = renderer => {
    if (!renderer) {
      res.setHeader('Content-Type', 'text/html')
      res.status(202).end(HTMLContent)
      return next()
    }
    const context = {
      url: decodeURI(req.url),
      output: {
        prepend: (context) => { return '' }, // these functions can be replaced in the Vue components to append or prepend some content AFTER all other things are rendered. So in this function You may call: output.prepend() { return context.renderStyles() } to attach styles
        append: (context) => { return '' },
        appendHead: (context) => { return '' },
        template: 'default',
        cacheTags: null
      },
      server: {
        app: app,
        response: res,
        request: req
      },
      meta: null,
      vs: {
        config: config,
        storeCode: req.header('x-vs-store-code') ? req.header('x-vs-store-code') : process.env.STORE_CODE
      }
    }
    renderer.renderToString(context).then(output => {
      if (!res.get('content-type')) {
        res.setHeader('Content-Type', 'text/html')
      }
      let tagsArray = []
      if (config.server.useOutputCacheTagging && context.output.cacheTags !== null) {
        tagsArray = Array.from(context.output.cacheTags)
        const cacheTags = tagsArray.join(' ')
        res.setHeader('X-VS-Cache-Tags', cacheTags)
        console.log(`cache tags for the request: ${cacheTags}`)
      }
      const contentPrepend = (typeof context.output.prepend === 'function') ? context.output.prepend(context) : ''
      const contentAppend = (typeof context.output.append === 'function') ? context.output.append(context) : ''

      output = contentPrepend + output + contentAppend
      if (context.output.template) { // case when we've got the template name back from vue app
        if (!isProd) context.output.template = 'default' // in dev mode we can not use pre-rendered HTML templates
        if (templatesCache[context.output.template]) { // please look at: https://github.com/vuejs/vue/blob/79cabadeace0e01fb63aa9f220f41193c0ca93af/src/server/template-renderer/index.js#L87 for reference
          output = templatesCache[context.output.template](context).replace('<!--vue-ssr-outlet-->', output)
        } else {
          throw new Error(`The given template name ${context.output.template} does not exist`)
        }
      }
      if (config.server.useOutputCache && cache) {
        cache.set(
          'page:' + req.url,
          { headers: res.getHeaders(), body: output },
          tagsArray
        ).catch(errorHandler)
      }
      res.end(output)
      console.log(`whole request [${req.url}]: ${Date.now() - s}ms`)
      next()
    }).catch(errorHandler)
  }

  const dynamicCacheHandler = () => {
    if (config.server.useOutputCache && cache) {
      cache.get(
        'page:' + req.url
      ).then(output => {
        if (output !== null) {
          if (output.headers) {
            for (const header of Object.keys(output.headers)) {
              res.setHeader(header, output.headers[header])
            }
          }
          res.setHeader('X-VS-Cache', 'Hit')
          if (output.body) {
            res.end(output.body)
          } else {
            res.setHeader('Content-Type', 'text/html')
            res.end(output.body)
          }
          res.end(output)
          console.log(`cache hit [${req.url}], cached request: ${Date.now() - s}ms`)
          next()
        } else {
          res.setHeader('Content-Type', 'text/html')
          res.setHeader('X-VS-Cache', 'Miss')
          console.log(`cache miss [${req.url}], request: ${Date.now() - s}ms`)
          dynamicRequestHandler(renderer) // render response
        }
      }).catch(errorHandler)
    } else {
      dynamicRequestHandler(renderer)
    }
  }

  if (config.server.dynamicConfigReload) {
    delete require.cache[require.resolve('config')]
    config = require('config') // reload config
    if (typeof serverExtensions.configProvider === 'function') {
      serverExtensions.configProvider(req).then(loadedConfig => {
        config = Object.assign(config, loadedConfig) // merge loaded conf with build time conf
        dynamicCacheHandler()
      }).catch(error => {
        if (config.server.dynamicConfigContinueOnError) {
          dynamicCacheHandler()
        } else {
          console.log('config provider error:', error)
          if (req.url !== '/error') {
            res.redirect('/error')
          }
          dynamicCacheHandler()
        }
      })
    } else {
      config = require('config') // reload config
      dynamicCacheHandler()
    }
  } else {
    dynamicCacheHandler()
  }
})

let port = process.env.PORT || config.server.port
const host = process.env.HOST || config.server.host
const start = () => {
  app.listen(port, host)
    .on('listening', () => {
      console.log(`Vue Storefront Server started at http://${host}:${port}`)
    })
    .on('error', (e) => {
      if (e.code === 'EADDRINUSE') {
        port = parseInt(port) + 1
        console.log(`The port is already in use, trying ${port}`)
        start()
      }
    })
}
start()
<commit_msg>IKR-3951 Apply improvements to the handling of 404 errors<commit_after>const fs = require('fs')
const path = require('path')
const express = require('express')
const compile = require('lodash.template')
const rootPath = require('app-root-path').path
const resolve = file => path.resolve(rootPath, file)

const cache = require('./utils/cache-instance')
const apiStatus = require('./utils/api-status')
const HTMLContent = require('../pages/Compilation')
let config = require('config')

const compileOptions = {
  escape: /{{([^{][\s\S]+?[^}])}}/g,
  interpolate: /{{{([\s\S]+?)}}}/g
}

const isProd = process.env.NODE_ENV === 'production'
process.noDeprecation = true

const app = express()

const templatesCache = {}
let renderer
for (const tplName of Object.keys(config.ssr.templates)) {
  const fileName = resolve(config.ssr.templates[tplName])
  if (fs.existsSync(fileName)) {
    const template = fs.readFileSync(fileName, 'utf-8')
    templatesCache[tplName] = compile(template, compileOptions)
  }
}
if (isProd) {
  // In production: create server renderer using server bundle and index HTML
  // template from real fs.
  // The server bundle is generated by vue-ssr-webpack-plugin.
  const clientManifest = require(resolve('dist/vue-ssr-client-manifest.json'))
  const bundle = require(resolve('dist/vue-ssr-bundle.json'))
  // src/index.template.html is processed by html-webpack-plugin to inject
  // build assets and output as dist/index.html.
  // TODO: Add dynamic templates loading from (config based?) list
  renderer = createRenderer(bundle, clientManifest)
} else {
  // In development: setup the dev server with watch and hot-reload,
  // and create a new renderer on bundle / index template update.
  require(resolve('core/build/dev-server'))(app, (bundle, template) => {
    templatesCache['default'] = compile(template, compileOptions) // Important Notice: template switching doesn't work with dev server because of the HMR
    renderer = createRenderer(bundle)
  })
}

function createRenderer (bundle, clientManifest, template) {
  // https://github.com/vuejs/vue/blob/dev/packages/vue-server-renderer/README.md#why-use-bundlerenderer
  return require('vue-server-renderer').createBundleRenderer(bundle, {
    clientManifest,
    // runInNewContext: false,
    cache: require('lru-cache')({
      max: 1000,
      maxAge: 1000 * 60 * 15
    })
  })
}

function invalidateCache (req, res) {
  if (config.server.useOutputCache) {
    if (req.query.tag && req.query.key) { // clear cache pages for specific query tag
      if (req.query.key !== config.server.invalidateCacheKey) {
        console.error('Invalid cache invalidation key')
        apiStatus(res, 'Invalid cache invalidation key', 500)
        return
      }
      console.log(`Clear cache request for [${req.query.tag}]`)
      let tags = []
      if (req.query.tag === '*') {
        tags = config.server.availableCacheTags
      } else {
        tags = req.query.tag.split(',')
      }
      const subPromises = []
      tags.forEach(tag => {
        if (config.server.availableCacheTags.indexOf(tag) >= 0 || config.server.availableCacheTags.find(t => {
          return tag.indexOf(t) === 0
        })) {
          subPromises.push(cache.invalidate(tag).then(() => {
            console.log(`Tags invalidated successfully for [${tag}]`)
          }))
        } else {
          console.error(`Invalid tag name ${tag}`)
        }
      })
      Promise.all(subPromises).then(r => {
        apiStatus(res, `Tags invalidated successfully [${req.query.tag}]`, 200)
      }).catch(error => {
        apiStatus(res, error, 500)
        console.error(error)
      })
    } else {
      apiStatus(res, 'Invalid parameters for Clear cache request', 500)
      console.error('Invalid parameters for Clear cache request')
    }
  } else {
    apiStatus(res, 'Cache invalidation is not required, output cache is disabled', 200)
  }
}

const serve = (path, cache, options) => express.static(resolve(path), Object.assign({
  maxAge: cache && isProd ? 60 * 60 * 24 * 30 : 0
}, options))

const themeRoot = require('../build/theme-path')

app.use('/dist', serve('dist', true))
app.use('/assets', serve(themeRoot + '/assets', true))
app.use('/service-worker.js', serve('dist/service-worker.js', {
  setHeaders: {'Content-Type': 'text/javascript; charset=UTF-8'}
}))

const serverExtensions = require(resolve('src/server'))
serverExtensions.registerUserServerRoutes(app)

app.post('/invalidate', invalidateCache)

app.get('/invalidate', invalidateCache)

app.get('*', (req, res, next) => {
  const NOT_ALLOWED_SSR_EXTENSIONS_REGEX = new RegExp(`(.*)(${config.server.ssrDisabledFor.extensions.join('|')})$`)
  const NOT_ALLOWED_CUSTOMERROR404_EXTENSIONS_REGEX = new RegExp(`(.*)(${config.server.customErrors.http404.notAllowedExtensions.join('|')})$`)
  if (NOT_ALLOWED_SSR_EXTENSIONS_REGEX.test(req.url)) {
    utils.apiStatus(res, 'Vue Storefront: Resource is not found', 404)
    return
  }

  const s = Date.now()
  const errorHandler = err => {
    if (err && err.code === 404) {
      if (NOT_ALLOWED_CUSTOMERROR404_EXTENSIONS_REGEX.test(req.url)) {
        utils.apiStatus(res, 'Vue Storefront: Resource is not found', 404)
        console.error(`Resource is not found : ${req.url}`)
        next()
      } else {
        res.redirect('/page-not-found')
        console.error(`Redirect for resource not found : ${req.url}`)
      }
    } else {
      res.redirect('/error')
      console.error(`Error during render : ${req.url}`)
      console.error(err)
      next()
    }
  }

  const dynamicRequestHandler = renderer => {
    if (!renderer) {
      res.setHeader('Content-Type', 'text/html')
      res.status(202).end(HTMLContent)
      return next()
    }
    const context = {
      url: decodeURI(req.url),
      output: {
        prepend: (context) => { return '' }, // these functions can be replaced in the Vue components to append or prepend some content AFTER all other things are rendered. So in this function You may call: output.prepend() { return context.renderStyles() } to attach styles
        append: (context) => { return '' },
        appendHead: (context) => { return '' },
        template: 'default',
        cacheTags: null
      },
      server: {
        app: app,
        response: res,
        request: req
      },
      meta: null,
      vs: {
        config: config,
        storeCode: req.header('x-vs-store-code') ? req.header('x-vs-store-code') : process.env.STORE_CODE
      }
    }
    renderer.renderToString(context).then(output => {
      if (!res.get('content-type')) {
        res.setHeader('Content-Type', 'text/html')
      }
      let tagsArray = []
      if (config.server.useOutputCacheTagging && context.output.cacheTags !== null) {
        tagsArray = Array.from(context.output.cacheTags)
        const cacheTags = tagsArray.join(' ')
        res.setHeader('X-VS-Cache-Tags', cacheTags)
        console.log(`cache tags for the request: ${cacheTags}`)
      }
      const contentPrepend = (typeof context.output.prepend === 'function') ? context.output.prepend(context) : ''
      const contentAppend = (typeof context.output.append === 'function') ? context.output.append(context) : ''

      output = contentPrepend + output + contentAppend
      if (context.output.template) { // case when we've got the template name back from vue app
        if (!isProd) context.output.template = 'default' // in dev mode we can not use pre-rendered HTML templates
        if (templatesCache[context.output.template]) { // please look at: https://github.com/vuejs/vue/blob/79cabadeace0e01fb63aa9f220f41193c0ca93af/src/server/template-renderer/index.js#L87 for reference
          output = templatesCache[context.output.template](context).replace('<!--vue-ssr-outlet-->', output)
        } else {
          throw new Error(`The given template name ${context.output.template} does not exist`)
        }
      }
      if (config.server.useOutputCache && cache) {
        cache.set(
          'page:' + req.url,
          { headers: res.getHeaders(), body: output },
          tagsArray
        ).catch(errorHandler)
      }
      res.end(output)
      console.log(`whole request [${req.url}]: ${Date.now() - s}ms`)
      next()
    }).catch(errorHandler)
  }

  const dynamicCacheHandler = () => {
    if (config.server.useOutputCache && cache) {
      cache.get(
        'page:' + req.url
      ).then(output => {
        if (output !== null) {
          if (output.headers) {
            for (const header of Object.keys(output.headers)) {
              res.setHeader(header, output.headers[header])
            }
          }
          res.setHeader('X-VS-Cache', 'Hit')
          if (output.body) {
            res.end(output.body)
          } else {
            res.setHeader('Content-Type', 'text/html')
            res.end(output.body)
          }
          res.end(output)
          console.log(`cache hit [${req.url}], cached request: ${Date.now() - s}ms`)
          next()
        } else {
          res.setHeader('Content-Type', 'text/html')
          res.setHeader('X-VS-Cache', 'Miss')
          console.log(`cache miss [${req.url}], request: ${Date.now() - s}ms`)
          dynamicRequestHandler(renderer) // render response
        }
      }).catch(errorHandler)
    } else {
      dynamicRequestHandler(renderer)
    }
  }

  if (config.server.dynamicConfigReload) {
    delete require.cache[require.resolve('config')]
    config = require('config') // reload config
    if (typeof serverExtensions.configProvider === 'function') {
      serverExtensions.configProvider(req).then(loadedConfig => {
        config = Object.assign(config, loadedConfig) // merge loaded conf with build time conf
        dynamicCacheHandler()
      }).catch(error => {
        if (config.server.dynamicConfigContinueOnError) {
          dynamicCacheHandler()
        } else {
          console.log('config provider error:', error)
          if (req.url !== '/error') {
            res.redirect('/error')
          }
          dynamicCacheHandler()
        }
      })
    } else {
      config = require('config') // reload config
      dynamicCacheHandler()
    }
  } else {
    dynamicCacheHandler()
  }
})

let port = process.env.PORT || config.server.port
const host = process.env.HOST || config.server.host
const start = () => {
  app.listen(port, host)
    .on('listening', () => {
      console.log(`Vue Storefront Server started at http://${host}:${port}`)
    })
    .on('error', (e) => {
      if (e.code === 'EADDRINUSE') {
        port = parseInt(port) + 1
        console.log(`The port is already in use, trying ${port}`)
        start()
      }
    })
}
start()
<|endoftext|>


<commit_before>var fs = require("fs");
/**
 * 基于文件的缓存
 * @return {[type]} [description]
 */
module.exports = Cache(function(){
    "use strict";
    return {
        gcType: "FileCache",
        init: function(options){
            this.options = extend({
                cache_path: C('cache_path'), //缓存目录
                cache_path_level: 2, //缓存子目录深度
                cache_file_suffix: C('cache_file_suffix') //缓存文件后缀名
            }, options);
            mkdir(this.options.cache_path);
            this.gcType += ":" + this.options.cache_path;

            this.super_("init", this.options);
        },
        /**
         * 存储的缓存文件
         * @param  {[type]} name [description]
         * @return {[type]}      [description]
         */
        getStoredFile: function(name){
            name = md5(this.key || name);
            var dir = name.split("").slice(0, this.options.cache_path_level).join("/");
            mkdir(this.options.cache_path + "/" + dir);
            var path = this.options.cache_path + "/" + dir + "/" + name + this.options.cache_file_suffix;
            return path;
        },
        /**
         * 获取缓存，返回promise
         * @param  {[type]} name [description]
         * @return {[type]}      [description]
         */
        get: function(name){
            var filePath = this.getStoredFile(name);
            if (!isFile(filePath)) {
                return getPromise();
            }
            var deferred = getDefer();
            var self = this;
            fs.exists(filePath, function(exists){
                if (!exists) {
                    return deferred.resolve();
                }
                fs.readFile(filePath, function(error, content){
                    if (error || !content) {
                        return deferred.resolve();
                    }
                    var data = JSON.parse(content);
                    if (Date.now() > data.expire) {
                        fs.unlink(filePath);
                        return deferred.resolve();
                    }
                    //更新expire时间
                    if (self.updateExpire) {
                        data.expire = Date.now() + data.timeout * 1000;
                        fs.writeFile(filePath, JSON.stringify(data), function(){});
                    }
                    deferred.resolve(data.data[name]);
                });
            });
            return deferred.promise;
        },
        /**
         * 设置缓存
         * @param {[type]} name   [description]
         * @param {[type]} value  [description]
         * @param {[type]} expire [description]
         */
        set: function(name, value, timeout){
            if (timeout === undefined) {
                timeout = this.options.timeout;
            }
            var filePath = this.getStoredFile(name);
            var data = {
                data: getObject(name, value),
                expire: Date.now() + timeout * 1000,
                timeout: timeout
            };
            setFileContent(filePath, JSON.stringify(data));
            return getPromise();
        },
        /**
         * 删除缓存
         * @param  {[type]} name [description]
         * @return {[type]}      [description]
         */
        rm: function(name){
            var filePath = this.getStoredFile(name);
            if (isFile(filePath)) {
                fs.unlink(filePath);
            }
        },
        /**
         * gc
         * @param  {[type]} now [description]
         * @return {[type]}     [description]
         */
        gc: function(now, path){
            path = path || this.options.cache_path;
            var self = this;
            var files = fs.readdirSync(path);
            files.forEach(function(item){
                var filePath = path + "/" + item;
                var stat = fs.statSync(filePath);
                if (stat.isDirectory()) {
                    self.gc(now, filePath);
                }else if (stat.isFile()) {
                    var data = getFileContent(filePath);
                    try{
                        data = JSON.parse(data);
                        if (now > data.expire) {
                            fs.unlink(filePath, function(){});
                        }
                    }catch(e){}
                }
            });
        }
    };
});<commit_msg>unlink添加callback<commit_after>var fs = require("fs");
/**
 * 基于文件的缓存
 * @return {[type]} [description]
 */
module.exports = Cache(function(){
    "use strict";
    return {
        gcType: "FileCache",
        init: function(options){
            this.options = extend({
                cache_path: C('cache_path'), //缓存目录
                cache_path_level: 2, //缓存子目录深度
                cache_file_suffix: C('cache_file_suffix') //缓存文件后缀名
            }, options);
            mkdir(this.options.cache_path);
            this.gcType += ":" + this.options.cache_path;

            this.super_("init", this.options);
        },
        /**
         * 存储的缓存文件
         * @param  {[type]} name [description]
         * @return {[type]}      [description]
         */
        getStoredFile: function(name){
            name = md5(this.key || name);
            var dir = name.split("").slice(0, this.options.cache_path_level).join("/");
            mkdir(this.options.cache_path + "/" + dir);
            var path = this.options.cache_path + "/" + dir + "/" + name + this.options.cache_file_suffix;
            return path;
        },
        /**
         * 获取缓存，返回promise
         * @param  {[type]} name [description]
         * @return {[type]}      [description]
         */
        get: function(name){
            var filePath = this.getStoredFile(name);
            if (!isFile(filePath)) {
                return getPromise();
            }
            var deferred = getDefer();
            var self = this;
            fs.exists(filePath, function(exists){
                if (!exists) {
                    return deferred.resolve();
                }
                fs.readFile(filePath, function(error, content){
                    if (error || !content) {
                        return deferred.resolve();
                    }
                    var data = JSON.parse(content);
                    if (Date.now() > data.expire) {
                        fs.unlink(filePath, function(){});
                        return deferred.resolve();
                    }
                    //更新expire时间
                    if (self.updateExpire) {
                        data.expire = Date.now() + data.timeout * 1000;
                        fs.writeFile(filePath, JSON.stringify(data), function(){});
                    }
                    deferred.resolve(data.data[name]);
                });
            });
            return deferred.promise;
        },
        /**
         * 设置缓存
         * @param {[type]} name   [description]
         * @param {[type]} value  [description]
         * @param {[type]} expire [description]
         */
        set: function(name, value, timeout){
            if (timeout === undefined) {
                timeout = this.options.timeout;
            }
            var filePath = this.getStoredFile(name);
            var data = {
                data: getObject(name, value),
                expire: Date.now() + timeout * 1000,
                timeout: timeout
            };
            setFileContent(filePath, JSON.stringify(data));
            return getPromise();
        },
        /**
         * 删除缓存
         * @param  {[type]} name [description]
         * @return {[type]}      [description]
         */
        rm: function(name){
            var filePath = this.getStoredFile(name);
            if (isFile(filePath)) {
                fs.unlink(filePath, function(){});
            }
        },
        /**
         * gc
         * @param  {[type]} now [description]
         * @return {[type]}     [description]
         */
        gc: function(now, path){
            path = path || this.options.cache_path;
            var self = this;
            var files = fs.readdirSync(path);
            files.forEach(function(item){
                var filePath = path + "/" + item;
                var stat = fs.statSync(filePath);
                if (stat.isDirectory()) {
                    self.gc(now, filePath);
                }else if (stat.isFile()) {
                    var data = getFileContent(filePath);
                    try{
                        data = JSON.parse(data);
                        if (now > data.expire) {
                            fs.unlink(filePath, function(){});
                        }
                    }catch(e){}
                }
            });
        }
    };
});<|endoftext|>


<commit_before>// Player [PROPERTIES] //
var Player = function(){
  this.position = { x: null, y: null };
  this.velocity = { x: null, y: null };
  this.init_pos = { x: null, y: null }; // init JUMP motion
  this.up = false; // JUMP
  this.hit = false; // JUMP
  this.g = 15; // sensitivity of JUMP
  this.t_p = 0; // JUMP
  this.dimension = { width: 120, height: 85};
  this.name = null;
  this.thresholdLevel = null;
  this.traj = {
    velocity: { x: 0, y: -100}
  };
  this.score = 0;
  this.touch = 0;
};

// Player [METHODS] //
Player.prototype.initialize = function(game, name,divOffset){
  this.name = name;
  this.thresholdLevel = $("#threshold").offset().top - 50 - (this.dimension.height * 0.7);
  if (this.name == "p1"){
    this.position.x = divOffset.left + 80;
    this.position.y = this.thresholdLevel - 5;
  }else if (this.name == "p2"){
    this.position.x = divOffset.left + game.COURT_SIZE.width - this.dimension.width - 80;
    this.position.y = this.thresholdLevel - 5 ;
  };
  this.updatePos();
};

Player.prototype.unifyPlayer = function(){
  var tmp = $("#" + this.name);
  this.position.y = tmp.offset().top + this.dimension.height * 0.5;
  if (this.name == "p1"){
    this.position.x = tmp.offset().left + this.dimension.width * 0.8;
  }else if (this.name == "p2"){
    this.position.x = tmp.offset().left + this.dimension.width * 0.2;
  };
};

var curr;
function jumpEvent (curr_player){
  curr = curr_player;
  game[curr_player].init_pos.x = game[curr_player].position.x;
  game[curr_player].init_pos.y = game[curr_player].position.y;
  timerList.push("jumpUp");
  jumpUp = setInterval(everyJump, 10);
}
var tmpArray = {
  p1: {
    prev: {x: null, y:null},
    curr: {x: null, y:null}
  },
  p2: {
    prev: {x: null, y:null},
    curr: {x: null, y:null}
  }
}
function everyJump (){
  if (game[curr].t_p !== 0){
    tmpArray[curr].prev.x = tmpArray[curr].curr.x;
    tmpArray[curr].prev.y = tmpArray[curr].curr.y;
    var tmpvalue = $("#" + curr).offset().top - game[curr].dimension.height;
    if (tmpArray[curr].prev.y >= game.thresholdLevel + 5){
        game[curr].t_p = 0;
        game[curr].up = false;
        game[curr].position.y = game.thresholdLevel - 5;
        removeTimer(jumpUp);
        clearInterval(jumpUp);
        game[curr].t_p -=0.25;
        game[curr].up = false;
    }
  }
  game[curr].t_p += 0.25;

  game[curr].position.x = game[curr].init_pos.x + game[curr].traj.velocity.x * game[curr].t_p;
  tmpArray[curr].curr.x = game[curr].position.x;
  game[curr].position.y = game[curr].init_pos.y + game[curr].traj.velocity.y * game[curr].t_p + 0.5 * game[curr].g * Math.pow(game[curr].t_p, 2);
  tmpArray[curr].curr.y = game[curr].position.y;
  game[curr].updatePos();
}

Player.prototype.updatePos = function(){
  $("#" + this.name).offset({
    left: this.position.x,
    top: this.position.y
  });
};
<commit_msg>fixed indentations<commit_after>// Player [PROPERTIES] //
var Player = function(){
  this.position = { x: null, y: null };
  this.velocity = { x: null, y: null };
  this.init_pos = { x: null, y: null }; // init JUMP motion
  this.up = false; // JUMP
  this.hit = false; // JUMP
  this.g = 15; // sensitivity of JUMP
  this.t_p = 0; // JUMP
  this.dimension = { width: 120, height: 85};
  this.name = null;
  this.thresholdLevel = null;
  this.traj = {
    velocity: { x: 0, y: -100}
  };
  this.score = 0;
  this.touch = 0;
};

var curr;
var tmpArray = {
  p1: {
    prev: {x: null, y:null},
    curr: {x: null, y:null}
  },
  p2: {
    prev: {x: null, y:null},
    curr: {x: null, y:null}
  }
};

// Player [METHODS] //
Player.prototype.initialize = function(game, name,divOffset){
  this.name = name;
  this.thresholdLevel = $("#threshold").offset().top - 50 - (this.dimension.height * 0.7);
  if (this.name == "p1"){
    this.position.x = divOffset.left + 80;
    this.position.y = this.thresholdLevel - 5;
  }else if (this.name == "p2"){
    this.position.x = divOffset.left + game.COURT_SIZE.width - this.dimension.width - 80;
    this.position.y = this.thresholdLevel - 5 ;
  };
  this.updatePos();
};
Player.prototype.updatePos = function(){
  $("#" + this.name).offset({
    left: this.position.x,
    top: this.position.y
  });
};
Player.prototype.unifyPlayer = function(){
  var tmp = $("#" + this.name);
  this.position.y = tmp.offset().top + this.dimension.height * 0.5;
  if (this.name == "p1"){
    this.position.x = tmp.offset().left + this.dimension.width * 0.8;
  }else if (this.name == "p2"){
    this.position.x = tmp.offset().left + this.dimension.width * 0.2;
  };
};
function jumpEvent (curr_player){
  curr = curr_player;
  game[curr_player].init_pos.x = game[curr_player].position.x;
  game[curr_player].init_pos.y = game[curr_player].position.y;
  timerList.push("jumpUp");
  jumpUp = setInterval(everyJump, 10);
}
function everyJump (){
  if (game[curr].t_p !== 0){
    tmpArray[curr].prev.x = tmpArray[curr].curr.x;
    tmpArray[curr].prev.y = tmpArray[curr].curr.y;
    var tmpvalue = $("#" + curr).offset().top - game[curr].dimension.height;
    if (tmpArray[curr].prev.y >= game.thresholdLevel + 5){
      game[curr].t_p = 0;
      game[curr].up = false;
      game[curr].position.y = game.thresholdLevel - 5;
      removeTimer(jumpUp);
      clearInterval(jumpUp);
      game[curr].t_p -=0.25;
      game[curr].up = false;
    }
  }
  game[curr].t_p += 0.25;

  game[curr].position.x = game[curr].init_pos.x + game[curr].traj.velocity.x * game[curr].t_p;
  tmpArray[curr].curr.x = game[curr].position.x;
  game[curr].position.y = game[curr].init_pos.y + game[curr].traj.velocity.y * game[curr].t_p + 0.5 * game[curr].g * Math.pow(game[curr].t_p, 2);
  tmpArray[curr].curr.y = game[curr].position.y;
  game[curr].updatePos();
}

<|endoftext|>


<commit_before>'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/bootstrap/dist/css/bootstrap.css',
        'public/lib/angular-material/angular-material.css',
        'public/lib/components-font-awesome/css/font-awesome.css',
        'public/lib/ng-tags-input/ng-tags-input.css',
        'public/lib/angular-moment-picker/dist/angular-moment-picker.css',
        'public/lib/textAngular/dist/textAngular.css',
        'public/lib/angular-toastr/dist/angular-toastr.css',
        'public/lib/ng-dialog/css/ngDialog.min.css',
        'public/lib/ng-dialog/css/ngDialog-theme-default.min.css',
        'public/lib/angucomplete-alt/angucomplete-alt.css',
        'public/lib/simple-line-icons/css/simple-line-icons.css',
        'public/lib/angular-loading-bar/build/loading-bar.css'
      ],
      js: [
        'public/lib/jquery/dist/jquery.min.js',
        'public/lib/angular/angular.js',
        'public/lib/angular-resource/angular-resource.js',
        'public/lib/angular-animate/angular-animate.js',
        'public/lib/angular-messages/angular-messages.js',
        'public/lib/angular-sanitize/angular-sanitize.js',
        'public/lib/angular-socket-io/socket.js',
        'public/lib/angular-touch/angular-touch.js',
        'public/lib/angular-ui-router/release/angular-ui-router.js',
        'public/lib/angular-ui-utils/ui-utils.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
        'public/lib/angular-bootstrap/ui.bootstrap.materialPicker.js',
        'public/lib/angular-file-upload/angular-file-upload.js',
        'public/lib/angular-aria/angular-aria.js',
        'public/lib/angular-material/angular-material.js',
        'public/lib/angular-ui-switch/angular-ui-switch.js',
        'public/lib/angular-elastic/elastic.js',
        'public/lib/angular-webstorage/angular-webstorage.js',
        'public/lib/chart.js/dist/Chart.js',
        'public/lib/angular-chart.js/dist/angular-chart.js',
        'public/lib/ng-tags-input/ng-tags-input.js',
        'public/lib/underscore/underscore.js',
        'public/lib/moment/moment.js',
        'public/lib/moment-timezone/moment-timezone.js',
        'public/lib/angular-moment/angular-moment.js',
        'public/lib/angular-moment-picker/dist/angular-moment-picker.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js',
        'public/lib/ngInfiniteScroll/build/ng-infinite-scroll.js',
        'public/lib/textAngular/dist/textAngular-rangy.min.js',
        'public/lib/textAngular/dist/textAngular-sanitize.min.js',
        'public/lib/textAngular/dist/textAngular.js',
        'public/lib/textAngular/dist/textAngularSetup.js',
        'public/lib/angular-toastr/dist/angular-toastr.tpls.js',
        'public/lib/ng-dialog/js/ngDialog.min.js',
        'public/lib/angucomplete-alt/angucomplete-alt.js',
        'public/lib/angular-loading-bar/build/loading-bar.js',
        'public/lib/angular-breadcrumb/dist/angular-breadcrumb.min.js',
        'public/lib/angular-socialshare/dist/angular-socialshare.js',
        'public/lib/angular-translate/angular-translate.min.js'
      ]
    },
    css: 'public/dist/application.min.css',
    js: 'public/dist/application.min.js'
  }
};
<commit_msg>Commited from lenh at Mon, Aug 28, 2017 12:12:06 PM<commit_after>'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/bootstrap/dist/css/bootstrap.css',
        'public/lib/angular-material/angular-material.css',
        'public/lib/components-font-awesome/css/font-awesome.css',
        'public/lib/ng-tags-input/ng-tags-input.css',
        'public/lib/angular-moment-picker/dist/angular-moment-picker.css',
        'public/lib/textAngular/dist/textAngular.css',
        'public/lib/angular-toastr/dist/angular-toastr.css',
        'public/lib/ng-dialog/css/ngDialog.min.css',
        'public/lib/ng-dialog/css/ngDialog-theme-default.min.css',
        'public/lib/angucomplete-alt/angucomplete-alt.css',
        'public/lib/simple-line-icons/css/simple-line-icons.css',
        'public/lib/angular-loading-bar/build/loading-bar.css'
      ],
      js: [
        'public/lib/jquery/dist/jquery.min.js',
        'public/lib/angular/angular.js',
        'public/lib/angular-resource/angular-resource.js',
        'public/lib/angular-animate/angular-animate.js',
        'public/lib/angular-messages/angular-messages.js',
        'public/lib/angular-sanitize/angular-sanitize.js',
        'public/lib/angular-socket-io/socket.js',
        'public/lib/angular-touch/angular-touch.js',
        'public/lib/angular-ui-router/release/angular-ui-router.js',
        'public/lib/angular-ui-utils/ui-utils.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
        'public/lib/angular-bootstrap/ui.bootstrap.materialPicker.js',
        'public/lib/angular-file-upload/angular-file-upload.js',
        'public/lib/angular-aria/angular-aria.js',
        'public/lib/angular-material/angular-material.js',
        'public/lib/angular-ui-switch/angular-ui-switch.js',
        'public/lib/angular-elastic/elastic.js',
        'public/lib/angular-webstorage/angular-webstorage.js',
        'public/lib/chart.js/dist/Chart.js',
        'public/lib/angular-chart.js/dist/angular-chart.js',
        'public/lib/ng-tags-input/ng-tags-input.js',
        'public/lib/underscore/underscore.js',
        'public/lib/moment/moment.js',
        'public/lib/moment-timezone/moment-timezone.js',
        'public/lib/angular-moment/angular-moment.js',
        'public/lib/angular-moment-picker/dist/angular-moment-picker.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js',
        'public/lib/ngInfiniteScroll/build/ng-infinite-scroll.js',
        'public/lib/textAngular/dist/textAngular-rangy.min.js',
        'public/lib/textAngular/dist/textAngular-sanitize.min.js',
        'public/lib/textAngular/dist/textAngular.js',
        'public/lib/textAngular/dist/textAngularSetup.js',
        'public/lib/angular-toastr/dist/angular-toastr.tpls.js',
        'public/lib/ng-dialog/js/ngDialog.min.js',
        'public/lib/angucomplete-alt/angucomplete-alt.js',
        'public/lib/angular-loading-bar/build/loading-bar.js',
        'public/lib/angular-breadcrumb/dist/angular-breadcrumb.min.js',
        'public/lib/angular-socialshare/dist/angular-socialshare.js',
        'public/lib/angular-translate/angular-translate.min.js',
        'public/lib/angular-translate-loader-static-files/angular-translate-loader-static-files.min.js'
      ]
    },
    css: 'public/dist/application.min.css',
    js: 'public/dist/application.min.js'
  }
};
<|endoftext|>


<commit_before>page('/', indexController.index);
page.exit('/', indexController.onExit);
// page('/results', resultsController.loadAll, resultsController.index);
page('/results', resultsController.loadIndexPage);
// page('/results/:date', resultsController.loadByDate, resultsController.loadByLatLon resultsController.index);
page('/results/:parameters', resultsController.detectParameters, resultsController.index, dataFetcher.fetchData, resultsController.afterAjaxCall);
// page('/results/:parameters', resultsController.detectParameters, dataFetcher.fetchData, resultsController.index);
// page('/overview', overviewController.loadAll, overviewController.index);

page();
//
<commit_msg>initialized /overview page route, added callBasicData method to route<commit_after>page('/', indexController.index);
page.exit('/', indexController.onExit);
// page('/results', resultsController.loadAll, resultsController.index);
page('/results', resultsController.loadIndexPage);
// page('/results/:date', resultsController.loadByDate, resultsController.loadByLatLon resultsController.index);
page('/results/:parameters', resultsController.detectParameters, resultsController.index, dataFetcher.fetchData, resultsController.afterAjaxCall);
// page('/results/:parameters', resultsController.detectParameters, dataFetcher.fetchData, resultsController.index);
page('/overview', overviewController.callBasicData);
// overviewController.loadAll, overviewController.index part of the overview route

page();
//
<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //create the map of values
        var map = new Array(960);
        for(var i = 0; i < 960; i++) {
            map[i] = new Array(540);
        }

        //fill the values
        for(var i = 0; i< 960; i++) {
            for(var j = 0; j < 540; j++) {
                map[i][j] = 1;
            }
        }

        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var myTimer;
        var blockSize = 2;

        // set the dynamic outside the loop
        var it1 = -1;
        var it2 = -1;

        document.getElementById("startbtn").onclick = paint;

        //paint the map
        function paint() {
            for(var i = 0; i < 960; i++) {
                for(var j = 0; j< 540; j++){
                    if(map[i][j] == 1){
                        c.fillStyle = '#87CEEB';
                        c.fillRect(i,j,1,1);
                    }
                }
            }
        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {

        //create an empty map
        var map = new Array(960);
        for(var i = 0; i < 960; i++) {
            map[i] = new Array(540);
        }

        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");

        //when we click, assign values and then paint
        document.getElementById("startbtn").onclick = paint;
        function paint() {

            //fill the values
            for(var i = 0; i< 960; i++) {
                for(var j = 0; j < 540; j++) {
                    if(Math.random() < .45){
                        map[i][j] = 1;
                    } else {
                        map[i][j] = 0;
                    }
                }
            }

            //paint the map
            for(var i = 0; i < 960; i++) {
                for(var j = 0; j< 540; j++){
                    if(map[i][j] == 1){
                        c.fillStyle = '#87CEEB';
                        c.fillRect(i,j,1,1);
                    }
                }
            }
        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>/*$(document).ready(function() {
    var $header = $("#mainSearch"),
        $clone = $header.before($header.clone().addClass("clone"));

    $(window).on("scroll", function() {
        var fromTop = $("html,body").scrollTop();
        $(window).toggleClass("down", (fromTop > 400));
    });
});*/

	$(window).scroll(function(event) {

		if($(window).scrollTop() >= 249) {
			$('mainSearch').addClass('down');
		} else {
			if($('mainSearch').hasClass('down')) {
				$('mainSearch').removeClass('down');
			}
		}

	});
<commit_msg>tweak<commit_after>/*$(document).ready(function() {
    var $header = $("#mainSearch"),
        $clone = $header.before($header.clone().addClass("clone"));

    $(window).on("scroll", function() {
        var fromTop = $("html,body").scrollTop();
        $(window).toggleClass("down", (fromTop > 400));
    });
});*/

	$(window).scroll(function(event) {
		console.log($(window).scrollTop());
		if($(window).scrollTop() >= 249) {
			$('mainSearch').addClass('down');
		} else {
			if($('mainSearch').hasClass('down')) {
				$('mainSearch').removeClass('down');
			}
		}

	});
<|endoftext|>


<commit_before>(function (OC, window, $, undefined) {
    'use strict';

    $(document).ready(function () {

        var source = $('#navigation-tpl').html();
        var template = Handlebars.compile(source);

        // this notes object holds all our notes
        var Papers = function (baseUrl) {
            this._baseUrl = baseUrl;
            this._papers = [];
            this._activePaper = undefined;
        };

        Papers.prototype = {
            load: function (id) {
                var self = this;
                this._papers.forEach(function (paper) {
                    if (paper.id === id) {
                        paper.active = true;
                        self._activeNote = paper;
                    } else {
                        paper.active = false;
                    }
                });
            },
            getActive: function () {
                return this._activePaper;
            },
            getAll: function () {
                return this._papers;
            },
            loadAll: function () {
                var deferred = $.Deferred();
                var self = this;
                $.get(this._baseUrl).done(function (papers) {
                    self._activePaper = undefined;
                    self._papers = papers;
                    deferred.resolve();
                }).fail(function () {
                    deferred.reject();
                });
                return deferred.promise();
            }
        };

        // this will be the view that is used to update the html
        var View = function (papers) {
            this._papers = papers;
        };

        View.prototype = {
            renderContent: function () {
            },
            renderList: function () {
                var source = $('#list-tpl').html();
                var template = Handlebars.compile(source);
            },
            renderNavigation: function () {
                var source = $('#navigation-tpl').html();
                var template = Handlebars.compile(source);
            },
            render: function () {
                //this.renderContent();
                //this.renderList();
                this.renderNavigation();
            }
        };

        var papers = new Papers(OC.generateUrl('/apps/paper/papers'));
        var view = new View(papers);
        //papers.loadAll().done(function () {
            view.render();
        //}).fail(function () {
        //    alert('Could not load papers');
        //});
    });

})(OC, window, jQuery);<commit_msg>Debugging<commit_after>(function (OC, window, $, undefined) {
    'use strict';

    $(document).ready(function () {

        var source = $('#navigation-tpl').html();
        var template = Handlebars.compile(source);

        // this notes object holds all our notes
        /*var Papers = function (baseUrl) {
            this._baseUrl = baseUrl;
            this._papers = [];
            this._activePaper = undefined;
        };

        Papers.prototype = {
            load: function (id) {
                var self = this;
                this._papers.forEach(function (paper) {
                    if (paper.id === id) {
                        paper.active = true;
                        self._activeNote = paper;
                    } else {
                        paper.active = false;
                    }
                });
            },
            getActive: function () {
                return this._activePaper;
            },
            getAll: function () {
                return this._papers;
            },
            loadAll: function () {
                var deferred = $.Deferred();
                var self = this;
                $.get(this._baseUrl).done(function (papers) {
                    self._activePaper = undefined;
                    self._papers = papers;
                    deferred.resolve();
                }).fail(function () {
                    deferred.reject();
                });
                return deferred.promise();
            }
        };

        // this will be the view that is used to update the html
        var View = function (papers) {
            this._papers = papers;
        };

        View.prototype = {
            renderContent: function () {
            },
            renderList: function () {
                var source = $('#list-tpl').html();
                var template = Handlebars.compile(source);
            },
            renderNavigation: function () {
                var source = $('#navigation-tpl').html();
                var template = Handlebars.compile(source);
            },
            render: function () {
                //this.renderContent();
                //this.renderList();
                this.renderNavigation();
            }
        };

        var papers = new Papers(OC.generateUrl('/apps/paper/papers'));
        var view = new View(papers);
        //papers.loadAll().done(function () {
            view.render();
        //}).fail(function () {
        //    alert('Could not load papers');
        //});*/
    });

})(OC, window, jQuery);<|endoftext|>


<commit_before>/*jslint browser: true */
/*globals Mustache: false, ace: false, require: false */

(function (mustache, ace, require, document, localStorage, Worker, console, setInterval) {
    'use strict';

        // Constants
    var SAVE_INTERVAL = 5000,

        // Misc
        activeEngine = 'mustache',
        renderingWorker,
        i,
        selectHtml = '',

        // Editors
        JSONMode = require('ace/mode/json').Mode,
        HTMLMode = require('ace/mode/html').Mode,
        templateEditor = ace.edit('template'),
        templateEditorContent = '',
        viewEditor = ace.edit('view'),
        viewEditorDefault = document.getElementById('view-default').innerHTML,
        viewEditorContent = '',
        resultEditor = ace.edit('result'),

        // Cached DOM elements
        templateElement = document.getElementById('template'),
        viewElement = document.getElementById('view'),
        engineElement = document.getElementById('engine'),
        engineInfoElement = document.getElementById('engine-info'),

        // Mustache templates
        engineTemplate = document.getElementById('engine-template').innerHTML,
        engineInfoTemplate = document.getElementById('engine-info-template').innerHTML,

        engines = {
            dot: {
                id: 'dot',
                name: 'doT.js',
                version: '0.1.7',
                size: '1.2',
                source: 'https://github.com/olado/doT'
            },
            ejs: {
                id: 'ejs',
                name: 'EJS',
                version: '0.6.1',
                size: '2.5',
                source: 'https://github.com/visionmedia/ejs'
            },
            haml: {
                id: 'haml',
                name: 'Haml.js',
                version: '0.4.2',
                size: '3.5',
                source: 'https://github.com/creationix/haml-js'
            },
            handlebars: {
                id: 'handlebars',
                name: 'Handlebars.js',
                version: '1.0.6beta',
                size: '9.6',
                source: 'https://github.com/wycats/handlebars.js'
            },
            hogan: {
                id: 'hogan',
                name: 'Hogan.js',
                version: '2.0.0',
                size: '2.8',
                source: 'https://github.com/twitter/hogan.js'
            },
            jade: {
                id: 'jade',
                name: 'Jade',
                version: '0.21.0',
                size: '9.3',
                source: 'https://github.com/visionmedia/jade'
            },
            mustache: {
                id: 'mustache',
                name: 'Mustache.js',
                version: '0.4.2',
                size: '2.2',
                source: 'https://github.com/janl/mustache.js'
            },
            underscore: {
                id: 'underscore',
                name: 'Underscore.js',
                version: '1.3.1',
                size: '4.4',
                source: 'https://github.com/documentcloud/underscore'
            }
        };

    /**
     * A basic object for listening to and emitting events.
     */
    function EventEmitter() {
        if (!(this instanceof EventEmitter)) {
            return new EventEmitter();
        }

        var listeners = {};

        /**
         * Registers an event listener.
         *
         * @param {string} topic Name of the event to listen to.
         * @param {function(data)} callback Function to register as a listener.
         */
        this.on = function (topic, callback) {
            if (!listeners[topic]) {
                listeners[topic] = [];
            }

            listeners[topic].push(callback);
        };

        /**
         * Emits an event.
         *
         * @param {string} topic Name of the event to emit.
         * @param {*} data Data to pass to the event listeners.
         */
        this.emit = function (topic, data) {
            if (listeners[topic]) {
                listeners[topic].forEach(function (callback) {
                    callback(data);
                });
            }
        };
    }

    /**
     * Encaspulates a web worker that renders templates using various engines.
     *
     * @param {string} initEngine Initial templating engine to use.
     */
    function RenderWorker(initEngine) {
        if (!(this instanceof RenderWorker)) {
            return new RenderWorker(initEngine);
        }

        var engine = initEngine,
            worker = new Worker('js/worker.js'),
            events = new EventEmitter(),
            commands = {
                init: function () {
                    worker.postMessage({
                        cmd: 'init',
                        id: engine
                    });
                },
                render: function (template, view) {
                    worker.postMessage({
                        cmd: 'render',
                        template: template,
                        view: view
                    });
                }
            };

        /**
         * Initialises the web worker.
         */
        function init() {
            worker.addEventListener('message', function (event) {
                events.emit('complete', event.data);
            }, false);

            commands.init();
        }

        /**
         * Changes the templating engine.
         *
         * @param {string} newEngine New templating engine to use.
         */
        this.changeEngine = function (newEngine) {
            engine = newEngine;

            worker.terminate();
            worker = new Worker('js/worker.js');
            init();
        };

        /**
         * Requests a template to be rendered.
         *
         * The 'complete' event is emitted when the template has been rendered.
         *
         * @param {string} template Template to render.
         * @param {object} view Variables to pass to the template.
         * @see RenderWorker.on()
         */
        this.render = function (template, view) {
            commands.render(template, view);
        };

        /**
         * Registers an event listener.
         *
         * Available events:
         * 'complete' - Emitted when a template has been rendered. Is passed an
         *              object containing 'result' and 'error' properties.
         *
         * @param {string} topic Name of the event to listen to.
         * @param {function(data)} callback Function to register as a listener.
         */
        this.on = function (topic, callback) {
            events.on.call(events, topic, callback);
        };

        init();
    }

    /**
     * Sends the current state of the editors to be rendered by the web worker.
     */
    function render() {
        var json = {},
            view = viewEditor.getSession().getValue(),
            template = templateEditor.getSession().getValue();

        try {
            json = JSON.parse(view);
            viewElement.classList.remove('error');
        } catch (error) {
            viewElement.classList.add('error');
        }

        renderingWorker.render(template, json);
    }

    // Load the default engine templates
    for (i in engines) {
        if (engines.hasOwnProperty(i)) {
            engines[i].template = document.getElementById('template-default-' +
                i).innerHTML;
        }
    }

    // Load application state
    try {
        activeEngine = localStorage.getItem('architect.engine') || activeEngine;
        templateEditorContent = localStorage.getItem('architect.template') ||
            engines[activeEngine].template;
        viewEditorContent = localStorage.getItem('architect.view') ||
            viewEditorDefault;
    } catch (error) {}

    // Initialise the web worker
    renderingWorker = new RenderWorker(activeEngine);

    // Initialise the engine select
    for (i in engines) {
        if (engines.hasOwnProperty(i)) {
            selectHtml += mustache.to_html(engineTemplate, {
                id: i,
                name: engines[i].name,
                selected: i === activeEngine
            });
        }
    }
    engineElement.innerHTML = selectHtml;

    engineInfoElement.innerHTML = mustache.to_html(
        engineInfoTemplate,
        engines[activeEngine]
    );

    // Initialise the editors
    templateEditor.getSession().setMode(new HTMLMode());
    templateEditor.getSession().setValue(templateEditorContent);
    viewEditor.getSession().setMode(new JSONMode());
    viewEditor.getSession().setValue(viewEditorContent);
    resultEditor.getSession().setMode(new HTMLMode());
    resultEditor.setReadOnly(true);

    // Event handlers

    templateEditor.getSession().on('change', render);
    viewEditor.getSession().on('change', render);

    engineElement.addEventListener('change', function () {
        activeEngine = engineElement.value;
        engineInfoElement.innerHTML = mustache.to_html(
            engineInfoTemplate,
            engines[activeEngine]
        );
        viewEditor.getSession().setValue(viewEditorDefault);
        templateEditor.getSession().setValue(engines[activeEngine].template);

        renderingWorker.changeEngine(activeEngine);
        render();
    }, false);

    renderingWorker.on('complete', function (data) {
        if (data.error) {
            if (console) {
                console.error(data.error);
            }
            templateElement.classList.add('error');
            resultEditor.getSession().setValue('');
        } else {
            templateElement.classList.remove('error');
            resultEditor.getSession().setValue(data.result);
        }
    });

    // Initial render
    render();

    // Save application state
    setInterval(function () {
        var view = viewEditor.getSession().getValue(),
            template = templateEditor.getSession().getValue();

        try {
            localStorage.setItem('architect.engine', activeEngine);
            localStorage.setItem('architect.template', template);
            localStorage.setItem('architect.view', view);
        } catch (error) {}
    }, SAVE_INTERVAL);
}(Mustache, ace, require, document, localStorage, Worker, console, setInterval));
<commit_msg>Encapsulate the defined templating engines.<commit_after>/*jslint browser: true */
/*globals Mustache: false, ace: false, require: false */

(function (mustache, ace, require, document, localStorage, Worker, console, setInterval) {
    'use strict';

        // Constants
    var SAVE_INTERVAL = 5000,

        // Misc
        Engines,
        renderingWorker,
        i,
        selectHtml = '',
        temp,

        // Editors
        JSONMode = require('ace/mode/json').Mode,
        HTMLMode = require('ace/mode/html').Mode,
        templateEditor = ace.edit('template'),
        templateEditorContent = '',
        viewEditor = ace.edit('view'),
        viewEditorDefault = document.getElementById('view-default').innerHTML,
        viewEditorContent = '',
        resultEditor = ace.edit('result'),

        // Cached DOM elements
        templateElement = document.getElementById('template'),
        viewElement = document.getElementById('view'),
        engineElement = document.getElementById('engine'),
        engineInfoElement = document.getElementById('engine-info'),

        // Mustache templates
        engineTemplate = document.getElementById('engine-template').innerHTML,
        engineInfoTemplate = document.getElementById('engine-info-template').innerHTML;

    /**
     * Singleton that encapsulates the defined templating engines.
     */
    Engines = (function () {
        var engines = [
                {
                    id: 'dot',
                    name: 'doT.js',
                    version: '0.1.7',
                    size: '1.2',
                    source: 'https://github.com/olado/doT'
                },
                {
                    id: 'ejs',
                    name: 'EJS',
                    version: '0.6.1',
                    size: '2.5',
                    source: 'https://github.com/visionmedia/ejs'
                },
                {
                    id: 'haml',
                    name: 'Haml.js',
                    version: '0.4.2',
                    size: '3.5',
                    source: 'https://github.com/creationix/haml-js'
                },
                {
                    id: 'handlebars',
                    name: 'Handlebars.js',
                    version: '1.0.6beta',
                    size: '9.6',
                    source: 'https://github.com/wycats/handlebars.js'
                },
                {
                    id: 'hogan',
                    name: 'Hogan.js',
                    version: '2.0.0',
                    size: '2.8',
                    source: 'https://github.com/twitter/hogan.js'
                },
                {
                    id: 'jade',
                    name: 'Jade',
                    version: '0.21.0',
                    size: '9.3',
                    source: 'https://github.com/visionmedia/jade'
                },
                {
                    id: 'mustache',
                    name: 'Mustache.js',
                    version: '0.4.2',
                    size: '2.2',
                    source: 'https://github.com/janl/mustache.js'
                },
                {
                    id: 'underscore',
                    name: 'Underscore.js',
                    version: '1.3.1',
                    size: '4.4',
                    source: 'https://github.com/documentcloud/underscore'
                }
            ],
            activeEngine = engines[0],
            exports = {};

        // Initialise engines' default template
        engines.forEach(function (engine) {
            engine.template = document.getElementById('template-default-' +
                engine.id).innerHTML;
        });

        /**
         * Gets the active engine.
         *
         * @returns {object} Map of the engine's info.
         */
        function getActiveEngine() {
            return activeEngine;
        }
        exports.getActiveEngine = getActiveEngine;

        /**
         * Sets the active engine.
         *
         * @param {string} engineId ID of the engine.
         */
        function setActiveEngine(engineId) {
            engines.forEach(function (engine) {
                if (engine.id === engineId) {
                    activeEngine = engine;
                }
            });
        }
        exports.setActiveEngine = setActiveEngine;

        /**
         * Get all of the defined engines.
         *
         * @returns {array.<object>} Array of maps of the engine info.
         */
        function getEngines() {
            return engines;
        }
        exports.getEngines = getEngines;

        return exports;
    }());

    /**
     * A basic object for listening to and emitting events.
     */
    function EventEmitter() {
        if (!(this instanceof EventEmitter)) {
            return new EventEmitter();
        }

        var listeners = {};

        /**
         * Registers an event listener.
         *
         * @param {string} topic Name of the event to listen to.
         * @param {function(data)} callback Function to register as a listener.
         */
        this.on = function (topic, callback) {
            if (!listeners[topic]) {
                listeners[topic] = [];
            }

            listeners[topic].push(callback);
        };

        /**
         * Emits an event.
         *
         * @param {string} topic Name of the event to emit.
         * @param {*} data Data to pass to the event listeners.
         */
        this.emit = function (topic, data) {
            if (listeners[topic]) {
                listeners[topic].forEach(function (callback) {
                    callback(data);
                });
            }
        };
    }

    /**
     * Encaspulates a web worker that renders templates using various engines.
     *
     * @param {string} initEngine Initial templating engine to use.
     */
    function RenderWorker(initEngine) {
        if (!(this instanceof RenderWorker)) {
            return new RenderWorker(initEngine);
        }

        var engine = initEngine,
            worker = new Worker('js/worker.js'),
            events = new EventEmitter(),
            commands = {
                init: function () {
                    worker.postMessage({
                        cmd: 'init',
                        id: engine
                    });
                },
                render: function (template, view) {
                    worker.postMessage({
                        cmd: 'render',
                        template: template,
                        view: view
                    });
                }
            };

        /**
         * Initialises the web worker.
         */
        function init() {
            worker.addEventListener('message', function (event) {
                events.emit('complete', event.data);
            }, false);

            commands.init();
        }

        /**
         * Changes the templating engine.
         *
         * @param {string} newEngine New templating engine to use.
         */
        this.changeEngine = function (newEngine) {
            engine = newEngine;

            worker.terminate();
            worker = new Worker('js/worker.js');
            init();
        };

        /**
         * Requests a template to be rendered.
         *
         * The 'complete' event is emitted when the template has been rendered.
         *
         * @param {string} template Template to render.
         * @param {object} view Variables to pass to the template.
         * @see RenderWorker.on()
         */
        this.render = function (template, view) {
            commands.render(template, view);
        };

        /**
         * Registers an event listener.
         *
         * Available events:
         * 'complete' - Emitted when a template has been rendered. Is passed an
         *              object containing 'result' and 'error' properties.
         *
         * @param {string} topic Name of the event to listen to.
         * @param {function(data)} callback Function to register as a listener.
         */
        this.on = function (topic, callback) {
            events.on.call(events, topic, callback);
        };

        init();
    }

    /**
     * Sends the current state of the editors to be rendered by the web worker.
     */
    function render() {
        var json = {},
            view = viewEditor.getSession().getValue(),
            template = templateEditor.getSession().getValue();

        try {
            json = JSON.parse(view);
            viewElement.classList.remove('error');
        } catch (error) {
            viewElement.classList.add('error');
        }

        renderingWorker.render(template, json);
    }

    // Load application state
    try {
        temp = localStorage.getItem('architect.engine');
        if (temp) {
            Engines.setActiveEngine(temp);
        }

        templateEditorContent = localStorage.getItem('architect.template') ||
            Engines.getActiveEngine().template;

        viewEditorContent = localStorage.getItem('architect.view') ||
            viewEditorDefault;
    } catch (error) {}

    // Initialise the web worker
    renderingWorker = new RenderWorker(Engines.getActiveEngine().id);

    // Initialise the engine select
    temp = '';
    Engines.getEngines().forEach(function (engine) {
        temp += mustache.to_html(engineTemplate, {
            id: engine.id,
            name: engine.name,
            selected: engine.id === Engines.getActiveEngine().id
        });
    });
    engineElement.innerHTML = temp;

    engineInfoElement.innerHTML = mustache.to_html(
        engineInfoTemplate,
        Engines.getActiveEngine()
    );

    // Initialise the editors
    templateEditor.getSession().setMode(new HTMLMode());
    templateEditor.getSession().setValue(templateEditorContent);
    viewEditor.getSession().setMode(new JSONMode());
    viewEditor.getSession().setValue(viewEditorContent);
    resultEditor.getSession().setMode(new HTMLMode());
    resultEditor.setReadOnly(true);

    // Event handlers

    templateEditor.getSession().on('change', render);
    viewEditor.getSession().on('change', render);

    engineElement.addEventListener('change', function () {
        Engines.setActiveEngine(engineElement.value);

        engineInfoElement.innerHTML = mustache.to_html(
            engineInfoTemplate,
            Engines.getActiveEngine()
        );

        viewEditor.getSession().setValue(viewEditorDefault);
        templateEditor.getSession().setValue(Engines.getActiveEngine().template);

        renderingWorker.changeEngine(Engines.getActiveEngine().id);
        render();
    }, false);

    renderingWorker.on('complete', function (data) {
        if (data.error) {
            if (console) {
                console.error(data.error);
            }
            templateElement.classList.add('error');
            resultEditor.getSession().setValue('');
        } else {
            templateElement.classList.remove('error');
            resultEditor.getSession().setValue(data.result);
        }
    });

    // Initial render
    render();

    // Save application state
    setInterval(function () {
        var view = viewEditor.getSession().getValue(),
            template = templateEditor.getSession().getValue();

        try {
            localStorage.setItem('architect.engine', Engines.getActiveEngine().id);
            localStorage.setItem('architect.template', template);
            localStorage.setItem('architect.view', view);
        } catch (error) {}
    }, SAVE_INTERVAL);
}(Mustache, ace, require, document, localStorage, Worker, console, setInterval));
<|endoftext|>