<commit_before>/*
 * CutJS viewer for p2.js
 */

Cut.p2 = function(world, options) {
  return new Cut.P2(world, options);
};

Cut.P2 = function(world, options) {
  Cut.P2.prototype._super.apply(this, arguments);

  var self = this;
  this.world = world;

  options = options || {};

  this.ratio = options.ratio || 128;

  this.maxSubSteps = options.maxSubSteps || 3;
  this.timeStep = options.timeStep || 1 / 60;

  this.lineWidth = "lineWidth" in options ? Cut._function(options.lineWidth)
      : Cut._function(0.025);
  this.lineColor = "lineColor" in options ? Cut._function(options.lineColor)
      : Cut._function("#000000");
  this.fillColor = "fillColor" in options ? Cut._function(options.fillColor)
      : Cut._function(Cut.P2.randomColor);

  world.on("addBody", function(e) {
    self.addRenderable(e.body);

  }).on("removeBody", function(e) {
    self.removeRenderable(e.body);

  }).on("addSpring", function(e) {
    self.addRenderable(e.spring);

  }).on("removeSpring", function(e) {
    self.removeRenderable(e.spring);
  });

  this.drawContacts = false;
  this.toggleContact = function(toggle) {
    if (arguments.length) {
      this.drawContacts = toggle;
    } else {
      this.drawContacts = !this.drawContacts;
    }
    return this;
  };

  // Add initial bodies
  for (var i = 0; i < world.bodies.length; i++) {
    this.addRenderable(world.bodies[i]);
  }
  for (var i = 0; i < world.springs.length; i++) {
    this.addRenderable(world.springs[i]);
  }

  this.tick(function() {
    this.step();
  });

  this.tempv = p2.vec2.fromValues(0, 0);
};

Cut.P2.prototype = new Cut(Cut.Proto);
Cut.P2.prototype._super = Cut;
Cut.P2.prototype.constructor = Cut.P2;

Cut.P2.prototype.step = function(t) {
  this.world.step(this.timeStep, t, this.maxSubSteps);

  for (var i = 0; i < this.world.bodies.length; i++) {
    var body = this.world.bodies[i];
    if (body.ui) {
      body.ui.pin({
        offsetX : body.position[0],
        offsetY : -body.position[1],
        rotation : -body.angle
      });
    }
  }
  for (var i = 0; i < this.world.springs.length; i++) {
    var spring = this.world.springs[i];

    spring.getWorldAnchorA(this.tempv);
    var ax = this.tempv[0];
    var ay = this.tempv[1];

    spring.getWorldAnchorB(this.tempv);
    var bx = this.tempv[0];
    var by = this.tempv[1];

    // Spring position is the mean point between the anchors
    var x = (ax + bx) / 2;
    var y = (ay + by) / 2;

    // Compute distance vector between anchors, in screen coords
    var dx = ax - bx;
    var dy = ay - by;

    var a = Math.atan2(dx, dy) + Math.PI / 2;

    var s = Cut.Math.length(dx, dy) / spring.restLength;

    spring.ui.pin({
      offsetX : x,
      offsetY : -y,
      scaleX : s,
      scaleY : 1 / s,
      rotation : a
    });
  }
};

Cut.P2.prototype.addRenderable = function(obj) {

  obj.ui = Cut.create().appendTo(this);

  if (obj instanceof p2.Body && obj.shapes.length) {
    if (obj.concavePath && !this.debugPolygons) {
      var cutout = this.drawConvex(obj.concavePath);
      Cut.image(cutout).appendTo(obj.ui).pin({
        handle : 0.5,
        offsetX : obj.shapeOffsets[i] ? obj.shapeOffsets[i][0] : 0,
        offsetY : obj.shapeOffsets[i] ? obj.shapeOffsets[i][1] : 0,
        rotation : -obj.shapeAngles[i] || 0
      });

    } else {
      for (var i = 0; i < obj.shapes.length; i++) {
        var shape = obj.shapes[i];

        var cutout = null;
        if (shape instanceof p2.Circle) {
          cutout = this.drawCircle(shape.radius);

        } else if (shape instanceof p2.Particle) {
          cutout = this.drawCircle(2 * this.lineWidth(), {
            lineColor : "",
            fillColor : this.lineColor()
          });

        } else if (shape instanceof p2.Plane) {
          cutout = this.drawPlane(-10, 10, 10);

        } else if (shape instanceof p2.Line) {
          cutout = this.drawLine(shape.length);

        } else if (shape instanceof p2.Rectangle) {
          cutout = this.drawRectangle(shape.width, shape.height);

        } else if (shape instanceof p2.Capsule) {
          cutout = this.drawCapsule(shape.length, shape.radius);

        } else if (shape instanceof p2.Convex) {
          if (shape.vertices.length) {
            cutout = this.drawConvex(shape.vertices);
          }
        }
        Cut.image(cutout).appendTo(obj.ui).pin({
          handle : 0.5,
          offsetX : obj.shapeOffsets[i] ? obj.shapeOffsets[i][0] : 0,
          offsetY : obj.shapeOffsets[i] ? obj.shapeOffsets[i][1] : 0,
          rotation : -obj.shapeAngles[i] || 0
        });
      }
    }

  } else if (obj instanceof p2.Spring) {
    var cutout = this.drawSpring(obj.restLength);
    Cut.image(cutout).appendTo(obj.ui).pin({
      handle : 0.5
    });
  }

};

Cut.P2.prototype.removeRenderable = function(obj) {
  obj.ui && obj.ui.remove();
};

Cut.P2.prototype.drawLine = function(length, options) {
  options = this.options(options);
  var lineWidth = options.lineWidth * 2, lineColor = options.lineColor, fillColor = options.fillColor;

  return Cut.Out.drawing(length + 2 * lineWidth, lineWidth, this.ratio,
      function(ctx, ratio) {
        ctx.scale(ratio, ratio);

        ctx.moveTo(lineWidth, lineWidth / 2);
        ctx.lineTo(lineWidth + length, lineWidth / 2);

        ctx.lineWidth = lineWidth;
        ctx.lineCap = "round";
        ctx.strokeStyle = lineColor;
        ctx.stroke();
      });

};

Cut.P2.prototype.drawRectangle = function(w, h, options) {
  options = this.options(options);
  var lineWidth = options.lineWidth, lineColor = options.lineColor, fillColor = options.fillColor;

  var width = w + 2 * lineWidth;
  var height = h + 2 * lineWidth;

  return Cut.Out.drawing(width, height, this.ratio, function(ctx, ratio) {
    ctx.scale(ratio, ratio);
    ctx.beginPath();
    ctx.rect(lineWidth, lineWidth, w, h);
    if (fillColor) {
      ctx.fillStyle = fillColor;
      ctx.fill();
    }
    ctx.lineWidth = lineWidth;
    ctx.strokeStyle = lineColor;
    ctx.stroke();
  });
};

Cut.P2.prototype.drawCircle = function(radius, options) {
  options = this.options(options);
  var lineWidth = options.lineWidth, lineColor = options.lineColor, fillColor = options.fillColor;

  var width = radius * 2 + lineWidth * 2;
  var height = radius * 2 + lineWidth * 2;

  return Cut.Out.drawing(width, height, this.ratio, function(ctx, ratio) {
    ctx.scale(ratio, ratio);
    ctx.beginPath();
    ctx.arc(width / 2, height / 2, radius, 0, 2 * Math.PI);
    if (fillColor) {
      ctx.fillStyle = fillColor;
      ctx.fill();
    }

    ctx.moveTo(radius + lineWidth, radius + lineWidth);
    ctx.lineTo(lineWidth, radius + lineWidth);

    ctx.lineWidth = lineWidth;
    ctx.strokeStyle = lineColor;
    ctx.stroke();
  });
};

Cut.P2.prototype.drawCapsule = function(len, radius, options) {

  options = this.options(options);
  var lineWidth = options.lineWidth, lineColor = options.lineColor, fillColor = options.fillColor;

  var width = len + 2 * radius + 2 * lineWidth;
  var height = 2 * radius + 2 * lineWidth;

  return Cut.Out.drawing(width, height, this.ratio, function(ctx, ratio) {
    ctx.scale(ratio, ratio);

    ctx.beginPath();
    ctx.moveTo(radius + lineWidth, lineWidth);
    ctx.lineTo(len + radius + lineWidth, lineWidth);
    ctx.arc(len + radius + lineWidth, radius + lineWidth, radius, -Math.PI / 2,
        Math.PI / 2);
    ctx.lineTo(radius + lineWidth, 2 * radius + lineWidth);
    ctx.arc(radius + lineWidth, radius + lineWidth, radius, Math.PI / 2,
        -Math.PI / 2);
    ctx.closePath();
    if (fillColor) {
      ctx.fillStyle = fillColor;
      ctx.fill();
    }
    ctx.lineWidth = lineWidth;
    ctx.strokeStyle = lineColor;
    ctx.stroke();
  });
};

Cut.P2.prototype.drawSpring = function(length, options) {
  options = this.options(options);
  var lineWidth = options.lineWidth, lineColor = options.lineColor, fillColor = options.fillColor;

  length = Math.max(length, lineWidth * 10);

  var N = 12;
  var dx = length / N;
  var dy = 0.2 * length;

  return Cut.Out.drawing(length, dy * 2, this.ratio, function(ctx, ratio) {
    ctx.scale(ratio, ratio);

    ctx.lineWidth = lineWidth;
    ctx.strokeStyle = lineColor;
    ctx.lineJoin = "round";

    ctx.moveTo(0, dy);
    for (var i = 1; i < N; i++) {
      var x = dx * i;
      var y = dy;
      if (i <= 1 || i >= N - 1) {
        // Do nothing
      } else if (i % 2 === 0) {
        y -= dy / 2;
      } else {
        y += dy / 2;
      }
      ctx.lineTo(x, y);
    }
    ctx.lineTo(length, dy);

    ctx.stroke();
  });
};

Cut.P2.prototype.drawPlane = function(x0, x1, max, options) {
  options = this.options(options);
  var lineWidth = options.lineWidth, lineColor = options.lineColor, fillColor = options.fillColor;

  return Cut.Out.drawing(max * 2, max * 2, this.ratio, function(ctx, ratio) {
    ctx.scale(ratio, ratio);

    if (fillColor) {
      ctx.beginPath();
      ctx.rect(0, max, 2 * max, 2 * max);
      ctx.fillStyle = fillColor;
      ctx.fill();
      ctx.closePath();
    }

    ctx.beginPath();
    ctx.moveTo(0, max);
    ctx.lineTo(2 * max, max);

    ctx.lineWidth = lineWidth;
    ctx.lineCap = "round";
    ctx.strokeStyle = lineColor;
    ctx.setLineDash && ctx.setLineDash([ 0.12, 0.06 ]);
    ctx.mozDash = [ 0.12, 0.06 ];

    ctx.stroke();
  });

};

Cut.P2.prototype.drawConvex = function(verts, options) {
  options = this.options(options);
  var lineWidth = options.lineWidth, lineColor = options.lineColor, fillColor = options.fillColor;

  if (!verts.length) {
    return;
  }

  var width = 0, height = 0;
  for (var i = 0; i < verts.length; i++) {
    var v = verts[i], x = v[0], y = -v[1];
    width = Math.max(Math.abs(x), width);
    height = Math.max(Math.abs(y), height)
  }

  var cutout = Cut.Out.drawing(2 * width + 2 * lineWidth, 2 * height + 2
      * lineWidth, this.ratio, function(ctx, ratio) {
    ctx.scale(ratio, ratio);

    ctx.beginPath();
    for (var i = 0; i < verts.length; i++) {
      var v = verts[i], x = v[0] + width + lineWidth, y = -v[1] + height
          + lineWidth;
      if (i == 0)
        ctx.moveTo(x, y);
      else
        ctx.lineTo(x, y);
    }

    if (verts.length > 2) {
      ctx.closePath();
    }

    if (fillColor) {
      ctx.fillStyle = fillColor;
      ctx.fill();
      ctx.closePath();
    }

    ctx.lineWidth = lineWidth;
    ctx.lineCap = "round";
    ctx.strokeStyle = lineColor;
    ctx.stroke();
  });

  return cutout;
};

Cut.P2.prototype.options = function(options) {
  options = typeof options === "object" ? options : {};
  options.lineWidth = options.lineWidth || this.lineWidth();
  options.lineColor = options.lineColor || this.lineColor();
  options.fillColor = options.fillColor || this.fillColor();
  return options;
};

Cut.P2.randomColor = function() {
  var red = Cut.Math.random(192, 256) | 0;
  var green = Cut.Math.random(192, 256) | 0;
  var blue = Cut.Math.random(192, 256) | 0;
  return "#" + red.toString(16) + green.toString(16) + blue.toString(16);
};

Cut._function = function(value) {
  return typeof value === "function" ? value : function() {
    return value;
  };
};<commit_msg>fix cut-p2<commit_after>/*
 * CutJS viewer for p2.js
 */

Cut.p2 = function(world, options) {
  return new Cut.P2(world, options);
};

Cut.P2 = function(world, options) {
  Cut.P2.prototype._super.apply(this, arguments);

  var self = this;
  this.world = world;

  options = options || {};

  this.ratio = options.ratio || 128;

  this.maxSubSteps = options.maxSubSteps || 3;
  this.timeStep = options.timeStep || 1 / 60;

  this.lineWidth = "lineWidth" in options ? Cut._function(options.lineWidth)
      : Cut._function(0.025);
  this.lineColor = "lineColor" in options ? Cut._function(options.lineColor)
      : Cut._function("#000000");
  this.fillColor = "fillColor" in options ? Cut._function(options.fillColor)
      : Cut._function(Cut.P2.randomColor);

  world.on("addBody", function(e) {
    self.addRenderable(e.body);

  }).on("removeBody", function(e) {
    self.removeRenderable(e.body);

  }).on("addSpring", function(e) {
    self.addRenderable(e.spring);

  }).on("removeSpring", function(e) {
    self.removeRenderable(e.spring);
  });

  this.drawContacts = false;
  this.toggleContact = function(toggle) {
    if (arguments.length) {
      this.drawContacts = toggle;
    } else {
      this.drawContacts = !this.drawContacts;
    }
    return this;
  };

  // Add initial bodies
  for (var i = 0; i < world.bodies.length; i++) {
    this.addRenderable(world.bodies[i]);
  }
  for (var i = 0; i < world.springs.length; i++) {
    this.addRenderable(world.springs[i]);
  }

  this.tick(function() {
    this.step();
  });

  this.tempv = p2.vec2.fromValues(0, 0);
};

Cut.P2.prototype = new Cut(Cut.Proto);
Cut.P2.prototype._super = Cut;
Cut.P2.prototype.constructor = Cut.P2;

Cut.P2.prototype.step = function(t) {
  this.world.step(this.timeStep, t, this.maxSubSteps);

  for (var i = 0; i < this.world.bodies.length; i++) {
    var body = this.world.bodies[i];
    if (body.ui) {
      body.ui.pin({
        offsetX : body.position[0],
        offsetY : -body.position[1],
        rotation : -body.angle
      });
    }
  }
  for (var i = 0; i < this.world.springs.length; i++) {
    var spring = this.world.springs[i];

    spring.getWorldAnchorA(this.tempv);
    var ax = this.tempv[0];
    var ay = this.tempv[1];

    spring.getWorldAnchorB(this.tempv);
    var bx = this.tempv[0];
    var by = this.tempv[1];

    // Spring position is the mean point between the anchors
    var x = (ax + bx) / 2;
    var y = (ay + by) / 2;

    // Compute distance vector between anchors, in screen coords
    var dx = ax - bx;
    var dy = ay - by;

    var a = Math.atan2(dx, dy) + Math.PI / 2;

    var s = Cut.Math.length(dx, dy) / spring.restLength;

    spring.ui.pin({
      offsetX : x,
      offsetY : -y,
      scaleX : s,
      scaleY : 1 / s,
      rotation : a
    });
  }
};

Cut.P2.prototype.addRenderable = function(obj) {

  obj.ui = Cut.create().appendTo(this);

  if (obj instanceof p2.Body && obj.shapes.length) {
    if (obj.concavePath && !this.debugPolygons) {
      var cutout = this.drawConvex(obj.concavePath);
      Cut.image(cutout).appendTo(obj.ui).pin({
        handle : 0.5,
        offsetX : obj.shapeOffsets[i] ? obj.shapeOffsets[i][0] : 0,
        offsetY : obj.shapeOffsets[i] ? obj.shapeOffsets[i][1] : 0,
        rotation : -obj.shapeAngles[i] || 0
      });

    } else {
      for (var i = 0; i < obj.shapes.length; i++) {
        var shape = obj.shapes[i];

        var cutout = null;
        if (shape instanceof p2.Circle) {
          cutout = this.drawCircle(shape.radius);

        } else if (shape instanceof p2.Particle) {
          cutout = this.drawCircle(2 * this.lineWidth(), {
            lineColor : "",
            fillColor : this.lineColor()
          });

        } else if (shape instanceof p2.Plane) {
          cutout = this.drawPlane(-10, 10, 10);

        } else if (shape instanceof p2.Line) {
          cutout = this.drawLine(shape.length);

        } else if (shape instanceof p2.Rectangle) {
          cutout = this.drawRectangle(shape.width, shape.height);

        } else if (shape instanceof p2.Capsule) {
          cutout = this.drawCapsule(shape.length, shape.radius);

        } else if (shape instanceof p2.Convex) {
          if (shape.vertices.length) {
            cutout = this.drawConvex(shape.vertices);
          }
        }
        Cut.image(cutout).appendTo(obj.ui).pin({
          handle : 0.5,
          offsetX : obj.shapeOffsets[i] ? obj.shapeOffsets[i][0] : 0,
          offsetY : -(obj.shapeOffsets[i] ? obj.shapeOffsets[i][1] : 0),
          rotation : -obj.shapeAngles[i] || 0
        });
      }
    }

  } else if (obj instanceof p2.Spring) {
    var cutout = this.drawSpring(obj.restLength);
    Cut.image(cutout).appendTo(obj.ui).pin({
      handle : 0.5
    });
  }

};

Cut.P2.prototype.removeRenderable = function(obj) {
  obj.ui && obj.ui.remove();
};

Cut.P2.prototype.drawLine = function(length, options) {
  options = this.options(options);
  var lineWidth = options.lineWidth * 2, lineColor = options.lineColor, fillColor = options.fillColor;

  return Cut.Out.drawing(length + 2 * lineWidth, lineWidth, this.ratio,
      function(ctx, ratio) {
        ctx.scale(ratio, ratio);

        ctx.moveTo(lineWidth, lineWidth / 2);
        ctx.lineTo(lineWidth + length, lineWidth / 2);

        ctx.lineWidth = lineWidth;
        ctx.lineCap = "round";
        ctx.strokeStyle = lineColor;
        ctx.stroke();
      });

};

Cut.P2.prototype.drawRectangle = function(w, h, options) {
  options = this.options(options);
  var lineWidth = options.lineWidth, lineColor = options.lineColor, fillColor = options.fillColor;

  var width = w + 2 * lineWidth;
  var height = h + 2 * lineWidth;

  return Cut.Out.drawing(width, height, this.ratio, function(ctx, ratio) {
    ctx.scale(ratio, ratio);
    ctx.beginPath();
    ctx.rect(lineWidth, lineWidth, w, h);
    if (fillColor) {
      ctx.fillStyle = fillColor;
      ctx.fill();
    }
    ctx.lineWidth = lineWidth;
    ctx.strokeStyle = lineColor;
    ctx.stroke();
  });
};

Cut.P2.prototype.drawCircle = function(radius, options) {
  options = this.options(options);
  var lineWidth = options.lineWidth, lineColor = options.lineColor, fillColor = options.fillColor;

  var width = radius * 2 + lineWidth * 2;
  var height = radius * 2 + lineWidth * 2;

  return Cut.Out.drawing(width, height, this.ratio, function(ctx, ratio) {
    ctx.scale(ratio, ratio);
    ctx.beginPath();
    ctx.arc(width / 2, height / 2, radius, 0, 2 * Math.PI);
    if (fillColor) {
      ctx.fillStyle = fillColor;
      ctx.fill();
    }

    ctx.moveTo(radius + lineWidth, radius + lineWidth);
    ctx.lineTo(lineWidth, radius + lineWidth);

    ctx.lineWidth = lineWidth;
    ctx.strokeStyle = lineColor;
    ctx.stroke();
  });
};

Cut.P2.prototype.drawCapsule = function(len, radius, options) {

  options = this.options(options);
  var lineWidth = options.lineWidth, lineColor = options.lineColor, fillColor = options.fillColor;

  var width = len + 2 * radius + 2 * lineWidth;
  var height = 2 * radius + 2 * lineWidth;

  return Cut.Out.drawing(width, height, this.ratio, function(ctx, ratio) {
    ctx.scale(ratio, ratio);

    ctx.beginPath();
    ctx.moveTo(radius + lineWidth, lineWidth);
    ctx.lineTo(len + radius + lineWidth, lineWidth);
    ctx.arc(len + radius + lineWidth, radius + lineWidth, radius, -Math.PI / 2,
        Math.PI / 2);
    ctx.lineTo(radius + lineWidth, 2 * radius + lineWidth);
    ctx.arc(radius + lineWidth, radius + lineWidth, radius, Math.PI / 2,
        -Math.PI / 2);
    ctx.closePath();
    if (fillColor) {
      ctx.fillStyle = fillColor;
      ctx.fill();
    }
    ctx.lineWidth = lineWidth;
    ctx.strokeStyle = lineColor;
    ctx.stroke();
  });
};

Cut.P2.prototype.drawSpring = function(length, options) {
  options = this.options(options);
  var lineWidth = options.lineWidth, lineColor = options.lineColor, fillColor = options.fillColor;

  length = Math.max(length, lineWidth * 10);

  var N = 12;
  var dx = length / N;
  var dy = 0.2 * length;

  return Cut.Out.drawing(length, dy * 2, this.ratio, function(ctx, ratio) {
    ctx.scale(ratio, ratio);

    ctx.lineWidth = lineWidth;
    ctx.strokeStyle = lineColor;
    ctx.lineJoin = "round";

    ctx.moveTo(0, dy);
    for (var i = 1; i < N; i++) {
      var x = dx * i;
      var y = dy;
      if (i <= 1 || i >= N - 1) {
        // Do nothing
      } else if (i % 2 === 0) {
        y -= dy / 2;
      } else {
        y += dy / 2;
      }
      ctx.lineTo(x, y);
    }
    ctx.lineTo(length, dy);

    ctx.stroke();
  });
};

Cut.P2.prototype.drawPlane = function(x0, x1, max, options) {
  options = this.options(options);
  var lineWidth = options.lineWidth, lineColor = options.lineColor, fillColor = options.fillColor;

  return Cut.Out.drawing(max * 2, max * 2, this.ratio, function(ctx, ratio) {
    ctx.scale(ratio, ratio);

    if (fillColor) {
      ctx.beginPath();
      ctx.rect(0, max, 2 * max, 2 * max);
      ctx.fillStyle = fillColor;
      ctx.fill();
      ctx.closePath();
    }

    ctx.beginPath();
    ctx.moveTo(0, max);
    ctx.lineTo(2 * max, max);

    ctx.lineWidth = lineWidth;
    ctx.lineCap = "round";
    ctx.strokeStyle = lineColor;
    ctx.setLineDash && ctx.setLineDash([ 0.12, 0.06 ]);
    ctx.mozDash = [ 0.12, 0.06 ];

    ctx.stroke();
  });

};

Cut.P2.prototype.drawConvex = function(verts, options) {
  options = this.options(options);
  var lineWidth = options.lineWidth, lineColor = options.lineColor, fillColor = options.fillColor;

  if (!verts.length) {
    return;
  }

  var width = 0, height = 0;
  for (var i = 0; i < verts.length; i++) {
    var v = verts[i], x = v[0], y = -v[1];
    width = Math.max(Math.abs(x), width);
    height = Math.max(Math.abs(y), height)
  }

  var cutout = Cut.Out.drawing(2 * width + 2 * lineWidth, 2 * height + 2
      * lineWidth, this.ratio, function(ctx, ratio) {
    ctx.scale(ratio, ratio);

    ctx.beginPath();
    for (var i = 0; i < verts.length; i++) {
      var v = verts[i], x = v[0] + width + lineWidth, y = -v[1] + height
          + lineWidth;
      if (i == 0)
        ctx.moveTo(x, y);
      else
        ctx.lineTo(x, y);
    }

    if (verts.length > 2) {
      ctx.closePath();
    }

    if (fillColor) {
      ctx.fillStyle = fillColor;
      ctx.fill();
      ctx.closePath();
    }

    ctx.lineWidth = lineWidth;
    ctx.lineCap = "round";
    ctx.strokeStyle = lineColor;
    ctx.stroke();
  });

  return cutout;
};

Cut.P2.prototype.options = function(options) {
  options = typeof options === "object" ? options : {};
  options.lineWidth = options.lineWidth || this.lineWidth();
  options.lineColor = options.lineColor || this.lineColor();
  options.fillColor = options.fillColor || this.fillColor();
  return options;
};

Cut.P2.randomColor = function() {
  var red = Cut.Math.random(192, 256) | 0;
  var green = Cut.Math.random(192, 256) | 0;
  var blue = Cut.Math.random(192, 256) | 0;
  return "#" + red.toString(16) + green.toString(16) + blue.toString(16);
};

Cut._function = function(value) {
  return typeof value === "function" ? value : function() {
    return value;
  };
};<|endoftext|>


<commit_before>// Native
import fs from 'fs'
import path from 'path'

// Packages
import fetch from 'node-fetch'

// Utilities
import plusxSync from './chmod'
import { disableProgress, enableProgress, info, showProgress } from './log'

const now = path.join(__dirname, 'now')
const targetWin32 = path.join(__dirname, 'now.exe')
const target = process.platform === 'win32' ? targetWin32 : now
const partial = target + '.partial'

const platformToName = {
  darwin: 'now-macos',
  linux: 'now-linux',
  win32: 'now-win.exe'
}

const getLatest = async () => {
  const res = await fetch('https://now-cli-latest.zeit.sh')

  if (res.status !== 200) {
    throw new Error(res.statusText)
  }

  return res.json()
}

async function main() {
  info('Retrieving the latest CLI version...')

  const latest = await getLatest()
  const name = platformToName[process.platform]
  const asset = latest.assets.filter(a => a.name === name)[0]

  info('For the sources, check out: https://github.com/zeit/now-cli')

  // Print an empty line
  console.log('')

  enableProgress('Downloading now CLI ' + latest.tag)
  showProgress(0)

  const { url } = asset
  const resp = await fetch(url)

  if (resp.status !== 200) {
    disableProgress()
    throw new Error(resp.statusText + ' ' + url)
  }

  const size = resp.headers.get('content-length')
  const ws = fs.createWriteStream(partial)

  await new Promise((resolve, reject) => {
    let bytesRead = 0

    resp.body.on('data', chunk => {
      bytesRead += chunk.length
      showProgress(100 * bytesRead / size)
    })

    resp.body.pipe(ws)

    ws
      .on('close', () => {
        showProgress(100)
        disableProgress()
        resolve()
      })
      .on('error', error => {
        disableProgress()
        reject(error)
      })
  })

  fs.renameSync(partial, target)

  if (process.platform === 'win32') {
    fs.writeFileSync(
      now,
      '#!/usr/bin/env node\n' +
        'var chip = require("child_process")\n' +
        'var args = process.argv.slice(2)\n' +
        'var opts = { stdio: "inherit" }\n' +
        'var r = chip.spawnSync(__dirname + "/now.exe", args, opts)\n' +
        'if (r.error) throw r.error\n' +
        'process.exit(r.status)\n'
    )
  } else {
    plusxSync(now)
  }
}

main().catch(err => {
  console.error(err)

  // eslint-disable-next-line unicorn/no-process-exit
  process.exit(2)
})
<commit_msg>Always download the specified version<commit_after>// Native
import fs from 'fs'
import path from 'path'

// Packages
import fetch from 'node-fetch'

// Utilities
import plusxSync from './chmod'
import { disableProgress, enableProgress, info, showProgress } from './log'

const now = path.join(__dirname, 'now')
const targetWin32 = path.join(__dirname, 'now.exe')
const target = process.platform === 'win32' ? targetWin32 : now
const partial = target + '.partial'

const packagePath = path.join(__dirname, '..', '..', 'package.json')
const packageJSON = require(packagePath)

const platformToName = {
  darwin: 'now-macos',
  linux: 'now-linux',
  win32: 'now-win.exe'
}

async function main() {
  info('Retrieving the latest CLI version...')

  const downloadURL = `https://api.github.com/repos/zeit/now-cli/releases/tags/${packageJSON.version}`
  const responseLatest = await fetch(downloadURL)
  const latest = await responseLatest.json()

  const name = platformToName[process.platform]
  const asset = latest.assets.find(a => a.name === name)

  info('For the sources, check out: https://github.com/zeit/now-cli')

  // Print an empty line
  console.log('')

  enableProgress('Downloading now CLI ' + packageJSON.version)
  showProgress(0)

  const { url } = asset
  const resp = await fetch(url)

  if (resp.status !== 200) {
    disableProgress()
    throw new Error(resp.statusText + ' ' + url)
  }

  const size = resp.headers.get('content-length')
  const ws = fs.createWriteStream(partial)

  await new Promise((resolve, reject) => {
    let bytesRead = 0

    resp.body.on('data', chunk => {
      bytesRead += chunk.length
      showProgress(100 * bytesRead / size)
    })

    resp.body.pipe(ws)

    ws
      .on('close', () => {
        showProgress(100)
        disableProgress()
        resolve()
      })
      .on('error', error => {
        disableProgress()
        reject(error)
      })
  })

  fs.renameSync(partial, target)

  if (process.platform === 'win32') {
    fs.writeFileSync(
      now,
      '#!/usr/bin/env node\n' +
        'var chip = require("child_process")\n' +
        'var args = process.argv.slice(2)\n' +
        'var opts = { stdio: "inherit" }\n' +
        'var r = chip.spawnSync(__dirname + "/now.exe", args, opts)\n' +
        'if (r.error) throw r.error\n' +
        'process.exit(r.status)\n'
    )
  } else {
    plusxSync(now)
  }
}

main().catch(err => {
  console.error(err)

  // eslint-disable-next-line unicorn/no-process-exit
  process.exit(2)
})
<|endoftext|>


<commit_before>'use strict';

var d            = require('es5-ext/lib/Object/descriptor')
  , isNamespace  = require('./is-namespace')

  , isArray = Array.isArray
  , defineProperty = Object.defineProperty
  , getPrototypeOf = Object.getPrototypeOf

  , base, fillChain, findNs, define, isValidNsRef
  , Relation, RelProto, RelTransport;

fillChain = function (obj, relName) {
	var proto = getPrototypeOf(obj);
	if (!proto.hasOwnProperty(relName)) fillChain(proto, relName);
	defineProperty(obj, relName, d('', obj[relName]._create_(obj)));
};

isValidNsRef = function (name) { return (name[0] !== name[0].toLowerCase()); };

findNs = function (value) {
	if (base.String && base.String.is(value)) return base.String;
	if (base.Boolean && base.Boolean.is(value)) return base.Boolean;
	if (base.Number && base.Number.is(value)) return base.Number;
	if (base.RegExp && base.RegExp.is(value)) return base.RegExp;
	if (base.DateTime && base.DateTime.is(value)) return base.DateTime;
};

define = function (obj, name, value) {
	var get, set, rel, relName, attr, allowNS;

	relName = '__' + name;
	allowNS = isValidNsRef(name);
	attr = ((typeof obj === 'function') || !obj._id_ || obj._descriptor_) ? '' :
			'e';
	rel = new Relation(obj, name, d.gs('c' + attr, get = function () {
		if (!this.hasOwnProperty(relName)) fillChain(this, relName);
		return this[relName].value;
	}, set = function (value) {
		var error, rel;
		if (!this.hasOwnProperty(relName)) fillChain(this, relName);
		rel = this[relName];
		if (value instanceof RelTransport) {
			if ((error = value.validate(this, name))) throw error;
			value.apply(rel);
		} else {
			rel[(!allowNS && isNamespace(value)) ? 'ns' : 'value'] = value;
		}
	}));

	defineProperty(obj, relName, d('', rel));
	defineProperty(obj, '_' + name, d.gs('', function () {
		if (!this.hasOwnProperty(relName)) fillChain(this, relName);
		return this[relName];
	}));
	defineProperty(obj, name, d.gs(attr, get, set));
};

module.exports = exports = function (obj, name, value) {
	var proto, base, rel, ns;
	if ((name in obj) && obj['__' + name]) {
		if (value instanceof RelTransport) {
			value.apply(obj['_' + name]);
		} else if (isNamespace(value) && !isValidNsRef(name)) {
			obj['_' + name]._ns.$setValue(value);
		} else {
			obj['_' + name].$setValue(value);
		}
	} else {
		base = obj;
		proto = getPrototypeOf(obj);
		while (proto.hasOwnProperty('_id_')) {
			base = proto;
			proto = getPrototypeOf(proto);
		}
		define(base, name);
		if (value instanceof RelTransport) {
			value.apply(obj['_' + name]);
		} else if (isNamespace(value) && !isValidNsRef(name)) {
			obj['_' + name]._ns.$setValue(value);
		} else if (value !== undefined) {
			rel = obj['_' + name];
			if (value !== null) {
				if (isArray(value)) {
					rel.multiple = true;
					if (value.length) {
						rel.required = true;
						if ((ns = findNs(value[0])) && value.slice(1).every(ns.is, ns)) {
							rel._ns.$setValue(ns);
						}
					}
				} else {
					rel.required = true;
					rel._ns.$setValue(findNs(value));
				}
			}
			rel.$setValue(value);
		}
	}
	return value;
};

exports.validate = function (obj, name, value) {
	var defined = (name in obj) && obj['__' + name] && true
	  , errors, error;

	if (value instanceof RelTransport) return value.validate(obj, name);
	if (isNamespace(value) && !isValidNsRef(name)) return null;
	if (defined) return obj['_' + name].validate(value);

	if (isArray(value)) {
		if ((errors = RelProto._validateValues_(value))) {
			error = new TypeError(value + " contains invalid values");
			error.errors = errors;
			return error;
		}
		return null;
	}
	return RelProto.validate(value);
};

exports.fillChain = fillChain;

Relation = require('./relation');
RelTransport = require('./rel-transport');
RelProto = Relation.prototype;
base = require('../types/base');
<commit_msg>Cleanup<commit_after>'use strict';

var d            = require('es5-ext/lib/Object/descriptor')
  , isNamespace  = require('./is-namespace')

  , isArray = Array.isArray
  , defineProperty = Object.defineProperty
  , getPrototypeOf = Object.getPrototypeOf

  , base, fillChain, findNs, define, isValidNsRef
  , Relation, RelProto, RelTransport;

fillChain = function (obj, relName) {
	var proto = getPrototypeOf(obj);
	if (!proto.hasOwnProperty(relName)) fillChain(proto, relName);
	defineProperty(obj, relName, d('', obj[relName]._create_(obj)));
};

isValidNsRef = function (name) { return (name[0] !== name[0].toLowerCase()); };

findNs = function (value) {
	if (base.String && base.String.is(value)) return base.String;
	if (base.Boolean && base.Boolean.is(value)) return base.Boolean;
	if (base.Number && base.Number.is(value)) return base.Number;
	if (base.RegExp && base.RegExp.is(value)) return base.RegExp;
	if (base.DateTime && base.DateTime.is(value)) return base.DateTime;
};

define = function (obj, name) {
	var get, set, rel, relName, attr, allowNS;

	relName = '__' + name;
	allowNS = isValidNsRef(name);
	attr = ((typeof obj === 'function') || !obj._id_ || obj._descriptor_) ? '' :
			'e';
	rel = new Relation(obj, name, d.gs('c' + attr, get = function () {
		if (!this.hasOwnProperty(relName)) fillChain(this, relName);
		return this[relName].value;
	}, set = function (value) {
		var error, rel;
		if (!this.hasOwnProperty(relName)) fillChain(this, relName);
		rel = this[relName];
		if (value instanceof RelTransport) {
			if ((error = value.validate(this, name))) throw error;
			value.apply(rel);
		} else {
			rel[(!allowNS && isNamespace(value)) ? 'ns' : 'value'] = value;
		}
	}));

	defineProperty(obj, relName, d('', rel));
	defineProperty(obj, '_' + name, d.gs('', function () {
		if (!this.hasOwnProperty(relName)) fillChain(this, relName);
		return this[relName];
	}));
	defineProperty(obj, name, d.gs(attr, get, set));
};

module.exports = exports = function (obj, name, value) {
	var proto, base, rel, ns;
	if ((name in obj) && obj['__' + name]) {
		if (value instanceof RelTransport) {
			value.apply(obj['_' + name]);
		} else if (isNamespace(value) && !isValidNsRef(name)) {
			obj['_' + name]._ns.$setValue(value);
		} else {
			obj['_' + name].$setValue(value);
		}
	} else {
		base = obj;
		proto = getPrototypeOf(obj);
		while (proto.hasOwnProperty('_id_')) {
			base = proto;
			proto = getPrototypeOf(proto);
		}
		define(base, name);
		if (value instanceof RelTransport) {
			value.apply(obj['_' + name]);
		} else if (isNamespace(value) && !isValidNsRef(name)) {
			obj['_' + name]._ns.$setValue(value);
		} else if (value !== undefined) {
			rel = obj['_' + name];
			if (value !== null) {
				if (isArray(value)) {
					rel.multiple = true;
					if (value.length) {
						rel.required = true;
						if ((ns = findNs(value[0])) && value.slice(1).every(ns.is, ns)) {
							rel._ns.$setValue(ns);
						}
					}
				} else {
					rel.required = true;
					rel._ns.$setValue(findNs(value));
				}
			}
			rel.$setValue(value);
		}
	}
	return value;
};

exports.validate = function (obj, name, value) {
	var defined = (name in obj) && obj['__' + name] && true
	  , errors, error;

	if (value instanceof RelTransport) return value.validate(obj, name);
	if (isNamespace(value) && !isValidNsRef(name)) return null;
	if (defined) return obj['_' + name].validate(value);

	if (isArray(value)) {
		if ((errors = RelProto._validateValues_(value))) {
			error = new TypeError(value + " contains invalid values");
			error.errors = errors;
			return error;
		}
		return null;
	}
	return RelProto.validate(value);
};

exports.fillChain = fillChain;

Relation = require('./relation');
RelTransport = require('./rel-transport');
RelProto = Relation.prototype;
base = require('../types/base');
<|endoftext|>


<commit_before>var dpx_tests = (function() {
    var each = function(object, f) {
        for (var p in object) {
            if (object.hasOwnProperty(p)) {
                f(p, object[p]);
            }
        }
    };

    var list = function(object, f) {
        var list = [];
        each(object, function(k, v) {
            list.push(f(k, v));
        });
        return list;
    };

    var log = function(message) {
        console.log(message);
    };

    var pprint = function(list, prefix, value) {
        if (value instanceof Array) {
            list.push('[\n' + prefix + '    ');
            for (var i = 0; i < value.length; ++i) {
                pprint(list, prefix + '    ', value[i]);
                if (i < value.length - 1) {
                    list.push(',\n' + prefix + '    ');
                }
            }
            list.push('\n' + prefix + ']');
        } else if (value instanceof Object) {
            list.push('{');
            var first = true;
            each(value, function(k, v) {
                if (first) {
                    first = false;
                } else {
                    list.push(',');
                }
                list.push('\n' + prefix + "'" + k + "': ");
                pprint(list, prefix + '    ', v);
            });
            list.push('\n' + prefix + '}');
        } else if (value instanceof String) {
            list.push("'" + value + "'");
        } else {
            list.push(value);
        }
        return list.join('');
    };

    var log_call = function(dict) {
        var list = ['callbackType ' + dict['callbackType']];
        if (dict['processedForm'] !== undefined) {
            var template = dict['processedForm']['template'];
            list.push('template ' + template.number + ' ' + template.name);

            list.push('regions');
            var regions = dict['processedForm']['regions'];
            for (var i = 0; i < regions.length; ++i) {
                var region = regions[i];
                each(region, function(k, v) {
                    list.push(i + ':[' + k + ']:[' + v + ']');
                });
            }
        }
        log(list.join('\n    '));
        var ll = [];
        log(pprint(ll, '', dict));
    };

    var get_output = function() {
        return document.getElementById('output');
    };

    var remove_output = function() {
        var node = get_output();
        while (node.childNodes.length != 0) {
            node.removeChild(node.childNodes[node.childNodes.length - 1]);
        }
    };

    var create_tag = function(tag) {
        get_output().appendChild(document.createElement(tag));
    };

    var create_text = function(text) {
        get_output().appendChild(document.createTextNode(text));
    };

    var create_image = function(dpx, image) {
        var img = document.createElement('img');
        img.setAttribute('src', dpx.getDataUri(image['id']));
        get_output().appendChild(img);
        create_tag('br');
        create_text(image['width'] + 'x' + image['height']);
    };

    var show_failure = function(failure, dpx) {
        if (failure === undefined) {
            return;
        }
        create_tag('hr');
        create_text(failure);
    };

    var show_form = function(form, dpx) {
        if (form === undefined) {
            return;
        }
        var regions = form['regions'];
        for (var i = 0; i < regions.length; ++i) {
            var region = regions[i];

            create_tag('hr');
            create_text(region['processingMode'] + ' ' + region['number'] + ' ' + region['name']);
            create_tag('br');
            if (region['absoluteOcrConfidence'] !== undefined || region['absoluteOcrConfidence'] !== undefined) {
                create_text('AC: ' + region['absoluteOcrConfidence'] + ', ' + 'RC: ' + region['relativeOcrConfidence']);
                create_tag('br');
            }
            create_text(region['processedData']);
            if (region.hasOwnProperty('image')) {
                create_tag('br');
                create_image(dpx, region['image']);
            }
        }
        create_tag('hr');
        create_image(dpx, form['formCapture']['image']);
    };

    var params = {
        'template': 'file:///sdcard/templates/Logistics%20Post.xml',
        'audioFeedback': false,
        'inputSource': 'camera',
        'inputSourceFilename': '/sdcard/templates/1024w_754h_Delivery Attempt Notification.yuv',
        // 'fileInteractiveMode': false,
        'uiResultConfirmation': false
    };

    var create_dpx = function() {
        var dpx = new Rho.DPX();
        each(params, function(k, v) {
            dpx.setProperty(k, v);
        });
        return dpx;
    };

    var callback = function(dict, dpx) {
        log_call(dict);
        create_tag('hr');
        create_text('callbackType ' + dict['callbackType']);
        create_tag('br');
        show_form(dict['processedForm'], dpx);
        show_failure(dict['failureReason'], dpx);
    };

    var capture = function() {
        try {
            var dpx = create_dpx();
            dpx.setCallback(function(dict) {
                callback(dict, dpx);

                if (dict['callbackType'] === 'success' || dict['callbackType'] === 'failure') {
                    dpx.close();
                }
            });
            dpx.captureDocument();
        } catch (e) {
            log('EXCEPTION ' + e);
        }
    };

    var dpx = undefined;

    var open = function() {
        try {
            dpx = create_dpx();
            dpx.setCallback(function(dict) {
                callback(dict, dpx);
            });
        } catch (e) {
            log('EXCEPTION ' + e);
        }
    };

    var start = function() {
        try {
            dpx.captureDocument();
        } catch (e) {
            log('EXCEPTION ' + e);
        }
    };

    var close = function() {
        try {
            dpx.close();
        } catch (e) {
            log('EXCEPTION ' + e);
        }
    };

    return {
        capture: capture,
        open: open,
        start: start,
        close: close,
        clear: remove_output
    };
})();

<commit_msg>RhoDPXApp: several parameters were added.<commit_after>var dpx_tests = (function() {
    var each = function(object, f) {
        for (var p in object) {
            if (object.hasOwnProperty(p)) {
                f(p, object[p]);
            }
        }
    };

    var list = function(object, f) {
        var list = [];
        each(object, function(k, v) {
            list.push(f(k, v));
        });
        return list;
    };

    var log = function(message) {
        console.log(message);
    };

    var pprint = function(list, prefix, value) {
        if (value instanceof Array) {
            list.push('[\n' + prefix + '    ');
            for (var i = 0; i < value.length; ++i) {
                pprint(list, prefix + '    ', value[i]);
                if (i < value.length - 1) {
                    list.push(',\n' + prefix + '    ');
                }
            }
            list.push('\n' + prefix + ']');
        } else if (value instanceof Object) {
            list.push('{');
            var first = true;
            each(value, function(k, v) {
                if (first) {
                    first = false;
                } else {
                    list.push(',');
                }
                list.push('\n' + prefix + "'" + k + "': ");
                pprint(list, prefix + '    ', v);
            });
            list.push('\n' + prefix + '}');
        } else if (value instanceof String) {
            list.push("'" + value + "'");
        } else {
            list.push(value);
        }
        return list.join('');
    };

    var log_call = function(dict) {
        var list = ['callbackType ' + dict['callbackType']];
        if (dict['processedForm'] !== undefined) {
            var template = dict['processedForm']['template'];
            list.push('template ' + template.number + ' ' + template.name);

            list.push('regions');
            var regions = dict['processedForm']['regions'];
            for (var i = 0; i < regions.length; ++i) {
                var region = regions[i];
                each(region, function(k, v) {
                    list.push(i + ':[' + k + ']:[' + v + ']');
                });
            }
        }
        log(list.join('\n    '));
        var ll = [];
        log(pprint(ll, '', dict));
    };

    var get_output = function() {
        return document.getElementById('output');
    };

    var remove_output = function() {
        var node = get_output();
        while (node.childNodes.length != 0) {
            node.removeChild(node.childNodes[node.childNodes.length - 1]);
        }
    };

    var create_tag = function(tag) {
        get_output().appendChild(document.createElement(tag));
    };

    var create_text = function(text) {
        get_output().appendChild(document.createTextNode(text));
    };

    var create_image = function(dpx, image) {
        var img = document.createElement('img');
        img.setAttribute('src', dpx.getDataUri(image['id']));
        get_output().appendChild(img);
        create_tag('br');
        create_text(image['width'] + 'x' + image['height']);
    };

    var show_failure = function(failure, dpx) {
        if (failure === undefined) {
            return;
        }
        create_tag('hr');
        create_text(failure);
    };

    var show_form = function(form, dpx) {
        if (form === undefined) {
            return;
        }
        var regions = form['regions'];
        for (var i = 0; i < regions.length; ++i) {
            var region = regions[i];

            create_tag('hr');
            create_text(region['processingMode'] + ' ' + region['number'] + ' ' + region['name']);
            create_tag('br');
            if (region['absoluteOcrConfidence'] !== undefined || region['absoluteOcrConfidence'] !== undefined) {
                create_text('AC: ' + region['absoluteOcrConfidence'] + ', ' + 'RC: ' + region['relativeOcrConfidence']);
                create_tag('br');
            }
            create_text(region['processedData']);
            if (region.hasOwnProperty('image')) {
                create_tag('br');
                create_image(dpx, region['image']);
            }
        }
        create_tag('hr');
        create_image(dpx, form['formCapture']['image']);
    };

    var params = {
        'template': 'file:///sdcard/templates/Logistics%20Post.xml',

        'debug': true,

        'audioFeedback': false,
        'hapticFeedback': false,
        'ledFeedback': false,

        'flashMode': Rho.DPX.FLASH_ON,
        'inputSource': Rho.DPX.SOURCE_CAMERA,
        'inputSourceFilename': '/sdcard/templates/1024w_754h_Delivery Attempt Notification.yuv',
        'fileInteractiveMode': true, // false does not work
        'manualResolutionMode': true,
        'manualResolution': Rho.DPX.RESOLUTION_SMALL,
        'userMode': Rho.DPX.USER_MODE_SNAPSHOT,
        'zoomAmount': 100,
        'uiResultConfirmation': false
    };

    var create_dpx = function() {
        var dpx = new Rho.DPX();
        each(params, function(k, v) {
            create_text(k + ': "' + v + '"');
            create_tag('br');
            dpx.setProperty(k, v);
        });
        return dpx;
    };

    var callback = function(dict, dpx) {
        log_call(dict);
        create_tag('hr');
        create_text('callbackType ' + dict['callbackType']);
        create_tag('br');
        show_form(dict['processedForm'], dpx);
        show_failure(dict['failureReason'], dpx);
    };

    var capture = function() {
        try {
            var dpx = create_dpx();
            dpx.setCallback(function(dict) {
                callback(dict, dpx);

                if (dict['callbackType'] === 'success' || dict['callbackType'] === 'failure') {
                    dpx.close();
                }
            });
            dpx.captureDocument();
        } catch (e) {
            log('EXCEPTION ' + e);
        }
    };

    var dpx = undefined;

    var open = function() {
        try {
            dpx = create_dpx();
            dpx.setCallback(function(dict) {
                callback(dict, dpx);
            });
        } catch (e) {
            log('EXCEPTION ' + e);
        }
    };

    var start = function() {
        try {
            dpx.captureDocument();
        } catch (e) {
            log('EXCEPTION ' + e);
        }
    };

    var close = function() {
        try {
            dpx.close();
        } catch (e) {
            log('EXCEPTION ' + e);
        }
    };

    return {
        capture: capture,
        open: open,
        start: start,
        close: close,
        clear: remove_output
    };
})();

<|endoftext|>


<commit_before>//
// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//

/**
* 1. Demonstrates how to upload all files from a given directory in parallel
*
* 2. Demonstrates how to download all files from a given blob container to a given destination directory.
*
* 3. Demonstrate making requests using AccessConditions.
*/

var fs = require('fs');

var azure;
if (fs.existsSync('absolute path to azure-storage.js')) {
  azure = require('absolute path to azure-storage');
} else {
  azure = require('azure-storage');
}

var container = 'updownsample3';
var blob = 'updownsample';
var blobAccess = 'updownaccesssample';

var blobService = azure.createBlobService()
      .withFilter(new azure.ExponentialRetryPolicyFilter());

// optionally set a proxy
/*var proxy = {
  protocol: 'http:',
  host: '127.0.0.1',
  port: 8888
};

blobService.setProxy(proxy);
*/

function uploadSample() {
  var processArguments = process.argv;
  if (processArguments.length !== 4) {
    console.log('Incorrect number of arguments. Should be: srcPath destPath');
    process.exit(1);
  }

  var srcPath = processArguments[2];
  var destPath = processArguments[3];

  console.log('Starting blobuploaddownloadsample.');

  // Create the container
  createContainer(container, function () {

    // Demonstrates how to upload all files from a given directoy
    uploadBlobs(srcPath, container, function () {

      // Demonstrates how to download all files from a given
      // blob container to a given destination directory.
      downloadBlobs(container, destPath, function () {

        // Demonstrate making requests using AccessConditions.
        useAccessCondition(container, function () {

          // Delete the container
          deleteContainer(container, function () {
            console.log('Ending blobuploaddownloadsample.');
          });
        });
      });
    });
  });
}

function createContainer (container, callback) {
  // Create the container.
  blobService.createContainerIfNotExists(container, function (error) {
    if (error) {
      console.log(error);
    } else {
      console.log('Created the container ' + container);
      callback();
    }
  });
}

function uploadBlobs(sourceDirectoryPath, containerName, callback) {
  console.log('Entering uploadBlobs.');

  // validate directory is valid.
  if (!fs.existsSync(sourceDirectoryPath)) {
    console.log(sourceDirectoryPath + ' is an invalid directory path.');
  } else {
    // Search the directory and generate a list of files to upload.
    walk(sourceDirectoryPath, function (error, files) {
      if (error) {
        console.log(error);
      } else {
        var finished = 0;

        // generate and schedule an upload for each file
        files.forEach(function (file) {
          var blobName = file.replace(/^.*[\\\/]/, '');

          blobService.createBlockBlobFromLocalFile(containerName, blobName, file, function (error) {
            finished++;

            if (error) {
              console.log(error);
            } else {
              console.log(' Blob ' + blobName + ' upload finished.');

              if (finished === files.length) {
                // Wait until all workers complete and the blobs are uploaded to the server.
                console.log('All files uploaded');
                callback();
              }
            }
          });
        });
      }
    });
  }
}

function downloadBlobs(containerName, destinationDirectoryPath, callback) {
  console.log('Entering downloadBlobs.');

  // Validate directory
  if (!fs.existsSync(destinationDirectoryPath)) {
    console.log(destinationDirectoryPath + ' does not exist. Attempting to create this directory...');
    fs.mkdirSync(destinationDirectoryPath);
    console.log(destinationDirectoryPath + ' created.');
  }

  // NOTE: does not handle pagination.
  blobService.listBlobsSegmented(containerName, null, function (error, result) {
    if (error) {
      console.log(error);
    } else {
      var blobs = result.entries;
      var blobsDownloaded = 0;

      blobs.forEach(function (blob) {
          blobService.getBlobToLocalFile(containerName, blob.name, destinationDirectoryPath + '/' + blob.name, function (error2) {
          blobsDownloaded++;

          if (error2) {
            console.log(error2);
          } else {
            console.log(' Blob ' + blob.name + ' download finished.');

            if (blobsDownloaded === blobs.length) {
              // Wait until all workers complete and the blobs are downloaded
              console.log('All files downloaded');
              callback();
            }
          }
        });
      });
    }
  });
}

function useAccessCondition(containerName, callback) {
  console.log('Entering useAccessCondition.');

  // Create a blob.
  blobService.createBlockBlobFromText(containerName, blobAccess, 'hello', function (error, blobAccess) {
    if (error) {
      console.log(error);
    } else {
      console.log(' Created the blob ' + blobAccess.name);
      console.log(' Blob Etag is: ' + blobAccess.etag);

      // Use the If-not-match ETag condition to access the blob. By
      // using the IfNoneMatch condition we are asserting that the blob needs
      // to have been modified in order to complete the request. In this
      // sample no other client is accessing the blob, so this will fail as
      // expected.
      var options = { accessConditions: { EtagNonMatch: blobAccess.etag} };
      blobService.createBlockBlobFromText(containerName, blobAccess.name, 'new hello', options, function (error2) {
        if (error2 && error2.statusCode === 412 && error2.code === 'ConditionNotMet') {
          console.log('Attempted to recreate the blob with the if-none-match access condition and got the expected exception.');
          callback();
        } else {
          console.log(' Blob was incorrectly updated');
          if (error2) {
            console.log(error2);
          }
        }
      });
    }
  });
}

function deleteContainer (container, callback) {
  // Delete the container.
  blobService.deleteContainerIfExists(container, function (error) {
    if (error) {
      console.log(error);
    } else {
      console.log('Deleted the container ' + container);
      callback();
    }
  });
}

// Utility function

var walk = function (dir, done) {
  var results = [];
  fs.readdir(dir, function (err, list) {
    if (err) return done(err);
    var i = 0;
    (function next() {
      var file = list[i++];
      if (!file) return done(null, results);
      file = dir + '/' + file;
      fs.stat(file, function (err2, stat) {
        if (stat && stat.isDirectory()) {
          walk(file, function (err3, res) {
            results = results.concat(res);
            next();
          });
        } else {
          results.push(file);
          next();
        }
      });
    })();
  });
};

uploadSample();
<commit_msg>Use better name for result parameter with blob information<commit_after>//
// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//

/**
* 1. Demonstrates how to upload all files from a given directory in parallel
*
* 2. Demonstrates how to download all files from a given blob container to a given destination directory.
*
* 3. Demonstrate making requests using AccessConditions.
*/

var fs = require('fs');

var azure;
if (fs.existsSync('absolute path to azure-storage.js')) {
  azure = require('absolute path to azure-storage');
} else {
  azure = require('azure-storage');
}

var container = 'updownsample3';
var blob = 'updownsample';
var blobAccess = 'updownaccesssample';

var blobService = azure.createBlobService()
      .withFilter(new azure.ExponentialRetryPolicyFilter());

// optionally set a proxy
/*var proxy = {
  protocol: 'http:',
  host: '127.0.0.1',
  port: 8888
};

blobService.setProxy(proxy);
*/

function uploadSample() {
  var processArguments = process.argv;
  if (processArguments.length !== 4) {
    console.log('Incorrect number of arguments. Should be: srcPath destPath');
    process.exit(1);
  }

  var srcPath = processArguments[2];
  var destPath = processArguments[3];

  console.log('Starting blobuploaddownloadsample.');

  // Create the container
  createContainer(container, function () {

    // Demonstrates how to upload all files from a given directoy
    uploadBlobs(srcPath, container, function () {

      // Demonstrates how to download all files from a given
      // blob container to a given destination directory.
      downloadBlobs(container, destPath, function () {

        // Demonstrate making requests using AccessConditions.
        useAccessCondition(container, function () {

          // Delete the container
          deleteContainer(container, function () {
            console.log('Ending blobuploaddownloadsample.');
          });
        });
      });
    });
  });
}

function createContainer (container, callback) {
  // Create the container.
  blobService.createContainerIfNotExists(container, function (error) {
    if (error) {
      console.log(error);
    } else {
      console.log('Created the container ' + container);
      callback();
    }
  });
}

function uploadBlobs(sourceDirectoryPath, containerName, callback) {
  console.log('Entering uploadBlobs.');

  // validate directory is valid.
  if (!fs.existsSync(sourceDirectoryPath)) {
    console.log(sourceDirectoryPath + ' is an invalid directory path.');
  } else {
    // Search the directory and generate a list of files to upload.
    walk(sourceDirectoryPath, function (error, files) {
      if (error) {
        console.log(error);
      } else {
        var finished = 0;

        // generate and schedule an upload for each file
        files.forEach(function (file) {
          var blobName = file.replace(/^.*[\\\/]/, '');

          blobService.createBlockBlobFromLocalFile(containerName, blobName, file, function (error) {
            finished++;

            if (error) {
              console.log(error);
            } else {
              console.log(' Blob ' + blobName + ' upload finished.');

              if (finished === files.length) {
                // Wait until all workers complete and the blobs are uploaded to the server.
                console.log('All files uploaded');
                callback();
              }
            }
          });
        });
      }
    });
  }
}

function downloadBlobs(containerName, destinationDirectoryPath, callback) {
  console.log('Entering downloadBlobs.');

  // Validate directory
  if (!fs.existsSync(destinationDirectoryPath)) {
    console.log(destinationDirectoryPath + ' does not exist. Attempting to create this directory...');
    fs.mkdirSync(destinationDirectoryPath);
    console.log(destinationDirectoryPath + ' created.');
  }

  // NOTE: does not handle pagination.
  blobService.listBlobsSegmented(containerName, null, function (error, result) {
    if (error) {
      console.log(error);
    } else {
      var blobs = result.entries;
      var blobsDownloaded = 0;

      blobs.forEach(function (blob) {
          blobService.getBlobToLocalFile(containerName, blob.name, destinationDirectoryPath + '/' + blob.name, function (error2) {
          blobsDownloaded++;

          if (error2) {
            console.log(error2);
          } else {
            console.log(' Blob ' + blob.name + ' download finished.');

            if (blobsDownloaded === blobs.length) {
              // Wait until all workers complete and the blobs are downloaded
              console.log('All files downloaded');
              callback();
            }
          }
        });
      });
    }
  });
}

function useAccessCondition(containerName, callback) {
  console.log('Entering useAccessCondition.');

  // Create a blob.
  blobService.createBlockBlobFromText(containerName, blobAccess, 'hello', function (error, blobInformation) {
    if (error) {
      console.log(error);
    } else {
      console.log(' Created the blob ' + blobInformation.name);
      console.log(' Blob Etag is: ' + blobInformation.etag);

      // Use the If-not-match ETag condition to access the blob. By
      // using the IfNoneMatch condition we are asserting that the blob needs
      // to have been modified in order to complete the request. In this
      // sample no other client is accessing the blob, so this will fail as
      // expected.
      var options = { accessConditions: { EtagNonMatch: blobInformation.etag} };
      blobService.createBlockBlobFromText(containerName, blobInformation.name, 'new hello', options, function (error2) {
        if (error2 && error2.statusCode === 412 && error2.code === 'ConditionNotMet') {
          console.log('Attempted to recreate the blob with the if-none-match access condition and got the expected exception.');
          callback();
        } else {
          console.log(' Blob was incorrectly updated');
          if (error2) {
            console.log(error2);
          }
        }
      });
    }
  });
}

function deleteContainer (container, callback) {
  // Delete the container.
  blobService.deleteContainerIfExists(container, function (error) {
    if (error) {
      console.log(error);
    } else {
      console.log('Deleted the container ' + container);
      callback();
    }
  });
}

// Utility function

var walk = function (dir, done) {
  var results = [];
  fs.readdir(dir, function (err, list) {
    if (err) return done(err);
    var i = 0;
    (function next() {
      var file = list[i++];
      if (!file) return done(null, results);
      file = dir + '/' + file;
      fs.stat(file, function (err2, stat) {
        if (stat && stat.isDirectory()) {
          walk(file, function (err3, res) {
            results = results.concat(res);
            next();
          });
        } else {
          results.push(file);
          next();
        }
      });
    })();
  });
};

uploadSample();
<|endoftext|>


<commit_before>/**
 * The Feed view.
 */
define([
  'jquery',
  'backbone',
  'underscore',
  'mps',
  'handlebars',
  'text!landing/templates/feed.handlebars',

], function($, Backbone, _, mps, Handlebars, tpl) {

  'use strict';

  var FeedView = Backbone.View.extend({

    el: '#feedView',

    template: Handlebars.compile(tpl),

    initialize: function() {
      this.loadFeed();
    },

    render: function() {
      this.$el.html(this.template({feed: this.feedlist}));
    },

    loadFeed: function() {
      $.ajax({
        url: 'https://pipes.yahoo.com/pipes/pipe.run?_id=5bc0b70181e4954888ddc8fb05598fa2&_render=json',
        type:'GET',
        success: _.bind(function(data){
          this.parse(data.value.items);
        },this)
      })
    },

    parse: function(data) {
      console.log(data)
      this.feedlist = _.map(data,_.bind(function(item){
        var result = null;
        if(item.cartodb_id){
          result = this.parseItem(item,'story');
        }else if(item.feed){
          result = this.parseItem(item,'disqus');
        }else if(item.guid){
          result = this.parseItem(item,'blog');
        }else{
          result = item;
        }
        return result;
      },this));
      this.feedlist = _.first(this.feedlist.sort(_.bind(function(a,b){
        return b.createDate - a.createDate;
      },this)),6);

      this.render();

    },

    parseItem: function(item,slug) {
      switch(slug){
        case 'story':
          return {
            author: item.author,
            createDate: this.parseDate(item.pubDate),
            description: 'added a new story',
            link: '/stories/'+item.cartodb_id,
            target: false,
            type: slug
          }
        break;
        case 'disqus':
          return {
            author: item.author,
            createDate: this.parseDate(item.pubDate),
            description: 'added a comment',
            link: item.link,
            target:true,
            type: slug
          }
        break;
        case 'blog':
          return{
            author: item['dc:creator'],
            createDate: this.parseDate(item.pubDate),
            description: 'added a new post in blog',
            link: item.link,
            target:true,
            type: slug
          }
        break;
      }
    },

    parseDate: function(date) {
      var moment = new Date(date);
      return moment.getTime();
    }

  });
  return FeedView;

});
<commit_msg>Cleaning<commit_after>/**
 * The Feed view.
 */
define([
  'jquery',
  'backbone',
  'underscore',
  'mps',
  'handlebars',
  'text!landing/templates/feed.handlebars',

], function($, Backbone, _, mps, Handlebars, tpl) {

  'use strict';

  var FeedView = Backbone.View.extend({

    el: '#feedView',

    template: Handlebars.compile(tpl),

    initialize: function() {
      this.loadFeed();
    },

    render: function() {
      this.$el.html(this.template({feed: this.feedlist}));
    },

    loadFeed: function() {
      $.ajax({
        url: 'https://pipes.yahoo.com/pipes/pipe.run?_id=5bc0b70181e4954888ddc8fb05598fa2&_render=json',
        type:'GET',
        success: _.bind(function(data){
          this.parse(data.value.items);
        },this)
      })
    },

    parse: function(data) {
      this.feedlist = _.map(data,_.bind(function(item){
        var result = null;
        if(item.cartodb_id){
          result = this.parseItem(item,'story');
        }else if(item.feed){
          result = this.parseItem(item,'disqus');
        }else if(item.guid){
          result = this.parseItem(item,'blog');
        }else{
          result = item;
        }
        return result;
      },this));
      this.feedlist = _.first(this.feedlist.sort(_.bind(function(a,b){
        return b.createDate - a.createDate;
      },this)),6);

      this.render();

    },

    parseItem: function(item,slug) {
      switch(slug){
        case 'story':
          return {
            author: item.author,
            createDate: this.parseDate(item.pubDate),
            description: 'added a new story',
            link: '/stories/'+item.cartodb_id,
            target: false,
            type: slug
          }
        break;
        case 'disqus':
          return {
            author: item.author,
            createDate: this.parseDate(item.pubDate),
            description: 'added a comment',
            link: item.link,
            target:true,
            type: slug
          }
        break;
        case 'blog':
          return{
            author: item['dc:creator'],
            createDate: this.parseDate(item.pubDate),
            description: 'added a new post in blog',
            link: item.link,
            target:true,
            type: slug
          }
        break;
      }
    },

    parseDate: function(date) {
      var moment = new Date(date);
      return moment.getTime();
    }

  });
  return FeedView;

});
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    _ = require('lodash'),
    User = mongoose.model('User'),
    Email = mongoose.model('Email'),
    errorHandler = require('./errors'),
    fs = require('fs'),
    path = require('path');

/**
 * Return image to the requester.  If rid and uemail are specified, the entry in the
 * recruiter's inviteeList/attendeeList will be updated to show the invitee has read
 * their invitation.
 *
 * @param rid _id field of recruiter that sent the invitation
 * @param uemail email of the user that received the invitation
 * @param eid _id field of event for which the invitation was sent
 */
exports.sendImage = function(req, res) {
	if(req.query.eid) {
		//Send the image immediately.
		var filepath;
		if(req.query.image) {
			filepath = path.join(__dirname, "..", "..", "public/modules/core/img/email/", req.query.image);
		} else {
			filepath = path.join(__dirname, "..", "..", "public/modules/core/img/email/logo.png");
		}
		var fileStats = fs.statSync(filepath);

		res.writeHead(200, {
			'Content-Type' : 'image/gif',
			'Content-Length' : fileStats.size
		});

		var readStream = fs.createReadStream(filepath);
		readStream.pipe(res);

		//Update email entry for this email.
		var email_id = mongoose.Types.ObjectId(req.query.eid);
		Email.findOne({_id : email_id}, function(err, email) {
			if(!err) {
				if(email) {
					email.read = true;
					email.save(function(err) {
						if(err) {
							console.log("Error updating emails for record " + email._id.toString());
						}
					});
				} else {
					console.log("Email document not found for " + req.query.eid);
				}
			} else {
				console.log("Error2 updating emails for record " + email._id.toString());
			}
		});
	} else {
		//Just return the frank logo.
		var filepath = path.join(__dirname, "..", "..", "public/modules/core/img/email/logo.png");
		var fileStats = fs.statSync(filepath);

		res.writeHead(200, {
			'Content-Type' : 'image/gif',
			'Content-Length' : fileStats.size
		});

		var readStream = fs.createReadStream(filepath);
		readStream.pipe(res);
	}
};<commit_msg>Updated comments.<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    _ = require('lodash'),
    User = mongoose.model('User'),
    Email = mongoose.model('Email'),
    errorHandler = require('./errors'),
    fs = require('fs'),
    path = require('path');

/**
 * Return image to the requester.  If eid is not specified, either the specified image or the default
 * image will be returned.  The default image is the logo.png image located in
 * public/modules/core/img/email.
 *
 * @param eid _id	field of email document to update
 * @param image 	file to return
 */
exports.sendImage = function(req, res) {
	if(req.query.eid) {
		//Send the image immediately.
		var filepath;
		if(req.query.image) {
			filepath = path.join(__dirname, "..", "..", "public/modules/core/img/email/", req.query.image);
		} else {
			filepath = path.join(__dirname, "..", "..", "public/modules/core/img/email/logo.png");
		}
		var fileStats = fs.statSync(filepath);

		res.writeHead(200, {
			'Content-Type' : 'image/gif',
			'Content-Length' : fileStats.size
		});

		var readStream = fs.createReadStream(filepath);
		readStream.pipe(res);

		//Update email entry for this email.
		var email_id = mongoose.Types.ObjectId(req.query.eid);
		Email.findOne({_id : email_id}, function(err, email) {
			if(!err) {
				if(email) {
					email.read = true;
					email.save(function(err) {
						if(err) {
							console.log("Error updating emails for record " + email._id.toString());
						}
					});
				} else {
					console.log("Email document not found for " + req.query.eid);
				}
			} else {
				console.log("Error2 updating emails for record " + email._id.toString());
			}
		});
	} else {
		//Just return the frank logo.
		var filepath;
		if(req.query.image) {
			filepath = path.join(__dirname, "..", "..", "public/modules/core/img/email/", req.query.image);
		} else {
			filepath = path.join(__dirname, "..", "..", "public/modules/core/img/email/logo.png");
		}
		var fileStats = fs.statSync(filepath);

		res.writeHead(200, {
			'Content-Type' : 'image/gif',
			'Content-Length' : fileStats.size
		});

		var readStream = fs.createReadStream(filepath);
		readStream.pipe(res);
	}
};<|endoftext|>


<commit_before>#!/usr/bin/env node

var program = require('commander');

program
  .version('1.0.0')
  .option('-p, --production', 'production')
  .option('-a, --appId <appId>', 'appId')
  .option('-j, --jsKey <jsKey>', 'jsKey')
  .option('-m, --masterKey <masterKey>', 'masterKey')
  //.option('-d, --debug', 'Show debug messages')
  //.option('-i, --info', 'Show info only')
  //.option('-vv, --verbose', 'Show more messages')
  //.option('--years_ago <YEARS_AGO>', 'sync <YEARS_AGO> today 00:00:00 in user\'s timezone')
  .option('-d, --days <days>', 'Process <days> ago until now')
  //.option('--since <SINCE>', 'A Unix timestamp or strtotime data value that points to the start of the range of time-based data')
  //.option('--until <UNTIL>', 'A Unix timestamp or strtotime data value that points to the end of the range of time-based data')
  //.option('--location', 'sync only location posts')
  .option('--url <url>', 'Specifiy parse api url')
  .option('-f, --config <config>', 'Specifiy config path')
  .parse(process.argv);

var appId = program.appId ? program.appId : process.env.APP_ID;
var jsKey = program.jsKey ? program.jsKey : process.env.JS_KEY;
var masterKey = program.masterKey ? program.masterKey : process.env.MASTER_KEY;
var user = program.user ? program.user : process.env.PARSE_USER;
var url = program.url;
var days = program.days;

var configPath = program.config ? program.config : process.env.HOME + '/.parse/' + 'config.json'; // $ docker-parse list 8tory_dev
var config = hasFile(configPath) ? require(configPath) : null;

if (config) {
  if (program.production) {
    appId     = appId ? appId : config.production.appId;
    jsKey     = jsKey ? jsKey : config.production.jsKey;
    masterKey = masterKey ? masterKey : config.production.masterKey;
    url = url ? url : config.production.url;
  } else {
    appId     = appId ? appId : config.dev.appId;
    jsKey     = jsKey ? jsKey : config.dev.jsKey;
    masterKey = masterKey ? masterKey : config.dev.masterKey;
    url = url ? url : config.dev.url;
  }
}

// TODO fatal error and exit
if (!appId) {
  console.error('missing appId');
  process.exit();
}
if (!jsKey) {
  console.error('missing jsKey');
  process.exit();
}
if (!masterKey) {
  console.error('missing masterKey');
}
//if (!url) console.error('missing server url');

console.log(appId);
console.log(jsKey);
console.log(masterKey);
console.log(url);

var Parse = require('parse/node').Parse;
var Rx = require('rx');
var Parses = require('./parses');

if (url) Parse.serverURL = url;
Parse.initialize(appId, jsKey, masterKey);
if (masterKey) Parse.Cloud.useMasterKey();

var query = new Parse.Query("User");
if (days) {
  query.ascending('createdAt');
  var daysAgo = new Date();
  daysAgo.setDate(daysAgo.getDate() - days);
  query.greaterThanOrEqualTo('createdAt', daysAgo);
}

Parses.allAsc(query).distinct(function (it) { return it.id; }).flatMap(function (it) {
  var adds = ['test', 'test2'];
  var from = it.get('tagList');
  console.log(from);
  for (var i = 0; i < adds.length; ++i) {
    if (!~from.indexOf(adds[i])) it.addUnique('tagList', adds[i]); // addUnique(key, item)
  }
  var to = it.get('tagList');
  console.log(to);
  console.log(it.dirty());
  return Rx.Observable.just(it);
}).doOnNext(function(user) {
  console.log(user.get('email'));
}).subscribe(function (it) {
  console.log(it.get('createdAt'));
});

function hasFile(f) {
  var fs = require('fs');
  var b = false;
  try {
    b = fs.statSync(f).isFile();
  } catch (e) {
  }
  return b;
}

/* vim: set sw=2: */
<commit_msg>Refine emails.js<commit_after>#!/usr/bin/env node

var program = require('commander');

program
  .version('1.0.0')
  .option('-p, --production', 'production')
  .option('-a, --appId <appId>', 'appId')
  .option('-j, --jsKey <jsKey>', 'jsKey')
  .option('-m, --masterKey <masterKey>', 'masterKey')
  //.option('-d, --debug', 'Show debug messages')
  //.option('-i, --info', 'Show info only')
  //.option('-vv, --verbose', 'Show more messages')
  //.option('--years_ago <YEARS_AGO>', 'sync <YEARS_AGO> today 00:00:00 in user\'s timezone')
  .option('-d, --days <days>', 'Process <days> ago until now')
  //.option('--since <SINCE>', 'A Unix timestamp or strtotime data value that points to the start of the range of time-based data')
  //.option('--until <UNTIL>', 'A Unix timestamp or strtotime data value that points to the end of the range of time-based data')
  //.option('--location', 'sync only location posts')
  .option('--url <url>', 'Specifiy parse api url')
  .option('-f, --config <config>', 'Specifiy config path')
  .parse(process.argv);

var appId = program.appId ? program.appId : process.env.APP_ID;
var jsKey = program.jsKey ? program.jsKey : process.env.JS_KEY;
var masterKey = program.masterKey ? program.masterKey : process.env.MASTER_KEY;
var user = program.user ? program.user : process.env.PARSE_USER;
var url = program.url;
var days = program.days;

var configPath = program.config ? program.config : process.env.HOME + '/.parse/' + 'config.json'; // $ docker-parse list 8tory_dev
var config = hasFile(configPath) ? require(configPath) : null;

if (config) {
  if (program.production) {
    appId     = appId ? appId : config.production.appId;
    jsKey     = jsKey ? jsKey : config.production.jsKey;
    masterKey = masterKey ? masterKey : config.production.masterKey;
    url = url ? url : config.production.url;
  } else {
    appId     = appId ? appId : config.dev.appId;
    jsKey     = jsKey ? jsKey : config.dev.jsKey;
    masterKey = masterKey ? masterKey : config.dev.masterKey;
    url = url ? url : config.dev.url;
  }
}

// TODO fatal error and exit
if (!appId) {
  console.error('missing appId');
  process.exit();
}
if (!jsKey) {
  console.error('missing jsKey');
  process.exit();
}
if (!masterKey) {
  console.error('missing masterKey');
}
//if (!url) console.error('missing server url');

console.log(appId);
console.log(jsKey);
console.log(masterKey);
console.log(url);

var Parse = require('parse/node').Parse;
var Rx = require('rx');
var Parses = require('./parses');

if (url) Parse.serverURL = url;
Parse.initialize(appId, jsKey, masterKey);
if (masterKey) Parse.Cloud.useMasterKey();

var query = new Parse.Query("User");
if (days) {
  query.ascending('createdAt');
  var daysAgo = new Date();
  daysAgo.setDate(daysAgo.getDate() - days);
  query.greaterThanOrEqualTo('createdAt', daysAgo);
}

Parses.allAsc(query)
  .doOnNext(function(user) {
    console.log(user.get('email'));
  }).subscribe(function (it) {
    console.log(it.get('createdAt'));
  });

function hasFile(f) {
  var fs = require('fs');
  var b = false;
  try {
    b = fs.statSync(f).isFile();
  } catch (e) {
  }
  return b;
}

/* vim: set sw=2: */
<|endoftext|>


<commit_before>// 1. basic template parse with es6 template literal tag function
function getFullString(strings, ...interpolatedValues) { // `...` essentially slices the arguments for us.
  return strings.reduce((total, current, index) => { // use an arrow function for brevity here
    total += current;
    print('index: ' + index + ' | current: ' + current);

    if (interpolatedValues.hasOwnProperty(index)) {
      total += interpolatedValues[index];
      print("interpolatedValues[index]: " + interpolatedValues[index]);
    }
    return total;
  }, '');
}

const sb = 'SB',
  sbn = 'n-SB',
  sbs = 'SBS';
getFullString `basic template: Hello
${`nested template: ${sbn}`} and and ${sbs}`;

/*
 * 3. cleaner decoupled template fragments
 */

const capitalize = (string) => {
  return string[0].toUpperCase() + string.slice(1).toUpperCase();
};

const deleteBtn = ({person, isAdmin}) => {
    return isAdmin ? `<button>Delete ${capitalize(person)}</button>`: '';
};

const pplItem = ({person, isAdmin}) => {
  return `

      ${capitalize(person)}
      ${deleteBtn({person, isAdmin})}

`;
};

const pplList = ({people, isAdmin}) => {
  return `

    ${people.map(person => `${pplItem({person, isAdmin})}`)}

`;
};

const page3 = ({ people, isAdmin }) => {
  return `
People

    ${pplList({ people, isAdmin })}`;
};

appendToBody(page3({ people: ['Keith', 'Dave', 'Amy' ], isAdmin: true }));
<commit_msg>clean<commit_after>/**
 * 1. basic template parse with es6 template literal tag function
 */
function getFullString(strings, ...interpolatedValues) { // `...` essentially slices the arguments for us.
  return strings.reduce((total, current, index) => { // use an arrow function for brevity here
    total += current;
    print('index: ' + index + ' | current: ' + current);

    if (interpolatedValues.hasOwnProperty(index)) {
      total += interpolatedValues[index];
      print("interpolatedValues[index]: " + interpolatedValues[index]);
    }
    return total;
  }, '');
}

const sb = 'SB',
  sbn = 'n-SB',
  sbs = 'SBS';
getFullString `basic template: Hello
${`nested template: ${sbn}`} and and ${sbs}`;

/**
 * 2. cleaner decoupled template fragments
 */
const capitalize = (string) => {
  return string[0].toUpperCase() + string.slice(1).toUpperCase();
};

const deleteBtn = ({person, isAdmin}) => {
    return isAdmin ? `<button>Delete ${capitalize(person)}</button>`: '';
};

const pplItem = ({person, isAdmin}) => {
  return `

      ${capitalize(person)}
      ${deleteBtn({person, isAdmin})}

`;
};

const pplList = ({people, isAdmin}) => {
  return `

    ${people.map(person => `${pplItem({person, isAdmin})}`)}

`;
};

const page3 = ({ people, isAdmin }) => {
  return `
People

    ${pplList({ people, isAdmin })}`;
};

appendToBody(page3({ people: ['Keith', 'Dave', 'Amy' ], isAdmin: true }));
<|endoftext|>


<commit_before>/*
 *  Copyright 2014 TWO SIGMA INVESTMENTS, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
/**
 * This plugins menu items for the control panel
 */
(function () {
    'use strict';
    var load = function (path) {
        var deferred = bkHelper.newDeferred();
        bkHelper.httpGet("/beaker/rest/fileio/load", {path: path}).
            success(function (data) {
                deferred.resolve(data);
            }).
            error(function (data, status, header, config) {
                deferred.reject(data, status, header, config);
            });
        return deferred.promise;
    };
    var save = function (path, json) {
        var deferred = bkHelper.newDeferred();
        bkHelper.httpPost("/beaker/rest/fileio/save", {path: path, content: json}).
            success(function (data) {
                bkHelper.setNotebookUrl(path);
                deferred.resolve(data);
            }).
            error(function (data, status, header, config) {
                deferred.reject(data, status, header, config);
            });
        return deferred.promise;
    };

    var errorHandler = function (data, status, headers, config) {
        bkHelper.showErrorModal(data);
        bkHelper.refreshRootScope();
    };

    bkHelper.registerSaveFunc("file", function (path, notebookModel) {
        var notebookJson = bkHelper.toPrettyJson(notebookModel);
        return save(path, notebookJson);
    });

    var openURI_filesys = function (path) {
        console.log("openURI_filesys", path);
        if (!path) {
            return;
        }
        load(path).then(function (ret) {
            var notebookJson = ret.value;
            bkHelper.loadNotebook(notebookJson, true, path);
            bkHelper.setSaveFunction(function (notebookModel) {
                return save(path, bkHelper.toPrettyJson(notebookModel));
            });
            bkHelper.evaluate("initialization");
        }, errorHandler);
    };
    bkHelper.setPathOpener("file", {
        open: function (url) {
            openURI_filesys(url);
        }
    });

    var fileMenuItems = [
        {
            name: "New",
            tooltip: "Open a new notebook with default languages(Evaluators)",
            action: function () {
                bkHelper.newSession();
            }
        },
        {
            name: "Open recent",
            items: function () {
                return bkHelper.getRecentMenuItems();
            }
        }
    ];
    var helpMenuItems = [
        {
            name: "Tutorial notebook",
            action: function () {
                bkHelper.openURI("file:config/tutorial.bkr");
            },
            tooltip: "Open the tutorial notebook"
        },
        {
            name: "Keyboard Shortcuts...",
            action: function () {
                window.open("./keyboardShortcuts.html");
            },
            tooltip: "Show keyboard shortcuts"
        }
    ];
    bkHelper.httpGet("/beaker/rest/fileio/getHomeDirectory").success(function (ret) {
        var homeDir = ret.value;
        var fileChooserStrategy = { result: "" };
        fileChooserStrategy.close = function (ev, closeFunc) {
            if (ev.which === 13) {
                closeFunc(this.result);
            }
        };
        fileChooserStrategy.treeViewfs = { // file service
            getChildren: function (path, callback) {
                var self = this;
                this.showSpinner = true;
                $http({
                    method: 'GET',
                    url: "/beaker/rest/fileio/getDecoratedChildren",
                    params: {
                        path: path
                    }
                }).success(function (list) {
                        self.showSpinner = false;
                        console.log(list);
                        callback(list);
                    }).error(function () {
                        self.showSpinner = false;
                        console.log("Error loading children");
                    });
            },
            open: function (path) {
                fileChooserStrategy.result = path;
            },
            showSpinner: false
        };
        var toAdd = [
            { parent: "File", items: fileMenuItems },
            {
                parent: "File",
                submenu: "Open",
                items: [
                    {
                        name: "Open... (File)",
                        tooltip: "Open a file from file system",
                        action: function () {
                            bkHelper.showFileChooser(
                                bkHelper.openURI,
                                '
' +
                                    '
Open
' +
                                    '
' +
                                    '
' +
                                    '   <tree-view rooturi="/" fs="getStrategy().treeViewfs"></tree-view>' +
                                    '   <tree-view rooturi="' + homeDir + '" fs="getStrategy().treeViewfs"></tree-view>' +
                                    '
' +
                                    '
' +
                                    '
<input id="openFileInput" class="input-xxlarge" ng-model="getStrategy().result" ng-keypress="getStrategy().close($event, close)" focus-start />
' +
                                    '   <button ng-click="close()" class="btn">Cancel</button>' +
                                    '   <button ng-click="close(getStrategy().result)" class="btn btn-primary">Open</button>' +
                                    '
', // template
                                fileChooserStrategy// strategy
                            );
                        }
                    }
                ]
            },
            { parent: "Help", items: helpMenuItems }
        ];
        pluginObj.onReady(toAdd);
    });
})();
<commit_msg>Make file opened from control panel menu change the title text<commit_after>/*
 *  Copyright 2014 TWO SIGMA INVESTMENTS, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
/**
 * This plugins menu items for the control panel
 */
(function () {
    'use strict';
    var load = function (path) {
        var deferred = bkHelper.newDeferred();
        bkHelper.httpGet("/beaker/rest/fileio/load", {path: path}).
            success(function (data) {
                deferred.resolve(data);
            }).
            error(function (data, status, header, config) {
                deferred.reject(data, status, header, config);
            });
        return deferred.promise;
    };
    var save = function (path, json) {
        var deferred = bkHelper.newDeferred();
        bkHelper.httpPost("/beaker/rest/fileio/save", {path: path, content: json}).
            success(function (data) {
                bkHelper.setNotebookUrl(path);
                deferred.resolve(data);
            }).
            error(function (data, status, header, config) {
                deferred.reject(data, status, header, config);
            });
        return deferred.promise;
    };

    var errorHandler = function (data, status, headers, config) {
        bkHelper.showErrorModal(data);
        bkHelper.refreshRootScope();
    };

    bkHelper.registerSaveFunc("file", function (path, notebookModel) {
        var notebookJson = bkHelper.toPrettyJson(notebookModel);
        return save(path, notebookJson);
    });

    var openURI_filesys = function (path) {
        console.log("openURI_filesys", path);
        if (!path) {
            return;
        }
        load(path).then(function (ret) {
            var notebookJson = ret.value;
            bkHelper.loadNotebook(notebookJson, true, path);
            bkHelper.setSaveFunction(function (notebookModel) {
                return save(path, bkHelper.toPrettyJson(notebookModel));
            });
            bkHelper.evaluate("initialization");
            document.title = path.replace(/^.*[\\\/]/, '');
        }, errorHandler);
    };
    bkHelper.setPathOpener("file", {
        open: function (url) {
            openURI_filesys(url);
        }
    });

    var fileMenuItems = [
        {
            name: "New",
            tooltip: "Open a new notebook with default languages(Evaluators)",
            action: function () {
                bkHelper.newSession();
            }
        },
        {
            name: "Open recent",
            items: function () {
                return bkHelper.getRecentMenuItems();
            }
        }
    ];
    var helpMenuItems = [
        {
            name: "Tutorial notebook",
            action: function () {
                bkHelper.openURI("file:config/tutorial.bkr");
            },
            tooltip: "Open the tutorial notebook"
        },
        {
            name: "Keyboard Shortcuts...",
            action: function () {
                window.open("./keyboardShortcuts.html");
            },
            tooltip: "Show keyboard shortcuts"
        }
    ];
    bkHelper.httpGet("/beaker/rest/fileio/getHomeDirectory").success(function (ret) {
        var homeDir = ret.value;
        var fileChooserStrategy = { result: "" };
        fileChooserStrategy.close = function (ev, closeFunc) {
            if (ev.which === 13) {
                closeFunc(this.result);
            }
        };
        fileChooserStrategy.treeViewfs = { // file service
            getChildren: function (path, callback) {
                var self = this;
                this.showSpinner = true;
                $http({
                    method: 'GET',
                    url: "/beaker/rest/fileio/getDecoratedChildren",
                    params: {
                        path: path
                    }
                }).success(function (list) {
                        self.showSpinner = false;
                        console.log(list);
                        callback(list);
                    }).error(function () {
                        self.showSpinner = false;
                        console.log("Error loading children");
                    });
            },
            open: function (path) {
                fileChooserStrategy.result = path;
            },
            showSpinner: false
        };
        var toAdd = [
            { parent: "File", items: fileMenuItems },
            {
                parent: "File",
                submenu: "Open",
                items: [
                    {
                        name: "Open... (File)",
                        tooltip: "Open a file from file system",
                        action: function () {
                            bkHelper.showFileChooser(
                                bkHelper.openURI,
                                '
' +
                                    '
Open
' +
                                    '
' +
                                    '
' +
                                    '   <tree-view rooturi="/" fs="getStrategy().treeViewfs"></tree-view>' +
                                    '   <tree-view rooturi="' + homeDir + '" fs="getStrategy().treeViewfs"></tree-view>' +
                                    '
' +
                                    '
' +
                                    '
<input id="openFileInput" class="input-xxlarge" ng-model="getStrategy().result" ng-keypress="getStrategy().close($event, close)" focus-start />
' +
                                    '   <button ng-click="close()" class="btn">Cancel</button>' +
                                    '   <button ng-click="close(getStrategy().result)" class="btn btn-primary">Open</button>' +
                                    '
', // template
                                fileChooserStrategy// strategy
                            );
                        }
                    }
                ]
            },
            { parent: "Help", items: helpMenuItems }
        ];
        pluginObj.onReady(toAdd);
    });
})();
<|endoftext|>