<commit_before>//Camtull-Rom spline implementation
//Inspired by code from [Tween.js][1]
//[1]: http://sole.github.com/tween.js/examples/05_spline.html

//## Example use
//
//     var points = [
//       new Core.Vec3(-2,  0, 0),
//       new Core.Vec3(-1,  0, 0),
//       new Core.Vec3( 1,  1, 0),
//       new Core.Vec3( 2, -1, 0)
//     ];
//
//     var spline = new Spline(points);
//
//     spline.getPointAt(0.25);

//## Reference

define(["pex/core/Vec3"], function(Vec3) {

  //### Spline ( points, [ loop ] )
  //`points` - *{ Array of Vec3 }* = [ ]
  //`loop` - is the spline a connected loop? *{ Boolean }* = false
  function Spline(points, loop) {
    this.points = points || [];
    this.dirtyLength = true;
    this.loop = loop || false;
    this.samplesCount = 2000;
  }

  //### getPoint ( t )
  //Gets position based on t-value.
  //It is fast, but resulting points will not be evenly distributed.
  //
  //`t` - *{ Number } <0, 1>*
  Spline.prototype.getPoint = function ( t ) {
    t = (t + 1 ) % 1;

    var points = this.points;
    var len = this.loop ? points.length : points.length - 1;
    var point = t * len;
    var intPoint = Math.floor( point );
    var weight = point - intPoint;

    var c0, c1, c2, c3;
    if (this.loop) {
      c0 = (intPoint - 1 + points.length ) % points.length;
      c1 = intPoint % points.length;
      c2 = (intPoint + 1 ) % points.length;
      c3 = (intPoint + 2 ) % points.length;
    }
    else {
      c0 = intPoint == 0 ? intPoint : intPoint - 1;
      c1 = intPoint;
      c2 = intPoint > points.length - 2 ? intPoint : intPoint + 1;
      c3 = intPoint > points.length - 3 ? intPoint : intPoint + 2;
    }

    var vec = new Vec3();
    vec.x = this.interpolate( points[ c0 ].x, points[ c1 ].x, points[ c2 ].x, points[ c3 ].x, weight );
    vec.y = this.interpolate( points[ c0 ].y, points[ c1 ].y, points[ c2 ].y, points[ c3 ].y, weight );
    vec.z = this.interpolate( points[ c0 ].z, points[ c1 ].z, points[ c2 ].z, points[ c3 ].z, weight );

    return vec;
  }

  //### addPoint ( p )
  //Adds point to the spline
  //
  //`p` - point to be added *{ Vec3 }*
  Spline.prototype.addPoint = function ( p ) {
    this.dirtyLength = true;
    this.points.push(p)
  }

  //### getPointAt ( d )
  //Gets position based on d-th of total length of the curve.
  //Precise but might be slow at the first use due to need to precalculate length.
  //
  //`d` - *{ Number } <0, 1>*
  Spline.prototype.getPointAt = function ( d ) {
    if (this.loop) {
      d = (d + 1 ) % 1;
    }
    else {
      d = Math.max(0, Math.min(d, 1));
    }

    if (this.dirtyLength) {
      this.precalculateLength();
    }

    //TODO: try binary search
    var k = 0;
    for(var i=0; i<this.accumulatedLengthRatios.length; i++) {
      if (this.accumulatedLengthRatios[i] >= d) {
        k = this.accumulatedRatios[i];
        break;
      }
    }

    return this.getPoint(k);
  }

  //### getPointAtIndex ( i )
  //Returns position of i-th point forming the curve
  //
  //`i` - *{ Number } <0, Spline.points.length)*
  Spline.prototype.getPointAtIndex = function ( i ) {
    if (i < this.points.length) {
      return this.points[i];
    }
    else {
      return null;
    }
  }

  //### getNumPoints ( )
  //Return number of base points in the spline
  Spline.prototype.getNumPoints = function() {
    return this.points.length;
  }

  //### getLength ( )
  //Returns the total length of the spline.
  Spline.prototype.getLength = function() {
    if (this.dirtyLength) {
      this.precalculateLength();
    }
    return this.length;
  }

  //### precalculateLength ( )
  //Goes through all the segments of the curve and calculates total length and
  //the ratio of each segment.
  Spline.prototype.precalculateLength = function() {
    var step = 1/this.samplesCount;
    var k = 0;
    var totalLength = 0;
    this.accumulatedRatios = [];
    this.accumulatedLengthRatios = [];
    this.accumulatedLengths = [];

    var point;
    var prevPoint;
    var k = 0;
    for(var i=0; i<this.samplesCount; i++) {
      prevPoint = point;
      point = this.getPoint(k);

      if (i > 0) {
        var len = point.subbed(prevPoint).length();
        totalLength += len;
      }

      this.accumulatedRatios.push(k);
      this.accumulatedLengths.push(totalLength)

      k += step;
    }

    for(var i=0; i<this.samplesCount; i++) {
      this.accumulatedLengthRatios.push(this.accumulatedLengths[i] / totalLength);
    }

    this.length = totalLength;
    this.dirtyLength = false;
  }

  //### interpolate ( p0, p1, p2, p3, t)
  //Helper function to calculate Catmul-Rom spline equation
  //
  //`p0` - previous value *{ Number }*
  //`p1` - current value *{ Number }*
  //`p2` - next value *{ Number }*
  //`p3` - next next value *{ Number }*
  //`t` - parametric distance between p1 and p2 *{ Number } <0, 1>*
  Spline.prototype.interpolate = function(p0, p1, p2, p3, t) {
    var v0 = ( p2 - p0 ) * 0.5;
    var v1 = ( p3 - p1 ) * 0.5;
    var t2 = t * t;
    var t3 = t * t2;
    return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  }

  return Spline;
})<commit_msg>Added methods to close spline<commit_after>//Camtull-Rom spline implementation
//Inspired by code from [Tween.js][1]
//[1]: http://sole.github.com/tween.js/examples/05_spline.html

//## Example use
//
//     var points = [
//       new Core.Vec3(-2,  0, 0),
//       new Core.Vec3(-1,  0, 0),
//       new Core.Vec3( 1,  1, 0),
//       new Core.Vec3( 2, -1, 0)
//     ];
//
//     var spline = new Spline(points);
//
//     spline.getPointAt(0.25);

//## Reference

define(["pex/core/Vec3"], function(Vec3) {

  //### Spline ( points, [ loop ] )
  //`points` - *{ Array of Vec3 }* = [ ]
  //`loop` - is the spline a connected loop? *{ Boolean }* = false
  function Spline(points, loop) {
    this.points = points || [];
    this.dirtyLength = true;
    this.loop = loop || false;
    this.samplesCount = 2000;
  }

  //### getPoint ( t )
  //Gets position based on t-value.
  //It is fast, but resulting points will not be evenly distributed.
  //
  //`t` - *{ Number } <0, 1>*
  Spline.prototype.getPoint = function ( t ) {
    t = (t + 1 ) % 1;

    var points = this.points;
    var len = this.loop ? points.length : points.length - 1;
    var point = t * len;
    var intPoint = Math.floor( point );
    var weight = point - intPoint;

    var c0, c1, c2, c3;
    if (this.loop) {
      c0 = (intPoint - 1 + points.length ) % points.length;
      c1 = intPoint % points.length;
      c2 = (intPoint + 1 ) % points.length;
      c3 = (intPoint + 2 ) % points.length;
    }
    else {
      c0 = intPoint == 0 ? intPoint : intPoint - 1;
      c1 = intPoint;
      c2 = intPoint > points.length - 2 ? intPoint : intPoint + 1;
      c3 = intPoint > points.length - 3 ? intPoint : intPoint + 2;
    }

    var vec = new Vec3();
    vec.x = this.interpolate( points[ c0 ].x, points[ c1 ].x, points[ c2 ].x, points[ c3 ].x, weight );
    vec.y = this.interpolate( points[ c0 ].y, points[ c1 ].y, points[ c2 ].y, points[ c3 ].y, weight );
    vec.z = this.interpolate( points[ c0 ].z, points[ c1 ].z, points[ c2 ].z, points[ c3 ].z, weight );

    return vec;
  }

  //### addPoint ( p )
  //Adds point to the spline
  //
  //`p` - point to be added *{ Vec3 }*
  Spline.prototype.addPoint = function ( p ) {
    this.dirtyLength = true;
    this.points.push(p)
  }

  //### getPointAt ( d )
  //Gets position based on d-th of total length of the curve.
  //Precise but might be slow at the first use due to need to precalculate length.
  //
  //`d` - *{ Number } <0, 1>*
  Spline.prototype.getPointAt = function ( d ) {
    if (this.loop) {
      d = (d + 1 ) % 1;
    }
    else {
      d = Math.max(0, Math.min(d, 1));
    }

    if (this.dirtyLength) {
      this.precalculateLength();
    }

    //TODO: try binary search
    var k = 0;
    for(var i=0; i<this.accumulatedLengthRatios.length; i++) {
      if (this.accumulatedLengthRatios[i] >= d) {
        k = this.accumulatedRatios[i];
        break;
      }
    }

    return this.getPoint(k);
  }

  //### getPointAtIndex ( i )
  //Returns position of i-th point forming the curve
  //
  //`i` - *{ Number } <0, Spline.points.length)*
  Spline.prototype.getPointAtIndex = function ( i ) {
    if (i < this.points.length) {
      return this.points[i];
    }
    else {
      return null;
    }
  }

  //### getNumPoints ( )
  //Return number of base points in the spline
  Spline.prototype.getNumPoints = function() {
    return this.points.length;
  }

  //### getLength ( )
  //Returns the total length of the spline.
  Spline.prototype.getLength = function() {
    if (this.dirtyLength) {
      this.precalculateLength();
    }
    return this.length;
  }

  //### precalculateLength ( )
  //Goes through all the segments of the curve and calculates total length and
  //the ratio of each segment.
  Spline.prototype.precalculateLength = function() {
    var step = 1/this.samplesCount;
    var k = 0;
    var totalLength = 0;
    this.accumulatedRatios = [];
    this.accumulatedLengthRatios = [];
    this.accumulatedLengths = [];

    var point;
    var prevPoint;
    var k = 0;
    for(var i=0; i<this.samplesCount; i++) {
      prevPoint = point;
      point = this.getPoint(k);

      if (i > 0) {
        var len = point.subbed(prevPoint).length();
        totalLength += len;
      }

      this.accumulatedRatios.push(k);
      this.accumulatedLengths.push(totalLength)

      k += step;
    }

    for(var i=0; i<this.samplesCount; i++) {
      this.accumulatedLengthRatios.push(this.accumulatedLengths[i] / totalLength);
    }

    this.length = totalLength;
    this.dirtyLength = false;
  }

  //### close ( )
  //Closes the spline. It will form a loop now.
  Spline.prototype.close = function( ) {
    this.loop = true;
  }

  //### isClosed ( )
  //Returns true if spline is closed (forms a loop) *{ Boolean }*
  Spline.prototype.isClosed = function() {
    return this.loop;
  }

  //### interpolate ( p0, p1, p2, p3, t)
  //Helper function to calculate Catmul-Rom spline equation
  //
  //`p0` - previous value *{ Number }*
  //`p1` - current value *{ Number }*
  //`p2` - next value *{ Number }*
  //`p3` - next next value *{ Number }*
  //`t` - parametric distance between p1 and p2 *{ Number } <0, 1>*
  Spline.prototype.interpolate = function(p0, p1, p2, p3, t) {
    var v0 = ( p2 - p0 ) * 0.5;
    var v1 = ( p3 - p1 ) * 0.5;
    var t2 = t * t;
    var t3 = t * t2;
    return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  }

  return Spline;
})<|endoftext|>


<commit_before>var pj = require('./paper-core.js')
var asyncMap = require('slide').asyncMap
var drompii = require('./drompii.js')
var through = require('through2')
var D = require('./dombii.js')
var ddx = require('./dedex.js')
var fs = require('fs')
var _ = require('underscore')
var path = require('path')

var OMNI = fs.readFileSync(__dirname+'/omni.hogan', 'utf8')
var GRIFTER = fs.readFileSync(__dirname+'/grifter.hogan', 'utf8')
var LOGIN = fs.readFileSync(__dirname+'/login.hogan', 'utf8')

module.exports = function Omni (opts) {
  var blob
  var dx = {}
  dx.desc = 'login'

  var s = through.obj(function Interface (d, enc, next) {
    if (d.code === 1) {
      next()
      login.draw({err:true,msg:d.message})
      document.body.querySelector('#login').focus()
      return null
    } else if (!d.key) { next(); return null }

    var tkn = (d.key.split(':').length>1)
      ? d.key.split(':')[1]
      : d.key

    if (tkn && tkn === opts.id) {
      if (d.key.split(':')[0] === '@edit') {
        sessionStorage['edit'] = d.value
        login.erase()
        omni.draw(dx, initUI)
      } else {
        if (d.value === '-edit') omni.erase() // but it should also be unpiped

        // var val = d.value[0]
        // if (!val) { next(); return false }
        // dx.pkg = val
        // ui.readout(val.name)
        // pj.view.draw()

      }
    }
    next()
  })

 // UI

  var ui =  {}

  function initUI () {
    pj.setup(document.querySelector('#cvs'))

    ui.results = new pj.Group({ point:[0,0] })

    ui.label = new pj.PointText({
      point : [0,0],
      fontFamily : 'Monaco',
      fillColor : 'black',
      content : name,
      fontSize : 10
    })

    ui.makeBox = function (name,pos) {
      var label = new pj.PointText({
        point : [0,0],
        fontFamily : 'Monaco',
        fillColor : 'black',
        content : name,
        fontSize : 10
      })

      label.position.x = (label.bounds.width/2) + 4
      label.position.y = (label.bounds.height/2) + 4

      var frame = new pj.Shape.Rectangle({
        strokeWidth : 1,
        strokeColor : 'black',
        point : [0,0],
        size : [label.bounds.width+8, label.bounds.height+8]
      })

      var nb = new pj.Group({
        children : [frame,label]
      })
      nb.position.x = label.position.x + 2

      var y = (ui.results.children.length+1)*(frame.bounds.height+4)
      y += (label.position.y+1)

      nb.position.y = y

      return nb
    }

    ui.readout = function (str) {
      ui.label.content = str
      ui.label.position.y = (ui.label.bounds.height/2) + 4
      ui.label.position.x = ui.label.bounds.width/2
    }
  }

  // TEMPLATES

  var login = new D({
    template : LOGIN,
    parent : document.body,
    events : [['.login','submit',function (e) {
      e.preventDefault()
      s.push('+@edit '+e.target[0].value+':'+opts.id)
      e.target[0].value = ''
    }]]
  })

  var omni = new D({
    id : opts.id,
    template : OMNI,
    parent : document.body,
    events : [
      [window,'contextmenu',grifter],
      ['.oz','keyup',keyInput]
    ]
  })

  var editor = new D({
    template : GRIFTER,
    parent : document.body,
    events : [
      ['.grifter','keyup',edit],
      ['.grifter','drop',upload],
      ['.grifter','dragenter',cancel],
      ['.grifter','dragleave',cancel],
      ['.grifter','dragover',cancel]
    ]
  })

  // EVENTS

  function keyInput (e) {
    var val = e.target.value.replace(' ','')

    if (e.keyCode === 8 || e.key === 'Backspace' && val === '')
      pj.view.draw()

    else if (e.keyCode === 13 || e.key === 'Enter') {
      e.preventDefault()
      // var b = ui.makeBox(dx.pkg.name,[0,10])
      // ui.results.addChild(b)
      // pj.view.draw()
      // e.target.value = ''
      s.push(val)
    }
  }

  // MAKE PANELS DRAGGABLE

  var drag
  function ungrip (e) { window.removeEventListener('mousemove',drag) }
  function grip(e) {
    e.preventDefault()

    ungrip(e)

    var p = e.target.parentElement
    var offX = e.clientX - p.pageX
    var offY = e.clientY - p.pageY

    drag = function (e) {
      dx.x = e.clientX - offX
      dx.y = e.clientY - offY
      omni.draw(dx)
    }

    window.addEventListener('mousemove', drag, false)
  }

  // CONTEXT / EDIT

  function grifter (e) {
    e.preventDefault()
    blob = drompii(e)
    editor.erase()

    var dx = {
      x : e.pageX-10,
      y: e.pageY-10,
      body: _.values(blob.edit)[0].replace(/[\n\r]/g,'')
    }

    if (dx.body.length>140) { dx.w = 400; dx.h = 300 }

    switch (blob.type) {
      case 'SPAN' : editor.draw(dx);break;
      case 'IMG' : editor.draw(dx);break;
    }
  }

  function edit (e) {
    if (e.keyCode === 13) {
      e.preventDefault()
      var body = e.target.value.replace(/[\n\r]/g,'')
      blob.data[_.keys(blob.edit)[0]] = body
      s.push({key:'+$'+blob.id,value:blob.data})
      editor.erase()
      return false
    }
  }

  function upload (e) {
    cancel(e)
    var files = e.dataTransfer.files

    for (file in files) {
      if (file === 'length') return
      if (files[file] && files[file].type)
        var fileName =files[file].name.replace(/[^a-z0-9]/gi,'_').toLowerCase()

      var filepath
      var ndata = {}
      var formData = new FormData()
      formData.append('file', fileName)
      formData.append('token', 'test123')

      var xhr = new XMLHttpRequest()
      xhr.addEventListener('error', function (e) { console.error(e) }, false)
      xhr.addEventListener('load', function (e) {
        s.push({key:'+$'+ndata.id,value:ndata.data})
      }, false)
      xhr.addEventListener('progress', function (e) {
        editor.data.body = 'loaded : ' + (e.loaded/e.total) * 100 + '% '
        editor.draw()
        if (e.loaded === e.total) editor.erase()
        else if (e.total === 0) editor.erase()
      }, false)
      xhr.open('post', '/upload', true)

      var reader = new FileReader()
      reader.readAsDataURL(files[file])
      reader.addEventListener('load', function (data) {
        filePath = '/files/'+fileName
        formData.append('blob', data.target.result)
        editor.erase()
        if (data.target.result.split('/')[0]==='data:image') {
          var img = new Image()
          img.src = data.target.result
          img.addEventListener('load',function (e) {
            blob.edit.w = e.target.width
            blob.edit.h = e.target.height
            blob.edit.src = '/files/'+fileName
            _.each(blob.edit, function (v,k,l) {
              if (blob.data[k]) blob.data[k] = v
            })
            _.each(blob, function (v,k,l) { ndata[k] = v })
          },false)
        }
        xhr.send(formData)
      }, false)
    }
  }

  if (sessionStorage['edit'])
    s.push('+@edit '+sessionStorage['edit']+':'+opts.id)

  if (!sessionStorage['edit']) {
    login.draw({err:false})
    document.body.querySelector('#login').focus()
  }

  return s
}

function cancel (e) {
  e.preventDefault()
  if (e.stopPropogation) e.stopPropogation()
}
<commit_msg>use new parcel functionality<commit_after>var pj = require('./paper-core.js')
var asyncMap = require('slide').asyncMap
var drompii = require('./drompii.js')
var through = require('through2')
var D = require('./dombii.js')
var ddx = require('./dedex.js')
var fs = require('fs')
var _ = require('underscore')
var path = require('path')

var OMNI = fs.readFileSync(__dirname+'/omni.hogan', 'utf8')
var GRIFTER = fs.readFileSync(__dirname+'/grifter.hogan', 'utf8')
var LOGIN = fs.readFileSync(__dirname+'/login.hogan', 'utf8')

module.exports = function Omni (opts) {
  var blob
  var dx = {}
  dx.desc = 'login'

  var s = through.obj(function Interface (d, enc, next) {
    if (d.code === 1) {
      next()
      login.draw({err:true,msg:d.message})
      document.body.querySelector('#login').focus()
      return null
    } else if (!d.key) { next(); return null }

    var tkn = (d.key.split(':').length>1)
      ? d.key.split(':')[1]
      : d.key

    if (tkn && tkn === opts.id) {
      if (d.key.split(':')[0] === '@edit') {
        sessionStorage['edit'] = d.value
        login.erase()
        omni.draw(dx, initUI)
      } else {
        if (d.value === '-edit') omni.erase() // but it should also be unpiped

        // var val = d.value[0]
        // if (!val) { next(); return false }
        // dx.pkg = val
        // ui.readout(val.name)
        // pj.view.draw()

      }
    }
    next()
  })

 // UI

  var ui =  {}

  function initUI () {
    pj.setup(document.querySelector('#cvs'))

    ui.results = new pj.Group({ point:[0,0] })

    ui.label = new pj.PointText({
      point : [0,0],
      fontFamily : 'Monaco',
      fillColor : 'black',
      content : name,
      fontSize : 10
    })

    ui.makeBox = function (name,pos) {
      var label = new pj.PointText({
        point : [0,0],
        fontFamily : 'Monaco',
        fillColor : 'black',
        content : name,
        fontSize : 10
      })

      label.position.x = (label.bounds.width/2) + 4
      label.position.y = (label.bounds.height/2) + 4

      var frame = new pj.Shape.Rectangle({
        strokeWidth : 1,
        strokeColor : 'black',
        point : [0,0],
        size : [label.bounds.width+8, label.bounds.height+8]
      })

      var nb = new pj.Group({
        children : [frame,label]
      })
      nb.position.x = label.position.x + 2

      var y = (ui.results.children.length+1)*(frame.bounds.height+4)
      y += (label.position.y+1)

      nb.position.y = y

      return nb
    }

    ui.readout = function (str) {
      ui.label.content = str
      ui.label.position.y = (ui.label.bounds.height/2) + 4
      ui.label.position.x = ui.label.bounds.width/2
    }
  }

  // TEMPLATES

  var login = new D({
    template : LOGIN,
    parent : document.body,
    events : [['.login','submit',function (e) {
      e.preventDefault()
      s.push('+@edit '+e.target[0].value+'/'+opts.id)
      e.target[0].value = ''
    }]]
  })

  var omni = new D({
    id : opts.id,
    template : OMNI,
    parent : document.body,
    events : [
      [window,'contextmenu',grifter],
      ['.oz','keyup',keyInput]
    ]
  })

  var editor = new D({
    template : GRIFTER,
    parent : document.body,
    events : [
      ['.grifter','keyup',edit],
      ['.grifter','drop',upload],
      ['.grifter','dragenter',cancel],
      ['.grifter','dragleave',cancel],
      ['.grifter','dragover',cancel]
    ]
  })

  // EVENTS

  function keyInput (e) {
    var val = e.target.value.replace(' ','')

    if (e.keyCode === 8 || e.key === 'Backspace' && val === '')
      pj.view.draw()

    else if (e.keyCode === 13 || e.key === 'Enter') {
      e.preventDefault()
      // var b = ui.makeBox(dx.pkg.name,[0,10])
      // ui.results.addChild(b)
      // pj.view.draw()
      // e.target.value = ''
      s.push(val+'/'+opts.id)
    }
  }

  // MAKE PANELS DRAGGABLE

  var drag
  function ungrip (e) { window.removeEventListener('mousemove',drag) }
  function grip(e) {
    e.preventDefault()

    ungrip(e)

    var p = e.target.parentElement
    var offX = e.clientX - p.pageX
    var offY = e.clientY - p.pageY

    drag = function (e) {
      dx.x = e.clientX - offX
      dx.y = e.clientY - offY
      omni.draw(dx)
    }

    window.addEventListener('mousemove', drag, false)
  }

  // CONTEXT / EDIT

  function grifter (e) {
    e.preventDefault()
    blob = drompii(e)
    editor.erase()

    var dx = {
      x : e.pageX-10,
      y: e.pageY-10,
      body: _.values(blob.edit)[0].replace(/[\n\r]/g,'')
    }

    if (dx.body.length>140) { dx.w = 400; dx.h = 300 }

    switch (blob.type) {
      case 'SPAN' : editor.draw(dx);break;
      case 'IMG' : editor.draw(dx);break;
    }
  }

  function edit (e) {
    if (e.keyCode === 13) {
      e.preventDefault()
      var body = e.target.value.replace(/[\n\r]/g,'')
      blob.data[_.keys(blob.edit)[0]] = body
      s.push({key:'+$'+blob.id,value:blob.data})
      editor.erase()
      return false
    }
  }

  function upload (e) {
    cancel(e)
    var files = e.dataTransfer.files

    for (file in files) {
      if (file === 'length') return
      if (files[file] && files[file].type)
        var fileName =files[file].name.replace(/[^a-z0-9]/gi,'_').toLowerCase()

      var filepath
      var ndata = {}
      var formData = new FormData()
      formData.append('file', fileName)
      formData.append('token', 'test123')

      var xhr = new XMLHttpRequest()
      xhr.addEventListener('error', function (e) { console.error(e) }, false)
      xhr.addEventListener('load', function (e) {
        s.push({key:'+$'+ndata.id,value:ndata.data})
      }, false)
      xhr.addEventListener('progress', function (e) {
        editor.data.body = 'loaded : ' + (e.loaded/e.total) * 100 + '% '
        editor.draw()
        if (e.loaded === e.total) editor.erase()
        else if (e.total === 0) editor.erase()
      }, false)
      xhr.open('post', '/upload', true)

      var reader = new FileReader()
      reader.readAsDataURL(files[file])
      reader.addEventListener('load', function (data) {
        filePath = '/files/'+fileName
        formData.append('blob', data.target.result)
        editor.erase()
        if (data.target.result.split('/')[0]==='data:image') {
          var img = new Image()
          img.src = data.target.result
          img.addEventListener('load',function (e) {
            blob.edit.w = e.target.width
            blob.edit.h = e.target.height
            blob.edit.src = '/files/'+fileName
            _.each(blob.edit, function (v,k,l) {
              if (blob.data[k]) blob.data[k] = v
            })
            _.each(blob, function (v,k,l) { ndata[k] = v })
          },false)
        }
        xhr.send(formData)
      }, false)
    }
  }

  if (sessionStorage['edit'])
    s.push('+@edit '+sessionStorage['edit']+'/'+opts.id)

  if (!sessionStorage['edit']) {
    login.draw({err:false})
    document.body.querySelector('#login').focus()
  }

  return s
}

function cancel (e) {
  e.preventDefault()
  if (e.stopPropogation) e.stopPropogation()
}
<|endoftext|>


<commit_before>var OSNPAddressTable = require('./osnp_address_table');
var OSNPCommandQueue = require('./osnp_command_queue');

var FrameType = {
  BEACON: 0x00,
  DATA: 0x01,
  ACK: 0x02,
  MAC_CMD: 0x03
};

var FrameVersion = {
  V2003: 0x00,
  V2006: 0x01
}

var AddressingMode = {
  NOT_PRESENT: 0x00,
  SHORT_ADDRESS: 0x02,
  EUI: 0x03
};

var MACCommand = {
  ASSOCIATION_REQUEST: 0x01,
  ASSOCIATION_RESPONSE: 0x02,
  DISASSOCIATED: 0x03,
  DATA_REQUEST: 0x04,
  DISCOVER: 0x07
}

var SecurityLevel = {
  NONE: 0x00,
  MIC_32: 0x01,
  MIC_64: 0x02,
  MIC_128: 0x03,
  ENC: 0x04,
  ENC_MIC_32: 0x05,
  ENC_MIC_64: 0x06,
  ENC_MIC_128: 0x07
}

var KeyIdentifierMode = {
  IMPLICIT: 0x00,
  KEY_IDX_ONLY: 0x01,
  KEY_SOURCE_4: 0x02,
  KEY_SOURCE_8: 0x03
}

exports.OSNPAddressTable = OSNPAddressTable;
exports.OSNPCommandQueue = OSNPCommandQueue;

exports.FrameType = FrameType;
exports.FrameVersion = FrameVersion;
exports.AddressingMode = AddressingMode;
exports.MACCommand = MACCommand;
exports.SecurityLevel = SecurityLevel;
exports.KeyIdentifierMode = KeyIdentifierMode;

function OSNPFrame() {
  this.frameControlLow = null;
  this.frameControlHigh = null;
  this.destinationPAN = null;
  this.destinationAddress = null;
  this.sourcePAN = null;
  this.sourceAddress = null;
  this.securityControl = null;
  this.frameCounter = null;
  this.keySource = null;
  this.keyIndex = null;
  this.payload = null;
}

OSNPFrame.prototype.getFrameType = function() {
  return this.frameControlLow & 0x07;
}

OSNPFrame.prototype.getDestinationAddressingMode = function() {
  return (this.frameControlHigh >>> 2) & 0x03;
}

OSNPFrame.prototype.getSourceAddressingMode = function() {
  return (this.frameControlHigh >>> 6) & 0x03;
}

OSNPFrame.prototype.getFrameVersion = function() {
  return (this.frameControlHigh >>> 4) & 0x03;
}

OSNPFrame.prototype.hasPANIDCompression = function() {
  return (this.frameControlLow & 0x40) == 0x40;
}

OSNPFrame.prototype.hasSecurityEnabled = function() {
  return (this.frameControlLow & 0x08) == 0x08;
}

OSNPFrame.prototype.hasSecurityHeader = function() {
  return this.hasSecurityEnabled() && ((this.frameControlHigh & 0x30) != 0x00);
}

OSNPFrame.prototype.hasFramePending = function() {
  return (this.frameControlLow & 0x10) == 0x10;
}

OSNPFrame.prototype.hasAckRequested = function() {
  return (this.frameControlLow & 0x20) == 0x20;
}

OSNPFrame.prototype.getKeyIdentifierMode = function() {
  return (this.securityControl >>> 3) & 0x03;
}

OSNPFrame.prototype.getEncodedLength = function() {
  var len = 3;
  if (this.destinationPAN != null) {
    len += this.destinationAddress.length + 2;
  }

  if (!this.hasPANIDCompression() && this.sourcePAN != null) {
    len += 2;
  }

  if (this.sourceAddress != null) {
    len += this.sourceAddress.length;
  }

  if (this.hasSecurityHeader()) {
    len += 5;
    if (this.keySource != null) {
      len += this.keySource.length + 1;
    } else if (this.getKeyIdentifierMode() == KeyIdentifierMode.KEY_IDX_ONLY) {
      len++;
    }
  }

  len += this.payload.length;

  return len;
}

OSNPFrame.prototype.encode = function(buf) {
  if (buf == undefined) {
    buf = new Buffer(this.getEncodedLength());
  }
  var index = 0;
  buf.writeUInt8(this.frameControlLow, index++);
  buf.writeUInt8(this.frameControlHigh, index++);
  buf.writeUInt8(this.sequenceNumber, index++);

  if (this.destinationPAN != null) {
    this.destinationPAN.copy(buf, index);
    index += 2;
    this.destinationAddress.copy(buf, index);
    index += this.destinationAddress.length;
  }

  if (!this.hasPANIDCompression() && this.sourcePAN != null) {
    this.sourcePAN.copy(buf, index);
    index += 2;
  }

  if (this.sourceAddress != null) {
    this.sourceAddress.copy(buf, index);
    index += this.sourceAddress.length;
  }

  if (this.hasSecurityHeader()) {
    buf.writeUInt8(this.securityControl, index++);
    buf.writeUInt32LE(this.frameCounter, index);
    index += 4;

    if (this.keySource != null) {
      this.keySource.copy(buf, index);
      index += this.keySource.length;
      buf.writeUInt8(this.keyIndex, index++);
    } else if (this.getKeyIdentifierMode() == KeyIdentifierMode.KEY_IDX_ONLY) {
      buf.writeUInt8(this.keyIndex, index++);
    }
  }

  this.payload.copy(buf, index);

  return buf;
}

var panID;
var shortAddress;
var eui;

var sequenceNumber = 0;

exports.setPANID = function(aPANID) {
  panID = aPANID;
}

exports.getPANID = function() {
  return panID;
}

exports.setShortAddress = function(aShortAddress) {
  shortAddress = aShortAddress;
}

exports.getShortAddress = function() {
  return shortAddress;
}

exports.setEUI = function(aEUI) {
  eui = aEUI;
}

exports.getEUI = function() {
  return eui;
}

exports.createPairingCommand = function(eui, shortAddress) {
  var frameControlLow = exports.makeFrameControlLow(FrameType.MAC_CMD, false, false, true, false);
  var frameControlHigh = exports.makeFrameControlHigh(AddressingMode.EUI, FrameVersion.V2003, AddressingMode.SHORT_ADDRESS);

  var frame = exports.createFrame(frameControlLow, frameControlHigh);
  frame.destinationPAN = new Buffer([0x00, 0x00]);
  frame.destinationAddress = eui;

  frame.payload = new Buffer([MACCommand.ASSOCIATION_REQUEST, shortAddress[0], shortAddress[1]]);
  return frame;
}

exports.createUnpairingCommand = function(shortAddress) {
  var frameControlLow = exports.makeFrameControlLow(FrameType.MAC_CMD, false, false, true, false);
  var frameControlHigh = exports.makeFrameControlHigh(AddressingMode.SHORT_ADDRESS, FrameVersion.V2003, AddressingMode.NOT_PRESENT);

  var frame = exports.createFrame(frameControlLow, frameControlHigh);
  frame.destinationPAN = exports.getPANID();
  frame.destinationAddress = shortAddress;
  frame.payload = new Buffer([MACCommand.DISASSOCIATED]);

  return frame;
}

exports.createDiscoveryRequest = function() {
  var frameControlLow = exports.makeFrameControlLow(FrameType.MAC_CMD, false, false, false, false);
  var frameControlHigh = exports.makeFrameControlHigh(AddressingMode.SHORT_ADDRESS, FrameVersion.V2003, AddressingMode.SHORT_ADDRESS);

  var frame = exports.createFrame(frameControlLow, frameControlHigh);
  frame.destinationPAN = new Buffer([0x00, 0x00]);
  frame.destinationAddress = new Buffer([0xff, 0xff]);
  frame.payload = new Buffer([MACCommand.DISCOVER]);

  return frame;
}

exports.createCommandPacket = function(data, eui, shortAddress, paired) {
  var frameControlLow = exports.makeFrameControlLow(FrameType.DATA, false, false, true, false);
  var frameControlHigh;

  if (paired) {
    frameControlHigh = exports.makeFrameControlHigh(AddressingMode.SHORT_ADDRESS, FrameVersion.V2003, AddressingMode.NOT_PRESENT);
  } else {
    frameControlHigh = exports.makeFrameControlHigh(AddressingMode.EUI, FrameVersion.V2003, AddressingMode.SHORT_ADDRESS);
  }

  var frame = exports.createFrame(frameControlLow, frameControlHigh);

  if (paired) {
    frame.destinationPAN = exports.getPANID();
    frame.destinationAddress = shortAddress;
  } else {
    frame.destinationPAN = new Buffer([0x00, 0x00]);
    frame.destinationAddress = eui;
  }

  frame.payload = data;

  return frame;
}

exports.parseFrame = function(frame) {
  var osnpFrame = new OSNPFrame();
  var index = 0;
  osnpFrame.frameControlLow = frame.readUInt8(index++);
  osnpFrame.frameControlHigh = frame.readUInt8(index++);
  osnpFrame.sequenceNumber = frame.readUInt8(index++);

  switch (osnpFrame.getDestinationAddressingMode()) {
  case AddressingMode.SHORT_ADDRESS:
    osnpFrame.destinationPAN = frame.slice(index, index + 2);
    index += 2;
    osnpFrame.destinationAddress = frame.slice(index, index + 2);
    index += 2;
    break;
  case AddressingMode.EUI:
    osnpFrame.destinationPAN = frame.slice(index, index + 2);
    index += 2;
    osnpFrame.destinationAddress = frame.slice(index, index + 8);
    index += 8;
    break;
  }

  if (osnpFrame.getSourceAddressingMode() != AddressingMode.NOT_PRESENT) {
    if(osnpFrame.hasPANIDCompression()) {
      osnpFrame.sourcePAN = osnpFrame.destinationPAN;
    } else {
      osnpFrame.sourcePAN = frame.slice(index, index + 2);
      index += 2;
    }
  }

  switch (osnpFrame.getSourceAddressingMode()) {
  case AddressingMode.SHORT_ADDRESS:
    osnpFrame.sourceAddress = frame.slice(index, index + 2);
    index += 2;
    break;
  case AddressingMode.EUI:
    osnpFrame.sourceAddress = frame.slice(index, index + 8);
    index += 8;
    break;
  }
  if (osnpFrame.hasSecurityHeader()) {
    osnpFrame.securityControl = frame.readUInt8(index++);
    osnpFrame.frameCounter = frame.readUInt32LE(index);
    index += 4;

    switch (osnpFrame.getKeyIdentifierMode()) {
    case KeyIdentifierMode.KEY_IDX_ONLY:
      osnpFrame.keyIndex = frame.readUInt8(index++);
      break;
    case KeyIdentifierMode.KEY_SOURCE_4:
      osnpFrame.keySource = frame.slice(index, index + 4);
      index += 4;
      osnpFrame.keyIndex = frame.readUInt8(index++);
      break;
    case KeyIdentifierMode.KEY_SOURCE_8:
      osnpFrame.keySource = frame.slice(index, index + 8);
      index += 8;
      osnpFrame.keyIndex = frame.readUInt8(index++);
      break;
    }
  }

  osnpFrame.payload = frame.slice(index, frame.length - 2);

  return osnpFrame;
}

exports.createFrame = function(frameControlLow, frameControlHigh) {
  var frame = new OSNPFrame();

  frame.frameControlLow = frameControlLow;
  frame.frameControlHigh = frameControlHigh;

  frame.sequenceNumber = sequenceNumber++;

  if (sequenceNumber >= 255) {
    sequenceNumber = 0;
  }

  if (frame.hasPANIDCompression() && (frame.getDestinationAddressingMode() != AddressingMode.NOT_PRESENT)) {
    frame.destinationPAN = panID;
  }

  switch (frame.getSourceAddressingMode()) {
  case AddressingMode.SHORT_ADDRESS:
    frame.sourcePAN = panID;
    frame.sourceAddress = shortAddress;
    break;
  case AddressingMode.EUI:
    frame.sourcePAN = panID;
    frame.sourceAddress = eui;
    break;
  }

  frame.payload = new Buffer(0);

  return frame;
}

exports.createResponse = function(originalFrame) {
  var frameControlLow = (originalFrame.frameControlLow & 0xEF) | 0x20;
  var frameControlHigh = (originalFrame.getSourceAddressingMode() << 2) | (originalFrame.getDestinationAddressingMode() << 6) | (originalFrame.frameControlHigher & 0x30);
  var frame = exports.createFrame(frameControlLow,  frameControlHigh);

  frame.destinationPAN = originalFrame.sourcePAN;
  frame.destinationAddress = originalFrame.sourceAddress;
  frame.securityControl = originalFrame.securityControl;
  frame.frameCounter = originalFrame.frameCounter;
  frame.keySource = originalFrame.keySource;
  frame.keyIndex = originalFrame.keyIndex;

  return frame;
}

exports.makeFrameControlLow = function(frameType, securityEnabled, framePending, ackRequest, panIDCompression) {
  return frameType | (securityEnabled ? 0x08 : 0x00) | (framePending ? 0x10 : 0x00) | (ackRequest ? 0x20 : 0x00) | (panIDCompression ? 0x40 : 0x00);
}

exports.makeFrameControlHigh = function(destinationAddressingMode, frameVersion, sourceAddressingMode) {
  return (destinationAddressingMode << 2) | (frameVersion << 4) | (sourceAddressingMode << 6);
}
<commit_msg>added rx mode<commit_after>var OSNPAddressTable = require('./osnp_address_table');
var OSNPCommandQueue = require('./osnp_command_queue');

var FrameType = {
  BEACON: 0x00,
  DATA: 0x01,
  ACK: 0x02,
  MAC_CMD: 0x03
};

var FrameVersion = {
  V2003: 0x00,
  V2006: 0x01
}

var AddressingMode = {
  NOT_PRESENT: 0x00,
  SHORT_ADDRESS: 0x02,
  EUI: 0x03
};

var MACCommand = {
  ASSOCIATION_REQUEST: 0x01,
  ASSOCIATION_RESPONSE: 0x02,
  DISASSOCIATED: 0x03,
  DATA_REQUEST: 0x04,
  DISCOVER: 0x07
}

var SecurityLevel = {
  NONE: 0x00,
  MIC_32: 0x01,
  MIC_64: 0x02,
  MIC_128: 0x03,
  ENC: 0x04,
  ENC_MIC_32: 0x05,
  ENC_MIC_64: 0x06,
  ENC_MIC_128: 0x07
}

var KeyIdentifierMode = {
  IMPLICIT: 0x00,
  KEY_IDX_ONLY: 0x01,
  KEY_SOURCE_4: 0x02,
  KEY_SOURCE_8: 0x03
}

var RXMode = {
  POLL_DRIVEN: 0x00,
  ALWAYS_ON: 0x01
};

exports.OSNPAddressTable = OSNPAddressTable;
exports.OSNPCommandQueue = OSNPCommandQueue;

exports.FrameType = FrameType;
exports.FrameVersion = FrameVersion;
exports.AddressingMode = AddressingMode;
exports.MACCommand = MACCommand;
exports.SecurityLevel = SecurityLevel;
exports.KeyIdentifierMode = KeyIdentifierMode;
exports.RXMode = RXMode;

function OSNPFrame() {
  this.frameControlLow = null;
  this.frameControlHigh = null;
  this.destinationPAN = null;
  this.destinationAddress = null;
  this.sourcePAN = null;
  this.sourceAddress = null;
  this.securityControl = null;
  this.frameCounter = null;
  this.keySource = null;
  this.keyIndex = null;
  this.payload = null;
}

OSNPFrame.prototype.getFrameType = function() {
  return this.frameControlLow & 0x07;
}

OSNPFrame.prototype.getDestinationAddressingMode = function() {
  return (this.frameControlHigh >>> 2) & 0x03;
}

OSNPFrame.prototype.getSourceAddressingMode = function() {
  return (this.frameControlHigh >>> 6) & 0x03;
}

OSNPFrame.prototype.getFrameVersion = function() {
  return (this.frameControlHigh >>> 4) & 0x03;
}

OSNPFrame.prototype.hasPANIDCompression = function() {
  return (this.frameControlLow & 0x40) == 0x40;
}

OSNPFrame.prototype.hasSecurityEnabled = function() {
  return (this.frameControlLow & 0x08) == 0x08;
}

OSNPFrame.prototype.hasSecurityHeader = function() {
  return this.hasSecurityEnabled() && ((this.frameControlHigh & 0x30) != 0x00);
}

OSNPFrame.prototype.hasFramePending = function() {
  return (this.frameControlLow & 0x10) == 0x10;
}

OSNPFrame.prototype.hasAckRequested = function() {
  return (this.frameControlLow & 0x20) == 0x20;
}

OSNPFrame.prototype.getKeyIdentifierMode = function() {
  return (this.securityControl >>> 3) & 0x03;
}

OSNPFrame.prototype.getEncodedLength = function() {
  var len = 3;
  if (this.destinationPAN != null) {
    len += this.destinationAddress.length + 2;
  }

  if (!this.hasPANIDCompression() && this.sourcePAN != null) {
    len += 2;
  }

  if (this.sourceAddress != null) {
    len += this.sourceAddress.length;
  }

  if (this.hasSecurityHeader()) {
    len += 5;
    if (this.keySource != null) {
      len += this.keySource.length + 1;
    } else if (this.getKeyIdentifierMode() == KeyIdentifierMode.KEY_IDX_ONLY) {
      len++;
    }
  }

  len += this.payload.length;

  return len;
}

OSNPFrame.prototype.encode = function(buf) {
  if (buf == undefined) {
    buf = new Buffer(this.getEncodedLength());
  }
  var index = 0;
  buf.writeUInt8(this.frameControlLow, index++);
  buf.writeUInt8(this.frameControlHigh, index++);
  buf.writeUInt8(this.sequenceNumber, index++);

  if (this.destinationPAN != null) {
    this.destinationPAN.copy(buf, index);
    index += 2;
    this.destinationAddress.copy(buf, index);
    index += this.destinationAddress.length;
  }

  if (!this.hasPANIDCompression() && this.sourcePAN != null) {
    this.sourcePAN.copy(buf, index);
    index += 2;
  }

  if (this.sourceAddress != null) {
    this.sourceAddress.copy(buf, index);
    index += this.sourceAddress.length;
  }

  if (this.hasSecurityHeader()) {
    buf.writeUInt8(this.securityControl, index++);
    buf.writeUInt32LE(this.frameCounter, index);
    index += 4;

    if (this.keySource != null) {
      this.keySource.copy(buf, index);
      index += this.keySource.length;
      buf.writeUInt8(this.keyIndex, index++);
    } else if (this.getKeyIdentifierMode() == KeyIdentifierMode.KEY_IDX_ONLY) {
      buf.writeUInt8(this.keyIndex, index++);
    }
  }

  this.payload.copy(buf, index);

  return buf;
}

var panID;
var shortAddress;
var eui;

var sequenceNumber = 0;

exports.setPANID = function(aPANID) {
  panID = aPANID;
}

exports.getPANID = function() {
  return panID;
}

exports.setShortAddress = function(aShortAddress) {
  shortAddress = aShortAddress;
}

exports.getShortAddress = function() {
  return shortAddress;
}

exports.setEUI = function(aEUI) {
  eui = aEUI;
}

exports.getEUI = function() {
  return eui;
}

exports.createPairingCommand = function(eui, shortAddress) {
  var frameControlLow = exports.makeFrameControlLow(FrameType.MAC_CMD, false, false, true, false);
  var frameControlHigh = exports.makeFrameControlHigh(AddressingMode.EUI, FrameVersion.V2003, AddressingMode.SHORT_ADDRESS);

  var frame = exports.createFrame(frameControlLow, frameControlHigh);
  frame.destinationPAN = new Buffer([0x00, 0x00]);
  frame.destinationAddress = eui;

  frame.payload = new Buffer([MACCommand.ASSOCIATION_REQUEST, shortAddress[0], shortAddress[1]]);
  return frame;
}

exports.createUnpairingCommand = function(shortAddress) {
  var frameControlLow = exports.makeFrameControlLow(FrameType.MAC_CMD, false, false, true, false);
  var frameControlHigh = exports.makeFrameControlHigh(AddressingMode.SHORT_ADDRESS, FrameVersion.V2003, AddressingMode.NOT_PRESENT);

  var frame = exports.createFrame(frameControlLow, frameControlHigh);
  frame.destinationPAN = exports.getPANID();
  frame.destinationAddress = shortAddress;
  frame.payload = new Buffer([MACCommand.DISASSOCIATED]);

  return frame;
}

exports.createDiscoveryRequest = function() {
  var frameControlLow = exports.makeFrameControlLow(FrameType.MAC_CMD, false, false, false, false);
  var frameControlHigh = exports.makeFrameControlHigh(AddressingMode.SHORT_ADDRESS, FrameVersion.V2003, AddressingMode.SHORT_ADDRESS);

  var frame = exports.createFrame(frameControlLow, frameControlHigh);
  frame.destinationPAN = new Buffer([0x00, 0x00]);
  frame.destinationAddress = new Buffer([0xff, 0xff]);
  frame.payload = new Buffer([MACCommand.DISCOVER]);

  return frame;
}

exports.createCommandPacket = function(data, eui, shortAddress, paired) {
  var frameControlLow = exports.makeFrameControlLow(FrameType.DATA, false, false, true, false);
  var frameControlHigh;

  if (paired) {
    frameControlHigh = exports.makeFrameControlHigh(AddressingMode.SHORT_ADDRESS, FrameVersion.V2003, AddressingMode.NOT_PRESENT);
  } else {
    frameControlHigh = exports.makeFrameControlHigh(AddressingMode.EUI, FrameVersion.V2003, AddressingMode.SHORT_ADDRESS);
  }

  var frame = exports.createFrame(frameControlLow, frameControlHigh);

  if (paired) {
    frame.destinationPAN = exports.getPANID();
    frame.destinationAddress = shortAddress;
  } else {
    frame.destinationPAN = new Buffer([0x00, 0x00]);
    frame.destinationAddress = eui;
  }

  frame.payload = data;

  return frame;
}

exports.parseFrame = function(frame) {
  var osnpFrame = new OSNPFrame();
  var index = 0;
  osnpFrame.frameControlLow = frame.readUInt8(index++);
  osnpFrame.frameControlHigh = frame.readUInt8(index++);
  osnpFrame.sequenceNumber = frame.readUInt8(index++);

  switch (osnpFrame.getDestinationAddressingMode()) {
  case AddressingMode.SHORT_ADDRESS:
    osnpFrame.destinationPAN = frame.slice(index, index + 2);
    index += 2;
    osnpFrame.destinationAddress = frame.slice(index, index + 2);
    index += 2;
    break;
  case AddressingMode.EUI:
    osnpFrame.destinationPAN = frame.slice(index, index + 2);
    index += 2;
    osnpFrame.destinationAddress = frame.slice(index, index + 8);
    index += 8;
    break;
  }

  if (osnpFrame.getSourceAddressingMode() != AddressingMode.NOT_PRESENT) {
    if(osnpFrame.hasPANIDCompression()) {
      osnpFrame.sourcePAN = osnpFrame.destinationPAN;
    } else {
      osnpFrame.sourcePAN = frame.slice(index, index + 2);
      index += 2;
    }
  }

  switch (osnpFrame.getSourceAddressingMode()) {
  case AddressingMode.SHORT_ADDRESS:
    osnpFrame.sourceAddress = frame.slice(index, index + 2);
    index += 2;
    break;
  case AddressingMode.EUI:
    osnpFrame.sourceAddress = frame.slice(index, index + 8);
    index += 8;
    break;
  }
  if (osnpFrame.hasSecurityHeader()) {
    osnpFrame.securityControl = frame.readUInt8(index++);
    osnpFrame.frameCounter = frame.readUInt32LE(index);
    index += 4;

    switch (osnpFrame.getKeyIdentifierMode()) {
    case KeyIdentifierMode.KEY_IDX_ONLY:
      osnpFrame.keyIndex = frame.readUInt8(index++);
      break;
    case KeyIdentifierMode.KEY_SOURCE_4:
      osnpFrame.keySource = frame.slice(index, index + 4);
      index += 4;
      osnpFrame.keyIndex = frame.readUInt8(index++);
      break;
    case KeyIdentifierMode.KEY_SOURCE_8:
      osnpFrame.keySource = frame.slice(index, index + 8);
      index += 8;
      osnpFrame.keyIndex = frame.readUInt8(index++);
      break;
    }
  }

  osnpFrame.payload = frame.slice(index, frame.length - 2);

  return osnpFrame;
}

exports.createFrame = function(frameControlLow, frameControlHigh) {
  var frame = new OSNPFrame();

  frame.frameControlLow = frameControlLow;
  frame.frameControlHigh = frameControlHigh;

  frame.sequenceNumber = sequenceNumber++;

  if (sequenceNumber >= 255) {
    sequenceNumber = 0;
  }

  if (frame.hasPANIDCompression() && (frame.getDestinationAddressingMode() != AddressingMode.NOT_PRESENT)) {
    frame.destinationPAN = panID;
  }

  switch (frame.getSourceAddressingMode()) {
  case AddressingMode.SHORT_ADDRESS:
    frame.sourcePAN = panID;
    frame.sourceAddress = shortAddress;
    break;
  case AddressingMode.EUI:
    frame.sourcePAN = panID;
    frame.sourceAddress = eui;
    break;
  }

  frame.payload = new Buffer(0);

  return frame;
}

exports.createResponse = function(originalFrame) {
  var frameControlLow = (originalFrame.frameControlLow & 0xEF) | 0x20;
  var frameControlHigh = (originalFrame.getSourceAddressingMode() << 2) | (originalFrame.getDestinationAddressingMode() << 6) | (originalFrame.frameControlHigher & 0x30);
  var frame = exports.createFrame(frameControlLow,  frameControlHigh);

  frame.destinationPAN = originalFrame.sourcePAN;
  frame.destinationAddress = originalFrame.sourceAddress;
  frame.securityControl = originalFrame.securityControl;
  frame.frameCounter = originalFrame.frameCounter;
  frame.keySource = originalFrame.keySource;
  frame.keyIndex = originalFrame.keyIndex;

  return frame;
}

exports.makeFrameControlLow = function(frameType, securityEnabled, framePending, ackRequest, panIDCompression) {
  return frameType | (securityEnabled ? 0x08 : 0x00) | (framePending ? 0x10 : 0x00) | (ackRequest ? 0x20 : 0x00) | (panIDCompression ? 0x40 : 0x00);
}

exports.makeFrameControlHigh = function(destinationAddressingMode, frameVersion, sourceAddressingMode) {
  return (destinationAddressingMode << 2) | (frameVersion << 4) | (sourceAddressingMode << 6);
}
<|endoftext|>


<commit_before>// takes node and edge data and out node and edge svgs
//
var React = require('react')
var Url = require('url')
var r = require('r-dom')
var map = require('lodash.map')
var debug = require('debug')('holodex:tag-group')
var keys = require('lodash.keys')
var reduce = require('lodash.reduce')

var Tag = require('./tag')
var TagSelect = require('./tag-select')
var config = require('config')

var prefix = Url.format(config.api)

module.exports = React.createClass({

  propTypes: {
    agents: React.PropTypes.array,
    tagData: React.PropTypes.object.isRequired,
    updateTag: React.PropTypes.func.isRequired,
    model: React.PropTypes.object,
    cancelIcon: React.PropTypes.node
  },

  render: function () {
    var tagData = this.props.tagData
    var cancelIcon = this.props.cancelIcon
    debug('tagData', tagData)
    var withPred = tagData.triple.predicate.active
    var pluralSubj = tagData.triple.subject.isPlural

    return r.div({ className: 'tags' }, [
      r.div({ className: 'tags-triples-container'},
        reduce(tagData.triple, function (memo, expression, key) {
            if (expression.active) {
              var label
              var index = Math.min(memo.length, expression.index) //TODO order logic
              if (key === 'subject') {
                label = withPred ? expression.withPredLabel : expression.label
              }
              if (key === 'predicate') {
                label = pluralSubj ? expression.pluralLabel : expression.label
              }
              if (key === 'object') {
                label = expression.label
              }

              debug('label', label)
              memo[index] = r(Tag, {
                color: expression.color,
                icon: cancelIcon,
                label: label,
                onIconClick: this.props.updateTag('triple', expression.id, false),
                trailingCancel: (key === 'object')
              })
            }
            return memo
          }.bind(this), [])
      ),
      r.div({ className: 'tags-filters'},
        tagData.filters.reduce(function (memo, filter, i) {
          if (filter.active) {
            memo.push(r(Tag, {
              color: filter.color,
              icon: cancelIcon,
              label: filter.label,
              onIconClick: this.props.updateTag('filters', filter.id, false),
              trailingCancel: true
            }))
          }
          return memo
        }.bind(this), [])
      ),
      r.div({ className: 'input' }, [
        r(TagSelect, {
          style: this.props.style,
          tagData: this.props.tagData,
          updateTag: this.props.updateTag
        })
      ])
    ])
  },
})
<commit_msg>styling of tag elements<commit_after>// takes node and edge data and out node and edge svgs
//
var React = require('react')
var Url = require('url')
var r = require('r-dom')
var map = require('lodash.map')
var debug = require('debug')('holodex:tag-group')
var keys = require('lodash.keys')
var reduce = require('lodash.reduce')

var Tag = require('./tag')
var TagSelect = require('./tag-select')
var config = require('config')

var vars = require('ui/vars')

var prefix = Url.format(config.api)

var style = {
  index: {
    marginTop: vars.gutterWidth,
    marginLeft: vars.gutterWidth,
    display: 'flex',
    flexDirection: 'column'
  },
  triple: {
    order: 0,
    display: 'flex',
    flexDirection: 'row'
  },
  tripleTag: {
  },
  filters: {
    marginLeft: vars.gutterWidth/2,
    order: 1,
    display: 'flex',
    flexDirection: 'column'
  },
  filterTag: {
    marginTop: vars.gutterWidth/3
  },
  tagInput: {
    order: 2,
    marginTop: vars.gutterWidth/3,
    marginLeft: vars.gutterWidth/2,
    display: 'block',
    border: 'none',
    color: '#333',
    borderBottom: '1px dotted black',
    padding: '5px 2px 0 2px',
  }
}

module.exports = React.createClass({

  propTypes: {
    style: React.PropTypes.object,
    tagData: React.PropTypes.object.isRequired,
    updateTag: React.PropTypes.func.isRequired,
    model: React.PropTypes.object,
    cancelIcon: React.PropTypes.node
  },

  render: function () {
    var tagData = this.props.tagData
    var cancelIcon = this.props.cancelIcon
    debug('tagData', tagData)
    var withPred = tagData.triple.predicate.active
    var pluralSubj = tagData.triple.subject.isPlural
    this.style = style

    var filters = tagData.filters.reduce(function (memo, filter, i) {
      if (filter.active) {
        memo.push(r(Tag, {
          color: filter.color,
          icon: cancelIcon,
          label: filter.label,
          onIconClick: this.props.updateTag('filters', filter.id, false),
          trailingCancel: true
        }))
      }
      return memo
    }.bind(this), [])

    return r.div({ className: 'tags', style: style.index }, [
      r.div({ className: 'triple', style: style.triple },
        reduce(tagData.triple, function (memo, expression, key) {
            if (expression.active) {
              var label
              var index = Math.min(memo.length, expression.index) //TODO order logic
              if (key === 'subject') {
                label = withPred ? expression.withPredLabel : expression.label
              }
              if (key === 'predicate') {
                label = pluralSubj ? expression.pluralLabel : expression.label
              }
              if (key === 'object') {
                label = expression.label
              }

              // var style = {
              //   order: index
              // }
              // var style = style.tripleTag
              // style.order = index

              memo[index] = r.div({ className: 'triple-tag', style: {order: index} }, [r(Tag, {
                color: expression.color,
                icon: cancelIcon,
                label: label,
                onIconClick: this.props.updateTag('triple', expression.id, false),
                trailingCancel: (key === 'object')
              })])

            }
            return memo
          }.bind(this), [])
      ),
      r.div({ className: 'tags-filters', style: style.filters },
        filters.map(function (filter, i) {
          var order = filters.length -1 - i
          var style = {order: order }
          return r.div({ className: 'filter-tag', style: this.style.filterTag }, [
            filter
          ])
        }.bind(this))
      ),
      r.div({ className: 'tag-input', style: this.style.tagInput }, [
        r(TagSelect, {
          style: this.props.style,
          tagData: this.props.tagData,
          updateTag: this.props.updateTag
        })
      ])
    ])
  },
})
<|endoftext|>


<commit_before>'use strict'

// A readable tar stream creator
// Technically, this is a transform stream that you write paths into,
// and tar format comes out of.
// The `add()` method is like `write()` but returns this,
// and end() return `this` as well, so you can
// do `new Pack(opt).add('files').add('dir').end().pipe(output)
// You could also do something like:
// streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar'))

class PackJob {
  constructor (path, absolute) {
    this.path = path || './'
    this.absolute = absolute
    this.stat = null
    this.readdir = null
    this.pending = false
    this.ignore = false
    this.piped = false
  }
}

const MiniPass = require('minipass')
const zlib = require('minizlib')
const WriteEntry = require('./write-entry.js')
const WriteEntrySync = WriteEntry.Sync
const Yallist = require('yallist')
const EOF = Buffer.alloc(1024)
const ONSTAT = Symbol('onStat')
const ENDED = Symbol('ended')
const QUEUE = Symbol('queue')
const CURRENT = Symbol('current')
const PROCESS = Symbol('process')
const PROCESSING = Symbol('processing')
const PROCESSJOB = Symbol('processJob')
const JOBS = Symbol('jobs')
const JOBDONE = Symbol('jobDone')
const ADDENTRY = Symbol('addEntry')
const STAT = Symbol('stat')
const READDIR = Symbol('readdir')
const ONREADDIR = Symbol('onreaddir')
const PIPE = Symbol('pipe')
const ENTRY = Symbol('entry')
const WRITEENTRYCLASS = Symbol('writeEntryClass')
const WRITE = Symbol('write')
const ONDRAIN = Symbol('ondrain')

const fs = require('fs')
const path = require('path')

class Pack extends MiniPass {
  constructor (opt) {
    super(opt)
    opt = opt || Object.create(null)
    this.opt = opt
    this.cwd = opt.cwd || process.cwd()
    this.maxReadSize = opt.maxReadSize
    this.preservePaths = !!opt.preservePaths
    this.strict = !!opt.strict
    this.prefix = (opt.prefix || '').replace(/(\\|\/)+$/, '')
    this.linkCache = opt.linkCache || new Map()
    this.statCache = opt.statCache || new Map()
    this.readdirCache = opt.readdirCache || new Map()
    this[WRITEENTRYCLASS] = WriteEntry
    if (typeof opt.onwarn === 'function')
      this.on('warn', opt.onwarn)

    this.zip = null
    if (opt.gzip) {
      if (typeof opt.gzip !== 'object')
        opt.gzip = {}
      this.zip = new zlib.Gzip(opt.gzip)
      this.zip.on('data', chunk => super.write(chunk))
      this.zip.on('end', _ => super.end())
      this.zip.on('drain', _ => this[ONDRAIN]())
    } else
      this.on('drain', this[ONDRAIN])

    this.portable = !!opt.portable

    this.filter = typeof opt.filter === 'function' ? opt.filter : _ => true
    this[QUEUE] = new Yallist
    this[JOBS] = 0
    this.jobs = +opt.jobs || 4
    this[PROCESSING] = false
    this[ENDED] = false
  }

  [WRITE] (chunk) {
    return super.write(chunk)
  }

  add (path) {
    this.write(path)
    return this
  }

  end (path) {
    if (path)
      this.write(path)
    this[ENDED] = true
    this[PROCESS]()
    return this
  }

  write (path) {
    if (this[ENDED])
      throw new Error('write after end')

    this[ADDENTRY](path)
    return this.flowing
  }

  [ADDENTRY] (p) {
    const absolute = path.resolve(this.cwd, p)
    if (this.prefix)
      p = this.prefix + '/' + p
    this[QUEUE].push(new PackJob(p, absolute))
    this[PROCESS]()
  }

  [STAT] (job) {
    job.pending = true
    this[JOBS] += 1
    fs.lstat(job.absolute, (er, stat) => {
      job.pending = false
      this[JOBS] -= 1
      if (er)
        return this.emit('error', er)
      this[ONSTAT](job, stat)
    })
  }

  [ONSTAT] (job, stat) {
    this.statCache.set(job.absolute, stat)
    job.stat = stat

    // now we have the stat, we can filter it.
    if (!this.filter(job.path, stat))
      job.ignore = true

    this[PROCESS]()
  }

  [READDIR] (job) {
    job.pending = true
    this[JOBS] += 1
    fs.readdir(job.absolute, (er, entries) => {
      job.pending = false
      this[JOBS] -= 1
      if (er)
        return this.emit('error', er)
      this[ONREADDIR](job, entries)
    })
  }

  [ONREADDIR] (job, entries) {
    this.readdirCache.set(job.absolute, entries)
    job.readdir = entries
    this[PROCESS]()
  }

  [PROCESS] () {
    if (this[PROCESSING])
      return

    this[PROCESSING] = true
    for (let w = this[QUEUE].head;
         w !== null && this[JOBS] < this.jobs;
         w = w.next) {
      this[PROCESSJOB](w.value)
    }
    this[PROCESSING] = false

    if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) {
      if (this.zip)
        this.zip.end(EOF)
      else {
        super.write(EOF)
        super.end()
      }
    }
  }

  get [CURRENT] () {
    return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value
  }

  [JOBDONE] (job) {
    this[QUEUE].shift()
    this[JOBS] -= 1
    this[PROCESS]()
  }

  [PROCESSJOB] (job) {
    if (job.pending)
      return

    if (!job.stat) {
      if (this.statCache.has(job.absolute))
        this[ONSTAT](job, this.statCache.get(job.absolute))
      else
        this[STAT](job)
    }
    if (!job.stat)
      return

    // filtered out!
    if (job.ignore) {
      if (job === this[CURRENT])
        this[QUEUE].shift()
      return
    }

    if (job.stat.isDirectory() && !job.readdir) {
      if (this.readdirCache.has(job.absolute))
        this[ONREADDIR](job, this.readdirCache.get(job.absolute))
      else
        this[READDIR](job)
      if (!job.readdir)
        return
    }

    if (!job.entry) {
      job.entry = this[ENTRY](job)
      if (!job.entry) {
        job.ignore = true
        return
      }
    }

    if (job === this[CURRENT] && !job.piped)
      this[PIPE](job)
  }

  warn (msg, data) {
    return this.emit('warn', msg, data)
  }

  [ENTRY] (job) {
    this[JOBS] += 1
    try {
      return new this[WRITEENTRYCLASS](job.path, {
        onwarn: (msg, data) => this.warn(msg, data),
        cwd: this.cwd,
        absolute: job.absolute,
        preservePaths: this.preservePaths,
        maxReadSize: this.maxReadSize,
        strict: this.strict,
        portable: this.portable,
        linkCache: this.linkCache,
        statCache: this.statCache
      }).on('end', _ => this[JOBDONE](job))
    } catch (er) {
      this.emit('error', er)
    }
  }

  [ONDRAIN] () {
    if (this[CURRENT] && this[CURRENT].entry)
      this[CURRENT].entry.resume()
  }

  // like .pipe() but using super, because our write() is special
  [PIPE] (job) {
    job.piped = true

    if (job.readdir)
      job.readdir.forEach(entry => this[ADDENTRY](job.path + '/' + entry))

    const source = job.entry
    const zip = this.zip

    if (zip)
      source.on('data', chunk => zip.write(chunk) || source.pause())
    else
      source.on('data', chunk => super.write(chunk) || source.pause())
  }

  resume () {
    if (this.zip)
      this.zip.resume()
    return super.resume()
  }

  pause () {
    if (this.zip)
      this.zip.pause()
    return super.pause()
  }
}

class PackSync extends Pack {
  constructor (opt) {
    super(opt)
    this[WRITEENTRYCLASS] = WriteEntrySync
  }

  // pause/resume are no-ops in sync streams.
  pause () {}
  resume () {}

  [STAT] (job) {
    this[ONSTAT](job, fs.lstatSync(job.absolute))
  }

  [READDIR] (job, stat) {
    this[ONREADDIR](job, fs.readdirSync(job.absolute))
  }

  // gotta get it all in this tick
  [PIPE] (job) {
    const source = job.entry
    const zip = this.zip

    if (job.readdir)
      job.readdir.forEach(entry => this[ADDENTRY](job.path + '/' + entry))

    if (zip)
      source.on('data', chunk => zip.write(chunk))
    else
      source.on('data', chunk => super[WRITE](chunk))
  }
}

Pack.Sync = PackSync

module.exports = Pack
<commit_msg>debugging: try to figure out why travis shows less than 100% branch coverage, this will be reverted<commit_after>'use strict'

// A readable tar stream creator
// Technically, this is a transform stream that you write paths into,
// and tar format comes out of.
// The `add()` method is like `write()` but returns this,
// and end() return `this` as well, so you can
// do `new Pack(opt).add('files').add('dir').end().pipe(output)
// You could also do something like:
// streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar'))

class PackJob {
  constructor (path, absolute) {
    this.path = path || './'
    this.absolute = absolute
    this.stat = null
    this.readdir = null
    this.pending = false
    this.ignore = false
    this.piped = false
  }
}

const MiniPass = require('minipass')
const zlib = require('minizlib')
const WriteEntry = require('./write-entry.js')
const WriteEntrySync = WriteEntry.Sync
const Yallist = require('yallist')
const EOF = Buffer.alloc(1024)
const ONSTAT = Symbol('onStat')
const ENDED = Symbol('ended')
const QUEUE = Symbol('queue')
const CURRENT = Symbol('current')
const PROCESS = Symbol('process')
const PROCESSING = Symbol('processing')
const PROCESSJOB = Symbol('processJob')
const JOBS = Symbol('jobs')
const JOBDONE = Symbol('jobDone')
const ADDENTRY = Symbol('addEntry')
const STAT = Symbol('stat')
const READDIR = Symbol('readdir')
const ONREADDIR = Symbol('onreaddir')
const PIPE = Symbol('pipe')
const ENTRY = Symbol('entry')
const WRITEENTRYCLASS = Symbol('writeEntryClass')
const WRITE = Symbol('write')
const ONDRAIN = Symbol('ondrain')

const fs = require('fs')
const path = require('path')

class Pack extends MiniPass {
  constructor (opt) {
    super(opt)
    opt = opt || Object.create(null)
    this.opt = opt
    this.cwd = opt.cwd || process.cwd()
    this.maxReadSize = opt.maxReadSize
    this.preservePaths = !!opt.preservePaths
    this.strict = !!opt.strict
    this.prefix = (opt.prefix || '').replace(/(\\|\/)+$/, '')
    this.linkCache = opt.linkCache || new Map()
    this.statCache = opt.statCache || new Map()
    this.readdirCache = opt.readdirCache || new Map()
    this[WRITEENTRYCLASS] = WriteEntry
    if (typeof opt.onwarn === 'function')
      this.on('warn', opt.onwarn)

    this.zip = null
    if (opt.gzip) {
      if (typeof opt.gzip !== 'object')
        opt.gzip = {}
      this.zip = new zlib.Gzip(opt.gzip)
      this.zip.on('data', chunk => {
        super.write(chunk)
      })
      this.zip.on('end', _ => {
        super.end()
      })
      this.zip.on('drain', _ => {
        this[ONDRAIN]()
      })
    } else
      this.on('drain', this[ONDRAIN])

    this.portable = !!opt.portable

    this.filter = typeof opt.filter === 'function' ? opt.filter : _ => {
      return true
    }
    this[QUEUE] = new Yallist
    this[JOBS] = 0
    this.jobs = +opt.jobs || 4
    this[PROCESSING] = false
    this[ENDED] = false
  }

  [WRITE] (chunk) {
    return super.write(chunk)
  }

  add (path) {
    this.write(path)
    return this
  }

  end (path) {
    if (path)
      this.write(path)
    this[ENDED] = true
    this[PROCESS]()
    return this
  }

  write (path) {
    if (this[ENDED])
      throw new Error('write after end')

    this[ADDENTRY](path)
    return this.flowing
  }

  [ADDENTRY] (p) {
    const absolute = path.resolve(this.cwd, p)
    if (this.prefix)
      p = this.prefix + '/' + p
    this[QUEUE].push(new PackJob(p, absolute))
    this[PROCESS]()
  }

  [STAT] (job) {
    job.pending = true
    this[JOBS] += 1
    fs.lstat(job.absolute, (er, stat) => {
      job.pending = false
      this[JOBS] -= 1
      if (er)
        return this.emit('error', er)
      this[ONSTAT](job, stat)
    })
  }

  [ONSTAT] (job, stat) {
    this.statCache.set(job.absolute, stat)
    job.stat = stat

    // now we have the stat, we can filter it.
    if (!this.filter(job.path, stat))
      job.ignore = true

    this[PROCESS]()
  }

  [READDIR] (job) {
    job.pending = true
    this[JOBS] += 1
    fs.readdir(job.absolute, (er, entries) => {
      job.pending = false
      this[JOBS] -= 1
      if (er)
        return this.emit('error', er)
      this[ONREADDIR](job, entries)
    })
  }

  [ONREADDIR] (job, entries) {
    this.readdirCache.set(job.absolute, entries)
    job.readdir = entries
    this[PROCESS]()
  }

  [PROCESS] () {
    if (this[PROCESSING])
      return

    this[PROCESSING] = true
    for (let w = this[QUEUE].head;
         w !== null && this[JOBS] < this.jobs;
         w = w.next) {
      this[PROCESSJOB](w.value)
    }
    this[PROCESSING] = false

    if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) {
      if (this.zip)
        this.zip.end(EOF)
      else {
        super.write(EOF)
        super.end()
      }
    }
  }

  get [CURRENT] () {
    return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value
  }

  [JOBDONE] (job) {
    this[QUEUE].shift()
    this[JOBS] -= 1
    this[PROCESS]()
  }

  [PROCESSJOB] (job) {
    if (job.pending)
      return

    if (!job.stat) {
      if (this.statCache.has(job.absolute))
        this[ONSTAT](job, this.statCache.get(job.absolute))
      else
        this[STAT](job)
    }
    if (!job.stat)
      return

    // filtered out!
    if (job.ignore) {
      if (job === this[CURRENT])
        this[QUEUE].shift()
      return
    }

    if (job.stat.isDirectory() && !job.readdir) {
      if (this.readdirCache.has(job.absolute))
        this[ONREADDIR](job, this.readdirCache.get(job.absolute))
      else
        this[READDIR](job)
      if (!job.readdir)
        return
    }

    if (!job.entry) {
      job.entry = this[ENTRY](job)
      if (!job.entry) {
        job.ignore = true
        return
      }
    }

    if (job === this[CURRENT] && !job.piped)
      this[PIPE](job)
  }

  warn (msg, data) {
    return this.emit('warn', msg, data)
  }

  [ENTRY] (job) {
    this[JOBS] += 1
    try {
      return new this[WRITEENTRYCLASS](job.path, {
        onwarn: (msg, data) => {
          this.warn(msg, data)
        },
        cwd: this.cwd,
        absolute: job.absolute,
        preservePaths: this.preservePaths,
        maxReadSize: this.maxReadSize,
        strict: this.strict,
        portable: this.portable,
        linkCache: this.linkCache,
        statCache: this.statCache
      }).on('end', _ => {
        this[JOBDONE](job)
      })
    } catch (er) {
      this.emit('error', er)
    }
  }

  [ONDRAIN] () {
    if (this[CURRENT] && this[CURRENT].entry)
      this[CURRENT].entry.resume()
  }

  // like .pipe() but using super, because our write() is special
  [PIPE] (job) {
    job.piped = true

    if (job.readdir)
      job.readdir.forEach(entry => {
        this[ADDENTRY](job.path + '/' + entry)
      })

    const source = job.entry
    const zip = this.zip

    if (zip)
      source.on('data', chunk => {
        if (!zip.write(chunk))
          source.pause()
      })
    else
      source.on('data', chunk => {
        if (!super.write(chunk))
          source.pause()
      })
  }

  resume () {
    if (this.zip)
      this.zip.resume()
    return super.resume()
  }

  pause () {
    if (this.zip)
      this.zip.pause()
    return super.pause()
  }
}

class PackSync extends Pack {
  constructor (opt) {
    super(opt)
    this[WRITEENTRYCLASS] = WriteEntrySync
  }

  // pause/resume are no-ops in sync streams.
  pause () {}
  resume () {}

  [STAT] (job) {
    this[ONSTAT](job, fs.lstatSync(job.absolute))
  }

  [READDIR] (job, stat) {
    this[ONREADDIR](job, fs.readdirSync(job.absolute))
  }

  // gotta get it all in this tick
  [PIPE] (job) {
    const source = job.entry
    const zip = this.zip

    if (job.readdir)
      job.readdir.forEach(entry => {
        this[ADDENTRY](job.path + '/' + entry)
      })

    if (zip)
      source.on('data', chunk => {
        zip.write(chunk)
      })
    else
      source.on('data', chunk => {
        super[WRITE](chunk)
      })
  }
}

Pack.Sync = PackSync

module.exports = Pack
<|endoftext|>


<commit_before>'use strict';

var _ = require('underscore');

module.exports = setup;

var dot = require('dot');

function setup (config) {
  var source = config.source;
  var include = config.include;

  return page;

  function page (src) {
    return dot.template(source.content(src))(it(src));
  }

  function it (src) {
    return _.extend(source.header(src), {
      include: include_with_param
    });
  }

  function include_with_param (src, it) {
    return include(compile, src);

    function compile (src) {
      var template = dot.template(source.content(src));
      var header   = source.header(src);
      var content  = template(_.extend(header, it));

      return _.extend(header, {
        toString: function () {
          return content;
        }
      });
    }
  }
}
<commit_msg>Rename for more clarity<commit_after>'use strict';

var _ = require('underscore');

module.exports = setup;

var dot = require('dot');

function setup (config) {
  var source = config.source;
  var include = config.include;

  return page;

  function page (src) {
    return dot.template(source.content(src))(it(src));
  }

  function it (src) {
    return _.extend(source.header(src), {
      include: source_representation
    });
  }

  function source_representation (filename, it) {
    return include(compile, filename);

    function compile (src) {
      var template = dot.template(source.content(src));
      var header   = source.header(src);
      var content  = template(_.extend(header, it));

      return _.extend(header, {
        toString: function () {
          return content;
        }
      });
    }
  }
}
<|endoftext|>


<commit_before>'use strict';
var createSurface = require('gl-surface-plot'),
    tinycolor = require('tinycolor2'),
    ndarray = require('ndarray'),
    fill = require('ndarray-fill');

function Surface (config) {

    this.config = config;
    this.Plotly = config.Plotly;
}

module.exports = Surface;

function parseColorScale (colorscale) {
    return colorscale.map( function (elem) {
        var index = elem[0];
        var color = tinycolor(elem[1]);
        var rgb = color.toRgb();
        return {
            index: index,
            rgb: [rgb.r, rgb.g, rgb.b]
        };
    });
}

var proto = Surface.prototype;

proto.attributes = {
    x: {type: 'data_array'},
    y: {type: 'data_array'},
    z: {type: 'data_array'},
    colorscale: {from: 'Heatmap'},
    showscale: {from: 'Heatmap'},
    reversescale: {from: 'Heatmap'},
    lighting: {
        ambient: {
            type: 'number',
            min: 0.01,
            max: 0.99,
            dflt: 0.8
        },
        diffuse: {
            type: 'number',
            min: 0.01,
            max: 0.99,
            dflt: 0.8
        },
        specular: {
            type: 'number',
            min: 0.01,
            max: 0.99,
            dflt: 0.05
        },
        roughness: {
            type: 'number',
            min: 0.01,
            max: 0.99,
            dflt: 0.5
        },
        fresnel: {
            type: 'number',
            min: 0.01,
            max: 0.99,
            dflt: 0.2
        }
    }
};

proto.supplyDefaults = function (traceIn, traceOut, defaultColor, layout) {
    var i, _this = this;
    var Plotly = this.config.Plotly;

    function coerce(attr, dflt) {
        return Plotly.Lib.coerce(traceIn, traceOut, _this.attributes, attr, dflt);
    }

    function coerceHeatmap(attr, dflt) {
        return Plotly.Lib.coerce(traceIn, traceOut, Plotly.Heatmap.attributes, attr, dflt);
    }

    var z = coerce('z');
    if(!z) {
        traceOut.visible = false;
        return;
    }

    var xlen = z[0].length;
    var ylen = z.length;

    coerce('x');
    coerce('y');

    if (!Array.isArray(traceOut.x)) {
        // build a linearly scaled x
        traceOut.x = [];
        for (i = 0; i < xlen; ++i) {
            traceOut.x[i] = i;
        }
    }

    if (!Array.isArray(traceOut.y)) {
        traceOut.y = [];
        for (i = 0; i < ylen; ++i) {
            traceOut.y[i] = i;
        }
    }

    coerce('lighting.ambient');
    coerce('lighting.diffuse');
    coerce('lighting.specular');
    coerce('lighting.roughness');
    coerce('lighting.fresnel');

    coerceHeatmap('colorscale');

    var reverseScale = coerceHeatmap('reversescale'),
        showScale = coerceHeatmap('showscale');

    // apply the colorscale reversal here, so we don't have to
    // do it in separate modules later
    if(reverseScale) {
        traceOut.colorscale = traceOut.colorscale.map(this.flipScale).reverse();
    }

    if(showScale) {
        Plotly.Colorbar.supplyDefaults(traceIn, traceOut, defaultColor, layout);
    }

};

proto.flipScale = function (si) {
    return [1 - si[0], si[1]];
};

proto.update = function update (scene, sceneLayout, data, surface) {

    var i, j,
        colormap = parseColorScale(data.colorscale),
        z = data.z,
        x = data.x,
        y = data.y,
        xaxis = sceneLayout.xaxis,
        yaxis = sceneLayout.yaxis,
        zaxis = sceneLayout.zaxis,
        ticks = [[],[]],
        xlen = z[0].length,
        ylen = z.length,
        field = ndarray(new Float32Array(xlen * ylen), [xlen, ylen]),
        coords = [
            ndarray(new Float32Array(xlen * ylen), [xlen, ylen]),
            ndarray(new Float32Array(xlen * ylen), [xlen, ylen])
        ],
        xc = coords[0],
        yc = coords[1],
        hasCoords = false,
        gl = scene.shell.gl;

    /*
     * Fill and transpose zdata.
     * Consistent with 'heatmap' and 'contour', plotly 'surface'
     * 'z' are such that sub-arrays correspond to y-coords
     * and that the sub-array entries correspond to a x-coords,
     * which is the transpose of 'gl-surface-plot'.
     */
    fill(field, function(row, col) {
        return zaxis.d2l(z[col][row]);
    });

    // coords x
    if (Array.isArray(x[0])) {
        for (i = 0; i < xlen; ++i) {
            for (j = 0; j < ylen; ++j) {
                xc.set(j, i, xaxis.d2l(x[i][j]));
            }
        }

        hasCoords = true;

    } else {
        // ticks x
        for (i = 0; i < xlen; i++) {
            ticks[0][i] = xaxis.d2l(x[i]);
        }
    }

    // coords y
    if (Array.isArray(y[0])) {
        for (i = 0; i < xlen; ++i) {
            for (j = 0; j < ylen; ++j) {
                yc.set(j, i, yaxis.d2l(y[i][j]));
            }
        }

        hasCoords = true;

    } else {
        // ticks y
        for (i = 0; i < ylen; i++) {
            ticks[1][i] = yaxis.d2l(y[i]);
        }
    }

    var params = {
        field: field,
        colormap: colormap
    };

    if (hasCoords) {
        params.coords = coords;
    } else {
        params.ticks = ticks;
    }

    if (surface) {
        /*
         * We already have drawn this surface,
         * lets just update it with the latest params
         */
        surface.update(params);
    } else {
        /*
         * Push it onto the render queue
         */

        var pickIds = scene.allocIds(1);

        params.pickId       = pickIds.ids[0];
        surface             =  createSurface(gl, field, params);
        surface.groupId     = pickIds.group;
        surface.plotlyType  = data.type;

        scene.glDataMap[data.uid] = surface;
    }

    if ('lighting' in data) {
        surface.ambientLight   = data.lighting.ambient;
        surface.diffuseLight   = data.lighting.diffuse;
        surface.specularLight  = data.lighting.specular;
        surface.roughness      = data.lighting.roughness;
        surface.fresnel        = data.lighting.fresnel;
    }
    // uids determine which data is tied to which gl-object
    surface.uid = data.uid;
    surface.visible = data.visible;

    return surface;

};

proto.colorbar = function(gd, cd) {
    this.Plotly.Heatmap.colorbar(gd, cd);
};
<commit_msg>use ndarray fill instead of nested for loops<commit_after>'use strict';
var createSurface = require('gl-surface-plot'),
    tinycolor = require('tinycolor2'),
    ndarray = require('ndarray'),
    fill = require('ndarray-fill');

function Surface (config) {

    this.config = config;
    this.Plotly = config.Plotly;
}

module.exports = Surface;

function parseColorScale (colorscale) {
    return colorscale.map( function (elem) {
        var index = elem[0];
        var color = tinycolor(elem[1]);
        var rgb = color.toRgb();
        return {
            index: index,
            rgb: [rgb.r, rgb.g, rgb.b]
        };
    });
}

var proto = Surface.prototype;

proto.attributes = {
    x: {type: 'data_array'},
    y: {type: 'data_array'},
    z: {type: 'data_array'},
    colorscale: {from: 'Heatmap'},
    showscale: {from: 'Heatmap'},
    reversescale: {from: 'Heatmap'},
    lighting: {
        ambient: {
            type: 'number',
            min: 0.01,
            max: 0.99,
            dflt: 0.8
        },
        diffuse: {
            type: 'number',
            min: 0.01,
            max: 0.99,
            dflt: 0.8
        },
        specular: {
            type: 'number',
            min: 0.01,
            max: 0.99,
            dflt: 0.05
        },
        roughness: {
            type: 'number',
            min: 0.01,
            max: 0.99,
            dflt: 0.5
        },
        fresnel: {
            type: 'number',
            min: 0.01,
            max: 0.99,
            dflt: 0.2
        }
    }
};

proto.supplyDefaults = function (traceIn, traceOut, defaultColor, layout) {
    var i, _this = this;
    var Plotly = this.config.Plotly;

    function coerce(attr, dflt) {
        return Plotly.Lib.coerce(traceIn, traceOut, _this.attributes, attr, dflt);
    }

    function coerceHeatmap(attr, dflt) {
        return Plotly.Lib.coerce(traceIn, traceOut, Plotly.Heatmap.attributes, attr, dflt);
    }

    var z = coerce('z');
    if(!z) {
        traceOut.visible = false;
        return;
    }

    var xlen = z[0].length;
    var ylen = z.length;

    coerce('x');
    coerce('y');

    if (!Array.isArray(traceOut.x)) {
        // build a linearly scaled x
        traceOut.x = [];
        for (i = 0; i < xlen; ++i) {
            traceOut.x[i] = i;
        }
    }

    if (!Array.isArray(traceOut.y)) {
        traceOut.y = [];
        for (i = 0; i < ylen; ++i) {
            traceOut.y[i] = i;
        }
    }

    coerce('lighting.ambient');
    coerce('lighting.diffuse');
    coerce('lighting.specular');
    coerce('lighting.roughness');
    coerce('lighting.fresnel');

    coerceHeatmap('colorscale');

    var reverseScale = coerceHeatmap('reversescale'),
        showScale = coerceHeatmap('showscale');

    // apply the colorscale reversal here, so we don't have to
    // do it in separate modules later
    if(reverseScale) {
        traceOut.colorscale = traceOut.colorscale.map(this.flipScale).reverse();
    }

    if(showScale) {
        Plotly.Colorbar.supplyDefaults(traceIn, traceOut, defaultColor, layout);
    }

};

proto.flipScale = function (si) {
    return [1 - si[0], si[1]];
};

proto.update = function update (scene, sceneLayout, data, surface) {

    var i, j,
        colormap = parseColorScale(data.colorscale),
        z = data.z,
        x = data.x,
        y = data.y,
        xaxis = sceneLayout.xaxis,
        yaxis = sceneLayout.yaxis,
        zaxis = sceneLayout.zaxis,
        ticks = [[],[]],
        xlen = z[0].length,
        ylen = z.length,
        field = ndarray(new Float32Array(xlen * ylen), [xlen, ylen]),
        coords = [
            ndarray(new Float32Array(xlen * ylen), [xlen, ylen]),
            ndarray(new Float32Array(xlen * ylen), [xlen, ylen])
        ],
        xc = coords[0],
        yc = coords[1],
        hasCoords = false,
        gl = scene.shell.gl;

    /*
     * Fill and transpose zdata.
     * Consistent with 'heatmap' and 'contour', plotly 'surface'
     * 'z' are such that sub-arrays correspond to y-coords
     * and that the sub-array entries correspond to a x-coords,
     * which is the transpose of 'gl-surface-plot'.
     */
    fill(field, function(row, col) {
        return zaxis.d2l(z[col][row]);
    });

    // coords x
    if (Array.isArray(x[0])) {
        fill(xc, function(row, col) {
            return zaxis.d2l(x[col][row]);
        });

        hasCoords = true;

    } else {
        // ticks x
        for (i = 0; i < xlen; i++) {
            ticks[0][i] = xaxis.d2l(x[i]);
        }
    }

    // coords y
    if (Array.isArray(y[0])) {
        fill(yc, function(row, col) {
            return zaxis.d2l(y[col][row]);
        });

        hasCoords = true;

    } else {
        // ticks y
        for (i = 0; i < ylen; i++) {
            ticks[1][i] = yaxis.d2l(y[i]);
        }
    }

    var params = {
        field: field,
        colormap: colormap
    };

    if (hasCoords) {
        params.coords = coords;
    } else {
        params.ticks = ticks;
    }

    if (surface) {
        /*
         * We already have drawn this surface,
         * lets just update it with the latest params
         */
        surface.update(params);
    } else {
        /*
         * Push it onto the render queue
         */

        var pickIds = scene.allocIds(1);

        params.pickId       = pickIds.ids[0];
        surface             =  createSurface(gl, field, params);
        surface.groupId     = pickIds.group;
        surface.plotlyType  = data.type;

        scene.glDataMap[data.uid] = surface;
    }

    if ('lighting' in data) {
        surface.ambientLight   = data.lighting.ambient;
        surface.diffuseLight   = data.lighting.diffuse;
        surface.specularLight  = data.lighting.specular;
        surface.roughness      = data.lighting.roughness;
        surface.fresnel        = data.lighting.fresnel;
    }
    // uids determine which data is tied to which gl-object
    surface.uid = data.uid;
    surface.visible = data.visible;

    return surface;

};

proto.colorbar = function(gd, cd) {
    this.Plotly.Heatmap.colorbar(gd, cd);
};
<|endoftext|>