<commit_before>import * as I          from 'immutable';
import * as fw         from './freeWords';
import * as generators from '../common/generators';

import { Partition } from '../common/unionFind';

const identify = (table, part, a, b) => {
  part = part.clone();
  table = table.asMutable();

  const queue = [[a, b]];

  while (queue.length) {
    const [a, b] = queue.shift().map(x => part.find(x));

    if (a != b) {
      part.union(a, b);

      for (const [g, bg] of table.get(b)) {
        const ag = table.getIn([a, g]);
        if (ag == null)
          table.setIn([a, g], bg);
        else if (part.find(ag) != part.find(bg))
          queue.push([ag, bg]);
      }
      table.set(b, table.get(a));
    }
  }

  return { table: table.asImmutable(), part };
};

const scan = (table, w, start, limit) => {
  let row = start;
  let i = 0;

  while (i < limit) {
    const next = table.getIn([row, w.get(i)]);
    if (next == null)
      break;
    else {
      ++i;
      row = next;
    }
  }

  return { row, index: i };
};

const scanAndIdentify = (table, part, w, start) => {
  const n = w.size;
  const { row: head, index: i } = scan(table, w, start, n);
  const { row: tail, index: j } = scan(table, fw.inverse(w), start, n - i);

  if (i + j == n - 1) {
    table = table.setIn([head, w.get(i)], tail).setIn([tail, -w.get(i)], head);
    return { table, part, next: head };
  }
  else if (i + j == n && head != tail)
    return identify(table, part, head, tail);
  else
    return { table, part };
};

const compressed = (table, part) => {
  const toIdx = {};
  let i = 0;
  for (const k of table.keySeq()) {
    if (part.find(k) == k) {
      toIdx[k] = i;
      ++i;
    }
  }

  const canon = a => toIdx[part.find(a)];

  return table.toMap()
    .filter((r, k) => toIdx[k] != null)
    .mapKeys(canon)
    .map(row => row.map(canon));
};

const _expandGenerators = nrGens =>
  I.Range(1, nrGens+1).concat(I.Range(-1, -(nrGens+1)));

const _expandRelators = relators =>
  I.Set(I.List(relators).flatMap(fw.relatorPermutations));

export const cosetTable = (nrGens, relators, subgroupGens) => {
  const gens = _expandGenerators(nrGens);
  const rels = _expandRelators(relators);

  let table = I.List([I.Map()]);
  let part = new Partition();
  let i = 0, j = 0;

  while (i < table.size) {
    if (table.size > 10000)
      throw new Error('maximum coset table size reached');

    if (j >= gens.size || i != part.find(i))
      [i, j] = [i + 1, 0];
    else {
      if (table.getIn([i, gens.get(j)]) == null) {
        const g = gens.get(j);
        const n = table.size;

        let t = { table: table.setIn([i, g], n).setIn([n, -g], i), part };
        for (const w of rels)
          t = scanAndIdentify(t.table, t.part, w, n);
        for (const w of subgroupGens)
          t = scanAndIdentify(t.table, t.part, fw.word(w), part.find(0));

        table = t.table;
        part = t.part;
      }
      ++j;
    }
  }

  return compressed(table, part);
};

export const cosetRepresentatives = table => {
  const queue = [0];
  const reps = [fw.empty];

  while (queue.length) {
    const i = queue.shift();
    const w = reps[i];

    for (const [g, k] of table.get(i).filter(g => reps[g] == null)) {
      reps[k] = fw.product([w, [g]]);
      queue.push(k);
    }
  }

  return reps;
};

const _firstFreeInTable = (table, gens) => {
  for (let k = 0; k < table.size; ++k) {
    for (const g of gens) {
      if (table.getIn([k, g]) == null)
        return [k, g];
    }
  }
};

const _scanRecursively = (rels, table, index) => {
  const p = () => new Partition();
  const q = [index];

  while (q.length) {
    const row = q.shift();

    for (const rel of rels) {
      const { table: t, part, next } = scanAndIdentify(table, p(), rel, row);

      if (part.isTrivial()) {
        table = t;
        if (next != null)
          q.push(next);
      }
      else
        return;
    }
  }

  return table;
};

const _potentialChildren = (table, gens, rels, maxCosets) => {
  const [k, g] = _firstFreeInTable(table, gens) || [];

  if (k == null)
    return I.List();
  else {
    const ginv = -g;
    const n = table.size;
    const matches = I.Range(k, n).filter(k => table.getIn([k, ginv]) == null);
    const candidates = n < maxCosets ? I.List(matches).push(n) : matches;

    return candidates
      .map(pos => {
        const t = table.setIn([k, g], pos).setIn([pos, ginv], k);
        return _scanRecursively(rels, t, k);
      })
      .filter(t => t != null);
  }
};

const _compareRenumberedFom = (table, gens, start) => {
  let o2n = I.Map([[start, 0]]);
  let n2o = I.Map([[0, start]]);
  let row = 0;
  let col = 0;

  while (true) {
    if (row >= o2n.size && row < table.size)
      throw new Error("coset table is not transitive");

    if (row >= table.size)
      return 0;
    else if (col >= gens.size) {
      ++row;
      col = 0;
    } else {
      const oval = table.getIn([row, gens.get(col)]);
      let nval = table.getIn([n2o.get(row), gens.get(col)]);
      if (nval != null && o2n.get(nval) == null) {
        n2o = n2o.set(o2n.size, nval);
        o2n = o2n.set(nval, o2n.size);
      }
      nval = o2n.get(nval);

      if (oval == nval)
        ++col;
      else if (oval == null)
        return -1;
      else if (nval == null)
        return 1;
      else
        return nval - oval;
    }
  }
};

const _isCanonical = (table, gens) => I.Range(1, table.size)
  .every(start => _compareRenumberedFom(table, gens, start) >= 0);

export const tables = (nrGens, relators, maxCosets) => {
  const gens = _expandGenerators(nrGens);
  const rels = _expandRelators(relators);
  const isFull = t => _firstFreeInTable(t, gens) == null;

  return generators.backtracker({
    root: I.List([I.Map()]),
    extract(table) { return isFull(table) ? table : null },
    children(table) {
      return _potentialChildren(table, gens, rels, maxCosets)
        .filter(t => !t.isEmpty() && _isCanonical(t, gens))
        .toArray();
    }
  });
};

const _inducedTable = (gens, img, img0) => {
  const table = I.List([I.Map()]).asMutable();
  const o2n = I.Map([[img0, 0]]).asMutable();
  const n2o = I.Map([[0, img0]]).asMutable();
  let i = 0;

  while (i < table.size) {
    gens.forEach(g => {
      const k = img(n2o.get(i), g);
      const n = o2n.has(k) ? o2n.get(k) : table.size;
      o2n.set(k, n);
      n2o.set(n, k);
      table.setIn([i, g], n).setIn([n, -g], i);
    });
    ++i;
  }

  return table.asImmutable();
};

export const intersectionTable = (tableA, tableB) => {
  return _inducedTable(
    (tableA.first() || I.Map()).keySeq(),
    (es, g) => I.List([tableA.getIn([es.get(0), g]),
                       tableB.getIn([es.get(1), g])]),
    I.List([0, 0])
  );
};

export const coreTable = base =>
  _inducedTable(
    (base.first() || I.Map()).keySeq(),
    (es, g) => es.map(e => base.getIn([e, g])),
    base.keySeq()
  );

const _sgn = x => (x > 0) - (x < 0);
const _sum = a => a.reduce((x, y) => x + y, 0);

export const relatorAsVector = (rel, nrgens) => {
  const counts = rel.groupBy(Math.abs).map(a => _sum(a.map(_sgn)));
  return I.List(I.Range(1, nrgens+1).map(i => counts.get(i) || 0));
};

export const relatorMatrix = (nrgens, relators) =>
  I.List(relators).map(rel => relatorAsVector(rel, nrgens));

if (require.main == module) {
  const test = table => {
    const reps = cosetRepresentatives(table);
    console.log(I.fromJS(reps), Object.keys(reps).length);
  };

  const base = cosetTable(
    3,
    [[1,1], [2,2], [3,3], [1,2,1,2,1,2], [1,3,1,3], fw.raisedTo(3, [2,3])],
    [[1,2]]);

  test(base);
  test(coreTable(base));

  console.log(_expandGenerators(4));
  console.log(_expandRelators([[1,2,-3]]));

  for (const x of generators.results(tables(2, [[1,1],[2,2],[1,2,1,2]], 8)))
    console.log(JSON.stringify(x));
}
<commit_msg>revise yet another function<commit_after>import * as I          from 'immutable';
import * as fw         from './freeWords';
import * as generators from '../common/generators';

import { Partition } from '../common/unionFind';

const identify = (table, part, a, b) => {
  part = part.clone();
  table = table.asMutable();

  const queue = [[a, b]];

  while (queue.length) {
    const [a, b] = queue.shift().map(x => part.find(x));

    if (a != b) {
      part.union(a, b);

      for (const [g, bg] of table.get(b)) {
        const ag = table.getIn([a, g]);
        if (ag == null)
          table.setIn([a, g], bg);
        else if (part.find(ag) != part.find(bg))
          queue.push([ag, bg]);
      }
      table.set(b, table.get(a));
    }
  }

  return { table: table.asImmutable(), part };
};

const scan = (table, w, start, limit) => {
  let row = start;
  let i = 0;

  while (i < limit) {
    const next = table.getIn([row, w.get(i)]);
    if (next == null)
      break;
    else {
      ++i;
      row = next;
    }
  }

  return { row, index: i };
};

const scanAndIdentify = (table, part, w, start) => {
  const n = w.size;
  const { row: head, index: i } = scan(table, w, start, n);
  const { row: tail, index: j } = scan(table, fw.inverse(w), start, n - i);

  if (i + j == n - 1) {
    table = table.setIn([head, w.get(i)], tail).setIn([tail, -w.get(i)], head);
    return { table, part, next: head };
  }
  else if (i + j == n && head != tail)
    return identify(table, part, head, tail);
  else
    return { table, part };
};

const compressed = (table, part) => {
  const toIdx = {};
  let i = 0;
  for (const k of table.keySeq()) {
    if (part.find(k) == k) {
      toIdx[k] = i;
      ++i;
    }
  }

  const canon = a => toIdx[part.find(a)];

  return table.toMap()
    .filter((r, k) => toIdx[k] != null)
    .mapKeys(canon)
    .map(row => row.map(canon));
};

const _expandGenerators = nrGens =>
  I.Range(1, nrGens+1).concat(I.Range(-1, -(nrGens+1)));

const _expandRelators = relators =>
  I.Set(I.List(relators).flatMap(fw.relatorPermutations));

export const cosetTable = (nrGens, relators, subgroupGens) => {
  const gens = _expandGenerators(nrGens);
  const rels = _expandRelators(relators);

  let table = I.List([I.Map()]);
  let part = new Partition();
  let i = 0, j = 0;

  while (i < table.size) {
    if (table.size > 10000)
      throw new Error('maximum coset table size reached');

    if (j >= gens.size || i != part.find(i))
      [i, j] = [i + 1, 0];
    else {
      if (table.getIn([i, gens.get(j)]) == null) {
        const g = gens.get(j);
        const n = table.size;

        let t = { table: table.setIn([i, g], n).setIn([n, -g], i), part };
        for (const w of rels)
          t = scanAndIdentify(t.table, t.part, w, n);
        for (const w of subgroupGens)
          t = scanAndIdentify(t.table, t.part, fw.word(w), part.find(0));

        table = t.table;
        part = t.part;
      }
      ++j;
    }
  }

  return compressed(table, part);
};

export const cosetRepresentatives = table => {
  const queue = [0];
  const reps = [fw.empty];

  while (queue.length) {
    const i = queue.shift();
    const w = reps[i];

    for (const [g, k] of table.get(i).filter(g => reps[g] == null)) {
      reps[k] = fw.product([w, [g]]);
      queue.push(k);
    }
  }

  return reps;
};

const _firstFreeInTable = (table, gens) => {
  for (let k = 0; k < table.size; ++k) {
    for (const g of gens) {
      if (table.getIn([k, g]) == null)
        return [k, g];
    }
  }
};

const _scanRecursively = (rels, table, index) => {
  const p = () => new Partition();
  const q = [index];

  while (q.length) {
    const row = q.shift();

    for (const rel of rels) {
      const { table: t, part, next } = scanAndIdentify(table, p(), rel, row);

      if (part.isTrivial()) {
        table = t;
        if (next != null)
          q.push(next);
      }
      else
        return;
    }
  }

  return table;
};

const _potentialChildren = (table, gens, rels, maxCosets) => {
  const [k, g] = _firstFreeInTable(table, gens) || [];
  const result = [];

  if (k != null) {
    const ginv = -g;
    const limit = Math.min(table.size + 1, maxCosets);

    for (let pos = k; pos < limit; ++pos) {
      if (table.getIn([pos, ginv]) == null) {
        const t0 = table.setIn([k, g], pos).setIn([pos, ginv], k);
        const t = _scanRecursively(rels, t0, k);
        if (t != null)
          result.push(t);
      }
    }
  }

  return I.List(result);
};

const _compareRenumberedFom = (table, gens, start) => {
  let o2n = I.Map([[start, 0]]);
  let n2o = I.Map([[0, start]]);
  let row = 0;
  let col = 0;

  while (true) {
    if (row >= o2n.size && row < table.size)
      throw new Error("coset table is not transitive");

    if (row >= table.size)
      return 0;
    else if (col >= gens.size) {
      ++row;
      col = 0;
    } else {
      const oval = table.getIn([row, gens.get(col)]);
      let nval = table.getIn([n2o.get(row), gens.get(col)]);
      if (nval != null && o2n.get(nval) == null) {
        n2o = n2o.set(o2n.size, nval);
        o2n = o2n.set(nval, o2n.size);
      }
      nval = o2n.get(nval);

      if (oval == nval)
        ++col;
      else if (oval == null)
        return -1;
      else if (nval == null)
        return 1;
      else
        return nval - oval;
    }
  }
};

const _isCanonical = (table, gens) => I.Range(1, table.size)
  .every(start => _compareRenumberedFom(table, gens, start) >= 0);

export const tables = (nrGens, relators, maxCosets) => {
  const gens = _expandGenerators(nrGens);
  const rels = _expandRelators(relators);
  const isFull = t => _firstFreeInTable(t, gens) == null;

  return generators.backtracker({
    root: I.List([I.Map()]),
    extract(table) { return isFull(table) ? table : null },
    children(table) {
      return _potentialChildren(table, gens, rels, maxCosets)
        .filter(t => !t.isEmpty() && _isCanonical(t, gens))
        .toArray();
    }
  });
};

const _inducedTable = (gens, img, img0) => {
  const table = I.List([I.Map()]).asMutable();
  const o2n = I.Map([[img0, 0]]).asMutable();
  const n2o = I.Map([[0, img0]]).asMutable();
  let i = 0;

  while (i < table.size) {
    gens.forEach(g => {
      const k = img(n2o.get(i), g);
      const n = o2n.has(k) ? o2n.get(k) : table.size;
      o2n.set(k, n);
      n2o.set(n, k);
      table.setIn([i, g], n).setIn([n, -g], i);
    });
    ++i;
  }

  return table.asImmutable();
};

export const intersectionTable = (tableA, tableB) => {
  return _inducedTable(
    (tableA.first() || I.Map()).keySeq(),
    (es, g) => I.List([tableA.getIn([es.get(0), g]),
                       tableB.getIn([es.get(1), g])]),
    I.List([0, 0])
  );
};

export const coreTable = base =>
  _inducedTable(
    (base.first() || I.Map()).keySeq(),
    (es, g) => es.map(e => base.getIn([e, g])),
    base.keySeq()
  );

const _sgn = x => (x > 0) - (x < 0);
const _sum = a => a.reduce((x, y) => x + y, 0);

export const relatorAsVector = (rel, nrgens) => {
  const counts = rel.groupBy(Math.abs).map(a => _sum(a.map(_sgn)));
  return I.List(I.Range(1, nrgens+1).map(i => counts.get(i) || 0));
};

export const relatorMatrix = (nrgens, relators) =>
  I.List(relators).map(rel => relatorAsVector(rel, nrgens));

if (require.main == module) {
  const test = table => {
    const reps = cosetRepresentatives(table);
    console.log(I.fromJS(reps), Object.keys(reps).length);
  };

  const base = cosetTable(
    3,
    [[1,1], [2,2], [3,3], [1,2,1,2,1,2], [1,3,1,3], fw.raisedTo(3, [2,3])],
    [[1,2]]);

  test(base);
  test(coreTable(base));

  console.log(_expandGenerators(4));
  console.log(_expandRelators([[1,2,-3]]));

  for (const x of generators.results(tables(2, [[1,1],[2,2],[1,2,1,2]], 8)))
    console.log(JSON.stringify(x));
}
<|endoftext|>


<commit_before>import {EventEmitter2 as EventEmitter } from "eventemitter2"
const Status        = require(__dirname + "/Status.js");
const Parameter     = require(__dirname + "/Parameter.js");
const Point         = require(__dirname + "/Point.js");
const HitPoint      = require(__dirname + "/HitPoint.js");
const MagicPoint    = require(__dirname + "/MagicPoint.js");
const STATUS_VALUES = require(`${__dirname}/../constant/Status.js`);
const UserState     = require(__dirname + "/../state/User.js");
import Job from "./Job";

function findSpell(spellName, spells) {
    return spells.filter((s) => s.name === spellName).pop() || null;
}

class User extends EventEmitter {
    constructor(
            id,
            name,
            hp,
            mp,
            equipment,
            parameter = new Parameter(),
            spells = [],
            status = new Status(),
            job = null
            ) {
        super();
        this.id = id;
        this.name = name;
        this.hitPoint = hp;
        this.magicPoint = mp;
        this.equipment = equipment;
        this.defaultParameter = parameter;
        this.spells = spells;
        this.status = status;
        this.changeJob(job);

        this.status.on("removed", (data) => {
            data.target === STATUS_VALUES.DEAD;
            this.cured(1)
        });

        this.hitPoint.empty() && this.status.dead();
        this.hitPoint.on("changed", (data) => {
            data.next.empty() && this.status.dead();
        });
    };

    attack(target) {
        if(this.isDead()) {
            return UserState.ActorDead;
        } else if(target.isDead()) {
            return UserState.TargetDead;
        }

        const attackResult = this.equipment.weapon.damage(target)(this.parameter);
        const result = User.actResult(this, target, attackResult, null);
        attackResult.hit && target.emit("attacked", result);
        return result;
    };

    cast(spellName, target) {
        const spell = findSpell(spellName, this.spells.concat(this.job.spells))
        if (this.isDead()) {
            return UserState.ActorDead;
        } else if (spell === null) {
            return UserState.NoTargetSpell;
        } else if (spell.requiredMagicPoint > this.magicPoint.current) {
            return UserState.NotEnoughMagicPoint;
        }

        this.magicPoint = spell.cast(this.magicPoint);
        const result = spell.effectTo(target)(this.parameter);
        if (typeof result === 'symbol') {
            return result;
        }
        return User.actResult(this, target, null, result);
    }

    damaged(x) {
        this.hitPoint.change(this.hitPoint.current - x);
        return {
            target: this,
            value: x
        };
    };

    cured(x) {
        this.hitPoint.change(this.hitPoint.current + x);
        return {
            target: this,
            value: x
        };
    };

    isDead() {
        return this.status.isDead();
    };

    changeJob(job) {
        if ( job ) {
            this.job = job;
            this.parameter = this.defaultParameter.plus(job.parameterAdjust);
        }
    }

    static actResult(actor, target, attack, effects) {
        return {
            actor: actor,
            target: target,
            attack: attack,
            effects: effects
        }
    }
}

module.exports = User;
<commit_msg>Fix for compativity<commit_after>import {EventEmitter2 as EventEmitter } from "eventemitter2"
const Status        = require(__dirname + "/Status.js");
const Parameter     = require(__dirname + "/Parameter.js");
const Point         = require(__dirname + "/Point.js");
const HitPoint      = require(__dirname + "/HitPoint.js");
const MagicPoint    = require(__dirname + "/MagicPoint.js");
const STATUS_VALUES = require(`${__dirname}/../constant/Status.js`);
const UserState     = require(__dirname + "/../state/User.js");
import Job from "./Job";

function findSpell(spellName, spells) {
    return spells.filter((s) => s.name === spellName).pop() || null;
}

class User extends EventEmitter {
    constructor(
            id,
            name,
            hp,
            mp,
            equipment,
            parameter = new Parameter(),
            spells = [],
            status = new Status(),
            job = null
            ) {
        super();
        this.id = id;
        this.name = name;
        this.hitPoint = hp;
        this.magicPoint = mp;
        this.equipment = equipment;
        this.defaultParameter = parameter;
        this.parameter = parameter;
        this.spells = spells;
        this.status = status;
        this.changeJob(job);

        this.status.on("removed", (data) => {
            data.target === STATUS_VALUES.DEAD;
            this.cured(1)
        });

        this.hitPoint.empty() && this.status.dead();
        this.hitPoint.on("changed", (data) => {
            data.next.empty() && this.status.dead();
        });
    };

    attack(target) {
        if(this.isDead()) {
            return UserState.ActorDead;
        } else if(target.isDead()) {
            return UserState.TargetDead;
        }

        const attackResult = this.equipment.weapon.damage(target)(this.parameter);
        const result = User.actResult(this, target, attackResult, null);
        attackResult.hit && target.emit("attacked", result);
        return result;
    };

    cast(spellName, target) {
        const spell = findSpell(spellName, this.getLearnedSpells())
        if (this.isDead()) {
            return UserState.ActorDead;
        } else if (spell === null) {
            return UserState.NoTargetSpell;
        } else if (spell.requiredMagicPoint > this.magicPoint.current) {
            return UserState.NotEnoughMagicPoint;
        }

        this.magicPoint = spell.cast(this.magicPoint);
        const result = spell.effectTo(target)(this.parameter);
        if (typeof result === 'symbol') {
            return result;
        }
        return User.actResult(this, target, null, result);
    }

    damaged(x) {
        this.hitPoint.change(this.hitPoint.current - x);
        return {
            target: this,
            value: x
        };
    };

    cured(x) {
        this.hitPoint.change(this.hitPoint.current + x);
        return {
            target: this,
            value: x
        };
    };

    isDead() {
        return this.status.isDead();
    };

    changeJob(job) {
        if ( job ) {
            this.job = job;
            this.parameter = this.defaultParameter.plus(job.parameterAdjust);
        }
    }

    getLearnedSpells() {
        return this.job ? this.spells.concat(this.job.spells) : this.spells;
    }

    static actResult(actor, target, attack, effects) {
        return {
            actor: actor,
            target: target,
            attack: attack,
            effects: effects
        }
    }
}

module.exports = User;
<|endoftext|>


<commit_before>import levels, { getLevelNumber } from './levels';
import timestampPrefix from './prefixes/timestampPrefix';
import levelPrefix from './prefixes/levelPrefix';

// creates an array that associates every log level with a function
function getLogFunctionArray(settings) {
  // if there is a single function in the settings, use it for all levels
  if (typeof settings.logFunction === 'function') {
    return levels.map(() => settings.logFunction);
  }

  // for each level, check if there is a method of the `console` object with that name.
  // if not found, use the function from the previous level (e.g. 'fatal' will use `console.error`
  // because `console.fatal` does not exist).
  // this will create a list of default functions to fall back to for each level.
  const defaultLogFnArr = ['log'] // need to start from a function that undoubtedly exists, so use 'log' first
    .concat(levels)
    .reduce((logFnArr, level, index) => {
      const consoleMethod = console[level];
      return logFnArr.concat(consoleMethod ? consoleMethod.bind(console) : logFnArr[index - 1]);
    }, [])
    .slice(1); // the first entry will be `console.log`, which was manually added, so get rid of it

  const customLogFnObj = settings.logFunction || {};

  // compose the array by checking if a custom function was specified for each level,
  // and falling back to the default one if not
  return levels.map((level, index) => (
    customLogFnObj[index] || customLogFnObj[level] || defaultLogFnArr[index]
  ));
}

// parses the user-provided settings and creates an object that holds the initial state of the logger
export default function getInitialState(settings) {
  // create the array that maps all levels to a function
  const logFunction = getLogFunctionArray(settings);

  // if `useColours` is specified, force the colours usage accordingly
  // otherwise only enable colours if the current process is running in a TTY
  const useColours = typeof settings.useColours === 'boolean'
    ? settings.useColours
    : (!settings.logFunction && typeof process !== 'undefined' && (process.stdout || {}).isTTY);

  const isEnabled = settings.isEnabled !== false;
  const currentLevel = getLevelNumber(settings.level || 0);

  // if the `prefixes` property is unspecified, default to `DATE [LEVEL] - MESSAGES`
  const prefixes = [].concat(settings.prefixes || [
    timestampPrefix,
    levelPrefix,
    '-',
  ]);

  return {
    logFunction,
    prefixes,
    isEnabled,
    currentLevel,
    useColours,
  };
}
<commit_msg>Minor update in autodetection of tty<commit_after>import levels, { getLevelNumber } from './levels';
import timestampPrefix from './prefixes/timestampPrefix';
import levelPrefix from './prefixes/levelPrefix';

// creates an array that associates every log level with a function
function getLogFunctionArray(settings) {
  // if there is a single function in the settings, use it for all levels
  if (typeof settings.logFunction === 'function') {
    return levels.map(() => settings.logFunction);
  }

  // for each level, check if there is a method of the `console` object with that name.
  // if not found, use the function from the previous level (e.g. 'fatal' will use `console.error`
  // because `console.fatal` does not exist).
  // this will create a list of default functions to fall back to for each level.
  const defaultLogFnArr = ['log'] // need to start from a function that undoubtedly exists, so use 'log' first
    .concat(levels)
    .reduce((logFnArr, level, index) => {
      const consoleMethod = console[level];
      return logFnArr.concat(consoleMethod ? consoleMethod.bind(console) : logFnArr[index - 1]);
    }, [])
    .slice(1); // the first entry will be `console.log`, which was manually added, so get rid of it

  const customLogFnObj = settings.logFunction || {};

  // compose the array by checking if a custom function was specified for each level,
  // and falling back to the default one if not
  return levels.map((level, index) => (
    customLogFnObj[index] || customLogFnObj[level] || defaultLogFnArr[index]
  ));
}

// parses the user-provided settings and creates an object that holds the initial state of the logger
export default function getInitialState(settings) {
  // create the array that maps all levels to a function
  const logFunction = getLogFunctionArray(settings);

  // if `useColours` is specified, force the colours usage accordingly
  // otherwise only enable colours if the current process is running in a TTY
  const useColours = typeof settings.useColours === 'boolean'
    ? settings.useColours
    : (!settings.logFunction && typeof process !== 'undefined' && process.stdout && process.stdout.isTTY);

  const isEnabled = settings.isEnabled !== false;
  const currentLevel = getLevelNumber(settings.level || 0);

  // if the `prefixes` property is unspecified, default to `DATE [LEVEL] - MESSAGES`
  const prefixes = [].concat(settings.prefixes || [
    timestampPrefix,
    levelPrefix,
    '-',
  ]);

  return {
    logFunction,
    prefixes,
    isEnabled,
    currentLevel,
    useColours,
  };
}
<|endoftext|>


<commit_before>(function() {
    gf.HudItem = Class.extend({
        init: function(x, y, settings) {
            //can be dragged
            this.draggable = false;

            //is this item visible?
            this.visible = true;

            //value of the item
            this.value = 0;

            this.name = '';

            //use the passed settings object ot override the default values above
            gf.utils.setValues(this, settings);

            this.default = this.value;

            //create the base div of this element
            this._createElement(x, y);

            //some private stuffs
            this.dirty = true;

            //dragging stuff
            this.dragging = false;
        },
        reset: function() {
            this.set(this.default);
            return this;
        },
        setValue: function(val) {
            this.value = val;
            this.dirty = true;
            return this;
        },
        getValue: function() {
            return this.value;
        },
        update: function() {
            if(!this.dirty) return;

            this.$elm.text(this.value);
            return this;
        },
        //virtual events
        onClick: function(e) {},
        onMouseDown: function(e) {
            if(!this.draggable) return;

            this.dragging = {
                x: e.clientX,
                y: e.clientY
            }
        },
        onMouseUp: function(e) {
            this.dragging = false;
        },
        onMouseMove: function(e) {
            if(!this.draggable || !this.dragging) return;

            var diffX = e.clientX - this.dragging.x,
                diffY = e.clientY - this.dragging.y,
                pos = this.$elm.position();

            this.dragging.x = e.clientX;
            this.dragging.y = e.clientY;

            this.$elm.css({
                top: pos.top += diffY,
                left: pos.left += diffX
            });
        },
        //private functions
        _createElement: function(x, y) {
            this.$elm = $('<div/>', {
                'class': 'gf-hud-item ' + this.name.toLowerCase().replace(' ', '-')
            }).css({
                position: 'relative',
                top: y,
                left: x
            });

            this._bindEvents();
        },
        _bindEvents: function() {
            this.$elm.on({
                click: this.onClick.bind(this),
                mousedown: this.onMouseDown.bind(this),
                mouseup: this.onMouseUp.bind(this),
                mousemove: this.onMouseMove.bind(this)
            });
        }
    });
})();<commit_msg>fix a layout issue<commit_after>(function() {
    gf.HudItem = Class.extend({
        init: function(x, y, settings) {
            //can be dragged
            this.draggable = false;

            //is this item visible?
            this.visible = true;

            //value of the item
            this.value = 0;

            this.name = '';

            //use the passed settings object ot override the default values above
            gf.utils.setValues(this, settings);

            this.default = this.value;

            //create the base div of this element
            this._createElement(x, y);

            //some private stuffs
            this.dirty = true;

            //dragging stuff
            this.dragging = false;
        },
        reset: function() {
            this.set(this.default);
            return this;
        },
        setValue: function(val) {
            this.value = val;
            this.dirty = true;
            return this;
        },
        getValue: function() {
            return this.value;
        },
        update: function() {
            if(!this.dirty) return;

            this.$elm.text(this.value);
            return this;
        },
        //virtual events
        onClick: function(e) {},
        onMouseDown: function(e) {
            if(!this.draggable) return;

            this.dragging = {
                x: e.clientX,
                y: e.clientY
            }
        },
        onMouseUp: function(e) {
            this.dragging = false;
        },
        onMouseMove: function(e) {
            if(!this.draggable || !this.dragging) return;

            var diffX = e.clientX - this.dragging.x,
                diffY = e.clientY - this.dragging.y,
                pos = this.$elm.position();

            this.dragging.x = e.clientX;
            this.dragging.y = e.clientY;

            this.$elm.css({
                top: pos.top += diffY,
                left: pos.left += diffX
            });
        },
        //private functions
        _createElement: function(x, y) {
            this.$elm = $('<div/>', {
                'class': 'gf-hud-item ' + this.name
            }).css({
                position: 'absolute',
                top: y,
                left: x
            });

            this._bindEvents();
        },
        _bindEvents: function() {
            this.$elm.on({
                click: this.onClick.bind(this),
                mousedown: this.onMouseDown.bind(this),
                mouseup: this.onMouseUp.bind(this),
                mousemove: this.onMouseMove.bind(this)
            });
        }
    });
})();<|endoftext|>


<commit_before>/**
 * Queue.js
 *
 * This file is part of alef.js.
 *
 * Written by Misha Tavkhelidze <misha.tavkhelidze@gmail.com>
 * Copyright (c) 2017 Misha Tavkhelidze
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/**
 * @private
 */
class Queue {
    enqueue() {}
    dequeue() {}
    peek() {}
    count() {}
    empty() {}
    full() {}
}
<commit_msg>Add Queue description<commit_after>/**
 * Queue.js
 *
 * This file is part of alef.js.
 *
 * Written by Misha Tavkhelidze <misha.tavkhelidze@gmail.com>
 * Copyright (c) 2017 Misha Tavkhelidze
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

// http://twistedoakstudios.com/blog/Post2096_making-an-immutable-queue-with-guaranteed-constant-time-operations
// https://blogs.msdn.microsoft.com/ericlippert/tag/immutability/

/**
 * Make two Lists: in and out. When out is empty, convert (pivot) in into out.
 *
 * Although pivoting will guaranteed to require O(n), amortized enqueue and
 * dequeue times will be O(1)
 */

/**
 * @private
 */
class Queue {
    enqueue() {}
    dequeue() {}
    peek() {}
    count() {}
    empty() {}
    full() {}
}
<|endoftext|>


<commit_before>(function (global, document, $, undefined) {
    "use strict";

    // datos del usuario
    var user_name = null;
    var fb_id = null;
    var hora = null;
    // conección a Firebase
    var Fire = new Firebase("https://saiberz.firebaseio.com/chat");
    var auth = new FirebaseSimpleLogin(Fire, function(error, user) {
        if (error) {
            console.error("An error occurred while attempting login.");
        } else if (user) {
            $("input").prop("disabled", false);
            $("input:text").prop("placeholder", "Escribe");
            user_name = user.displayName;
            fb_id = user.id;
            $("#fbl").hide(1000);
            $("#fblo").show(1000);
        } else {
            user_name = "Anonymous!";
            $("#fbl").show(1000);
            $("#fblo").hide(1000);
        }
    });

    Fire.on("child_added", function(ss) {
        ss = ss.val();
        addmessage(ss.text, ss.name, ss.id, ss.hour);
        if(ss.text === "#")
                    notificar(ss.text);
    });

    function addmessage(m, un, user_id, hour) {
        var newdivbox = document.createElement("div");
        var newdiv1 = document.createElement("figure");
        var newdiv2 = document.createElement("div");
        var contenedor = document.createElement("div");
        contenedor.setAttribute("id", "todo");

        var timeago = moment(hour).fromNow();
        newdivbox.setAttribute("id", "container");
        var newimg = document.createElement("img");
        newimg.src = "http://graph.facebook.com/" + user_id + "/picture";
        newimg.setAttribute("id", "user-image");
        newdiv1.appendChild(newimg);
        newdiv2.setAttribute("id", "user-message");
        var text = document.createElement("p");
        text.appendChild(document.createTextNode(m));
        text.setAttribute("id", "user-comment");
        var text2 = document.createElement("span");
        text2.appendChild(document.createTextNode(" ("+timeago+")"));
        text2.setAttribute("id", "user-comment-time");
        var userlink = document.createElement("a");
        userlink.setAttribute("href", "http://fb.com/" + user_id);
        userlink.setAttribute("id", "user-name");
        userlink.appendChild(document.createTextNode(un));
        newdiv2.appendChild(userlink);
        newdiv2.appendChild(text2);
        newdiv2.appendChild(text);
        newdivbox.appendChild(newdiv1);
        newdivbox.appendChild(newdiv2);
        contenedor.appendChild(newdivbox);
        $("#chatbox").prepend(contenedor);
    }

    function notificar(m) {
        if (Notification && Notification.permission !== "granted") {
            Notification.requestPermission(function (status) {
                if (Notification.permission !== status) {
                    Notification.permission = status;
                }
            });
        }
        // If the user agreed to get notified
        if (Notification && Notification.permission === "granted") {
            var n = new Notification(m);
        }
    };

    // event handlers

    $("#fblo").click(function() {
        if(confirm("Are you sure")) {
            auth.logout();
            $("input").prop("disabled", true);
        }
    });

    $("#fbl").click(function() {
        auth.login("facebook");
    });

    $("#message-input").keypress(function (event) {
        var ENTER_KEY = 13;
        if (event.keyCode === ENTER_KEY) {
            if($("#message-input").val() !== "") {
                var text = $("#message-input").val();
                var hour = moment().format();
                Fire.push({name:user_name, text:text, id:fb_id,hour: hour});
                $("#message-input").val("");
            }
        }
    });

})(window, window.document, window.jQuery);
<commit_msg>olvide algo xD<commit_after>(function (global, document, $, undefined) {
    "use strict";

    // datos del usuario
    var user_name = null;
    var fb_id = null;
    var hora = null;
    // conección a Firebase
    var Fire = new Firebase("https://saiberz.firebaseio.com/chat");
    var auth = new FirebaseSimpleLogin(Fire, function(error, user) {
        if (error) {
            console.error("An error occurred while attempting login.");
        } else if (user) {
            $("input").prop("disabled", false);
            $("input:text").prop("placeholder", "Escribe");
            user_name = user.displayName;
            fb_id = user.id;
            $("#fbl").hide(1000);
            $("#fblo").show(1000);
        } else {
            user_name = "Anonymous!";
            $("#fbl").show(1000);
            $("#fblo").hide(1000);
        }
    });

    Fire.on("child_added", function(ss) {
        ss = ss.val();
        addmessage(ss.text, ss.name, ss.id, ss.hour);
        if(ss.text[0] === "#")
                    notificar(ss.text);
    });

    function addmessage(m, un, user_id, hour) {
        var newdivbox = document.createElement("div");
        var newdiv1 = document.createElement("figure");
        var newdiv2 = document.createElement("div");
        var contenedor = document.createElement("div");
        contenedor.setAttribute("id", "todo");

        var timeago = moment(hour).fromNow();
        newdivbox.setAttribute("id", "container");
        var newimg = document.createElement("img");
        newimg.src = "http://graph.facebook.com/" + user_id + "/picture";
        newimg.setAttribute("id", "user-image");
        newdiv1.appendChild(newimg);
        newdiv2.setAttribute("id", "user-message");
        var text = document.createElement("p");
        text.appendChild(document.createTextNode(m));
        text.setAttribute("id", "user-comment");
        var text2 = document.createElement("span");
        text2.appendChild(document.createTextNode(" ("+timeago+")"));
        text2.setAttribute("id", "user-comment-time");
        var userlink = document.createElement("a");
        userlink.setAttribute("href", "http://fb.com/" + user_id);
        userlink.setAttribute("id", "user-name");
        userlink.appendChild(document.createTextNode(un));
        newdiv2.appendChild(userlink);
        newdiv2.appendChild(text2);
        newdiv2.appendChild(text);
        newdivbox.appendChild(newdiv1);
        newdivbox.appendChild(newdiv2);
        contenedor.appendChild(newdivbox);
        $("#chatbox").prepend(contenedor);
    }

    function notificar(m) {
        if (Notification && Notification.permission !== "granted") {
            Notification.requestPermission(function (status) {
                if (Notification.permission !== status) {
                    Notification.permission = status;
                }
            });
        }
        // If the user agreed to get notified
        if (Notification && Notification.permission === "granted") {
            var n = new Notification(m);
        }
    };

    // event handlers

    $("#fblo").click(function() {
        if(confirm("Are you sure")) {
            auth.logout();
            $("input").prop("disabled", true);
        }
    });

    $("#fbl").click(function() {
        auth.login("facebook");
    });

    $("#message-input").keypress(function (event) {
        var ENTER_KEY = 13;
        if (event.keyCode === ENTER_KEY) {
            if($("#message-input").val() !== "") {
                var text = $("#message-input").val();
                var hour = moment().format();
                Fire.push({name:user_name, text:text, id:fb_id,hour: hour});
                $("#message-input").val("");
            }
        }
    });

})(window, window.document, window.jQuery);
<|endoftext|>


<commit_before>// copied from govau/designsystem

var mainmenu        = document.getElementById( 'mainmenu' );
var mainmenuToggle  = document.getElementById( 'mainmenu-toggle' );
var searchToggle  	= document.getElementById( 'search-toggle' );
var overlay         = document.getElementById( 'overlay' );

var focustrapTop    = document.getElementById( 'focustrap-top' );
var focustrapBottom = document.getElementById( 'focustrap-bottom' );
var mainmenuLinks   = document.querySelectorAll( '.header a, .header button' );
var navSkipLink     = document.querySelectorAll( '.au-skip-link__link[href="#mainmenu"]' )[ 0 ];

function CloseMenuOnly() {
	AU.accordion.Close(mainmenuToggle, undefined);
	mainmenuToggle.innerHTML = 'Open menu';							// Change the text in the toggle
}

function CloseSearchOnly() {
	AU.accordion.Close(searchToggle, undefined);
	searchToggle.innerHTML = 'Open search';
}

function ToggleMenu() {
	AU.accordion.Toggle( mainmenuToggle, undefined, {
		onOpen: function() {
			CloseSearchOnly();															 // Force close the search in case it's currently open
			mainmenuToggle.innerHTML = 'Close menu';         // Change the text in the toggle
			focustrapTop.setAttribute( "tabindex", 0 );      // Enable the focus trap
			focustrapBottom.setAttribute( "tabindex", 0 );
			AddClass( document.body, 'overlay--open' );      // Stop scrolling when overlay is open
		},
		onClose: function() {
			mainmenuToggle.innerHTML = 'Open menu';
			focustrapTop.removeAttribute( "tabindex" );
			focustrapBottom.removeAttribute( "tabindex" );
			RemoveClass( document.body, 'overlay--open' );
		},
	});
}

function ToggleSearch() {
	AU.accordion.Toggle( searchToggle, undefined, {
		onOpen: function() {
			CloseMenuOnly();																 // Force close the menu in case it's currently open
			searchToggle.innerHTML = 'Close search';         // Change the text in the toggle
			focustrapTop.setAttribute( "tabindex", 0 );      // Enable the focus trap
			focustrapBottom.setAttribute( "tabindex", 0 );
			AddClass( document.body, 'overlay--open' );      // Stop scrolling when overlay is open
		},
		onClose: function() {
			searchToggle.innerHTML = 'Open search';
			focustrapTop.removeAttribute( "tabindex" );
			focustrapBottom.removeAttribute( "tabindex" );
			RemoveClass( document.body, 'overlay--open' );
		},
	});
}

// On click of the menu toggle open or close the menu
AddEvent( mainmenuToggle, 'click', function( event ) {
	PreventEvent( event );
	ToggleMenu();
});

// On click of the search toggle open or close the search
AddEvent( searchToggle, 'click', function( event ) {
	PreventEvent( event );
	ToggleSearch();
});

// Close the menu if the overlay is clicked
AddEvent( overlay, 'click', function( event ) {
	PreventEvent( event );
	ToggleMenu();
});

// Move the focus to the correct item when it lands on a trap
AddEvent( focustrapTop, 'focus', function( event ) {
	PreventEvent( event );
	mainmenuLinks[ mainmenuLinks.length - 1 ].focus();
});

AddEvent( focustrapBottom, 'focus', function( event ) {
	PreventEvent( event );
	mainmenuLinks[ 0 ].focus();
});

if ( mainmenu ){
	var MenuCheck = function() {
		var currentMenuDisplay = window.getComputedStyle( mainmenu, '' ).getPropertyValue( 'display' );

		if( currentMenuDisplay === 'none' ){
			mainmenu.setAttribute( "aria-hidden", "true" );
		}
		else {
			mainmenu.setAttribute( "aria-hidden", "false" );
		}
	};

	var SkipLinkCheck = function() {
		var mobileMenuDisplay = window.getComputedStyle( mainmenuToggle, '' ).getPropertyValue( 'display' );

		if( mobileMenuDisplay === 'none' ){
			navSkipLink.setAttribute( "href", "#mainmenu" );
		}
		else {
			navSkipLink.setAttribute( "href", "#mainmenu-toggle" );
		}
	}

	// Run on page load
	MenuCheck();
	SkipLinkCheck();

	// Run functions after a debounced resize
	var PageResize = Debounce(function() {
		MenuCheck();
		SkipLinkCheck();
	}, 250);

	// Run PageResize function on resize
	window.onresize = function() {
		PageResize();
	}
}
<commit_msg>Fix the bug where desktop mainmenu disappears when using the search accordion<commit_after>// copied from govau/designsystem

var mainmenu        = document.getElementById( 'mainmenu' );
var searchmenu      = document.getElementById( 'searchmenu' );
var mainmenuToggle  = document.getElementById( 'mainmenu-toggle' );
var searchToggle  	= document.getElementById( 'search-toggle' );
var overlay         = document.getElementById( 'overlay' );

var focustrapTop    = document.getElementById( 'focustrap-top' );
var focustrapBottom = document.getElementById( 'focustrap-bottom' );
var mainmenuLinks   = document.querySelectorAll( '.header a, .header button' );
var navSkipLink     = document.querySelectorAll( '.au-skip-link__link[href="#mainmenu"]' )[ 0 ];

function CloseMenuOnly() {
 if (mainmenuToggle.innerHTML == "Close menu") {
		AU.accordion.Toggle(mainmenuToggle, undefined);
		mainmenuToggle.innerHTML = 'Open menu';
	}
}

function CloseSearchOnly() {
	if (searchToggle.innerHTML == "Close search") {
 		AU.accordion.Toggle(searchToggle, undefined);
 		searchToggle.innerHTML = 'Open search';
 	}
}

function ToggleMenu() {
	AU.accordion.Toggle( mainmenuToggle, undefined, {
		onOpen: function() {
			CloseSearchOnly();															 // Force close the search in case it's currently open
			mainmenuToggle.innerHTML = 'Close menu';         // Change the text in the toggle
			focustrapTop.setAttribute( "tabindex", 0 );      // Enable the focus trap
			focustrapBottom.setAttribute( "tabindex", 0 );
			AddClass( document.body, 'overlay--open' );      // Stop scrolling when overlay is open
		},
		onClose: function() {
			mainmenuToggle.innerHTML = 'Open menu';
			focustrapTop.removeAttribute( "tabindex" );
			focustrapBottom.removeAttribute( "tabindex" );
			RemoveClass( document.body, 'overlay--open' );
		},
	});
}

function ToggleSearch() {
	AU.accordion.Toggle( searchToggle, undefined, {
		onOpen: function() {
			CloseMenuOnly();																 // Force close the menu in case it's currently open
			searchToggle.innerHTML = 'Close search';         // Change the text in the toggle
			focustrapTop.setAttribute( "tabindex", 0 );      // Enable the focus trap
			focustrapBottom.setAttribute( "tabindex", 0 );
			AddClass( document.body, 'overlay--open' );      // Stop scrolling when overlay is open
		},
		onClose: function() {
			searchToggle.innerHTML = 'Open search';
			focustrapTop.removeAttribute( "tabindex" );
			focustrapBottom.removeAttribute( "tabindex" );
			RemoveClass( document.body, 'overlay--open' );
		},
	});
}

// On click of the menu toggle open or close the menu
AddEvent( mainmenuToggle, 'click', function( event ) {
	PreventEvent( event );
	ToggleMenu();
});

// On click of the search toggle open or close the search
AddEvent( searchToggle, 'click', function( event ) {
	PreventEvent( event );
	ToggleSearch();
});

// Close the menu if the overlay is clicked
AddEvent( overlay, 'click', function( event ) {
	PreventEvent( event );
	ToggleMenu();
});

// Move the focus to the correct item when it lands on a trap
AddEvent( focustrapTop, 'focus', function( event ) {
	PreventEvent( event );
	mainmenuLinks[ mainmenuLinks.length - 1 ].focus();
});

AddEvent( focustrapBottom, 'focus', function( event ) {
	PreventEvent( event );
	mainmenuLinks[ 0 ].focus();
});

if ( mainmenu ){
	var MenuCheck = function() {
		var currentMenuDisplay = window.getComputedStyle( mainmenu, '' ).getPropertyValue( 'display' );

		if( currentMenuDisplay === 'none' ){
			mainmenu.setAttribute( "aria-hidden", "true" );
		}
		else {
			mainmenu.setAttribute( "aria-hidden", "false" );
		}
	};

	var SkipLinkCheck = function() {
		var mobileMenuDisplay = window.getComputedStyle( mainmenuToggle, '' ).getPropertyValue( 'display' );

		if( mobileMenuDisplay === 'none' ){
			navSkipLink.setAttribute( "href", "#mainmenu" );
		}
		else {
			navSkipLink.setAttribute( "href", "#mainmenu-toggle" );
		}
	}

	// Run on page load
	MenuCheck();
	SkipLinkCheck();

	// Run functions after a debounced resize
	var PageResize = Debounce(function() {
		MenuCheck();
		SkipLinkCheck();
	}, 250);

	// Run PageResize function on resize
	window.onresize = function() {
		PageResize();
	}
}
<|endoftext|>


<commit_before>(function (global, document, $, undefined) {
    "use strict";

    // datos del usuario
    var user_name = null;
    var fb_id = null;
    var hora = null;
    // conección a Firebase
    var Fire = new Firebase("https://saiberz.firebaseio.com/chat");
    var auth = new FirebaseSimpleLogin(Fire, function(error, user) {
        if (error) {
            console.error("An error occurred while attempting login.");
        } else if (user) {
            $("input").prop("disabled", false);
            $("input:text").prop("placeholder", "Escribe");
            user_name = user.displayName;
            fb_id = user.id;
            $("#fbl").hide(1000);
            $("#fblo").show(1000);
        } else {
            user_name = "Anonymous!";
            $("#fbl").show(1000);
            $("#fblo").hide(1000);
        }
    });

    Fire.on("child_added", function(ss) {
        ss = ss.val();
        addmessage(ss.text, ss.name, ss.id, ss.hour);
        if(ss.text[0] === "#")
                    notificar(ss.text);
    });

    function addmessage(m, un, user_id, hour) {
        var newdivbox = document.createElement("div");
        var newdiv1 = document.createElement("figure");
        var newdiv2 = document.createElement("div");
        var contenedor = document.createElement("div");
        contenedor.setAttribute("id", "todo");

        var timeago = moment(hour).fromNow();
        newdivbox.setAttribute("id", "container");
        var newimg = document.createElement("img");
        newimg.src = "http://graph.facebook.com/" + user_id + "/picture";
        newimg.setAttribute("id", "user-image");
        newdiv1.appendChild(newimg);
        newdiv2.setAttribute("id", "user-message");
        var text = document.createElement("p");
        text.appendChild(document.createTextNode(m));
        text.setAttribute("id", "user-comment");
        var text2 = document.createElement("span");
        text2.appendChild(document.createTextNode(" ("+timeago+")"));
        text2.setAttribute("id", "user-comment-time");
        var userlink = document.createElement("a");
        userlink.setAttribute("href", "http://fb.com/" + user_id);
        userlink.setAttribute("id", "user-name");
        userlink.appendChild(document.createTextNode(un));
        newdiv2.appendChild(userlink);
        newdiv2.appendChild(text2);
        newdiv2.appendChild(text);
        newdivbox.appendChild(newdiv1);
        newdivbox.appendChild(newdiv2);
        contenedor.appendChild(newdivbox);
        $("#chatbox").prepend(contenedor);
    }

    function notificar(m) {
        if (Notification && Notification.permission !== "granted") {
            Notification.requestPermission(function (status) {
                if (Notification.permission !== status) {
                    Notification.permission = status;
                }
            });
        }
        // If the user agreed to get notified
        if (Notification && Notification.permission === "granted") {
            var n = new Notification(m);
        }
    };

    // event handlers

    $("#fblo").click(function() {
        if(confirm("Are you sure")) {
            auth.logout();
            $("input").prop("disabled", true);
        }
    });

    $("#fbl").click(function() {
        auth.login("facebook");
    });

    $("#message-input").keypress(function (event) {
        var ENTER_KEY = 13;
        if (event.keyCode === ENTER_KEY) {
            if($("#message-input").val() !== "") {
                var text = $("#message-input").val();
                var hour = moment().format();
                Fire.push({name:user_name, text:text, id:fb_id,hour: hour});
                $("#message-input").val("");
            }
        }
    });

})(window, window.document, window.jQuery);
<commit_msg>option1: limited 50<commit_after>(function (global, document, $, undefined) {
    "use strict";

    // datos del usuario
    var user_name = null;
    var fb_id = null;
    var hora = null;
    // conección a Firebase
    var lastMessages = null;
    var Fire = new Firebase("https://saiberz.firebaseio.com/chat");
    var auth = new FirebaseSimpleLogin(Fire, function(error, user) {
        if (error) {
            console.error("An error occurred while attempting login.");
        } else if (user) {
            $("input").prop("disabled", false);
            $("input:text").prop("placeholder", "Escribe");
            user_name = user.displayName;
            fb_id = user.id;
            $("#fbl").hide(1000);
            $("#fblo").show(1000);
        } else {
            user_name = "Anonymous!";
            $("#fbl").show(1000);
            $("#fblo").hide(1000);
        }
    });
    lastMessages = Fire.endAt().limit(25);
    lastMessages.on("child_added", function(ss) {
        ss = ss.val();
        addmessage(ss.text, ss.name, ss.id, ss.hour);
        if(ss.text[0] === "#")
                    notificar(ss.text);
    });

    function addmessage(m, un, user_id, hour) {
        var newdivbox = document.createElement("div");
        var newdiv1 = document.createElement("figure");
        var newdiv2 = document.createElement("div");
        var contenedor = document.createElement("div");
        contenedor.setAttribute("id", "todo");

        var timeago = moment(hour).fromNow();
        newdivbox.setAttribute("id", "container");
        var newimg = document.createElement("img");
        newimg.src = "http://graph.facebook.com/" + user_id + "/picture";
        newimg.setAttribute("id", "user-image");
        newdiv1.appendChild(newimg);
        newdiv2.setAttribute("id", "user-message");
        var text = document.createElement("p");
        text.appendChild(document.createTextNode(m));
        text.setAttribute("id", "user-comment");
        var text2 = document.createElement("span");
        text2.appendChild(document.createTextNode(" ("+timeago+")"));
        text2.setAttribute("id", "user-comment-time");
        var userlink = document.createElement("a");
        userlink.setAttribute("href", "http://fb.com/" + user_id);
        userlink.setAttribute("id", "user-name");
        userlink.appendChild(document.createTextNode(un));
        newdiv2.appendChild(userlink);
        newdiv2.appendChild(text2);
        newdiv2.appendChild(text);
        newdivbox.appendChild(newdiv1);
        newdivbox.appendChild(newdiv2);
        contenedor.appendChild(newdivbox);
        $("#chatbox").prepend(contenedor);
    }

    function notificar(m) {
        if (Notification && Notification.permission !== "granted") {
            Notification.requestPermission(function (status) {
                if (Notification.permission !== status) {
                    Notification.permission = status;
                }
            });
        }
        // If the user agreed to get notified
        if (Notification && Notification.permission === "granted") {
            var n = new Notification(m);
        }
    };

    // event handlers

    $("#fblo").click(function() {
        if(confirm("Are you sure")) {
            auth.logout();
            $("input").prop("disabled", true);
        }
    });

    $("#fbl").click(function() {
        auth.login("facebook");
    });

    $("#message-input").keypress(function (event) {
        var ENTER_KEY = 13;
        if (event.keyCode === ENTER_KEY) {
            if($("#message-input").val() !== "") {
                var text = $("#message-input").val();
                var hour = moment().format();
                Fire.push({name:user_name, text:text, id:fb_id,hour: hour});
                $("#message-input").val("");
            }
        }
    });

})(window, window.document, window.jQuery);
<|endoftext|>


<commit_before>var h = 425;
var w = 675;
var paintColor = color(17, 0, 255);
var brushSize = 8;
var isDraw = 0;
var clear = true;
var type = false;
var typeCursorX = -1;
var typeCursorY = -1;
var letter = 'A';
var ts = 40;	// text size
var bs = 30; 	// brush size

void setup() {
  size(w, h);
}

function setWH() {
	w = document.getElementById("wid").value;
	h = document.getElementById("hei").value;
	setup();
}

void draw() {

	if (clear) {
		background(0,0,0);
		clear = false;
		typeCursorX = -1;
		typeCursorY = -1;
	}

    // red
    fill(250, 0, 0);
    rect(w-bs,0,bs,bs);

    // blue
    fill(51, 0, 255);
    rect(w-bs,bs,bs,bs);

    // yellow
    fill(255, 255, 0);
    rect(w-bs,2*bs,bs,bs);

    // green
    fill(0, 255, 38);
    rect(w-bs,3*bs,bs,bs);

    // purple
    fill(213, 0, 255);
    rect(w-bs,4*bs,bs,bs);

	// brushSize
	noStroke();
    fill(0,0,0);
    rect(w-bs,5*bs,bs,bs);
    rect(w-bs,6*bs,bs,bs);
    rect(w-bs,7*bs,bs,bs);
    fill(255,255,255);
    // +
    rect(w-.6*bs,5.4*bs,.2*bs,.6*bs);
    rect(w-.8*bs,5.6*bs,.6*bs,.2*bs);
    // -
    rect(w-.8*bs,7.4*bs,.6*bs,.2*bs);
    textSize(.8*bs);
    text(brushSize, w-.9*bs,7*bs);

	//eraser
	stroke(0,0,0);
	fill(0,0,0);
	rect(w-bs,8*bs,bs,bs);
	fill(255,0,0);
    textSize(.8*bs);
    text("E", w-.9*bs, 8.8*bs);

	if (isDraw === 1) {
		noStroke();
		fill(paintColor);
		rect(mouseX-brushSize, mouseY-brushSize, brushSize, brushSize);
	}

	if (type) {
		fill(paintColor);
		textSize(ts);
		text(letter, typeCursorX, typeCursorY);
		textFont("Courier New");
		type = false;
		}

}

void keyPressed() {
	if (key == CODED) {
	} else {
		letter = key;
		type = true;
		if (typeCursorX === -1) {
			typeCursorX = mouseX;
			typeCursorY = mouseY;
		} else if (typeCursorX > w-bs-ts*1.3) {
			typeCursorX = 0;
			typeCursorY = typeCursorY + ts;
		} else {
			typeCursorX = typeCursorX + ts/1.3;

		}
	}
}

void mouseReleased() {
	isDraw = 0;
}

void mousePressed() {
 	if(mouseX < w-bs) {
		typeCursorX = mouseX;
		typeCursorY = mouseY;
    	isDraw = 1;
	}
}

 void mouseClicked() {
	if (mouseX > w-50) {
		if (mouseY > 5*bs && mouseY < 6.5*bs && brushSize < 96) {
			brushSize += 4;
			ts = brushsize*10;
		}
		if (mouseY < 8.5*bs && mouseY > 7*bs  && brushSize > 4) {
			brushSize -= 4;
			ts = brushsize*10;
		}

		// red
		if (mouseY < bs) {
		    paintColor = color(255, 0, 0);
		}

		// blue
		if (mouseY > bs && mouseY < 2*bs) {
		    paintColor = color(51, 0, 255);
		}

		// yellow
		if (mouseY > 2*bs && mouseY < 3*bs) {
		    paintColor = color(255, 255, 0);
		}

		// green
		if (mouseY > 3*bs && mouseY < 4*bs) {
		    paintColor = color(0, 255, 38);
		}

		// purple
		if (mouseY > 4*bs && mouseY < 5*bs) {
		    paintColor = color(213, 0, 255);
		}

		// eraser
		if (mouseY > 8*bs && mouseY < 9.5*bs) {
		    clear = true;
		}
	}
}
<commit_msg>Update draw.js<commit_after>var h = document.getElementById("hei").value;
var w = document.getElementById("wid").value;
var paintColor = color(17, 0, 255);
var brushSize = 8;
var isDraw = 0;
var clear = true;
var type = false;
var typeCursorX = -1;
var typeCursorY = -1;
var letter = 'A';
var ts = 40;	// text size
var bs = 30; 	// brush size

void setup() {
  size(w, h);
}

function setWH() {
	w = document.getElementById("wid").value;
	h = document.getElementById("hei").value;
	setup();
}

void draw() {

	if (clear) {
		background(0,0,0);
		clear = false;
		typeCursorX = -1;
		typeCursorY = -1;
	}

    // red
    fill(250, 0, 0);
    rect(w-bs,0,bs,bs);

    // blue
    fill(51, 0, 255);
    rect(w-bs,bs,bs,bs);

    // yellow
    fill(255, 255, 0);
    rect(w-bs,2*bs,bs,bs);

    // green
    fill(0, 255, 38);
    rect(w-bs,3*bs,bs,bs);

    // purple
    fill(213, 0, 255);
    rect(w-bs,4*bs,bs,bs);

	// brushSize
	noStroke();
    fill(0,0,0);
    rect(w-bs,5*bs,bs,bs);
    rect(w-bs,6*bs,bs,bs);
    rect(w-bs,7*bs,bs,bs);
    fill(255,255,255);
    // +
    rect(w-.6*bs,5.4*bs,.2*bs,.6*bs);
    rect(w-.8*bs,5.6*bs,.6*bs,.2*bs);
    // -
    rect(w-.8*bs,7.4*bs,.6*bs,.2*bs);
    textSize(.8*bs);
    text(brushSize, w-.9*bs,7*bs);

	//eraser
	stroke(0,0,0);
	fill(0,0,0);
	rect(w-bs,8*bs,bs,bs);
	fill(255,0,0);
    textSize(.8*bs);
    text("E", w-.9*bs, 8.8*bs);

	if (isDraw === 1) {
		noStroke();
		fill(paintColor);
		rect(mouseX-brushSize, mouseY-brushSize, brushSize, brushSize);
	}

	if (type) {
		fill(paintColor);
		textSize(ts);
		text(letter, typeCursorX, typeCursorY);
		textFont("Courier New");
		type = false;
		}

}

void keyPressed() {
	if (key == CODED) {
	} else {
		letter = key;
		type = true;
		if (typeCursorX === -1) {
			typeCursorX = mouseX;
			typeCursorY = mouseY;
		} else if (typeCursorX > w-bs-ts*1.3) {
			typeCursorX = 0;
			typeCursorY = typeCursorY + ts;
		} else {
			typeCursorX = typeCursorX + ts/1.3;

		}
	}
}

void mouseReleased() {
	isDraw = 0;
}

void mousePressed() {
 	if(mouseX < w-bs) {
		typeCursorX = mouseX;
		typeCursorY = mouseY;
    	isDraw = 1;
	}
}

 void mouseClicked() {
	if (mouseX > w-50) {
		if (mouseY > 5*bs && mouseY < 6.5*bs && brushSize < 96) {
			brushSize += 4;
			ts = brushsize*10;
		}
		if (mouseY < 8.5*bs && mouseY > 7*bs  && brushSize > 4) {
			brushSize -= 4;
			ts = brushsize*10;
		}

		// red
		if (mouseY < bs) {
		    paintColor = color(255, 0, 0);
		}

		// blue
		if (mouseY > bs && mouseY < 2*bs) {
		    paintColor = color(51, 0, 255);
		}

		// yellow
		if (mouseY > 2*bs && mouseY < 3*bs) {
		    paintColor = color(255, 255, 0);
		}

		// green
		if (mouseY > 3*bs && mouseY < 4*bs) {
		    paintColor = color(0, 255, 38);
		}

		// purple
		if (mouseY > 4*bs && mouseY < 5*bs) {
		    paintColor = color(213, 0, 255);
		}

		// eraser
		if (mouseY > 8*bs && mouseY < 9.5*bs) {
		    clear = true;
		}
	}
}
<|endoftext|>


<commit_before>'use strict';
let data;

self.addEventListener('install', skipWaiting);

self.addEventListener('message', function (event) {
	if (event.data) {
		if (typeof event.data === 'string') {
			data = new URL(event.data, event.source.url).href;
		} else if (event.data.framework && event.data.modules && event.data.prefix) {
			data = event.data;
			for (let i = 0; i < data.framework.length; i++) {
				data.framework[i] = new URL(data.framework[i], event.source.url).href;
			}
			for (let i = 0; i < data.modules.length; i++) {
				data.modules[i] = new URL(data.modules[i] + '/', event.source.url).href;
			}
			caches.open(data.prefix + 'modules').then(function (cache) {
				return cache.keys().then(function (keys) {
					keys.forEach(function (request) {
						if (!findModule(request.url)) {
							cache.delete(request);
						}
					});
				});
			});
			caches.open(data.prefix + 'framework').then(function (cache) {
				return cache.keys().then(function (keys) {
					keys.forEach(function (request) {
						if (data.framework.indexOf(request.url) < 0) {
							cache.delete(request);
						}
					});
				});
			});
		}
	}
});

self.addEventListener('fetch', function (event) {
	if (data && event.request.method === 'GET') {
		if (typeof data === 'string') {
			if (event.request.url.length >= data.length && event.request.url.substr(0, data.length) === data) {
				event.respondWith(fetch(event.request, {
					cache: 'no-cache'
				}));
			}
		} else {
			let type;
			if (data.framework.indexOf(event.request.url) >= 0) {
				type = 'framework';
			} else if (findModule(event.request.url)) {
				type = 'modules';
			}
			if (type) {
				event.respondWith(caches.open(data.prefix + type).then(function (cache) {
					return cache.match(event.request).then(function (response) {
						if (response) {
							return response;
						} else {
							return fetch(event.request, {
								cache: 'no-cache'
							}).then(function (response) {
								if (response.ok) {
									cache.put(event.request, response.clone());
								}
								return response;
							});
						}
					});
				}));
			}
		}
	}
});

function findModule(url) {
	let found;
	for (let i = 0; i < data.modules.length; i++) {
		if (url.length > data.modules[i].length && url.substr(0, data.modules[i].length) === data.modules[i]) {
			found = true;
			break;
		}
	}
	return found;
}<commit_msg>no message<commit_after>'use strict';
let data;

self.addEventListener('install', skipWaiting);

self.addEventListener('message', function (event) {
	if (event.data) {
		if (typeof event.data === 'string') {
			data = new URL(event.data, event.source.url).href;
		} else if (event.data.framework && event.data.modules && event.data.prefix) {
			data = event.data;
			for (let i = 0; i < data.framework.length; i++) {
				data.framework[i] = new URL(data.framework[i], event.source.url).href;
			}
			for (let i = 0; i < data.modules.length; i++) {
				data.modules[i] = new URL(data.modules[i] + '/', event.source.url).href;
			}
			caches.open(data.prefix + 'modules').then(cache => cache.keys().then(keys => keys.forEach(request => {
				if (!findModule(request.url)) {
					cache.delete(request);
				}
			})));
			caches.open(data.prefix + 'framework').then(cache => cache.keys().then(keys => keys.forEach(request => {
				if (data.framework.indexOf(request.url) < 0) {
					cache.delete(request);
				}
			})));
		}
	}
});

self.addEventListener('fetch', function (event) {
	if (data && event.request.method === 'GET') {
		if (typeof data === 'string') {
			if (event.request.url.length >= data.length && event.request.url.substr(0, data.length) === data) {
				event.respondWith(fetch(event.request, {
					cache: 'no-cache'
				}));
			}
		} else {
			let type;
			if (data.framework.indexOf(event.request.url) >= 0) {
				type = 'framework';
			} else if (findModule(event.request.url)) {
				type = 'modules';
			}
			if (type) {
				event.respondWith(caches.open(data.prefix + type).then(cache => cache.match(event.request).then(response => response ? response : fetch(event.request, {
					cache: 'no-cache'
				}).then(response => {
					if (response.ok) {
						cache.put(event.request, response.clone());
					}
					return response;
				}))));
			}
		}
	}
});

function findModule(url) {
	let found;
	for (let i = 0; i < data.modules.length; i++) {
		if (url.length > data.modules[i].length && url.substr(0, data.modules[i].length) === data.modules[i]) {
			found = true;
			break;
		}
	}
	return found;
}<|endoftext|>


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

const { GitProcess } = require('dugite')
const childProcess = require('child_process')
const klaw = require('klaw')
const minimist = require('minimist')
const path = require('path')

const SOURCE_ROOT = path.normalize(path.dirname(__dirname))

const BLACKLIST = new Set([
  ['atom', 'browser', 'mac', 'atom_application.h'],
  ['atom', 'browser', 'mac', 'atom_application_delegate.h'],
  ['atom', 'browser', 'resources', 'win', 'resource.h'],
  ['atom', 'browser', 'ui', 'cocoa', 'atom_menu_controller.h'],
  ['atom', 'browser', 'ui', 'cocoa', 'atom_ns_window.h'],
  ['atom', 'browser', 'ui', 'cocoa', 'atom_ns_window_delegate.h'],
  ['atom', 'browser', 'ui', 'cocoa', 'atom_preview_item.h'],
  ['atom', 'browser', 'ui', 'cocoa', 'atom_touch_bar.h'],
  ['atom', 'browser', 'ui', 'cocoa', 'touch_bar_forward_declarations.h'],
  ['atom', 'browser', 'ui', 'cocoa', 'NSColor+Hex.h'],
  ['atom', 'browser', 'ui', 'cocoa', 'NSString+ANSI.h'],
  ['atom', 'common', 'api', 'api_messages.h'],
  ['atom', 'common', 'common_message_generator.cc'],
  ['atom', 'common', 'common_message_generator.h'],
  ['atom', 'common', 'node_includes.h'],
  ['atom', 'node', 'osfhandle.cc'],
  ['brightray', 'browser', 'mac', 'bry_inspectable_web_contents_view.h'],
  ['brightray', 'browser', 'mac', 'event_dispatching_window.h'],
  ['brightray', 'browser', 'mac', 'notification_center_delegate.h'],
  ['brightray', 'browser', 'win', 'notification_presenter_win7.h'],
  ['brightray', 'browser', 'win', 'win32_desktop_notifications', 'common.h'],
  ['brightray', 'browser', 'win', 'win32_desktop_notifications',
    'desktop_notification_controller.cc'],
  ['brightray', 'browser', 'win', 'win32_desktop_notifications',
    'desktop_notification_controller.h'],
  ['brightray', 'browser', 'win', 'win32_desktop_notifications', 'toast.h'],
  ['brightray', 'browser', 'win', 'win32_notification.h'],
  ['spec', 'static', 'jquery-2.0.3.min.js']
].map(tokens => path.join(SOURCE_ROOT, ...tokens)))

function spawnAndCheckExitCode (cmd, args, opts) {
  opts = Object.assign({ stdio: 'inherit' }, opts)
  const status = childProcess.spawnSync(cmd, args, opts).status
  if (status) process.exit(status)
}

const LINTERS = [ {
  key: 'c++',
  roots: ['atom', 'brightray'],
  test: filename => filename.endsWith('.cc') || filename.endsWith('.h'),
  run: (opts, filenames) => {
    const result = childProcess.spawnSync('cpplint.py', filenames, { encoding: 'utf8' })
    // cpplint.py writes EVERYTHING to stderr, including status messages
    if (result.stderr) {
      for (const line of result.stderr.split(/[\r\n]+/)) {
        if (line.length && !line.startsWith('Done processing ') && line !== 'Total errors found: 0') {
          console.warn(line)
        }
      }
    }
    if (result.status) process.exit(result.status)
  }
}, {
  key: 'python',
  roots: ['script'],
  test: filename => filename.endsWith('.py'),
  run: (opts, filenames) => {
    const rcfile = path.normalize(path.join(SOURCE_ROOT, '..', 'third_party', 'depot_tools', 'pylintrc'))
    const args = ['--rcfile=' + rcfile, ...filenames]
    const env = Object.assign({ PYTHONPATH: path.join(SOURCE_ROOT, 'script') }, process.env)
    spawnAndCheckExitCode('pylint.py', args, { env })
  }
}, {
  key: 'javascript',
  roots: ['lib', 'spec', 'script', 'default_app'],
  test: filename => filename.endsWith('.js'),
  run: (opts, filenames) => {
    const cmd = path.join(SOURCE_ROOT, 'node_modules', '.bin', 'eslint')
    const args = [ '--cache', ...filenames ]
    if (opts.fix) args.unshift('--fix')
    spawnAndCheckExitCode(cmd, args, { cwd: SOURCE_ROOT })
  }
}]

function parseCommandLine () {
  let help
  const opts = minimist(process.argv.slice(2), {
    boolean: [ 'c++', 'javascript', 'python', 'help', 'changed', 'fix', 'verbose' ],
    alias: { 'c++': ['cc', 'cpp', 'cxx'], javascript: ['js', 'es'], python: 'py', changed: 'c', help: 'h', verbose: 'v' },
    unknown: arg => { help = true }
  })
  if (help || opts.help) {
    console.log('Usage: script/lint.js [--cc] [--js] [--py] [-c|--changed] [-h|--help] [-v|--verbose] [--fix]')
    process.exit(0)
  }
  return opts
}

async function findChangedFiles (top) {
  const result = await GitProcess.exec(['diff', 'HEAD', '--name-only'], top)
  if (result.exitCode !== 0) {
    console.log('Failed to find changed files', GitProcess.parseError(result.stderr))
    process.exit(1)
  }
  const relativePaths = result.stdout.split(/\r\n|\r|\n/g)
  const absolutePaths = relativePaths.map(x => path.join(top, x))
  return new Set(absolutePaths)
}

async function findMatchingFiles (top, test) {
  return new Promise((resolve, reject) => {
    const matches = []
    klaw(top)
      .on('end', () => resolve(matches))
      .on('data', item => {
        if (test(item.path)) {
          matches.push(item.path)
        }
      })
  })
}

async function findFiles (args, linter) {
  let filenames = []
  let whitelist = null

  // build the whitelist
  if (args.changed) {
    whitelist = await findChangedFiles(SOURCE_ROOT)
    if (!whitelist.size) {
      return filenames
    }
  }

  // accumulate the raw list of files
  for (const root of linter.roots) {
    const files = await findMatchingFiles(path.join(SOURCE_ROOT, root), linter.test)
    filenames.push(...files)
  }

  // remove blacklisted files
  filenames = filenames.filter(x => !BLACKLIST.has(x))

  // if a whitelist exists, remove anything not in it
  if (whitelist) {
    filenames = filenames.filter(x => whitelist.has(x))
  }

  return filenames
}

async function main () {
  const opts = parseCommandLine()

  // no mode specified? run 'em all
  if (!opts['c++'] && !opts.javascript && !opts.python) {
    opts['c++'] = opts.javascript = opts.python = true
  }

  const linters = LINTERS.filter(x => opts[x.key])

  for (const linter of linters) {
    const filenames = await findFiles(opts, linter)
    if (filenames.length) {
      if (opts.verbose) { console.log(`linting ${filenames.length} ${linter.key} ${filenames.length === 1 ? 'file' : 'files'}`) }
      linter.run(opts, filenames)
    }
  }
}

if (process.mainModule === module) {
  main()
}
<commit_msg>refactor: use same diff args as run-clang-format<commit_after>#!/usr/bin/env node

const { GitProcess } = require('dugite')
const childProcess = require('child_process')
const klaw = require('klaw')
const minimist = require('minimist')
const path = require('path')

const SOURCE_ROOT = path.normalize(path.dirname(__dirname))

const BLACKLIST = new Set([
  ['atom', 'browser', 'mac', 'atom_application.h'],
  ['atom', 'browser', 'mac', 'atom_application_delegate.h'],
  ['atom', 'browser', 'resources', 'win', 'resource.h'],
  ['atom', 'browser', 'ui', 'cocoa', 'atom_menu_controller.h'],
  ['atom', 'browser', 'ui', 'cocoa', 'atom_ns_window.h'],
  ['atom', 'browser', 'ui', 'cocoa', 'atom_ns_window_delegate.h'],
  ['atom', 'browser', 'ui', 'cocoa', 'atom_preview_item.h'],
  ['atom', 'browser', 'ui', 'cocoa', 'atom_touch_bar.h'],
  ['atom', 'browser', 'ui', 'cocoa', 'touch_bar_forward_declarations.h'],
  ['atom', 'browser', 'ui', 'cocoa', 'NSColor+Hex.h'],
  ['atom', 'browser', 'ui', 'cocoa', 'NSString+ANSI.h'],
  ['atom', 'common', 'api', 'api_messages.h'],
  ['atom', 'common', 'common_message_generator.cc'],
  ['atom', 'common', 'common_message_generator.h'],
  ['atom', 'common', 'node_includes.h'],
  ['atom', 'node', 'osfhandle.cc'],
  ['brightray', 'browser', 'mac', 'bry_inspectable_web_contents_view.h'],
  ['brightray', 'browser', 'mac', 'event_dispatching_window.h'],
  ['brightray', 'browser', 'mac', 'notification_center_delegate.h'],
  ['brightray', 'browser', 'win', 'notification_presenter_win7.h'],
  ['brightray', 'browser', 'win', 'win32_desktop_notifications', 'common.h'],
  ['brightray', 'browser', 'win', 'win32_desktop_notifications',
    'desktop_notification_controller.cc'],
  ['brightray', 'browser', 'win', 'win32_desktop_notifications',
    'desktop_notification_controller.h'],
  ['brightray', 'browser', 'win', 'win32_desktop_notifications', 'toast.h'],
  ['brightray', 'browser', 'win', 'win32_notification.h'],
  ['spec', 'static', 'jquery-2.0.3.min.js']
].map(tokens => path.join(SOURCE_ROOT, ...tokens)))

function spawnAndCheckExitCode (cmd, args, opts) {
  opts = Object.assign({ stdio: 'inherit' }, opts)
  const status = childProcess.spawnSync(cmd, args, opts).status
  if (status) process.exit(status)
}

const LINTERS = [ {
  key: 'c++',
  roots: ['atom', 'brightray'],
  test: filename => filename.endsWith('.cc') || filename.endsWith('.h'),
  run: (opts, filenames) => {
    const result = childProcess.spawnSync('cpplint.py', filenames, { encoding: 'utf8' })
    // cpplint.py writes EVERYTHING to stderr, including status messages
    if (result.stderr) {
      for (const line of result.stderr.split(/[\r\n]+/)) {
        if (line.length && !line.startsWith('Done processing ') && line !== 'Total errors found: 0') {
          console.warn(line)
        }
      }
    }
    if (result.status) process.exit(result.status)
  }
}, {
  key: 'python',
  roots: ['script'],
  test: filename => filename.endsWith('.py'),
  run: (opts, filenames) => {
    const rcfile = path.normalize(path.join(SOURCE_ROOT, '..', 'third_party', 'depot_tools', 'pylintrc'))
    const args = ['--rcfile=' + rcfile, ...filenames]
    const env = Object.assign({ PYTHONPATH: path.join(SOURCE_ROOT, 'script') }, process.env)
    spawnAndCheckExitCode('pylint.py', args, { env })
  }
}, {
  key: 'javascript',
  roots: ['lib', 'spec', 'script', 'default_app'],
  test: filename => filename.endsWith('.js'),
  run: (opts, filenames) => {
    const cmd = path.join(SOURCE_ROOT, 'node_modules', '.bin', 'eslint')
    const args = [ '--cache', ...filenames ]
    if (opts.fix) args.unshift('--fix')
    spawnAndCheckExitCode(cmd, args, { cwd: SOURCE_ROOT })
  }
}]

function parseCommandLine () {
  let help
  const opts = minimist(process.argv.slice(2), {
    boolean: [ 'c++', 'javascript', 'python', 'help', 'changed', 'fix', 'verbose' ],
    alias: { 'c++': ['cc', 'cpp', 'cxx'], javascript: ['js', 'es'], python: 'py', changed: 'c', help: 'h', verbose: 'v' },
    unknown: arg => { help = true }
  })
  if (help || opts.help) {
    console.log('Usage: script/lint.js [--cc] [--js] [--py] [-c|--changed] [-h|--help] [-v|--verbose] [--fix]')
    process.exit(0)
  }
  return opts
}

async function findChangedFiles (top) {
  const result = await GitProcess.exec(['diff', '--name-only', '--cached'], top)
  if (result.exitCode !== 0) {
    console.log('Failed to find changed files', GitProcess.parseError(result.stderr))
    process.exit(1)
  }
  const relativePaths = result.stdout.split(/\r\n|\r|\n/g)
  const absolutePaths = relativePaths.map(x => path.join(top, x))
  return new Set(absolutePaths)
}

async function findMatchingFiles (top, test) {
  return new Promise((resolve, reject) => {
    const matches = []
    klaw(top)
      .on('end', () => resolve(matches))
      .on('data', item => {
        if (test(item.path)) {
          matches.push(item.path)
        }
      })
  })
}

async function findFiles (args, linter) {
  let filenames = []
  let whitelist = null

  // build the whitelist
  if (args.changed) {
    whitelist = await findChangedFiles(SOURCE_ROOT)
    if (!whitelist.size) {
      return filenames
    }
  }

  // accumulate the raw list of files
  for (const root of linter.roots) {
    const files = await findMatchingFiles(path.join(SOURCE_ROOT, root), linter.test)
    filenames.push(...files)
  }

  // remove blacklisted files
  filenames = filenames.filter(x => !BLACKLIST.has(x))

  // if a whitelist exists, remove anything not in it
  if (whitelist) {
    filenames = filenames.filter(x => whitelist.has(x))
  }

  return filenames
}

async function main () {
  const opts = parseCommandLine()

  // no mode specified? run 'em all
  if (!opts['c++'] && !opts.javascript && !opts.python) {
    opts['c++'] = opts.javascript = opts.python = true
  }

  const linters = LINTERS.filter(x => opts[x.key])

  for (const linter of linters) {
    const filenames = await findFiles(opts, linter)
    if (filenames.length) {
      if (opts.verbose) { console.log(`linting ${filenames.length} ${linter.key} ${filenames.length === 1 ? 'file' : 'files'}`) }
      linter.run(opts, filenames)
    }
  }
}

if (process.mainModule === module) {
  main()
}
<|endoftext|>


<commit_before>var haikus = {};
haikus.def = "Digestive system\nA haiku presentation\nJust hover the names\n\nDigestive system\nThe way of processing food\nGives materials";
haikus.mouth = "All starts at the mouth\nChewing is mandatory\nOr you can't swallow";
haikus.pharynx = "Second is the pharynx\nMaking sure you do not choke\nOn things you swallow";
haikus.esophagus = "The esophagus\nTransporting mush further down\nTowards your stomach";
haikus.stomach = "";
haikus.pancreas = "";
haikus.s_intes = "";
haikus.anus = "";
haikus.appendix = "";
haikus.l_intes = "";
haikus.gall = "";
haikus.liver = "";

var span;
var resdif;
var extra;

String.prototype.repeat = function(count) {
    if (count < 1) return '';
    var result = '', pattern = this.valueOf();
    while (count > 1) {
        if (count & 1) result += pattern;
        count >>= 1, pattern += pattern;
    }
    return result + pattern;
};

function resize() {
	//Add margin if widescreen
	resdif = ($(window).width()/$(window).height());
	extra = 0;
	if (resdif >= 1.6) {
		$('.container').css('right', '8%');
		$('.textcontainercontainer').css('left', '5%');
		extra = $(window).width() * 0.20;
	} else {
		$('.container').css('right', '0');
		$('.textcontainercontainer').css('left', '0');
	}

	//Add size to container to textfill works
	$('.textcontainer').width($(window).width()-$('img').width()-extra-5);

	$('.textcontainer').textfill({
		maxFontPixels: -1,
		widthOnly: false,
		minFontPixels: 4
	});
}

function update(haiku) {
	var text = haikus[haiku];
	text += "
".repeat(6 - (text.match(/\n/gi) || []).length);
	text = text.replace(/\n/gi, '
');

	span.html(text);
}

$(document).ready(function() {
	span = $('.textcontainer span');

	update('def');

	$(window).resize(function() {
		resize();
	}).resize();

	$('map').imageMapResize();

	$('area').hover(function () {
		update($(this).attr('title'));
		resize();
	}, function () {
		update('def');
		resize();
	});

	$(window).load(function() {
		$(window).resize(); //sometimes doesn't work earlier :/
	});
});
<commit_msg>Margins, even on non widescreen screens<commit_after>var haikus = {};
haikus.def = "Digestive system\nA haiku presentation\nJust hover the names\n\nDigestive system\nThe way of processing food\nGives materials";
haikus.mouth = "All starts at the mouth\nChewing is mandatory\nOr you can't swallow";
haikus.pharynx = "Second is the pharynx\nMaking sure you do not choke\nOn things you swallow";
haikus.esophagus = "The esophagus\nTransporting mush further down\nTowards your stomach";
haikus.stomach = "";
haikus.pancreas = "";
haikus.s_intes = "";
haikus.anus = "";
haikus.appendix = "";
haikus.l_intes = "";
haikus.gall = "";
haikus.liver = "";

var span;
var resdif;
var extra;

String.prototype.repeat = function(count) {
    if (count < 1) return '';
    var result = '', pattern = this.valueOf();
    while (count > 1) {
        if (count & 1) result += pattern;
        count >>= 1, pattern += pattern;
    }
    return result + pattern;
};

function resize() {
	//Add margin if widescreen
	resdif = ($(window).width()/$(window).height());
	extra = 0;
	if (resdif >= 1.6) {
		$('.container').css('right', '8%');
		$('.textcontainercontainer').css('left', '5%');
		extra = $(window).width() * 0.20;
	} else {
		$('.container').css('right', '1%');
		$('.textcontainercontainer').css('left', '1%');
	}

	//Add size to container to textfill works
	$('.textcontainer').width($(window).width()-$('img').width()-extra-5);

	$('.textcontainer').textfill({
		maxFontPixels: -1,
		widthOnly: false,
		minFontPixels: 4
	});
}

function update(haiku) {
	var text = haikus[haiku];
	text += "
".repeat(6 - (text.match(/\n/gi) || []).length);
	text = text.replace(/\n/gi, '
');

	span.html(text);
}

$(document).ready(function() {
	span = $('.textcontainer span');

	update('def');

	$(window).resize(function() {
		resize();
	}).resize();

	$('map').imageMapResize();

	$('area').hover(function () {
		update($(this).attr('title'));
		resize();
	}, function () {
		update('def');
		resize();
	});

	$(window).load(function() {
		$(window).resize(); //sometimes doesn't work earlier :/
	});
});
<|endoftext|>


<commit_before>

/**
 * scxml currently does not correctly declare the datamodel variables
 * -> fix this by injecting the datamodel variables by intercepting documentStringToModel.handleRawModule(url, rawModule, ...)
 *
 * TODO detect if this fix is needed (e.g. when future versions of scion-scxml have fixed this internally)
 *
 * @param       {scxml} [scxmlCompiler] the scxml module, e.g. require('@scion-scxml/scxml').
 * 																				If omitted, the default scxml module will be used, i.e. require('@scion-scxml/scxml').
 * 																				If already applied once, multiple calls to this function will be ignored.
 */
function _fixRawCompileInjectDataModule(scxmlCompiler){
	if(!scxmlCompiler){
		scxmlCompiler = require('@scion-scxml/scxml');
	}
	if(scxmlCompiler.documentStringToModel.__handleRawModule){
		return;
	}
	scxmlCompiler.documentStringToModel.__handleRawModule = scxmlCompiler.documentStringToModel.handleRawModule;
	scxmlCompiler.documentStringToModel.handleRawModule = function(_url, rawModule){
		var invokeConstructor;
		for(var i=rawModule.invokeConstructors.length-1; i >= 0; --i){
			invokeConstructor = rawModule.invokeConstructors[i];
			if(invokeConstructor.datamodel) {//FIXME russa
				var injectionNode = invokeConstructor.module._children[2];
				injectionNode.add(invokeConstructor.datamodel);
				injectionNode.add('\n');
			}
		}
		scxmlCompiler.documentStringToModel.__handleRawModule.apply(scxmlCompiler.documentStringToModel, arguments);
	}
}

module.exports = {
	fixRawCompileInjectDataModule: _fixRawCompileInjectDataModule
};
<commit_msg>guard scxml-datamodel-declaration-fix against unexpected data structures<commit_after>
var _ = require('lodash');
var warn = require('../utils/log-utils.js').warn;

/**
 * scxml currently does not correctly declare the datamodel variables
 * -> fix this by injecting the datamodel variables by intercepting documentStringToModel.handleRawModule(url, rawModule, ...)
 *
 * TODO detect if this fix is needed (e.g. when future versions of scion-scxml have fixed this internally)
 *
 * @param       {scxml} [scxmlCompiler] the scxml module, e.g. require('@scion-scxml/scxml').
 * 																				If omitted, the default scxml module will be used, i.e. require('@scion-scxml/scxml').
 * 																				If already applied once, multiple calls to this function will be ignored.
 */
function _fixRawCompileInjectDataModule(scxmlCompiler){
	if(!scxmlCompiler){
		scxmlCompiler = require('@scion-scxml/scxml');
	}
	if(scxmlCompiler.documentStringToModel.__handleRawModule){
		return;
	}
	scxmlCompiler.documentStringToModel.__handleRawModule = scxmlCompiler.documentStringToModel.handleRawModule;
	scxmlCompiler.documentStringToModel.handleRawModule = function(_url, rawModule){
		var invokeConstructor;
		for(var i=rawModule.invokeConstructors.length-1; i >= 0; --i){
			invokeConstructor = rawModule.invokeConstructors[i];
			if(invokeConstructor.datamodel) {
				if(!_.isArray(invokeConstructor.module._children) || invokeConstructor.module._children.length < 3 || typeof invokeConstructor.module._children[2].add !== 'function'){
					warn('[mmir-tooling] could not FIX scxml datamodel variable declaration, because of encountering unknown data structure. Please update mmir-tooling to fix this.')
				} else {
					var injectionNode = invokeConstructor.module._children[2];
					injectionNode.add(invokeConstructor.datamodel);
					injectionNode.add('\n');
				}
			}
		}
		scxmlCompiler.documentStringToModel.__handleRawModule.apply(scxmlCompiler.documentStringToModel, arguments);
	}
}

module.exports = {
	fixRawCompileInjectDataModule: _fixRawCompileInjectDataModule
};
<|endoftext|>