<commit_before>import * as generators from '../common/generators';
import * as cosets from '../fpgroups/cosets';
import * as util from '../common/util';

import * as covers from '../dsymbols/covers';
import * as DS from '../dsymbols/delaney';
import * as DS2D from '../dsymbols/delaney2d';
import * as fundamental from '../dsymbols/fundamental';
import * as props from '../dsymbols/properties';

import { rationals } from '../arithmetic/types';
const Q = rationals;

const timers = util.timers();

const _loopless = (ds, i, j, D) => DS.orbit2(ds, i, j, D)
  .every(E => ds.s(i, E) != E && ds.s(j, E) != E);

const _orbits = ds => {
  const result = [];

  for (const [i, j] of [[0, 1], [1, 2]]) {
    for (const D of DS.orbitReps2(ds, i, j)) {
      result.push([i, D, DS.r(ds, i, j, D), _loopless(ds, i, j, D)]);
    }
  }

  return result;
};

const _openOrbits = ds =>
  _orbits(ds).filter(([i, D, r, loopless]) => !ds.v(i, i+1, D));

const _withMinimalBranchings = ds => {
  const branchings = (i, j) =>
    DS.orbitReps2(ds, i, j)
    .filter(D => !ds.v(i, j, D))
    .map(D => [D, Math.ceil(3 / DS.r(ds, i, j, D))]);

  return DS.withBranchings(
    DS.withBranchings(ds, 0, branchings(0, 1)),
    1,
    branchings(1, 2)
  );
};

const _compareMapped = (ds, m) => {
  for (const D of ds.elements()) {
    for (const [i, j] of [[0, 1], [1, 2]]) {
      const d = ds.v(i, j, D) - ds.v(i, j, m[D]);
      if (d != 0) return d;
    }
  }
  return 0;
};

const _isCanonical = (ds, maps) => maps.every(m => _compareMapped(ds, m) >= 0);

const _newCurvature = (curv, loopless, v, vOld) =>
  Q.plus(
    curv,
    Q.times(loopless ? 2 : 1, Q.minus(Q.div(1, v), Q.div(1, vOld)))
  );

const _isMinimallyHyperbolic = (ds, curv) => {
  if (Q.ge(curv, 0))
    return false;

  for (const [i, D, r, loopless] of _orbits(ds)) {
    const v = ds.v(i, i+1, D);

    if (v && v > Math.ceil(3 / r)) {
      const newCurv = _newCurvature(curv, loopless, v-1, v);
      if (Q.lt(newCurv, 0))
        return false;
    }
  }

  return true;
};

const _goodResult = (ds, curv) => {
  let good;

  if (Q.le(curv, 0))
    good = true;
  else {
    const cones = [];
    const corners = [];
    for (const [i, j] of [[0, 1], [0, 2], [1, 2]]) {
      for (const D of DS.orbitReps2(ds, i, j)) {
        const v = ds.v(i, j, D);
        if (v > 1) {
          if (_loopless(ds, i, j, D))
            cones.push(v);
          else
            corners.push(v);
        }
      }
    }
    const front = cones.sort().reverse().join('');
    const middle = props.isLoopless(ds) ? '' : '*';
    const back = corners.sort().reverse().join('');
    const cross = props.isWeaklyOriented(ds) ? '' : 'x';
    const key = front + middle + back + cross;

    const goodKeys = [
      '', '*', 'x',
      '532', '432', '332',
      '422', '322', '222',
      '44', '33', '22',
      '*532', '*432', '*332', '3*2',
      '*422', '*322', '*222', '2*4', '2*3', '2*2',
      '*44', '*33', '*22', '4*', '3*', '2*', '4x', '3x', '2x',
      // TODO the following are only allowed for backwards compatibility
      //'722', '622', '522',
      //'*722', '*622', '*522',
      //'7*', '6*', '5*', '7x', '6x', '5x'
    ];

    good = goodKeys.indexOf(key) >= 0;
  }

  return good;
};

const _morphism = (src, srcD0, img, imgD0) => {
  const idcs = src.indices();

  const q = [[srcD0, imgD0]];
  const m = new Array(src.size + 1);
  m[srcD0] = imgD0;

  while (q.length) {
    const [D, E] = q.shift();

    for (const i of idcs) {
      const Di = src.s(i, D);
      const Ei = img.s(i, E);

      if (Di != null || Ei != null) {
        if (m[Di] == null) {
          q.push([Di, Ei]);
          m[Di] = Ei;
        }
        else if (m[Di] != Ei)
          return null;
      }
    }
  }

  return m;
};

const _automorphisms = ds => {
  const elms = ds.elements();
  if (elms.length) {
    const D = elms[0];
    return elms.map(E => _morphism(ds, D, ds, E)).filter(m => m != null);
  }
};

const _curvature = ds => {
  timers && timers.start('curvature');
  const denom = 420;
  let numer = -DS.size(ds) * denom;
  for (const [i, j] of [[0, 1], [0, 2], [1, 2]]) {
    for (const D of DS.orbitReps2(ds, i, j)) {
      const k = _loopless(ds, i, j, D) ? 2 : 1;
      numer += k * denom / ds.v(i, j, D);
    }
  }
  const curv = Q.div(numer, denom);
  timers && timers.stop('curvature');
  return curv;
};

const branchings = ds => {
  timers && timers.start('branchings.init');
  const unused = _openOrbits(ds);
  const maps = _automorphisms(ds);
  const ds0 = _withMinimalBranchings(ds);
  const curv0 = _curvature(ds0);
  timers && timers.stop('branchings.init');

  return generators.backtracker({
    root: [ds0, curv0, unused],

    extract([ds, curv, unused]) {
      if (unused.length == 0) {
        timers && timers.start('branchings.extract');
        const keep = _isCanonical(ds, maps) && _goodResult(ds, curv);
        timers && timers.stop('branchings.extract');
        if (keep)
          return ds;
      }
    },

    children([ds, curv, unused]) {
      if (unused.length) {
        if (Q.lt(curv, 0)) {
          return [[ds, curv, []]];
        }
        else {
          timers && timers.start('branchings.children');
          const [i, D, r, loopless] = unused[0];
          const v0 = ds.v(i, i+1, D);
          const out = [];

          for (let v = v0; v <= 7; ++v) {
            const newCurv = _newCurvature(curv, loopless, v, v0);
            const newDs = DS.withBranchings(ds, i, [[D, v]]);

            if (Q.ge(newCurv, 0) || _isMinimallyHyperbolic(newDs, newCurv))
              out.push([ newDs, newCurv, unused.slice(1) ]);

            if (Q.lt(newCurv, 0))
              break;
          }
          timers && timers.stop('branchings.children');

          return out;
        }
      }
    }
  });
}

const delaneySets = maxSize => {
  const _firstUndefined = data => {
    const i = data.indexOf(null);
    if (i >= 0)
      return [Math.floor(i / 3) + 1, i % 3];
  };

  const _get = (data, i, D) => data[(D - 1) * 3 + i];

  const _set = (data, i, D, E) => {
    data[(D - 1) * 3 + i] = E;
    data[(E - 1) * 3 + i] = D;
  };

  const _makeDelaneySet = data => {
    const dim = 2;
    const size = data.length / 3;
    const ops = new Array(dim + 1).fill(0).map(_ => []);
    const brs = new Array(dim).fill(0).map(_ => []);

    for (let D = 1; D <= size; ++D) {
      for (let i = 0; i <= 2; ++i)
        brs[i].push([D, _get(data, i, D)]);
    }
    return DS.build(dim, size, (_, i) => ops[i], (_, i) => brs[i]);
  };

  const _close02Orbit = (data, D) => {
  };

  const _potentialChildren = (data, maxSize) => {
    const size = data.length / 3;
    const limit = Math.min(size + 1, maxSize);
    const [D, i] = _firstUndefined(data);
    const result = [];

    for (const E of range(D, limit)) {
      if (E > size)
        data = data.concat([null, null, null]);

      if (_get(data, E, i) == null) {
        out = data.slice();
        _set(out, i, D, E);
        _close02Orbits(out, D);
        result.push(out);
      }
    }

    return result;
  };

  return generators.backtracker({
    root: [null, null, null],

    extract(data) {
      return _firstUndefined(data) ? null : _makeDelaneySet(data);
    },

    children(data) {
      return _potentialChildren(data, maxSize).filter(_isCanonical);
    }
  });
}

function* coversGenerator(ds, maxDeg) {
  timers && timers.start('covers');
  const fun = fundamental.fundamentalGroup(ds);
  const tableGenerator = cosets.tables(fun.nrGenerators, fun.relators, maxDeg);
  const iter = generators.results(tableGenerator);
  timers && timers.stop('covers');

  while (true) {
    timers && timers.start('covers');
    timers && timers.start('covers.generator');
    const result = iter.next();
    timers && timers.stop('covers.generator');
    timers && timers.stop('covers');

    if (result.done)
      break;

    timers && timers.start('covers');
    timers && timers.start('covers.convert');
    const cover = covers.coverForTable(ds, result.value, fun.edge2word);
    timers && timers.stop('covers.convert');
    timers && timers.stop('covers');

    yield cover;
  }
};

if (require.main == module) {
  const arg = process.argv[2];

  timers && timers.start('total');

  if (Number.isInteger(parseInt(arg))) {
    const ds0 = DS.parse('<1.1:1:1,1,1:0,0>');

    for (const dset of coversGenerator(ds0, parseInt(arg))) {
      timers && timers.start('branchings');
      for (const ds of generators.results(branchings(dset)))
        console.log(`${ds}`);
      timers && timers.stop('branchings');
    }
  }
  else {
    for (const ds of generators.results(branchings(DS.parseSymbols(arg)[0])))
      console.log(`${ds}`);
  }

  timers && timers.stop('total');
  timers && console.log(`${JSON.stringify(timers.current(), null, 2)}`);
}
<commit_msg>scripts/daniel: finished alternative D-set generator, now needs debugging<commit_after>import * as generators from '../common/generators';
import * as cosets from '../fpgroups/cosets';
import * as util from '../common/util';

import * as covers from '../dsymbols/covers';
import * as DS from '../dsymbols/delaney';
import * as DS2D from '../dsymbols/delaney2d';
import * as fundamental from '../dsymbols/fundamental';
import * as props from '../dsymbols/properties';

import { rationals } from '../arithmetic/types';
const Q = rationals;

const timers = util.timers();

const _loopless = (ds, i, j, D) => DS.orbit2(ds, i, j, D)
  .every(E => ds.s(i, E) != E && ds.s(j, E) != E);

const _orbits = ds => {
  const result = [];

  for (const [i, j] of [[0, 1], [1, 2]]) {
    for (const D of DS.orbitReps2(ds, i, j)) {
      result.push([i, D, DS.r(ds, i, j, D), _loopless(ds, i, j, D)]);
    }
  }

  return result;
};

const _openOrbits = ds =>
  _orbits(ds).filter(([i, D, r, loopless]) => !ds.v(i, i+1, D));

const _withMinimalBranchings = ds => {
  const branchings = (i, j) =>
    DS.orbitReps2(ds, i, j)
    .filter(D => !ds.v(i, j, D))
    .map(D => [D, Math.ceil(3 / DS.r(ds, i, j, D))]);

  return DS.withBranchings(
    DS.withBranchings(ds, 0, branchings(0, 1)),
    1,
    branchings(1, 2)
  );
};

const _compareMapped = (ds, m) => {
  for (const D of ds.elements()) {
    for (const [i, j] of [[0, 1], [1, 2]]) {
      const d = ds.v(i, j, D) - ds.v(i, j, m[D]);
      if (d != 0) return d;
    }
  }
  return 0;
};

const _isCanonical = (ds, maps) => maps.every(m => _compareMapped(ds, m) >= 0);

const _newCurvature = (curv, loopless, v, vOld) =>
  Q.plus(
    curv,
    Q.times(loopless ? 2 : 1, Q.minus(Q.div(1, v), Q.div(1, vOld)))
  );

const _isMinimallyHyperbolic = (ds, curv) => {
  if (Q.ge(curv, 0))
    return false;

  for (const [i, D, r, loopless] of _orbits(ds)) {
    const v = ds.v(i, i+1, D);

    if (v && v > Math.ceil(3 / r)) {
      const newCurv = _newCurvature(curv, loopless, v-1, v);
      if (Q.lt(newCurv, 0))
        return false;
    }
  }

  return true;
};

const _goodResult = (ds, curv) => {
  let good;

  if (Q.le(curv, 0))
    good = true;
  else {
    const cones = [];
    const corners = [];
    for (const [i, j] of [[0, 1], [0, 2], [1, 2]]) {
      for (const D of DS.orbitReps2(ds, i, j)) {
        const v = ds.v(i, j, D);
        if (v > 1) {
          if (_loopless(ds, i, j, D))
            cones.push(v);
          else
            corners.push(v);
        }
      }
    }
    const front = cones.sort().reverse().join('');
    const middle = props.isLoopless(ds) ? '' : '*';
    const back = corners.sort().reverse().join('');
    const cross = props.isWeaklyOriented(ds) ? '' : 'x';
    const key = front + middle + back + cross;

    const goodKeys = [
      '', '*', 'x',
      '532', '432', '332',
      '422', '322', '222',
      '44', '33', '22',
      '*532', '*432', '*332', '3*2',
      '*422', '*322', '*222', '2*4', '2*3', '2*2',
      '*44', '*33', '*22', '4*', '3*', '2*', '4x', '3x', '2x',
      // TODO the following are only allowed for backwards compatibility
      //'722', '622', '522',
      //'*722', '*622', '*522',
      //'7*', '6*', '5*', '7x', '6x', '5x'
    ];

    good = goodKeys.indexOf(key) >= 0;
  }

  return good;
};

const _morphism = (src, srcD0, img, imgD0) => {
  const idcs = src.indices();

  const q = [[srcD0, imgD0]];
  const m = new Array(src.size + 1);
  m[srcD0] = imgD0;

  while (q.length) {
    const [D, E] = q.shift();

    for (const i of idcs) {
      const Di = src.s(i, D);
      const Ei = img.s(i, E);

      if (Di != null || Ei != null) {
        if (m[Di] == null) {
          q.push([Di, Ei]);
          m[Di] = Ei;
        }
        else if (m[Di] != Ei)
          return null;
      }
    }
  }

  return m;
};

const _automorphisms = ds => {
  const elms = ds.elements();
  if (elms.length) {
    const D = elms[0];
    return elms.map(E => _morphism(ds, D, ds, E)).filter(m => m != null);
  }
};

const _curvature = ds => {
  timers && timers.start('curvature');
  const denom = 420;
  let numer = -DS.size(ds) * denom;
  for (const [i, j] of [[0, 1], [0, 2], [1, 2]]) {
    for (const D of DS.orbitReps2(ds, i, j)) {
      const k = _loopless(ds, i, j, D) ? 2 : 1;
      numer += k * denom / ds.v(i, j, D);
    }
  }
  const curv = Q.div(numer, denom);
  timers && timers.stop('curvature');
  return curv;
};

const branchings = ds => {
  timers && timers.start('branchings.init');
  const unused = _openOrbits(ds);
  const maps = _automorphisms(ds);
  const ds0 = _withMinimalBranchings(ds);
  const curv0 = _curvature(ds0);
  timers && timers.stop('branchings.init');

  return generators.backtracker({
    root: [ds0, curv0, unused],

    extract([ds, curv, unused]) {
      if (unused.length == 0) {
        timers && timers.start('branchings.extract');
        const keep = _isCanonical(ds, maps) && _goodResult(ds, curv);
        timers && timers.stop('branchings.extract');
        if (keep)
          return ds;
      }
    },

    children([ds, curv, unused]) {
      if (unused.length) {
        if (Q.lt(curv, 0)) {
          return [[ds, curv, []]];
        }
        else {
          timers && timers.start('branchings.children');
          const [i, D, r, loopless] = unused[0];
          const v0 = ds.v(i, i+1, D);
          const out = [];

          for (let v = v0; v <= 7; ++v) {
            const newCurv = _newCurvature(curv, loopless, v, v0);
            const newDs = DS.withBranchings(ds, i, [[D, v]]);

            if (Q.ge(newCurv, 0) || _isMinimallyHyperbolic(newDs, newCurv))
              out.push([ newDs, newCurv, unused.slice(1) ]);

            if (Q.lt(newCurv, 0))
              break;
          }
          timers && timers.stop('branchings.children');

          return out;
        }
      }
    }
  });
}

const delaneySets = maxSize => {
  const _firstUndefined = data => {
    const i = data.indexOf(null);
    if (i >= 0)
      return [Math.floor(i / 3) + 1, i % 3];
  };

  const _size = data => data.length / 3;

  const _get = (data, i, D) => data[(D - 1) * 3 + i];

  const _set = (data, i, D, E) => {
    data[(D - 1) * 3 + i] = E;
    data[(E - 1) * 3 + i] = D;
  };

  const _makeDelaneySet = data => {
    const dim = 2;
    const size = _size(data);
    const ops = new Array(dim + 1).fill(0).map(_ => []);
    const brs = new Array(dim).fill(0).map(_ => []);

    for (let D = 1; D <= size; ++D) {
      for (let i = 0; i <= 2; ++i)
        ops[i].push([D, _get(data, i, D)]);
    }
    return DS.build(dim, size, (_, i) => ops[i], (_, i) => brs[i]);
  };

  const _scan = (data, w, D, limit) => {
    let [E, k] = [D, 0];

    while (k < limit && _get(w[k], E) != null)
      [E, k] = [_get(w[k], E), k + 1];

    return [E, k];
  };

  const _scan02Orbit = (data, D) => {
    const [head, i] = _scan(data, [0, 2, 0, 2], D, 4);
    const [tail, j] = _scan(data, [2, 0, 2, 0], head, 4 - i);
    const gap = 4 - i - j;
    return [head, tail, gap, 2 * (i % 2)];
  };

  const _potentialChildren = (data, maxSize) => {
    const size = _size(data);
    const limit = Math.min(size + 1, maxSize);
    const [D, i] = _firstUndefined(data);
    const result = [];

    for (let E = D; E < limit; ++E) {
      if (E > size)
        data = data.concat([null, null, null]);

      if (_get(data, E, i) == null) {
        const out = data.slice();
        _set(out, i, D, E);

        const [head, tail, gap, k] = _scan02Orbit(out, D);
        if (gap == 1)
          _set(out, k, head, tail);
        else if (gap > 0 || head == tail)
          result.push(out);
      }
    }

    return result;
  };

  const _compareRenumberedFrom = (data, D0) => {
    const n2o = [ null, D0];
    const o2n = { [D0]: 1 };

    for (let D = 1; D <= _size(data); ++D) {
      if (D >= n2o.length)
        throw new Error("symbol is not transitive");

      for (const i of [0, 1, 2]) {
        const E = _get(data, i, n2o[D]);
        if (E != null && o2n[E] == null) {
          o2n[E] = n2o.length;
          n2o.push(E);
        }

        const nval = o2n[E];
        const oval = _get(data, i, D);
        if (oval != nval)
          return oval == null ? -1 : nval == null ? 1 : nval - oval;
      }
    }

    return 0;
  };

  const _isCanonical = data => {
    for (let D = 1; D <= _size(data); ++D) {
      if (_compareRenumberedFrom(data, D) < 0)
        return false;
    }
    return true;
  };

  return generators.backtracker({
    root: [null, null, null],

    extract(data) {
      return _firstUndefined(data) ? null : _makeDelaneySet(data);
    },

    children(data) {
      return _potentialChildren(data, maxSize).filter(_isCanonical);
    }
  });
}

function* coversGenerator(ds, maxDeg) {
  timers && timers.start('covers');
  const fun = fundamental.fundamentalGroup(ds);
  const tableGenerator = cosets.tables(fun.nrGenerators, fun.relators, maxDeg);
  const iter = generators.results(tableGenerator);
  timers && timers.stop('covers');

  while (true) {
    timers && timers.start('covers');
    timers && timers.start('covers.generator');
    const result = iter.next();
    timers && timers.stop('covers.generator');
    timers && timers.stop('covers');

    if (result.done)
      break;

    timers && timers.start('covers');
    timers && timers.start('covers.convert');
    const cover = covers.coverForTable(ds, result.value, fun.edge2word);
    timers && timers.stop('covers.convert');
    timers && timers.stop('covers');

    yield cover;
  }
};

if (require.main == module) {
  const arg = process.argv[2];

  timers && timers.start('total');

  if (Number.isInteger(parseInt(arg))) {
    const maxSize = parseInt(arg);
    const ds0 = DS.parse('<1.1:1:1,1,1:0,0>');

    //for (const dset of coversGenerator(ds0, maxSize)) {
    for (const dset of generators.results(delaneySets(maxSize))) {
      timers && timers.start('branchings');
      for (const ds of generators.results(branchings(dset)))
        console.log(`${ds}`);
      timers && timers.stop('branchings');
    }
  }
  else {
    for (const ds of generators.results(branchings(DS.parseSymbols(arg)[0])))
      console.log(`${ds}`);
  }

  timers && timers.stop('total');
  timers && console.log(`${JSON.stringify(timers.current(), null, 2)}`);
}
<|endoftext|>


<commit_before>// Copyright (c) 2013, importre. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/**
 * Parses the result of $scope.loadDevices().
 *
 * @param data
 * @returns {{firstSerial: null, deviceInfoList: Object, numOfDevices: Number}}
 */
function parseDeviceInfoList(data) {
    var lines = data.trim().split("\n");
    var deviceInfoList = new Object();
    var firstSerial = null;

    for (var i in lines) {
        lines[i] = lines[i].trim().split(/\s+/g);
        var serial = lines[i][0];

        if (0 == i) {
            firstSerial = serial;
        }

        deviceInfoList[serial] = {
            serial: serial,
            state: lines[i][1],
            usb: null,
            product: null,
            model: null,
            device: null
        }
        for (var j = 2; j < lines[i].length; j++) {
            if (lines[i][j].match(/^usb:/)) {
                deviceInfoList[serial].usb = lines[i][j].substr(4);
            } else if (lines[i][j].match(/^product:/)) {
                deviceInfoList[serial].product = lines[i][j].substr(8);
            } else if (lines[i][j].match(/^model:/)) {
                deviceInfoList[serial].model = lines[i][j].substr(6);
            } else if (lines[i][j].match(/^device:/)) {
                deviceInfoList[serial].device = lines[i][j].substr(7);
            }
        }
    }

    var keys = Object.keys(deviceInfoList);
    if (keys.length > 0) {
        firstSerial = keys.sort()[0];
    }

    return {
        firstSerial: firstSerial,
        deviceInfoList: deviceInfoList,
        numOfDevices: lines.length
    };
}

/**
 * Parses the result of $scope.loadPackages().
 *
 * @param data
 * @returns {Array}
 */
function parsePackageList(data) {
    var lines = data.trim().split("\n");

    for (var i in lines) {
        lines[i] = lines[i].replace(/^package:/, "").trim();
    }

    return lines;
}

/**
 * Makes adb command.
 *
 * @param cmd
 * @returns {string} <the length of zero padded cmd><cmd>
 */
function makeCommand(cmd) {
    var hex = cmd.length.toString(16);
    while (hex.length < 4) {
        hex = "0" + hex;
    }

    cmd = hex + cmd;
    return cmd;
}

/**
 * Parses the result of $scope.loadProcessList()
 *
 * @param data
 * @returns {Array}
 */
function parseProcessList(data) {
    var re = new RegExp(/^(\w+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+([a-fA-F0-9]+)\s+([a-fA-F0-9]+ \w)\s+(.+)/m);
    var lines = data.trim().split("\n");
    var line;

    for (var i in lines) {
        line = lines[i].trim();
        if (0 == i) {
            line = line.trim().split(/\s+/);
        } else {
            line = re.exec(line);
            line.splice(0, 1);
        }
        lines[i] = line;
    }
    return lines;
}

function parseMemInfo(data) {
    // \1: memory (kb)
    // \2: process name
    // \3: pid
    var re = new RegExp(/^(\d+)\s+kB:\s+(\S+)\s\(pid\s+(\d+).*/);
    var lines = data.trim().split("\n");
    var line;
    var pss = 0;
    var ret = [];

    for (var i in lines) {
        line = lines[i].trim();

        if (line.length == 0) {
            continue;
        }

        if (line.indexOf("Total PSS by process") >= 0) {
            pss++;
            continue;
        }

        if (pss == 1) {
            line = re.exec(line);
            if (line) {
                ret.push({
                    process: line[2],
                    pid: line[3],
                    kb: line[1] + " KB",
                    mb: parseInt(parseFloat(line[1]) / 1024 + 0.5) + " MB"
                });
            } else {
                break;
            }
        }
    }
    return ret;
}

function parsePackageMemInfo(data) {
    var lines = data.trim().split("\n");
    var line, tempLine, length;
    var ret = [];
    var cnt = 0;
    var found = false;
    var idxOfSize, idxOfAlloc, idxOfFree;

    for (var i in lines) {
        line = lines[i].trim();
        tempLine = line.split(/\s+/);
        length = tempLine.length;

        if (!found) {
            idxOfSize = tempLine.indexOf("Size");
            idxOfAlloc = tempLine.indexOf("Alloc");
            idxOfFree = tempLine.indexOf("Free");

            if (idxOfSize >= 0 && idxOfAlloc >= 0 && idxOfFree >= 0) {
                idxOfSize = length - idxOfSize;
                idxOfAlloc = length - idxOfAlloc;
                idxOfFree = length - idxOfFree;
                found = true;
                continue;
            }
        }

        if (found && (tempLine[0] == "Native" || tempLine[0] == "Dalvik")) {
            ret.push({
                area: tempLine[0],
                size: tempLine[length - idxOfSize],
                alloc: tempLine[length - idxOfAlloc],
                free: tempLine[length - idxOfFree]
            });
            cnt++;
        }

        if (cnt >= 2) {
            break;
        }
    }
    return ret;
}

function parseDiskSpace(data) {
    var lines = data.trim().split("\n");
    var line, head, body = [];

    for (var i in lines) {
        line = lines[i].trim().split(/\s+/);
        if (i == 0) {
            head = line;
        } else {
            body.push(line);
        }
    }
    return {head: head, body: body};
}<commit_msg>Support for parsing android 4.4 process list result.<commit_after>// Copyright (c) 2013, importre. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/**
 * Parses the result of $scope.loadDevices().
 *
 * @param data
 * @returns {{firstSerial: null, deviceInfoList: Object, numOfDevices: Number}}
 */
function parseDeviceInfoList(data) {
    var lines = data.trim().split("\n");
    var deviceInfoList = new Object();
    var firstSerial = null;

    for (var i in lines) {
        lines[i] = lines[i].trim().split(/\s+/g);
        var serial = lines[i][0];

        if (0 == i) {
            firstSerial = serial;
        }

        deviceInfoList[serial] = {
            serial: serial,
            state: lines[i][1],
            usb: null,
            product: null,
            model: null,
            device: null
        }
        for (var j = 2; j < lines[i].length; j++) {
            if (lines[i][j].match(/^usb:/)) {
                deviceInfoList[serial].usb = lines[i][j].substr(4);
            } else if (lines[i][j].match(/^product:/)) {
                deviceInfoList[serial].product = lines[i][j].substr(8);
            } else if (lines[i][j].match(/^model:/)) {
                deviceInfoList[serial].model = lines[i][j].substr(6);
            } else if (lines[i][j].match(/^device:/)) {
                deviceInfoList[serial].device = lines[i][j].substr(7);
            }
        }
    }

    var keys = Object.keys(deviceInfoList);
    if (keys.length > 0) {
        firstSerial = keys.sort()[0];
    }

    return {
        firstSerial: firstSerial,
        deviceInfoList: deviceInfoList,
        numOfDevices: lines.length
    };
}

/**
 * Parses the result of $scope.loadPackages().
 *
 * @param data
 * @returns {Array}
 */
function parsePackageList(data) {
    var lines = data.trim().split("\n");

    for (var i in lines) {
        lines[i] = lines[i].replace(/^package:/, "").trim();
    }

    return lines;
}

/**
 * Makes adb command.
 *
 * @param cmd
 * @returns {string} <the length of zero padded cmd><cmd>
 */
function makeCommand(cmd) {
    var hex = cmd.length.toString(16);
    while (hex.length < 4) {
        hex = "0" + hex;
    }

    cmd = hex + cmd;
    return cmd;
}

/**
 * Parses the result of $scope.loadProcessList()
 *
 * @param data
 * @returns {Array}
 */
function parseProcessList(data) {
    // parse oldstyle ps result
    var ore = new RegExp(/^(\w+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+([a-fA-F0-9]+)\s+([a-fA-F0-9]+ \w)\s+(.+)/m);
    // parse 4.4 or above ps result
    var nre = new RegExp(/^(\d+)\s+(\d+)\s+(\d+m?)\s+(\w+\s*<?)\s+(.+)/m);
    var lines = data.trim().split("\n");
    var line;

    for (var i in lines) {
        line = lines[i].trim();
        if (0 == i) {
            line = line.trim().split(/\s+/);
        } else {
            var parsed = ore.exec(line);
            line = !!parsed ? parsed : nre.exec(line);
            line.splice(0, 1);
        }
        lines[i] = line;
    }
    return lines;
}

function parseMemInfo(data) {
    // \1: memory (kb)
    // \2: process name
    // \3: pid
    var re = new RegExp(/^(\d+)\s+kB:\s+(\S+)\s\(pid\s+(\d+).*/);
    var lines = data.trim().split("\n");
    var line;
    var pss = 0;
    var ret = [];

    for (var i in lines) {
        line = lines[i].trim();

        if (line.length == 0) {
            continue;
        }

        if (line.indexOf("Total PSS by process") >= 0) {
            pss++;
            continue;
        }

        if (pss == 1) {
            line = re.exec(line);
            if (line) {
                ret.push({
                    process: line[2],
                    pid: line[3],
                    kb: line[1] + " KB",
                    mb: parseInt(parseFloat(line[1]) / 1024 + 0.5) + " MB"
                });
            } else {
                break;
            }
        }
    }
    return ret;
}

function parsePackageMemInfo(data) {
    var lines = data.trim().split("\n");
    var line, tempLine, length;
    var ret = [];
    var cnt = 0;
    var found = false;
    var idxOfSize, idxOfAlloc, idxOfFree;

    for (var i in lines) {
        line = lines[i].trim();
        tempLine = line.split(/\s+/);
        length = tempLine.length;

        if (!found) {
            idxOfSize = tempLine.indexOf("Size");
            idxOfAlloc = tempLine.indexOf("Alloc");
            idxOfFree = tempLine.indexOf("Free");

            if (idxOfSize >= 0 && idxOfAlloc >= 0 && idxOfFree >= 0) {
                idxOfSize = length - idxOfSize;
                idxOfAlloc = length - idxOfAlloc;
                idxOfFree = length - idxOfFree;
                found = true;
                continue;
            }
        }

        if (found && (tempLine[0] == "Native" || tempLine[0] == "Dalvik")) {
            ret.push({
                area: tempLine[0],
                size: tempLine[length - idxOfSize],
                alloc: tempLine[length - idxOfAlloc],
                free: tempLine[length - idxOfFree]
            });
            cnt++;
        }

        if (cnt >= 2) {
            break;
        }
    }
    return ret;
}

function parseDiskSpace(data) {
    var lines = data.trim().split("\n");
    var line, head, body = [];

    for (var i in lines) {
        line = lines[i].trim().split(/\s+/);
        if (i == 0) {
            head = line;
        } else {
            body.push(line);
        }
    }
    return {head: head, body: body};
}
<|endoftext|>


<commit_before>//
// Description:
//   Send a request to play a youtube video
//
// Commands:
//   hubot tube me <video> - Plays the audio from a youtube video
//   hubot tube stop - Stops the current youtube video audio that is playing
//
// Authors:
//   jballant
//
/*jshint node:true */
"use strict";

var http = require('http');
var logger = require('./support/logger');
var XSERV_BASE_URL = 'http://xserv:5051/';

function makeUrl (tubeUrl) {
    var findVideoIdForUrlReg = /^https:\/\/www\.youtube\.com\/watch\?v=(\w+)/;
    var matches = tubeUrl.match(findVideoIdForUrlReg);
    var vidId;
    if (matches && matches[1]) {
        vidId = matches[1];
    } else {
        return null;
    }
    return XSERV_BASE_URL + 'youtube/?vid=' + encodeURIComponent(vidId);
}

function makePlayVideoRequest (tubeUrl, callback) {
    // TODO: Remove these below
    var url = makeUrl(tubeUrl);
    if (!url) {
        logger.minorInfo('Could not create play url for link %s', tubeUrl);
        return callback('Malformed youtube link');
    }
    logger.minorInfo('Requesting youtube sound clip "%s"', url);
    callback(null, url);

    // TODO: Uncomment request below once endpoint works
    // http.get(url, function (res) {
    //     logResponse(url, res);
    //     if (callback) {
    //         callback(null, url);
    //     }
    // });
}

function makeStopVideoRequest (callback) {
    var url = XSERV_BASE_URL + 'stop-youtube';
    logger.minorInfo('Requesting that the current youtube clip stop playing');
    http.get(url, function (res) {
        logResponse(url, res);
        if (callback) {
            callback();
        }
    });
}

function logResponse (url, res) {
    logger.requestResolution(url, res.statusCode);
}

function notFound (message) {
    return message.send('Not found');
}

module.exports = function (robot) {

    robot.respond(/tube me (.+)/i, function (message) {
        if (!message.match[1]) {
            logger.minorInfo('Could not find url match in message');
            return notFound(message);
        }
        var url = message.match[1];
        makePlayVideoRequest(url, function (err, finalUrl) {
            if (err) {
                return message.send(err);
            }
            // TODO REMOVE THE BELOW WHEN ENDPOINTS WORK
            return message.send("Playing youtube clip " + finalUrl);
            // return message.send("Playing youtube clip");
        });
    });

    robot.respond(/tube stop/i, function (message) {
        makeStopVideoRequest();
    });

};<commit_msg>Work on making youtube scripts actually work<commit_after>// Description:
//   Hit an api with play and stop commands to play youtube videos
//
// Configuration:
//   HUBOT_YOUTUBE_API_BASE_URL
//
// Description:
//   Send a request to play a youtube video
//
// Commands:
//   hubot tube me <video> - Plays or queues the audio from a youtube video
//   hubot tube stop - Stops the current youtube video audio that is playing and empties the queue
//   hubot tube next - Proceeds to the next youtube clip in the queue
//
// Authors:
//   jballant
//
/*jshint node:true */
"use strict";

var http = require('http');
var logger = require('./support/logger');
var nodeUrl = require('url');
var XSERV_BASE_URL = "" + (process.env.HUBOT_YOUTUBE_API_BASE_URL || 'http://xserv:5051/');
var SPOTIFY_URL = "" + (process.env.HUBOT_SPOT_URL || "http://localhost ");

function makeUrl (tubeUrl) {
    // var findVideoIdForUrlReg = /^https:\/\/www\.youtube\.com\/watch\?v=(\w+)/;
    // var matches = tubeUrl.match(findVideoIdForUrlReg);
    // var vidId;
    // if (matches && matches[1]) {
    //     vidId = matches[1];
    // } else {
    //     return null;
    // }
    if (!tubeUrl) {
        return null;
    }
    return XSERV_BASE_URL + 'play-youtube-uri/?uri=' + encodeURIComponent(tubeUrl);
}

function isValidTubeURL (url) {
    return (/^https:\/\/www\.youtube\.com\/watch\/?\?v=(\w+)/).test(url);
}

function hmsToSecondsOnly(str) {
    var p = str.split(':');
    var s = 0;
    var m = 1;
    while (p.length > 0) {
        s += m * parseInt(p.pop(), 10);
        m *= 60;
    }
    return s;
}

function makeGetRequest (url, callback) {
    http.get(url, function (res) {
        logResponse(url, res);
        var body = '';
        if (callback) {
            res.on('data', function (chunk) {
                body += chunk;
            });
            res.on('end', function () {
                logInfo(body);
                callback(null, body);
            });
        }
    }).on('error', function (e) {
        logErr(e);
        if (callback) {
            callback(e);
        }
    });
}

function makePlayVideoRequest (tubeUrl, callback) {
    var url = makeUrl(tubeUrl);
    if (!url) {
        logInfo('Could not create play url for link %s', tubeUrl);
        return callback('Malformed youtube link');
    }
    logger.minorInfo('Requesting youtube sound clip "%s"', url);
    makeGetRequest(url, callback);
}

function makeStopVideoRequest (callback) {
    var url = XSERV_BASE_URL + 'kill-video';
    logger.minorInfo('Requesting that the current youtube clip stop playing');
    makeGetRequest(url, callback);
}

// function makeSpotifyRequest (action, volume callback) {
//     var resolved = false;
//     var url = SPOTIFY_URL + '/' + action
//     var urlOptions = nodeUrl.
//     return http.request().query(options)[action]()(function (err, res, body) {
//         resolved = true;
//         return callback(err, res, body);
//     });
// }

function pauseSpotify (callback) {
    // return
}

function restartSpotify (callback) {
    // body...
}

function logResponse (url, res) {
    logger.requestResolution(url, res.statusCode);
}

function logInfo () {
    logger.minorInfo.apply(logger, arguments);
}

function logErr (err) {
    logger.error(err);
}

function notFound (message) {
    return message.send('Not found');
}

module.exports = function (robot) {

    var playingVideo = false;
    var videoQueue = [];
    var videoTimeout;

    var clearVideoTimeout = function () {
        if (videoTimeout) {
            logInfo("Clearing current video timeout that is playing");
            clearTimeout(videoTimeout);
        }
    };

    var waitForVideoToFinish = function (message, videoUrl, videoTimeInHMS) {
        var wait = ((hmsToSecondsOnly(videoTimeInHMS) * 1000) + 4000);
        videoTimeout = setTimeout(function () {
            playingVideo = false;
            logInfo("youtube clip %s finished", videoUrl);
            if (videoQueue.length) {
                logInfo("Proceeding to next clip in queue");
                tubeMePlayVideo(message);
            } else {
                logInfo("End of youtube queue");
            }
        }, wait);
        logInfo("Waiting %s seconds, then will proceed to next item in queue", wait / 1000);
    };

    var tubeMePlayVideo = function (message) {
        if (!videoQueue.length) {
            return message.send("Youtube clip queue empty");
        }
        playingVideo = true;
        var nextUrl = videoQueue.shift();
        logInfo("deQueueing youtube clip %s", nextUrl);
        makePlayVideoRequest(nextUrl, function (err, time) {
            if (err) {
                playingVideo = false;
                return message.send(err);
            }

            waitForVideoToFinish(message, nextUrl, time);

            message.send("Playing youtube clip " + nextUrl);
        });
    };

    robot.respond(/tube me (.+)/i, function (message) {
        if (!message.match[1]) {
            logger.minorInfo('Could not find url match in message');
            return notFound(message);
        }
        var url = message.match[1];
        if (!isValidTubeURL(url)) {
            return message.send("Invalid youtube url");
        }
        videoQueue.push(url);
        if (playingVideo) {
            return message.send('Youtube clip ' + url + ' queued');
        }
        tubeMePlayVideo(message);
    });

    robot.respond(/tube next/i, function (message) {
        makeStopVideoRequest(function (err) {
            if (err) {
                logErr(err);
                return message.send('Error stopping youtube clip');
            }
            playingVideo = false;
            clearVideoTimeout();
            tubeMePlayVideo(message);
        });
    });

    robot.respond(/tube stop/i, function (message) {
        makeStopVideoRequest(function (err) {
            if (err) {
                logErr(err);
                return message.send('Error stopping youtube clip');
            }
            playingVideo = false;
            videoQueue = [];
            message.send("Stopped youtube clip");
        });
    });

};<|endoftext|>


<commit_before>// Description:
//   Turn up!
//
// Dependencies:
//   None
//
// Configuration:
//   None
//
// Commands:
//   .* turn up.*
//   .* turnup.*
//   .* turnip.*
//
// Author:
//   Various Artists

var images = [
    'https://68.media.tumblr.com/4ea21ce02dd015ee9f1057524ec6e5ca/tumblr_o39ceghovA1sgl0ajo1_400.gif',
    'https://media.giphy.com/media/dLPTwfYtmuLF6/giphy.gif',
    'http://i1.kym-cdn.com/photos/images/original/000/708/752/6f5.gif',
    'http://www.lovethispic.com/uploaded_images/143705-Lisa-Simpson-Dancing.gif',
    'http://i.imgur.com/arTwCW7.gif',
    'http://i.imgur.com/m6VRS8u.gif',
    'http://i.imgur.com/MiC6C6l.gif',
    'https://media.giphy.com/media/olAik8MhYOB9K/giphy.gif',
    'https://media.giphy.com/media/BoPUZQRQEPogo/giphy.gif',
    'https://media.giphy.com/media/wqPWKOtW2AD9S/giphy.gif',
    'http://akns-images.eonline.com/eol_images/Entire_Site/2015810/rs_470x314-150910120306-giphy_3.gif',
    'http://public.articles.mtv.com/wp-content/uploads/style/2014/01/bombs-shimmy.gif',
    'http://cdn3-www.musicfeeds.com.au/assets/uploads/5d73c185050fc72385ead151133f2364.gif',
    'https://media.tenor.co/images/541b4abe6eb9f9545139bb2e0767009b/raw',
    'http://o.aolcdn.com/hss/storage/midas/6bc81f4958f714d71db568487588928c/202849138/1.gif',
    'https://media.giphy.com/media/3o6ozw9w2pPU8ndp0k/giphy.gif',
    'https://s3.amazonaws.com/rapgenius/kenan-and-kel-aw-here-it-goes-awh-here-goes-intro-kel-1352766252e.gif',
    'https://ddppchicago.files.wordpress.com/2017/02/overcoming.gif?w=665',
    'http://i.imgur.com/qK0BMiH.gif',
    'https://media.giphy.com/media/i2dE5VvBNxBw4/giphy.gif',
    'http://i.imgur.com/aZvNY8S.gif',
    'http://a.fod4.com/images/GifGuide/dancing/tumblr_lit5wdB6j21qcfba3o1_500.gif',
    'https://33.media.tumblr.com/6800b0da8ced43a3d142441d033b34a8/tumblr_nm568diaWN1rxw730o1_500.gif'
];

function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

function send (msg, howMany) {
    var items = shuffle(images);
    howMany = howMany || 1;
    for (i = 0; i < howMany; i++) {
        //This way there are no duplicates unless you've asked for more than we have
        msg.send(items[i % items.length] + "?_=" + (Math.ceil(Math.random() * 1000)));
    }
}

module.exports = function(robot) {

    robot.hear(/(turn up|turnup|turnip)/i, function (msg) {
        send(msg);
    });

};
<commit_msg>tom haverford<commit_after>// Description:
//   Turn up!
//
// Dependencies:
//   None
//
// Configuration:
//   None
//
// Commands:
//   .* turn up.*
//   .* turnup.*
//   .* turnip.*
//
// Author:
//   Various Artists

var images = [
    'https://68.media.tumblr.com/4ea21ce02dd015ee9f1057524ec6e5ca/tumblr_o39ceghovA1sgl0ajo1_400.gif',
    'https://media.giphy.com/media/dLPTwfYtmuLF6/giphy.gif',
    'http://i1.kym-cdn.com/photos/images/original/000/708/752/6f5.gif',
    'http://www.lovethispic.com/uploaded_images/143705-Lisa-Simpson-Dancing.gif',
    'http://i.imgur.com/arTwCW7.gif',
    'http://i.imgur.com/m6VRS8u.gif',
    'http://i.imgur.com/MiC6C6l.gif',
    'https://media.giphy.com/media/olAik8MhYOB9K/giphy.gif',
    'https://media.giphy.com/media/BoPUZQRQEPogo/giphy.gif',
    'https://media.giphy.com/media/wqPWKOtW2AD9S/giphy.gif',
    'http://akns-images.eonline.com/eol_images/Entire_Site/2015810/rs_470x314-150910120306-giphy_3.gif',
    'http://public.articles.mtv.com/wp-content/uploads/style/2014/01/bombs-shimmy.gif',
    'http://cdn3-www.musicfeeds.com.au/assets/uploads/5d73c185050fc72385ead151133f2364.gif',
    'https://media.tenor.co/images/541b4abe6eb9f9545139bb2e0767009b/raw',
    'http://o.aolcdn.com/hss/storage/midas/6bc81f4958f714d71db568487588928c/202849138/1.gif',
    'https://media.giphy.com/media/3o6ozw9w2pPU8ndp0k/giphy.gif',
    'https://s3.amazonaws.com/rapgenius/kenan-and-kel-aw-here-it-goes-awh-here-goes-intro-kel-1352766252e.gif',
    'https://ddppchicago.files.wordpress.com/2017/02/overcoming.gif?w=665',
    'http://i.imgur.com/qK0BMiH.gif',
    'https://media.giphy.com/media/i2dE5VvBNxBw4/giphy.gif',
    'http://i.imgur.com/aZvNY8S.gif',
    'http://a.fod4.com/images/GifGuide/dancing/tumblr_lit5wdB6j21qcfba3o1_500.gif',
    'https://33.media.tumblr.com/6800b0da8ced43a3d142441d033b34a8/tumblr_nm568diaWN1rxw730o1_500.gif',
    'https://media.giphy.com/media/xUPGcAOBV8MyGs9fBm/giphy.gif',
    'http://i.imgur.com/zLCysMj.gif'
];

function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

function send (msg, howMany) {
    var items = shuffle(images);
    howMany = howMany || 1;
    for (i = 0; i < howMany; i++) {
        //This way there are no duplicates unless you've asked for more than we have
        msg.send(items[i % items.length] + "?_=" + (Math.ceil(Math.random() * 1000)));
    }
}

module.exports = function(robot) {

    robot.hear(/(turn up|turnup|turnip)/i, function (msg) {
        send(msg);
    });

};
<|endoftext|>


<commit_before>/* eslint no-console: 0 */

import utils from "./utils";
import nodefn from "when/node";
import semver from "semver";

const CHANGELOG_PATH = "./CHANGELOG.md";
const sequenceSteps = [
	gitFetchUpstreamMaster,
	gitCheckoutMaster,
	gitMergeUpstreamMaster,
	gitMergeUpstreamDevelop,
	updateVersion,
	gitLog,
	updateLog,
	updateChangelog,
	gitDiff,
	gitAdd,
	gitCommit,
	gitTag,
	gitPushUpstreamMaster,
	npmPublish,
	gitCheckoutDevelop,
	gitMergeMaster,
	gitPushUpstreamDevelop,
	gitPushOriginMaster
];

export function gitFetchUpstreamMaster( [ git, options ] ) {
	const command = "git fetch upstream --tags";
	utils.log.begin( command );
	return utils.exec( command ).then( () => utils.log.end() );
}

export function gitCheckoutMaster( [ git, options ] ) {
	const command = "git checkout master";
	utils.log.begin( command );
	return nodefn.lift( ::git.checkout )( "master" )
		.then( () => utils.log.end() );
}

export function gitMergeUpstreamMaster( [ git, options ] ) {
	const command = "git merge --ff-only upstream/master";
	utils.log.begin( command );
	return nodefn.lift( ::git.merge )( [ "--ff-only", "upstream/master" ] )
		.then( () => utils.log.end() );
}

export function gitMergeUpstreamDevelop( [ git, options ] ) {
	const command = "git merge upstream/develop";
	if ( options.develop ) {
		utils.log.begin( command );
		return nodefn.lift( ::git.merge )( [ "upstream/develop" ] )
			.then( () => utils.log.end() );
	}
	return null;
}

export function updateVersion( [ git, options ] ) {
	const packageJson = utils.readJSONFile( "./package.json" );
	const oldVersion = packageJson.version;
	const newVersion = packageJson.version = semver.inc( oldVersion, options.release );
	utils.writeJSONFile( "./package.json", packageJson );
	options.versions = { oldVersion, newVersion };
	console.log( `Updated package.json from ${ oldVersion } to ${ newVersion }` );
}

export function gitLog( [ git, options ] ) {
	let contents = utils.readFile( CHANGELOG_PATH );

	if ( ~contents.indexOf( "### Next" ) ) {
		contents = contents.replace( /### Next([^#]+)/, ( match, submatch ) => {
			options.log = submatch.trim();
			return "";
		} );
		utils.writeFile( CHANGELOG_PATH, contents );
	} else {
		return utils.exec( "git tag --sort=v:refname" ).then( tags => {
			tags = tags.trim().split( "\n" );
			const latestRelease = tags[ tags.length - 1 ];
			const command = `git --no-pager log --no-merges --date-order --pretty=format:'%s' ${ latestRelease }..`;
			utils.log.begin( command );
			return utils.exec( command ).then( data => {
				data = data.trim().replace( /^(.+)$/gm, "* $1" );
				options.log = data;
				utils.log.end();
			} );
		} );
	}
}

export function updateLog( [ git, options ] ) {
	const command = "log preview";
	console.log( `Here is a preview of your log: \n${ options.log }` );
	return utils.prompt( [ {
		type: "confirm",
		name: "log",
		message: "Would you like to edit your log",
		default: true
	} ] ).then( answers => {
		utils.log.begin( command );
		if ( answers.log ) {
			return utils.editor( options.log )
				.then( data => {
					options.log = data.trim();
					utils.log.end();
				} );
		}
	} );
}

export function updateChangelog( [ git, options ] ) {
	const version = `### ${ options.versions.newVersion }`;
	const update = `${ version }\n\n${ options.log }`;
	const command = "update changelog";
	utils.log.begin( command );
	let contents = utils.readFile( CHANGELOG_PATH );
	if ( options.release === "major" ) {
		const wildcardVersion = options.versions.newVersion.replace( ".0.0", ".x" );
		contents = `## ${ wildcardVersion }\n\n${ update }\n\n${ contents }`;
	} else {
		contents = contents.replace( /(## .*\n)/, `$1\n${ update }\n` );
	}
	utils.writeFile( CHANGELOG_PATH, contents );
	utils.log.end();
}

export function gitDiff( [ git, options ] ) {
	const command = "git diff --color CHANGELOG.md package.json";
	return utils.exec( command )
		.then( data => {
			console.log( data );
			return utils.prompt( [ {
				type: "confirm",
				name: "proceed",
				message: "Are you okay with this diff",
				default: true
			} ] ).then( answers => {
				utils.log.begin( command );
				utils.log.end();
				if ( !answers.proceed ) {
					process.exit( 0 ); // eslint-disable-line no-process-exit
				}
			} );
		} );
}

export function gitAdd( [ git, options ] ) {
	const command = "git add CHANGELOG.md package.json";
	utils.log.begin( command );
	return nodefn.lift( ::git.add )( [ "CHANGELOG.md", "package.json" ] )
		.then( () => utils.log.end() );
}

export function gitCommit( [ git, options ] ) {
	const command = `git commit -m "${ options.versions.newVersion }"`;
	utils.log.begin( command );
	return nodefn.lift( ::git.commit )( options.versions.newVersion )
		.then( () => utils.log.end() );
}

export function gitTag( [ git, options ] ) {
	const command = `git tag -a v${ options.versions.newVersion } -m "..."`;
	utils.log.begin( command );
	return nodefn.lift( ::git.addAnnotatedTag )( `v${ options.versions.newVersion }`, options.log )
		.then( () => utils.log.end() );
}

export function gitPushUpstreamMaster( [ git, options ] ) {
	const command = "git push upstream master --tags";
	utils.log.begin( command );
	return utils.exec( command )
		.then( data => utils.log.end() );
}

export function npmPublish( [ git, options ] ) {
	const command = `npm publish`;
	// look at `private` and `publishConfig.registry` package.json properties...
	return utils.prompt( [ {
		type: "confirm",
		name: "publish",
		message: "Do you want to publish this package",
		default: true
	} ] ).then( answers => {
		utils.log.begin( command );
		if ( answers.publish ) {
			return utils.exec( command ).then( data => utils.log.end() );
		}
		utils.log.end();
	} );
}

export function gitCheckoutDevelop( [ git, options ] ) {
	const command = `git checkout develop`;
	if ( options.develop ) {
		utils.log.begin( command );
		return nodefn.lift( ::git.checkout )( "develop" )
			.then( () => utils.log.end() );
	}
	return null;
}

export function gitMergeMaster( [ git, options ] ) {
	const command = `git merge --ff-only master`;
	if ( options.develop ) {
		utils.log.begin( command );
		return nodefn.lift( ::git.merge )( [ "--ff-only", "master" ] )
			.then( () => utils.log.end() );
	}
	return null;
}

export function gitPushUpstreamDevelop( [ git, options ] ) {
	const command = `git push upstream develop`;
	if ( options.develop ) {
		utils.log.begin( command );
		return nodefn.lift( ::git.push )( "upstream", "develop" )
			.then( () => utils.log.end() );
	}
	return null;
}

export function gitPushOriginMaster( [ git, options ] ) {
	const command = `git push origin master`;
	utils.log.begin( command );
	return nodefn.lift( ::git.push )( "origin", "master" )
		.then( () => utils.log.end() );
}

export default sequenceSteps;
<commit_msg>Check for tags before adding a range<commit_after>/* eslint no-console: 0 */

import utils from "./utils";
import nodefn from "when/node";
import semver from "semver";

const CHANGELOG_PATH = "./CHANGELOG.md";
const sequenceSteps = [
	gitFetchUpstreamMaster,
	gitCheckoutMaster,
	gitMergeUpstreamMaster,
	gitMergeUpstreamDevelop,
	updateVersion,
	gitLog,
	updateLog,
	updateChangelog,
	gitDiff,
	gitAdd,
	gitCommit,
	gitTag,
	gitPushUpstreamMaster,
	npmPublish,
	gitCheckoutDevelop,
	gitMergeMaster,
	gitPushUpstreamDevelop,
	gitPushOriginMaster
];

export function gitFetchUpstreamMaster( [ git, options ] ) {
	const command = "git fetch upstream --tags";
	utils.log.begin( command );
	return utils.exec( command ).then( () => utils.log.end() );
}

export function gitCheckoutMaster( [ git, options ] ) {
	const command = "git checkout master";
	utils.log.begin( command );
	return nodefn.lift( ::git.checkout )( "master" )
		.then( () => utils.log.end() );
}

export function gitMergeUpstreamMaster( [ git, options ] ) {
	const command = "git merge --ff-only upstream/master";
	utils.log.begin( command );
	return nodefn.lift( ::git.merge )( [ "--ff-only", "upstream/master" ] )
		.then( () => utils.log.end() );
}

export function gitMergeUpstreamDevelop( [ git, options ] ) {
	const command = "git merge upstream/develop";
	if ( options.develop ) {
		utils.log.begin( command );
		return nodefn.lift( ::git.merge )( [ "upstream/develop" ] )
			.then( () => utils.log.end() );
	}
	return null;
}

export function updateVersion( [ git, options ] ) {
	const packageJson = utils.readJSONFile( "./package.json" );
	const oldVersion = packageJson.version;
	const newVersion = packageJson.version = semver.inc( oldVersion, options.release );
	utils.writeJSONFile( "./package.json", packageJson );
	options.versions = { oldVersion, newVersion };
	console.log( `Updated package.json from ${ oldVersion } to ${ newVersion }` );
}

export function gitLog( [ git, options ] ) {
	let contents = utils.readFile( CHANGELOG_PATH );

	if ( ~contents.indexOf( "### Next" ) ) {
		contents = contents.replace( /### Next([^#]+)/, ( match, submatch ) => {
			options.log = submatch.trim();
			return "";
		} );
		utils.writeFile( CHANGELOG_PATH, contents );
	} else {
		return utils.exec( "git tag --sort=v:refname" ).then( tags => {
			let command = `git --no-pager log --no-merges --date-order --pretty=format:'%s'`;
			tags = tags.trim();
			if ( tags.length ) {
				tags = tags.split( "\n" );
				const latestRelease = tags[ tags.length - 1 ];
				command = `${ command } ${ latestRelease }..`;
			}
			utils.log.begin( command );
			return utils.exec( command ).then( data => {
				data = data.trim().replace( /^(.+)$/gm, "* $1" );
				options.log = data;
				utils.log.end();
			} );
		} );
	}
}

export function updateLog( [ git, options ] ) {
	const command = "log preview";
	console.log( `Here is a preview of your log: \n${ options.log }` );
	return utils.prompt( [ {
		type: "confirm",
		name: "log",
		message: "Would you like to edit your log",
		default: true
	} ] ).then( answers => {
		utils.log.begin( command );
		if ( answers.log ) {
			return utils.editor( options.log )
				.then( data => {
					options.log = data.trim();
					utils.log.end();
				} );
		}
	} );
}

export function updateChangelog( [ git, options ] ) {
	const version = `### ${ options.versions.newVersion }`;
	const update = `${ version }\n\n${ options.log }`;
	const command = "update changelog";
	utils.log.begin( command );
	let contents = utils.readFile( CHANGELOG_PATH );
	if ( options.release === "major" ) {
		const wildcardVersion = options.versions.newVersion.replace( ".0.0", ".x" );
		contents = `## ${ wildcardVersion }\n\n${ update }\n\n${ contents }`;
	} else {
		contents = contents.replace( /(## .*\n)/, `$1\n${ update }\n` );
	}
	utils.writeFile( CHANGELOG_PATH, contents );
	console.log( CHANGELOG_PATH, contents );
	utils.log.end();
}

export function gitDiff( [ git, options ] ) {
	const command = "git diff --color CHANGELOG.md package.json";
	return utils.exec( command )
		.then( data => {
			console.log( data );
			return utils.prompt( [ {
				type: "confirm",
				name: "proceed",
				message: "Are you okay with this diff",
				default: true
			} ] ).then( answers => {
				utils.log.begin( command );
				utils.log.end();
				if ( !answers.proceed ) {
					process.exit( 0 ); // eslint-disable-line no-process-exit
				}
			} );
		} );
}

export function gitAdd( [ git, options ] ) {
	const command = "git add CHANGELOG.md package.json";
	utils.log.begin( command );
	return nodefn.lift( ::git.add )( [ "CHANGELOG.md", "package.json" ] )
		.then( () => utils.log.end() );
}

export function gitCommit( [ git, options ] ) {
	const command = `git commit -m "${ options.versions.newVersion }"`;
	utils.log.begin( command );
	return nodefn.lift( ::git.commit )( options.versions.newVersion )
		.then( () => utils.log.end() );
}

export function gitTag( [ git, options ] ) {
	const command = `git tag -a v${ options.versions.newVersion } -m "..."`;
	utils.log.begin( command );
	return nodefn.lift( ::git.addAnnotatedTag )( `v${ options.versions.newVersion }`, options.log )
		.then( () => utils.log.end() );
}

export function gitPushUpstreamMaster( [ git, options ] ) {
	const command = "git push upstream master --tags";
	utils.log.begin( command );
	return utils.exec( command )
		.then( data => utils.log.end() );
}

export function npmPublish( [ git, options ] ) {
	const command = `npm publish`;
	// look at `private` and `publishConfig.registry` package.json properties...
	return utils.prompt( [ {
		type: "confirm",
		name: "publish",
		message: "Do you want to publish this package",
		default: true
	} ] ).then( answers => {
		utils.log.begin( command );
		if ( answers.publish ) {
			return utils.exec( command ).then( data => utils.log.end() );
		}
		utils.log.end();
	} );
}

export function gitCheckoutDevelop( [ git, options ] ) {
	const command = `git checkout develop`;
	if ( options.develop ) {
		utils.log.begin( command );
		return nodefn.lift( ::git.checkout )( "develop" )
			.then( () => utils.log.end() );
	}
	return null;
}

export function gitMergeMaster( [ git, options ] ) {
	const command = `git merge --ff-only master`;
	if ( options.develop ) {
		utils.log.begin( command );
		return nodefn.lift( ::git.merge )( [ "--ff-only", "master" ] )
			.then( () => utils.log.end() );
	}
	return null;
}

export function gitPushUpstreamDevelop( [ git, options ] ) {
	const command = `git push upstream develop`;
	if ( options.develop ) {
		utils.log.begin( command );
		return nodefn.lift( ::git.push )( "upstream", "develop" )
			.then( () => utils.log.end() );
	}
	return null;
}

export function gitPushOriginMaster( [ git, options ] ) {
	const command = `git push origin master`;
	utils.log.begin( command );
	return nodefn.lift( ::git.push )( "origin", "master" )
		.then( () => utils.log.end() );
}

export default sequenceSteps;
<|endoftext|>


<commit_before>const errors = require('../../data-models/errors.json');
const _ = require('lodash');

module.exports = failure => {
  if(errors[failure.type]) {
    const error = errors[failure.type];
    _.map(failure.properties, (v, k) => {
      error.message = error.message.replace(`%${k}`, v);
    });
    return error;
  }
  return errors.internalServerError;
};
<commit_msg>Fixed: wrong properties returning in error service<commit_after>const errors = require('../../data-models/errors.json');
const _ = require('lodash');

module.exports = failure => {
  if(errors[failure.type]) {
    const error = _.clone(errors[failure.type]);
    _.map(failure.properties, (v, k) => {
      error.message = _.replace(error.message, `%${k}`, v);
    });
    return error;
  }
  return errors.internalServerError;
};
<|endoftext|>


<commit_before>const Promise = require('bluebird')
const MongoClient = require('mongodb').MongoClient;
const t = require('tcomb-validation');
const inputs = require('../models/inputs.js');

function connect(url, callback) {
    MongoClient.connect(url, function (err, db) {
        if (err) {
            console.log(err)
        }
        console.log('db is conected');
        callback(db)
    })
}

function insert(db, collection, stuff, done) {
    if (Array.isArray(stuff)) {
        db.collection(collection).insertMany(stuff, function (err, r) {
            if (err) {
                done({ status: 500, message: err })
            }

            done({ status: 200, message: r })
        });
    } else {
        db.collection(collection).insertOne(stuff, function (err, r) {
            if (err) {
                done({ status: 500, message: err })
            }

            done({ status: 200, message: r })
        });
    }
}

function updatePassport(db, collection, select, stuff, done) {

    const entry = {
        date: Math.round((new Date()).getTime() / 1000),
        facilityName: stuff.facilityName,
        locationName: stuff.supplier,
        geoloc: stuff.location,
        postCode: 'placeholder',
        physicalQuality: stuff.physicalQuality,
        chemicalContaminents: stuff.chemicalContaminents,
        microbialSafety: stuff.microbialSafety,
        temperatureControl: stuff.temperatureControl
    }

    console.log({ "itemID": select })
        db.collection(collection).updateOne({ "itemID": select }, { $push: { stamps: entry } }, (err, doc) => {
            if (err) {
                done({ status: 500, message: err })
            }
            done({ status: 200, message: doc })
        })
}

function getPassport(db, collection, select, done) {
    console.log({ "itemId": select })
    db.collection(collection).findOne({ "itemId": select }, (err, doc) => {
        if (err) {
            done({ status: 500, message: err })
        }
        done({ status: 200, message: doc })
    })
}

function createPassport(db, collection, stuff, done) {
    db.collection(collection).insertOne(stuff, (err, doc) => {
        if (err) {
            done({ status: 500, message: err })
        }
        done({ status: 200, message: doc })
    })
}

module.exports = {
    insert: insert,
    connect: connect,
    getPassport: getPassport,
    updatePassport: updatePassport,
    createPassport: createPassport
}<commit_msg>promise/all/ might work<commit_after>const Promise = require('bluebird')
const MongoClient = require('mongodb').MongoClient;
const t = require('tcomb-validation');
const inputs = require('../models/inputs.js');

function connect(url, callback) {
    MongoClient.connect(url, function (err, db) {
        if (err) {
            console.log(err)
        }
        console.log('db is conected');
        callback(db)
    })
}

function insert(db, collection, stuff, done) {
    if (Array.isArray(stuff)) {
        db.collection(collection).insertMany(stuff, function (err, r) {
            if (err) {
                done({ status: 500, message: err })
            }

            done({ status: 200, message: r })
        });
    } else {
        db.collection(collection).insertOne(stuff, function (err, r) {
            if (err) {
                done({ status: 500, message: err })
            }

            done({ status: 200, message: r })
        });
    }
}

function updatePassport(db, collection, select, stuff, done) {

    const entry = {
        date: Math.round((new Date()).getTime() / 1000),
        facilityName: stuff.facilityName,
        locationName: stuff.supplier,
        geoloc: stuff.location,
        postCode: 'placeholder',
        physicalQuality: stuff.physicalQuality,
        chemicalContaminents: stuff.chemicalContaminents,
        microbialSafety: stuff.microbialSafety,
        temperatureControl: stuff.temperatureControl
    }

    console.log({ "itemID": select })
        db.collection(collection).updateOne({ "itemId": select }, { $push: { stamps: entry } }, (err, doc) => {
            if (err) {
                done({ status: 500, message: err })
            }
            done({ status: 200, message: doc })
        })
}

function getPassport(db, collection, select, done) {
    console.log({ "itemId": select })
    db.collection(collection).findOne({ "itemId": select }, (err, doc) => {
        if (err) {
            done({ status: 500, message: err })
        }
        done({ status: 200, message: doc })
    })
}

function createPassport(db, collection, stuff, done) {
    db.collection(collection).insertOne(stuff, (err, doc) => {
        if (err) {
            done({ status: 500, message: err })
        }
        done({ status: 200, message: doc })
    })
}

module.exports = {
    insert: insert,
    connect: connect,
    getPassport: getPassport,
    updatePassport: updatePassport,
    createPassport: createPassport
}<|endoftext|>


<commit_before>import './polyfills'

class SimpleGallery {
	constructor(form, name = 'gallery', container = '.gallery-container') {
		this.form = form
		this.input = document.querySelector(`${this.form} input[name="${name}"]`)

		this.initDOM(container)
		this.initGallery()
		this.initSortable()
		this.eventListeners()
	}

	initDOM(container) {
		document.querySelector(`${this.form} ${container}`).innerHTML += `

`
	}

	initGallery() {
		if (!this.input.value) return

		const gallery = JSON.parse(this.input.value)

		if (gallery.lenght == 0) return

		let html = ''

		gallery.map(image => html += this.generateDOM(image))
		document.querySelector('.gallery-items').innerHTML = html
	}

	initSortable() {
		const container = document.querySelector(`${this.form} .gallery-items`)
		Sortable.create(container, {
			animation: 150,
			onUpdate: (e) => {
				const gallery = JSON.parse(this.input.value)
				const oldIndex = e.oldIndex
				const newIndex = e.newIndex

				gallery.swap(oldIndex, newIndex)

				this.input.value = JSON.stringify(gallery)
			}
		})
	}

	eventListeners() {
		document.querySelector(`${this.form} input.upload`).addEventListener('change', this.addItem.bind(this))
		document.querySelector('.gallery').delegate('click', '.remove', this.removeItem.bind(this))
		document.querySelector('.gallery').delegate('change', '.item', this.changeTitle.bind(this))
	}

	addItem(e) {
		e.preventDefault()
		const files = e.target.files
		const data = new FormData()

		for (let i in files) {
			if (files.hasOwnProperty(i)) {
				data.append('gallery[]', files[i])
			}
		}

		this.makeAJAX(data)
	}

	makeAJAX(data) {
		const self = this
		const xhttp = new XMLHttpRequest()
		const form = document.querySelector(this.form)

		document.querySelector('.gallery').classList.add('loading-active')

		xhttp.onreadystatechange = function() {
			if (xhttp.readyState == 4) {
				document.querySelector('.gallery').classList.remove('loading-active')
				if (401) {
					const data = JSON.stringify([
						{'url': 'https://unsplash.it/150/?image=10'},
						{'url': 'https://unsplash.it/150/?image=20'},
						{'url': 'https://unsplash.it/150/?image=30'}
					])
					console.info('Example data loaded!')
					self.addImages(data)

				}
				if (xhttp.status == 200) {
					self.addImages(xhttp.responseText)
				}
			}
		}

		xhttp.upload.addEventListener('progress', function(e) {
			const loading = document.querySelector(`${self.form} .loading .bar`)
			loading.style.width = Math.ceil((e.loaded/e.total) * 100) + '%'
    }, false)

		xhttp.open('POST', form.action, true)
		xhttp.send(data)
	}

	addImages(data) {
		const images = JSON.parse(data)
		let gallery = (this.input.value != '') ? JSON.parse(this.input.value) : []

		images.map(image => {
			image.title = 'No description'
			gallery.push(image)
		})

		this.saveGallery(gallery)
	}

	removeItem(e) {
		e.preventDefault()
		const gallery = JSON.parse(this.input.value)
		const item = e.target.parentElement
		const url = item.children[0].src

		gallery.forEach((item, i) => {
      if (item.url != url) return
      gallery.splice(i, 1)
    })

		this.saveGallery(gallery)
	}

	saveGallery(gallery) {
		let html = ''
		gallery.map(image => html += this.generateDOM(image))
		this.input.value = JSON.stringify(gallery)
		document.querySelector('.gallery-items').innerHTML = html
	}

	changeTitle(e) {
		const gallery = JSON.parse(this.input.value)
		const item = e.target.parentElement
		const url = item.children[0].src

		gallery.forEach((item, i) => {
      if (item.url != url) return
      gallery[i]['title'] = e.target.value
    })

		this.input.value = JSON.stringify(gallery)
	}

	generateDOM(image) {
		return `

				<input class="title" name="title" value="${image.title}" />
				<button class='remove'>×</button>

		`
	}
}

module.exports = SimpleGallery
<commit_msg>Data example removed<commit_after>import './polyfills'

class SimpleGallery {
	constructor(form, name = 'gallery', container = '.gallery-container') {
		this.form = form
		this.input = document.querySelector(`${this.form} input[name="${name}"]`)

		this.initDOM(container)
		this.initGallery()
		this.initSortable()
		this.eventListeners()
	}

	initDOM(container) {
		document.querySelector(`${this.form} ${container}`).innerHTML += `

`
	}

	initGallery() {
		if (!this.input.value) return

		const gallery = JSON.parse(this.input.value)

		if (gallery.lenght == 0) return

		let html = ''

		gallery.map(image => html += this.generateDOM(image))
		document.querySelector('.gallery-items').innerHTML = html
	}

	initSortable() {
		const container = document.querySelector(`${this.form} .gallery-items`)
		Sortable.create(container, {
			animation: 150,
			onUpdate: (e) => {
				const gallery = JSON.parse(this.input.value)
				const oldIndex = e.oldIndex
				const newIndex = e.newIndex

				gallery.swap(oldIndex, newIndex)

				this.input.value = JSON.stringify(gallery)
			}
		})
	}

	eventListeners() {
		document.querySelector(`${this.form} input.upload`).addEventListener('change', this.addItem.bind(this))
		document.querySelector('.gallery').delegate('click', '.remove', this.removeItem.bind(this))
		document.querySelector('.gallery').delegate('change', '.item', this.changeTitle.bind(this))
	}

	addItem(e) {
		e.preventDefault()
		const files = e.target.files
		const data = new FormData()

		for (let i in files) {
			if (files.hasOwnProperty(i)) {
				data.append('gallery[]', files[i])
			}
		}

		this.makeAJAX(data)
	}

	makeAJAX(data) {
		const self = this
		const xhttp = new XMLHttpRequest()
		const form = document.querySelector(this.form)

		document.querySelector('.gallery').classList.add('loading-active')

		xhttp.onreadystatechange = function() {
			if (xhttp.readyState == 4) {
				document.querySelector('.gallery').classList.remove('loading-active')
				if (xhttp.status == 200) {
					self.addImages(xhttp.responseText)
				}
			}
		}

		xhttp.upload.addEventListener('progress', function(e) {
			const loading = document.querySelector(`${self.form} .loading .bar`)
			loading.style.width = Math.ceil((e.loaded/e.total) * 100) + '%'
    }, false)

		xhttp.open('POST', form.action, true)
		xhttp.send(data)
	}

	addImages(data) {
		const images = JSON.parse(data)
		let gallery = (this.input.value != '') ? JSON.parse(this.input.value) : []

		images.map(image => {
			image.title = 'No description'
			gallery.push(image)
		})

		this.saveGallery(gallery)
	}

	removeItem(e) {
		e.preventDefault()
		const gallery = JSON.parse(this.input.value)
		const item = e.target.parentElement
		const url = item.children[0].src

		gallery.forEach((item, i) => {
      if (item.url != url) return
      gallery.splice(i, 1)
    })

		this.saveGallery(gallery)
	}

	saveGallery(gallery) {
		let html = ''
		gallery.map(image => html += this.generateDOM(image))
		this.input.value = JSON.stringify(gallery)
		document.querySelector('.gallery-items').innerHTML = html
	}

	changeTitle(e) {
		const gallery = JSON.parse(this.input.value)
		const item = e.target.parentElement
		const url = item.children[0].src

		gallery.forEach((item, i) => {
      if (item.url != url) return
      gallery[i]['title'] = e.target.value
    })

		this.input.value = JSON.stringify(gallery)
	}

	generateDOM(image) {
		return `

				<input class="title" name="title" value="${image.title}" />
				<button class='remove'>×</button>

		`
	}
}

module.exports = SimpleGallery
<|endoftext|>