<commit_before>'use strict';

const repl = require('repl');
const io = require('socket.io');

let randInt = (min, max) => Math.floor(Math.random() * (max - min)) + min;
let randChoose = choices => choices[randInt(0, choices.length)];
class Player {
  constructor(server, id) {
    let config = server.config;
    this.id = id;
    this.clan = null;
    this.server = server;
    this.untilSend = 1;

    this.lastPing = new Date();

    this.name = 'unknown';
    this.skin = 0;
    this.size = config.playerScale;

    this.aimAngle = 0;
    this.movement = null;
    this.kill();
  }
  updateMovement(delta) {
    let config = this.server.config;
    let tx = 0;
    let ty = 0;
    if (this.movement != null) {
      tx = Math.cos(this.movement);
      ty = Math.sin(this.movement);
    }
    this.vx *= Math.pow(config.playerDecel, delta);
    this.vy *= Math.pow(config.playerDecel, delta);
    this.vx += tx * config.playerSpeed * delta * this.size / 2;
    this.vy += ty * config.playerSpeed * delta * this.size / 2;
    this.x += this.vx;
    this.y += this.vy;
  }
  update(delta) {
    if (this.alive) {
      this.updateMovement(delta);
      this.untilSend--;
      if (!this.untilSend) {
        this.untilSend = this.server.config.clientSendRate;
        this.sendPosition();
      }
    }
  }
  sendPosition() {
    let socket = this.socket;
    socket.emit('a');
    socket.emit('3', [
      this.id,
      this.x,
      this.y, -2.26,-1,0,0,null,0,0,0,0]);
  }
  link(socket) {
    this.socket = socket;
    socket.once('error', err => {
      console.log(err);
      this.destroy();
    });

    var emit = (...arg) => {
      try {
        socket.broadcast.emit(...arg)
        socket.emit(...arg)
      } catch (e) {
        sockets.forEach(a => a.emit(...arg))
      }
    }

    socket.on('2', angle => this.aimAngle = angle);
    socket.on('3', angle => this.movement = angle);

    socket.on("14", data => emit("p",this.x,this.y));

    socket.once('disconnect', () => this.destroy());
    socket.emit('id', {
      teams: this.server.clans
    });
    socket.on('1', data => {
      this.name = data.name.length > 15 || !data.name ? 'unknown' : data.name;
      this.skin = data.skin;
      this.spawn();
    });
  }
  destroy() {
    this.kill();
    this.server.remove(this.id);
    this.socket.disconnect();
  }
  kill() {
    this.alive = false;
    this.x = 0;
    this.y = 0;
    this.slowDown();
  }
  slowDown() {
    this.vx = 0;
    this.vy = 0;
  }
  spawn() {
    let config = this.server.config;
    let socket = this.socket;
    this.alive = true;
    let { x, y } = this.server.allocatePosition(this.size);
    this.x = x;
    this.y = y;
    this.slowDown();
    socket.emit('1', this.id);
    socket.emit('2', [socket.id,this.id,this.name,this.x,this.y,0,100,100,this.size,this.skin],true);
  }
  hitResource(type) {

  }
}
class Resource {
  constructor(server, x, y, size, type) {
    let config = server.config;
    this.x = x;
    this.y = y;
    this.type = config.resourceTypes.indexOf(type);
    this.size = size;
  }
  reward(by) {
    by.hitResource(this.type);
  }
}
class Server {
  constructor(config) {
    this.config = config;
    this.players = Array(config.maxPlayers).fill(null);
    this.lastRun = Date.now();
    this.clans = [];
    this.objects = [];
    setInterval(() => this.update(), config.serverUpdateRate);
    this.generateWorld();
  }
  remove(sid) {
    this.players[sid] = null;
  }
  update() {
    let now = Date.now();
    let delta = now - this.lastRun;
    this.lastRun = now;
    for (let i of this.players) {
      if (i != null) {
        i.update(delta);
      }
    }
  }
  generateWorld() {
    let config = this.config;
    let areaCount = config.areaCount;
    let mapScale = config.mapScale;
    let areaSize = mapScale / areaCount;
    let all = [];
    for (let afx = 0, atx = 1; afx < areaCount; afx++, atx++) {
      for (let afy = 0, aty = 1; afy < areaCount; afy++, aty++) {
        for (let i = 0; i < config.treesPerArea; i++) {
          let x = randInt(areaSize * afx, areaSize * atx);
          let y = randInt(areaSize * afy, areaSize * aty);
          all.push(new Resource(this, x, y, randChoose(config.treeScales), 'wood'));
        }
        for (let i = 0; i < config.bushesPerArea; i++) {
          let x = randInt(areaSize * afx, areaSize * atx);
          let y = randInt(areaSize * afy, areaSize * aty);
          all.push(new Resource(this, x, y, randChoose(config.bushScales), 'food'));
        }
      }
    }
    for (let i = 0; i < config.totalRocks; i++) {
      let x = randInt(0, mapScale);
      let y = randInt(0, mapScale);
      all.push(new Resource(this, x, y, randChoose(config.rockScales), 'stone'));
    }
    for (let i = 0; i < config.goldOres; i++) {
      let x = randInt(0, mapScale);
      let y = randInt(0, mapScale);
      all.push(new Resource(this, x, y, 0, 'points'));
    }
    this.objects = all;
  }
  allocatePosition(size) {
    let scale = this.config.mapScale;
    let x = 0;
    let y = 0;
    while (true) {
      x = randInt(0, scale);
      y = randInt(0, scale);
      if (true) { // check if there's nothing overlapping
        break;
      }
    }
    return { x, y };
  }
  handle(socket) {
    for (let i = 0; i < this.players.length; i++) {
      if (this.players[i] == null) {
        let player = new Player(this, i);
        player.link(socket);
        this.players[i] = player;
        break;
      }
    }
  }
}

let app = new Server({
  mapScale: 14400,
  maxPlayers: 50,
  clientSendRate: 5,
  serverUpdateRate: 9,
  playerDecel: 0.993,
  playerSpeed: 0.0016,
  playerScale: 35,
  areaCount: 7,
  treesPerArea: 9,
  bushesPerArea: 3,
  totalRocks: 32,
  goldOres: 7,
  resourceTypes: ['wood', 'food', 'stone', 'points'],
  treeScales: [140, 145, 150, 155],
  bushScales: [80, 85, 95],
  rockScales: [80, 85, 90],
});

for (let i = 5000; i <= 5010; i++) {
  io(i).on('connection', socket => app.handle(socket));
}
/*
let teams = [];
let sockets = [];
  io(i).on('connection', function (socket) {
    let emit = (...arg) => {
      try {
        socket.broadcast.emit(...arg);
        socket.emit(...arg);
      } catch (e) {
        sockets.forEach(a => a.emit(...arg));
      }
    };
    sockets.push(socket);
    socket.on('1', function (data) {
      let id = 27;
      let name = data.name.length > 15 ? 'unknown' : data.name;
      socket.emit('id', {
        "teams": teams
      });
      socket.emit('1', id);
      socket.emit('mm', 0);
      socket.emit('3', []);
      let x = randInt(0, config.mapScale);
      let y = randInt(0, config.mapScale);
      let userteam = null;
      let last = 0;
      socket.emit("2", ["a3Pm5dMzeKOjc5gvAJEF", id, name, x, 7200, 0, 100, 100, 35, data.skin], true);
      socket.emit("5", [27, data.name, 9001]); //[5,"RIP",31988,45,"KADEJO503",23404,34,"winter wolf",4821,28,"Godenot",4500,33,"Arena Closer",3000,32,"LightTheif",2940,6,"CarlosKoS-_-16",2800,4,"GD desconhecido",2635,35,"jack black GD",2357,19,"AMIGO BOM",1623])
      socket.emit("6", [
        29, 3115.1, 13592.9, 0, 109.2, 1, null, -1,
        353, 4103, 13436, 0, 80, 2, null, -1,
        339, 2498, 14155, 0, 90, 2, null, -1
      ]);
      socket.emit("8", 2.6, 28);
      socket.on("ch", data => {
        emit("ch", id, data);
      });
      socket.on("8", data => {
        console.log('CLAN CREATE REQUEST:', data);
        teams.push([{
          "sid": data,
          "owner": id
        }]);
        let userteam = data;
        emit("st", data, true);
      });
      socket.on("3", function (data) {
        if (data == null) {
          vx = vy = 0;
          return;
        } else if (x < 0 || x > config.mapScale || y < 0 || y > config.mapScale) {
          x = 7200;
          y = 7200;
        }
        if (y >= 6840 && y <= 7560) {
          x += 0.44;
        }
        let speed = y > 2400 ? 60 * 0.8 : 60;
        vx = Math.cos(data) * speed;
        vy = Math.sin(data) * speed;
        x += vx;
        y += vy;
        socket.emit('a');
        socket.emit("3", [id, x, y, -2.26, -1, 0, 0, null, 0, 0, 0, 0]);
      });
      socket.on("14", function (data) {
        console.log('ping!!!', arguments);
      });
    });
  });
}
*/
repl.start({
  eval: (a, _c, _f, cb) => {
    try {
      cb(null, eval(a)); // jshint ignore: line
    } catch (e) {
      cb(e);
    }
  }
});
<commit_msg>Set an earlier date for the lastPing initial value<commit_after>'use strict';

const repl = require('repl');
const io = require('socket.io');

let randInt = (min, max) => Math.floor(Math.random() * (max - min)) + min;
let randChoose = choices => choices[randInt(0, choices.length)];
class Player {
  constructor(server, id) {
    let config = server.config;
    this.id = id;
    this.clan = null;
    this.server = server;
    this.untilSend = 1;

    this.lastPing = new Date(2017, 9, 7, 5, 57, 0);.

    this.name = 'unknown';
    this.skin = 0;
    this.size = config.playerScale;

    this.aimAngle = 0;
    this.movement = null;
    this.kill();
  }
  updateMovement(delta) {
    let config = this.server.config;
    let tx = 0;
    let ty = 0;
    if (this.movement != null) {
      tx = Math.cos(this.movement);
      ty = Math.sin(this.movement);
    }
    this.vx *= Math.pow(config.playerDecel, delta);
    this.vy *= Math.pow(config.playerDecel, delta);
    this.vx += tx * config.playerSpeed * delta * this.size / 2;
    this.vy += ty * config.playerSpeed * delta * this.size / 2;
    this.x += this.vx;
    this.y += this.vy;
  }
  update(delta) {
    if (this.alive) {
      this.updateMovement(delta);
      this.untilSend--;
      if (!this.untilSend) {
        this.untilSend = this.server.config.clientSendRate;
        this.sendPosition();
      }
    }
  }
  sendPosition() {
    let socket = this.socket;
    socket.emit('a');
    socket.emit('3', [
      this.id,
      this.x,
      this.y, -2.26,-1,0,0,null,0,0,0,0]);
  }
  link(socket) {
    this.socket = socket;
    socket.once('error', err => {
      console.log(err);
      this.destroy();
    });

    var emit = (...arg) => {
      try {
        socket.broadcast.emit(...arg)
        socket.emit(...arg)
      } catch (e) {
        sockets.forEach(a => a.emit(...arg))
      }
    }

    socket.on('2', angle => this.aimAngle = angle);
    socket.on('3', angle => this.movement = angle);

    socket.on("14", data => emit("p",this.x,this.y));

    socket.once('disconnect', () => this.destroy());
    socket.emit('id', {
      teams: this.server.clans
    });
    socket.on('1', data => {
      this.name = data.name.length > 15 || !data.name ? 'unknown' : data.name;
      this.skin = data.skin;
      this.spawn();
    });
  }
  destroy() {
    this.kill();
    this.server.remove(this.id);
    this.socket.disconnect();
  }
  kill() {
    this.alive = false;
    this.x = 0;
    this.y = 0;
    this.slowDown();
  }
  slowDown() {
    this.vx = 0;
    this.vy = 0;
  }
  spawn() {
    let config = this.server.config;
    let socket = this.socket;
    this.alive = true;
    let { x, y } = this.server.allocatePosition(this.size);
    this.x = x;
    this.y = y;
    this.slowDown();
    socket.emit('1', this.id);
    socket.emit('2', [socket.id,this.id,this.name,this.x,this.y,0,100,100,this.size,this.skin],true);
  }
  hitResource(type) {

  }
}
class Resource {
  constructor(server, x, y, size, type) {
    let config = server.config;
    this.x = x;
    this.y = y;
    this.type = config.resourceTypes.indexOf(type);
    this.size = size;
  }
  reward(by) {
    by.hitResource(this.type);
  }
}
class Server {
  constructor(config) {
    this.config = config;
    this.players = Array(config.maxPlayers).fill(null);
    this.lastRun = Date.now();
    this.clans = [];
    this.objects = [];
    setInterval(() => this.update(), config.serverUpdateRate);
    this.generateWorld();
  }
  remove(sid) {
    this.players[sid] = null;
  }
  update() {
    let now = Date.now();
    let delta = now - this.lastRun;
    this.lastRun = now;
    for (let i of this.players) {
      if (i != null) {
        i.update(delta);
      }
    }
  }
  generateWorld() {
    let config = this.config;
    let areaCount = config.areaCount;
    let mapScale = config.mapScale;
    let areaSize = mapScale / areaCount;
    let all = [];
    for (let afx = 0, atx = 1; afx < areaCount; afx++, atx++) {
      for (let afy = 0, aty = 1; afy < areaCount; afy++, aty++) {
        for (let i = 0; i < config.treesPerArea; i++) {
          let x = randInt(areaSize * afx, areaSize * atx);
          let y = randInt(areaSize * afy, areaSize * aty);
          all.push(new Resource(this, x, y, randChoose(config.treeScales), 'wood'));
        }
        for (let i = 0; i < config.bushesPerArea; i++) {
          let x = randInt(areaSize * afx, areaSize * atx);
          let y = randInt(areaSize * afy, areaSize * aty);
          all.push(new Resource(this, x, y, randChoose(config.bushScales), 'food'));
        }
      }
    }
    for (let i = 0; i < config.totalRocks; i++) {
      let x = randInt(0, mapScale);
      let y = randInt(0, mapScale);
      all.push(new Resource(this, x, y, randChoose(config.rockScales), 'stone'));
    }
    for (let i = 0; i < config.goldOres; i++) {
      let x = randInt(0, mapScale);
      let y = randInt(0, mapScale);
      all.push(new Resource(this, x, y, 0, 'points'));
    }
    this.objects = all;
  }
  allocatePosition(size) {
    let scale = this.config.mapScale;
    let x = 0;
    let y = 0;
    while (true) {
      x = randInt(0, scale);
      y = randInt(0, scale);
      if (true) { // check if there's nothing overlapping
        break;
      }
    }
    return { x, y };
  }
  handle(socket) {
    for (let i = 0; i < this.players.length; i++) {
      if (this.players[i] == null) {
        let player = new Player(this, i);
        player.link(socket);
        this.players[i] = player;
        break;
      }
    }
  }
}

let app = new Server({
  mapScale: 14400,
  maxPlayers: 50,
  clientSendRate: 5,
  serverUpdateRate: 9,
  playerDecel: 0.993,
  playerSpeed: 0.0016,
  playerScale: 35,
  areaCount: 7,
  treesPerArea: 9,
  bushesPerArea: 3,
  totalRocks: 32,
  goldOres: 7,
  resourceTypes: ['wood', 'food', 'stone', 'points'],
  treeScales: [140, 145, 150, 155],
  bushScales: [80, 85, 95],
  rockScales: [80, 85, 90],
});

for (let i = 5000; i <= 5010; i++) {
  io(i).on('connection', socket => app.handle(socket));
}
/*
let teams = [];
let sockets = [];
  io(i).on('connection', function (socket) {
    let emit = (...arg) => {
      try {
        socket.broadcast.emit(...arg);
        socket.emit(...arg);
      } catch (e) {
        sockets.forEach(a => a.emit(...arg));
      }
    };
    sockets.push(socket);
    socket.on('1', function (data) {
      let id = 27;
      let name = data.name.length > 15 ? 'unknown' : data.name;
      socket.emit('id', {
        "teams": teams
      });
      socket.emit('1', id);
      socket.emit('mm', 0);
      socket.emit('3', []);
      let x = randInt(0, config.mapScale);
      let y = randInt(0, config.mapScale);
      let userteam = null;
      let last = 0;
      socket.emit("2", ["a3Pm5dMzeKOjc5gvAJEF", id, name, x, 7200, 0, 100, 100, 35, data.skin], true);
      socket.emit("5", [27, data.name, 9001]); //[5,"RIP",31988,45,"KADEJO503",23404,34,"winter wolf",4821,28,"Godenot",4500,33,"Arena Closer",3000,32,"LightTheif",2940,6,"CarlosKoS-_-16",2800,4,"GD desconhecido",2635,35,"jack black GD",2357,19,"AMIGO BOM",1623])
      socket.emit("6", [
        29, 3115.1, 13592.9, 0, 109.2, 1, null, -1,
        353, 4103, 13436, 0, 80, 2, null, -1,
        339, 2498, 14155, 0, 90, 2, null, -1
      ]);
      socket.emit("8", 2.6, 28);
      socket.on("ch", data => {
        emit("ch", id, data);
      });
      socket.on("8", data => {
        console.log('CLAN CREATE REQUEST:', data);
        teams.push([{
          "sid": data,
          "owner": id
        }]);
        let userteam = data;
        emit("st", data, true);
      });
      socket.on("3", function (data) {
        if (data == null) {
          vx = vy = 0;
          return;
        } else if (x < 0 || x > config.mapScale || y < 0 || y > config.mapScale) {
          x = 7200;
          y = 7200;
        }
        if (y >= 6840 && y <= 7560) {
          x += 0.44;
        }
        let speed = y > 2400 ? 60 * 0.8 : 60;
        vx = Math.cos(data) * speed;
        vy = Math.sin(data) * speed;
        x += vx;
        y += vy;
        socket.emit('a');
        socket.emit("3", [id, x, y, -2.26, -1, 0, 0, null, 0, 0, 0, 0]);
      });
      socket.on("14", function (data) {
        console.log('ping!!!', arguments);
      });
    });
  });
}
*/
repl.start({
  eval: (a, _c, _f, cb) => {
    try {
      cb(null, eval(a)); // jshint ignore: line
    } catch (e) {
      cb(e);
    }
  }
});
<|endoftext|>


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

var cli = require( 'cli' )
var _ = require( 'lodash' )

cli.parse( {
  compact:   [ 'c', 'Output compact CSS.' ],
  minified:  [ 'm', 'Output minified CSS.' ],
  output:    [ false, 'Write to FILE rather than the console.', 'file' ]
} )

cli.main(function ( args, options ) {

  var inside = false
  var declarations = {}
  var declaration = ''
  var selectors = {}
  var _selectors = []
  var selector = ''
  var outputCss = ''

  var lineSep = '\n\n'
  var selectorSep = '\n'
  var declarationSep = ';\n'
  var declarationPrefix = '\t'
  var space = ' '

  if ( options.compact ) {
    lineSep = '\n'
    declarationSep = '; '
    selectorSep = declarationPrefix = ''
  }
  if ( options.minified ) {
    declarationSep = ';'
    lineSep = selectorSep = declarationPrefix = space = ''
  }

  var removeTrailingChar = function ( str, char ) {
    char = char || ','
    var rx = new RegExp( char + '+$' )
    return str.trim().replace( rx, '' )
  }

  var outputFile = function (file) {
    cli.withInput(file, function (line, sep, eof) {
      if ( !eof ) {
        /*
        * Input phase
        */
        if ( line.indexOf( '{' ) > -1 ) {
          // Start of selector block
          inside = true
          declaration = line.split( '{' )[0].trim()
          declarations[declaration] = []
          _selectors = []
        } else if ( line.indexOf( '}' ) > -1 ) {
          // End of selector block
          inside = false
          declaration = ''
          if ( line.split( '}' ).length > 1 ) {
            selector = line.split( '}' )[0].trim()
            selector && _selectors.push( removeTrailingChar( selector ) )
          }
        } else if ( inside ) {
          // Inside selector block
          _selectors.push( removeTrailingChar( line ) )
        }

        if ( _selectors.length > 0 && declaration ) {
          _selectors = _selectors.join( ',' ).trim().split( ',' )
          _selectors.forEach( function ( tag ) {
            if ( selectors[ tag ] ) {
              if ( selectors[ tag ].indexOf( declaration ) < 0 ) {
                selectors[ tag ].push( declaration )
              }
            } else {
              selectors[ tag ] = [ declaration ]
            }
          } )
        }

      } else if (cli.args.length) {
        cli.output('Revercss only supports one file at a time.') // For now ...
        //outputFile(cli.args.shift())
      } else {
        /*
        * Output phase
        */

        _.forEach( selectors, function( declarations, selector ) {
          outputCss += [ selector, '{', selectorSep ].join( space )
          declarations.forEach( function( declaration ) {
            outputCss += [ declarationPrefix, declaration, declarationSep ].join( '' )
          } )
          outputCss += '}' + lineSep
        } )

        try {
          if ( options.output ) {
            outputStream = this.native.fs.createWriteStream( options.output )
          } else {
            outputStream = process.stdout
          }
          outputStream.write( outputCss )
        } catch (e) {
          this.fatal('Could not write to output stream.')
        }

        if ( options.echo ) {
          console.log( outputCss )
        }

      }
    })
  }

  if (cli.args.length) {
    outputFile(cli.args.shift())
  }

})<commit_msg>Added support for stdin<commit_after>#!/usr/bin/env node

var cli = require( 'cli' )
var _ = require( 'lodash' )

cli.parse( {
  compact:   [ 'c', 'Output compact CSS.' ],
  minified:  [ 'm', 'Output minified CSS.' ],
  output:    [ false, 'Write to FILE rather than the console.', 'file' ]
} )

cli.main(function ( args, options ) {

  var inside = false
  var declarations = {}
  var declaration = ''
  var selectors = {}
  var _selectors = []
  var selector = ''
  var outputCss = ''

  var lineSep = '\n\n'
  var selectorSep = '\n'
  var declarationSep = ';\n'
  var declarationPrefix = '\t'
  var space = ' '

  if ( options.compact ) {
    lineSep = '\n'
    declarationSep = '; '
    selectorSep = declarationPrefix = ''
  }
  if ( options.minified ) {
    declarationSep = ';'
    lineSep = selectorSep = declarationPrefix = space = ''
  }

  var removeTrailingChar = function ( str, char ) {
    char = char || ','
    var rx = new RegExp( char + '+$' )
    return str.trim().replace( rx, '' )
  }

  var handleInput = function (line, sep, eof) {
    if ( !eof ) {
      /*
      * Input phase
      */
      if ( line.indexOf( '{' ) > -1 ) {
        // Start of selector block
        inside = true
        declaration = line.split( '{' )[0].trim()
        declarations[declaration] = []
        _selectors = []
      } else if ( line.indexOf( '}' ) > -1 ) {
        // End of selector block
        inside = false
        declaration = ''
        if ( line.split( '}' ).length > 1 ) {
          selector = line.split( '}' )[0].trim()
          selector && _selectors.push( removeTrailingChar( selector ) )
        }
      } else if ( inside ) {
        // Inside selector block
        _selectors.push( removeTrailingChar( line ) )
      }

      if ( _selectors.length > 0 && declaration ) {
        _selectors = _selectors.join( ',' ).trim().split( ',' )
        _selectors.forEach( function ( tag ) {
          if ( selectors[ tag ] ) {
            if ( selectors[ tag ].indexOf( declaration ) < 0 ) {
              selectors[ tag ].push( declaration )
            }
          } else {
            selectors[ tag ] = [ declaration ]
          }
        } )
      }

    } else if (cli.args.length) {
      cli.output('Revercss only supports one file at a time.')
    } else {
      /*
      * Output phase
      */

      _.forEach( selectors, function( declarations, selector ) {
        outputCss += [ selector, '{', selectorSep ].join( space )
        declarations.forEach( function( declaration ) {
          outputCss += [ declarationPrefix, declaration, declarationSep ].join( '' )
        } )
        outputCss += '}' + lineSep
      } )

      try {
        if ( options.output ) {
          outputStream = this.native.fs.createWriteStream( options.output )
        } else {
          outputStream = process.stdout
        }
        outputStream.write( outputCss )
      } catch (e) {
        this.fatal('Could not write to output stream.')
      }

    }
  }

  if (cli.args.length) {
    cli.withInput( cli.args.shift(), handleInput )
  } else {
    cli.withInput( handleInput )
  }

})<|endoftext|>


<commit_before>var postcss = require('postcss');
var find = require('array-find');
var referenceableNodes = [];

module.exports = postcss.plugin('postcss-reference', function (opts) {
    opts = opts || {
        debug: false
    };

    // Work with options here

    var referenceRules = [];
    var findReferenceableRules = function findReferenceableRules(css) {
        // Walk through list of rules in @reference blocks, push them into the
        // referenceRules array and then remove them from the AST so they don't
        // get output to the compiled CSS unless matched.
        css.walkAtRules('reference', function(atRule) {
            if (atRule.parent.name === 'media') {
                console.log('found it');
            }
            atRule.walkRules(function(rule) {
                referenceRules.push(rule);
            });

            atRule.remove();
        });
    };

    var sortResults = function sortResults(array) {
        // sort relationships alphabetically in descending order so
        // they will properly append after the original rule
        array.sort(function (a, b) {

            if (a < b) {
                return 1;
            }
            if (a > b) {
                return -1;
            }
            // a must be equal to b
            return 0;
        });
    };

    var findReferences = function findReferences(css) {
        // Now that our @reference blocks have been processed
        // Walk through our rules looking for @references declarations
        css.walkRules(function(rule) {
            // TODO :: if rule's selector has a pseudoclass, prepend matches to
            // the rule

            rule.walk(function(node) {

                if (node.type === 'atrule' &&
                    node.name === 'references') {

                    // extract our @references() contents and split selectors into an array
                    var terms = node.params.split(',');

                    // check our reference array for any of our terms
                    var matches = matchReferences(referenceRules, terms);

                    // TODO :: spin this out into separate function so it can be reused for mqMatching
                    // if referenced and referencing rules have declarations
                    // with of same property, defer to the referencing rule
                    rule.walkDecls(function(decl) {
                        matches.decls.forEach(function(match, d, matchedDecls) {
                            if (decl.prop === match.prop) {
                                matchedDecls.splice(d, 1);
                            }
                        });
                    });

                    for (var m in matches.decls) {
                        rule.insertBefore(node, matches.decls[m]);
                    }

                    // sort results so they output in the original order referenced
                    if (matches.relationships.length) {
                        sortResults(matches.relationships);
                    }

                    matches.relationships.forEach(function(newRule) {
                        css.insertAfter(rule, newRule);
                    });

                    node.remove();
                }
            });
        });
    };

    var testExactMatch = function testExactMatch(item, array, prop) {
        debugger;
        obj.selectors.filter(function(ref) {
            array.forEach(function (obj) {
                if (item === obj[prop]) {
                    return true;
                }
            });

            return false;
        });
    };

    var testRelationExistsIn = function testSelectorExistsIn(item, array, prop) {
        var value = false;

        array.forEach(function (obj) {
            if (item.indexOf(obj[prop]) === 0) {
                value = true;
            }
        });

        return value;
    };

    var extractMatchingDecls = function extractMatchingDecls(matchArray, rule) {

        rule.walkDecls(function(decl) {
            var dup = null;

            // check for duplicates in our list of matches
            dup = findDuplicates(matchArray, decl, "prop");

            if (dup !== null) {
                // if it's a dupe, replace existing rule
                matchArray[dup].replaceWith(decl);
            } else {
                // otherwise add to the declarations list
                matchArray.push(decl);
            }
        });
    };

    var extractMatchingRelationships = function extractMatchingRelationships(matchArray, rule) {

        if (!matchArray.length) {
            matchArray.push(rule);
        } else {
            matchArray.forEach(function(match) {
                var dup = null;

                dup = findDuplicates(matchArray, rule, "selector");

                if (dup !== null) {
                    // walk through each decl in rule and discard all matching decls
                    // from dup before merging remaining decls
                    rule.walkDecls(function(decl) {
                        var dupDecl = findDuplicates(matchArray[dup].nodes, rule.nodes[decl], "prop");

                        matchArray[dup].nodes[dupDecl].remove();
                    });
                } else {
                    // otherwise add to the declarations list
                    matchArray.push(rule);
                }
            });
        }
    };

    var findDuplicates = function findDuplicates(matchArray, node, childParam) {
        var dup = null;

        find(matchArray, function(match, index, array) {
            if (match[childParam] === node[childParam]) {
                dup = index;
            }
        });

        return dup;
    };

    // var handleExactMatches = function handleExactMatches(obj, objParam, termsArray, destination) {
    //     obj.selectors.filter(function(ref) {
    //         var hasRelation = testRelationExistsIn(ref, termsArray, objParam);
    //
    //         if (hasRelation) {
    //             destination.push(ref.trim());
    //         }
    //     });
    // };

    var handleRelationshipMatches = function handleRelationshipMatches(obj, matchedRefSelArray, termsArray, declDest, ruleDest) {
        matchedRefSelArray.forEach(function(selector, index, selectors) {

            termsArray.forEach(function(term, tindex, terms) {
                // var flagAll = (term.indexOf(" all") !== -1);
                var tmpSelectorsArray = selectors;

                // if it's an exact match already in the matches references obj...
                if (term.name === selector) {
                    // just merge up the declarations of the successfully
                    // referenced rule
                    extractMatchingDecls(declDest, obj);

                } else if (obj.selector.indexOf(term.name) === 0 && term.all) {
                    // otherwise, if the it's not an explicit match, but the 'all' flag is set
                    // and the selector describes a relationships to the term, gather
                    // those references for our matches array
                    // i.e. prevent matches with .button like .button-primary, but allow
                    // matches like .button .primary, .button.primary, or .button > .primary
                    var safeChars = [" ", ".", "#", "+", "~", ">", ":"];

                    if (obj.selector.length > term.name.length &&
                        safeChars.indexOf(obj.selector.charAt(term.name.length)) === 0) {
                            extractMatchingRelationships(ruleDest, obj);
                    }
                }
            });
        });
    };

    var matchReferences = function matchReferences(referenceRules, terms) {
        var matches = {
            decls: [],
            relationships: [],
            mqDecls: {
                mediaQuery: null,
                nodes: []
            },
            mqRelationships: {
                mediaQuery: null,
                nodes: []
            }
        };

        // terms and params are a string at this point.  Convert to an array of
        // well defined objects for cleaner processing
        var processedTerms = [];

        terms.forEach(function(term) {
            var obj = {
                all: false,
                mq: null,
                name: null
            };

            obj.all = (term.indexOf(" all") !== -1);
            // strip out any params from term now that flags are set
            // (only 'all' for now)
            term = term.replace(" all", '');

            // clean any whitespaces which might surround commas after param
            // extraction and assign the term to obj.name
            obj.name = term.trim();

            processedTerms.push(obj);
        });

        referenceRules.forEach(function (reference, index, references) {
            // Strip out any selectors in our current reference rule which don't match
            // any of our requested terms
            var matchedRefSelectors = [];
            var isMatch = testExactMatch(reference, processedTerms, "name");
            var hasRelation = testRelationExistsIn(reference, processedTerms, "name");

            if (isMatch) {
                handleExactMatches(reference, "name", processedTerms, matchedRefSelectors);
            } else if (hasRelation) {
                handleRelationshipMatches(reference, matchedRefSelectors, processedTerms, matches.decls, matches.relationships);
            }
        });

        return matches;
    };

    return function (css, result) {
        findReferenceableRules(css);
        findReferences(css);
    };
});
<commit_msg>retooling matching sequence to strip duplicate matches<commit_after>var postcss = require('postcss');
var find = require('array-find');
var referenceableNodes = [];

module.exports = postcss.plugin('postcss-reference', function (opts) {
    opts = opts || {
        debug: false
    };

    // Work with options here

    var referenceRules = [];
    var findReferenceableRules = function findReferenceableRules(css) {
        // Walk through list of rules in @reference blocks, push them into the
        // referenceRules array and then remove them from the AST so they don't
        // get output to the compiled CSS unless matched.
        css.walkAtRules('reference', function(atRule) {
            if (atRule.parent.name === 'media') {
                console.log('found it');
            }
            atRule.walkRules(function(rule) {
                referenceRules.push(rule);
            });

            atRule.remove();
        });
    };

    var sortResults = function sortResults(array) {
        // sort relationships alphabetically in descending order so
        // they will properly append after the original rule
        array.sort(function (a, b) {

            if (a < b) {
                return 1;
            }
            if (a > b) {
                return -1;
            }
            // a must be equal to b
            return 0;
        });
    };

    var findReferences = function findReferences(css) {
        // Now that our @reference blocks have been processed
        // Walk through our rules looking for @references declarations
        css.walkRules(function(rule) {
            // TODO :: if rule's selector has a pseudoclass, prepend matches to
            // the rule

            rule.walk(function(node) {

                if (node.type === 'atrule' &&
                    node.name === 'references') {

                    // extract our @references() contents and split selectors into an array
                    var terms = node.params.split(',');

                    // check our reference array for any of our terms
                    var matches = matchReferences(referenceRules, terms);

                    // TODO :: spin this out into separate function so it can be reused for mqMatching
                    // if referenced and referencing rules have declarations
                    // with of same property, defer to the referencing rule
                    rule.walkDecls(function(decl) {
                        matches.decls.forEach(function(match, d, matchedDecls) {
                            if (decl.prop === match.prop) {
                                matchedDecls.splice(d, 1);
                            }
                        });
                    });

                    for (var m in matches.decls) {
                        rule.insertBefore(node, matches.decls[m]);
                    }

                    // sort results so they output in the original order referenced
                    if (matches.relationships.length) {
                        sortResults(matches.relationships);
                    }

                    matches.relationships.forEach(function(newRule) {
                        css.insertAfter(rule, newRule);
                    });

                    node.remove();
                }
            });
        });
    };

    var extractMatchingDecls = function extractMatchingDecls(matchArray, rule) {

        rule.walkDecls(function(decl) {
            var dup = null;

            // check for duplicates in our list of matches
            dup = findDuplicates(matchArray, decl, "prop");

            if (dup !== null) {
                // if it's a dupe, replace existing rule
                matchArray[dup].replaceWith(decl);
            } else {
                // otherwise add to the declarations list
                matchArray.push(decl);
            }
        });
    };

    var extractMatchingRelationships = function extractMatchingRelationships(matchArray, rule) {

        if (!matchArray.length) {
            matchArray.push(rule);
        } else {
            matchArray.forEach(function(match) {
                var dup = null;

                dup = findDuplicates(matchArray, rule, "selector");

                if (dup !== null) {
                    // walk through each decl in rule and discard all matching decls
                    // from dup before merging remaining decls
                    rule.walkDecls(function(decl) {
                        var dupDecl = findDuplicates(matchArray[dup].nodes, rule.nodes[decl], "prop");

                        matchArray[dup].nodes[dupDecl].remove();
                    });
                } else {
                    // otherwise add to the declarations list
                    matchArray.push(rule);
                }
            });
        }
    };

    var findDuplicates = function findDuplicates(matchArray, node, childParam) {
        var dup = null;

        find(matchArray, function(match, index, array) {
            if (match[childParam] === node[childParam]) {
                dup = index;
            }
        });

        return dup;
    };

    var testRelationExistsIn = function testSelectorExistsIn(ref, terms, prop) {
        var value = false;

        terms.forEach(function (term) {
            if (ref.indexOf(term[prop]) === 0) {
                value = true;
            }
        });

        return value;
    };

    var handleExactMatches = function handleExactMatches(obj, objParam, termsArray, destination) {
        obj.selectors.filter(function(ref) {
            termsArray.forEach(function (term, index, array) {
                if (ref === term[objParam]) {
                    // TODO :: pass obj to extractMatchingDecls instead of pushing to the refSelectorArray
                    // move trim to ref being compared
                    destination.push(ref.trim());
                    array.splice(index, 1);
                }
            });
        });
    };

    var handleRelationshipMatches = function handleRelationshipMatches(obj, matchedRefSelArray, termsArray, declDest, ruleDest) {
        matchedRefSelArray.forEach(function(selector, index, selectors) {

            termsArray.forEach(function(term, tindex, terms) {
                // var flagAll = (term.indexOf(" all") !== -1);
                var tmpSelectorsArray = selectors;

                // if it's an exact match already in the matches references obj...
                if (term.name === selector) {
                    // just merge up the declarations of the successfully
                    // referenced rule
                    extractMatchingDecls(declDest, obj);

                } else if (obj.selector.indexOf(term.name) === 0 && term.all) {
                    // otherwise, if the it's not an explicit match, but the 'all' flag is set
                    // and the selector describes a relationships to the term, gather
                    // those references for our matches array
                    // i.e. prevent matches with .button like .button-primary, but allow
                    // matches like .button .primary, .button.primary, or .button > .primary
                    var safeChars = [" ", ".", "#", "+", "~", ">", ":"];

                    if (obj.selector.length > term.name.length &&
                        safeChars.indexOf(obj.selector.charAt(term.name.length)) === 0) {
                            extractMatchingRelationships(ruleDest, obj);
                    }
                }
            });
        });
    };

    var matchReferences = function matchReferences(referenceRules, terms) {
        var matches = {
            decls: [],
            relationships: [],
            mqDecls: {
                mediaQuery: null,
                nodes: []
            },
            mqRelationships: {
                mediaQuery: null,
                nodes: []
            }
        };

        // terms and params are a string at this point.  Convert to an array of
        // well defined objects for cleaner processing
        var processedTerms = [];

        terms.forEach(function(term) {
            var obj = {
                all: false,
                mq: null,
                name: null
            };

            obj.all = (term.indexOf(" all") !== -1);
            // strip out any params from term now that flags are set
            // (only 'all' for now)
            term = term.replace(" all", '');

            // clean any whitespaces which might surround commas after param
            // extraction and assign the term to obj.name
            obj.name = term.trim();

            processedTerms.push(obj);
        });

        referenceRules.forEach(function (reference, index, references) {
            // Strip out any selectors in our current reference rule which don't match
            // any of our requested terms
            var matchedRefSelectors = [];

            handleExactMatches(reference, "name", processedTerms, matchedRefSelectors);
            handleRelationshipMatches(reference, matchedRefSelectors, processedTerms, matches.decls, matches.relationships);
        });

        return matches;
    };

    return function (css, result) {
        findReferenceableRules(css);
        findReferences(css);
    };
});
<|endoftext|>


<commit_before>var FBdata = require('./src/data');
var renderer = require('./src/renderer');
var nav = require('./src/navigation');
var notification = require('./src/notification');

notification();

var currentPost;

var showOnePost = function(answer) {
  answer = parseInt(answer, 10);
  if (typeof answer === 'number' && !Number.isNaN(answer) && answer < renderer.getNumberOfPosts()) {
    currentPost = answer;
    renderer.post(answer, true);
    showPostMenu();
  } else {
    renderer.all();
    showListMenu();
  }
};

var showListMenu = function() {
  nav.showMenu(
    'Wybierz numer postu do otwarcia lub Ctrl+C aby wyjść',
    showOnePost
  );
};

var onePostAction = function(answer) {
  answer = answer.toLowerCase();
  switch (answer) {
    case 'f':
      require('child_process').exec('open ' + renderer.getPostUrl(currentPost));
      renderer.post(currentPost, true);
      showPostMenu();
      break;
    case 'w':
      currentPost = null;
      renderer.all();
      showListMenu();
      break;
    default:
      renderer.post(currentPost, true);
      showPostMenu();
  }
}

var showPostMenu = function(){
  nav.showMenu(
    "Wybierz 'f' aby zobaczyć post w przeglądarce lub 'w' aby wrócić" ,
    onePostAction
  );
}

FBdata(function(err, data) {
  renderer.setData(data);
  renderer.all();
  showListMenu();
});
<commit_msg>[JSNEWS-CLIENT] - fixed update bug<commit_after>var FBdata = require('./src/data');
var renderer = require('./src/renderer');
var nav = require('./src/navigation');
var notification = require('./src/notification');
var config = require('./src/config');

var currentPost;
var currentCache = '';

var showOnePost = function(answer) {
  answer = parseInt(answer, 10);
  if (typeof answer === 'number' && !Number.isNaN(answer) && answer < renderer.getNumberOfPosts()) {
    currentPost = answer;
    renderer.post(answer, true);
    showPostMenu();
  } else {
    renderer.all();
    showListMenu();
  }
};

var showListMenu = function() {
  nav.showMenu(
    'Wybierz numer postu do otwarcia lub Ctrl+C aby wyjść',
    showOnePost
  );
};

var onePostAction = function(answer) {
  answer = answer.toLowerCase();
  switch (answer) {
    case 'f':
      require('child_process').exec('open ' + renderer.getPostUrl(currentPost));
      renderer.post(currentPost, true);
      showPostMenu();
      break;
    case 'w':
      currentPost = null;
      renderer.all();
      showListMenu();
      break;
    default:
      renderer.post(currentPost, true);
      showPostMenu();
  }
};

var showPostMenu = function(){
  nav.showMenu(
    "Wybierz 'f' aby zobaczyć post w przeglądarce lub 'w' aby wrócić" ,
    onePostAction
  );
}

var render = function(){
  FBdata(function(err, data) {
    setTimeout(render, config.refreshTime);
    if (currentCache === '') {
      // first render, no current cache
      currentCache = JSON.stringify(data);
    } else if (currentCache !== JSON.stringify(data)) {
      // updated! notify!
      currentCache = JSON.stringify(data);
      notification();
    } else if (currentCache === JSON.stringify(data)) {
      return;
    }

    renderer.setData(data);
    renderer.all();
    showListMenu();

    // check for update every config.refreshTime
  });
}

render();
<|endoftext|>


<commit_before>"use strict";
const fs = require("fs");
const methodDeclarationRegex = /(?:\+|\-)\s?\(((?:\w|\<|\>)*)\)(?:\w|\s|\<|\>|\:|\(|\)|\*)*;/g;

// Get Groups for matches
function getNthGroupForMatch(string, regex, index) {
  const matches = [];
  let match;
  while ((match = regex.exec(string))) {
    matches.push(match[index]);
  }
  return matches;
}

const parseClassName = file => {
  const nameRegex = /@interface \w*/i;
  const nameRegexLength = 11;
  return file.match(nameRegex)[0].substr(nameRegexLength);
};

const extractMultiLineComment = (lineIndex, lines) => {
  let i = lineIndex;
  const commentLines = [];

  while (i > 0) {
    i--;

    // is start of multi line string
    if (lines[i].indexOf("/**") !== -1) {
      return commentLines.join("\n");
    }

    // is end of multiline string
    if (lines[i].indexOf("*/") !== -1) {
      continue;
    }

    // is comment line
    if (lines[i].indexOf("*") !== -1) {
      commentLines.unshift(lines[i].replace(/\s*\*\s*/, ""));
    }
  }

  // No comment found
  return "";
};

const parseMethods = file => {
  const lines = file.split("\n");

  return file.match(methodDeclarationRegex).map(methodDeclaration => {
    const matchReturnType = /(?:\+|\-)\s?\(((?:\w|\<|\>)*)\)/;
    const returnType = methodDeclaration.match(matchReturnType);

    const methodBody = methodDeclaration
      .replace(returnType[0], "")
      .replace(";", "");

    const argumentsRegex = /\s?\(((?:\w|\s|\*|\<|\>)*)\)((?:\w)*)\s?/g;
    const rawArgs = [
      getNthGroupForMatch(methodBody, argumentsRegex, 1),
      getNthGroupForMatch(methodBody, argumentsRegex, 2)
    ];

    const name = rawArgs[0].length
      ? methodBody
          .replace(argumentsRegex, "")
          .replace(/\s/g, "")
          .replace(/\(\)/g, "")
      : methodBody;

    const firstMethodLine = methodDeclaration.split("\n")[0];
    const lineIndex = lines.findIndex(line => {
      return firstMethodLine === line;
    });

    const isSingleLineComment = lines[lineIndex - 1].indexOf("//") != -1;
    const comment = isSingleLineComment
      ? lines[lineIndex - 1].replace(/\/\/(?:\s)*/, "")
      : extractMultiLineComment(lineIndex, lines);

    const [argumentTypes, argumentNames] = rawArgs;
    // Both should be the same length
    const args = argumentTypes.length
      ? argumentTypes.map((type, index) => ({
          type,
          name: argumentNames[index]
        }))
      : [];

    return {
      static: methodDeclaration.indexOf("+") !== -1,
      args,
      comment,
      name,
      returnType: returnType[1]
    };
  });
};

const parse = file => {
  return {
    name: parseClassName(file),
    methods: parseMethods(file)
  };
};

module.exports = parse;
<commit_msg>remove unused import<commit_after>"use strict";
const methodDeclarationRegex = /(?:\+|\-)\s?\(((?:\w|\<|\>)*)\)(?:\w|\s|\<|\>|\:|\(|\)|\*)*;/g;

// Get Groups for matches
function getNthGroupForMatch(string, regex, index) {
  const matches = [];
  let match;
  while ((match = regex.exec(string))) {
    matches.push(match[index]);
  }
  return matches;
}

const parseClassName = file => {
  const nameRegex = /@interface \w*/i;
  const nameRegexLength = 11;
  return file.match(nameRegex)[0].substr(nameRegexLength);
};

const extractMultiLineComment = (lineIndex, lines) => {
  let i = lineIndex;
  const commentLines = [];

  while (i > 0) {
    i--;

    // is start of multi line string
    if (lines[i].indexOf("/**") !== -1) {
      return commentLines.join("\n");
    }

    // is end of multiline string
    if (lines[i].indexOf("*/") !== -1) {
      continue;
    }

    // is comment line
    if (lines[i].indexOf("*") !== -1) {
      commentLines.unshift(lines[i].replace(/\s*\*\s*/, ""));
    }
  }

  // No comment found
  return "";
};

const parseMethods = file => {
  const lines = file.split("\n");

  return file.match(methodDeclarationRegex).map(methodDeclaration => {
    const matchReturnType = /(?:\+|\-)\s?\(((?:\w|\<|\>)*)\)/;
    const returnType = methodDeclaration.match(matchReturnType);

    const methodBody = methodDeclaration
      .replace(returnType[0], "")
      .replace(";", "");

    const argumentsRegex = /\s?\(((?:\w|\s|\*|\<|\>)*)\)((?:\w)*)\s?/g;
    const rawArgs = [
      getNthGroupForMatch(methodBody, argumentsRegex, 1),
      getNthGroupForMatch(methodBody, argumentsRegex, 2)
    ];

    const name = rawArgs[0].length
      ? methodBody
          .replace(argumentsRegex, "")
          .replace(/\s/g, "")
          .replace(/\(\)/g, "")
      : methodBody;

    const firstMethodLine = methodDeclaration.split("\n")[0];
    const lineIndex = lines.findIndex(line => {
      return firstMethodLine === line;
    });

    const isSingleLineComment = lines[lineIndex - 1].indexOf("//") != -1;
    const comment = isSingleLineComment
      ? lines[lineIndex - 1].replace(/\/\/(?:\s)*/, "")
      : extractMultiLineComment(lineIndex, lines);

    const [argumentTypes, argumentNames] = rawArgs;
    // Both should be the same length
    const args = argumentTypes.length
      ? argumentTypes.map((type, index) => ({
          type,
          name: argumentNames[index]
        }))
      : [];

    return {
      static: methodDeclaration.indexOf("+") !== -1,
      args,
      comment,
      name,
      returnType: returnType[1]
    };
  });
};

const parse = file => {
  return {
    name: parseClassName(file),
    methods: parseMethods(file)
  };
};

module.exports = parse;
<|endoftext|>


<commit_before>var traverse = module.exports = function (obj) {
    return new Traverse(obj);
};

function Traverse (obj) {
    this.value = obj;
}

Traverse.prototype.get = function (ps) {
    var node = this.value;
    for (var i = 0; i < ps.length; i ++) {
        var key = ps[i];
        if (!Object.hasOwnProperty.call(node, key)) {
            node = undefined;
            break;
        }
        node = node[key];
    }
    return node;
};

Traverse.prototype.has = function (ps) {
    var node = this.value;
    for (var i = 0; i < ps.length; i ++) {
        var key = ps[i];
        if (!Object.hasOwnProperty.call(node, key)) {
            return false;
        }
        node = node[key];
    }
    return true;
};

Traverse.prototype.set = function (ps, value) {
    var node = this.value;
    for (var i = 0; i < ps.length - 1; i ++) {
        var key = ps[i];
        if (!Object.hasOwnProperty.call(node, key)) node[key] = {};
        node = node[key];
    }
    node[ps[i]] = value;
    return value;
};

Traverse.prototype.map = function (cb) {
    return walk(this.value, cb, true);
};

Traverse.prototype.forEach = function (cb) {
    this.value = walk(this.value, cb, false);
    return this.value;
};

Traverse.prototype.reduce = function (cb, init) {
    var skip = arguments.length === 1;
    var acc = skip ? this.value : init;
    this.forEach(function (x) {
        if (!this.isRoot || !skip) {
            acc = cb.call(this, acc, x);
        }
    });
    return acc;
};

Traverse.prototype.paths = function () {
    var acc = [];
    this.forEach(function (x) {
        acc.push(this.path);
    });
    return acc;
};

Traverse.prototype.nodes = function () {
    var acc = [];
    this.forEach(function (x) {
        acc.push(this.node);
    });
    return acc;
};

Traverse.prototype.clone = function () {
    var parents = [], nodes = [];

    return (function clone (src) {
        for (var i = 0; i < parents.length; i++) {
            if (parents[i] === src) {
                return nodes[i];
            }
        }

        if (typeof src === 'object' && src !== null) {
            var dst = copy(src);

            parents.push(src);
            nodes.push(dst);

            forEach(Object_keys(src), function (key) {
                dst[key] = clone(src[key]);
            });

            parents.pop();
            nodes.pop();
            return dst;
        }
        else {
            return src;
        }
    })(this.value);
};

function walk (root, cb, immutable) {
    var path = [];
    var parents = [];
    var alive = true;

    return (function walker (node_) {
        var node = immutable ? copy(node_) : node_;
        var modifiers = {};

        var keepGoing = true;

        var state = {
            node : node,
            node_ : node_,
            path : [].concat(path),
            parent : parents[parents.length - 1],
            parents : parents,
            key : path.slice(-1)[0],
            isRoot : path.length === 0,
            level : path.length,
            circular : null,
            update : function (x, stopHere) {
                if (!state.isRoot) {
                    state.parent.node[state.key] = x;
                }
                state.node = x;
                if (stopHere) keepGoing = false;
            },
            'delete' : function (stopHere) {
                delete state.parent.node[state.key];
                if (stopHere) keepGoing = false;
            },
            remove : function (stopHere) {
                if (Array_isArray(state.parent.node)) {
                    state.parent.node.splice(state.key, 1);
                }
                else {
                    delete state.parent.node[state.key];
                }
                if (stopHere) keepGoing = false;
            },
            keys : null,
            before : function (f) { modifiers.before = f },
            after : function (f) { modifiers.after = f },
            pre : function (f) { modifiers.pre = f },
            post : function (f) { modifiers.post = f },
            stop : function () { alive = false },
            block : function () { keepGoing = false }
        };

        if (!alive) return state;

        if (typeof node === 'object' && node !== null) {
            state.keys = Object_keys(node);

            state.isLeaf = state.keys.length == 0;

            for (var i = 0; i < parents.length; i++) {
                if (parents[i].node_ === node_) {
                    state.circular = parents[i];
                    break;
                }
            }
        }
        else {
            state.isLeaf = true;
        }

        state.notLeaf = !state.isLeaf;
        state.notRoot = !state.isRoot;

        // use return values to update if defined
        var ret = cb.call(state, state.node);
        if (ret !== undefined && state.update) state.update(ret);

        if (modifiers.before) modifiers.before.call(state, state.node);

        if (!keepGoing) return state;

        if (typeof state.node == 'object'
        && state.node !== null && !state.circular) {
            parents.push(state);

            if (!state.keys) state.keys = Object_keys(state.node);

            forEach(state.keys, function (key, i) {
                path.push(key);

                if (modifiers.pre) modifiers.pre.call(state, state.node[key], key);

                var child = walker(state.node[key]);
                if (immutable && Object.hasOwnProperty.call(state.node, key)) {
                    state.node[key] = child.node;
                }

                child.isLast = i == state.keys.length - 1;
                child.isFirst = i == 0;

                if (modifiers.post) modifiers.post.call(state, child);

                path.pop();
            });
            parents.pop();
        }

        if (modifiers.after) modifiers.after.call(state, state.node);

        return state;
    })(root).node;
}

function copy (src) {
    if (typeof src === 'object' && src !== null) {
        var dst;

        if (Array_isArray(src)) {
            dst = [];
        }
        else if (isDate(src)) {
            dst = new Date(src);
        }
        else if (isRegExp(src)) {
            dst = new RegExp(src);
        }
        else if (isError(src)) {
            dst = { message: src.message };
        }
        else if (isBoolean(src)) {
            dst = new Boolean(src);
        }
        else if (isNumber(src)) {
            dst = new Number(src);
        }
        else if (isString(src)) {
            dst = new String(src);
        }
        else if (Object.create && Object.getPrototypeOf) {
            dst = Object.create(Object.getPrototypeOf(src));
        }
        else if (src.__proto__ || src.constructor.prototype) {
            var proto = src.__proto__ || src.constructor.prototype || {};
            var T = function () {};
            T.prototype = proto;
            dst = new T;
            if (!dst.__proto__) dst.__proto__ = proto;
        }

        forEach(Object_keys(src), function (key) {
            dst[key] = src[key];
        });
        return dst;
    }
    else return src;
}

var Object_keys = Object.keys || function keys (obj) {
    var res = [];
    for (var key in obj) res.push(key)
    return res;
};

function toS (obj) { return Object.prototype.toString.call(obj) }
function isDate (obj) { return toS(obj) === '[object Date]' }
function isRegExp (obj) { return toS(obj) === '[object RegExp]' }
function isError (obj) { return toS(obj) === '[object Error]' }
function isBoolean (obj) { return toS(obj) === '[object Boolean]' }
function isNumber (obj) { return toS(obj) === '[object Number]' }
function isString (obj) { return toS(obj) === '[object String]' }

var Array_isArray = Array.isArray || function isArray (xs) {
    return Object.prototype.toString.call(xs) === '[object Array]';
};

var forEach = function (xs, fn) {
    if (xs.forEach) return xs.forEach(fn)
    else for (var i = 0; i < xs.length; i++) {
        fn(xs[i], i, xs);
    }
};

forEach(Object_keys(Traverse.prototype), function (key) {
    traverse[key] = function (obj) {
        var args = [].slice.call(arguments, 1);
        var t = new Traverse(obj);
        return t[key].apply(t, args);
    };
});
<commit_msg>Update state with the current node before recursing<commit_after>var traverse = module.exports = function (obj) {
    return new Traverse(obj);
};

function Traverse (obj) {
    this.value = obj;
}

Traverse.prototype.get = function (ps) {
    var node = this.value;
    for (var i = 0; i < ps.length; i ++) {
        var key = ps[i];
        if (!Object.hasOwnProperty.call(node, key)) {
            node = undefined;
            break;
        }
        node = node[key];
    }
    return node;
};

Traverse.prototype.has = function (ps) {
    var node = this.value;
    for (var i = 0; i < ps.length; i ++) {
        var key = ps[i];
        if (!Object.hasOwnProperty.call(node, key)) {
            return false;
        }
        node = node[key];
    }
    return true;
};

Traverse.prototype.set = function (ps, value) {
    var node = this.value;
    for (var i = 0; i < ps.length - 1; i ++) {
        var key = ps[i];
        if (!Object.hasOwnProperty.call(node, key)) node[key] = {};
        node = node[key];
    }
    node[ps[i]] = value;
    return value;
};

Traverse.prototype.map = function (cb) {
    return walk(this.value, cb, true);
};

Traverse.prototype.forEach = function (cb) {
    this.value = walk(this.value, cb, false);
    return this.value;
};

Traverse.prototype.reduce = function (cb, init) {
    var skip = arguments.length === 1;
    var acc = skip ? this.value : init;
    this.forEach(function (x) {
        if (!this.isRoot || !skip) {
            acc = cb.call(this, acc, x);
        }
    });
    return acc;
};

Traverse.prototype.paths = function () {
    var acc = [];
    this.forEach(function (x) {
        acc.push(this.path);
    });
    return acc;
};

Traverse.prototype.nodes = function () {
    var acc = [];
    this.forEach(function (x) {
        acc.push(this.node);
    });
    return acc;
};

Traverse.prototype.clone = function () {
    var parents = [], nodes = [];

    return (function clone (src) {
        for (var i = 0; i < parents.length; i++) {
            if (parents[i] === src) {
                return nodes[i];
            }
        }

        if (typeof src === 'object' && src !== null) {
            var dst = copy(src);

            parents.push(src);
            nodes.push(dst);

            forEach(Object_keys(src), function (key) {
                dst[key] = clone(src[key]);
            });

            parents.pop();
            nodes.pop();
            return dst;
        }
        else {
            return src;
        }
    })(this.value);
};

function walk (root, cb, immutable) {
    var path = [];
    var parents = [];
    var alive = true;

    return (function walker (node_) {
        var node = immutable ? copy(node_) : node_;
        var modifiers = {};

        var keepGoing = true;

        var state = {
            node : node,
            node_ : node_,
            path : [].concat(path),
            parent : parents[parents.length - 1],
            parents : parents,
            key : path.slice(-1)[0],
            isRoot : path.length === 0,
            level : path.length,
            circular : null,
            update : function (x, stopHere) {
                if (!state.isRoot) {
                    state.parent.node[state.key] = x;
                }
                state.node = x;
                if (stopHere) keepGoing = false;
            },
            'delete' : function (stopHere) {
                delete state.parent.node[state.key];
                if (stopHere) keepGoing = false;
            },
            remove : function (stopHere) {
                if (Array_isArray(state.parent.node)) {
                    state.parent.node.splice(state.key, 1);
                }
                else {
                    delete state.parent.node[state.key];
                }
                if (stopHere) keepGoing = false;
            },
            keys : null,
            before : function (f) { modifiers.before = f },
            after : function (f) { modifiers.after = f },
            pre : function (f) { modifiers.pre = f },
            post : function (f) { modifiers.post = f },
            stop : function () { alive = false },
            block : function () { keepGoing = false }
        };

        if (!alive) return state;

        function updateState() {
            if (typeof state.node === 'object' && state.node !== null) {
                state.keys = Object_keys(state.node);

                state.isLeaf = state.keys.length == 0;

                for (var i = 0; i < parents.length; i++) {
                    if (parents[i].node_ === node_) {
                        state.circular = parents[i];
                        break;
                    }
                }
            }
            else {
                state.isLeaf = true;
            }

            state.notLeaf = !state.isLeaf;
            state.notRoot = !state.isRoot;
        }

        updateState();

        // use return values to update if defined
        var ret = cb.call(state, state.node);
        if (ret !== undefined && state.update) state.update(ret);

        if (modifiers.before) modifiers.before.call(state, state.node);

        if (!keepGoing) return state;

        if (typeof state.node == 'object'
        && state.node !== null && !state.circular) {
            parents.push(state);

            updateState();

            forEach(state.keys, function (key, i) {
                path.push(key);

                if (modifiers.pre) modifiers.pre.call(state, state.node[key], key);

                var child = walker(state.node[key]);
                if (immutable && Object.hasOwnProperty.call(state.node, key)) {
                    state.node[key] = child.node;
                }

                child.isLast = i == state.keys.length - 1;
                child.isFirst = i == 0;

                if (modifiers.post) modifiers.post.call(state, child);

                path.pop();
            });
            parents.pop();
        }

        if (modifiers.after) modifiers.after.call(state, state.node);

        return state;
    })(root).node;
}

function copy (src) {
    if (typeof src === 'object' && src !== null) {
        var dst;

        if (Array_isArray(src)) {
            dst = [];
        }
        else if (isDate(src)) {
            dst = new Date(src);
        }
        else if (isRegExp(src)) {
            dst = new RegExp(src);
        }
        else if (isError(src)) {
            dst = { message: src.message };
        }
        else if (isBoolean(src)) {
            dst = new Boolean(src);
        }
        else if (isNumber(src)) {
            dst = new Number(src);
        }
        else if (isString(src)) {
            dst = new String(src);
        }
        else if (Object.create && Object.getPrototypeOf) {
            dst = Object.create(Object.getPrototypeOf(src));
        }
        else if (src.__proto__ || src.constructor.prototype) {
            var proto = src.__proto__ || src.constructor.prototype || {};
            var T = function () {};
            T.prototype = proto;
            dst = new T;
            if (!dst.__proto__) dst.__proto__ = proto;
        }

        forEach(Object_keys(src), function (key) {
            dst[key] = src[key];
        });
        return dst;
    }
    else return src;
}

var Object_keys = Object.keys || function keys (obj) {
    var res = [];
    for (var key in obj) res.push(key)
    return res;
};

function toS (obj) { return Object.prototype.toString.call(obj) }
function isDate (obj) { return toS(obj) === '[object Date]' }
function isRegExp (obj) { return toS(obj) === '[object RegExp]' }
function isError (obj) { return toS(obj) === '[object Error]' }
function isBoolean (obj) { return toS(obj) === '[object Boolean]' }
function isNumber (obj) { return toS(obj) === '[object Number]' }
function isString (obj) { return toS(obj) === '[object String]' }

var Array_isArray = Array.isArray || function isArray (xs) {
    return Object.prototype.toString.call(xs) === '[object Array]';
};

var forEach = function (xs, fn) {
    if (xs.forEach) return xs.forEach(fn)
    else for (var i = 0; i < xs.length; i++) {
        fn(xs[i], i, xs);
    }
};

forEach(Object_keys(Traverse.prototype), function (key) {
    traverse[key] = function (obj) {
        var args = [].slice.call(arguments, 1);
        var t = new Traverse(obj);
        return t[key].apply(t, args);
    };
});
<|endoftext|>


<commit_before>/*global angular, Blob, URL */

(function () {
  'use strict';

  angular.module('angular.img', [])
    .directive('httpSrc', ['$http', function ($http) {
      return {
        // do not share scope with sibling img tags and parent
        // (prevent show same images on img tag)
        scope: {
          httpSrc: '@'
        },
        link: function ($scope, elem, attrs) {
          function revokeObjectURL() {
            if ($scope.objectURL) {
              URL.revokeObjectURL($scope.objectURL);
            }
          }

          $scope.$watch('objectURL', function (objectURL) {
            elem.attr('src', objectURL);
          });

          $scope.$on('$destroy', function () {
            revokeObjectURL();
          });

          attrs.$observe('httpSrc', function (url) {
            revokeObjectURL();

            if (url && url.indexOf('data:') === 0) {
              $scope.objectURL = url;
            } else if (url) {
              $http.get(url, { responseType: 'arraybuffer' })
                .then(function (response) {
                  var blob = new Blob(
                    [response.data], { type: response.headers('Content-Type') }
                  );
                  $scope.objectURL = URL.createObjectURL(blob);
                });
            }
          });
        }
      };
    }]);

})();
<commit_msg>resolve conflict with 656f4239d711c81f7f853905ec8a94d522adb8ce<commit_after>/*global angular, Blob, URL */

(function () {
  'use strict';

  angular.module('angular.img', [])
    .directive('httpSrc', ['$http', function ($http) {
      return {
        // do not share scope with sibling img tags and parent
        // (prevent show same images on img tag)
        scope: {
          httpSrc: '@'
        },
        link: function ($scope, elem, attrs) {
          function revokeObjectURL() {
            if ($scope.objectURL) {
              URL.revokeObjectURL($scope.objectURL);
            }
          }

          $scope.$watch('objectURL', function (objectURL) {
            elem.attr('src', objectURL);
          });

          $scope.$on('$destroy', function () {
            revokeObjectURL();
          });

          attrs.$observe('httpSrc', function (url) {
            revokeObjectURL();

            if (url && url.indexOf('data:') === 0) {
              $scope.objectURL = url;
            } else if (url) {
              $http.get(url, {
                  responseType: 'arraybuffer'
                  headers: {
                    'accept': 'image/webp,image/*,*/*;q=0.8'
                  }
                })
                .then(function (response) {
                  var blob = new Blob(
                    [response.data], { type: response.headers('Content-Type') }
                  );
                  $scope.objectURL = URL.createObjectURL(blob);
                });
            }
          });
        }
      };
    }]);
})();
<|endoftext|>


<commit_before>'use strict';

// ## dependencies
//
var util = require('./lib/util');

// ## exports
//
exports = module.exports = Manifold;

// # Manifold constructor
//
// arguments
//  - `opt` type `Object` optional
//
// returns
//  - manifold instance
//
function Manifold(o){

  if(!(this instanceof Manifold)){
    return new Manifold(o);
  }

  o = o || { };
  this.parth = new util.Parth();
  this.store = {
    name: util.type(o.name).string || '#rootNode',
    depth: 0
  };

  // ## manifold.parse(name[, parser])
  // > premise: general purpose parsers go here
  //
  // arguments
  //  - `name` type `string`
  //  - `parser` type `function` optional
  //
  // return
  //  - `parser` function if arguments < 2
  //  - `this` otherwise
  //

  this.parse = function (name, parser){
    if(arguments.length < 2){
      return this.parse.prop[name] || util.parse;
    }

    if(typeof prop !== 'string' && typeof parser !== 'function'){
      name = JSON.stringify(name);
      throw new util.Error(
        ' While setting `'+name+'` at this.parse(prop[, parser]):\n' +
        ' > `prop` should be a string and, if given, `parser` a function');
    }

    var self = this;
    this.parse.prop[name] = function(/* arguments */){
      return parser.apply(self, arguments) || { };
    };

    return this;
  };
  this.parse.prop = Object.create(null);
}

// ## Manifold.set
// > premise: set relaxed, get fast
//
// arguments
//  - `stems` types `string`, `array`, `function` or `object`
//  - optional: `o` types `object` or `function`
//
// return `this`
//

Manifold.prototype.set = function(stems, opt){
  var stemsIs = util.type(stems);
  if( !stemsIs.match(/function|string|array|object/g) ){
   throw new util.Error('set(stems [,options]) \n'+
     '> stems should be: `string`, `array`, `function` or `object`');
  }

  var optIs = util.type(opt);
  opt = optIs.plainObject || stemsIs.plainObject || { };
  opt.handle = stemsIs.function || optIs.function;

  stems = (this.parth.set(stems) || '').argv || [ ];
  var node = this.store, parent = this.store;
  stems.forEach(function createChildren(stem){
    // ensure node existence
    if(!node.children){ node.children = { }; }
    if(!node.children[stem]){
      node.children[stem] = {
        path: util.fold((node.path || '') + ' ' + stem),
        depth: node.depth + 1,
        parent: node.path || this.store.name
      };
    }
    parent = node;
    node = node.children[stem];
  }, this);

  // props of last node from its parent using options
  Object.keys(opt).forEach(function parseProps(name){
    var value = util.clone(opt[name], true);
    if(value === void 0){ return ; }
    if(this.parse.prop[name]){
      return this.parse(name)(parent, stems.slice(), value);
    }

    node[name] = node[name] || { };
    if(util.type(value).plainObject){
      util.merge(node[name], value);
    } else { node[name] = value; }

  }, this);

  return this;
};

// ## Manifold.get(stems[, opt])
// > take a string or array, return the matching object
//
// arguments
//  - `stems` type `string` or `array`
//  - `opt` type `object` optional holding all extra information
//
// return
//  - `found` node
// --
// api.public
// --
//
Manifold.prototype.get = function(stems, opt){
  var stem, index, found;
  opt = opt || util.type(stems).plainObject || { };

  index = 0;
  stems = this.parth.get(stems, opt) || opt;
  if(!stems.argv){ index = -1; }
  stems = stems.argv;

  found = this.store;
  while(index > -1){ // always failback
    stem = stems[index];
    if(found.children && found.children[stem]){
      found = found.children[stem]; index++;
    } else { index = -1; }
  }

  if(opt.ref){ return found; }

  util.merge(opt, found);
  delete opt.children;
  return util.clone(opt, true);
};
<commit_msg>#get should check both stems and opt.argv existence<commit_after>'use strict';

// ## dependencies
//
var util = require('./lib/util');

// ## exports
//
exports = module.exports = Manifold;

// # Manifold constructor
//
// arguments
//  - `opt` type `Object` optional
//
// returns
//  - manifold instance
//
function Manifold(o){

  if(!(this instanceof Manifold)){
    return new Manifold(o);
  }

  o = o || { };
  this.parth = new util.Parth();
  this.store = {
    name: util.type(o.name).string || '#rootNode',
    depth: 0
  };

  // ## manifold.parse(name[, parser])
  // > premise: general purpose parsers go here
  //
  // arguments
  //  - `name` type `string`
  //  - `parser` type `function` optional
  //
  // return
  //  - `parser` function if arguments < 2
  //  - `this` otherwise
  //

  this.parse = function (name, parser){
    if(arguments.length < 2){
      return this.parse.prop[name] || util.parse;
    }

    if(typeof prop !== 'string' && typeof parser !== 'function'){
      name = JSON.stringify(name);
      throw new util.Error(
        ' While setting `'+name+'` at this.parse(prop[, parser]):\n' +
        ' > `prop` should be a string and, if given, `parser` a function');
    }

    var self = this;
    this.parse.prop[name] = function(/* arguments */){
      return parser.apply(self, arguments) || { };
    };

    return this;
  };
  this.parse.prop = Object.create(null);
}

// ## Manifold.set
// > premise: set relaxed, get fast
//
// arguments
//  - `stems` types `string`, `array`, `function` or `object`
//  - optional: `o` types `object` or `function`
//
// return `this`
//

Manifold.prototype.set = function(stems, opt){
  var stemsIs = util.type(stems);
  if( !stemsIs.match(/function|string|array|object/g) ){
   throw new util.Error('set(stems [,options]) \n'+
     '> stems should be: `string`, `array`, `function` or `object`');
  }

  var optIs = util.type(opt);
  opt = optIs.plainObject || stemsIs.plainObject || { };
  opt.handle = stemsIs.function || optIs.function;

  stems = (this.parth.set(stems) || '').argv || [ ];
  var node = this.store, parent = this.store;
  stems.forEach(function createChildren(stem){
    // ensure node existence
    if(!node.children){ node.children = { }; }
    if(!node.children[stem]){
      node.children[stem] = {
        path: util.fold((node.path || '') + ' ' + stem),
        depth: node.depth + 1,
        parent: node.path || this.store.name
      };
    }
    parent = node;
    node = node.children[stem];
  }, this);

  // props of last node from its parent using options
  Object.keys(opt).forEach(function parseProps(name){
    var value = util.clone(opt[name], true);
    if(value === void 0){ return ; }
    if(this.parse.prop[name]){
      return this.parse(name)(parent, stems.slice(), value);
    }

    node[name] = node[name] || { };
    if(util.type(value).plainObject){
      util.merge(node[name], value);
    } else { node[name] = value; }

  }, this);

  return this;
};

// ## Manifold.get(stems[, opt])
// > take a string or array, return the matching object
//
// arguments
//  - `stems` type `string` or `array`
//  - `opt` type `object` optional holding all extra information
//
// return
//  - `found` node
// --
// api.public
// --
//
Manifold.prototype.get = function(stems, opt){
  var stem, index, found;
  opt = opt || util.type(stems).plainObject || { };

  index = 0;
  stems = this.parth.get(stems, opt);
  if(!stems && !opt.argv){ index = -1; }
  stems = (stems || opt).argv;

  found = this.store;
  while(index > -1){ // always failback
    stem = stems[index];
    if(found.children && found.children[stem]){
      found = found.children[stem]; index++;
    } else { index = -1; }
  }

  if(opt.ref){ return found; }

  util.merge(opt, found);
  delete opt.children;
  return util.clone(opt, true);
};
<|endoftext|>