<commit_before>function Barbersynth(voices) {
  var that = Object.create(Barbersynth.prototype);

  that.scheduleChordChanges = function() {
    var nextStartTime;
    var scheduleToneChange = function(voice){
       voice.scheduleToneChange(nextStartTime);
    };

    while(!(nextStartTime = that.advanceStartTime()).done) {
      nextStartTime = nextStartTime.value;
      that.computeBaseToneAndPartials();
      voices.map(scheduleToneChange);
    }

  };

  that.advanceStartTime = function() {

  };

  that.computeBaseToneAndPartials = function() {

  };

  return that;
}
<commit_msg>Comments<commit_after>function Barbersynth(voices) {
  var that = Object.create(Barbersynth.prototype);

  that.scheduleChordChanges = function() {
    var nextStartTime;

    // This is really ugly, but my IDE doesn't like functions beeing created
    // in loops...
    var scheduleToneChange = function(voice){
       voice.scheduleToneChange(nextStartTime);
    };

    // This is just a for...of loop, but IE doesn't seem to support that just
    // yet, so I leave it like this for now.
    while(!(nextStartTime = that.advanceStartTime()).done) {
      nextStartTime = nextStartTime.value;
      that.computeBaseToneAndPartials();
      voices.map(scheduleToneChange);
    }

  };

  that.advanceStartTime = function() {

  };

  that.computeBaseToneAndPartials = function() {

  };

  return that;
}
<|endoftext|>


<commit_before>import Component from '@ember/component';
import { action, computed } from '@ember/object';
import { map } from '@ember/object/computed';
import { inject as service } from '@ember/service';
import { htmlSafe } from '@ember/template';

import $ from 'jquery';

export default Component.extend({
  units: service(),

  tagName: '',

  height: 133,

  flot: null,

  active: null,
  passive: null,
  enls: null,

  contests: null,
  elevations: null,

  flotStyle: computed('height', function () {
    if (this.height) {
      return htmlSafe(`width: 100%; height: ${this.height}px;`);
    }
  }),

  initFlot: action(function (element) {
    this._initFlot(element);
  }),

  _initFlot(element) {
    let units = this.units;

    let opts = {
      grid: {
        borderWidth: 0,
        hoverable: true,
        clickable: true,
        autoHighlight: false,
        margin: 5,
      },
      xaxis: {
        mode: 'time',
        timeformat: '%H:%M',
      },
      yaxes: [
        {
          min: 0,
          tickFormatter: units.addAltitudeUnit.bind(units),
        },
        {
          show: false,
          min: 0,
          max: 1000,
        },
      ],
      crosshair: {
        mode: 'x',
      },
    };

    if (this.uploadMode) {
      opts.selection = {
        mode: 'x',
      };

      opts.crosshair = {
        mode: null,
      };
    }

    let placeholder = $(element);

    this.set('placeholder', placeholder);
    this.set('flot', $.plot(placeholder, [], opts));
  },

  draw() {
    this.update();

    let flot = this.flot;
    flot.setupGrid();
    flot.draw();
  },

  update() {
    let elevations = {
      data: this.elevations,
      color: 'rgb(235, 155, 98)',
      lines: {
        lineWidth: 0,
        fill: 0.8,
      },
    };

    let data = [elevations];
    data = data.concat(this.activeTraces);
    data = data.concat(this.passiveTraces);
    data = data.concat(this.enlData);
    data = data.concat(this.getContests());

    this.flot.setData(data);
  },

  activeTraces: map('active.@each.{data,color}', trace => ({
    data: trace.data,
    color: trace.color,
  })),

  passiveTraces: map('passive.@each.{data,color}', trace => ({
    data: trace.data,
    color: $.color.parse(trace.color).add('a', -0.6).toString(),
    shadowSize: 0,
    lines: {
      lineWidth: 1,
    },
  })),

  enlData: map('enls.@each.{data,color}', enl => ({
    data: enl.data,
    color: enl.color,
    lines: {
      lineWidth: 0,
      fill: 0.2,
    },
    yaxis: 2,
  })),

  getContests() {
    // Skip the function if there are no contest markers
    let contests = this.contests;
    if (!contests) {
      return [];
    }

    // Iterate through the contests
    return contests
      .map(contest => {
        let times = contest.get('times');
        if (times.length < 1) {
          return;
        }

        let color = contest.get('color');

        // Add the turnpoint markers to the markings array
        let markings = times.map(time => ({
          position: time * 1000,
        }));

        // Add the chart series for this contest to the data array
        return {
          marks: {
            show: true,
            lineWidth: 1,
            toothSize: 6,
            color,
            fillColor: color,
          },
          data: [],
          markdata: markings,
        };
      })
      .filter(Boolean);
  },
});
<commit_msg>BaseBarogram: Convert `getContests()` to `contestData` computed property<commit_after>import Component from '@ember/component';
import { action, computed } from '@ember/object';
import { map } from '@ember/object/computed';
import { inject as service } from '@ember/service';
import { htmlSafe } from '@ember/template';

import $ from 'jquery';

export default Component.extend({
  units: service(),

  tagName: '',

  height: 133,

  flot: null,

  active: null,
  passive: null,
  enls: null,

  contests: null,
  elevations: null,

  flotStyle: computed('height', function () {
    if (this.height) {
      return htmlSafe(`width: 100%; height: ${this.height}px;`);
    }
  }),

  initFlot: action(function (element) {
    this._initFlot(element);
  }),

  _initFlot(element) {
    let units = this.units;

    let opts = {
      grid: {
        borderWidth: 0,
        hoverable: true,
        clickable: true,
        autoHighlight: false,
        margin: 5,
      },
      xaxis: {
        mode: 'time',
        timeformat: '%H:%M',
      },
      yaxes: [
        {
          min: 0,
          tickFormatter: units.addAltitudeUnit.bind(units),
        },
        {
          show: false,
          min: 0,
          max: 1000,
        },
      ],
      crosshair: {
        mode: 'x',
      },
    };

    if (this.uploadMode) {
      opts.selection = {
        mode: 'x',
      };

      opts.crosshair = {
        mode: null,
      };
    }

    let placeholder = $(element);

    this.set('placeholder', placeholder);
    this.set('flot', $.plot(placeholder, [], opts));
  },

  draw() {
    this.update();

    let flot = this.flot;
    flot.setupGrid();
    flot.draw();
  },

  update() {
    let elevations = {
      data: this.elevations,
      color: 'rgb(235, 155, 98)',
      lines: {
        lineWidth: 0,
        fill: 0.8,
      },
    };

    let data = [elevations];
    data = data.concat(this.activeTraces);
    data = data.concat(this.passiveTraces);
    data = data.concat(this.enlData);
    data = data.concat(this.contestData.filter(Boolean));

    this.flot.setData(data);
  },

  activeTraces: map('active.@each.{data,color}', trace => ({
    data: trace.data,
    color: trace.color,
  })),

  passiveTraces: map('passive.@each.{data,color}', trace => ({
    data: trace.data,
    color: $.color.parse(trace.color).add('a', -0.6).toString(),
    shadowSize: 0,
    lines: {
      lineWidth: 1,
    },
  })),

  enlData: map('enls.@each.{data,color}', enl => ({
    data: enl.data,
    color: enl.color,
    lines: {
      lineWidth: 0,
      fill: 0.2,
    },
    yaxis: 2,
  })),

  contestData: map('contests.@each.{times,color}', contest => {
    let times = contest.get('times');
    if (times.length < 1) {
      return;
    }

    let color = contest.get('color');

    // Add the turnpoint markers to the markings array
    let markings = times.map(time => ({
      position: time * 1000,
    }));

    // Add the chart series for this contest to the data array
    return {
      marks: {
        show: true,
        lineWidth: 1,
        toothSize: 6,
        color,
        fillColor: color,
      },
      data: [],
      markdata: markings,
    };
  }),
});
<|endoftext|>


<commit_before>(function uglify_js_closure(con ,process){
var cfg = JSON.parse(process.env.NODEJS_CONFIG) ,ctl
var ipt = require('util').inspect
   ,text_plain = { 'Content-Type': 'text/plain; charset=utf-8' }
   ,app_json   = { 'Content-Type': 'application/json; charset=utf-8' }

function log(m){ con.log(m) }
function err(e){ con.error(e) }

    function run_backend(){
        log('^ app is starting http @ port ' + cfg.backend.job_port + '\n' +
                new Date().toISOString()
        )
        //err('error check')
        run_app()
    }

require('http').ServerResponse.prototype.json =
/*  res.json({ success: true })
 *  res.json('{ "success": true }')
 *  res.json(401, { msg: ' Authorization Required' })
 */
function res_json(obj){
    if(2 == arguments.length){// args: status / body
        this.statusCode = obj
        obj = arguments[1]
    }
    if('string' != typeof obj) obj = JSON.stringify(obj)
    this.setHeader('Content-Length', obj.length)
    this.writeHead(this.statusCode, app_json)
    this.end(obj)
}

/*`connect` for business logic as from node-webkit(local UI)
 * as from regular HTTP (localhost or any host)
 */

function run_app(){
var utils  = require('connect/lib/utils.js')
   ,connect = require('connect')
   ,app = connect()

    /* Application middleware setup */

    app.use(connect.cookieParser())
    app.use(connect.json())
    app.use(mwPostTextPlain)

    //.use(require('connect/lib/middleware/session')({secret: cfg.backend.sess_puzl}))
    //,MongoStore = require('connect-mongo')(express)

    /* backend static: for non localhost users */
    app.use('/app_back.js' ,mwAssume404)
    app.use('/' ,connect.static(__dirname))
    app.use('/extjs/' ,connect.static(__dirname + '/' + cfg.extjs.path))
    cfg.extjs.path = 'extjs/'// switch local to external path
    app.use('/app.config.extjs.json' ,function($ ,res){ res.json(cfg.extjs) })

// TODO: require plugins here
/* https://github.com/caulagi/sntd/blob/master/config/express.js */
/*/ Bootstrap models
    var models_path = __dirname + '/app/models'
    fs.readdirSync(models_path).forEach(function (file) {
        if (~file.indexOf('.js')) require(models_path + '/' + file)
    })*/

    /* Finally, error middleware setup */
    app.use(function mwErrorHandler(err, req, res, next){
            if(!err) return next()
            if (err.status) res.statusCode = err.status
            if (res.statusCode < 400) res.statusCode = 500
            err(ipt(err) + ' (internal backend error)')
            res.writeHead(res.statusCode, text_plain)
            return res.end(err.stack)//XXX frontend must wrap this in pretty UI
        })
       .use(mwAssume404)// no middleware handled request
    .listen(cfg.backend.job_port ,app_is_up_and_running)
    return

    function app_is_up_and_running(){
        log('^ app is up and running\n' +
            new Date().toISOString()
        )
    }

    function mwAssume404(req, res){
        res.writeHead(res.statusCode = 404, text_plain)
        return res.end(
            'URL: ' + req.originalUrl + '\n\n' +
            'Not found'
        )
    }

    function mwPostTextPlain(req, res, next){
        if (req._body) return next()
        var limit = connect.limit('4mb')
        if('text/plain' == utils.mime(req))
            return limit(req, res
        ,function(err){
          if(err) return next(err)
          var buf = ''
          req.setEncoding('utf8')
          req.on('data', function(chunk){ buf += chunk })
          req.on('end', function(){
              req.body = { plain_text: buf }
              next()
          })
          return req._body = true
        })
        return next()
    }
}

/*==============================================================================
\  / Process control http channel.
 \/  This: child.kill([signal]), where signals can be 'SIGTERM' or 'SIGHUP' etc.
 /\  is very old non cross platform way of child process control.
 \/
 /\  Here we have HTTP server on controlling port
/  \
================================================================================*/

process.on('uncaughtException', function(err){
    log('Caught exception: ' + err.stack)
})

process.on('exit', function process_exit(){
    log('$ backend process exit event')
})

ctl = require('http').createServer(
function proc_ctl_http_serv(req, res){
    var body = ''

    res.on('close', proc_ctl_res_unexpected_close)

    log('ctl req url:' + req.url)
    if ('/sts_running' == req.url){
    } else if ('/cmd_exit' == req.url){
        process.nextTick(function(){
            process.exit(0)
        })
        body += '$ is going down'
    } else if ('/cmd_stat' == req.url){
        body += Math.ceil(process.uptime()) + '\n' + ctl.toISOString()
    } else {// show somw info about this
        body += '? control channel resourses:\n\n' +
        'sts_running cmd_stat cmd_exit' +
        '\n\n' +
        'application under control is at port: ' + cfg.backend.job_port + '\n'
    }
    res.writeHead(200 ,{ 'Content-Length': body.length ,'Content-Type': 'text/plain' })
    res.end(body)
})

ctl.on('listening',
function proc_ctl_http_serv_listening(){
    ctl = new Date()// fill `ctl` as running flag
    log(
        '^ backend http proc ctl @ http://127.0.0.1:' + cfg.backend.ctl_port + '\n' +
        ctl.toISOString()
    )
})

ctl.on('error',
function proc_ctl_http_serv_error(e){
// NOTE: net error handler must not be inside init(listen) callback!!!
    if('EADDRINUSE' == e.code){// 'EADDRNOTAVAIL'?
        err(
            "!!! FATAL(ctl): can't listen host:port='127.0.0.1':" + cfg.backend.ctl_port +
            "\n" + ipt(e) +
            "\nNOTE: check config 'ctl_port' option collision"
        )
    } else {//FIXME: handle all fatal errors to unset `ctl` and process.exit()
        err("! ERROR(ctl) controlling http channel: " + ipt(e))
    }
    if (!ctl) process.exit(1)
})

ctl.on('clientError',
function proc_ctl_client_error(e, sock){
    err("! ERROR(ctl) in client connection: " + ipt(e))
})

function proc_ctl_res_unexpected_close(){
    err('! ERROR(ctl) aborted request')
}

ctl.listen(cfg.backend.ctl_port ,'127.0.0.1' ,run_backend)
ctl.unref()// "allow the program to exit if this is the only active server in the event system"
ctl = null// setup is over, waiting for 'listening' event, `ctl` is running flag
})(console ,process)
<commit_msg>app_back `connect`: have `session` after `static`, prevent needless work<commit_after>(function uglify_js_closure(con ,process){
var cfg = JSON.parse(process.env.NODEJS_CONFIG) ,ctl
var ipt = require('util').inspect
   ,text_plain = { 'Content-Type': 'text/plain; charset=utf-8' }
   ,app_json   = { 'Content-Type': 'application/json; charset=utf-8' }

function log(m){ con.log(m) }
function err(e){ con.error(e) }

    function run_backend(){
        log('^ app is starting http @ port ' + cfg.backend.job_port + '\n' +
                new Date().toISOString()
        )
        //err('error check')
        run_app()
    }

require('http').ServerResponse.prototype.json =
/*  res.json({ success: true })
 *  res.json('{ "success": true }')
 *  res.json(401, { msg: ' Authorization Required' })
 */
function res_json(obj){
    if(2 == arguments.length){// args: status / body
        this.statusCode = obj
        obj = arguments[1]
    }
    if('string' != typeof obj) obj = JSON.stringify(obj)
    this.setHeader('Content-Length', obj.length)
    this.writeHead(this.statusCode, app_json)
    this.end(obj)
}

/*`connect` for business logic as from node-webkit(local UI)
 * as from regular HTTP (localhost or any host)
 */

function run_app(){
var utils  = require('connect/lib/utils.js')
   ,connect = require('connect')
   ,app = connect()

    /* Application middleware setup */

    app.use(connect.cookieParser())
    app.use(connect.json())
    app.use(mwPostTextPlain)

    /* backend static: for non localhost users */
    app.use('/app_back.js' ,mwAssume404)
    app.use('/' ,connect.static(__dirname))
    app.use('/extjs/' ,connect.static(__dirname + '/' + cfg.extjs.path))
    cfg.extjs.path = 'extjs/'// switch local to external path

    /* have `session` after `static`, to prevent needless work */
    // TODO!!!: .use(require('connect.session')({secret: cfg.backend.sess_puzl}))
    //,MongoStore = require('connect-mongo')(express)
    app.use('/app.config.extjs.json' ,function($ ,res){ res.json(cfg.extjs) })

// TODO: require plugins here
/* https://github.com/caulagi/sntd/blob/master/config/express.js */
/*/ Bootstrap models
    var models_path = __dirname + '/app/models'
    fs.readdirSync(models_path).forEach(function (file) {
        if (~file.indexOf('.js')) require(models_path + '/' + file)
    })*/

    /* Finally, error middleware setup */
    app.use(function mwErrorHandler(err, req, res, next){
            if(!err) return next()
            if (err.status) res.statusCode = err.status
            if (res.statusCode < 400) res.statusCode = 500
            err(ipt(err) + ' (internal backend error)')
            res.writeHead(res.statusCode, text_plain)
            return res.end(err.stack)//XXX frontend must wrap this in pretty UI
        })
       .use(mwAssume404)// no middleware handled request
    .listen(cfg.backend.job_port ,app_is_up_and_running)
    return

    function app_is_up_and_running(){
        log('^ app is up and running\n' +
            new Date().toISOString()
        )
    }

    function mwAssume404(req, res){
        res.writeHead(res.statusCode = 404, text_plain)
        return res.end(
            'URL: ' + req.originalUrl + '\n\n' +
            'Not found'
        )
    }

    function mwPostTextPlain(req, res, next){
        if (req._body) return next()
        var limit = connect.limit('4mb')
        if('text/plain' == utils.mime(req))
            return limit(req, res
        ,function(err){
          if(err) return next(err)
          var buf = ''
          req.setEncoding('utf8')
          req.on('data', function(chunk){ buf += chunk })
          req.on('end', function(){
              req.body = { plain_text: buf }
              next()
          })
          return req._body = true
        })
        return next()
    }
}

/*==============================================================================
\  / Process control http channel.
 \/  This: child.kill([signal]), where signals can be 'SIGTERM' or 'SIGHUP' etc.
 /\  is very old non cross platform way of child process control.
 \/
 /\  Here we have HTTP server on controlling port
/  \
================================================================================*/

process.on('uncaughtException', function(err){
    log('Caught exception: ' + err.stack)
})

process.on('exit', function process_exit(){
    log('$ backend process exit event')
})

ctl = require('http').createServer(
function proc_ctl_http_serv(req, res){
    var body = ''

    res.on('close', proc_ctl_res_unexpected_close)

    log('ctl req url:' + req.url)
    if ('/sts_running' == req.url){
    } else if ('/cmd_exit' == req.url){
        process.nextTick(function(){
            process.exit(0)
        })
        body += '$ is going down'
    } else if ('/cmd_stat' == req.url){
        body += Math.ceil(process.uptime()) + '\n' + ctl.toISOString()
    } else {// show somw info about this
        body += '? control channel resourses:\n\n' +
        'sts_running cmd_stat cmd_exit' +
        '\n\n' +
        'application under control is at port: ' + cfg.backend.job_port + '\n'
    }
    res.writeHead(200 ,{ 'Content-Length': body.length ,'Content-Type': 'text/plain' })
    res.end(body)
})

ctl.on('listening',
function proc_ctl_http_serv_listening(){
    ctl = new Date()// fill `ctl` as running flag
    log(
        '^ backend http proc ctl @ http://127.0.0.1:' + cfg.backend.ctl_port + '\n' +
        ctl.toISOString()
    )
})

ctl.on('error',
function proc_ctl_http_serv_error(e){
// NOTE: net error handler must not be inside init(listen) callback!!!
    if('EADDRINUSE' == e.code){// 'EADDRNOTAVAIL'?
        err(
            "!!! FATAL(ctl): can't listen host:port='127.0.0.1':" + cfg.backend.ctl_port +
            "\n" + ipt(e) +
            "\nNOTE: check config 'ctl_port' option collision"
        )
    } else {//FIXME: handle all fatal errors to unset `ctl` and process.exit()
        err("! ERROR(ctl) controlling http channel: " + ipt(e))
    }
    if (!ctl) process.exit(1)
})

ctl.on('clientError',
function proc_ctl_client_error(e, sock){
    err("! ERROR(ctl) in client connection: " + ipt(e))
})

function proc_ctl_res_unexpected_close(){
    err('! ERROR(ctl) aborted request')
}

ctl.listen(cfg.backend.ctl_port ,'127.0.0.1' ,run_backend)
ctl.unref()// "allow the program to exit if this is the only active server in the event system"
ctl = null// setup is over, waiting for 'listening' event, `ctl` is running flag
})(console ,process)
<|endoftext|>


<commit_before>var BaseURL = "https://linode.shellcode.in/"
var DatasetURL = document.baseURI.substring(0, document.baseURI.lastIndexOf("/") + 1) + "assets/";

function LoadList(dataset, idName, callback, attribute){
  _.orderBy(dataset, ["upvotes", "downvotes"], ["desc", "asc"]);
  var idName = idName === undefined ? "list" : idName;
  var template = "

TRACK - ALBUM

ARTIST

UPVOTESDOWNVOTES

";

  document.getElementById(idName).innerHTML = "";

  if (dataset[0] !== undefined && dataset[0] !== null && dataset != ""){
    $("#track").html(dataset[0]["name"] + " - " + dataset[0]["albumname"]);
    $("#artist").html(dataset[0]["artists"][0]["name"]);
    $("#cover").attr({"alt": dataset[0]["name"], "src": dataset[0]["images"][2]["url"]});
    $("#count").html(dataset[0]["upvotes"] + " UP");
  }

  for (var i = 1; i < dataset.length; ++i){
    var itemTemp = template;
    var itemID = dataset[i]["ID"];
    var itemUpvote = dataset[i]["upvotes"];
    var itemDownvote = dataset[i]["downvotes"];
    var itemCover = dataset[i]["images"][2]["url"];
    var itemTrack = dataset[i]["name"];
    var itemAlbum = dataset[i]["albumname"];
    var itemArtists = dataset[i]["artists"];
    var itemDuration = dataset[i]["Duration"]

    itemTemp = itemTemp.replace(/TRACKID/g, itemID).replace(/UPVOTES/g, itemUpvote).replace(/DOWNVOTES/g, itemDownvote).replace(/COVER/g, itemCover).replace(/TRACK/g, itemTrack).replace(/ALBUM/g, itemAlbum).replace(/ARTIST/g, itemArtists[0]["name"]);

    document.getElementById(idName).innerHTML += itemTemp;
  }
}

function LoadJSON(queryURL, queryParam, queryMethod, storageKey, callback, attribute){
  var httpRequest = new XMLHttpRequest();
  var queryMethod = queryMethod === undefined ? "GET" : queryMethod;
  var storageKey = storageKey === undefined ? "temp" : storageKey;

  httpRequest.open(queryMethod, queryURL + (queryMethod === "GET" ? "?" + $.param(queryParam) : "") , true);
  //httpRequest.setRequestHeader("Access-Control-Allow-Origin", "*");
  httpRequest.onload = function(e){
    if (httpRequest.readyState === 4 && httpRequest.status === 200){
      localStorage.setItem(storageKey, httpRequest.responseText);
      if (callback !== undefined && callback !== null)
        callback(httpRequest.responseText === "" ? undefined : JSON.parse(httpRequest.responseText), attribute);
    }
    else
      console.error(httpRequest.statusText);
  }
  // if (!queryURL.includes("file:///")) httpRequest.send(queryMethod === "GET" ? null : $.param(queryParam));
  if (!queryURL.includes("file:///"))
    if (queryMethod === "GET") httpRequest.send(null);
    else {
      var formData = new FormData();
      for (var key in queryParam) formData.append(key, queryParam[key]);
      httpRequest.send(formData);
    }
}

function VoteAction(el){
  console.log(el.getAttribute("track"));
}

function Initialize(dataset, attribute){
  var localUUID = localStorage.getItem("uuid");
  if (localUUID === null || localUUID === ""){
    identity().get(function(UUID){
      document.cookie = "uuid=" + UUID + "; max-age=86400;";
      localStorage.setItem("uuid", UUID);
    });
  }

  var localPoolID = localStorage.getItem("poolid");
  if (localPoolID !== null && localPoolID !== ""){
    $("#join").addClass("inactive");
    $("#pool").html("Pool: " + localPoolID);
    $("#quit, #container, #play").removeClass("inactive");

    var localDataset = localStorage.getItem("dataset");
    if ((dataset === undefined || dataset === null || dataset === "")
      && localDataset !== null && localDataset !== ""){
      LoadList(JSON.parse(localDataset)["songheap"]);
    }
  }

  if (dataset !== undefined && dataset !== null && dataset !== ""){
    LoadList(dataset["songheap"]);
  }

}

function Finalize(dataset, attribute){
  Initialize();
  if (dataset === undefined || dataset === null || dataset === "" || (attribute["refresh"] !== undefined && attribute["refresh"] !== null && attribute["refresh"] === true)){
    var queryResult = LoadJSON(BaseURL + "getpool", {}, "GET", "dataset", Initialize, {});
    //var queryResult = LoadJSON(DatasetURL + "dataset.json", {}, "GET", "dataset", Initialize, {});
  }
}

function JoinPool(){
  var inputPoolID = document.getElementById("poolid").value;
  if (inputPoolID !== undefined && inputPoolID !== null && inputPoolID !== ""){
    localStorage.setItem("poolid", inputPoolID);
    var queryResult = LoadJSON(BaseURL + "join_pool", {"poolShortId": inputPoolID, "userId": localStorage.getItem("uuid")}, "POST", "temp", Finalize, {"refresh": true});
    //var queryResult = LoadJSON(DatasetURL + "dataset.json", {"poolShortId": inputPoolID, "userId": localStorage.getItem("uuid")}, "GET", "temp", Initialize, {});
  }
}

function QuitPool(){
  localStorage.removeItem("poolid");
  localStorage.removeItem("dataset");
  window.location.reload(true);
}

function VoteAction(elem, upvote){
  console.log(BaseURL + (upvote ? "upvote" : "downvote"));
  var queryResult = LoadJSON(BaseURL + (upvote ? "upvote" : "downvote"), {"songId": elem.getAttribute("data-track"), "userId": localStorage.getItem("uuid")}, "POST", "temp", Finalize, {"refresh": true});
}

function SearchMusic(){
  var inputKeyword = document.getElementById("keyword").value;
  if (inputKeyword !== undefined && inputKeyword !== null && inputKeywordv !== ""){
    $("#result").removeClass("inactive");
    $("#list").addClass("inactive");
    var queryResult = LoadJSON(BaseURL + "search_for_songs", {"search_query": inputKeyword, "number_of_results": 10}, "POST", "temp", function(data, attr){ LoadList(data, "result"); }, {});
    //var queryResult = LoadJSON(DatasetURL + "dataset.json", {}, "GET", "temp", function(data, attr){ console.LoadList(data, "result"); }, {});
  }
}

Initialize();

$("#quit").click(QuitPool);
$("#quit").singletap(QuitPool);<commit_msg>latest commit<commit_after>var BaseURL = "https://linode.shellcode.in/"
var DatasetURL = document.baseURI.substring(0, document.baseURI.lastIndexOf("/") + 1) + "assets/";

function LoadList(dataset, idName, callback, attribute){
  _.orderBy(dataset, ["upvotes", "downvotes"], ["desc", "asc"]);
  var idName = idName === undefined ? "list" : idName;
  var template = "

TRACK - ALBUM

ARTIST

UPVOTESDOWNVOTES

";

  document.getElementById(idName).innerHTML = "";

  if (dataset[0] !== undefined && dataset[0] !== null && dataset != ""){
    $("#track").html(dataset[0]["name"] + " - " + dataset[0]["albumname"]);
    $("#artist").html(dataset[0]["artists"][0]["name"]);
    $("#cover").attr({"alt": dataset[0]["name"], "src": dataset[0]["images"][2]["url"]});
    $("#count").html(dataset[0]["upvotes"] + " UP");
  }

  for (var i = 1; i < dataset.length; ++i){
    var itemTemp = template;
    var itemID = dataset[i]["ID"];
    var itemUpvote = dataset[i]["upvotes"];
    var itemDownvote = dataset[i]["downvotes"];
    var itemCover = dataset[i]["images"][2]["url"];
    var itemTrack = dataset[i]["name"];
    var itemAlbum = dataset[i]["albumname"];
    var itemArtists = dataset[i]["artists"];
    var itemDuration = dataset[i]["Duration"]

    itemTemp = itemTemp.replace(/TRACKID/g, itemID).replace(/UPVOTES/g, itemUpvote).replace(/DOWNVOTES/g, itemDownvote).replace(/COVER/g, itemCover).replace(/TRACK/g, itemTrack).replace(/ALBUM/g, itemAlbum).replace(/ARTIST/g, itemArtists[0]["name"]);

    document.getElementById(idName).innerHTML += itemTemp;
  }
}

function LoadJSON(queryURL, queryParam, queryMethod, storageKey, callback, attribute){
  var httpRequest = new XMLHttpRequest();
  var queryMethod = queryMethod === undefined ? "GET" : queryMethod;
  var storageKey = storageKey === undefined ? "temp" : storageKey;

  httpRequest.open(queryMethod, queryURL + (queryMethod === "GET" ? "?" + $.param(queryParam) : "") , true);
  //httpRequest.setRequestHeader("Access-Control-Allow-Origin", "*");
  httpRequest.onload = function(e){
    if (httpRequest.readyState === 4 && httpRequest.status === 200){
      var response = httpRequest.responseText === "" ? undefined : JSON.parse(httpRequest.responseText);
      if (response !== undefined && response !== null && response !== ""){
        localStorage.setItem(storageKey, httpRequest.responseText);
        localStorage.setItem("playlistid",response["playlistid"]);
      }

      if (callback !== undefined && callback !== null) callback(response, attribute);
    }
    else
      console.error(httpRequest.statusText);
  }
  // if (!queryURL.includes("file:///")) httpRequest.send(queryMethod === "GET" ? null : $.param(queryParam));
  if (!queryURL.includes("file:///"))
    if (queryMethod === "GET") httpRequest.send(null);
    else {
      var formData = new FormData();
      for (var key in queryParam) formData.append(key, queryParam[key]);
      httpRequest.send(formData);
    }
}

function VoteAction(el){
  console.log(el.getAttribute("track"));
}

function Initialize(dataset, attribute){
  var localUUID = localStorage.getItem("uuid");
  if (localUUID === null || localUUID === ""){
    identity().get(function(UUID){
      document.cookie = "uuid=" + UUID + "; max-age=86400;";
      localStorage.setItem("uuid", UUID);
    });
  }

  var localPoolID = localStorage.getItem("poolid");
  if (localPoolID !== null && localPoolID !== ""){
    $("#join").addClass("inactive");
    $("#pool").html("Pool: " + localPoolID);
    $("#quit, #container, #play").removeClass("inactive");

    var localDataset = localStorage.getItem("dataset");
    if ((dataset === undefined || dataset === null || dataset === "")
      && localDataset !== null && localDataset !== ""){
      LoadList(JSON.parse(localDataset)["songheap"]);
    }
  }

  if (dataset !== undefined && dataset !== null && dataset !== ""){
    LoadList(dataset["songheap"]);
  }

}

function Finalize(dataset, attribute){
  Initialize();
  if (dataset === undefined || dataset === null || dataset === "" || (attribute["refresh"] !== undefined && attribute["refresh"] !== null && attribute["refresh"] === true)){
    var queryResult = LoadJSON(BaseURL + "getpool", {}, "GET", "dataset", Initialize, {});
    //var queryResult = LoadJSON(DatasetURL + "dataset.json", {}, "GET", "dataset", Initialize, {});
  }
}

function JoinPool(){
  var inputPoolID = document.getElementById("poolid").value;
  if (inputPoolID !== undefined && inputPoolID !== null && inputPoolID !== ""){
    localStorage.setItem("poolid", inputPoolID);
    var queryResult = LoadJSON(BaseURL + "join_pool", {"poolShortId": inputPoolID, "userId": localStorage.getItem("uuid")}, "POST", "temp", Finalize, {"refresh": true});
    //var queryResult = LoadJSON(DatasetURL + "dataset.json", {"poolShortId": inputPoolID, "userId": localStorage.getItem("uuid")}, "GET", "temp", Initialize, {});
  }
}

function QuitPool(){
  localStorage.removeItem("poolid");
  localStorage.removeItem("dataset");
  window.location.reload(true);
}

function VoteAction(elem, upvote){
  console.log(BaseURL + (upvote ? "upvote" : "downvote"));
  var queryResult = LoadJSON(BaseURL + (upvote ? "upvote/" : "downvote/") +  localStorage["playlistid"] + "/" + elem.getAttribute("data-track"), {"userId": localStorage.getItem("uuid")}, "POST", "temp", Finalize, {"refresh": true});
}

function SearchMusic(){
  var inputKeyword = document.getElementById("keyword").value;
  if (inputKeyword !== undefined && inputKeyword !== null && inputKeywordv !== ""){
    $("#result").removeClass("inactive");
    $("#list").addClass("inactive");
    var queryResult = LoadJSON(BaseURL + "search_for_songs", {"search_query": inputKeyword, "number_of_results": 10}, "POST", "temp", function(data, attr){ LoadList(data, "result"); }, {});
    //var queryResult = LoadJSON(DatasetURL + "dataset.json", {}, "GET", "temp", function(data, attr){ console.LoadList(data, "result"); }, {});
  }
}

Initialize();

$("#quit").click(QuitPool);
$("#quit").singletap(QuitPool);<|endoftext|>


<commit_before>var r = 960,
    format = d3.format(",d"),
    fill = d3.scale.category20c();

var bubble = d3.layout.pack()
    .sort(null)
    .size([r, r])
    .padding(1.5);

var vis = d3.select("#chart").append("svg")
    .attr("width", r)
    .attr("height", r)
    .attr("class", "bubble");

d3.json("../data/flare.json", function(json) {
  var node = vis.selectAll("g.node")
      .data(bubble.nodes(classes(json))
      .filter(function(d) { return !d.children; }))
    .enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

  node.append("title")
      .text(function(d) { return d.className + ": " + format(d.value); });

  node.append("circle")
      .attr("r", function(d) { return d.r; })
      .style("fill", function(d) { return fill(d.packageName); });

  node.append("text")
      .attr("text-anchor", "middle")
      .attr("dy", ".3em")
      .text(function(d) { return d.className.substring(0, d.r / 3); });
});

// Returns a flattened hierarchy containing all leaf nodes under the root.
function classes(root) {
  var classes = [];

  function recurse(name, node) {
    if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
    else classes.push({packageName: name, className: node.name, value: node.size});
  }

  recurse(null, root);
  return {children: classes};
}
<commit_msg>Fix bubble example by removing title which is difficult to path for VML. Closes #61.<commit_after>var r = 960,
    format = d3.format(",d"),
    fill = d3.scale.category20c();

var bubble = d3.layout.pack()
    .sort(null)
    .size([r, r])
    .padding(1.5);

var vis = d3.select("#chart").append("svg")
    .attr("width", r)
    .attr("height", r)
    .attr("class", "bubble");

d3.json("../data/flare.json", function(json) {
  var node = vis.selectAll("g.node")
      .data(bubble.nodes(classes(json))
      .filter(function(d) { return !d.children; }))
    .enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

  //node.append("title")
  //    .text(function(d) { return d.className + ": " + format(d.value); });

  node.append("circle")
      .attr("r", function(d) { return d.r; })
      .style("fill", function(d) { return fill(d.packageName); });

  node.append("text")
      .attr("text-anchor", "middle")
      .attr("dy", ".3em")
      .text(function(d) { return d.className.substring(0, d.r / 3); });
});

// Returns a flattened hierarchy containing all leaf nodes under the root.
function classes(root) {
  var classes = [];

  function recurse(name, node) {
    if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
    else classes.push({packageName: name, className: node.name, value: node.size});
  }

  recurse(null, root);
  return {children: classes};
}
<|endoftext|>


<commit_before>var db = require("./db");
var Q = require("q");

module.exports = {

    getUserByEmail: function (email) {
        var defer = Q.defer();
        db.findOne({email: email}, function (err, user) {
            defer.resolve(user);
        })
        return defer.promise;
    },

    getUserByUsername: function (username) {
        var defer = Q.defer();
        db.findOne({username: username}, function (err, user) {
            defer.resolve(user);
        })
        return defer.promise;
    },

    getUserById: function (uid) {
        var defer = Q.defer();
        db.findOne({id: uid}, function (err, user) {
            defer.resolve(user);
        })
        return defer.promise;
    },

    allUser:function(){
        var defer = Q.defer();
        db.find().toArray(function(err,users){
            defer.resolve(users || []);
        })
        return defer.promise;
    }
}<commit_msg>fixed #getUserByUsername<commit_after>var db = require("./db");
var Q = require("q");

module.exports = {

    getUserByEmail: function (email) {
        var defer = Q.defer();
        db.findOne({email: email}, function (err, user) {
            defer.resolve(user);
        })
        return defer.promise;
    },

    getUserByUsername: function (username) {
        var defer = Q.defer();
        if(username){
            db.findOne({username: username}, function (err, user) {
                defer.resolve(user);
            })
        }else{
            defer.resolve();
        }
        return defer.promise;
    },

    getUserById: function (uid) {
        var defer = Q.defer();
        db.findOne({id: uid}, function (err, user) {
            defer.resolve(user);
        })
        return defer.promise;
    },

    allUser:function(){
        var defer = Q.defer();
        db.find().toArray(function(err,users){
            defer.resolve(users || []);
        })
        return defer.promise;
    }
}<|endoftext|>


<commit_before>var zlib = require("zlib");
var fs = require("fs");

exports.parsers = {

  processCheckIn: function(req,res,callback) {
    var unZippedPath = "/tmp/"+(new Date()).valueOf()+".json";
    var unZippedStream = fs.createWriteStream(unZippedPath);
    fs.createReadStream(req.files.blob.path).pipe(zlib.createGunzip()).pipe(unZippedStream);
    unZippedStream.on("close",function(){
      fs.readFile(unZippedPath,function(err,unZippedJSON){
        if (err) {
          console.log("Failed to open unzipped JSON file: "+unZippedPath);
        } else {

          callback(req,res,parseCheckInJSON(JSON.parse(unZippedJSON)));

          fs.unlink(unZippedPath, function(err){
            if (err) { console.log("Failed to delete unzipped JSON file after usage..."); }
          });

        }
      });
    });

  } // end of processCheckIn

}

function parseCheckInJSON(json) {

  var d = {
    udid: json.udid,
    appVersion: json.appV,
    isCharging: json.powr,
    isCharged: json.chrg,
    batteryLevel: json.batt,
    batteryTemp: json.temp,
    networkSearch: json.srch,
    specT: [],
    specV: [],
    specC: [],
    sent: Date.parse(json.sent)
  };

  d.lum = (json.lumn !== null) ? json.lumn.split(",") : [];
  d.lumAvg = 0;
  d.cpuP = (json.cpuP !== null) ? json.cpuP.split(",") : [];
  d.cpuPAvg = 0;
  d.cpuC = (json.cpuC !== null) ? json.cpuC.split(",") : [];
  d.cpuCAvg = 0;
  for (var i = 0; i < d.lum.length; i++) { d.lumAvg = d.lumAvg + parseInt(d.lum[i]); }
    if (d.lumAvg > 0) { d.lumAvg = Math.round(d.lumAvg / d.lum.length); }
  for (var i = 0; i < d.cpuP.length; i++) { d.cpuPAvg = d.cpuPAvg + parseInt(d.cpuP[i]); }
    if (d.cpuPAvg > 0) { d.cpuPAvg = Math.round(d.cpuPAvg / d.cpuP.length); }
  for (var i = 0; i < d.cpuC.length; i++) { d.cpuCAvg = d.cpuCAvg + parseInt(d.cpuC[i]); }
    if (d.cpuCAvg > 0) { d.cpuCAvg = Math.round(d.cpuCAvg / d.cpuC.length); }

  var dateMs = parseInt(d.sent.valueOf());

  var specTimes = json.specT.split(",");
  for (var i = 0; i < specTimes.length; i++) {
    d.specT[i] = new Date(dateMs-(parseInt(specTimes[i],16)*1000));
  }
  d.specC = specTimes.length;

  var specGroup = json.specV.split("*");
  for (var g = 0; g < d.specC; g++) {
    d.specV[g] = [];
    var specHex = specGroup[g].split(",");
    for (var i = 0; i < specHex.length; i++) { d.specV[g][i] = parseInt(specHex[i], 16); }
  }
  return d;
}<commit_msg>nothing really<commit_after>var zlib = require("zlib");
var fs = require("fs");

exports.parsers = {

  processCheckIn: function(req,res,callback) {
    var unZippedPath = "/tmp/"+(new Date()).valueOf()+".json";
    var unZippedStream = fs.createWriteStream(unZippedPath);
    fs.createReadStream(req.files.blob.path).pipe(zlib.createGunzip()).pipe(unZippedStream);
    unZippedStream.on("close",function(){
      fs.readFile(unZippedPath,function(err,unZippedJSON){
        if (err) {
          console.log("Failed to open unzipped JSON file: "+unZippedPath);
        } else {

          callback(req,res,parseCheckInJSON(JSON.parse(unZippedJSON)));

          fs.unlink(unZippedPath, function(err){
            if (err) { console.log("Failed to delete unzipped JSON file after usage..."); }
          });

        }
      });
    });

  }

}

function parseCheckInJSON(json) {

  var d = {
    udid: json.udid,
    appVersion: json.appV,
    isCharging: json.powr,
    isCharged: json.chrg,
    batteryLevel: json.batt,
    batteryTemp: json.temp,
    networkSearch: json.srch,
    specT: [],
    specV: [],
    specC: [],
    sent: Date.parse(json.sent)
  };

  d.lum = (json.lumn !== null) ? json.lumn.split(",") : [];
  d.lumAvg = 0;
  d.cpuP = (json.cpuP !== null) ? json.cpuP.split(",") : [];
  d.cpuPAvg = 0;
  d.cpuC = (json.cpuC !== null) ? json.cpuC.split(",") : [];
  d.cpuCAvg = 0;
  for (var i = 0; i < d.lum.length; i++) { d.lumAvg = d.lumAvg + parseInt(d.lum[i]); }
    if (d.lumAvg > 0) { d.lumAvg = Math.round(d.lumAvg / d.lum.length); }
  for (var i = 0; i < d.cpuP.length; i++) { d.cpuPAvg = d.cpuPAvg + parseInt(d.cpuP[i]); }
    if (d.cpuPAvg > 0) { d.cpuPAvg = Math.round(d.cpuPAvg / d.cpuP.length); }
  for (var i = 0; i < d.cpuC.length; i++) { d.cpuCAvg = d.cpuCAvg + parseInt(d.cpuC[i]); }
    if (d.cpuCAvg > 0) { d.cpuCAvg = Math.round(d.cpuCAvg / d.cpuC.length); }

  var dateMs = parseInt(d.sent.valueOf());

  var specTimes = json.specT.split(",");
  for (var i = 0; i < specTimes.length; i++) {
    d.specT[i] = new Date(dateMs-(parseInt(specTimes[i],16)*1000));
  }
  d.specC = specTimes.length;

  var specGroup = json.specV.split("*");
  for (var g = 0; g < d.specC; g++) {
    d.specV[g] = [];
    var specHex = specGroup[g].split(",");
    for (var i = 0; i < specHex.length; i++) { d.specV[g][i] = parseInt(specHex[i], 16); }
  }
  return d;
}<|endoftext|>


<commit_before>define(["knockout", "app/urls", "jquery", "data", "knockout.init"],
	function (ko, urls, $, data, init) {
		function ViewModel(selected) {

			this.placesUrl = urls.fips + "places/";
			this.autoCompletePlacesUrl = this.placesUrl + "?q=%QUERY&types=City&types=County";
			this.templateName = "place-picker-choice";

			this.selected = ko.isObservable(selected) ? selected : ko.observable(selected);
			this.selected.clear = function () {
				this.selected(undefined);
			}.bind(this);

			this.mapping = function (data) {
				var model = init(this, data);

				return model;
			}.bind(this);
		}

		return ViewModel;
	});

<commit_msg>Include partial-word matches in place picker CS-12315<commit_after>define(["knockout", "app/urls", "jquery", "data", "knockout.init"],
	function (ko, urls, $, data, init) {
		function ViewModel(selected) {

			this.placesUrl = urls.fips + "places/";
			this.autoCompletePlacesUrl = this.placesUrl + "?q=%QUERY*&types=City&types=County";
			this.templateName = "place-picker-choice";

			this.selected = ko.isObservable(selected) ? selected : ko.observable(selected);
			this.selected.clear = function () {
				this.selected(undefined);
			}.bind(this);

			this.mapping = function (data) {
				var model = init(this, data);

				return model;
			}.bind(this);
		}

		return ViewModel;
	});

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { render } from 'react-dom';
import { Notification } from 'react-notification';

class Example extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isActive: false
    }
  }

  toggleNotification() {
    this.setState({
      isActive: !this.state.isActive
    })
  }

  render() {
    const { isActive } = this.state;

    return (

        <button
          onClick={this.toggleNotification.bind(this)}
          children={!isActive ? "Show notification" : "Hide notification"}
        />
        <Notification
          isActive={this.state.isActive}
          message="Notification"
          action="Dismiss"
          title="Title!"
          onDismiss={this.toggleNotification.bind(this)}
          onClick={() =>  this.setState({ isActive: false })}
        />

    );
  }
}

render(<Example />, document.querySelector('#mount'));
<commit_msg>Include permanent notification in example<commit_after>import React, { Component } from 'react';
import { render } from 'react-dom';
import { Notification } from 'react-notification';

class Example extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isActive: false,
      permanentNotification: false
    }
  }

  toggleNotification() {
    this.setState({
      isActive: !this.state.isActive
    })
  }

  render() {
    const { isActive } = this.state;

    return (

        <button
          onClick={this.toggleNotification.bind(this)}
          children={!isActive ? "Show notification" : "Hide notification"}
        />

        <button
          onClick={() => this.setState({
            permanentNotification: true
          })}
          children="Show permanent notification"
        />
        <Notification
          isActive={this.state.isActive}
          message="Notification"
          action="Dismiss"
          title="Title!"
          onDismiss={this.toggleNotification.bind(this)}
          onClick={() =>  this.setState({ isActive: false })}
        />
        <Notification
          isActive={this.state.permanentNotification}
          dismissAfter={false}
          message="Permanent Notification"
          title="Title!"
        />

    );
  }
}

render(<Example />, document.querySelector('#mount'));
<|endoftext|>


<commit_before>#!/bin/env node

var express = require('express');
var router = express.Router();
var User = require(__dirname + '/../../db/user.js');

router.get('/api/profile', function(req, res, next)
{
	res.json(req.user);
});

router.post('/api/profile', function(req, res, next)
{
	User.update({_id:req.user._id}, req.body, function(err)
	{
		if(err)
		{
			console.log('Error updating'); console.log(err);
			res.sendStatus(500);
		} else {
			console.log('User profile updated');

			res.status(200);
			res.json(req.body);
		}
	});
});

router.get('/api/profile/pushbullet/devicelist', function(req, res, next)
{
	if(req.user.notificationproviders)
	{
		if(req.user.notificationproviders.pushbullet)
		{
			if(req.user.notificationproviders.pushbullet.accesstoken)
			{
				var PushBullet = require('pushbullet');
				var pusher = new PushBullet(req.user.notificationproviders.pushbullet.accesstoken);
				pusher.devices(function(error, response) {
				    console.log("Pushbullet device list response");
					console.log(response);
					res.json(response);
				});
			} else {
				res.sendStatus(500);
			}
		} else {
			res.sendStatus(500);
		}
	} else {
		res.sendStatus(500);
	}
});

module.exports.router = router;
<commit_msg>delete responses _id before update<commit_after>#!/bin/env node

var express = require('express');
var router = express.Router();
var User = require(__dirname + '/../../db/user.js');

router.get('/api/profile', function(req, res, next)
{
	res.json(req.user);
});

router.post('/api/profile', function(req, res, next)
{
	delete req.body._id;
	User.update({_id:req.user._id}, req.body, function(err)
	{
		if(err)
		{
			console.log('Error updating'); console.log(err);
			res.sendStatus(500);
		} else {
			console.log('User profile updated');

			res.status(200);
			res.json(req.body);
		}
	});
});

router.get('/api/profile/pushbullet/devicelist', function(req, res, next)
{
	if(req.user.notificationproviders)
	{
		if(req.user.notificationproviders.pushbullet)
		{
			if(req.user.notificationproviders.pushbullet.accesstoken)
			{
				var PushBullet = require('pushbullet');
				var pusher = new PushBullet(req.user.notificationproviders.pushbullet.accesstoken);
				pusher.devices(function(error, response) {
				    console.log("Pushbullet device list response");
					console.log(response);
					res.json(response);
				});
			} else {
				res.sendStatus(500);
			}
		} else {
			res.sendStatus(500);
		}
	} else {
		res.sendStatus(500);
	}
});

module.exports.router = router;
<|endoftext|>


<commit_before>var _ = require('lodash'),
  express = require('express'),
  handler = require('../common/handler'),
  docker = require('../../config').docker,
  version = require('../../package.json').version;

let router = express.Router();

router
  .get('/_ping', (req, res) => {
    docker.ping(handler.sendTo(res));
  })
  .get('/events', (req, res) => {
    docker.getEvents(req.query, handler.streamTo(res));
  })
  .get('/info', (req, res) => {
    docker.info(handler.sendTo(res));
  })
  .get('/version', (req, res) => {
    docker.version(handler.sendTo(res, (data) => {
      data.ApiVersion += ` (Docker Proxy ${version})`;
    }));
  })
  .post('/auth', (req, res) => {
    docker.checkAuth(req.body, handler.sendTo(res));
  })
  .post('/build', (req, res) => {
    docker.buildImage(req, req.body, handler.streamTo(res));
  })
  .post('/commit', (req, res) => {
    let container = docker.getContainer(req.query.container);

    container.commit(req.query, handler.sendTo(res, () => {
      res.status(201);
    }));
  });

module.exports = router;
<commit_msg>reindent commit<commit_after>var _ = require('lodash'),
  express = require('express'),
  handler = require('../common/handler'),
  docker = require('../../config').docker,
  version = require('../../package.json').version;

let router = express.Router();

router
  .get('/_ping', (req, res) => {
    docker.ping(handler.sendTo(res));
  })
  .get('/events', (req, res) => {
    docker.getEvents(req.query, handler.streamTo(res));
  })
  .get('/info', (req, res) => {
    docker.info(handler.sendTo(res));
  })
  .get('/version', (req, res) => {
    docker.version(handler.sendTo(res, (data) => {
      data.ApiVersion += ` (Docker Proxy ${version})`;
    }));
  })
  .post('/auth', (req, res) => {
    docker.checkAuth(req.body, handler.sendTo(res));
  })
  .post('/build', (req, res) => {
    docker.buildImage(req, req.body, handler.streamTo(res));
  })
  .post('/commit', (req, res) => {
    docker
      .getContainer(req.query.container)
      .commit(req.query, handler.sendTo(res, () => {
        res.status(201);
      }));
  });

module.exports = router;
<|endoftext|>


<commit_before>var express = require('express');
var crypto = require('crypto');
var db = require('../helpers/db')();
var dateHelper = require('../helpers/date')();

var router = express.Router();

/************************/
/* GET user itineraries */
/************************/
router.get('/', function (req, res, next) {
	// Get itineraries in database
	var itineraries = db.all('itinerary', '(SELECT COUNT(*) as nbStep FROM step WHERE id_Itinerary = main.id) as nbStep', function (error, results, fields) {
		if (error != null)
			res.respond(error, 500);
		else {
			if (results == null || results.length == 0)
				res.respond(results, 200);
			else {
				var finalresult = [];

				results.forEach(function (element) {
					db.byFields('user', {
						id: element.id_User
					}, null, function (error2, results2, fields2) {
						if (error2 != null)
							res.respond(error2, 500);
						else {
							var user = {
								id: results2[0]['id'],
								name: results2[0]['name']
							}
							element['user'] = user;
							finalresult.push(element);
						}

						if(finalresult.length == results.length)
							res.respond(finalresult, 200);
					});
				});
			}
		}
	});
});

router.get('/user/:userid', function (req, res, next) {
	// Get params from client
	var userId = req.params.userid;

	// Get itineraries of a user in database with these parameters if exists
	var itineraries = db.byFields('itinerary', {
		id_User: userId
	}, null, function (error, results, fields) {
		if (error != null)
			res.respond(error, 500);
		else
			res.respond(results);
	});
});

router.get('/:itineraryid', function (req, res, next) {
	// Get params from client
	var itineraryId = req.params.itineraryid;

	// Get itineraries of a user in database with these parameters if exists
	var itineraries = db.byFields('itinerary', {
		id: itineraryId
	}, null, function (error, results, fields) {
		if (error != null)
			res.respond(error, 500);
		else
			res.respond(results.length > 0 ? results[0] : null);
	});
});

/************************/
/* PUT update itinerary */
/************************/
router.put('/:itineraryid', function (req, res, next) {
	// Get params from client
	var itineraryId = req.params.itineraryid;

	var name = req.body.name;
	var country = req.body.country;
	var description = req.body.description;

	// Update the itinerary in database
	db.update('itinerary', {
		name: name,
		country: country,
		description: description,
	}, {
			id: itineraryId
		}, function (error, results, fields) {
			if (error != null)
				res.respond(error, 500);
			else
				res.respond([]);
		});
});

/**********************/
/* POST add itinerary */
/**********************/
router.post('/', function (req, res, next) {
	// Get params from client
	var name = req.body.name;
	var country = req.body.country;
	var description = req.body.description;
	var userId = req.body.userId;

	// Insert the itinerary in database
	db.add('itinerary', {
		name: name,
		country: country,
		description: description,
		id_User: userId,
		date: dateHelper.getDateTime()
	}, function (error, results, fields) {
		if (error != null)
			res.respond(error, 500);
		else
			res.respond({ id: results.insertId });
	});
});

/***************************/
/* DELETE delete itinerary */
/***************************/
router.delete('/:itineraryid', function (req, res, next) {
	// Get params from client
	var itineraryId = req.params.itineraryid;

	// Delete the itinerary in database
	db.remove('step', {
		id_Itinerary: itineraryId,
	}, function (error, results, fields) {
		if (error != null)
			res.respond(error, 500);
		else {
			db.remove('itinerary', {
				id: itineraryId,
			}, function (error, results, fields) {
				if (error != null)
					res.respond(error, 500);
				else
					res.respond([]);
			});
		}
	});
});

module.exports = router;
<commit_msg>add map view ok<commit_after>var express = require('express');
var crypto = require('crypto');
var db = require('../helpers/db')();
var dateHelper = require('../helpers/date')();

var router = express.Router();

/************************/
/* GET user itineraries */
/************************/
router.get('/', function (req, res, next) {
	// Get itineraries in database
	var itineraries = db.all('itinerary', '(SELECT COUNT(*) as nbStep FROM step WHERE id_Itinerary = main.id) as nbStep, (SELECT lat FROM step WHERE id_Itinerary = main.id ORDER BY id LIMIT 1) as stepLat, (SELECT lng FROM step WHERE id_Itinerary = main.id ORDER BY id LIMIT 1) as stepLng', function (error, results, fields) {
		if (error != null)
			res.respond(error, 500);
		else {
			if (results == null || results.length == 0)
				res.respond(results, 200);
			else {
				var finalresult = [];

				results.forEach(function (element) {
					db.byFields('user', {
						id: element.id_User
					}, null, function (error2, results2, fields2) {
						if (error2 != null)
							res.respond(error2, 500);
						else {
							var user = {
								id: results2[0]['id'],
								name: results2[0]['name']
							}
							element['user'] = user;
							finalresult.push(element);
						}

						if(finalresult.length == results.length)
							res.respond(finalresult, 200);
					});
				});
			}
		}
	});
});

router.get('/user/:userid', function (req, res, next) {
	// Get params from client
	var userId = req.params.userid;

	// Get itineraries of a user in database with these parameters if exists
	var itineraries = db.byFields('itinerary', {
		id_User: userId
	}, null, function (error, results, fields) {
		if (error != null)
			res.respond(error, 500);
		else
			res.respond(results);
	});
});

router.get('/:itineraryid', function (req, res, next) {
	// Get params from client
	var itineraryId = req.params.itineraryid;

	// Get itineraries of a user in database with these parameters if exists
	var itineraries = db.byFields('itinerary', {
		id: itineraryId
	}, null, function (error, results, fields) {
		if (error != null)
			res.respond(error, 500);
		else
			res.respond(results.length > 0 ? results[0] : null);
	});
});

/************************/
/* PUT update itinerary */
/************************/
router.put('/:itineraryid', function (req, res, next) {
	// Get params from client
	var itineraryId = req.params.itineraryid;

	var name = req.body.name;
	var country = req.body.country;
	var description = req.body.description;

	// Update the itinerary in database
	db.update('itinerary', {
		name: name,
		country: country,
		description: description,
	}, {
			id: itineraryId
		}, function (error, results, fields) {
			if (error != null)
				res.respond(error, 500);
			else
				res.respond([]);
		});
});

/**********************/
/* POST add itinerary */
/**********************/
router.post('/', function (req, res, next) {
	// Get params from client
	var name = req.body.name;
	var country = req.body.country;
	var description = req.body.description;
	var userId = req.body.userId;

	// Insert the itinerary in database
	db.add('itinerary', {
		name: name,
		country: country,
		description: description,
		id_User: userId,
		date: dateHelper.getDateTime()
	}, function (error, results, fields) {
		if (error != null)
			res.respond(error, 500);
		else
			res.respond({ id: results.insertId });
	});
});

/***************************/
/* DELETE delete itinerary */
/***************************/
router.delete('/:itineraryid', function (req, res, next) {
	// Get params from client
	var itineraryId = req.params.itineraryid;

	// Delete the itinerary in database
	db.remove('step', {
		id_Itinerary: itineraryId,
	}, function (error, results, fields) {
		if (error != null)
			res.respond(error, 500);
		else {
			db.remove('itinerary', {
				id: itineraryId,
			}, function (error, results, fields) {
				if (error != null)
					res.respond(error, 500);
				else
					res.respond([]);
			});
		}
	});
});

module.exports = router;
<|endoftext|>


<commit_before>var fs = require('fs')
var os = require('os')
var join = require('path').join
var lruCache = require('lru-cache')
var readTorrent = require('read-torrent')
var torrentStream = require('torrent-stream')
var debug = require('debug')('back-row:torrent')
var mkdirp = require('mkdirp')
var parseTorrent = require('parse-torrent')

var TORRENT_PATH = process.env.TORRENT_CACHE_PATH || join(os.tmpDir(), 'back-row')
var TORRENT_INFO_HASH_PATH = join(TORRENT_PATH, 'info-hash')

/**
 * Create a torrent cache.
 *
 * @type {LRUCache}
 */
var TORRENT_CACHE = lruCache({
  max: process.env.TORRENT_CACHE_LIMIT || 10 * 1000 * 1000 * 1000, // 10GB
  length: torrentLength,
  dispose: disposeTorrent
})

/**
 * Keep track of the latest torrent downloads.
 *
 * @type {LRUCache}
 */
var URI_CACHE = lruCache(100) /* { [infoHash: string]: engine } */

/**
 * Dispose of the torrent.
 *
 * @param {String} key
 * @param {Object} torrent
 */
function disposeTorrent (key, torrent) {
  removeTorrent(torrent, logError)
}

/**
 * Remove the torrent from the filesystem.
 *
 * @param {Object}   torrent
 * @param {Function} cb
 */
function removeTorrent (engine, cb) {
  engine.remove(function (rmError) {
    fs.unlink(cacheFilename(engine), function (unlinkError) {
      cb(rmError || unlinkError)
    })
  })
}

/**
 * Return the torrent download size.
 *
 * @param  {Object} torrent
 * @return {Number}
 */
function torrentLength (engine) {
  return engine.torrent ? engine.torrent.length : 0
}

/**
 * Return a consistent file location for torrents.
 *
 * @param  {Object} engine
 * @return {String}
 */
function cacheFilename (engine) {
  return join(TORRENT_INFO_HASH_PATH, engine.infoHash + '.torrent')
}

/**
 * Export the torrent stream.
 */
module.exports = torrent

/**
 * Create a torrent stream.
 *
 * @param {String}   uri
 * @param {Function} done
 */
function torrent (uri, done) {
  if (!/^magnet:|^https?:\/\//i.test(uri)) {
    return done(new Error('Unknown torrent specified'))
  }

  debug('torrent', uri)

  return createTorrentFromLocation(uri, done)
}

/**
 * Create a torrent stream from a uri.
 *
 * @param {String}   uri
 * @param {Function} done
 */
function createTorrentFromLocation (uri, done) {
  function next (err, torrent) {
    if (err) {
      return done(err)
    }

    if (/https?:\/\//i.test(uri)) {
      URI_CACHE.set(uri, torrent)
    }

    return createTorrent(torrent, done)
  }

  if (URI_CACHE.has(uri)) {
    return next(null, URI_CACHE.get(uri))
  }

  return readTorrent(uri, next)
}

/**
 * Create a torrent engine from an object.
 *
 * @param {Object}   torrent
 * @param {Function} done
 */
function createTorrent (torrent, done) {
  var engine = TORRENT_CACHE.get(torrent.infoHash)
  var exists = !!engine

  if (!engine) {
    engine = createEngine(torrent)
  }

  function next (engine) {
    // Avoid unnecessary torrent persistence creation.
    if (exists) {
      return done(null, engine)
    }

    TORRENT_CACHE.set(engine.infoHash, engine)

    return mkdirp(TORRENT_INFO_HASH_PATH, function (err) {
      if (err) {
        return done(err)
      }

      var buf = parseTorrent.toTorrentFile(engine.torrent)

      return fs.writeFile(cacheFilename(engine), buf, function (err) {
        return done(err, engine)
      })
    })
  }

  if (engine.torrent) {
    return next(engine)
  }

  return engine.on('ready', function () {
    return next(engine)
  })
}

/**
 * Create a new torrent stream.
 *
 * @param  {String} uri
 * @return {Object}
 */
function createEngine (uri) {
  var engine = torrentStream(uri, {
    tmp: TORRENT_PATH
  })

  engine.on('error', logError)
  engine.on('interested', function () { engine.swarm.resume() })
  engine.on('uninterested', function () { engine.swarm.pause() })

  return engine
}

/**
 * Log an error callback that isn't handled otherwise.
 *
 * @param {Error} err
 */
function logError (err) {
  if (err) {
    console.log(err)
  }
}

/**
 * Create and/or read existing torrent files into application. This is an
 * in-memory solution to keeping the cache within the defined limit.
 */
(function () {
  try {
    fs.statSync(TORRENT_INFO_HASH_PATH)
  } catch (e) {
    return // Ignore rebooting when hashes are empty.
  }

  var hashes = fs.readdirSync(TORRENT_INFO_HASH_PATH)

  console.log('Found ' + hashes.length + ' hashes in ' + TORRENT_INFO_HASH_PATH)

  hashes.forEach(function (hash) {
    var filename = join(TORRENT_INFO_HASH_PATH, hash)
    var torrent = parseTorrent(fs.readFileSync(filename))

    console.log('Restarting torrent stream:', torrent.name)

    return createTorrent(torrent, logError)
  })
})()
<commit_msg>Correct https? uri cache check<commit_after>var fs = require('fs')
var os = require('os')
var join = require('path').join
var lruCache = require('lru-cache')
var readTorrent = require('read-torrent')
var torrentStream = require('torrent-stream')
var debug = require('debug')('back-row:torrent')
var mkdirp = require('mkdirp')
var parseTorrent = require('parse-torrent')

var TORRENT_PATH = process.env.TORRENT_CACHE_PATH || join(os.tmpDir(), 'back-row')
var TORRENT_INFO_HASH_PATH = join(TORRENT_PATH, 'info-hash')

/**
 * Create a torrent cache.
 *
 * @type {LRUCache}
 */
var TORRENT_CACHE = lruCache({
  max: process.env.TORRENT_CACHE_LIMIT || 10 * 1000 * 1000 * 1000, // 10GB
  length: torrentLength,
  dispose: disposeTorrent
})

/**
 * Keep track of the latest torrent downloads.
 *
 * @type {LRUCache}
 */
var URI_CACHE = lruCache(100) /* { [infoHash: string]: engine } */

/**
 * Dispose of the torrent.
 *
 * @param {String} key
 * @param {Object} torrent
 */
function disposeTorrent (key, torrent) {
  removeTorrent(torrent, logError)
}

/**
 * Remove the torrent from the filesystem.
 *
 * @param {Object}   torrent
 * @param {Function} cb
 */
function removeTorrent (engine, cb) {
  engine.remove(function (rmError) {
    fs.unlink(cacheFilename(engine), function (unlinkError) {
      cb(rmError || unlinkError)
    })
  })
}

/**
 * Return the torrent download size.
 *
 * @param  {Object} torrent
 * @return {Number}
 */
function torrentLength (engine) {
  return engine.torrent ? engine.torrent.length : 0
}

/**
 * Return a consistent file location for torrents.
 *
 * @param  {Object} engine
 * @return {String}
 */
function cacheFilename (engine) {
  return join(TORRENT_INFO_HASH_PATH, engine.infoHash + '.torrent')
}

/**
 * Export the torrent stream.
 */
module.exports = torrent

/**
 * Create a torrent stream.
 *
 * @param {String}   uri
 * @param {Function} done
 */
function torrent (uri, done) {
  if (!/^magnet:|^https?:\/\//i.test(uri)) {
    return done(new Error('Unknown torrent specified'))
  }

  debug('torrent', uri)

  return createTorrentFromLocation(uri, done)
}

/**
 * Create a torrent stream from a uri.
 *
 * @param {String}   uri
 * @param {Function} done
 */
function createTorrentFromLocation (uri, done) {
  function next (err, torrent) {
    if (err) {
      return done(err)
    }

    if (/^https?:\/\//i.test(uri)) {
      URI_CACHE.set(uri, torrent)
    }

    return createTorrent(torrent, done)
  }

  if (URI_CACHE.has(uri)) {
    return next(null, URI_CACHE.get(uri))
  }

  return readTorrent(uri, next)
}

/**
 * Create a torrent engine from an object.
 *
 * @param {Object}   torrent
 * @param {Function} done
 */
function createTorrent (torrent, done) {
  var engine = TORRENT_CACHE.get(torrent.infoHash)
  var exists = !!engine

  if (!engine) {
    engine = createEngine(torrent)
  }

  function next (engine) {
    // Avoid unnecessary torrent persistence creation.
    if (exists) {
      return done(null, engine)
    }

    TORRENT_CACHE.set(engine.infoHash, engine)

    return mkdirp(TORRENT_INFO_HASH_PATH, function (err) {
      if (err) {
        return done(err)
      }

      var buf = parseTorrent.toTorrentFile(engine.torrent)

      return fs.writeFile(cacheFilename(engine), buf, function (err) {
        return done(err, engine)
      })
    })
  }

  if (engine.torrent) {
    return next(engine)
  }

  return engine.on('ready', function () {
    return next(engine)
  })
}

/**
 * Create a new torrent stream.
 *
 * @param  {String} uri
 * @return {Object}
 */
function createEngine (uri) {
  var engine = torrentStream(uri, {
    tmp: TORRENT_PATH
  })

  engine.on('error', logError)
  engine.on('interested', function () { engine.swarm.resume() })
  engine.on('uninterested', function () { engine.swarm.pause() })

  return engine
}

/**
 * Log an error callback that isn't handled otherwise.
 *
 * @param {Error} err
 */
function logError (err) {
  if (err) {
    console.log(err)
  }
}

/**
 * Create and/or read existing torrent files into application. This is an
 * in-memory solution to keeping the cache within the defined limit.
 */
(function () {
  try {
    fs.statSync(TORRENT_INFO_HASH_PATH)
  } catch (e) {
    return // Ignore rebooting when hashes are empty.
  }

  var hashes = fs.readdirSync(TORRENT_INFO_HASH_PATH)

  console.log('Found ' + hashes.length + ' hashes in ' + TORRENT_INFO_HASH_PATH)

  hashes.forEach(function (hash) {
    var filename = join(TORRENT_INFO_HASH_PATH, hash)
    var torrent = parseTorrent(fs.readFileSync(filename))

    console.log('Restarting torrent stream:', torrent.name)

    return createTorrent(torrent, logError)
  })
})()
<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var UserInvite = require('../models/userInvite');
var Verify = require('./verify');
var SendMail = require('./sendmail');

var router = express.Router();
router.use(bodyParser.json());

//#################################################################################################
//#################################################################################################
router.route('/')

//get all user invites:
.get(function(req, res) {
    UserInvite.find(req.query)
        .populate('role')
        .exec(function(err, userInvites) {
            if(err) throw err;
            res.json(userInvites);
    });
})

//add a new user invite to the system:
.post(Verify.verifyOrdinaryUser, SendMail.sendInviteEmail, function(req, res, next) {
    console.log(req.emailResponse);
    UserInvite.create(req.body, function(err, userInvite) {
        if(err) return next(err);
        console.log("New user invite created");
        res.json(userInvite);
    });
})

.delete(Verify.verifyOrdinaryUser, function(req, res, next) {
    UserInvite.remove({}, function(err, userInvites) {
        if(err) return next(err);
        console.log("Removed: \n" + userInvites);
        res.json("All user invites removed.");
    });
});

//#################################################################################################
//#################################################################################################
router.route('/:userInviteId')

///GET user invite by ID
.get(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.findById(req.params.userInviteId)
        .populate('role')
        .exec(function(err, userInvite) {
            if(err) throw err;
            res.json(userInvite);
    });
})

//PUT update user invite by ID
.put(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.findByIdAndUpdate(req.params.userInviteId, {$set: req.body}, {new: true})
        .exec(function(err, userInvite) {
            if(err) throw err;
            res.json(userInvite);
    });
})

///DELETE user invite by ID
.delete(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.findById(req.params.userInviteId)
        .exec(function(err, userInvite) {
            if(err) throw err;
            userInvite.remove();
            res.json("Successfully removed user invite " + userInvite.invite_key);
    });
});

//#################################################################################################
//#################################################################################################
router.route('/findByKey/:inviteKey')

///GET user invite by ID
.get(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.find({invite_key: req.params.inviteKey})
        .populate('role')
        .exec(function(err, userInvite) {
            if(err) throw err;
            res.json(userInvite);
    });
});

module.exports = router;<commit_msg>added deleteByKey/:inviteKey path<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var UserInvite = require('../models/userInvite');
var Verify = require('./verify');
var SendMail = require('./sendmail');

var router = express.Router();
router.use(bodyParser.json());

//#################################################################################################
//#################################################################################################
router.route('/')

//get all user invites:
.get(function(req, res) {
    UserInvite.find(req.query)
        .populate('role')
        .exec(function(err, userInvites) {
            if(err) throw err;
            res.json(userInvites);
    });
})

//add a new user invite to the system:
.post(Verify.verifyOrdinaryUser, SendMail.sendInviteEmail, function(req, res, next) {
    console.log(req.emailResponse);
    UserInvite.create(req.body, function(err, userInvite) {
        if(err) return next(err);
        console.log("New user invite created");
        res.json(userInvite);
    });
})

.delete(Verify.verifyOrdinaryUser, function(req, res, next) {
    UserInvite.remove({}, function(err, userInvites) {
        if(err) return next(err);
        console.log("Removed: \n" + userInvites);
        res.json("All user invites removed.");
    });
});

//#################################################################################################
//#################################################################################################
router.route('/:userInviteId')

///GET user invite by ID
.get(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.findById(req.params.userInviteId)
        .populate('role')
        .exec(function(err, userInvite) {
            if(err) throw err;
            res.json(userInvite);
    });
})

//PUT update user invite by ID
.put(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.findByIdAndUpdate(req.params.userInviteId, {$set: req.body}, {new: true})
        .exec(function(err, userInvite) {
            if(err) throw err;
            res.json(userInvite);
    });
})

///DELETE user invite by ID
.delete(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.findById(req.params.userInviteId)
        .exec(function(err, userInvite) {
            if(err) throw err;
            userInvite.remove();
            res.json("Successfully removed user invite " + userInvite.invite_key);
    });
});

//#################################################################################################
//#################################################################################################
router.route('/findByKey/:inviteKey')

///GET user invite by invite key
.get(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.find({invite_key: req.params.inviteKey})
        .populate('role')
        .exec(function(err, userInvite) {
            if(err) throw err;
            res.json(userInvite);
    });
});

//#################################################################################################
//#################################################################################################
router.route('/deleteByKey/:inviteKey')

///DELETE user invite by invite key
.delete(Verify.verifyOrdinaryUser, function(req, res) {
    UserInvite.find({invite_key: req.params.inviteKey})
        .exec(function(err, userInvite) {
            if(err) throw err;
            userInvite.remove();
            res.json("Successfully removed user invite " + userInvite.invite_key);
    });
});

module.exports = router;<|endoftext|>


<commit_before>var express = require('express');
var User = require(__dirname + '/../models/user');
var jsonParser = require('body-parser').json();
var httpBasic = require(__dirname + '/../lib/http_basic');
var handleError = require(__dirname + '/../lib/handle_error');

var app = module.exports = exports = express.Router();

app.get('/', function(req, res, next){
    if(!req.auth.username){
      redirect: '/signin'
    }
});

app.get('/signin', httpBasic, function(req, res){
    User.findOne({'basic.username': req.auth.username}, function(err, user){
        if(err) return handleError(err, res);
        if(!User){
            console.log('could not authenticate ' + req.auth.username);
            return res.status(401).json({success: false, msg: 'could not authenticate'});
        }

        User.compareHash(req.auth.password, function(err, hashRes){
            if(err) return handleError(err, res);
            if(!hashRes){
                console.log('could not authenticate ' + req.auth.username);
                return res.status(401).json({success: false, msg: 'could not authenticate'});
            }

            User.generateToken(function(err, token){
                if(err) return handleError(err, res);
                res.json({success: true, token: token});
            });
        });
    });
});

app.post('/signup', jsonParser, function(req, res){
    var newUser = new User();
    newUser.basic.username = req.body.username;
    newUser.username = req.body.username;
    newUser.generateHash(req.body.password, function(err, hash){
        if(err) return handleError(err, data);
        newUser.save(function(err, data){
            if(err) return handleError(err, data);
            newUser.generateToken(function(err, token){
                if(err) return handleError(err, res);
                res.json({success: true, token: token});
            });
        });
    });
});
<commit_msg>adding event emitters to user_routes for auth<commit_after>var express = require('express');
var User = require(__dirname + '/../models/user');
var jsonParser = require('body-parser').json();
var httpBasic = require(__dirname + '/../lib/http_basic');
var handleError = require(__dirname + '/../lib/handle_error');
var EventEmitter = require('events').EventEmitter;
var ee = new EventEmitter();
var user;

var app = module.exports = exports = express.Router();

app.get('/', function(req, res, next){
    if(!req.auth.username){
      redirect: '/signin'
    }
});

app.get('/signin', httpBasic, function(req, res){
    ee.emit('findOne', req, res, user);
});

ee.on('findOne', function(req, res, user){
    User.findOne({'basic.username': req.auth.username}, function(err, user){
        if(err) return handleError(err, res);
        if(!User){
            console.log('could not authenticate ' + req.auth.username);
            return res.status(401).json({success: false, msg: 'could not authenticate'});
        }
        ee.emit('compareHash', req, res, user);
    });
});

ee.on('compareHash', function(req, res, user){
    User.compareHash(req.auth.password, function(err, hashRes){
        if(err) return handleError(err, res);
        if(!hashRes){
            console.log('could not authenticate ' + req.auth.username);
            return res.status(401).json({success: false, msg: 'could not authenticate'});
        }
        ee.emit('generateToken', req, res, user);
    });
});

ee.on('generateToken', function(req, res, user){
    User.generateToken(function(err, token){
        if(err) return handleError(err, res);
        res.json({success: true, token: token});
    });
});

app.post('/signup', jsonParser, function(req, res){
    var newUser = new User();
    newUser.basic.username = req.body.username;
    newUser.username = req.body.username;
    ee.emit('generateHash', newUser, req, res);
});

ee.on('generateHash', function(newUser, req, res){
    newUser.generateHash(req.body.password, function(err, hash){
        if(err) return handleError(err, data);
        ee.emit('save', newUser, req, res);
    });
});

ee.on('save', function(newUser, req, res){
    newUser.save(function(err, data){
        if(err) return handleError(err, data);
        ee.emit('generateToken', newUser, req, res);
    });
});

ee.on('generateNewToken', function(newUser, req, res){
    newUser.generateToken(function(err, token){
        if(err) return handleError(err, res);
        res.json({success: true, token: token});
});
<|endoftext|>


<commit_before>
window.vis = window.vis || {};

window.vis.svgs = function(element){

  var simplify = require('simplify-geojson')

  var w = 600, h = 600;
  var svg = d3.select(element)
    .select('.panel-body')
    .append('svg')
    .attr('width', w)
    .attr('height', h);

  d3.json('/sw/geo.simple.json',function(error, geo) {
    if(error) return console.error("Unable to get json", error);

      var groups = geofn
                    .group_bounds(geo.features.map(function(f){
                      return f.bbox
                    }))

      // group together by intersecting bounding box
      var group_layout = {
        children:
          groups
          .map(function(bound, i) {
            return {
              id:i,
              bbox: bound,
              centroids: []
            }
          })
      }

      d3.layout.pack()
        .value(function(){return 1})
        .size([w,h])
        (group_layout)

      // assign groups to features
      geo.features.forEach(function(feature, i){
        for (var i = 0; i < groups.length; i++) {
          if(geofn.intersects(feature.bbox, groups[i])){
            feature.properties.group = group_layout.children[i];
            group_layout.children[i].centroids.push(feature.properties.centroid);
            break;
          }
        }
      })

      group_layout.children.forEach(function(group){
        group.centroid = d3.transpose(group.centroids)
                           .map(function(d){return d3.mean(d)})
      })

      var layout = {
        children: d3.range(geo.features.length).map(function(){return {}})
      }

      d3.layout.pack()
        .value(function(d, i){return geo.features[i].properties.total_distance})
        .value(function(){return 1})
        .size([w,h])
        (layout)

      geo.features.forEach(function(feature,i){
        feature.properties.layout = layout.children[i]
      })

      var projection = d3.geo.equirectangular()
                          .translate([0,0])
                          .scale(300000);

      var path = d3.geo.path().projection(projection)

      var colours = d3.scale.category20();

      var x = d3.scale.linear()
        .domain([0,geo.features.length])
        .range([50,w-50])

      svg.selectAll("path.activity")
          .data(geo.features)
          .enter()
            .append("path")
            .attr('class', 'activity')
            .attr("d", function(d){
              path.projection()
                .rotate(
                  d.properties.centroid
                   .slice(0,2)
                   .map(function(d){return d*-1})
                )
              return path(d);
            })
            .style('stroke', function(d,i){
              return colours(d.properties.group.id)
            })
            .attr('transform', function(d,i){
                var l = d.properties.layout;
                return 'translate('+l.x+','+l.y+') scale(0.5) rotate(-45)'
            })

            // group together
            .transition()
            .delay(function(d,i){
              return (i * 5) + 200
            })
            .duration(3500)
            .attr('transform', function(d,i){
                var g = d.properties.group;
                return 'translate('+g.x+','+g.y+') scale(.5)'
            })

            // re-plot based on centroid
            .transition()
            .delay(function(d,i){
              return (i * 5) + 4500
            })
            .duration(3500)

            .attr("d", function(d, i){
              var g = d.properties.group;
              path.projection()
                .rotate(
                  g.centroid
                   .slice(0,2)
                   .map(function(d){return d*-1})
                )
              return path(d);
            })

      svg.selectAll('circle.choice')
        .data(group_layout.children)
        .enter()
        .append('circle')
        .attr('class','choice')
        .attr('r', 0)
        .on('click', function(d){
          console.log(d)
          window.location.hash = 'box=' + d.bbox.join(',')
        })
        .transition()
        .delay(function(d,i){return 7000 + i*100})
        .duration(2000)
        .attr('r',  function(d){return d.r})
        .attr('cx', function(d){return d.x})
        .attr('cy', function(d){return d.y})

    })

}
<commit_msg>move layout to a place where it doesn’t screw stuff<commit_after>
window.vis = window.vis || {};

window.vis.svgs = function(element){

  var simplify = require('simplify-geojson')

  var w = 600, h = 600;
  var svg = d3.select(element)
    .select('.panel-body')
    .append('svg')
    .attr('width', w)
    .attr('height', h);

  d3.json('/sw/geo.simple.json',function(error, geo) {
    if(error) return console.error("Unable to get json", error);

      var groups = geofn
                    .group_bounds(geo.features.map(function(f){
                      return f.bbox
                    }))

      // group together by intersecting bounding box
      var group_layout = {
        children:
          groups
          .map(function(bound, i) {
            return {
              id:i,
              bbox: bound,
              centroids: []
            }
          })
      }

      // assign groups to features
      geo.features.forEach(function(feature, i){
        for (var i = 0; i < groups.length; i++) {
          if(geofn.intersects(feature.bbox, groups[i])){
            feature.properties.group = group_layout.children[i];
            group_layout.children[i].centroids.push(feature.properties.centroid);
            break;
          }
        }
      })

      // WARNING layout can re-order group_layout.children
      d3.layout.pack()
        .value(function(){return 1})
        .size([w,h])
        (group_layout)

      group_layout.children.forEach(function(group){
        group.centroid = d3.transpose(group.centroids)
                           .map(function(d){return d3.mean(d)})
      })

      var layout = {
        children: d3.range(geo.features.length).map(function(){return {}})
      }

      d3.layout.pack()
        .value(function(d, i){return geo.features[i].properties.total_distance})
        .value(function(){return 1})
        .size([w,h])
        (layout)

      geo.features.forEach(function(feature,i){
        feature.properties.layout = layout.children[i]
      })

      var projection = d3.geo.equirectangular()
                          .translate([0,0])
                          .scale(300000);

      var path = d3.geo.path().projection(projection)

      var colours = d3.scale.category20();

      var x = d3.scale.linear()
        .domain([0,geo.features.length])
        .range([50,w-50])

      svg.selectAll("path.activity")
          .data(geo.features)
          .enter()
            .append("path")
            .attr('class', 'activity')
            .attr("d", function(d){
              path.projection()
                .rotate(
                  d.properties.centroid
                   .slice(0,2)
                   .map(function(d){return d*-1})
                )
              return path(d);
            })
            .style('stroke', function(d,i){
              return colours(d.properties.group.id)
            })
            .attr('transform', function(d,i){
                var l = d.properties.layout;
                return 'translate('+l.x+','+l.y+') scale(0.5) rotate(-45)'
            })

            // group together
            .transition()
            .delay(function(d,i){
              return (i * 5) + 200
            })
            .duration(3500)
            .attr('transform', function(d,i){
                var g = d.properties.group;
                return 'translate('+g.x+','+g.y+') scale(.5)'
            })

            // re-plot based on centroid
            .transition()
            .delay(function(d,i){
              return (i * 5) + 4500
            })
            .duration(3500)

            .attr("d", function(d, i){
              var g = d.properties.group;
              path.projection()
                .rotate(
                  g.centroid
                   .slice(0,2)
                   .map(function(d){return d*-1})
                )
              return path(d);
            })

      svg.selectAll('circle.choice')
        .data(group_layout.children)
        .enter()
        .append('circle')
        .attr('class','choice')
        .attr('r', 0)
        .on('click', function(d){
          console.log(d)
          window.location.hash = 'box=' + d.bbox.join(',')
        })
        .transition()
        .delay(function(d,i){return 7000 + i*100})
        .duration(2000)
        .attr('r',  function(d){return d.r})
        .attr('cx', function(d){return d.x})
        .attr('cy', function(d){return d.y})

    })

}
<|endoftext|>