<commit_before>var isReady=false;
this.socket.on("nameerror",function(){
	document.getElementById("tips").innerHTML="你输入的昵称已经有人在用了";
});

this.socket.on("loginsuccess",function(){
	var p=new Player(new Position(300,300),0,document.getElementById("text").value,0);
	e.Players.push(p);
	isReady=true;
	document.getElementById("ipt").style.display="none";
	e.canvas.style.display="block";
	e.run();
});

this.socket.on("getInfo",function(pos,sprite,socekt_index,name,left,right){
	if(isReady){
		for(var i=0;i<e.Players.length;i++){
			if(e.Players[i].name==name){
				e.Players[i].position=pos;
				e.Players[i].sprite=e.Resource.pic[sprite];
				e.Players[i].left=left;
				e.Players[i].right=right;
				if(sprite==7||sprite==14)
					e.Players[i].col_height=18;
				else
					e.Players[i].col_height=28;
				return;
			}
		}
		e.Players.push(new Player(pos,sprite,name,socekt_index));
	}
});

this.socket.on("pushPlayer",function(name,dir){
	if(e.Players[0].name==name){
		e.Players[0].push(dir);
	}
})<commit_msg>update net.js<commit_after>var isReady=false;
this.socket.on("nameerror",function(){
	document.getElementById("tips").innerHTML="你输入的昵称已经有人在用了";
});

this.socket.on("loginsuccess",function(level,time,pc){
	var p=new Player(new Position(maps[e.level].startpos.x,maps[e.level].startpos.y),0,document.getElementById("text").value,0);
	e.Players.push(p);
	isReady=true;
	document.getElementById("ipt").style.display="none";
	e.canvas.style.display="block";
	e.level=level;
	e.time=time;
	e.playercount=pc;
	e.run();
});

this.socket.on("getInfo",function(pos,sprite,socekt_index,name,left,right){
	if(isReady){
		for(var i=0;i<e.Players.length;i++){
			if(e.Players[i].name==name){
				e.Players[i].position=pos;
				e.Players[i].sprite=e.Resource.pic[sprite];
				e.Players[i].left=left;
				e.Players[i].right=right;
				if(sprite==7||sprite==14)
					e.Players[i].col_height=18;
				else
					e.Players[i].col_height=28;
				return;
			}
		}
		e.Players.push(new Player(pos,sprite,name,e.Players.length));
	}
});

this.socket.on("timecount",function(time,pc){
	e.time=time;
	e.playercount=pc;
})

this.socket.on("pushPlayer",function(name,dir){
	if(e.Players[0].name==name){
		e.Players[0].push(dir);
	}
})

this.socket.on("Playerup",function(name,spd){
	if(e.Players[0].name==name){
		e.Players[0].vv=spd;
	}
});

this.socket.on("logout",function(name){
	for(var i=0;i<e.Players.length;i++){
		if(e.Players[i].name==name){
			e.Players.splice(i,1);
		}
	}
});

this.socket.on("check",function(Player){
	e.ischeck=true;
});

this.socket.on("bethrow",function(name,dir){
	if(e.Players[0].name==name){
		e.Players[0].bethrow(dir);
	}
});

this.socket.on("changemap",function(level){
	e.level=level;
	console.log(e.level);
	console.log(maps[e.level]);
	e.Cubes=maps[e.level].Cubes;
});<|endoftext|>


<commit_before>var THREE = require('THREE'),
    us = require('lodash');

var FRAME = 1e3/60;

function docToBoxes(Canvas, LDoc){

  var boxes = [],
      rem = LDoc.typography.base,
      regionCursors = {};

  us.each(LDoc.segments, function(segment, i){

    if(us.has(segment, 'page')){

      var allMargins = 2 * segment.page['min-horizontal-margin'] * rem,
          vMargin = segment.page['vertical-margin'] * rem,
          pageMaxHeight = segment.page['max-height'] * rem,
          colMinWidth = segment.page.columns['min-width'] * rem,
          colMaxWidth = segment.page.columns['max-width'] * rem,
          modMinHeight = segment.page.modules['min-height'] * rem,
          colGutter = segment.page.columns.gutter * rem,
          modGutter = segment.page.modules.gutter * rem;

      var maxPageWidth = segment.page['max-columns'] * colMaxWidth
            + (segment.page['max-columns'] - 1) * colGutter
            + allMargins,
          minPageWidth = segment.page['min-columns'] * colMinWidth
            + (segment.page['max-columns'] - 1) * colGutter
            + allMargins,
          pageWidth = Math.min(Canvas.width, maxPageWidth);

      var pageX = (Canvas.width - pageWidth) / 2,
          colX = pageX + allMargins / 2;

      var nCols = Math.min(Math.max(1, Math.floor(pageWidth / (colMinWidth + colGutter))), segment.page['max-columns']),
          colWidth = ((nCols - 1) * colGutter + allMargins - pageWidth) / -nCols;

      var mods = LDoc.modules[segment.region],
          curCol = 0,
          cols = [];

      // populate columns

      us.times(nCols, function(i){

        cols[i] = {
          'remaining-height': pageMaxHeight,
          modules: []
        }

      });

      // populate columns with minimums

      var mod, m;

      for(m = 0; m < mods.length; m += 1){

        mod = mods[m];

        if (modMinHeight <= cols[curCol]['remaining-height']) {
          cols[curCol].modules.push(mod);
          cols[curCol]['remaining-height'] -= modMinHeight + modGutter;
        } else if (us.has(cols[curCol + 1], 'remaining-height')) {
          curCol += 1;
          cols[curCol].modules.push(mod);
          cols[curCol]['remaining-height'] -= modMinHeight + modGutter;
        } else {
          break;
        }

      }

      regionCursors[segment.region] = m;

      // flex grow the modules in each column

      us.each(cols, function(col, c){

        col['remaining-height'] += modGutter;

        var curY = vMargin;

        us.each(col.modules, function(mod, m){

          // here's where we add this to the boxes array

          var height = modMinHeight + col['remaining-height'] / col.modules.length,
              left = colX + c * (colWidth + colGutter),
              top = Canvas.height - curY;

          boxes.push(us.extend(mod, {

            left: left,
            top: top,
            right: left + colWidth,
            bottom: top - height

          }));

          curY += height + modGutter;

        });

      });

    }

  });

  // hide modules that didn't make the cut

  us.each(regionCursors, function(m, rid){

    if(m < LDoc.modules[rid].length){

      var n;

      for(n = m; n < LDoc.modules[rid].length; n += 1){

        boxes.push(us.extend(LDoc.modules[rid][n], {

          left: -20,
          top: -20,
          right: -20,
          bottom: -20

        }));

      }

    }

  });

  return boxes;

}

function LayoutGeometry(LDoc){

  this.document = LDoc;

}

LayoutGeometry.prototype.toCG = function(Canvas, geometry){

  var start = performance.now(),
      geo = geometry || new THREE.Geometry();

  geo.dynamic = true;

  us.each(docToBoxes(Canvas, this.document), function(box, i){

    var vi = i * 4,
        fi = i * 2;

    if(!geometry){
      geo.vertices[vi    ] = new THREE.Vector3(0, 0, 0);
      geo.vertices[vi + 1] = new THREE.Vector3(0, 0, 0);
      geo.vertices[vi + 2] = new THREE.Vector3(0, 0, 0);
      geo.vertices[vi + 3] = new THREE.Vector3(0, 0, 0);

      geo.faces.push(
        new THREE.Face3(vi, vi + 1, vi + 2),
        new THREE.Face3(vi+3, vi + 2, vi + 1)
      );
    }

    geo.vertices[vi].x = box.left;
    geo.vertices[vi].y = box.top;

    geo.vertices[vi + 1].x = box.left;
    geo.vertices[vi + 1].y = box.bottom;

    geo.vertices[vi + 2].x = box.right;
    geo.vertices[vi + 2].y = box.top;

    geo.vertices[vi + 3].x = box.right;
    geo.vertices[vi + 3].y = box.bottom;

    geo.faces[fi].vertexColors[0] = new THREE.Color(box.fill);
    geo.faces[fi].vertexColors[1] = new THREE.Color(box.fill);
    geo.faces[fi].vertexColors[2] = new THREE.Color(box.fill);

    geo.faces[fi+1].vertexColors[0] = new THREE.Color(box.fill);
    geo.faces[fi+1].vertexColors[1] = new THREE.Color(box.fill);
    geo.faces[fi+1].vertexColors[2] = new THREE.Color(box.fill);

  });

  if(!geometry){
    geo.computeFaceNormals();
    geo.computeVertexNormals();
  }else{
    geo.verticesNeedUpdate = true;
  }

  var duration = performance.now() - start;

  if(duration > FRAME){
    console.warn('LayoutGeometry calculation took too long:', duration);
  }

  return geo;

};

module.exports = LayoutGeometry;<commit_msg>Derp.<commit_after>var THREE = require('three'),
    us = require('lodash');

var FRAME = 1e3/60;

function docToBoxes(Canvas, LDoc){

  var boxes = [],
      rem = LDoc.typography.base,
      regionCursors = {};

  us.each(LDoc.segments, function(segment, i){

    if(us.has(segment, 'page')){

      var allMargins = 2 * segment.page['min-horizontal-margin'] * rem,
          vMargin = segment.page['vertical-margin'] * rem,
          pageMaxHeight = segment.page['max-height'] * rem,
          colMinWidth = segment.page.columns['min-width'] * rem,
          colMaxWidth = segment.page.columns['max-width'] * rem,
          modMinHeight = segment.page.modules['min-height'] * rem,
          colGutter = segment.page.columns.gutter * rem,
          modGutter = segment.page.modules.gutter * rem;

      var maxPageWidth = segment.page['max-columns'] * colMaxWidth
            + (segment.page['max-columns'] - 1) * colGutter
            + allMargins,
          minPageWidth = segment.page['min-columns'] * colMinWidth
            + (segment.page['max-columns'] - 1) * colGutter
            + allMargins,
          pageWidth = Math.min(Canvas.width, maxPageWidth);

      var pageX = (Canvas.width - pageWidth) / 2,
          colX = pageX + allMargins / 2;

      var nCols = Math.min(Math.max(1, Math.floor(pageWidth / (colMinWidth + colGutter))), segment.page['max-columns']),
          colWidth = ((nCols - 1) * colGutter + allMargins - pageWidth) / -nCols;

      var mods = LDoc.modules[segment.region],
          curCol = 0,
          cols = [];

      // populate columns

      us.times(nCols, function(i){

        cols[i] = {
          'remaining-height': pageMaxHeight,
          modules: []
        }

      });

      // populate columns with minimums

      var mod, m;

      for(m = 0; m < mods.length; m += 1){

        mod = mods[m];

        if (modMinHeight <= cols[curCol]['remaining-height']) {
          cols[curCol].modules.push(mod);
          cols[curCol]['remaining-height'] -= modMinHeight + modGutter;
        } else if (us.has(cols[curCol + 1], 'remaining-height')) {
          curCol += 1;
          cols[curCol].modules.push(mod);
          cols[curCol]['remaining-height'] -= modMinHeight + modGutter;
        } else {
          break;
        }

      }

      regionCursors[segment.region] = m;

      // flex grow the modules in each column

      us.each(cols, function(col, c){

        col['remaining-height'] += modGutter;

        var curY = vMargin;

        us.each(col.modules, function(mod, m){

          // here's where we add this to the boxes array

          var height = modMinHeight + col['remaining-height'] / col.modules.length,
              left = colX + c * (colWidth + colGutter),
              top = Canvas.height - curY;

          boxes.push(us.extend(mod, {

            left: left,
            top: top,
            right: left + colWidth,
            bottom: top - height

          }));

          curY += height + modGutter;

        });

      });

    }

  });

  // hide modules that didn't make the cut

  us.each(regionCursors, function(m, rid){

    if(m < LDoc.modules[rid].length){

      var n;

      for(n = m; n < LDoc.modules[rid].length; n += 1){

        boxes.push(us.extend(LDoc.modules[rid][n], {

          left: -20,
          top: -20,
          right: -20,
          bottom: -20

        }));

      }

    }

  });

  return boxes;

}

function LayoutGeometry(LDoc){

  this.document = LDoc;

}

LayoutGeometry.prototype.toCG = function(Canvas, geometry){

  var start = performance.now(),
      geo = geometry || new THREE.Geometry();

  geo.dynamic = true;

  us.each(docToBoxes(Canvas, this.document), function(box, i){

    var vi = i * 4,
        fi = i * 2;

    if(!geometry){
      geo.vertices[vi    ] = new THREE.Vector3(0, 0, 0);
      geo.vertices[vi + 1] = new THREE.Vector3(0, 0, 0);
      geo.vertices[vi + 2] = new THREE.Vector3(0, 0, 0);
      geo.vertices[vi + 3] = new THREE.Vector3(0, 0, 0);

      geo.faces.push(
        new THREE.Face3(vi, vi + 1, vi + 2),
        new THREE.Face3(vi+3, vi + 2, vi + 1)
      );
    }

    geo.vertices[vi].x = box.left;
    geo.vertices[vi].y = box.top;

    geo.vertices[vi + 1].x = box.left;
    geo.vertices[vi + 1].y = box.bottom;

    geo.vertices[vi + 2].x = box.right;
    geo.vertices[vi + 2].y = box.top;

    geo.vertices[vi + 3].x = box.right;
    geo.vertices[vi + 3].y = box.bottom;

    geo.faces[fi].vertexColors[0] = new THREE.Color(box.fill);
    geo.faces[fi].vertexColors[1] = new THREE.Color(box.fill);
    geo.faces[fi].vertexColors[2] = new THREE.Color(box.fill);

    geo.faces[fi+1].vertexColors[0] = new THREE.Color(box.fill);
    geo.faces[fi+1].vertexColors[1] = new THREE.Color(box.fill);
    geo.faces[fi+1].vertexColors[2] = new THREE.Color(box.fill);

  });

  if(!geometry){
    geo.computeFaceNormals();
    geo.computeVertexNormals();
  }else{
    geo.verticesNeedUpdate = true;
  }

  var duration = performance.now() - start;

  if(duration > FRAME){
    console.warn('LayoutGeometry calculation took too long:', duration);
  }

  return geo;

};

module.exports = LayoutGeometry;<|endoftext|>


<commit_before>var Insert = require('./commands').Insert
  , Update = require('./commands').Update
  , Remove = require('./commands').Remove
  , Query = require('../connection/commands').Query
  , copy = require('../connection/utils').copy
  , CommandResult = require('../topologies/command_result')
  , MongoError = require('../error');

var LegacySupport = function() {

  //
  // Aggregate up all the results
  //
  var aggregateInsertResults = function(results, connection) {
    var final = { ok: 1, n: 0 }

    // Map all the results coming back
    for(var i = 0; i < results.length; i++) {
      var result = results[i];

      // We have a command error
      if(result != null && result.ok == 0 || result.err || result.errmsg) {
        if(result.ok == 0) final.ok = 0;
        final.code = result.code;
        final.errmsg = result.errmsg || result.err || result.errMsg;

        // Check if we have a write error
        if(result.code == 11000
          || result.code == 11001
          || result.code == 12582
          || result.code == 14
          || result.code == 13511) {
          if(final.writeErrors == null) final.writeErrors = [];
          final.writeErrors.push({
              index: i
            , code: result.code
            , errmsg: result.errmsg || result.err || result.errMsg
          });
        } else {
          final.writeConcernError = {
              code: result.code
            , errmsg: result.errmsg || result.err || result.errMsg
          }
        }
      } else {
        final.n += 1;
      }

      // Result as expected
      if(result != null && result.lastOp) final.lastOp = result.lastOp;
    }

    // Return final aggregated results
    return new CommandResult(final, connection);
  }

  //
  // Execute all inserts in an ordered manner
  //
  var executeOrdered = function(command, ismaster, ns, bson, pool, callbacks, ops, options, callback) {
    var _ops = ops.slice(0);
    // Bind to current domain
    callback = bindToCurrentDomain(callback);
    // Collect all the getLastErrors
    var getLastErrors = [];

    // Execute an operation
    var executeOp = function(list, _callback) {
      // Get a pool connection
      var connection = pool.get();
      // No more items in the list
      if(list.length == 0) return _callback(null, aggregateInsertResults(getLastErrors, connection));

      // Get the first operation
      var doc = list.shift();

      // Create an insert command
      var op = new command(Query.getRequestId(), ismaster, bson, ns, [doc], options);
      // Write concern
      var writeConcern = options.writeConcern || {w:1};
      // Create a getLastError command
      var getLastErrorOp = new Query(bson, "system.$cmd", copy(writeConcern, {getLastError: 1}), {numberToReturn: -1});

      // Error out if no connection available
      if(connection == null)
        return _callback(new MongoError("no connection available"));

      try {
        // Execute the insert
        connection.write(op);
        // Write the lastError message
        connection.write(getLastErrorOp);
        // Register the callback
        callbacks.once(getLastErrorOp.requestId, function(err, result) {
          // Get the document
          var doc = result.documents[0];
          // Save the getLastError document
          getLastErrors.push(doc);
          // If we have an error terminate
          if(doc.ok == 0 || doc.err || doc.errmsg) return callback(null, aggregateInsertResults(getLastErrors, connection));
          // Execute the next op in the list
          executeOp(list, callback);
        });
      } catch(err) {
        // We have a serialization error, rewrite as a write error to have same behavior as modern
        // write commands
        getLastErrors.push({ ok: 1, errmsg: err, code: 14 });
        // Return due to an error
        return callback(null, aggregateInsertResults(getLastErrors, connection));
      }
    }

    // Execute the operations
    executeOp(_ops, callback);
  }

  var executeUnordered = function(command, ismaster, ns, bson, pool, callbacks, ops, options, callback) {
    // Bind to current domain
    callback = bindToCurrentDomain(callback);
    // Total operations to write
    var totalOps = ops.length;
    // Collect all the getLastErrors
    var getLastErrors = [];

    for(var i = 0; i < ops.length; i++) {
      // Create an insert command
      var op = new command(Query.getRequestId(), ismaster, bson, ns, [ops[i]], options);
      // Write concern
      var writeConcern = options.writeConcern || {w:1};
      // Create a getLastError command
      var getLastErrorOp = new Query(bson, "system.$cmd", copy(writeConcern, {getLastError: 1}), {numberToReturn: -1});

      // Get a pool connection
      var connection = pool.get();

      // Error out if no connection available
      if(connection == null)
        return _callback(new MongoError("no connection available"));

      try {
        // Execute the insert
        connection.write(op);
        // Write the lastError message
        connection.write(getLastErrorOp);

        // Give the result from getLastError the right index
        var callbackOp = function(_index) {
          return function(err, result) {
            // Update the number of operations executed
            totalOps = totalOps - 1;
            // Save the getLastError document
            getLastErrors[_index] = result.documents[0];
            // Check if we are done
            if(totalOps == 0) {
              callback(null, aggregateInsertResults(getLastErrors, connection));
            }
          }
        }
        // Register the callback
        callbacks.once(getLastErrorOp.requestId, callbackOp(i));
      } catch(err) {
        // Update the number of operations executed
        totalOps = totalOps - 1;
        // We have a serialization error, rewrite as a write error to have same behavior as modern
        // write commands
        getLastErrors[i] = { ok: 1, errmsg: err, code: 14 };
        // Check if we are done
        if(totalOps == 0) {
          callback(null, aggregateInsertResults(getLastErrors, connection));
        }
      }
    }
  }

  //
  // Needs to support legacy mass insert as well as ordered/unordered legacy
  // emulation
  //
  this.insert = function(ismaster, ns, bson, pool, callbacks, ops, options, callback) {
    options = options || {};
    // Default is ordered execution
    var ordered = typeof options.ordered == 'boolean' ? options.ordered : true;
    var legacy = typeof options.legacy == 'boolean' ? options.legacy : false;

    // We are unordered
    if(!ordered) {
      return executeUnordered(Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback);
    }

    return executeOrdered(Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback);
  }

  this.update = function(ismaster, ns, bson, pool, callbacks, ops, options, callback) {
    options = options || {};
    // Default is ordered execution
    var ordered = typeof options.ordered == 'boolean' ? options.ordered : true;

    // We are unordered
    if(!ordered) {
      return executeUnordered(Update, ismaster, ns, bson, pool, callbacks, ops, options, callback);
    }

    return executeOrdered(Update, ismaster, ns, bson, pool, callbacks, ops, options, callback);
  }

  this.remove = function(ismaster, ns, bson, pool, callbacks, ops, options, callback) {
    options = options || {};
    // Default is ordered execution
    var ordered = typeof options.ordered == 'boolean' ? options.ordered : true;

    // We are unordered
    if(!ordered) {
      return executeUnordered(Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback);
    }

    return executeOrdered(Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback);
  }
}

/**
 * @ignore
 */
var bindToCurrentDomain = function(callback) {
  var domain = process.domain;
  if(domain == null || callback == null) {
    return callback;
  } else {
    return domain.bind(callback);
  }
}

module.exports = LegacySupport;<commit_msg>Minor fixes for the legacy support of merging of results<commit_after>var Insert = require('./commands').Insert
  , Update = require('./commands').Update
  , Remove = require('./commands').Remove
  , Query = require('../connection/commands').Query
  , copy = require('../connection/utils').copy
  , CommandResult = require('../topologies/command_result')
  , MongoError = require('../error');

var LegacySupport = function() {

  //
  // Aggregate up all the results
  //
  var aggregateWriteOperationResults = function(results, connection) {
    var final = { ok: 1, n: 0 }

    // Map all the results coming back
    for(var i = 0; i < results.length; i++) {
      var result = results[i];

      // console.dir(result)
      // console.log(result.n)

      // We have a command error
      if(result != null && result.ok == 0 || result.err || result.errmsg) {
        if(result.ok == 0) final.ok = 0;
        final.code = result.code;
        final.errmsg = result.errmsg || result.err || result.errMsg;

        // Check if we have a write error
        if(result.code == 11000
          || result.code == 11001
          || result.code == 12582
          || result.code == 14
          || result.code == 13511) {
          if(final.writeErrors == null) final.writeErrors = [];
          final.writeErrors.push({
              index: i
            , code: result.code
            , errmsg: result.errmsg || result.err || result.errMsg
          });
        } else {
          final.writeConcernError = {
              code: result.code
            , errmsg: result.errmsg || result.err || result.errMsg
          }
        }
      } else if(typeof result.n == 'number') {
        final.n += result.n;
      } else {
        final.n += 1;
      }

      // Result as expected
      if(result != null && result.lastOp) final.lastOp = result.lastOp;
    }

    // Return final aggregated results
    return new CommandResult(final, connection);
  }

  //
  // Execute all inserts in an ordered manner
  //
  var executeOrdered = function(command, ismaster, ns, bson, pool, callbacks, ops, options, callback) {
    var _ops = ops.slice(0);
    // Bind to current domain
    callback = bindToCurrentDomain(callback);
    // Collect all the getLastErrors
    var getLastErrors = [];

    // Execute an operation
    var executeOp = function(list, _callback) {
      // Get a pool connection
      var connection = pool.get();
      // No more items in the list
      if(list.length == 0) return _callback(null, aggregateWriteOperationResults(getLastErrors, connection));

      // Get the first operation
      var doc = list.shift();

      // Create an insert command
      var op = new command(Query.getRequestId(), ismaster, bson, ns, [doc], options);
      // Write concern
      var writeConcern = options.writeConcern || {w:1};
      // Create a getLastError command
      var getLastErrorOp = new Query(bson, "system.$cmd", copy(writeConcern, {getLastError: 1}), {numberToReturn: -1});

      // Error out if no connection available
      if(connection == null)
        return _callback(new MongoError("no connection available"));

      try {
        // Execute the insert
        connection.write(op);
        // Write the lastError message
        connection.write(getLastErrorOp);
        // Register the callback
        callbacks.once(getLastErrorOp.requestId, function(err, result) {
          // Get the document
          var doc = result.documents[0];
          // Save the getLastError document
          getLastErrors.push(doc);
          // If we have an error terminate
          if(doc.ok == 0 || doc.err || doc.errmsg) return callback(null, aggregateWriteOperationResults(getLastErrors, connection));
          // Execute the next op in the list
          executeOp(list, callback);
        });
      } catch(err) {
        // We have a serialization error, rewrite as a write error to have same behavior as modern
        // write commands
        getLastErrors.push({ ok: 1, errmsg: err, code: 14 });
        // Return due to an error
        return callback(null, aggregateWriteOperationResults(getLastErrors, connection));
      }
    }

    // Execute the operations
    executeOp(_ops, callback);
  }

  var executeUnordered = function(command, ismaster, ns, bson, pool, callbacks, ops, options, callback) {
    // Bind to current domain
    callback = bindToCurrentDomain(callback);
    // Total operations to write
    var totalOps = ops.length;
    // Collect all the getLastErrors
    var getLastErrors = [];

    for(var i = 0; i < ops.length; i++) {
      // Create an insert command
      var op = new command(Query.getRequestId(), ismaster, bson, ns, [ops[i]], options);
      // Write concern
      var writeConcern = options.writeConcern || {w:1};
      // Create a getLastError command
      var getLastErrorOp = new Query(bson, "system.$cmd", copy(writeConcern, {getLastError: 1}), {numberToReturn: -1});

      // Get a pool connection
      var connection = pool.get();

      // Error out if no connection available
      if(connection == null)
        return _callback(new MongoError("no connection available"));

      try {
        // Execute the insert
        connection.write(op);
        // Write the lastError message
        connection.write(getLastErrorOp);

        // Give the result from getLastError the right index
        var callbackOp = function(_index) {
          return function(err, result) {
            // Update the number of operations executed
            totalOps = totalOps - 1;
            // Save the getLastError document
            getLastErrors[_index] = result.documents[0];
            // Check if we are done
            if(totalOps == 0) {
              callback(null, aggregateWriteOperationResults(getLastErrors, connection));
            }
          }
        }
        // Register the callback
        callbacks.once(getLastErrorOp.requestId, callbackOp(i));
      } catch(err) {
        // Update the number of operations executed
        totalOps = totalOps - 1;
        // We have a serialization error, rewrite as a write error to have same behavior as modern
        // write commands
        getLastErrors[i] = { ok: 1, errmsg: err, code: 14 };
        // Check if we are done
        if(totalOps == 0) {
          callback(null, aggregateWriteOperationResults(getLastErrors, connection));
        }
      }
    }
  }

  //
  // Needs to support legacy mass insert as well as ordered/unordered legacy
  // emulation
  //
  this.insert = function(ismaster, ns, bson, pool, callbacks, ops, options, callback) {
    options = options || {};
    // Default is ordered execution
    var ordered = typeof options.ordered == 'boolean' ? options.ordered : true;
    var legacy = typeof options.legacy == 'boolean' ? options.legacy : false;
    ops = Array.isArray(ops) ? ops :[ops];

    // We are unordered
    if(!ordered) {
      return executeUnordered(Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback);
    }

    return executeOrdered(Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback);
  }

  this.update = function(ismaster, ns, bson, pool, callbacks, ops, options, callback) {
    options = options || {};
    // Default is ordered execution
    var ordered = typeof options.ordered == 'boolean' ? options.ordered : true;
    ops = Array.isArray(ops) ? ops :[ops];

    // We are unordered
    if(!ordered) {
      return executeUnordered(Update, ismaster, ns, bson, pool, callbacks, ops, options, callback);
    }

    return executeOrdered(Update, ismaster, ns, bson, pool, callbacks, ops, options, callback);
  }

  this.remove = function(ismaster, ns, bson, pool, callbacks, ops, options, callback) {
    options = options || {};
    // Default is ordered execution
    var ordered = typeof options.ordered == 'boolean' ? options.ordered : true;
    ops = Array.isArray(ops) ? ops :[ops];

    // We are unordered
    if(!ordered) {
      return executeUnordered(Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback);
    }

    return executeOrdered(Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback);
  }
}

/**
 * @ignore
 */
var bindToCurrentDomain = function(callback) {
  var domain = process.domain;
  if(domain == null || callback == null) {
    return callback;
  } else {
    return domain.bind(callback);
  }
}

module.exports = LegacySupport;<|endoftext|>


<commit_before>import React from 'react'
import { Avatar, Flex, Box } from 'rebass'
import { shuffle, range } from 'lodash'
import { mx } from '../theme'

const Root = Flex.extend.attrs({
  justify: 'center',
  align: 'center',
  pt: 3,
  px: [1, 3]
})`
  position: relative;
  max-width: 100vw;
  height: 100vh;
  overflow-y: hidden;
`

const Fill = Flex.extend.attrs({ justify: 'space-around', wrap: true })`
  position: absolute;
  top: 0;
  z-index: -1;
`

const Cloud = Box.extend`
  max-width: 48rem;
  margin: auto;
  border-radius: 4rem;
  box-shadow: 0 0 2rem 4rem rgba(250, 250, 250, 0.95);
  background-color: rgba(250, 250, 250, 0.95);
  text-align: center;
  position: relative;
  z-index: 2;
  @media (min-height: 24em) {
    border-radius: 8rem;
    box-shadow: 0 0 4rem 4rem rgba(250, 250, 250, 0.95);
    top: -2rem;
  }
`

const Bubble = Avatar.extend`
  margin: 0.75em;
  &:nth-child(odd) {
    margin-left: 1.5em;
    margin-top: 0;
  }
  &:nth-child(even) {
    margin-right: 1em;
  }
  &:nth-child(6n) {
    width: 3em;
    height: 3em;
    margin-bottom: 1em;
  }
  &:nth-child(8n) {
    width: 2.5em;
    height: 2.5em;
    margin-left: 1em;
  }
  &:nth-child(13n) {
    width: 1.5em;
    height: 1.5em;
  }
  ${mx[1]} {
    &:first-child {
      margin-left: 6rem;
    }
  }
`

const Bubbles = ({ children }) => (
  <Root>
    <Fill>
      {shuffle(range(92)).map(i => (
        <Bubble
          src={`/avatars/${i + 1}.jpg`}
          size={sample([48, 56, 64, 72, 84, 96])}
          key={`a-${i}`}
        />
      ))}
    </Fill>
    <Cloud children={children} />
  </Root>
)

export default Bubbles
<commit_msg>Fix mobile header<commit_after>import React from 'react'
import { Avatar, Flex, Box } from 'rebass'
import { shuffle, range } from 'lodash'
import { mx } from '../theme'

const Root = Flex.extend.attrs({
  justify: 'center',
  align: 'center',
  pt: 3,
  px: 3
})`
  position: relative;
  max-width: 100vw;
  height: 100vh;
  overflow-y: hidden;
`

const Fill = Flex.extend.attrs({ justify: 'space-around', wrap: true })`
  position: absolute;
  top: 0;
  z-index: -1;
`

const Cloud = Box.extend`
  max-width: 48rem;
  margin: auto;
  border-radius: 4rem;
  box-shadow: 0 0 2rem 4rem rgba(250, 250, 250, 0.95);
  background-color: rgba(250, 250, 250, 0.95);
  text-align: center;
  position: relative;
  z-index: 2;
  @media (min-height: 24em) {
    border-radius: 8rem;
    box-shadow: 0 0 4rem 4rem rgba(250, 250, 250, 0.95);
    top: -2rem;
  }
`

const Bubble = Avatar.extend`
  margin: 0.75em;
  &:nth-child(odd) {
    margin-left: 1.5em;
    margin-top: 0;
  }
  &:nth-child(even) {
    margin-right: 1em;
  }
  &:nth-child(6n) {
    width: 3em;
    height: 3em;
    margin-bottom: 1em;
  }
  &:nth-child(8n) {
    width: 2.5em;
    height: 2.5em;
    margin-left: 1em;
  }
  &:nth-child(13n) {
    width: 1.5em;
    height: 1.5em;
  }
  ${mx[1]} {
    &:first-child {
      margin-left: 6rem;
    }
  }
`

const Bubbles = ({ children }) => (
  <Root>
    <Fill>
      {shuffle(range(92)).map(i => (
        <Bubble
          src={`/avatars/${i + 1}.jpg`}
          size={sample([48, 56, 64, 72, 84, 96])}
          key={`a-${i}`}
        />
      ))}
    </Fill>
    <Cloud children={children} />
  </Root>
)

export default Bubbles
<|endoftext|>


<commit_before> document.addEventListener("deviceready", onDeviceReady, false);
    var db = window.openDatabase("gastos", "1.0", "local database", 200000); //will create database Dummy_DB or open it
    var results=0;
    //function will be called when device ready
    function onDeviceReady(){
        db.transaction(populateDB, errorCB, successCB);
    }

    //create table and insert some record
    function populateDB(tx) {
        tx.executeSql('Create Table IF NOT EXISTS categorias_ingreso(id_categoria_ingreso integer primary key, nombre_categoria_ingreso text )');
        tx.executeSql('Create Table IF NOT EXISTS categorias_egreso(id_categoria_egreso integer primary key, nombre_categoria_egreso text )');
        tx.executeSql('Create Table IF NOT EXISTS subcategorias_egreso(id_subcategoria_egreso integer primary key, nombre_subcategoria_egreso, id_categoria_egreso)');
        tx.executeSql('Create Table IF NOT EXISTS saldos_ingreso(id_saldo_ingreso integer primary key, fecha_ingreso TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, monto_ingresado real, id_categoria_ingreso integer)');
        tx.executeSql('Create Table IF NOT EXISTS saldos_egreso(id_saldo_egreso integer primary key, fecha_egreso TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, monto_egresado real, id_categoria_egreso integer)');
        tx.executeSql('Create Table IF NOT EXISTS cta(id_cuenta_in integer primary key, nombre text, saldo real)');
    }

    //function will be called when an error occurred
    function errorCB(err) {
        console.log("Error processing SQL: "+err.code);
    }

    //function will be called when process succeed
    function successCB() {
        console.log("success!");
        db.transaction(select,errorCB);
    }

    function select() {
      var ingreso;
      var egreso= 0;
      var hoy = new Date();
      var mm = hoy.getMonth()+1;
      if (mm<10) {mm = '0' + mm;}else {mm = String(mm);}
      db.transaction(function(tx) {
          tx.executeSql("SELECT SUM(monto_ingresado) AS ingreso from saldos_ingreso WHERE strftime('%m', fecha_ingreso) = ? ", [mm], function(tx,res) {
          ingreso = Number(res.rows.item(0).ingreso);
          tx.executeSql("SELECT SUM(monto_egresado) AS egresado from saldos_egreso WHERE strftime('%m', fecha_egreso)  = ? ", [mm], function(tx,res) {
            egreso = Number(res.rows.item(0).egresado);
            document.getElementById('saldo_m').innerHTML = "$ " + (ingreso - egreso);
            selectAca();
            selectPat();
            nivel_riqueza();
          });
        });
      });
    }
    function selectAca(){
      var ingreso;
      var egreso= 0;
      var hoy = new Date();
      var yy = String(hoy.getFullYear());
      db.transaction(function(tx) {
        tx.executeSql("SELECT SUM(monto_ingresado) AS ingreso from saldos_ingreso WHERE strftime('%Y', fecha_ingreso) = ? ", [yy], function(tx,res) {
          ingreso = Number(res.rows.item(0).ingreso);
          tx.executeSql("SELECT SUM(monto_egresado) AS egresado from saldos_egreso WHERE strftime('%Y', fecha_egreso) = ?  ", [yy], function(tx,res) {
            egreso = Number(res.rows.item(0).egresado);
            document.getElementById('saldo_aca').innerHTML = "$ " + (ingreso - egreso);
          });
        });
      });
    }
    function selectPat(){
      var ingreso;
      var egreso= 0;
      db.transaction(function(tx) {
        tx.executeSql("SELECT SUM(monto_ingresado) AS ingreso from saldos_ingreso", [], function(tx,res) {
          ingreso = Number(res.rows.item(0).ingreso);
          tx.executeSql("SELECT SUM(monto_egresado) AS egresado from saldos_egreso", [], function(tx,res) {
            egreso = Number(res.rows.item(0).egresado);
            document.getElementById('patrimonio').innerHTML = "$ " + (ingreso - egreso);
          });
        });
      });
    }

    function nivel_riqueza() {
      var patrimonio = 0;
      var promedio = 0;
      var nivel_riqueza = 0;
      db.transaction(function(tx) {
        console.log("****************************************************");
        tx.executeSql("SELECT SUM(monto_ingresado) AS ingreso from saldos_ingreso", [], function(tx,res) {
          ingreso = Number(res.rows.item(0).ingreso);
          tx.executeSql("SELECT SUM(monto_egresado) AS egresado from saldos_egreso", [], function(tx,res) {
            egreso = Number(res.rows.item(0).egresado);
            patrimonio = ingreso - egreso;
            tx.executeSql("SELECT avg(monto_egresado) AS promedio from saldos_egreso ",[],function (tx,res) {
              promedio = Number(res.rows.item(0).promedio);
              if (promedio != 0) {
                nr = patrimonio/promedio;
                document.getElementById('nivel_riqueza').innerHTML = nr.toFixed(1);
              }else {
                nr = "0";
                document.getElementById('nivel_riqueza').innerHTML = nr;
              }
              console.log(nr);
            })
          });
        });
      });
    }
<commit_msg>Update pon.js<commit_after> document.addEventListener("deviceready", onDeviceReady, false);
    var db = window.openDatabase("gastos", "1.0", "local database", 200000); //will create database Dummy_DB or open it
    var results=0;
    //function will be called when device ready
    function onDeviceReady(){
        db.transaction(populateDB, errorCB, successCB);
    }

    //create table and insert some record
    function populateDB(tx) {
        tx.executeSql('Create Table IF NOT EXISTS categorias_ingreso(id_categoria_ingreso integer primary key, nombre_categoria_ingreso text )');
        tx.executeSql('Create Table IF NOT EXISTS categorias_egreso(id_categoria_egreso integer primary key, nombre_categoria_egreso text )');
        tx.executeSql('Create Table IF NOT EXISTS subcategorias_egreso(id_subcategoria_egreso integer primary key, nombre_subcategoria_egreso, id_categoria_egreso)');
        tx.executeSql('Create Table IF NOT EXISTS saldos_ingreso(id_saldo_ingreso integer primary key, fecha_ingreso TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, monto_ingresado real, id_categoria_ingreso integer)');
        tx.executeSql('Create Table IF NOT EXISTS saldos_egreso(id_saldo_egreso integer primary key, fecha_egreso TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, monto_egresado real, id_subcategoria_egreso integer)');
        tx.executeSql('Create Table IF NOT EXISTS cta(id_cuenta_in integer primary key, nombre text, saldo real)');
    }

    //function will be called when an error occurred
    function errorCB(err) {
        console.log("Error processing SQL: "+err.code);
    }

    //function will be called when process succeed
    function successCB() {
        console.log("success!");
        db.transaction(select,errorCB);
    }

    function select() {
      var ingreso;
      var egreso= 0;
      var hoy = new Date();
      var mm = hoy.getMonth()+1;
      if (mm<10) {mm = '0' + mm;}else {mm = String(mm);}
      db.transaction(function(tx) {
          tx.executeSql("SELECT SUM(monto_ingresado) AS ingreso from saldos_ingreso WHERE strftime('%m', fecha_ingreso) = ? ", [mm], function(tx,res) {
          ingreso = Number(res.rows.item(0).ingreso);
          tx.executeSql("SELECT SUM(monto_egresado) AS egresado from saldos_egreso WHERE strftime('%m', fecha_egreso)  = ? ", [mm], function(tx,res) {
            egreso = Number(res.rows.item(0).egresado);
            document.getElementById('saldo_m').innerHTML = "$ " + (ingreso - egreso);
            selectAca();
            selectPat();
            nivel_riqueza();
          });
        });
      });
    }
    function selectAca(){
      var ingreso;
      var egreso= 0;
      var hoy = new Date();
      var yy = String(hoy.getFullYear());
      db.transaction(function(tx) {
        tx.executeSql("SELECT SUM(monto_ingresado) AS ingreso from saldos_ingreso WHERE strftime('%Y', fecha_ingreso) = ? ", [yy], function(tx,res) {
          ingreso = Number(res.rows.item(0).ingreso);
          tx.executeSql("SELECT SUM(monto_egresado) AS egresado from saldos_egreso WHERE strftime('%Y', fecha_egreso) = ?  ", [yy], function(tx,res) {
            egreso = Number(res.rows.item(0).egresado);
            document.getElementById('saldo_aca').innerHTML = "$ " + (ingreso - egreso);
          });
        });
      });
    }
    function selectPat(){
      var ingreso;
      var egreso= 0;
      db.transaction(function(tx) {
        tx.executeSql("SELECT SUM(monto_ingresado) AS ingreso from saldos_ingreso", [], function(tx,res) {
          ingreso = Number(res.rows.item(0).ingreso);
          tx.executeSql("SELECT SUM(monto_egresado) AS egresado from saldos_egreso", [], function(tx,res) {
            egreso = Number(res.rows.item(0).egresado);
            document.getElementById('patrimonio').innerHTML = "$ " + (ingreso - egreso);
          });
        });
      });
    }

    function nivel_riqueza() {
      var patrimonio = 0;
      var promedio = 0;
      var nivel_riqueza = 0;
      db.transaction(function(tx) {
        console.log("****************************************************");
        tx.executeSql("SELECT SUM(monto_ingresado) AS ingreso from saldos_ingreso", [], function(tx,res) {
          ingreso = Number(res.rows.item(0).ingreso);
          tx.executeSql("SELECT SUM(monto_egresado) AS egresado from saldos_egreso", [], function(tx,res) {
            egreso = Number(res.rows.item(0).egresado);
            patrimonio = ingreso - egreso;
            tx.executeSql("SELECT avg(monto_egresado) AS promedio from saldos_egreso ",[],function (tx,res) {
              promedio = Number(res.rows.item(0).promedio);
              if (promedio != 0) {
                nr = patrimonio/promedio;
                document.getElementById('nivel_riqueza').innerHTML = nr.toFixed(1);
              }else {
                nr = "0";
                document.getElementById('nivel_riqueza').innerHTML = nr;
              }
              console.log(nr);
            })
          });
        });
      });
    }
<|endoftext|>


<commit_before>/**
 *
 * Worker script for browser and node
 *
 * @fileoverview Worker script for browser and node
 * @author Kevin Kwok <antimatter15@gmail.com>
 * @author Guillermo Webster <gui@mit.edu>
 * @author Jerome Wu <jeromewus@gmail.com>
 */
require('regenerator-runtime/runtime');
const fileType = require('file-type');
const isURL = require('is-url');
const dump = require('./utils/dump');
const isWebWorker = require('../utils/getEnvironment')('type') === 'webworker';
const setImage = require('./utils/setImage');
const defaultParams = require('./constants/defaultParams');
const { log, setLogging } = require('../utils/log');

/*
 * Tesseract Module returned by TesseractCore.
 */
let TessModule;
/*
 * TessearctBaseAPI instance
 */
let api = null;
let latestJob;
let adapter = {};
let params = defaultParams;

const load = async ({ workerId, jobId, payload: { options: { corePath, logging } } }, res) => {
  setLogging(logging);
  if (!TessModule) {
    const Core = await adapter.getCore(corePath, res);

    res.progress({ workerId, status: 'initializing tesseract', progress: 0 });

    Core({
      TesseractProgress(percent) {
        latestJob.progress({
          workerId,
          jobId,
          status: 'recognizing text',
          progress: Math.max(0, (percent - 30) / 70),
        });
      },
    }).then((tessModule) => {
      TessModule = tessModule;
      res.progress({ workerId, status: 'initialized tesseract', progress: 1 });
      res.resolve({ loaded: true });
    });
  } else {
    res.resolve({ loaded: true });
  }
};

const FS = ({ workerId, payload: { method, args } }, res) => {
  log(`[${workerId}]: FS.${method} with args ${args}`);
  res.resolve(TessModule.FS[method](...args));
};

const loadLanguage = async ({
  workerId,
  payload: {
    langs,
    options: {
      langPath,
      dataPath,
      cachePath,
      cacheMethod,
      gzip = true,
    },
  },
},
res) => {
  const loadAndGunzipFile = async (_lang) => {
    const lang = typeof _lang === 'string' ? _lang : _lang.code;
    const readCache = ['refresh', 'none'].includes(cacheMethod)
      ? () => Promise.resolve()
      : adapter.readCache;
    let data = null;

    try {
      const _data = await readCache(`${cachePath || '.'}/${lang}.traineddata`);
      if (typeof _data !== 'undefined') {
        log(`[${workerId}]: Load ${lang}.traineddata from cache`);
        res.progress({ workerId, status: 'loading language traineddata (from cache)', progress: 0.5 });
        data = _data;
      } else {
        throw Error('Not found in cache');
      }
    } catch (e) {
      log(`[${workerId}]: Load ${lang}.traineddata from ${langPath}`);
      if (typeof _lang === 'string') {
        let path = null;

        if (isURL(langPath) || langPath.startsWith('moz-extension://') || langPath.startsWith('chrome-extension://') || langPath.startsWith('file://')) { /** When langPath is an URL */
          path = langPath;
        }

        if (path !== null) {
          const fetchUrl = `${path}/${lang}.traineddata${gzip ? '.gz' : ''}`;
          const resp = await (isWebWorker ? fetch : adapter.fetch)(fetchUrl);
          if (!resp.ok) {
            throw Error(`Network error while fetching ${fetchUrl}. Response code: ${resp.status}`);
          }
          data = await resp.arrayBuffer();
        } else {
          data = await adapter.readCache(`${langPath}/${lang}.traineddata${gzip ? '.gz' : ''}`);
        }
      } else {
        data = _lang.data; // eslint-disable-line
      }
    }

    data = new Uint8Array(data);

    const type = fileType(data);
    if (typeof type !== 'undefined' && type.mime === 'application/gzip') {
      data = adapter.gunzip(data);
    }

    if (TessModule) {
      if (dataPath) {
        try {
          TessModule.FS.mkdir(dataPath);
        } catch (err) {
          res.reject(err.toString());
        }
      }
      TessModule.FS.writeFile(`${dataPath || '.'}/${lang}.traineddata`, data);
    }

    if (['write', 'refresh', undefined].includes(cacheMethod)) {
      await adapter.writeCache(`${cachePath || '.'}/${lang}.traineddata`, data);
    }

    return Promise.resolve(data);
  };

  res.progress({ workerId, status: 'loading language traineddata', progress: 0 });
  try {
    await Promise.all((typeof langs === 'string' ? langs.split('+') : langs).map(loadAndGunzipFile));
    res.progress({ workerId, status: 'loaded language traineddata', progress: 1 });
    res.resolve(langs);
  } catch (err) {
    if (isWebWorker && err instanceof DOMException) {
      /*
       * For some reason google chrome throw DOMException in loadLang,
       * while other browser is OK, for now we ignore this exception
       * and hopefully to find the root cause one day.
       */
    } else {
      res.reject(err.toString());
    }
  }
};

const setParameters = ({ payload: { params: _params } }, res) => {
  Object.keys(_params)
    .filter((k) => !k.startsWith('tessjs_'))
    .forEach((key) => {
      api.SetVariable(key, _params[key]);
    });
  params = { ...params, ..._params };

  if (typeof res !== 'undefined') {
    res.resolve(params);
  }
};

const initialize = ({
  workerId,
  payload: { langs: _langs, oem },
}, res) => {
  const langs = (typeof _langs === 'string')
    ? _langs
    : _langs.map((l) => ((typeof l === 'string') ? l : l.data)).join('+');

  try {
    res.progress({
      workerId, status: 'initializing api', progress: 0,
    });
    if (api !== null) {
      api.End();
    }
    api = new TessModule.TessBaseAPI();
    const status = api.Init(null, langs, oem);
    if (status === -1) {
      res.reject('initialization failed');
    }
    params = defaultParams;
    setParameters({ payload: { params } });
    res.progress({
      workerId, status: 'initialized api', progress: 1,
    });
    res.resolve();
  } catch (err) {
    res.reject(err.toString());
  }
};

const recognize = ({ payload: { image, options: { rectangle: rec } } }, res) => {
  try {
    const ptr = setImage(TessModule, api, image);
    if (typeof rec === 'object') {
      api.SetRectangle(rec.left, rec.top, rec.width, rec.height);
    }
    api.Recognize(null);
    res.resolve(dump(TessModule, api, params));
    TessModule._free(ptr);
  } catch (err) {
    res.reject(err.toString());
  }
};

const getPDF = ({ payload: { title, textonly } }, res) => {
  const pdfRenderer = new TessModule.TessPDFRenderer('tesseract-ocr', '/', textonly);
  pdfRenderer.BeginDocument(title);
  pdfRenderer.AddImage(api);
  pdfRenderer.EndDocument();
  TessModule._free(pdfRenderer);

  res.resolve(TessModule.FS.readFile('/tesseract-ocr.pdf'));
};

const detect = ({ payload: { image } }, res) => {
  try {
    const ptr = setImage(TessModule, api, image);
    const results = new TessModule.OSResults();

    if (!api.DetectOS(results)) {
      api.End();
      TessModule._free(ptr);
      res.reject('Failed to detect OS');
    } else {
      const best = results.best_result;
      const oid = best.orientation_id;
      const sid = best.script_id;

      TessModule._free(ptr);

      res.resolve({
        tesseract_script_id: sid,
        script: results.unicharset.get_script_from_script_id(sid),
        script_confidence: best.sconfidence,
        orientation_degrees: [0, 270, 180, 90][oid],
        orientation_confidence: best.oconfidence,
      });
    }
  } catch (err) {
    res.reject(err.toString());
  }
};

const terminate = (_, res) => {
  try {
    if (api !== null) {
      api.End();
    }
    res.resolve({ terminated: true });
  } catch (err) {
    res.reject(err.toString());
  }
};

/**
 * dispatchHandlers
 *
 * @name dispatchHandlers
 * @function worker data handler
 * @access public
 * @param {object} data
 * @param {string} data.jobId - unique job id
 * @param {string} data.action - action of the job, only recognize and detect for now
 * @param {object} data.payload - data for the job
 * @param {function} send - trigger job to work
 */
exports.dispatchHandlers = (packet, send) => {
  const res = (status, data) => {
    send({
      ...packet,
      status,
      data,
    });
  };
  res.resolve = res.bind(this, 'resolve');
  res.reject = res.bind(this, 'reject');
  res.progress = res.bind(this, 'progress');

  latestJob = res;

  try {
    ({
      load,
      FS,
      loadLanguage,
      initialize,
      setParameters,
      recognize,
      getPDF,
      detect,
      terminate,
    })[packet.action](packet, res);
  } catch (err) {
    /** Prepare exception to travel through postMessage */
    res.reject(err.toString());
  }
};

/**
 * setAdapter
 *
 * @name setAdapter
 * @function
 * @access public
 * @param {object} adapter - implementation of the worker, different in browser and node environment
 */
exports.setAdapter = (_adapter) => {
  adapter = _adapter;
};
<commit_msg>Made all errors in loadLanguage lead to promise rejection per #414 (#669)<commit_after>/**
 *
 * Worker script for browser and node
 *
 * @fileoverview Worker script for browser and node
 * @author Kevin Kwok <antimatter15@gmail.com>
 * @author Guillermo Webster <gui@mit.edu>
 * @author Jerome Wu <jeromewus@gmail.com>
 */
require('regenerator-runtime/runtime');
const fileType = require('file-type');
const isURL = require('is-url');
const dump = require('./utils/dump');
const isWebWorker = require('../utils/getEnvironment')('type') === 'webworker';
const setImage = require('./utils/setImage');
const defaultParams = require('./constants/defaultParams');
const { log, setLogging } = require('../utils/log');

/*
 * Tesseract Module returned by TesseractCore.
 */
let TessModule;
/*
 * TessearctBaseAPI instance
 */
let api = null;
let latestJob;
let adapter = {};
let params = defaultParams;

const load = async ({ workerId, jobId, payload: { options: { corePath, logging } } }, res) => {
  setLogging(logging);
  if (!TessModule) {
    const Core = await adapter.getCore(corePath, res);

    res.progress({ workerId, status: 'initializing tesseract', progress: 0 });

    Core({
      TesseractProgress(percent) {
        latestJob.progress({
          workerId,
          jobId,
          status: 'recognizing text',
          progress: Math.max(0, (percent - 30) / 70),
        });
      },
    }).then((tessModule) => {
      TessModule = tessModule;
      res.progress({ workerId, status: 'initialized tesseract', progress: 1 });
      res.resolve({ loaded: true });
    });
  } else {
    res.resolve({ loaded: true });
  }
};

const FS = ({ workerId, payload: { method, args } }, res) => {
  log(`[${workerId}]: FS.${method} with args ${args}`);
  res.resolve(TessModule.FS[method](...args));
};

const loadLanguage = async ({
  workerId,
  payload: {
    langs,
    options: {
      langPath,
      dataPath,
      cachePath,
      cacheMethod,
      gzip = true,
    },
  },
},
res) => {
  const loadAndGunzipFile = async (_lang) => {
    const lang = typeof _lang === 'string' ? _lang : _lang.code;
    const readCache = ['refresh', 'none'].includes(cacheMethod)
      ? () => Promise.resolve()
      : adapter.readCache;
    let data = null;

    try {
      const _data = await readCache(`${cachePath || '.'}/${lang}.traineddata`);
      if (typeof _data !== 'undefined') {
        log(`[${workerId}]: Load ${lang}.traineddata from cache`);
        res.progress({ workerId, status: 'loading language traineddata (from cache)', progress: 0.5 });
        data = _data;
      } else {
        throw Error('Not found in cache');
      }
    } catch (e) {
      log(`[${workerId}]: Load ${lang}.traineddata from ${langPath}`);
      if (typeof _lang === 'string') {
        let path = null;

        if (isURL(langPath) || langPath.startsWith('moz-extension://') || langPath.startsWith('chrome-extension://') || langPath.startsWith('file://')) { /** When langPath is an URL */
          path = langPath;
        }

        if (path !== null) {
          const fetchUrl = `${path}/${lang}.traineddata${gzip ? '.gz' : ''}`;
          const resp = await (isWebWorker ? fetch : adapter.fetch)(fetchUrl);
          if (!resp.ok) {
            throw Error(`Network error while fetching ${fetchUrl}. Response code: ${resp.status}`);
          }
          data = await resp.arrayBuffer();
        } else {
          data = await adapter.readCache(`${langPath}/${lang}.traineddata${gzip ? '.gz' : ''}`);
        }
      } else {
        data = _lang.data; // eslint-disable-line
      }
    }

    data = new Uint8Array(data);

    const type = fileType(data);
    if (typeof type !== 'undefined' && type.mime === 'application/gzip') {
      data = adapter.gunzip(data);
    }

    if (TessModule) {
      if (dataPath) {
        try {
          TessModule.FS.mkdir(dataPath);
        } catch (err) {
          res.reject(err.toString());
        }
      }
      TessModule.FS.writeFile(`${dataPath || '.'}/${lang}.traineddata`, data);
    }

    if (['write', 'refresh', undefined].includes(cacheMethod)) {
      await adapter.writeCache(`${cachePath || '.'}/${lang}.traineddata`, data);
    }

    return Promise.resolve(data);
  };

  res.progress({ workerId, status: 'loading language traineddata', progress: 0 });
  try {
    await Promise.all((typeof langs === 'string' ? langs.split('+') : langs).map(loadAndGunzipFile));
    res.progress({ workerId, status: 'loaded language traineddata', progress: 1 });
    res.resolve(langs);
  } catch (err) {
    res.reject(err.toString());
  }
};

const setParameters = ({ payload: { params: _params } }, res) => {
  Object.keys(_params)
    .filter((k) => !k.startsWith('tessjs_'))
    .forEach((key) => {
      api.SetVariable(key, _params[key]);
    });
  params = { ...params, ..._params };

  if (typeof res !== 'undefined') {
    res.resolve(params);
  }
};

const initialize = ({
  workerId,
  payload: { langs: _langs, oem },
}, res) => {
  const langs = (typeof _langs === 'string')
    ? _langs
    : _langs.map((l) => ((typeof l === 'string') ? l : l.data)).join('+');

  try {
    res.progress({
      workerId, status: 'initializing api', progress: 0,
    });
    if (api !== null) {
      api.End();
    }
    api = new TessModule.TessBaseAPI();
    const status = api.Init(null, langs, oem);
    if (status === -1) {
      res.reject('initialization failed');
    }
    params = defaultParams;
    setParameters({ payload: { params } });
    res.progress({
      workerId, status: 'initialized api', progress: 1,
    });
    res.resolve();
  } catch (err) {
    res.reject(err.toString());
  }
};

const recognize = ({ payload: { image, options: { rectangle: rec } } }, res) => {
  try {
    const ptr = setImage(TessModule, api, image);
    if (typeof rec === 'object') {
      api.SetRectangle(rec.left, rec.top, rec.width, rec.height);
    }
    api.Recognize(null);
    res.resolve(dump(TessModule, api, params));
    TessModule._free(ptr);
  } catch (err) {
    res.reject(err.toString());
  }
};

const getPDF = ({ payload: { title, textonly } }, res) => {
  const pdfRenderer = new TessModule.TessPDFRenderer('tesseract-ocr', '/', textonly);
  pdfRenderer.BeginDocument(title);
  pdfRenderer.AddImage(api);
  pdfRenderer.EndDocument();
  TessModule._free(pdfRenderer);

  res.resolve(TessModule.FS.readFile('/tesseract-ocr.pdf'));
};

const detect = ({ payload: { image } }, res) => {
  try {
    const ptr = setImage(TessModule, api, image);
    const results = new TessModule.OSResults();

    if (!api.DetectOS(results)) {
      api.End();
      TessModule._free(ptr);
      res.reject('Failed to detect OS');
    } else {
      const best = results.best_result;
      const oid = best.orientation_id;
      const sid = best.script_id;

      TessModule._free(ptr);

      res.resolve({
        tesseract_script_id: sid,
        script: results.unicharset.get_script_from_script_id(sid),
        script_confidence: best.sconfidence,
        orientation_degrees: [0, 270, 180, 90][oid],
        orientation_confidence: best.oconfidence,
      });
    }
  } catch (err) {
    res.reject(err.toString());
  }
};

const terminate = (_, res) => {
  try {
    if (api !== null) {
      api.End();
    }
    res.resolve({ terminated: true });
  } catch (err) {
    res.reject(err.toString());
  }
};

/**
 * dispatchHandlers
 *
 * @name dispatchHandlers
 * @function worker data handler
 * @access public
 * @param {object} data
 * @param {string} data.jobId - unique job id
 * @param {string} data.action - action of the job, only recognize and detect for now
 * @param {object} data.payload - data for the job
 * @param {function} send - trigger job to work
 */
exports.dispatchHandlers = (packet, send) => {
  const res = (status, data) => {
    send({
      ...packet,
      status,
      data,
    });
  };
  res.resolve = res.bind(this, 'resolve');
  res.reject = res.bind(this, 'reject');
  res.progress = res.bind(this, 'progress');

  latestJob = res;

  try {
    ({
      load,
      FS,
      loadLanguage,
      initialize,
      setParameters,
      recognize,
      getPDF,
      detect,
      terminate,
    })[packet.action](packet, res);
  } catch (err) {
    /** Prepare exception to travel through postMessage */
    res.reject(err.toString());
  }
};

/**
 * setAdapter
 *
 * @name setAdapter
 * @function
 * @access public
 * @param {object} adapter - implementation of the worker, different in browser and node environment
 */
exports.setAdapter = (_adapter) => {
  adapter = _adapter;
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import * as counterActions from '../actions/counterActions';
import { dispatch } from '../store';

@connect(state => ({
	counter: state.counter,
}))
export class Counter extends Component {
	static propTypes = {
		counter: PropTypes.number,
	};

	constructor(props) {
		super(props);
	}

	render() {
		return (

Counter: {this.props.counter}

				<button onClick={() => dispatch(counterActions.decrement())}>-</button>
				<button onClick={() => dispatch(counterActions.increment())}>+</button>

		);
	}
}
<commit_msg>Add defaultProps and initial state.<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import * as counterActions from '../actions/counterActions';
import { dispatch } from '../store';

@connect(state => ({
	counter: state.counter,
}))
export class Counter extends Component {
	static propTypes = {
		counter: PropTypes.number,
	};

	static defaultProps = {
		counter: 0,
	};

	state = {};

	constructor(props) {
		super(props);
	}

	render() {
		return (

Counter: {this.props.counter}

				<button onClick={() => dispatch(counterActions.decrement())}>-</button>
				<button onClick={() => dispatch(counterActions.increment())}>+</button>

		);
	}
}
<|endoftext|>


<commit_before>'use strict'

// Library for making requests
const request = require('request')
const BigNumber = require('bignumber.js')

// Necessary node libraries to make sia.js emit events
const Util = require('util')
const EventEmitter = require('events')
const nodePath = require('path')

/**
 * SiadWrapper, a closure, initializes siad as a background process and
 * provides functions to interact with it
 * @class SiadWrapper
 */
function SiadWrapper () {
  // siad details with default values
  var settings = {
    detached: false,
    address: 'localhost:9980',
    rpcAddress: ':9981',
    hostAddress: ':9982',
    datadir: nodePath.join(__dirname, '..', 'Sia'),
    path: nodePath.join(__dirname, '..', 'Sia', process.platform === 'win32' ? 'siad.exe' : 'siad')
  }
  // Ensure precision for unit conversions
  BigNumber.config({ DECIMAL_PLACES: 30 })
  BigNumber.config({ EXPONENTIAL_AT: 1e+9 })
  // Unit conversion constants
  const hastingsPerSiacoin = new BigNumber(10).pow(24)

  // Tracks if siad was last known to be running or not
  var running = false
  // Keep reference to `this` to emit events from within contexts where `this`
  // does not point to this class
  var self = this
  // Inherit `EventEmitter` properties
  EventEmitter.call(this)

  /**
   * Relays calls to daemonAPI with the localhost:port address appended
   * @function SiadWrapper#call
   * @param {apiCall} call - function to run if Siad is running
   * @param {apiResponse} callback
   * @returns {object} request call object
   */
  function apiCall (call, callback) {
    // Interpret string-only calls. Will default to 'GET' requests
    if (typeof call === 'string') {
      call = { url: call }
    }

    // Setup request
    call.url = 'http://' + settings.address + call.url
    call.json = true
    call.headers = {
      'User-Agent': 'Sia-Agent'
    }

    // Return the request sent if the user wants to be creative and get more
    // information than what's passed to the callback
    // TODO: Don't understand why the setImmediate is needed, but without it,
    // some calls seem to not return right after another call but eventually do
    // return once another call is made. Some sort of resource blocking is
    // happening
    setImmediate(function () {
      request(call, function (err, response, body) {
        // The error from request should be null if siad is running
        running = !err

        // If siad puts out an error, pass it as first argument to callback
        if (!err && response.statusCode !== 200) {
          err = body
          body = null
        }

        // Return results to callback
        if (callback !== undefined) {
          callback(err, body)
        }
      })
    })
  }

  // Checks whether siad is running on the current address
  function checkIfSiadRunning (callback) {
    return apiCall('/daemon/version', function (err) {
      // There should be no reason this call would error if siad were running
      // and serving requests
      running = !err

      // Return result to callback
      if (callback !== undefined) {
        callback(running)
      }
    })
  }

  /**
   * Checks whether siad is running and runs ones of two callbacks
   * @function SiadWrapper#ifRunning
   * @param {callback} is - called if siad is running
   * @param {callback} not - called if siad is not running
   * @returns {object} request call object
   */
  function ifSiadRunning (is, not) {
    return checkIfSiadRunning(function (running) {
      if (running && is !== undefined) {
        is()
      } else if (not !== undefined) {
        not()
      }
    })
  }

  /**
   * Synchronous way to check if siad is running, may not be up to date
   * @function SiadWrapper#isRunning
   * @returns {boolean} whether siad is running
   */
  function isSiadRunning (callback) {
    return running
  }

  // Polls the siad API until it comes online
  function waitUntilLoaded (callback) {
    return ifSiadRunning(callback, function () {
      setTimeout(function () {
        waitUntilLoaded(callback)
      }, 1000)
    })
  }

  /**
   * Starts the daemon as a long running background process
   * @param {callback} callback - function to be run if successful
   * @returns {boolean} if start was attempted
   */
  function start (callback) {
    // Check if siad is already running
    if (running) {
      if (callback !== null) {
        callback(new Error('Attempted to start siad when it was already running'))
      }
      return false
    }

    // Check synchronously if siad doesn't exist at settings.path
    const fs = require('fs')
    try {
      require('fs').statSync(settings.path)
    } catch (e) {
      if (callback !== null) {
        callback(e)
      }
      return false
    }

    // Set siad folder as configured settings.datadir
    var processOptions = {
      cwd: settings.datadir
    }

    // If the detached option is set, spawn siad as a separate process to be
    // run in the background after the parent process has closed
    if (settings.detached) {
      let log = nodePath.join(settings.datadir, 'out.log')
      let out = fs.openSync(log, 'a')
      let err = fs.openSync(log, 'a')
      processOptions.detached = true
      processOptions.stdio = [ 'ignore', out, err ]
    }

    // Spawn siad
    try {
      const Process = require('child_process').spawn
      var daemonProcess = new Process(settings.path, [
        '--api-addr=' + settings.address,
        '--rpc-addr=' + settings.rpcAddress,
        '--host-addr=' + settings.hostAddress,
        '--sia-directory=' + settings.datadir
      ], processOptions)
    } catch (e) {
      if (callback !== null) {
        callback(e)
      }
      return false
    }

    // Exclude it from the parent process' event loop if detached
    if (settings.detached) {
      daemonProcess.unref()
    } else {
      // Listen for siad events and emit them from wrapper
      // TODO: Attach these to siad if it's already running
      var childProcessEvents = ['close', 'disconnect', 'error', 'message']
      childProcessEvents.forEach(function (ev) {
        daemonProcess.on(ev, function (arg1, arg2) {
          self.emit(ev, arg1, arg2)
        })
      })
      daemonProcess.on('exit', function (code) {
        running = false
        self.emit('exit', code)
      })
    }

    // Wait until siad finishes loading to call callback
    waitUntilLoaded(callback)
    return true
  }

  /**
   * Sends a stop call to the daemon
   * @param {callback} callback - function to be run if successful
   * @returns {boolean} if stop was attempted, should always be true
   */
  function stop (callback) {
    apiCall('/daemon/stop', function (err) {
      if (!err) {
        running = false
      }
      if (callback !== undefined) {
        callback(err)
      }
    })
    return true
  }

  /**
   * Sets the member variables based on the passed config. Checks if siad is
   * running on the new configuration so running should be up to date for
   * the callback
   * @param {config} c - the config object derived from config.json
   * @param {callback} callback - first argument is any errors, second argument
   * is the new configuration
   * @returns {object} siad configuration object
   */
  function configure (newSettings, callback) {
    for (let key in settings) {
      // Set passed in settings within siad
      if (settings.hasOwnProperty(key) && newSettings.hasOwnProperty(key)) {
        settings[key] = newSettings[key]
      } else if (settings.hasOwnProperty(key)) {
        // Set settings to sync with siad
        newSettings[key] = settings[key]
      }
    }
    if (callback !== undefined) {
      checkIfSiadRunning(function (check) {
        callback(null, settings)
      })
    }
    return settings
  }

  /**
   * Downloads siad and siac to a specified or default location
   * @param {string} path - An optional location of where to download to
   * @param {callback} callback
   * @returns {boolean} if download was started, should always be true
   */
  function download (path, callback) {
    if (typeof path === 'string') {
      settings.path = path
    } else {
      // the first argument is either undefined or the callback
      callback = path
      path = settings.path
    }
    return require('./download.js')(path, callback)
  }

  // Sia unit conversion functions.
  // Convert Hastings (the base unit) to Siacoin.  Use strings as input to avoid precision loss.
  // @param {hastings :string}
  // @return BigNumber
  function hastingsToSiacoins (hastings) {
    const hastingsNumber = new BigNumber(hastings)
    return hastingsNumber.dividedBy(hastingsPerSiacoin)
  }
  // Convert Siacoin to Hastings.  Use strings as input to avoid precision loss.
  // @params {siacoin :string}
  // @return BigNumber
  function siacoinsToHastings (siacoins) {
    const siacoinNumber = new BigNumber(siacoins)
    return siacoinNumber.times(hastingsPerSiacoin)
  }

  // Make certain members public
  this.call = apiCall
  this.ifRunning = ifSiadRunning
  this.isRunning = isSiadRunning
  this.start = start
  this.stop = stop
  this.configure = configure
  this.download = download
  this.siacoinsToHastings = siacoinsToHastings
  this.hastingsToSiacoins = hastingsToSiacoins
}

// Inherit functions from `EventEmitter`'s prototype
Util.inherits(SiadWrapper, EventEmitter)

module.exports = new SiadWrapper()
<commit_msg>daemonProcess scoping<commit_after>'use strict'

// Library for making requests
const request = require('request')
const BigNumber = require('bignumber.js')

// Necessary node libraries to make sia.js emit events
const Util = require('util')
const EventEmitter = require('events')
const nodePath = require('path')

/**
 * SiadWrapper, a closure, initializes siad as a background process and
 * provides functions to interact with it
 * @class SiadWrapper
 */
function SiadWrapper () {
  // siad details with default values
  var settings = {
    detached: false,
    address: 'localhost:9980',
    rpcAddress: ':9981',
    hostAddress: ':9982',
    datadir: nodePath.join(__dirname, '..', 'Sia'),
    path: nodePath.join(__dirname, '..', 'Sia', process.platform === 'win32' ? 'siad.exe' : 'siad')
  }
  // Ensure precision for unit conversions
  BigNumber.config({ DECIMAL_PLACES: 30 })
  BigNumber.config({ EXPONENTIAL_AT: 1e+9 })
  // Unit conversion constants
  const hastingsPerSiacoin = new BigNumber(10).pow(24)

  // Tracks if siad was last known to be running or not
  var running = false
  // Keep reference to `this` to emit events from within contexts where `this`
  // does not point to this class
  var self = this
  // Inherit `EventEmitter` properties
  EventEmitter.call(this)

  /**
   * Relays calls to daemonAPI with the localhost:port address appended
   * @function SiadWrapper#call
   * @param {apiCall} call - function to run if Siad is running
   * @param {apiResponse} callback
   * @returns {object} request call object
   */
  function apiCall (call, callback) {
    // Interpret string-only calls. Will default to 'GET' requests
    if (typeof call === 'string') {
      call = { url: call }
    }

    // Setup request
    call.url = 'http://' + settings.address + call.url
    call.json = true
    call.headers = {
      'User-Agent': 'Sia-Agent'
    }

    // Return the request sent if the user wants to be creative and get more
    // information than what's passed to the callback
    // TODO: Don't understand why the setImmediate is needed, but without it,
    // some calls seem to not return right after another call but eventually do
    // return once another call is made. Some sort of resource blocking is
    // happening
    setImmediate(function () {
      request(call, function (err, response, body) {
        // The error from request should be null if siad is running
        running = !err

        // If siad puts out an error, pass it as first argument to callback
        if (!err && response.statusCode !== 200) {
          err = body
          body = null
        }

        // Return results to callback
        if (callback !== undefined) {
          callback(err, body)
        }
      })
    })
  }

  // Checks whether siad is running on the current address
  function checkIfSiadRunning (callback) {
    return apiCall('/daemon/version', function (err) {
      // There should be no reason this call would error if siad were running
      // and serving requests
      running = !err

      // Return result to callback
      if (callback !== undefined) {
        callback(running)
      }
    })
  }

  /**
   * Checks whether siad is running and runs ones of two callbacks
   * @function SiadWrapper#ifRunning
   * @param {callback} is - called if siad is running
   * @param {callback} not - called if siad is not running
   * @returns {object} request call object
   */
  function ifSiadRunning (is, not) {
    return checkIfSiadRunning(function (running) {
      if (running && is !== undefined) {
        is()
      } else if (not !== undefined) {
        not()
      }
    })
  }

  /**
   * Synchronous way to check if siad is running, may not be up to date
   * @function SiadWrapper#isRunning
   * @returns {boolean} whether siad is running
   */
  function isSiadRunning (callback) {
    return running
  }

  // Polls the siad API until it comes online
  function waitUntilLoaded (callback) {
    return ifSiadRunning(callback, function () {
      setTimeout(function () {
        waitUntilLoaded(callback)
      }, 1000)
    })
  }

  /**
   * Starts the daemon as a long running background process
   * @param {callback} callback - function to be run if successful
   * @returns {boolean} if start was attempted
   */
  function start (callback) {
    // Check if siad is already running
    if (running) {
      if (callback !== null) {
        callback(new Error('Attempted to start siad when it was already running'))
      }
      return false
    }

    // Check synchronously if siad doesn't exist at settings.path
    const fs = require('fs')
    try {
      require('fs').statSync(settings.path)
    } catch (e) {
      if (callback !== null) {
        callback(e)
      }
      return false
    }

    // Set siad folder as configured settings.datadir
    var processOptions = {
      cwd: settings.datadir
    }

    // If the detached option is set, spawn siad as a separate process to be
    // run in the background after the parent process has closed
    if (settings.detached) {
      let log = nodePath.join(settings.datadir, 'out.log')
      let out = fs.openSync(log, 'a')
      let err = fs.openSync(log, 'a')
      processOptions.detached = true
      processOptions.stdio = [ 'ignore', out, err ]
    }

    let daemonProcess
    // Spawn siad
    try {
      const Process = require('child_process').spawn
      daemonProcess = new Process(settings.path, [
        '--api-addr=' + settings.address,
        '--rpc-addr=' + settings.rpcAddress,
        '--host-addr=' + settings.hostAddress,
        '--sia-directory=' + settings.datadir
      ], processOptions)
    } catch (e) {
      if (callback !== null) {
        callback(e)
      }
      return false
    }

    // Exclude it from the parent process' event loop if detached
    if (settings.detached) {
      daemonProcess.unref()
    } else {
      // Listen for siad events and emit them from wrapper
      // TODO: Attach these to siad if it's already running
      var childProcessEvents = ['close', 'disconnect', 'error', 'message']
      childProcessEvents.forEach(function (ev) {
        daemonProcess.on(ev, function (arg1, arg2) {
          self.emit(ev, arg1, arg2)
        })
      })
      daemonProcess.on('exit', function (code) {
        running = false
        self.emit('exit', code)
      })
    }

    // Wait until siad finishes loading to call callback
    waitUntilLoaded(callback)
    return true
  }

  /**
   * Sends a stop call to the daemon
   * @param {callback} callback - function to be run if successful
   * @returns {boolean} if stop was attempted, should always be true
   */
  function stop (callback) {
    apiCall('/daemon/stop', function (err) {
      if (!err) {
        running = false
      }
      if (callback !== undefined) {
        callback(err)
      }
    })
    return true
  }

  /**
   * Sets the member variables based on the passed config. Checks if siad is
   * running on the new configuration so running should be up to date for
   * the callback
   * @param {config} c - the config object derived from config.json
   * @param {callback} callback - first argument is any errors, second argument
   * is the new configuration
   * @returns {object} siad configuration object
   */
  function configure (newSettings, callback) {
    for (let key in settings) {
      // Set passed in settings within siad
      if (settings.hasOwnProperty(key) && newSettings.hasOwnProperty(key)) {
        settings[key] = newSettings[key]
      } else if (settings.hasOwnProperty(key)) {
        // Set settings to sync with siad
        newSettings[key] = settings[key]
      }
    }
    if (callback !== undefined) {
      checkIfSiadRunning(function (check) {
        callback(null, settings)
      })
    }
    return settings
  }

  /**
   * Downloads siad and siac to a specified or default location
   * @param {string} path - An optional location of where to download to
   * @param {callback} callback
   * @returns {boolean} if download was started, should always be true
   */
  function download (path, callback) {
    if (typeof path === 'string') {
      settings.path = path
    } else {
      // the first argument is either undefined or the callback
      callback = path
      path = settings.path
    }
    return require('./download.js')(path, callback)
  }

  // Sia unit conversion functions.
  // Convert Hastings (the base unit) to Siacoin.  Use strings as input to avoid precision loss.
  // @param {hastings :string}
  // @return BigNumber
  function hastingsToSiacoins (hastings) {
    const hastingsNumber = new BigNumber(hastings)
    return hastingsNumber.dividedBy(hastingsPerSiacoin)
  }
  // Convert Siacoin to Hastings.  Use strings as input to avoid precision loss.
  // @params {siacoin :string}
  // @return BigNumber
  function siacoinsToHastings (siacoins) {
    const siacoinNumber = new BigNumber(siacoins)
    return siacoinNumber.times(hastingsPerSiacoin)
  }

  // Make certain members public
  this.call = apiCall
  this.ifRunning = ifSiadRunning
  this.isRunning = isSiadRunning
  this.start = start
  this.stop = stop
  this.configure = configure
  this.download = download
  this.siacoinsToHastings = siacoinsToHastings
  this.hastingsToSiacoins = hastingsToSiacoins
}

// Inherit functions from `EventEmitter`'s prototype
Util.inherits(SiadWrapper, EventEmitter)

module.exports = new SiadWrapper()
<|endoftext|>


<commit_before>// import * as types from "../types";

export function ImportDeclaration(node) {
    const hasNewlines = this.nodeContainsNewlines(node);

    this.ensure("import");
    this.ensureSpace();

    if (node.isType) {
        this.ensure("type");
        this.ensureSpace();
    }

    if (node.specifiers.length) {
        let didIndent = false;

        for (let [index, specifier] of node.specifiers.entries()) {
            let isLast = index + 1 === node.specifiers.length;

            if (this.isCurrent("{")) {

                this.ensure("{");

                if (hasNewlines) {
                    didIndent = true;
                    this.indent();
                    this.ensureNewline();
                } else {
                    this.ensureSpace();
                }
            }

            this.insertIndentation();
            this.print(specifier);

            if (isLast) {
                if (didIndent) {
                    this.dedent();
                    this.ensureNewline();
                } else {
                    this.ensureSpace();
                }

                if (this.isCurrent("}")) {
                    this.ensure("}");
                    this.ensureSpace();
                }

            } else {
                this.ensureVoid();
                this.ensure(",");

                if (didIndent) {
                    this.ensureNewline();
                } else {
                    this.ensureSpace();
                }
            }
        }

        this.ensure("from");
        this.ensureSpace();
    }

    this.print(node.source);
    this.ensureVoid();
    this.ensure(";");
}

export function ImportSpecifier(node) {
    this.print(node.local);

    if (node.local && node.local !== node.imported) {
        this.ensureSpace();
        this.ensure("as");
        this.ensureSpace();
        this.print(node.imported);
    }
}

export function ImportDefaultSpecifier(node) {
    this.print(node.local);
}

export function ImportNamespaceSpecifier(node) {
    this.ensure("*");
    this.ensureSpace();
    this.ensure("as");
    this.ensureSpace();
    this.print(node.local);
}

export function ExportDefaultSpecifier(node) {
    this.print(node.exported);
}

export function ExportSpecifier(node) {
    this.print(node.local);
    if (node.exported && node.local.name !== node.exported.name) {
        this.ensureSpace();
        this.ensure("as");
        this.ensureSpace();
        this.print(node.exported);
    }
}

export function ExportNamespaceSpecifier(node) {
    this.ensure("*");
    this.ensureSpace();
    this.ensure("as");
    this.ensureSpace();
    this.print(node.exported);
}

export function ExportAllDeclaration(node) {
    this.ensure("export");
    this.ensureSpace();
    this.ensure("*");

    if (node.exported) {
        this.ensureSpace();
        this.ensure("as");
        this.ensureSpace();
        this.print(node.exported);
    }

    this.ensureSpace();
    this.ensure("from");
    this.ensureSpace();

    this.print(node.source);

    this.ensureVoid();
    this.ensure(";");
}

export function ExportNamedDeclaration(node) {
    this.ensure("export");
    this.ensureSpace();

    ExportDeclaration.call(this, node);

    if (this.isNext(";")) {
        this.ensureVoid();
        this.ensure(";");
    } else if (this.isCurrent(";")) {
        this.ensure(";");
    }
}

export function ExportDefaultDeclaration(node) {
    this.ensure("export");
    this.ensureSpace();
    this.ensure("default");
    this.ensureSpace();
    ExportDeclaration.call(this, node);
}

function ExportDeclaration(node) {
    if (node.declaration) {
        this.print(node.declaration);
    } else {
        const hasNewlines = this.nodeContainsNewlines(node);

        if (node.specifiers.length) {
            let didIndent = false;

            for (let [index, specifier] of node.specifiers.entries()) {
                let isLast = index + 1 === node.specifiers.length;

                process.stdout.write("\n");

                if (this.isCurrent("{")) {

                    this.ensure("{");

                    if (hasNewlines) {
                        didIndent = true;
                        this.indent();
                        this.ensureNewline();
                    } else {
                        this.ensureSpace();
                    }
                }

                this.print(specifier);

                if (isLast) {
                    if (didIndent) {
                        this.dedent();
                        this.ensureNewline();
                    } else {
                        this.ensureSpace();
                    }

                    if (this.isCurrent("}")) {
                        this.ensure("}");
                    }
                } else {
                    this.ensureVoid();
                    this.ensure(",");

                    if (didIndent) {
                        this.ensureNewline();
                    } else {
                        this.ensureSpace();
                    }
                }
            }

        }

        if (node.source) {
            this.ensureSpace();
            this.ensure("from");
            this.ensureSpace();
            this.print(node.source);
        }
    }
}
<commit_msg>Don't print newlines to stdout in ExportDeclarations.<commit_after>// import * as types from "../types";

export function ImportDeclaration(node) {
    const hasNewlines = this.nodeContainsNewlines(node);

    this.ensure("import");
    this.ensureSpace();

    if (node.isType) {
        this.ensure("type");
        this.ensureSpace();
    }

    if (node.specifiers.length) {
        let didIndent = false;

        for (let [index, specifier] of node.specifiers.entries()) {
            let isLast = index + 1 === node.specifiers.length;

            if (this.isCurrent("{")) {

                this.ensure("{");

                if (hasNewlines) {
                    didIndent = true;
                    this.indent();
                    this.ensureNewline();
                } else {
                    this.ensureSpace();
                }
            }

            this.insertIndentation();
            this.print(specifier);

            if (isLast) {
                if (didIndent) {
                    this.dedent();
                    this.ensureNewline();
                } else {
                    this.ensureSpace();
                }

                if (this.isCurrent("}")) {
                    this.ensure("}");
                    this.ensureSpace();
                }

            } else {
                this.ensureVoid();
                this.ensure(",");

                if (didIndent) {
                    this.ensureNewline();
                } else {
                    this.ensureSpace();
                }
            }
        }

        this.ensure("from");
        this.ensureSpace();
    }

    this.print(node.source);
    this.ensureVoid();
    this.ensure(";");
}

export function ImportSpecifier(node) {
    this.print(node.local);

    if (node.local && node.local !== node.imported) {
        this.ensureSpace();
        this.ensure("as");
        this.ensureSpace();
        this.print(node.imported);
    }
}

export function ImportDefaultSpecifier(node) {
    this.print(node.local);
}

export function ImportNamespaceSpecifier(node) {
    this.ensure("*");
    this.ensureSpace();
    this.ensure("as");
    this.ensureSpace();
    this.print(node.local);
}

export function ExportDefaultSpecifier(node) {
    this.print(node.exported);
}

export function ExportSpecifier(node) {
    this.print(node.local);
    if (node.exported && node.local.name !== node.exported.name) {
        this.ensureSpace();
        this.ensure("as");
        this.ensureSpace();
        this.print(node.exported);
    }
}

export function ExportNamespaceSpecifier(node) {
    this.ensure("*");
    this.ensureSpace();
    this.ensure("as");
    this.ensureSpace();
    this.print(node.exported);
}

export function ExportAllDeclaration(node) {
    this.ensure("export");
    this.ensureSpace();
    this.ensure("*");

    if (node.exported) {
        this.ensureSpace();
        this.ensure("as");
        this.ensureSpace();
        this.print(node.exported);
    }

    this.ensureSpace();
    this.ensure("from");
    this.ensureSpace();

    this.print(node.source);

    this.ensureVoid();
    this.ensure(";");
}

export function ExportNamedDeclaration(node) {
    this.ensure("export");
    this.ensureSpace();

    ExportDeclaration.call(this, node);

    if (this.isNext(";")) {
        this.ensureVoid();
        this.ensure(";");
    } else if (this.isCurrent(";")) {
        this.ensure(";");
    }
}

export function ExportDefaultDeclaration(node) {
    this.ensure("export");
    this.ensureSpace();
    this.ensure("default");
    this.ensureSpace();
    ExportDeclaration.call(this, node);
}

function ExportDeclaration(node) {
    if (node.declaration) {
        this.print(node.declaration);
    } else {
        const hasNewlines = this.nodeContainsNewlines(node);

        if (node.specifiers.length) {
            let didIndent = false;

            for (let [index, specifier] of node.specifiers.entries()) {
                let isLast = index + 1 === node.specifiers.length;

                if (this.isCurrent("{")) {

                    this.ensure("{");

                    if (hasNewlines) {
                        didIndent = true;
                        this.indent();
                        this.ensureNewline();
                    } else {
                        this.ensureSpace();
                    }
                }

                this.print(specifier);

                if (isLast) {
                    if (didIndent) {
                        this.dedent();
                        this.ensureNewline();
                    } else {
                        this.ensureSpace();
                    }

                    if (this.isCurrent("}")) {
                        this.ensure("}");
                    }
                } else {
                    this.ensureVoid();
                    this.ensure(",");

                    if (didIndent) {
                        this.ensureNewline();
                    } else {
                        this.ensureSpace();
                    }
                }
            }

        }

        if (node.source) {
            this.ensureSpace();
            this.ensure("from");
            this.ensureSpace();
            this.print(node.source);
        }
    }
}
<|endoftext|>


<commit_before>'use strict';

function loadBadgeCategories(args, callback) {
  var categories = ['programming', 'attendance', 'mentor', 'events'];
  callback(null, {categories: categories});
}

module.exports = loadBadgeCategories;

<commit_msg>remove attendance catergory<commit_after>'use strict';

function loadBadgeCategories(args, callback) {
  var categories = ['programming', 'mentor', 'events'];
  callback(null, {categories: categories});
}

module.exports = loadBadgeCategories;

<|endoftext|>


<commit_before>TrelloPowerUp.initialize({
  'board-buttons': function(t, options){
    return [{
    icon: './images/Trane_logo.svg',
    text: 'Trane Button',
    callback: function(t){
      alert("hey!");
    }}];
  },
  'show-settings': function(t, options){
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184
    });
  }
});
<commit_msg>modified trane logo img<commit_after>TrelloPowerUp.initialize({
  'board-buttons': function(t, options){
    return [{
    icon: './images/Trane_logo_crop.png',
    text: 'Trane Button',
    callback: function(t){
      alert("hey!");
    }}];
  },
  'show-settings': function(t, options){
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184
    });
  }
});
<|endoftext|>