<commit_before>var BOARD_HEIGHT = 288;
var BOARD_WIDTH = 224;
var VERT_TILES = BOARD_HEIGHT / 8;
var HORIZ_TILES = BOARD_WIDTH / 8;

gameBoard = new Array(VERT_TILES);
for(var y = 0; y < VERT_TILES; y++) {
  gameBoard[y] = new Array(HORIZ_TILES);
  for(var x = 0; x < HORIZ_TILES; x++) {
    gameBoard[y][x] = "";
  }
}

var canvas, context, canvasData;

var drawPixel = function(args) {
  var index = (args.x + args.y * canvas.width) * 4;

  canvasData.data[index + 0] = args.r;
  canvasData.data[index + 1] = args.g;
  canvasData.data[index + 2] = args.b;
  canvasData.data[index + 3] = args.a;
}

var drawObject = function(args) {
  var width = args.objectArr.length;
  var height = args.objectArr[0].length;
  context.clearRect(args.x, args.y, width, height);

  args.objectArr.forEach(function(row, rIndex) {
    row.forEach(function(col, cIndex) {
      if(col == "x") {
        drawPixel({
          x: args.x + cIndex,
          y: args.y + rIndex,
          r: args.color.r,
          g: args.color.g,
          b: args.color.b,
          a: args.color.a
        });
      }
    });
  });
}

var drawPac = function(x, y) {
  context.fillStyle = "#FF0";
  context.beginPath();
  context.arc(x, y, 6, 0.25 * Math.PI, 1.75 * Math.PI, false);
  context.lineTo(x, y);
  context.closePath();
  context.fill();
}
var drawGhost = function(xPos, yPos, color, direction, step) {
  context.clearRect(xPos - 7, yPos - 7, 14, 16);

  context.fillStyle = color;
  var x = new Number(xPos);
  var y = new Number(yPos);

  // body
  context.beginPath();
  context.arc(x, y, 6, Math.PI, 0, false);
  context.moveTo(x += 7, y);
  context.lineTo(x, y += 5);
  context.lineTo(x -= 14, y);
  context.lineTo(x, y -= 5);
  context.closePath();
  context.fill();

  drawGhostTendrils(xPos, yPos, step);
  drawGhostEyes(xPos, yPos, direction);
}
var drawGhostEyes = function(ghostX, ghostY, direction) {
  context.fillStyle = "#FFF";
  var x = ghostX -= 3;
  var y = ghostY -= 3;

  switch(direction) {
    case "up": y -= 2; break;
    case "down": y += 1; break;
    case "left": x--; break;
    case "right": x++; break;
  }

  // Whites of eyes
  context.beginPath();
  context.moveTo(x, y);
  context.lineTo(x += 0.5, y);
  context.lineTo(x += 1.5, y += 1.5);
  context.lineTo(x, y += 2);
  context.lineTo(x -= 1.5, y += 1.5);
  context.lineTo(x -= 1, y);
  context.lineTo(x -= 1.5, y -= 1.5);
  context.lineTo(x, y -= 2);
  context.lineTo(x += 1.5, y -= 1.5);
  context.moveTo(x += 6.5, y);
  context.lineTo(x += 0.5, y);
  context.lineTo(x += 1.5, y += 1.5);
  context.lineTo(x, y += 2);
  context.lineTo(x -= 1.5, y += 1.5);
  context.lineTo(x -= 1, y);
  context.lineTo(x -= 1.5, y -= 1.5);
  context.lineTo(x, y -= 2);
  context.lineTo(x += 1.5, y -= 1.5);
  context.fill();

  switch(direction) {
    case "up":
      x = ghostX - 1;
      y = ghostY - 2;
    break;
    case "down":
      x = ghostX - 1;
      y = ghostY + 4;
    break;
    case "left":
      x = ghostX - 3;
      y = ghostY + 2;
    break;
    case "right":
      x = ghostX + 1;
      y = ghostY + 2;
    break;
  }

  context.fillStyle = "#22F";
  context.fillRect(x, y, 2, 2);
  context.fillRect(x += 6, y, 2, 2);
}
var drawGhostTendrils = function(ghostX, ghostY, step) {
  var x = ghostX + 7;
  var y = ghostY + 5;

  context.moveTo(x, y);
  switch(step) {
    case 0:
      context.lineTo(x, y += 3);
      context.lineTo(x -= 1, y);
      context.lineTo(x -= 2, y -= 2.5);
      context.lineTo(x -= 2, y += 2.5);
      context.lineTo(x -= 1, y);
      context.lineTo(x, y -= 2);
      context.lineTo(x -= 2, y);
      context.lineTo(x, y += 2);
      context.lineTo(x -= 1, y);
      context.lineTo(x -= 2, y -= 2.5);
      context.lineTo(x -= 2, y += 2.5);
      context.lineTo(x -= 1, y);
      context.lineTo(x, y -= 3);
    break;
    case 1:
      context.lineTo(x, y += 1);
      context.lineTo(x -= 2, y += 2.5);
      context.lineTo(x -= 2, y -= 2.5);
      context.lineTo(x -= 1, y);
      context.lineTo(x -= 2, y += 2.5);
      context.lineTo(x -= 2, y -= 2.5);
      context.lineTo(x -= 1, y);
      context.lineTo(x -= 2, y += 2.5);
      context.lineTo(x -= 2, y -= 2.5);
      context.lineTo(x, y -= 1);
    break;
  }
  context.closePath();
  context.fill();
}

var aCxt, pacOsc, pacGain, pacModOsc, pacModGain;

var initAudio = function() {
  aCxt = !!AudioContext ? new AudioContext() : new webkitAudioContext();
  pacOsc = aCxt.createOscillator();
  pacModOsc = aCxt.createOscillator();
  pacGain = aCxt.createGain();
  pacModGain = aCxt.createGain();

  pacOsc.connect(pacGain);
  pacGain.connect(aCxt.destination);
  pacModOsc.connect(pacModGain);
  pacModGain.connect(pacOsc.frequency);

  pacModOsc.type = "triangle";
  pacOsc.type = "triangle";
  pacOsc.frequency.value = 415;
  pacGain.gain.value = 0.1;
  pacModOsc.frequency.value = 2.67;
  pacModGain.gain.value = 100;
}

var startPacAudio = function(seconds) {
  var runSeconds = seconds || 2;
  pacOsc.start();
  pacModOsc.start();
  pacOsc.stop(runSeconds);
  pacModOsc.stop(runSeconds);
}

var ready = function(fun) {
  if(document.readyState != "loading") {
    fun();
  }
  else if(document.addEventListener) {
    document.addEventListener("DOMContentLoaded", fun);
  }
  else {
    document.attachEvent("onreadystatechange", function() {
      if(document.readyState != "loading") {
        fun();
      }
    });
  }
}

ready(function() {
  canvas = document.getElementById("board");
  context = canvas.getContext("2d");
  canvasData = context.getImageData(0, 0, canvas.width, canvas.height);

  var debugDisp = document.getElementById("debug");

  var x = 8;
  var y = 8;
  for(var prop in charset) {
    drawObject({
      x: x,
      y: y,
      objectArr: charset[prop],
      color: {r: 255, g: 255, b: 255, a: 255}
    });
    x += 8;
    if(x + 8 > BOARD_WIDTH) {
      x = 8;
      y += 8;
    }
  }

  context.putImageData(canvasData, 0, 0);

  drawBorders();

  // Green grid to delineate 8 x 8 tiles
  // context.fillStyle = "#080";
  // for(var x = 0; x < BOARD_WIDTH; x += 8) {
  //   context.fillRect(x, 0, 1, BOARD_HEIGHT);
  // }
  // for(var y = 0; y < BOARD_HEIGHT; y += 8) {
  //   context.fillRect(0, y, BOARD_WIDTH, 1);
  // }

  drawPac(113, 212);

  var step = 0;
  setInterval(function() {
    if(step == 0) step = 1;
    else step = 0;

    drawGhost(112, 115, "#F00", "left", step);
    drawGhost(96, 139, "#4FF", "up", step);
    drawGhost(112, 139, "#FCF", "right", step);
    drawGhost(128, 139, "#FA6", "down", step);
  }, 250);
});
<commit_msg>Update drawPac to clear rect before rendering<commit_after>var BOARD_HEIGHT = 288;
var BOARD_WIDTH = 224;
var VERT_TILES = BOARD_HEIGHT / 8;
var HORIZ_TILES = BOARD_WIDTH / 8;

gameBoard = new Array(VERT_TILES);
for(var y = 0; y < VERT_TILES; y++) {
  gameBoard[y] = new Array(HORIZ_TILES);
  for(var x = 0; x < HORIZ_TILES; x++) {
    gameBoard[y][x] = "";
  }
}

var canvas, context, canvasData;

var drawPixel = function(args) {
  var index = (args.x + args.y * canvas.width) * 4;

  canvasData.data[index + 0] = args.r;
  canvasData.data[index + 1] = args.g;
  canvasData.data[index + 2] = args.b;
  canvasData.data[index + 3] = args.a;
}

var drawObject = function(args) {
  var width = args.objectArr.length;
  var height = args.objectArr[0].length;
  context.clearRect(args.x, args.y, width, height);

  args.objectArr.forEach(function(row, rIndex) {
    row.forEach(function(col, cIndex) {
      if(col == "x") {
        drawPixel({
          x: args.x + cIndex,
          y: args.y + rIndex,
          r: args.color.r,
          g: args.color.g,
          b: args.color.b,
          a: args.color.a
        });
      }
    });
  });
}

var drawPac = function(x, y) {
  context.clearRect(x - 7, y - 7, 14, 14);

  context.fillStyle = "#FF0";
  context.beginPath();
  context.arc(x, y, 6, 0.25 * Math.PI, 1.75 * Math.PI, false);
  context.lineTo(x, y);
  context.closePath();
  context.fill();
}

var drawGhost = function(xPos, yPos, color, direction, step) {
  context.clearRect(xPos - 7, yPos - 7, 14, 16);

  context.fillStyle = color;
  var x = new Number(xPos);
  var y = new Number(yPos);

  // body
  context.beginPath();
  context.arc(x, y, 6, Math.PI, 0, false);
  context.moveTo(x += 7, y);
  context.lineTo(x, y += 5);
  context.lineTo(x -= 14, y);
  context.lineTo(x, y -= 5);
  context.closePath();
  context.fill();

  drawGhostTendrils(xPos, yPos, step);
  drawGhostEyes(xPos, yPos, direction);
}
var drawGhostEyes = function(ghostX, ghostY, direction) {
  context.fillStyle = "#FFF";
  var x = ghostX -= 3;
  var y = ghostY -= 3;

  switch(direction) {
    case "up": y -= 2; break;
    case "down": y += 1; break;
    case "left": x--; break;
    case "right": x++; break;
  }

  // Whites of eyes
  context.beginPath();
  context.moveTo(x, y);
  context.lineTo(x += 0.5, y);
  context.lineTo(x += 1.5, y += 1.5);
  context.lineTo(x, y += 2);
  context.lineTo(x -= 1.5, y += 1.5);
  context.lineTo(x -= 1, y);
  context.lineTo(x -= 1.5, y -= 1.5);
  context.lineTo(x, y -= 2);
  context.lineTo(x += 1.5, y -= 1.5);
  context.moveTo(x += 6.5, y);
  context.lineTo(x += 0.5, y);
  context.lineTo(x += 1.5, y += 1.5);
  context.lineTo(x, y += 2);
  context.lineTo(x -= 1.5, y += 1.5);
  context.lineTo(x -= 1, y);
  context.lineTo(x -= 1.5, y -= 1.5);
  context.lineTo(x, y -= 2);
  context.lineTo(x += 1.5, y -= 1.5);
  context.fill();

  switch(direction) {
    case "up":
      x = ghostX - 1;
      y = ghostY - 2;
    break;
    case "down":
      x = ghostX - 1;
      y = ghostY + 4;
    break;
    case "left":
      x = ghostX - 3;
      y = ghostY + 2;
    break;
    case "right":
      x = ghostX + 1;
      y = ghostY + 2;
    break;
  }

  context.fillStyle = "#22F";
  context.fillRect(x, y, 2, 2);
  context.fillRect(x += 6, y, 2, 2);
}
var drawGhostTendrils = function(ghostX, ghostY, step) {
  var x = ghostX + 7;
  var y = ghostY + 5;

  context.moveTo(x, y);
  switch(step) {
    case 0:
      context.lineTo(x, y += 3);
      context.lineTo(x -= 1, y);
      context.lineTo(x -= 2, y -= 2.5);
      context.lineTo(x -= 2, y += 2.5);
      context.lineTo(x -= 1, y);
      context.lineTo(x, y -= 2);
      context.lineTo(x -= 2, y);
      context.lineTo(x, y += 2);
      context.lineTo(x -= 1, y);
      context.lineTo(x -= 2, y -= 2.5);
      context.lineTo(x -= 2, y += 2.5);
      context.lineTo(x -= 1, y);
      context.lineTo(x, y -= 3);
    break;
    case 1:
      context.lineTo(x, y += 1);
      context.lineTo(x -= 2, y += 2.5);
      context.lineTo(x -= 2, y -= 2.5);
      context.lineTo(x -= 1, y);
      context.lineTo(x -= 2, y += 2.5);
      context.lineTo(x -= 2, y -= 2.5);
      context.lineTo(x -= 1, y);
      context.lineTo(x -= 2, y += 2.5);
      context.lineTo(x -= 2, y -= 2.5);
      context.lineTo(x, y -= 1);
    break;
  }
  context.closePath();
  context.fill();
}

var aCxt, pacOsc, pacGain, pacModOsc, pacModGain;

var initAudio = function() {
  aCxt = !!AudioContext ? new AudioContext() : new webkitAudioContext();
  pacOsc = aCxt.createOscillator();
  pacModOsc = aCxt.createOscillator();
  pacGain = aCxt.createGain();
  pacModGain = aCxt.createGain();

  pacOsc.connect(pacGain);
  pacGain.connect(aCxt.destination);
  pacModOsc.connect(pacModGain);
  pacModGain.connect(pacOsc.frequency);

  pacModOsc.type = "triangle";
  pacOsc.type = "triangle";
  pacOsc.frequency.value = 415;
  pacGain.gain.value = 0.1;
  pacModOsc.frequency.value = 2.67;
  pacModGain.gain.value = 100;
}

var startPacAudio = function(seconds) {
  var runSeconds = seconds || 2;
  pacOsc.start();
  pacModOsc.start();
  pacOsc.stop(runSeconds);
  pacModOsc.stop(runSeconds);
}

var ready = function(fun) {
  if(document.readyState != "loading") {
    fun();
  }
  else if(document.addEventListener) {
    document.addEventListener("DOMContentLoaded", fun);
  }
  else {
    document.attachEvent("onreadystatechange", function() {
      if(document.readyState != "loading") {
        fun();
      }
    });
  }
}

ready(function() {
  canvas = document.getElementById("board");
  context = canvas.getContext("2d");
  canvasData = context.getImageData(0, 0, canvas.width, canvas.height);

  var debugDisp = document.getElementById("debug");

  var x = 8;
  var y = 8;
  for(var prop in charset) {
    drawObject({
      x: x,
      y: y,
      objectArr: charset[prop],
      color: {r: 255, g: 255, b: 255, a: 255}
    });
    x += 8;
    if(x + 8 > BOARD_WIDTH) {
      x = 8;
      y += 8;
    }
  }

  context.putImageData(canvasData, 0, 0);

  drawBorders();

  // Green grid to delineate 8 x 8 tiles
  // context.fillStyle = "#080";
  // for(var x = 0; x < BOARD_WIDTH; x += 8) {
  //   context.fillRect(x, 0, 1, BOARD_HEIGHT);
  // }
  // for(var y = 0; y < BOARD_HEIGHT; y += 8) {
  //   context.fillRect(0, y, BOARD_WIDTH, 1);
  // }

  drawPac(113, 212);

  var step = 0;
  setInterval(function() {
    if(step == 0) step = 1;
    else step = 0;

    drawGhost(112, 115, "#F00", "left", step);
    drawGhost(96, 139, "#4FF", "up", step);
    drawGhost(112, 139, "#FCF", "right", step);
    drawGhost(128, 139, "#FA6", "down", step);
  }, 250);
});
<|endoftext|>


<commit_before><commit_msg>Fix typo with object<commit_after><|endoftext|>


<commit_before>import test from 'ava';
import * as string from '../../src';
test('string', t => {
	var c = '7';
	var n = 10;
	var mul = string.mul;

	var lfill = string.__lfill__(c, n, mul);
	var rfill = string.__rfill__(c, n, mul);

	t.deepEqual(lfill('jjj'), '7777777jjj', 'lfill');
	t.deepEqual(rfill('jjj'), 'jjj7777777', 'rfill');
});
<commit_msg>:art: style: Format misc test.<commit_after>import test from 'ava';
import * as string from '../../src';
test('fill', t => {
	const c = '7';
	const n = 10;
	const mul = string.mul;

	const lfill = string.__lfill__(c, n, mul);
	const rfill = string.__rfill__(c, n, mul);

	t.deepEqual(lfill('jjj'), '7777777jjj', 'lfill');
	t.deepEqual(rfill('jjj'), 'jjj7777777', 'rfill');
});
<|endoftext|>


<commit_before>'use 6to6';

module.exports = v => v + 1
<commit_msg>Change invalid.js fixture for babel transpilation<commit_after>'use 6to6';

module.exports = async function hello() {}
<|endoftext|>


<commit_before><commit_msg>メニューが正しくdestroyできていない問題を修正<commit_after><|endoftext|>


<commit_before><commit_msg>MINOR<commit_after><|endoftext|>


<commit_before><commit_msg>Simpler tests<commit_after><|endoftext|>


<commit_before><commit_msg>helper for multiple sending messages<commit_after><|endoftext|>


<commit_before><commit_msg>jshint errors fixed<commit_after><|endoftext|>


<commit_before>var validator = require('validator');

module.exports = {

  find: function(req, res) {
    Community.fetchAll().then(res.ok).catch(res.serverError);
  },

  findOne: function(req, res) {
    var community = res.locals.community;

    return Promise.method(() => community.get('network_id') ? community.load('network') : null)()
    .then(() => community.pick('id', 'name', 'slug', 'avatar_url', 'banner_url', 'description', 'settings'))
    .tap(data => {
      var network = community.relations.network;
      if (network) data.network = network.pick('id', 'name', 'slug');
    })
    .then(res.ok)
    .catch(res.serverError);
  },

  findSettings: function(req, res) {
    Community.find(req.param('communityId'), {withRelated: ['leader']})
    .then(community => _.merge(community.pick(
      'welcome_message', 'beta_access_code', 'settings'
    ), {
      leader: community.relations.leader.pick('id', 'name', 'avatar_url')
    }))
    .then(res.ok)
    .catch(res.serverError);
  },

  update: function(req, res) {
    var whitelist = [
        'banner_url', 'avatar_url', 'name', 'description', 'settings',
        'welcome_message', 'leader_id', 'beta_access_code'
      ],
      attributes = _.pick(req.allParams(), whitelist),
      community = new Community({id: req.param('communityId')});

    community.save(attributes, {patch: true})
    .then(() => res.ok({}))
    .catch(res.serverError);
  },

  invite: function(req, res) {
    Community.find(req.param('communityId'))
    .then(function(community) {

      var emails = (req.param('emails') || '').split(',').map(function(email) {
        var trimmed = email.trim(),
          matchLongFormat = trimmed.match(/.*<(.*)>/);

        if (matchLongFormat) return matchLongFormat[1];
        return trimmed;
      });

      return Promise.map(emails, function(email) {
        if (!validator.isEmail(email)) {
          return {email: email, error: "not a valid email address"};
        }

        return Invitation.createAndSend({
          email:       email,
          userId:      req.session.userId,
          communityId: community.id,
          message:     RichText.markdown(req.param('message')),
          moderator:   req.param('moderator'),
          subject:     req.param('subject')
        }).then(function() {
          return {email: email, error: null};
        }).catch(function(err) {
          return {email: email, error: err.message};
        });
      });

    })
    .then(results => res.ok({results: results}));
  },

  findModerators: function(req, res) {
    Community.find(req.param('communityId')).then(function(community) {
      return community.moderators().fetch();
    }).then(function(moderators) {
      res.ok(moderators.map(function(user) {
        return {
          id: user.id,
          name: user.get('name'),
          avatar_url: user.get('avatar_url')
        };
      }));
    });
  },

  addModerator: function(req, res) {
    Membership.setModeratorRole(req.param('userId'), req.param('communityId'))
    .then(() => res.ok({}))
    .catch(res.serverError);
  },

  removeModerator: function(req, res) {
    Membership.removeModeratorRole(req.param('userId'), req.param('communityId'))
    .then(() => res.ok({}))
    .catch(res.serverError);
  },

  joinWithCode: function(req, res) {
    Community.query('whereRaw', 'lower(beta_access_code) = lower(?)', req.param('code')).fetch()
    .tap(community => Membership.create(req.session.userId, community.id))
    .then(community => res.ok(community.pick('id', 'slug')))
    .catch(err => {
      if (err.message && err.message.contains('duplicate key value')) {
        res.ok(community.pick('id', 'slug'));
      } else {
        res.serverError(err);
      }
    });
  },

  leave: function(req, res) {
    res.locals.membership.destroyMe()
    .then(() => res.ok({}))
    .catch(res.serverError);
  },

  removeMember: function(req, res) {
    Membership.find(req.param('userId'), req.param('communityId'))
    .then(membership => membership.save({
      active: false,
      deactivated_at: new Date(),
      deactivator_id: req.session.userId
    }, {patch: true}))
    .then(() => res.ok({}))
    .catch(res.serverError);
  },

  validate: function(req, res) {
    var allowedColumns = ['name', 'slug', 'beta_access_code'],
      allowedConstraints = ['exists', 'unique'],
      params = _.pick(req.allParams(), 'constraint', 'column', 'value');

    // prevent SQL injection
    if (!_.include(allowedColumns, params.column))
      return res.badRequest(format('invalid value "%s" for parameter "column"', params.column));

    if (!params.value)
      return res.badRequest('missing required parameter "value"');

    if (!_.include(allowedConstraints, params.constraint))
      return res.badRequest(format('invalid value "%s" for parameter "constraint"', params.constraint));

    var statement = format('lower(%s) = lower(?)', params.column);
    Community.query().whereRaw(statement, params.value).count()
    .then(function(rows) {
      var data;
      if (params.constraint === 'unique') {
        data = {unique: parseInt(rows[0].count) === 0};
      } else if (params.constraint === 'exists') {
        var exists = parseInt(rows[0].count) >= 1;
        data = {exists: exists};
      }
      res.ok(data);
    })
    .catch(res.serverError.bind(res));
  },

  create: function(req, res) {
    var attrs = _.pick(req.allParams(),
      'name', 'description', 'slug', 'category',
      'beta_access_code', 'banner_url', 'avatar_url');

    var community = new Community(_.merge(attrs, {
      created_at: new Date(),
      created_by_id: req.session.userId
    }));

    if (process.env.NODE_ENV) {
      community.set('leader_id', 21);
      community.set('welcome_message', "Thank you for joining us here at Hylo. " +
        "Through our communities, we can find everything we need. If we share " +
        "with each other the unique gifts and intentions we each have, we can " +
        "create extraordinary things. Let's get started!");
    }

    bookshelf.transaction(function(trx) {
      return community.save(null, {transacting: trx})
      .tap(() => Membership.create(req.session.userId, community.id, {
        role: Membership.MODERATOR_ROLE,
        transacting: trx
      }));
    })
    // The assets were uploaded to /community/new, since we didn't have an id;
    // copy them over to /community/:id now
    .tap(community => Queue.classMethod('Community', 'copyAssets', {communityId: community.id}))
    // FIXME this additional lookup wouldn't be necessary
    // if we had a Membership instance from the previous
    // step. But the absence of an id column on the table
    // doesn't play nice with Bookshelf.
    .then(() => Membership.find(req.session.userId, community.id, {withRelated: ['community']}))
    .then(res.ok)
    .catch(res.serverError);
  },

  findForNetwork: function(req, res) {
    Community.where('network_id', req.param('networkId'))
    .fetchAll({withRelated: ['memberships']})
    .then(communities => communities.map(c =>
      _.extend(c.pick('id', 'name', 'slug', 'avatar_url', 'banner_url'), {
        memberCount: c.relations.memberships.length
      })))
    .then(communities => _.sortBy(communities, c => -c.memberCount))
    .then(res.ok)
    .catch(res.serverError);
  }

};<commit_msg>don't fail if there is no community leader set<commit_after>var validator = require('validator');

module.exports = {

  find: function(req, res) {
    Community.fetchAll().then(res.ok).catch(res.serverError);
  },

  findOne: function(req, res) {
    var community = res.locals.community;

    return Promise.method(() => community.get('network_id') ? community.load('network') : null)()
    .then(() => community.pick('id', 'name', 'slug', 'avatar_url', 'banner_url', 'description', 'settings'))
    .tap(data => {
      var network = community.relations.network;
      if (network) data.network = network.pick('id', 'name', 'slug');
    })
    .then(res.ok)
    .catch(res.serverError);
  },

  findSettings: function(req, res) {
    var leader;
    Community.find(req.param('communityId'), {withRelated: ['leader']})
    .tap(community => leader = community.relations.leader)
    .then(community => _.merge(community.pick(
      'welcome_message', 'beta_access_code', 'settings'
    ), {
      leader: leader ? leader.pick('id', 'name', 'avatar_url') : null
    }))
    .then(res.ok)
    .catch(res.serverError);
  },

  update: function(req, res) {
    var whitelist = [
        'banner_url', 'avatar_url', 'name', 'description', 'settings',
        'welcome_message', 'leader_id', 'beta_access_code'
      ],
      attributes = _.pick(req.allParams(), whitelist),
      community = new Community({id: req.param('communityId')});

    community.save(attributes, {patch: true})
    .then(() => res.ok({}))
    .catch(res.serverError);
  },

  invite: function(req, res) {
    Community.find(req.param('communityId'))
    .then(function(community) {

      var emails = (req.param('emails') || '').split(',').map(function(email) {
        var trimmed = email.trim(),
          matchLongFormat = trimmed.match(/.*<(.*)>/);

        if (matchLongFormat) return matchLongFormat[1];
        return trimmed;
      });

      return Promise.map(emails, function(email) {
        if (!validator.isEmail(email)) {
          return {email: email, error: "not a valid email address"};
        }

        return Invitation.createAndSend({
          email:       email,
          userId:      req.session.userId,
          communityId: community.id,
          message:     RichText.markdown(req.param('message')),
          moderator:   req.param('moderator'),
          subject:     req.param('subject')
        }).then(function() {
          return {email: email, error: null};
        }).catch(function(err) {
          return {email: email, error: err.message};
        });
      });

    })
    .then(results => res.ok({results: results}));
  },

  findModerators: function(req, res) {
    Community.find(req.param('communityId')).then(function(community) {
      return community.moderators().fetch();
    }).then(function(moderators) {
      res.ok(moderators.map(function(user) {
        return {
          id: user.id,
          name: user.get('name'),
          avatar_url: user.get('avatar_url')
        };
      }));
    });
  },

  addModerator: function(req, res) {
    Membership.setModeratorRole(req.param('userId'), req.param('communityId'))
    .then(() => res.ok({}))
    .catch(res.serverError);
  },

  removeModerator: function(req, res) {
    Membership.removeModeratorRole(req.param('userId'), req.param('communityId'))
    .then(() => res.ok({}))
    .catch(res.serverError);
  },

  joinWithCode: function(req, res) {
    Community.query('whereRaw', 'lower(beta_access_code) = lower(?)', req.param('code')).fetch()
    .tap(community => Membership.create(req.session.userId, community.id))
    .then(community => res.ok(community.pick('id', 'slug')))
    .catch(err => {
      if (err.message && err.message.contains('duplicate key value')) {
        res.ok(community.pick('id', 'slug'));
      } else {
        res.serverError(err);
      }
    });
  },

  leave: function(req, res) {
    res.locals.membership.destroyMe()
    .then(() => res.ok({}))
    .catch(res.serverError);
  },

  removeMember: function(req, res) {
    Membership.find(req.param('userId'), req.param('communityId'))
    .then(membership => membership.save({
      active: false,
      deactivated_at: new Date(),
      deactivator_id: req.session.userId
    }, {patch: true}))
    .then(() => res.ok({}))
    .catch(res.serverError);
  },

  validate: function(req, res) {
    var allowedColumns = ['name', 'slug', 'beta_access_code'],
      allowedConstraints = ['exists', 'unique'],
      params = _.pick(req.allParams(), 'constraint', 'column', 'value');

    // prevent SQL injection
    if (!_.include(allowedColumns, params.column))
      return res.badRequest(format('invalid value "%s" for parameter "column"', params.column));

    if (!params.value)
      return res.badRequest('missing required parameter "value"');

    if (!_.include(allowedConstraints, params.constraint))
      return res.badRequest(format('invalid value "%s" for parameter "constraint"', params.constraint));

    var statement = format('lower(%s) = lower(?)', params.column);
    Community.query().whereRaw(statement, params.value).count()
    .then(function(rows) {
      var data;
      if (params.constraint === 'unique') {
        data = {unique: parseInt(rows[0].count) === 0};
      } else if (params.constraint === 'exists') {
        var exists = parseInt(rows[0].count) >= 1;
        data = {exists: exists};
      }
      res.ok(data);
    })
    .catch(res.serverError.bind(res));
  },

  create: function(req, res) {
    var attrs = _.pick(req.allParams(),
      'name', 'description', 'slug', 'category',
      'beta_access_code', 'banner_url', 'avatar_url');

    var community = new Community(_.merge(attrs, {
      created_at: new Date(),
      created_by_id: req.session.userId
    }));

    if (process.env.NODE_ENV) {
      community.set('leader_id', 21);
      community.set('welcome_message', "Thank you for joining us here at Hylo. " +
        "Through our communities, we can find everything we need. If we share " +
        "with each other the unique gifts and intentions we each have, we can " +
        "create extraordinary things. Let's get started!");
    }

    bookshelf.transaction(function(trx) {
      return community.save(null, {transacting: trx})
      .tap(() => Membership.create(req.session.userId, community.id, {
        role: Membership.MODERATOR_ROLE,
        transacting: trx
      }));
    })
    // The assets were uploaded to /community/new, since we didn't have an id;
    // copy them over to /community/:id now
    .tap(community => Queue.classMethod('Community', 'copyAssets', {communityId: community.id}))
    // FIXME this additional lookup wouldn't be necessary
    // if we had a Membership instance from the previous
    // step. But the absence of an id column on the table
    // doesn't play nice with Bookshelf.
    .then(() => Membership.find(req.session.userId, community.id, {withRelated: ['community']}))
    .then(res.ok)
    .catch(res.serverError);
  },

  findForNetwork: function(req, res) {
    Community.where('network_id', req.param('networkId'))
    .fetchAll({withRelated: ['memberships']})
    .then(communities => communities.map(c =>
      _.extend(c.pick('id', 'name', 'slug', 'avatar_url', 'banner_url'), {
        memberCount: c.relations.memberships.length
      })))
    .then(communities => _.sortBy(communities, c => -c.memberCount))
    .then(res.ok)
    .catch(res.serverError);
  }

};
<|endoftext|>


<commit_before>/**
 * Hooks into `require()` to watch for modifications of the required
 * file. If a modification is detected, the process exits with code
 * `101`.
 */

/**
 * Module dependencies.
 */
var fs = require('fs');
var Path = require('path');

/**
 * Watches the given module's filename.
 */
function watch(module) {
  if (!module.loaded) {
    fs.watchFile(module.filename, {interval : 500, persistent: false}, function(cur, prev) {
      if (cur && +cur.mtime !== +prev.mtime) {
        process.exit(101);
      }
    });
  }
}

/**
 * This is how the argv array looks like:
 * `['node', '/path/to/wrapper.js', '--option1', '--optionN', 'script', 'arg1', 'argN']`
 * ... so we remove ourself:
 */
process.argv.splice(1, 1);

/** Find the first arg that is not an option, starting at index 1 */
var arg;
for (var i=1; i < process.argv.length; i++) {
  arg = process.argv[i];
  if (!/^-/.test(arg)) {
    break;
  }
}

/** Resolve the location of the main script relative to cwd */
var main = Path.resolve(process.cwd(), arg);

/** Hook into `require()` */
function hookInto(ext) {
  var extensionHandler = require.extensions[ext];
  require.extensions[ext] = function(module, filename) {
    if (module.id == main) {
      module.id = '.';
      module.parent = null;
      process.mainModule = module;
    }
    watch(module);
    extensionHandler(module, filename);
    if (ext == '.js' && Path.basename(filename, ext) == 'coffee-script') {
      hookInto('.coffee');
    }
  };
}

hookInto('.js');

if (Path.extname(main) == '.coffee') {
  require('coffee-script');
}

/** Load the wrapped script */
require(main);<commit_msg>Added new line at eof<commit_after>/**
 * Hooks into `require()` to watch for modifications of the required
 * file. If a modification is detected, the process exits with code
 * `101`.
 */

/**
 * Module dependencies.
 */
var fs = require('fs');
var Path = require('path');

/**
 * Watches the given module's filename.
 */
function watch(module) {
  if (!module.loaded) {
    fs.watchFile(module.filename, {interval : 500, persistent: false}, function(cur, prev) {
      if (cur && +cur.mtime !== +prev.mtime) {
        process.exit(101);
      }
    });
  }
}

/**
 * This is how the argv array looks like:
 * `['node', '/path/to/wrapper.js', '--option1', '--optionN', 'script', 'arg1', 'argN']`
 * ... so we remove ourself:
 */
process.argv.splice(1, 1);

/** Find the first arg that is not an option, starting at index 1 */
var arg;
for (var i=1; i < process.argv.length; i++) {
  arg = process.argv[i];
  if (!/^-/.test(arg)) {
    break;
  }
}

/** Resolve the location of the main script relative to cwd */
var main = Path.resolve(process.cwd(), arg);

/** Hook into `require()` */
function hookInto(ext) {
  var extensionHandler = require.extensions[ext];
  require.extensions[ext] = function(module, filename) {
    if (module.id == main) {
      module.id = '.';
      module.parent = null;
      process.mainModule = module;
    }
    watch(module);
    extensionHandler(module, filename);
    if (ext == '.js' && Path.basename(filename, ext) == 'coffee-script') {
      hookInto('.coffee');
    }
  };
}

hookInto('.js');

if (Path.extname(main) == '.coffee') {
  require('coffee-script');
}

/** Load the wrapped script */
require(main);
<|endoftext|>


<commit_before>'use strict';

/**
 * Validate params fields
 * @param {apiService} service
 * @param {Object} params
 */
function validate(service, params) {

    if (service.needRequiredFields(params, ['name'])) {
        return;
    }

    saveDepartment(service, params);
}

/**
 * Update/create the department document
 *
 * @param {apiService} service
 * @param {Object} params
 */
function saveDepartment(service, params) {

    var Gettext = require('node-gettext');
    var gt = new Gettext();

    var DepartmentModel = service.app.db.models.Department;

    var fieldsToSet = {
        name: params.name,
        nonWorkingDays: params.nonWorkingDays,
        operator: params.operator
    };

    if (params.id)
    {
        DepartmentModel.findByIdAndUpdate(params.id, fieldsToSet, function(err, document) {
            if (service.handleMongoError(err))
            {
                service.resolveSuccess(
                    document,
                    gt.gettext('The department has been modified')
                );
            }
        });

    } else {

        DepartmentModel.create(fieldsToSet, function(err, document) {

            if (service.handleMongoError(err))
            {
                service.resolveSuccess(
                    document,
                    gt.gettext('The department has been created')
                );
            }
        });
    }
}

/**
 * Construct the department save service
 * @param   {object}          services list of base classes from apiService
 * @param   {express|object}  app      express or headless app
 * @returns {saveItemService}
 */
exports = module.exports = function(services, app) {

    var service = new services.save(app);

    /**
     * Call the department save service
     *
     * @param {Object} params
     *
     * @return {Promise}
     */
    service.getResultPromise = function(params) {
        validate(service, params);
        return service.deferred.promise;
    };

    return service;
};

<commit_msg>remove non workingdays from deparment<commit_after>'use strict';

/**
 * Validate params fields
 * @param {apiService} service
 * @param {Object} params
 */
function validate(service, params) {

    if (service.needRequiredFields(params, ['name'])) {
        return;
    }

    saveDepartment(service, params);
}

/**
 * Update/create the department document
 *
 * @param {apiService} service
 * @param {Object} params
 */
function saveDepartment(service, params) {

    var Gettext = require('node-gettext');
    var gt = new Gettext();

    var DepartmentModel = service.app.db.models.Department;

    var fieldsToSet = {
        name: params.name,
        operator: params.operator
    };

    if (params.id)
    {
        DepartmentModel.findByIdAndUpdate(params.id, fieldsToSet, function(err, document) {
            if (service.handleMongoError(err))
            {
                service.resolveSuccess(
                    document,
                    gt.gettext('The department has been modified')
                );
            }
        });

    } else {

        DepartmentModel.create(fieldsToSet, function(err, document) {

            if (service.handleMongoError(err))
            {
                service.resolveSuccess(
                    document,
                    gt.gettext('The department has been created')
                );
            }
        });
    }
}

/**
 * Construct the department save service
 * @param   {object}          services list of base classes from apiService
 * @param   {express|object}  app      express or headless app
 * @returns {saveItemService}
 */
exports = module.exports = function(services, app) {

    var service = new services.save(app);

    /**
     * Call the department save service
     *
     * @param {Object} params
     *
     * @return {Promise}
     */
    service.getResultPromise = function(params) {
        validate(service, params);
        return service.deferred.promise;
    };

    return service;
};

<|endoftext|>


<commit_before>import axios from 'axios';
import jwt from 'jsonwebtoken';
import Article from '../../models/article';
import Podcast from '../../models/podcast';
import RSS from '../../models/rss';
import Episode from '../../models/episode';
import logger from '../../utils/logger';
import { getStreamClient } from '../../utils/stream';

import config from '../../config';

function createGlobalToken() {
	const token = jwt.sign(
		{
			action: '*',
			feed_id: '*',
			resource: '*',
			user_id: '*',
		},
		config.stream.apiSecret,
		{ algorithm: 'HS256', noTimestamp: true },
	);
	return token;
}

export async function getRecommendations(userID, type, limit) {
	if (!userID) {
		throw Error('missing user id');
	}
	const streamClient = getStreamClient();
	streamClient.personalizationToken = createGlobalToken();

	const path = `winds_${type}_recommendations`;
	const queryParams = { user_id: userID, limit: limit };
	const response = await streamClient.personalization.get(path, queryParams);

	return response.data.results.map(result => {
		return result.foreign_id.split(':')[1];
	});
}

export async function getRSSRecommendations(userID, limit = 20) {
	try {
		let ids = await getRecommendations(userID, 'rss', limit);
		return RSS.find({ _id: { $in: ids } });
	} catch (err) {
		logger.warn(`Failed to get RSS recomentations for user ${userID}`, { err });
		return [];
	}
}

export async function getPodcastRecommendations(userID, limit = 20) {
	try {
		let ids = await getRecommendations(userID, 'podcast', limit);
		return Podcast.find({ _id: { $in: ids } });
	} catch (err) {
		logger.warn(`Failed to get Podcast recomentations for user ${userID}`, { err });
		return [];
	}
}

export async function getEpisodeRecommendations(userID, limit = 20) {
	try {
		let ids = await getRecommendations(userID, 'episode', limit);
		let episodes = await Episode.find({ _id: { $in: ids } });
		if (ids.length != episodes.length) {
			logger.warn(`failed to find some episodes from list ${ids.join(',')}`);
		}
		return episodes;
	} catch (err) {
		logger.warn(`Failed to get Episode recomentations for user ${userID}`, { err });
		return [];
	}
}

export async function getArticleRecommendations(userID, limit = 20) {
	try {
		let ids = await getRecommendations(userID, 'article', limit);
		let articles = await Article.find({ _id: { $in: ids } });
		if (ids.length != articles.length) {
			logger.warn(`failed to find some articles from list ${ids.join(',')}`);
		}
		return articles;
	} catch (err) {
		logger.warn(`Failed to get Article recomentations for user ${userID}`, { err });
		return [];
	}
}
<commit_msg>Support multiple response styles in personalisation utilities<commit_after>import axios from 'axios';
import jwt from 'jsonwebtoken';
import Article from '../../models/article';
import Podcast from '../../models/podcast';
import RSS from '../../models/rss';
import Episode from '../../models/episode';
import logger from '../../utils/logger';
import { getStreamClient } from '../../utils/stream';

import config from '../../config';

function createGlobalToken() {
	const token = jwt.sign(
		{
			action: '*',
			feed_id: '*',
			resource: '*',
			user_id: '*',
		},
		config.stream.apiSecret,
		{ algorithm: 'HS256', noTimestamp: true },
	);
	return token;
}

export async function getRecommendations(userID, type, limit) {
	if (!userID) {
		throw Error('missing user id');
	}
	const streamClient = getStreamClient();
	streamClient.personalizationToken = createGlobalToken();

	const path = `winds_${type}_recommendations`;
	const queryParams = { user_id: userID, limit: limit };
	const response = await streamClient.personalization.get(path, queryParams);

	const data = response.data ? response.data.results : response.results;
	return data.map(result => {
		return result.foreign_id.split(':')[1];
	});
}

export async function getRSSRecommendations(userID, limit = 20) {
	try {
		let ids = await getRecommendations(userID, 'rss', limit);
		return RSS.find({ _id: { $in: ids } });
	} catch (err) {
		logger.warn(`Failed to get RSS recomentations for user ${userID}`, { err });
		return [];
	}
}

export async function getPodcastRecommendations(userID, limit = 20) {
	try {
		let ids = await getRecommendations(userID, 'podcast', limit);
		return Podcast.find({ _id: { $in: ids } });
	} catch (err) {
		logger.warn(`Failed to get Podcast recomentations for user ${userID}`, { err });
		return [];
	}
}

export async function getEpisodeRecommendations(userID, limit = 20) {
	try {
		let ids = await getRecommendations(userID, 'episode', limit);
		let episodes = await Episode.find({ _id: { $in: ids } });
		if (ids.length != episodes.length) {
			logger.warn(`failed to find some episodes from list ${ids.join(',')}`);
		}
		return episodes;
	} catch (err) {
		logger.warn(`Failed to get Episode recomentations for user ${userID}`, { err });
		return [];
	}
}

export async function getArticleRecommendations(userID, limit = 20) {
	try {
		let ids = await getRecommendations(userID, 'article', limit);
		let articles = await Article.find({ _id: { $in: ids } });
		if (ids.length != articles.length) {
			logger.warn(`failed to find some articles from list ${ids.join(',')}`);
		}
		return articles;
	} catch (err) {
		logger.warn(`Failed to get Article recomentations for user ${userID}`, { err });
		return [];
	}
}
<|endoftext|>


<commit_before>var cheerio = require("cheerio"),
    http = require("http"),
    qs = require("querystring"),
    url = require("url");

var XVideos = module.exports;

XVideos.resolveId = function resolveId(id, cb) {
  if (typeof id !== "number") {
    return cb(Error("wrong type for id; expected number but got " + typeof id));
  }

  var req = http.get("http://www.xvideos.com/video" + id, function(res) {
    if (res.statusCode === 404) {
      return cb(Error("video not found"));
    }

    if (res.statusCode !== 301) {
      return cb(Error("incorrect status code; expected 301 but got " + res.statusCode));
    }

    return cb(null, res.headers.location);
  });

  req.once("error", cb);
};

XVideos.details = function details(url, cb) {
  var req = http.get(url, function(res) {
    var body = Buffer(0);

    res.on("readable", function() {
      var chunk;
      while (chunk = res.read()) {
        body = Buffer.concat([body, chunk]);
      }
    });

    if (res.statusCode === 404) {
      return cb(Error("video not found"));
    }

    if (res.statusCode !== 200) {
      return cb(Error("incorrect status code; expected 200 but got " + res.statusCode));
    }

    res.on("end", function() {
      body = body.toString("utf8");

      var $ = cheerio.load(body);

      var title = $("#main > h2").text().replace(/-[^-]+$/, "").trim();

      var tags = $("#video-tags > li > a").map(function(i, e) {
        return $(e).text().trim();
      }).filter(function(e) {
        return e !== "tags";
      });

      var duration = $(".duration").text().trim().replace(/^-/, "").trim();

      var flv;
      if (matches = body.match(/flv_url=(http%3A%2F%2F.+?)&/)) {
        flv = unescape(matches[1]);
      }
      if (!flv) {
        return cb(Error("couldn't find flv"));
      }

      return cb(null, {title: title, duration: duration, tags: tags, flv: flv});
    });
  });

  req.once("error", cb);
};

XVideos.search = function search(parameters, cb) {
  var req = http.get("http://www.xvideos.com/?" + qs.stringify(parameters), function(res) {
    var body = Buffer(0);

    res.on("readable", function() {
      var chunk;
      while (chunk = res.read()) {
        body = Buffer.concat([body, chunk]);
      }
    });

    if (res.statusCode !== 200) {
      return cb(Error("incorrect status code; expected 200 but got " + res.statusCode));
    }

    res.on("end", function() {
      body = body.toString("utf8");

      var $ = cheerio.load(body);

      var videos = $(".thumbBlock > .thumbInside").map(function(i, e) {
        var html = $(e).find("script").text().replace(/^thumbcastDisplayRandomThumb\('(.+?)'\);$/, "$1"),
            $$ = cheerio.load(html);

        return {
          url: url.resolve("http://www.xvideos.com/", $$("div.thumb > a").attr("href").replace("/THUMBNUM/", "/")),
          title: $$("p > a").text(),
          duration: $(e).find("span.duration").text().replace(/[\(\)]/g, "").trim(),
        };
      });

      var total = parseInt($("h3.blackTitle").text().replace(/[\r\n]/g, " ").replace(/^.*- (\d+) results.*$/, "$1"), 10);

      return cb(null, {total: total, videos: videos});
    });
  });

  req.once("error", cb);
};
<commit_msg>handle weird javascript and static html results<commit_after>var cheerio = require("cheerio"),
    http = require("http"),
    qs = require("querystring"),
    url = require("url");

var XVideos = module.exports;

XVideos.resolveId = function resolveId(id, cb) {
  if (typeof id !== "number") {
    return cb(Error("wrong type for id; expected number but got " + typeof id));
  }

  var req = http.get("http://www.xvideos.com/video" + id, function(res) {
    if (res.statusCode === 404) {
      return cb(Error("video not found"));
    }

    if (res.statusCode !== 301) {
      return cb(Error("incorrect status code; expected 301 but got " + res.statusCode));
    }

    return cb(null, res.headers.location);
  });

  req.once("error", cb);
};

XVideos.details = function details(url, cb) {
  var req = http.get(url, function(res) {
    var body = Buffer(0);

    res.on("readable", function() {
      var chunk;
      while (chunk = res.read()) {
        body = Buffer.concat([body, chunk]);
      }
    });

    if (res.statusCode === 404) {
      return cb(Error("video not found"));
    }

    if (res.statusCode !== 200) {
      return cb(Error("incorrect status code; expected 200 but got " + res.statusCode));
    }

    res.on("end", function() {
      body = body.toString("utf8");

      var $ = cheerio.load(body);

      var title = $("#main > h2").text().replace(/-[^-]+$/, "").trim();

      var tags = $("#video-tags > li > a").map(function(i, e) {
        return $(e).text().trim();
      }).filter(function(e) {
        return e !== "tags";
      });

      var duration = $(".duration").text().trim().replace(/^-/, "").trim();

      var flv;
      if (matches = body.match(/flv_url=(http%3A%2F%2F.+?)&/)) {
        flv = unescape(matches[1]);
      }
      if (!flv) {
        return cb(Error("couldn't find flv"));
      }

      return cb(null, {title: title, duration: duration, tags: tags, flv: flv});
    });
  });

  req.once("error", cb);
};

XVideos.search = function search(parameters, cb) {
  var req = http.get("http://www.xvideos.com/?" + qs.stringify(parameters), function(res) {
    var body = Buffer(0);

    res.on("readable", function() {
      var chunk;
      while (chunk = res.read()) {
        body = Buffer.concat([body, chunk]);
      }
    });

    if (res.statusCode !== 200) {
      return cb(Error("incorrect status code; expected 200 but got " + res.statusCode));
    }

    res.on("end", function() {
      body = body.toString("utf8");

      var $ = cheerio.load(body);

      var videos = $(".thumbBlock > .thumbInside").map(function(i, e) {
        var find;

        if ($(e).find("script").length) {
          find = cheerio.load($(e).find("script").text().replace(/^thumbcastDisplayRandomThumb\('(.+?)'\);$/, "$1"));
        } else {
          find = $(e).find.bind($(e));
        }

        return {
          url: url.resolve("http://www.xvideos.com/", find("div.thumb > a").attr("href").replace("/THUMBNUM/", "/")),
          title: find("p > a").text(),
          duration: $(e).find("span.duration").text().replace(/[\(\)]/g, "").trim(),
        };
      });

      var total = parseInt($("h3.blackTitle").text().replace(/[\r\n]/g, " ").replace(/^.*- (\d+) results.*$/, "$1"), 10);

      return cb(null, {total: total, videos: videos});
    });
  });

  req.once("error", cb);
};
<|endoftext|>


<commit_before>//NEW CONTROLLER

var searchApp = angular.module('searchApp');

searchApp

	.factory('pagination', function( $sce ) {

		var currentPage = 0;
		var itemsPerPage = 21;
		var results = [];

		return {

			//
			setResults: function( newResults ) {
				results = newResults
			}, /* END of setProducts */

			//
			getPageProducts: function(num) {
				var num = angular.isUndefined(num) ? 0 : num;
				var first = itemsPerPage * num;
				var last = first + itemsPerPage;
				currentPage = num;
				last = last > results.length ? (results.length - 1) : last;
				return results.slice(first, last);
			}, /* END of getPageProducts */

			//
			getTotalPagesNum: function() {
				return Math.ceil( results.length / itemsPerPage );
			}, /* END of getTotalPagesNum */

			//
			getPaginationList: function() {
				var pagesNum = this.getTotalPagesNum();
				var paginationList = [];
				paginationList.push({
					name: $sce.trustAsHtml('«'),
					link: 'prev'
				});
				for (var i = 0; i < pagesNum; i++) {
					var name = i + 1;
					paginationList.push({
						name: $sce.trustAsHtml( String(name) ),
						link: i
					});
				};
				paginationList.push({
					name: $sce.trustAsHtml('»'),
					link: 'next'
				});
				if (pagesNum > 1) {
					return paginationList;
				} else {
					return null;
				}
			}, /* END of getPaginationList */

			//
			getPrevPageProducts: function() {
				var prevPageNum = currentPage - 1;
				if ( prevPageNum < 0 ) prevPageNum = 0;
				return this.getPageProducts( prevPageNum );
			}, /* END of getPrevPageProducts */

			//
			getNextPageProducts: function() {
				var nextPageNum = currentPage + 1;
				var pagesNum = this.getTotalPagesNum();
				if ( nextPageNum >= pagesNum ) nextPageNum = pagesNum - 1;
				return this.getPageProducts( nextPageNum );
			}, /* END of getNextPageProducts */

			//
			getCurrentPageNum: function() {
				return currentPage;
			}, /* END of getCurrentPageNum */

		}
	}) /* END of factory-pagination */

	.controller('searchController', function ($scope, $http, pagination) {

		$scope.search = {
			text: ''
		};

		var index = 0;

		$scope.toggle = true;
		$scope.imputToggle = false;

		$scope.change = function (){

				$http.get('http://' + location.host + '/api/iknow/v1/docbook/domain/1/entities/' + $scope.search.text + '/similar')
					.then(function(response) {
							tempArray = response.data.entities;
							$scope.searchItems = tempArray.slice(0, 10);
						});
				if ($scope.search.text == '')
					$scope.imputToggle = false;
				else $scope.imputToggle = true;
		}

		$scope.handleClick = function (item){
			$scope.currrentSearchItem = item;
			$scope.search.text = $scope.currrentSearchItem.value;
			$scope.toggle = false;
			$scope.imputToggle = true;
		}

		$scope.handleArrows = function (event) {

			if(event.keyCode  === 40) // up
				index += 1;
			if(event.keyCode  === 38) // down
				index -= 1;

			if (index < 0)
				index = 9;
			if (index > 9)
				index = 0;
			if 	((event.keyCode  === 40) || (event.keyCode  === 38))
			{
				$scope.search.text = $scope.searchItems[index].value;
				$scope.currrentSearchItem = $scope.searchItems[index];
				//$scope.toggle = false;
			}

		}

		$scope.makeSearch = function (){

			if ($scope.search.text != '')
			{
				$http.get('http://' + location.host + '/csp/docsearch/rest/SearchByText/' + $scope.search.text)
					.then(function(response) {
							$scope.resObj = response.data.sources;
							pagination.setResults(response.data.sources);
							$scope.results = pagination.getPageProducts($scope.currentPage);
							$scope.paginationList = pagination.getPaginationList();
						});

				$scope.toggle = false;

			} else
				$scope.toggle = true;
		}

		$scope.showPage = function(page) {
					if ( page == 'prev' ) {
						$scope.results = pagination.getPrevPageProducts();
					} else if ( page == 'next' ) {
						$scope.results = pagination.getNextPageProducts();
					} else {
						$scope.results = pagination.getPageProducts( page );
					}
				}

		$scope.currentPageNum = function() {
			return pagination.getCurrentPageNum();
		}

	})/* END of controller - searchController */<commit_msg>контроллер<commit_after>var searchApp = angular.module('searchApp');

searchApp

	.factory('pagination', function( $sce ) {

		var currentPage = 0;
		var itemsPerPage = 21;
		var results = [];

		return {

			//
			setResults: function( newResults ) {
				results = newResults
			}, /* END of setProducts */

			//
			getPageProducts: function(num) {
				var num = angular.isUndefined(num) ? 0 : num;
				var first = itemsPerPage * num;
				var last = first + itemsPerPage;
				currentPage = num;
				last = last > results.length ? (results.length - 1) : last;
				return results.slice(first, last);
			}, /* END of getPageProducts */

			//
			getTotalPagesNum: function() {
				return Math.ceil( results.length / itemsPerPage );
			}, /* END of getTotalPagesNum */

			//
			getPaginationList: function() {
				var pagesNum = this.getTotalPagesNum();
				var paginationList = [];
				paginationList.push({
					name: $sce.trustAsHtml('«'),
					link: 'prev'
				});
				for (var i = 0; i < pagesNum; i++) {
					var name = i + 1;
					paginationList.push({
						name: $sce.trustAsHtml( String(name) ),
						link: i
					});
				};
				paginationList.push({
					name: $sce.trustAsHtml('»'),
					link: 'next'
				});
				if (pagesNum > 1) {
					return paginationList;
				} else {
					return null;
				}
			}, /* END of getPaginationList */

			//
			getPrevPageProducts: function() {
				var prevPageNum = currentPage - 1;
				if ( prevPageNum < 0 ) prevPageNum = 0;
				return this.getPageProducts( prevPageNum );
			}, /* END of getPrevPageProducts */

			//
			getNextPageProducts: function() {
				var nextPageNum = currentPage + 1;
				var pagesNum = this.getTotalPagesNum();
				if ( nextPageNum >= pagesNum ) nextPageNum = pagesNum - 1;
				return this.getPageProducts( nextPageNum );
			}, /* END of getNextPageProducts */

			//
			getCurrentPageNum: function() {
				return currentPage;
			}, /* END of getCurrentPageNum */

		}
	}) /* END of factory-pagination */

	.controller('searchController', function ($scope, $http, pagination) {

		$scope.search = {
			text: ''
		};

		var index = 0;

		$scope.toggle = true;
		$scope.imputToggle = false;

		$scope.change = function (){

				$http.get('http://' + location.host + '/api/iknow/v1/docbook/domain/1/entities/' + $scope.search.text + '/similar')
					.then(function(response) {
							tempArray = response.data.entities;
							$scope.searchItems = tempArray.slice(0, 10);
						});
				if ($scope.search.text == '')
					$scope.imputToggle = false;
				else $scope.imputToggle = true;
		}

		$scope.handleClick = function (item){
			$scope.currrentSearchItem = item;
			$scope.search.text = $scope.currrentSearchItem.value;
			$scope.toggle = false;
			$scope.imputToggle = true;
		}

		$scope.handleArrows = function (event) {

			if(event.keyCode  === 40) // up
				index += 1;
			if(event.keyCode  === 38) // down
				index -= 1;

			if (index < 0)
				index = 9;
			if (index > 9)
				index = 0;
			if 	((event.keyCode  === 40) || (event.keyCode  === 38))
			{
				$scope.search.text = $scope.searchItems[index].value;
				$scope.currrentSearchItem = $scope.searchItems[index];
				//$scope.toggle = false;
			}

		}

		$scope.makeSearch = function (){

			if ($scope.search.text != '')
			{
				$http.get('http://' + location.host + '/csp/docsearch/rest/SearchByText/' + $scope.search.text)
					.then(function(response) {
							$scope.resObj = response.data.sources;
							pagination.setResults(response.data.sources);
							$scope.results = pagination.getPageProducts($scope.currentPage);
							$scope.paginationList = pagination.getPaginationList();
						});

				$scope.toggle = false;

			} else
				$scope.toggle = true;
		}

		$scope.showPage = function(page) {
					if ( page == 'prev' ) {
						$scope.results = pagination.getPrevPageProducts();
					} else if ( page == 'next' ) {
						$scope.results = pagination.getNextPageProducts();
					} else {
						$scope.results = pagination.getPageProducts( page );
					}
				}

		$scope.currentPageNum = function() {
			return pagination.getCurrentPageNum();
		}

	})/* END of controller - searchController */<|endoftext|>


<commit_before>'use strict';

/*
** Import Packages
*/
let Promise = require("bluebird");
let debug = require("debug")("bot-express:flow");
let ParseError = require("../error/parse");
let Flow = require("./flow");

module.exports = class RestartConversationFlow extends Flow {
    /*
    ** ### Retart Conversation Flow ###
    ** -> Process parameters.
    ** -> Run final action.
    */

    constructor(vp, bot_event, intent, options) {
        context = {
            _flow: "restart_conversation",
            intent: intent,
            confirmed: {},
            to_confirm: [],
            confirming: null,
            previous: {
                confirmed: [],
                message: []
            },
            _message_queue: [],
            sender_language: null
        };
        vp.context = context;
        super(vp, bot_event, context, options);
    }

    run(){
        debug("### This is Retart Conversation Flow. ###");

        // ### Process Parameters ###
        // If we find some parameters from initial message, add them to the conversation.
        let parameters_processed = [];
        if (this.context.intent.parameters && Object.keys(this.context.intent.parameters).length > 0){
            for (let param_key of Object.keys(this.context.intent.parameters)){
                // Parse and Add parameters using skill specific logic.
                parameters_processed.push(
                    super.apply_parameter(param_key, this.context.intent.parameters[param_key]).then(
                        (applied_parameter) => {
                            if (applied_parameter == null){
                                debug("Parameter was not applicable. We skip reaction and go to finish.");
                                return;
                            }
                            return super.react(null, applied_parameter.key, applied_parameter.value);
                        }
                    ).catch(
                        ParseError, (error) => {
                            debug("Parser rejected the value.");
                            return super.react(error, param_key, this.context.intent.parameters[param_key]);
                        }
                    )
                );
            }
        }
        return Promise.all(parameters_processed).then(
            (response) => {
                // ### Run Final Action ###
                return super.finish();
            }
        );
    } // End of run()
};
<commit_msg>adding translation<commit_after>'use strict';

/*
** Import Packages
*/
let Promise = require("bluebird");
let debug = require("debug")("bot-express:flow");
let ParseError = require("../error/parse");
let Flow = require("./flow");

module.exports = class RestartConversationFlow extends Flow {
    /*
    ** ### Retart Conversation Flow ###
    ** -> Process parameters.
    ** -> Run final action.
    */

    constructor(vp, bot_event, intent, options) {
        let context = {
            _flow: "restart_conversation",
            intent: intent,
            confirmed: {},
            to_confirm: [],
            confirming: null,
            previous: {
                confirmed: [],
                message: []
            },
            _message_queue: [],
            sender_language: null
        };
        vp.context = context;
        super(vp, bot_event, context, options);
    }

    run(){
        debug("### This is Retart Conversation Flow. ###");

        // ### Process Parameters ###
        // If we find some parameters from initial message, add them to the conversation.
        let parameters_processed = [];
        if (this.context.intent.parameters && Object.keys(this.context.intent.parameters).length > 0){
            for (let param_key of Object.keys(this.context.intent.parameters)){
                // Parse and Add parameters using skill specific logic.
                parameters_processed.push(
                    super.apply_parameter(param_key, this.context.intent.parameters[param_key]).then(
                        (applied_parameter) => {
                            if (applied_parameter == null){
                                debug("Parameter was not applicable. We skip reaction and go to finish.");
                                return;
                            }
                            return super.react(null, applied_parameter.key, applied_parameter.value);
                        }
                    ).catch(
                        ParseError, (error) => {
                            debug("Parser rejected the value.");
                            return super.react(error, param_key, this.context.intent.parameters[param_key]);
                        }
                    )
                );
            }
        }
        return Promise.all(parameters_processed).then(
            (response) => {
                // ### Run Final Action ###
                return super.finish();
            }
        );
    } // End of run()
};
<|endoftext|>


<commit_before>var sourceMapToComment = require("source-map-to-comment");
var sourceMap          = require("source-map");
var chokidar           = require("chokidar");
var path               = require("path");
var util               = require("./util");
var fs                 = require("fs");
var _                  = require("lodash");

module.exports = function (commander, filenames) {
  var results = [];

  var buildResult = function () {
    var map = new sourceMap.SourceMapGenerator({
      file: commander.outFile || "stdout"
    });

    var code = "";
    var offset = 0;

    _.each(results, function (result) {
      var filename = result.filename;
      code += result.code + "\n";

      if (result.map) {
        var consumer = new sourceMap.SourceMapConsumer(result.map);

        map._sources.add(filename);
        map.setSourceContent(filename, result.actual);

        consumer.eachMapping(function (mapping) {
          map._mappings.add({
            generatedLine: mapping.generatedLine + offset,
            generatedColumn: mapping.generatedColumn,
            originalLine: mapping.originalLine,
            originalColumn: mapping.originalColumn,
            source: filename
          });
        });

        offset = code.split("\n").length;
      }
    });

    if (commander.sourceMapsInline || (!commander.outFile && commander.sourceMaps)) {
      code += "\n" + sourceMapToComment(map);
    }

    return {
      map: map,
      code: code
    };
  };

  var output = function () {
    var result = buildResult();

    if (commander.outFile) {
      if (commander.sourceMaps) {
        var mapLoc = commander.outFile + ".map";
        result.code = util.addSourceMappingUrl(result.code, mapLoc);
        fs.writeFileSync(mapLoc, JSON.stringify(result.map));
      }

      fs.writeFileSync(commander.outFile, result.code);
    } else {
      process.stdout.write(result.code + "\n");
    }
  };

  var stdin = function () {
    var code = "";

    process.stdin.setEncoding("utf8");

    process.stdin.on("readable", function () {
      var chunk = process.stdin.read();
      if (chunk !== null) code += chunk;
    });

    process.stdin.on("end", function () {
      results.push(util.transform(commander.filename, code));
      output();
    });
  };

  var walk = function () {
    var _filenames = [];
    results = [];

    _.each(filenames, function (filename) {
      if (!fs.existsSync(filename)) return;

      var stat = fs.statSync(filename);
      if (stat.isDirectory()) {
        var dirname = filename;

        _.each(util.readdirFilter(filename), function (filename) {
          _filenames.push(path.join(dirname, filename));
        });
      } else {
        _filenames.push(filename);
      }
    });

    _.each(_filenames, function (filename) {
      results.push(util.compile(filename));
    });

    output();
  };

  var files = function () {
    walk();

    if (commander.watch) {
      chokidar.watch(filenames, {
        persistent: true,
        ignoreInitial: true
      }).on("all", function (type, filename) {
        if (type === "add" || type === "change") {
          console.log(type, filename);
          try {
            walk();
          } catch (err) {
            console.error(err.stack);
          }
        }
      });
    }
  };

  if (filenames.length) {
    files();
  } else {
    stdin();
  }
};
<commit_msg>use convert-source-map package - closes #960<commit_after>var convertSourceMap = require("convert-source-map");
var sourceMap        = require("source-map");
var chokidar         = require("chokidar");
var path             = require("path");
var util             = require("./util");
var fs               = require("fs");
var _                = require("lodash");

module.exports = function (commander, filenames) {
  var results = [];

  var buildResult = function () {
    var map = new sourceMap.SourceMapGenerator({
      file: commander.outFile || "stdout"
    });

    var code = "";
    var offset = 0;

    _.each(results, function (result) {
      var filename = result.filename;
      code += result.code + "\n";

      if (result.map) {
        var consumer = new sourceMap.SourceMapConsumer(result.map);

        map._sources.add(filename);
        map.setSourceContent(filename, result.actual);

        consumer.eachMapping(function (mapping) {
          map._mappings.add({
            generatedLine: mapping.generatedLine + offset,
            generatedColumn: mapping.generatedColumn,
            originalLine: mapping.originalLine,
            originalColumn: mapping.originalColumn,
            source: filename
          });
        });

        offset = code.split("\n").length;
      }
    });

    if (commander.sourceMapsInline || (!commander.outFile && commander.sourceMaps)) {
      code += "\n" + convertSourceMap.fromObject(map).toComment();
    }

    return {
      map: map,
      code: code
    };
  };

  var output = function () {
    var result = buildResult();

    if (commander.outFile) {
      if (commander.sourceMaps) {
        var mapLoc = commander.outFile + ".map";
        result.code = util.addSourceMappingUrl(result.code, mapLoc);
        fs.writeFileSync(mapLoc, JSON.stringify(result.map));
      }

      fs.writeFileSync(commander.outFile, result.code);
    } else {
      process.stdout.write(result.code + "\n");
    }
  };

  var stdin = function () {
    var code = "";

    process.stdin.setEncoding("utf8");

    process.stdin.on("readable", function () {
      var chunk = process.stdin.read();
      if (chunk !== null) code += chunk;
    });

    process.stdin.on("end", function () {
      results.push(util.transform(commander.filename, code));
      output();
    });
  };

  var walk = function () {
    var _filenames = [];
    results = [];

    _.each(filenames, function (filename) {
      if (!fs.existsSync(filename)) return;

      var stat = fs.statSync(filename);
      if (stat.isDirectory()) {
        var dirname = filename;

        _.each(util.readdirFilter(filename), function (filename) {
          _filenames.push(path.join(dirname, filename));
        });
      } else {
        _filenames.push(filename);
      }
    });

    _.each(_filenames, function (filename) {
      results.push(util.compile(filename));
    });

    output();
  };

  var files = function () {
    walk();

    if (commander.watch) {
      chokidar.watch(filenames, {
        persistent: true,
        ignoreInitial: true
      }).on("all", function (type, filename) {
        if (type === "add" || type === "change") {
          console.log(type, filename);
          try {
            walk();
          } catch (err) {
            console.error(err.stack);
          }
        }
      });
    }
  };

  if (filenames.length) {
    files();
  } else {
    stdin();
  }
};
<|endoftext|>


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

"use strict"

let node
let dwait = require("./lib/hacky-logs.js")

const fs = require("fs")
const path = require("path")
const mkdirp = require("mkdirp")

const MergeRecursive = require("merge-recursive")
const ZeroNet = require("zeronet-node")

const FS = require("zeronet-storage-fs")

const Common = require("zeronet-common")

let dir = require("./lib/storage-dir")()

mkdirp.sync(dir)
mkdirp.sync(path.join(dir, "logs"))

const defaults = {
  swarm: {
    server: {
      host: "0.0.0.0",
      port: 15543
    },
    server6: {
      host: "::",
      port: 15543
    },
    protocol: {
      crypto: []
    }
  },
  uiserver: {
    listen: {
      host: "127.0.0.1",
      port: 15544
    }
  },
  node: {
    trackers: [
      //"zero://boot3rdez4rzn36x.onion:15441",
      //"zero://boot.zeronet.io#f36ca555bee6ba216b14d10f38c16f7769ff064e0e37d887603548cc2e64191d:15441",
      "udp://tracker.coppersurfer.tk:6969",
      "udp://tracker.leechers-paradise.org:6969",
      "udp://9.rarbg.com:2710",
      "http://tracker.opentrackr.org:1337/announce",
      "http://explodie.org:6969/announce",
      "http://tracker1.wasabii.com.tw:6969/announce"
      //"http://localhost:25534/announce"
    ],
  },
  common: new Common({
    debug_file: path.resolve(dir, path.join("logs", "debug.log")),
    debug_shift_file: path.resolve(dir, path.join("logs", "debug-last.log")),
    debug: !!process.env.DEBUG
  }),
  storage: new FS(path.join(dir, "data"))
}

const errCB = err => {
  if (!err && process.env.TESTOK) process.emit("SIGINT")
  if (!err) return node.logger("node")("Started successfully")
  console.error("The node failed to start")
  console.error(err)
  process.exit(2)
}

const confpath = path.resolve(dir, process.env.CONFIG_FILE || "config.json")

let config

if (fs.existsSync(confpath)) {
  const config_data = JSON.parse(fs.readFileSync(confpath).toString())
  config = MergeRecursive(config_data, defaults)
} else config = defaults

let exiting

function exit(code) {
  if (!node) {
    console.error("Stopping before started!")
    exiting = true
    exit(2)
  }
  if (exiting) {
    node.logger("node").warn("Force stop!")
    return process.nextTick(() => process.exit(2))
  }
  exiting = true
  node.logger("node")("Stopping...")
  node.logger("node")("Press ^C to force stop")
  node.stop(err => {
    if (err) {
      node.logger("node").error(err)
      console.error("FAILED TO QUIT GRACEFULLY")
      throw err
    }
    node.logger("node")("Stopped")
    process.exit(code || 0)
  })
}

["SIGTERM", "SIGINT", "SIGUSR2"].forEach(sig => process.on(sig, exit))

require("peer-id").create((err, id) => {
  config.id = id
  node = new ZeroNet(config)
  dwait.map(d => d())
  dwait = null
  node.start(errCB)
})
<commit_msg>Fixes<commit_after>#!/usr/bin/env node

"use strict"

let node
let dwait = require("./lib/hacky-logs.js")

const fs = require("fs")
const path = require("path")
const mkdirp = require("mkdirp")

const MergeRecursive = require("merge-recursive")
const ZeroNet = require("zeronet-node")

const FS = require("zeronet-storage-fs")

const Common = require("zeronet-common")

let dir = require("./lib/storage-dir")()

mkdirp.sync(dir)
mkdirp.sync(path.join(dir, "logs"))

const defaults = {
  swarm: {
    server: {
      host: "0.0.0.0",
      port: 15543
    },
    server6: {
      host: "::",
      port: 15543
    },
    protocol: {
      crypto: []
    }
  },
  uiserver: {
    listen: {
      host: "127.0.0.1",
      port: 15544
    }
  },
  node: {
    trackers: [
      //"zero://boot3rdez4rzn36x.onion:15441",
      //"zero://boot.zeronet.io#f36ca555bee6ba216b14d10f38c16f7769ff064e0e37d887603548cc2e64191d:15441",
      "udp://tracker.coppersurfer.tk:6969",
      "udp://tracker.leechers-paradise.org:6969",
      "udp://9.rarbg.com:2710",
      "http://tracker.opentrackr.org:1337/announce",
      "http://explodie.org:6969/announce",
      "http://tracker1.wasabii.com.tw:6969/announce"
      //"http://localhost:25534/announce"
    ],
  },
  common: new Common({
    debug_file: path.resolve(dir, path.join("logs", "debug.log")),
    debug_shift_file: path.resolve(dir, path.join("logs", "debug-last.log")),
    debug: !!process.env.DEBUG
  }),
  storage: new FS(path.join(dir, "data"))
}

const errCB = err => {
  if (!err && process.env.TESTOK) process.emit("SIGINT")
  if (!err) return node.logger("node")("Started successfully")
  console.error("The node failed to start")
  console.error(err)
  process.exit(2)
}

const confpath = path.resolve(dir, process.env.CONFIG_FILE || "config.json")

let config

if (fs.existsSync(confpath)) {
  const config_data = JSON.parse(fs.readFileSync(confpath).toString())
  config = MergeRecursive(defaults, config_data)
} else config = defaults

let exiting

function exit(code) {
  if (!node) {
    console.error("Stopping before started!")
    exiting = true
    exit(2)
  }
  if (exiting) {
    node.logger("node").warn("Force stop!")
    return process.nextTick(() => process.exit(2))
  }
  exiting = true
  node.logger("node")("Stopping...")
  node.logger("node")("Press ^C to force stop")
  node.stop(err => {
    if (err) {
      node.logger("node").error(err)
      console.error("FAILED TO QUIT GRACEFULLY")
      throw err
    }
    node.logger("node")("Stopped")
    process.exit(code || 0)
  })
}

["SIGTERM", "SIGINT", "SIGUSR2"].forEach(sig => process.on(sig, exit))

require("peer-id").create((err, id) => {
  config.id = id
  node = new ZeroNet(config)
  dwait.map(d => d())
  dwait = null
  node.start(errCB)
})
<|endoftext|>


<commit_before>"use strict";

var util = require('util');
var events = require('events');
var fs = require('fs');
var path = require('path');
var child_process = require('child_process');
var async = require('async');

var RootfsExecuter = require('./rootfs_executer');

var Rootfs = module.exports = function() {
	var self = this;

	self.arch = null;
	self.targetPath = null;
	self.initialDirPath = null;
	self.environmentReady = false;
};

util.inherits(Rootfs, events.EventEmitter);

Rootfs.prototype.clone = function(targetPath, callback) {
	var self = this;

	var rootfs = null;
	async.series([
		function(next) {

			fs.exists(self.targetPath, function(exists) {
				if (!exists) {
					next(new Error('No such rootfs.'));
					return;
				}

				next();
			});
		},
		function(next) {

			fs.exists(targetPath, function(exists) {
				if (!exists) {
					fs.mkdir(targetPath, function(err) {
						next(err);
					});
					return;
				}

				next();
			});
		},
		function(next) {

			fs.readdir(self.targetPath, function(err, files) {
				if (err) {
					next(err);
					return;
				}

				if (files.length == 0) {
					next(new Error('No such rootfs.'));
					return;
				}

				// Preparing entries
				var sources = [];
				for (var index in files) {
					sources.push(path.join(self.targetPath, files[index]));
				}

				// Arguments
				var args = [ '-a' ].concat(sources, [ targetPath ]);

				// Copying files
				var cmd = child_process.spawn('cp', args);
				cmd.on('close', function() {

					// Creatinga  new rootfs object
					rootfs = new Rootfs();
					rootfs.arch = self.arch;
					rootfs.targetPath = targetPath;

					next();
				});
			});
		}
	], function(err) {
		callback(err, rootfs);
	});
};

Rootfs.prototype.move = function(targetPath, callback) {
	var self = this;

	fs.exists(self.targetPath, function(exists) {
		if (!exists) {
			callback(new Error('No such rootfs.'));
			return;
		}

		fs.readdir(self.targetPath, function(err, files) {

			if (files.length == 0) {
				callback();
				return;
			}

			// Preparing entries
			var sources = [];
			for (var index in files) {
				sources.push(path.join(self.targetPath, files[index]));
			}

			// Arguments
			var args = [ '-f' ].concat(sources, [ targetPath ]);

			var cmd = child_process.spawn('mv', args);
			cmd.on('close', function() {
				self.targetPath = targetPath;
				callback();
			});
		});
	});
};

Rootfs.prototype.remove = function(callback) {
	var self = this;

	if (!self.targetPath) {
		process.nextTick(callback);
		return;
	}

	var cmd = child_process.spawn('rm', [
		'-fr',
		self.targetPath
	]);

	cmd.on('close', function() {
		callback();
	});
};

Rootfs.prototype.applyOverwrite = function(sourcePath, callback) {
	var self = this;

	fs.exists(sourcePath, function(exists) {

		if (!exists) {
			callback(new Error('Source for overwriting doesn\'t exist'));
			return;
		}

		// Overwriting files
		fs.readdir(sourcePath, function(err, files) {
			if (err) {
				callback(err);
				return;
			}

			if (files.length == 0) {
				callback(null);
				return;
			}

			var sources = [];
			for (var index in files) {
				sources.push(path.join(sourcePath, files[index]));
			}

			var args = [ '-a' ].concat(sources, [ self.targetPath ]);

			var cmd = child_process.spawn('cp', args);

//			cmd.stdout.pipe(process.stdout);
//			cmd.stderr.pipe(process.stderr);

			cmd.on('close', function() {
				callback(null);
			});
		});
	});
};

Rootfs.prototype.prepareEnvironment = function(callback) {
	var self = this;

	if (self.environmentReady) {
		process.nextTick(callback);
		return;
	}

	if (self.arch != 'armhf') {
		process.nextTick(callback);
		return;
	}

	async.series([

		function(next) {

			// Initializing domain name server settings
			var cmd = child_process.spawn('cp', [
				'-a',
				path.join('/', 'etc', 'resolv.conf'),
				path.join(self.targetPath, 'etc')
			]);

			cmd.on('close', function() {
				next();
			});
		},
		function(next) {

			// Preparing emulator
			var cmd = child_process.spawn('cp', [
				'-a',
				path.join('/', 'usr', 'bin', 'qemu-arm-static'),
				path.join(self.targetPath, 'usr', 'bin')
			]);

			cmd.on('close', function() {
				next();
			});
		},
		function(next) {

			// Setting proxy to speed up apt-get
			var proxyConfig = 'Acquire::http::Proxy "http://127.0.0.1:3142/apt-cacher/";';

			fs.writeFile(path.join(self.targetPath, 'etc', 'apt', 'apt.conf.d', '01stemmer'), proxyConfig, function(err) {
				next(err);
			});

		},
		function(next) {

			// Setting local repository
			var repo = 'deb file:/.stemmer/packages ./';

			fs.writeFile(path.join(self.targetPath, 'etc', 'apt', 'sources.list.d', 'stemmer.list'), repo, function(err) {
				next(err);
			});

		},
		function(next) {

			var stemmerPath = path.join(self.targetPath, '.stemmer');
			async.series([
				function(_next) {
					fs.exists(stemmerPath, function(exists) {
						if (exists) {
							self.initialDirPath = stemmerPath;
							next();
							return;
						}

						fs.mkdir(stemmerPath, function(err) {
							if (err) {
								_next(err);
								return;
							}

							self.initialDirPath = stemmerPath;
							_next();

						});
					});
				},
				function(_next) {

					fs.mkdir(path.join(stemmerPath, 'packages'), function(err) {
						if (err) {
							_next(err);
							return;
						}

						_next();

					});
				},
				function(_next) {

					// Initializing a fake environment to avoid invoke-rc.d running
					var fakeLinks = [
						'initctl',
						'invoke-rc.d',
						'restart',
						'start',
						'stop',
						'start-stop-daemon',
						'service'
					];

					async.each(fakeLinks, function(linkname, cb) {
						fs.symlink('/bin/true', path.join(stemmerPath, linkname), function(err) {
							cb(err);
						});
					}, function(err) {

						_next(err);
					});
				}
			], function(err) {
				next(err);
			})

		}
	], function(err) {
		if (err) {
			self.clearEnvironment(function() {
				callback(err);
			});

			return;
		}

		self.environmentReady = true;
		callback(null);
	});
};

Rootfs.prototype.clearEnvironment = function(callback) {
	var self = this;

	if (!self.environmentReady) {
		process.nextTick(callback);
		return;
	}

	async.series([

		function(next) {

			self.emit('clear', 'packages');

			// Clear APT stuffs
			var rootfsExecuter = new RootfsExecuter(self);
			rootfsExecuter.addCommand('rm -fr /var/lib/apt/lists/*');
			rootfsExecuter.addCommand('apt-get clean');
			rootfsExecuter.addCommand('rm -fr /var/lib/dpkg/available-old');
			rootfsExecuter.addCommand('rm -fr /var/lib/dpkg/diversions-old');
			rootfsExecuter.addCommand('rm -fr /var/lib/dpkg/status-old');
			rootfsExecuter.run({}, function() {
				next();
			});
		},
		function(next) {

			self.emit('clear', 'apt_settings');

			fs.unlink(path.join(self.targetPath, 'etc', 'apt', 'apt.conf.d', '01stemmer'), next);
		},
		function(next) {

			fs.unlink(path.join(self.targetPath, 'etc', 'apt', 'sources.list.d', 'stemmer.list'), next);
		},
		function(next) {

			self.emit('clear', 'initial_directory');

			var cmd = child_process.spawn('rm', [
				'-fr',
				self.initialDirPath
			]);

			cmd.on('close', function() {
				self.initialDirPath = null;
				next();
			});
		},
		function(next) {

			self.emit('clear', 'emulator');

			fs.unlink(path.join(self.targetPath, 'usr', 'bin', 'qemu-arm-static'), next);
		},
		function(next) {

			self.emit('clear', 'dns_settings');

			fs.unlink(path.join(self.targetPath, 'etc', 'resolv.conf'), next);
		}
	], function() {
		self.environmentReady = false;
		callback();
	});
};

Rootfs.prototype.setPackageIndexes = function(indexPath, callback) {
	var self = this;

	var rootfsExecuter = new RootfsExecuter(self);

	var outputPath = path.join(self.targetPath, 'var', 'lib', 'apt', 'lists');

	fs.readdir(indexPath, function(err, files) {
		if (err) {
			callback(err);
			return;
		}

		if (files.length == 0) {
			callback();
			return;
		}

		var filelist = [];

		// Finding index files
		async.each(files, function(filename, next) {

			filelist.push(path.join(indexPath, filename));

			next();

		}, function() {

			// Copying index files
			var args = [ '-a' ].concat(filelist, [ outputPath ]);
			var cmd = child_process.spawn('cp', args);
			cmd.on('close', function() {

				callback(null);
			});
		})
	});

};

Rootfs.prototype.fetchPackageIndexes = function(outputPath, callback) {
	var self = this;

	var rootfsExecuter = new RootfsExecuter(self);

	var sourceDirPath = path.join(self.targetPath, 'var', 'lib', 'apt', 'lists');

	fs.readdir(sourceDirPath, function(err, files) {
		if (err) {
			callback(err);
			return;
		}

		if (files.length == 0) {
			callback();
			return;
		}

		var filelist = [];

		// Finding index files
		async.each(files, function(filename, next) {

			if (filename.lastIndexOf('_Packages') > 0 ||
				filename.lastIndexOf('_Translation-en') > 0 ||
				filename.lastIndexOf('_InRelease') > 0 ||
				filename.lastIndexOf('_Release') > 0) {

				filelist.push(path.join(sourceDirPath, filename));
			}

			next();

		}, function() {

			// Copying index files
			var args = [ '-a' ].concat(filelist, [ outputPath ]);
			var cmd = child_process.spawn('cp', args);
			cmd.on('close', function() {

				callback(null);
			});
		})
	});

};

Rootfs.prototype.registerServices = function(services, opts, callback) {
	var self = this;

	if (Object.keys(services).length == 0) {
		process.nextTick(function() {
			callback(null);
		});
		return;
	}

	var rootfsExecuter = new RootfsExecuter(self);

	for (var name in services) {
		rootfsExecuter.addCommand('insserv -v -d /etc/init.d/' + name);
	}

	rootfsExecuter.run({}, function() {
		callback(null);
	});
};

Rootfs.prototype.installPackages = function(packages, opts, callback) {
	var self = this;

	if (Object.keys(packages).length == 0) {
		process.nextTick(function() {
			callback(null);
		});
		return;
	}

	var pkgs = [];
	for (var name in packages) {
		var version = packages[name];
		if (version == '*' || version == '')
			pkgs.push(name);
		else
			pkgs.push(name + '=' + version);
	}

	var rootfsExecuter = new RootfsExecuter(self);

	rootfsExecuter.addCommand('apt-get update');
	rootfsExecuter.addCommand('apt-get install -f --no-install-recommends -q --force-yes -y ' + pkgs.join(' '))
	rootfsExecuter.run({}, function() {
		callback(null);
	});

};

Rootfs.prototype.applyPackages = function(opts, callback) {
	var self = this;

	// TODO: check Packages.gz and remove it if it doesn't exist
	var failed = false;
	var dpkg = child_process.spawn('dpkg-scanpackages', [
		'.',
		'/dev/null'
	], {
		cwd: path.join(self.targetPath, '.stemmer', 'packages')
	});

	var gzip = child_process.spawn('gzip', [
		'-9c'
	]);

	dpkg.stdout.on('data', function(data) {
		gzip.stdin.write(data);
	});

	dpkg.on('close', function() {
		gzip.stdin.end();
	});

	var packageListFile = path.join(self.targetPath, '.stemmer', 'packages', 'Packages.gz');
	gzip.stdout.on('data', function(data) {

		fs.appendFile(packageListFile, data, function(err) {
			if (err) {
				callback(err);
				failed = true;
			}
		});
	});

	gzip.on('close', function() {
		if (!failed)
			callback();
	});

};
<commit_msg>doesn't break if no overwriting directory<commit_after>"use strict";

var util = require('util');
var events = require('events');
var fs = require('fs');
var path = require('path');
var child_process = require('child_process');
var async = require('async');

var RootfsExecuter = require('./rootfs_executer');

var Rootfs = module.exports = function() {
	var self = this;

	self.arch = null;
	self.targetPath = null;
	self.initialDirPath = null;
	self.environmentReady = false;
};

util.inherits(Rootfs, events.EventEmitter);

Rootfs.prototype.clone = function(targetPath, callback) {
	var self = this;

	var rootfs = null;
	async.series([
		function(next) {

			fs.exists(self.targetPath, function(exists) {
				if (!exists) {
					next(new Error('No such rootfs.'));
					return;
				}

				next();
			});
		},
		function(next) {

			fs.exists(targetPath, function(exists) {
				if (!exists) {
					fs.mkdir(targetPath, function(err) {
						next(err);
					});
					return;
				}

				next();
			});
		},
		function(next) {

			fs.readdir(self.targetPath, function(err, files) {
				if (err) {
					next(err);
					return;
				}

				if (files.length == 0) {
					next(new Error('No such rootfs.'));
					return;
				}

				// Preparing entries
				var sources = [];
				for (var index in files) {
					sources.push(path.join(self.targetPath, files[index]));
				}

				// Arguments
				var args = [ '-a' ].concat(sources, [ targetPath ]);

				// Copying files
				var cmd = child_process.spawn('cp', args);
				cmd.on('close', function() {

					// Creatinga  new rootfs object
					rootfs = new Rootfs();
					rootfs.arch = self.arch;
					rootfs.targetPath = targetPath;

					next();
				});
			});
		}
	], function(err) {
		callback(err, rootfs);
	});
};

Rootfs.prototype.move = function(targetPath, callback) {
	var self = this;

	fs.exists(self.targetPath, function(exists) {
		if (!exists) {
			callback(new Error('No such rootfs.'));
			return;
		}

		fs.readdir(self.targetPath, function(err, files) {

			if (files.length == 0) {
				callback();
				return;
			}

			// Preparing entries
			var sources = [];
			for (var index in files) {
				sources.push(path.join(self.targetPath, files[index]));
			}

			// Arguments
			var args = [ '-f' ].concat(sources, [ targetPath ]);

			var cmd = child_process.spawn('mv', args);
			cmd.on('close', function() {
				self.targetPath = targetPath;
				callback();
			});
		});
	});
};

Rootfs.prototype.remove = function(callback) {
	var self = this;

	if (!self.targetPath) {
		process.nextTick(callback);
		return;
	}

	var cmd = child_process.spawn('rm', [
		'-fr',
		self.targetPath
	]);

	cmd.on('close', function() {
		callback();
	});
};

Rootfs.prototype.applyOverwrite = function(sourcePath, callback) {
	var self = this;

	fs.exists(sourcePath, function(exists) {

		if (!exists) {
			// Target director doesn't exist
			callback(null);
			return;
		}

		// Overwriting files
		fs.readdir(sourcePath, function(err, files) {
			if (err) {
				callback(err);
				return;
			}

			if (files.length == 0) {
				callback(null);
				return;
			}

			var sources = [];
			for (var index in files) {
				sources.push(path.join(sourcePath, files[index]));
			}

			var args = [ '-a' ].concat(sources, [ self.targetPath ]);

			var cmd = child_process.spawn('cp', args);

//			cmd.stdout.pipe(process.stdout);
//			cmd.stderr.pipe(process.stderr);

			cmd.on('close', function() {
				callback(null);
			});
		});
	});
};

Rootfs.prototype.prepareEnvironment = function(callback) {
	var self = this;

	if (self.environmentReady) {
		process.nextTick(callback);
		return;
	}

	if (self.arch != 'armhf') {
		process.nextTick(callback);
		return;
	}

	async.series([

		function(next) {

			// Initializing domain name server settings
			var cmd = child_process.spawn('cp', [
				'-a',
				path.join('/', 'etc', 'resolv.conf'),
				path.join(self.targetPath, 'etc')
			]);

			cmd.on('close', function() {
				next();
			});
		},
		function(next) {

			// Preparing emulator
			var cmd = child_process.spawn('cp', [
				'-a',
				path.join('/', 'usr', 'bin', 'qemu-arm-static'),
				path.join(self.targetPath, 'usr', 'bin')
			]);

			cmd.on('close', function() {
				next();
			});
		},
		function(next) {

			// Setting proxy to speed up apt-get
			var proxyConfig = 'Acquire::http::Proxy "http://127.0.0.1:3142/apt-cacher/";';

			fs.writeFile(path.join(self.targetPath, 'etc', 'apt', 'apt.conf.d', '01stemmer'), proxyConfig, function(err) {
				next(err);
			});

		},
		function(next) {

			// Setting local repository
			var repo = 'deb file:/.stemmer/packages ./';

			fs.writeFile(path.join(self.targetPath, 'etc', 'apt', 'sources.list.d', 'stemmer.list'), repo, function(err) {
				next(err);
			});

		},
		function(next) {

			var stemmerPath = path.join(self.targetPath, '.stemmer');
			async.series([
				function(_next) {
					fs.exists(stemmerPath, function(exists) {
						if (exists) {
							self.initialDirPath = stemmerPath;
							next();
							return;
						}

						fs.mkdir(stemmerPath, function(err) {
							if (err) {
								_next(err);
								return;
							}

							self.initialDirPath = stemmerPath;
							_next();

						});
					});
				},
				function(_next) {

					fs.mkdir(path.join(stemmerPath, 'packages'), function(err) {
						if (err) {
							_next(err);
							return;
						}

						_next();

					});
				},
				function(_next) {

					// Initializing a fake environment to avoid invoke-rc.d running
					var fakeLinks = [
						'initctl',
						'invoke-rc.d',
						'restart',
						'start',
						'stop',
						'start-stop-daemon',
						'service'
					];

					async.each(fakeLinks, function(linkname, cb) {
						fs.symlink('/bin/true', path.join(stemmerPath, linkname), function(err) {
							cb(err);
						});
					}, function(err) {

						_next(err);
					});
				}
			], function(err) {
				next(err);
			})

		}
	], function(err) {
		if (err) {
			self.clearEnvironment(function() {
				callback(err);
			});

			return;
		}

		self.environmentReady = true;
		callback(null);
	});
};

Rootfs.prototype.clearEnvironment = function(callback) {
	var self = this;

	if (!self.environmentReady) {
		process.nextTick(callback);
		return;
	}

	async.series([

		function(next) {

			self.emit('clear', 'packages');

			// Clear APT stuffs
			var rootfsExecuter = new RootfsExecuter(self);
			rootfsExecuter.addCommand('rm -fr /var/lib/apt/lists/*');
			rootfsExecuter.addCommand('apt-get clean');
			rootfsExecuter.addCommand('rm -fr /var/lib/dpkg/available-old');
			rootfsExecuter.addCommand('rm -fr /var/lib/dpkg/diversions-old');
			rootfsExecuter.addCommand('rm -fr /var/lib/dpkg/status-old');
			rootfsExecuter.run({}, function() {
				next();
			});
		},
		function(next) {

			self.emit('clear', 'apt_settings');

			fs.unlink(path.join(self.targetPath, 'etc', 'apt', 'apt.conf.d', '01stemmer'), next);
		},
		function(next) {

			fs.unlink(path.join(self.targetPath, 'etc', 'apt', 'sources.list.d', 'stemmer.list'), next);
		},
		function(next) {

			self.emit('clear', 'initial_directory');

			var cmd = child_process.spawn('rm', [
				'-fr',
				self.initialDirPath
			]);

			cmd.on('close', function() {
				self.initialDirPath = null;
				next();
			});
		},
		function(next) {

			self.emit('clear', 'emulator');

			fs.unlink(path.join(self.targetPath, 'usr', 'bin', 'qemu-arm-static'), next);
		},
		function(next) {

			self.emit('clear', 'dns_settings');

			fs.unlink(path.join(self.targetPath, 'etc', 'resolv.conf'), next);
		}
	], function() {
		self.environmentReady = false;
		callback();
	});
};

Rootfs.prototype.setPackageIndexes = function(indexPath, callback) {
	var self = this;

	var rootfsExecuter = new RootfsExecuter(self);

	var outputPath = path.join(self.targetPath, 'var', 'lib', 'apt', 'lists');

	fs.readdir(indexPath, function(err, files) {
		if (err) {
			callback(err);
			return;
		}

		if (files.length == 0) {
			callback();
			return;
		}

		var filelist = [];

		// Finding index files
		async.each(files, function(filename, next) {

			filelist.push(path.join(indexPath, filename));

			next();

		}, function() {

			// Copying index files
			var args = [ '-a' ].concat(filelist, [ outputPath ]);
			var cmd = child_process.spawn('cp', args);
			cmd.on('close', function() {

				callback(null);
			});
		})
	});

};

Rootfs.prototype.fetchPackageIndexes = function(outputPath, callback) {
	var self = this;

	var rootfsExecuter = new RootfsExecuter(self);

	var sourceDirPath = path.join(self.targetPath, 'var', 'lib', 'apt', 'lists');

	fs.readdir(sourceDirPath, function(err, files) {
		if (err) {
			callback(err);
			return;
		}

		if (files.length == 0) {
			callback();
			return;
		}

		var filelist = [];

		// Finding index files
		async.each(files, function(filename, next) {

			if (filename.lastIndexOf('_Packages') > 0 ||
				filename.lastIndexOf('_Translation-en') > 0 ||
				filename.lastIndexOf('_InRelease') > 0 ||
				filename.lastIndexOf('_Release') > 0) {

				filelist.push(path.join(sourceDirPath, filename));
			}

			next();

		}, function() {

			// Copying index files
			var args = [ '-a' ].concat(filelist, [ outputPath ]);
			var cmd = child_process.spawn('cp', args);
			cmd.on('close', function() {

				callback(null);
			});
		})
	});

};

Rootfs.prototype.registerServices = function(services, opts, callback) {
	var self = this;

	if (Object.keys(services).length == 0) {
		process.nextTick(function() {
			callback(null);
		});
		return;
	}

	var rootfsExecuter = new RootfsExecuter(self);

	for (var name in services) {
		rootfsExecuter.addCommand('insserv -v -d /etc/init.d/' + name);
	}

	rootfsExecuter.run({}, function() {
		callback(null);
	});
};

Rootfs.prototype.installPackages = function(packages, opts, callback) {
	var self = this;

	if (Object.keys(packages).length == 0) {
		process.nextTick(function() {
			callback(null);
		});
		return;
	}

	var pkgs = [];
	for (var name in packages) {
		var version = packages[name];
		if (version == '*' || version == '')
			pkgs.push(name);
		else
			pkgs.push(name + '=' + version);
	}

	var rootfsExecuter = new RootfsExecuter(self);

	rootfsExecuter.addCommand('apt-get update');
	rootfsExecuter.addCommand('apt-get install -f --no-install-recommends -q --force-yes -y ' + pkgs.join(' '))
	rootfsExecuter.run({}, function() {
		callback(null);
	});

};

Rootfs.prototype.applyPackages = function(opts, callback) {
	var self = this;

	// TODO: check Packages.gz and remove it if it doesn't exist
	var failed = false;
	var dpkg = child_process.spawn('dpkg-scanpackages', [
		'.',
		'/dev/null'
	], {
		cwd: path.join(self.targetPath, '.stemmer', 'packages')
	});

	var gzip = child_process.spawn('gzip', [
		'-9c'
	]);

	dpkg.stdout.on('data', function(data) {
		gzip.stdin.write(data);
	});

	dpkg.on('close', function() {
		gzip.stdin.end();
	});

	var packageListFile = path.join(self.targetPath, '.stemmer', 'packages', 'Packages.gz');
	gzip.stdout.on('data', function(data) {

		fs.appendFile(packageListFile, data, function(err) {
			if (err) {
				callback(err);
				failed = true;
			}
		});
	});

	gzip.on('close', function() {
		if (!failed)
			callback();
	});

};
<|endoftext|>