<commit_before>
'use strict';

var should= require('should')
var assert= require('assert')
var path= require('path')
var http= require('http')
var request = require('request');
var connect= require('connect')
var async= require('async')
var _= require('underscore')

var port= 8889
var host = 'localhost'

var FSRoute = require( '..' );

function an_instance(url_path) {
  var fsroute= new_life_router()
  return fsroute({url:'//localhost:3000/'+url_path},{},function () {
    throw new Error('404')
  })
}
function noop ()
{
}

function serve(middleware,requests,done) {
  var server= http.createServer(function(req,res){
    res.send= function(status,body) {
      if (1 == arguments.length) {
        body= status;
        status= 200;
      }
      this.statusCode= status;
      this.end(body);
    }
    middleware(req,res,function(err) {
      if (err) {
        res.statusCode= 500
        res.end(err.toString())
      }
      else {
        res.statusCode= 404
        res.end()
      }
    });
  })
  async.series(requests,function (){
    server.close(function() {
      done();
    });
  })
  server.listen(port)
}

function fullURL(url)
{
  return 'http://localhost:'+port+url;
}

function get(url,expected,done) {
  request.get(fullURL(url), function (error, response, body) {
    response.statusCode.should.equal(200);
    body.should.equal(expected);
    done();
  })
}

function get404(url,done) {
  request.get(fullURL(url), function (error, response, body) {
    response.statusCode.should.equal(404);
    done();
  })
}

function new_testsite_router(roadmap) {
  return new FSRoute(path.join(__dirname,'../testsite'),roadmap)
}
function new_life_router(roadmap) {
  return new FSRoute(path.join(__dirname,'life'),roadmap)
}

function simple_get_test(url,expected,roadmap,done)
{
  if (arguments.length == 3) {
    done= roadmap;
    roadmap= undefined;
  }
  var fsRouter= new_testsite_router(roadmap)
  serve(
    fsRouter.connect_middleware,
    [
      function(cb) {
        get(url,expected,cb)
      },
    ],
    done
  );
}

function get_404_test(url,roadmap,done)
{
  if (arguments.length == 2) {
    done= roadmap;
    roadmap= undefined;
  }
  var fsRouter= new_testsite_router(roadmap)
  serve(
    fsRouter.connect_middleware,
    [
      function(cb) {
        get404(url,cb)
      },
    ],
    done
  );
}

describe( 'FSRoute', function() {
  describe( 'FSRoute()', function() {
    it( 'should be a function', function() {
      assert(_.isFunction(FSRoute))
    } );
    it( 'should return a RequestHandler constructor function', function() {
      var fsRouter= new_life_router()
      fsRouter.RequestHandler.name.should.equal('RequestHandler')
      assert(_.isFunction(fsRouter.RequestHandler))
      fsRouter.should.have.property('connect_middleware')
      fsRouter.should.have.property('connect_error_handler')
      fsRouter.should.have.property('composable_middleware')
      fsRouter.should.have.property('composable_error_handler')
    } );
    it( "should start out with fsroute.left being the url's path (less leading slash)", function() {
      var fsRouter= new_life_router()
      var inst= new fsRouter.RequestHandler({req:{method:'GET',url:'/animals/vertibrates/mammals'}},noop)
      var right= inst.right
      assert(_.isArray(right))
      right.join('/').should.equal('animals/vertibrates/mammals')
    } );
    it( 'should start out with fsroute.right being an empty array', function() {
      var fsRouter= new_life_router()
      var inst= new fsRouter.RequestHandler({req:{method:'GET',url:'/animals/vertibrates/mammals'}},noop)
      var left= inst.left
      assert(_.isArray(left))
      left.length.should.equal(0)
    } );
    it( 'should simply 404 if no handler in code and the path does not exist', function(done) {
      serve(
        new_life_router().connect_middleware,
        [
          function(cb) {
            get404('/fungi',cb)
          },
        ],
        done
      );
    } );
    it( 'should 404 if no handler in code and the resource is not found in the filesystem', function(done) {
      serve(
        new_life_router().connect_middleware,
        [
          function(cb) {
            get404('/fungi',cb)
          },
        ],
        done
      );
    } );
    it( 'should find code at the top level of the code branch', function(done) {
      var roadmap= {
        hello: function (next) {
          this.res.end('world')
        }
      }
      simple_get_test('/hello','world',roadmap,done);
    } );
    it( 'should serve a file from the resource branch and not try to interpret is as javascript', function(done) {
      simple_get_test('/protista.js','includes algae and diatoms',done);
    } );
    it( 'should run method-specific code at the top level of the code branch', function(done) {
      var roadmap= {
        hello: {
          $GET: function (next) {
                  this.res.end('world')
                }
        }
      }
      simple_get_test('/hello','world',roadmap,done);
    } );
    it( 'should not run code that is specific to some other method', function(done) {
      var roadmap= {
        hello: {
          $POST: function (next) {
                  this.res.end('world')
                }
        }
      }
      get_404_test('/hello',roadmap,done);
    } );
    it( 'should automatically descend to the second level of a roadmap', function(done) {
      var roadmap= {
        foo: {
          bar: function (next) {
                  this.res.end('bas')
                }
        }
      }
      simple_get_test('/foo/bar','bas',roadmap,done);
    } );

  } );
} );
<commit_msg>Bring together two FSRoute wrappers that were really the same thing.<commit_after>
'use strict';

var should= require('should')
var assert= require('assert')
var path= require('path')
var http= require('http')
var request = require('request');
var connect= require('connect')
var async= require('async')
var _= require('underscore')

var port= 8889
var host = 'localhost'

var FSRoute = require( '..' );

function an_instance(url_path) {
  var fsroute= new_testsite_router()
  return fsroute({url:'//localhost:3000/'+url_path},{},function () {
    throw new Error('404')
  })
}
function noop ()
{
}

function serve(middleware,requests,done) {
  var server= http.createServer(function(req,res){
    res.send= function(status,body) {
      if (1 == arguments.length) {
        body= status;
        status= 200;
      }
      this.statusCode= status;
      this.end(body);
    }
    middleware(req,res,function(err) {
      if (err) {
        res.statusCode= 500
        res.end(err.toString())
      }
      else {
        res.statusCode= 404
        res.end()
      }
    });
  })
  async.series(requests,function (){
    server.close(function() {
      done();
    });
  })
  server.listen(port)
}

function fullURL(url)
{
  return 'http://localhost:'+port+url;
}

function get(url,expected,done) {
  request.get(fullURL(url), function (error, response, body) {
    response.statusCode.should.equal(200);
    body.should.equal(expected);
    done();
  })
}

function get404(url,done) {
  request.get(fullURL(url), function (error, response, body) {
    response.statusCode.should.equal(404);
    done();
  })
}

function new_testsite_router(roadmap) {
  return new FSRoute(path.join(__dirname,'../testsite'),roadmap)
}

function simple_get_test(url,expected,roadmap,done)
{
  if (arguments.length == 3) {
    done= roadmap;
    roadmap= undefined;
  }
  var fsRouter= new_testsite_router(roadmap)
  serve(
    fsRouter.connect_middleware,
    [
      function(cb) {
        get(url,expected,cb)
      },
    ],
    done
  );
}

function get_404_test(url,roadmap,done)
{
  if (arguments.length == 2) {
    done= roadmap;
    roadmap= undefined;
  }
  var fsRouter= new_testsite_router(roadmap)
  serve(
    fsRouter.connect_middleware,
    [
      function(cb) {
        get404(url,cb)
      },
    ],
    done
  );
}

describe( 'FSRoute', function() {
  describe( 'FSRoute()', function() {
    it( 'should be a function', function() {
      assert(_.isFunction(FSRoute))
    } );
    it( 'should return a RequestHandler constructor function', function() {
      var fsRouter= new_testsite_router()
      fsRouter.RequestHandler.name.should.equal('RequestHandler')
      assert(_.isFunction(fsRouter.RequestHandler))
      fsRouter.should.have.property('connect_middleware')
      fsRouter.should.have.property('connect_error_handler')
      fsRouter.should.have.property('composable_middleware')
      fsRouter.should.have.property('composable_error_handler')
    } );
    it( "should start out with fsroute.left being the url's path (less leading slash)", function() {
      var fsRouter= new_testsite_router()
      var inst= new fsRouter.RequestHandler({req:{method:'GET',url:'/animals/vertibrates/mammals'}},noop)
      var right= inst.right
      assert(_.isArray(right))
      right.join('/').should.equal('animals/vertibrates/mammals')
    } );
    it( 'should start out with fsroute.right being an empty array', function() {
      var fsRouter= new_testsite_router()
      var inst= new fsRouter.RequestHandler({req:{method:'GET',url:'/animals/vertibrates/mammals'}},noop)
      var left= inst.left
      assert(_.isArray(left))
      left.length.should.equal(0)
    } );
    it( 'should simply 404 if no handler in code and the path does not exist', function(done) {
      serve(
        new_testsite_router().connect_middleware,
        [
          function(cb) {
            get404('/fungi',cb)
          },
        ],
        done
      );
    } );
    it( 'should 404 if no handler in code and the resource is not found in the filesystem', function(done) {
      serve(
        new_testsite_router().connect_middleware,
        [
          function(cb) {
            get404('/fungi',cb)
          },
        ],
        done
      );
    } );
    it( 'should find code at the top level of the code branch', function(done) {
      var roadmap= {
        hello: function (next) {
          this.res.end('world')
        }
      }
      simple_get_test('/hello','world',roadmap,done);
    } );
    it( 'should serve a file from the resource branch and not try to interpret is as javascript', function(done) {
      simple_get_test('/protista.js','includes algae and diatoms',done);
    } );
    it( 'should run method-specific code at the top level of the code branch', function(done) {
      var roadmap= {
        hello: {
          $GET: function (next) {
                  this.res.end('world')
                }
        }
      }
      simple_get_test('/hello','world',roadmap,done);
    } );
    it( 'should not run code that is specific to some other method', function(done) {
      var roadmap= {
        hello: {
          $POST: function (next) {
                  this.res.end('world')
                }
        }
      }
      get_404_test('/hello',roadmap,done);
    } );
    it( 'should automatically descend to the second level of a roadmap', function(done) {
      var roadmap= {
        foo: {
          bar: function (next) {
                  this.res.end('bas')
                }
        }
      }
      simple_get_test('/foo/bar','bas',roadmap,done);
    } );

  } );
} );
<|endoftext|>


<commit_before>Polymer({

  is: 'transburger-icon',
  extends: 'button',

  properties: {
    /**
     * Hamburger icon transformation.
     * Possible values: `close`, `arrow-left`, `arrow-right`.
     */
    transformTo: {
      type: String,
      value: 'close',
      observer: '_transformToObserver'
    },

    /**
     * Where to place the hamburger icon when the button has text
     * or other contents inside it.
     * Possible values: `left`, `right`.
     */
    iconPosition: {
      type: String,
      value: 'left',
      reflectToAttribute: true
    },

    /**
     * If true, the second icon will be shown initially.
     */
    active: {
      type: Boolean,
      value: false,
      observer: '_activeObserver'
    },

    /**
     * If true, the icon won't be changed after clicking the button.
     * Use this attribute to change the icon programmatically.
     */
    noTransform: {
      type: Boolean,
      value: false,
      observer: '_noTransformObserver'
    }
  },

  detached: function() {
    if (!this.noTransform) {
      this.unlisten(this, 'click', 'toggleIcon');
    }
  },

  toggleIcon: function() {
    this.active = !this.active;
  },

  _transformToObserver: function() {
    this.$.icon.classList.add('t-icon--' + this.transformTo);
  },

  _activeObserver: function() {
    this.$.icon.classList.toggle('is-active', this.active);
    this.fire('transburger-icon-changed', {
      icon: this.active ? this.transformTo : 'menu'
    });
  },

  _noTransformObserver: function() {
    if (this.noTransform) {
      this.unlisten(this, 'click', 'toggleIcon');
    } else {
      this.listen(this, 'click', 'toggleIcon');
    }
  }
});
<commit_msg>add docs about fired events<commit_after>Polymer({

  is: 'transburger-icon',
  extends: 'button',

  properties: {
    /**
     * Hamburger icon transformation.
     * Possible values: `close`, `arrow-left`, `arrow-right`.
     */
    transformTo: {
      type: String,
      value: 'close',
      observer: '_transformToObserver'
    },

    /**
     * Where to place the hamburger icon when the button has text
     * or other contents inside it.
     * Possible values: `left`, `right`.
     */
    iconPosition: {
      type: String,
      value: 'left',
      reflectToAttribute: true
    },

    /**
     * If true, the second icon will be shown initially.
     */
    active: {
      type: Boolean,
      value: false,
      observer: '_activeObserver'
    },

    /**
     * If true, the icon won't be changed after clicking the button.
     * Use this attribute to change the icon programmatically.
     */
    noTransform: {
      type: Boolean,
      value: false,
      observer: '_noTransformObserver'
    }
  },

  detached: function() {
    if (!this.noTransform) {
      this.unlisten(this, 'click', 'toggleIcon');
    }
  },

  toggleIcon: function() {
    this.active = !this.active;
  },

  _transformToObserver: function() {
    this.$.icon.classList.add('t-icon--' + this.transformTo);
  },

  _activeObserver: function() {
    this.$.icon.classList.toggle('is-active', this.active);
    this.fire('transburger-icon-changed', {
      icon: this.active ? this.transformTo : 'menu'
    });
  },

  _noTransformObserver: function() {
    if (this.noTransform) {
      this.unlisten(this, 'click', 'toggleIcon');
    } else {
      this.listen(this, 'click', 'toggleIcon');
    }
  }

  /**
   * Fired when the icon is changed.
   * @event transburger-icon-changed
   */
});
<|endoftext|>


<commit_before>import {firstImplementer} from '../lib/helpers';

class A {
  one() { return 'a-one'; }
  two() { return 'a-two'; }
}

class B {
  two() { return 'b-two'; }
  three() { return 'b-three'; }
}

describe('firstImplementer', function() {
  const a = new A();
  const b = new B();

  it('calls methods from the first target that has the method', function() {
    const target = firstImplementer(a, b);
    assert.equal(target.one, a.one);
    assert.equal(target.two, a.two);
    assert.equal(target.three, b.three);
  });

  it('reports a combined prototype', function() {
    const target = firstImplementer(a, b);
    const proto = Object.getPrototypeOf(target);
    const obj = Object.create(proto);
    assert.equal(obj.one(), 'a-one');
    assert.equal(obj.two(), 'a-two');
    assert.equal(obj.three(), 'b-three');
  });
});
<commit_msg>Test firstImplementer set and getOwnPropertyDescriptor<commit_after>import {firstImplementer} from '../lib/helpers';

class A {
  one() { return 'a-one'; }
  two() { return 'a-two'; }
}

class B {
  two() { return 'b-two'; }
  three() { return 'b-three'; }
}

describe('firstImplementer', function() {
  const a = new A();
  const b = new B();

  it('calls methods from the first target that has the method', function() {
    const target = firstImplementer(a, b);
    assert.equal(target.one, a.one);
    assert.equal(target.two, a.two);
    assert.equal(target.three, b.three);
  });

  it('reports a combined prototype', function() {
    const target = firstImplementer(a, b);
    const proto = Object.getPrototypeOf(target);
    const obj = Object.create(proto);
    assert.equal(obj.one(), 'a-one');
    assert.equal(obj.two(), 'a-two');
    assert.equal(obj.three(), 'b-three');
  });

  it('sets properties that exist on an implementer on that implementer, and ones that do not on the target', function() {
    const target = firstImplementer(a, b);
    target.one = () => 'new-one';
    assert.equal(a.one(), 'new-one');
    target.three = () => 'new-three';
    assert.notOk(a.three);
    assert.equal(b.three(), 'new-three');
    target.four = () => 'four! ah ah ah';
    assert.notOk(a.four);
    assert.notOk(b.four);
    assert.equal(target.four(), 'four! ah ah ah');
  });

  it('correctly reports getOwnPropertyDescriptor', function() {
    const target = firstImplementer(a, b);
    const descOne = Object.getOwnPropertyDescriptor(target, 'one');
    assert.equal(descOne.value, a.one);
    const descThree = Object.getOwnPropertyDescriptor(target, 'three');
    assert.equal(descThree.value, b.three);
    const descTarget = Object.getOwnPropertyDescriptor(target, '__implementations');
    assert.deepEqual(descTarget.value, [a, b]);
  });
});
<|endoftext|>


<commit_before>var expect = require("chai").expect;
var importController = require(__dirname + "/../server/controllers" + "/import-controller")();

var expectedUnweightedNetwork = {
  genes: [
    { name: "A" },
    { name: "B" },
    { name: "C" },
    { name: "D" }
  ],

  links: [
    { source: 1, target: 0 },
    { source: 1, target: 2 },
    { source: 2, target: 1 }
  ],

  errors: [],
  warnings: [],
  sheetType: "unweighted"
};

var expectedWeightedNetwork = {
  genes: [
    { name: "A" },
    { name: "B" },
    { name: "C" },
    { name: "D" }
  ],

  links: [
    { source: 1, target: 0, value: -0.75 },
    { source: 1, target: 2, value: 0.25 },
    { source: 2, target: 1, value: 0.5 }
  ],

  errors: [],
  warnings: [],
  sheetType: "weighted"
};

var expectedUnweightedNetworkWithCycle = {
  genes: [
    { name: "A" },
    { name: "B" },
    { name: "C" },
    { name: "D" },
    { name: "E" }
  ],

  links: [
    { source: 0, target: 0 },
    { source: 1, target: 0 },
    { source: 1, target: 2 },
    { source: 2, target: 1 },
    { source: 3, target: 3 }
  ],

  errors: [],
  warnings: [],
  sheetType: "unweighted"
};

var expectedWeightedNetworkWithCycle = {
  genes: [
    { name: "A" },
    { name: "B" },
    { name: "C" },
    { name: "D" },
    { name: "E" }
  ],

  links: [
    { source: 0, target: 0, value: 0.875 },
    { source: 1, target: 0, value: -0.75 },
    { source: 1, target: 2, value: 0.25 },
    { source: 2, target: 1, value: 0.5 },
    { source: 3, target: 3, value: -0.375 }
  ],

  errors: [],
  warnings: [],
  sheetType: "weighted"
};

var unweightedTestSif = [
  "A",
  [ "B", "pd", "A", "C" ].join("\t"),
  [ "C", "pd", "B" ].join("\t"),
  "D"
].join("\n") + "\n";

var weightedTestSif = [
  "A",
  [ "B", "-0.75", "A" ].join("\t"),
  [ "B", "0.25", "C" ].join("\t"),
  [ "C", "0.5", "B" ].join("\t"),
  "D"
].join("\n") + "\n";

var inconsistentlyWeightedTestSif = [
  "A",
  [ "B", "-0.75", "A" ].join("\t"),
  [ "B", "pd", "C" ].join("\t"),
  [ "C", "0.5", "B" ].join("\t"),
  "D"
].join("\n") + "\n";

var unweightedTestSifWithCycle = [
  [ "A", "pd", "A" ].join("\t"),
  [ "B", "pd", "A", "C" ].join("\t"),
  [ "C", "pd", "B" ].join("\t"),
  [ "D", "pd", "D" ].join("\t"),
  "E"
].join("\n") + "\n";

var weightedTestSifWithCycle = [
  [ "A", "0.875", "A" ].join("\t"),
  [ "B", "-0.75", "A" ].join("\t"),
  [ "B", "0.25", "C" ].join("\t"),
  [ "C", "0.5", "B" ].join("\t"),
  [ "D", "-0.375", "D" ].join("\t"),
  "E"
].join("\n") + "\n";

var inconsistentlyWeightedTestSifWithCycle = [
  [ "A", "0.875", "A" ].join("\t"),
  [ "B", "-0.75", "A" ].join("\t"),
  [ "B", "0.25", "C" ].join("\t"),
  [ "C", "0.5", "B" ].join("\t"),
  [ "D", "pd", "D" ].join("\t"),
  "E"
].join("\n") + "\n";

describe("Import from SIF", function () {
  it("should import unweighted networks from SIF correctly", function () {
    expect(
      importController.sifToGrnsight(unweightedTestSif)
    ).to.deep.equal(expectedUnweightedNetwork);
  });

  it("should import weighted networks from SIF correctly", function () {
    expect(
      importController.sifToGrnsight(weightedTestSif)
    ).to.deep.equal(expectedWeightedNetwork);
  });

  it("should import inconsistently weighted networks from SIF as unweighted", function () {
    expect(
      importController.sifToGrnsight(inconsistentlyWeightedTestSif)
    ).to.deep.equal(expectedUnweightedNetwork);
  });

  it("should import unweighted networks with cycles from SIF correctly", function () {
    expect(
      importController.sifToGrnsight(unweightedTestSifWithCycle)
    ).to.deep.equal(expectedUnweightedNetworkWithCycle);
  });

  it("should import weighted networks with cycles from SIF correctly", function () {
    expect(
      importController.sifToGrnsight(weightedTestSifWithCycle)
    ).to.deep.equal(expectedWeightedNetworkWithCycle);
  });

  it("should import inconsistently weighted networks with cycles from SIF as unweighted", function () {
    expect(
      importController.sifToGrnsight(inconsistentlyWeightedTestSifWithCycle)
    ).to.deep.equal(expectedUnweightedNetworkWithCycle);
  });
});

var unweightedTestGraphMl = [
  '<?xml version="1.0" encoding="UTF-8"?>',
  '<graphml xmlns="http://graphml.graphdrawing.org/xmlns" ' +
    'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
    'xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns ' +
    'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">',
  '  <graph edgedefault="directed">',
  '    <node id="A"/>',
  '    <node id="B"/>',
  '    <node id="C"/>',
  '    <node id="D"/>',
  '    <edge source="B" target="A"/>',
  '    <edge source="B" target="C"/>',
  '    <edge source="C" target="B"/>',
  '  </graph>',
  '</graphml>'
].join("\n");

var weightedTestGraphMl = [
  '<?xml version="1.0" encoding="UTF-8"?>',
  '<graphml xmlns="http://graphml.graphdrawing.org/xmlns" ' +
    'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
    'xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns ' +
    'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">',
  '  <key id="edge-value-id" for="edge" attr.name="weight" attr.type="double"/>',
  '  <graph edgedefault="directed">',
  '    <node id="A"/>',
  '    <node id="B"/>',
  '    <node id="C"/>',
  '    <node id="D"/>',
  '    <edge source="B" target="A">',
  '      <data key="edge-value-id">-0.75</data>',
  '    </edge>',
  '    <edge source="B" target="C">',
  '      <data key="edge-value-id">0.25</data>',
  '    </edge>',
  '    <edge source="C" target="B">',
  '      <data key="edge-value-id">0.5</data>',
  '    </edge>',
  '  </graph>',
  '</graphml>'
].join("\n");

var unweightedTestGraphMlWithCycle = [
  '<?xml version="1.0" encoding="UTF-8"?>',
  '<graphml xmlns="http://graphml.graphdrawing.org/xmlns" ' +
    'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
    'xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns ' +
    'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">',
  '  <graph edgedefault="directed">',
  '    <node id="A"/>',
  '    <node id="B"/>',
  '    <node id="C"/>',
  '    <node id="D"/>',
  '    <node id="E"/>',
  '    <edge source="A" target="A"/>',
  '    <edge source="B" target="A"/>',
  '    <edge source="B" target="C"/>',
  '    <edge source="C" target="B"/>',
  '    <edge source="D" target="D"/>',
  '  </graph>',
  '</graphml>'
].join("\n");

var weightedTestGraphMlWithCycle = [
  '<?xml version="1.0" encoding="UTF-8"?>',
  '<graphml xmlns="http://graphml.graphdrawing.org/xmlns" ' +
    'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
    'xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns ' +
    'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">',
  '  <key id="edge-value-id" for="edge" attr.name="weight" attr.type="double"/>',
  '  <graph edgedefault="directed">',
  '    <node id="A"/>',
  '    <node id="B"/>',
  '    <node id="C"/>',
  '    <node id="D"/>',
  '    <node id="E"/>',
  '    <edge source="A" target="A">',
  '      <data key="edge-value-id">0.875</data>',
  '    </edge>',
  '    <edge source="B" target="A">',
  '      <data key="edge-value-id">-0.75</data>',
  '    </edge>',
  '    <edge source="B" target="C">',
  '      <data key="edge-value-id">0.25</data>',
  '    </edge>',
  '    <edge source="C" target="B">',
  '      <data key="edge-value-id">0.5</data>',
  '    </edge>',
  '    <edge source="D" target="D">',
  '      <data key="edge-value-id">-0.375</data>',
  '    </edge>',
  '  </graph>',
  '</graphml>'
].join("\n");

describe("Import from GraphML", function () {
  it("should import unweighted networks from GraphML correctly", function () {
    expect(
      importController.graphMlToGrnsight(unweightedTestGraphMl)
    ).to.deep.equal(expectedUnweightedNetwork);
  });

  it("should import weighted networks from GraphML correctly", function () {
    expect(
      importController.graphMlToGrnsight(weightedTestGraphMl)
    ).to.deep.equal(expectedWeightedNetwork);
  });

  it("should import unweighted networks with cycles from GraphML correctly", function () {
    expect(
      importController.graphMlToGrnsight(unweightedTestGraphMlWithCycle)
    ).to.deep.equal(expectedUnweightedNetworkWithCycle);
  });

  it("should import weighted networks with cycles from GraphML correctly", function () {
    expect(
      importController.graphMlToGrnsight(weightedTestGraphMlWithCycle)
    ).to.deep.equal(expectedWeightedNetworkWithCycle);
  });

  it("should issue a warning if edgedefault is not set to 'directed'", function () {
    var EDGE_DEFAULT_NOT_DIRECTED_WARNING = {
      warningCode: "EDGE_DEFAULT_NOT_DIRECTED",
      errorDescription: "GRNsight interprets the graph as directed unconditionally."
    };

    var undirected = unweightedTestGraphMl.replace('edgedefault="directed"', 'edgedefault="undirected"');
    expect(
      importController.graphMlToGrnsight(undirected).warnings
    ).to.deep.equal([EDGE_DEFAULT_NOT_DIRECTED_WARNING]);

    var noEdgedefault = unweightedTestGraphMl.replace('edgedefault="directed"', "");
    expect(
      importController.graphMlToGrnsight(noEdgedefault).warnings
    ).to.deep.equal([EDGE_DEFAULT_NOT_DIRECTED_WARNING]);
  });

  it("should issue a warning if a weighted graph has edges without weights", function () {
    var EDGES_WITHOUT_WEIGHTS_WARNING = {
      warningCode: "EDGES_WITHOUT_WEIGHTS",
      errorDescription: "GRNsight attempted to import the graph as weighted, but some edges did not have a weight."
    };

    var missingWeight = weightedTestGraphMl.replace('<data key="edge-value-id">0.5</data>', "");
    expect(
      importController.graphMlToGrnsight(missingWeight).warnings
    ).to.deep.equal([EDGES_WITHOUT_WEIGHTS_WARNING]);

    var nanWeight = weightedTestGraphMl.replace('<data key="edge-value-id">0.5</data>',
        '<data key="edge-value-id">pizza pizza</data>');
    expect(
      importController.graphMlToGrnsight(nanWeight).warnings
    ).to.deep.equal([EDGES_WITHOUT_WEIGHTS_WARNING]);
  });

  it("should ignore unsupported GraphML features", function () {
    var fs = require("fs");
    var UTF8 = { encoding: "utf-8" };

    fs.readFile(__dirname + "/../test-files/import-samples/hyper.graphml", UTF8, function (error, data) {
      expect(
        importController.graphMlToGrnsight(data)
      ).to.deep.equal({
        genes: [
          { name: "n0" },
          { name: "n1" },
          { name: "n2" },
          { name: "n3" },
          { name: "n4" },
          { name: "n5" },
          { name: "n6" }
        ],

        links: [
          { source: 0, target: 4 }
        ],

        errors: [],
        warnings: [],
        sheetType: "unweighted"
      }); // Look ma, no hyperedges.
    });

    fs.readFile(__dirname + "/../test-files/import-samples/nested.graphml", UTF8, function (error, data) {
      expect(
        importController.graphMlToGrnsight(data)
      ).to.deep.equal({
        genes: [
          { name: "n0" },
          { name: "n1" },
          { name: "n2" },
          { name: "n3" },
          { name: "n4" },
          { name: "n5" },
          { name: "n6" }
        ],

        links: [
          { source: 0, target: 2 },
          { source: 0, target: 1 },
          { source: 1, target: 3 },
          { source: 3, target: 2 },
          { source: 2, target: 4 }
        ],

        errors: [],
        warnings: [],
        sheetType: "unweighted"
      }); // Look ma, no nested graphs (nor edges that refer to them).
    });
  });
});
<commit_msg>SIF tests do not need an empty last line.<commit_after>var expect = require("chai").expect;
var importController = require(__dirname + "/../server/controllers" + "/import-controller")();

var expectedUnweightedNetwork = {
  genes: [
    { name: "A" },
    { name: "B" },
    { name: "C" },
    { name: "D" }
  ],

  links: [
    { source: 1, target: 0 },
    { source: 1, target: 2 },
    { source: 2, target: 1 }
  ],

  errors: [],
  warnings: [],
  sheetType: "unweighted"
};

var expectedWeightedNetwork = {
  genes: [
    { name: "A" },
    { name: "B" },
    { name: "C" },
    { name: "D" }
  ],

  links: [
    { source: 1, target: 0, value: -0.75 },
    { source: 1, target: 2, value: 0.25 },
    { source: 2, target: 1, value: 0.5 }
  ],

  errors: [],
  warnings: [],
  sheetType: "weighted"
};

var expectedUnweightedNetworkWithCycle = {
  genes: [
    { name: "A" },
    { name: "B" },
    { name: "C" },
    { name: "D" },
    { name: "E" }
  ],

  links: [
    { source: 0, target: 0 },
    { source: 1, target: 0 },
    { source: 1, target: 2 },
    { source: 2, target: 1 },
    { source: 3, target: 3 }
  ],

  errors: [],
  warnings: [],
  sheetType: "unweighted"
};

var expectedWeightedNetworkWithCycle = {
  genes: [
    { name: "A" },
    { name: "B" },
    { name: "C" },
    { name: "D" },
    { name: "E" }
  ],

  links: [
    { source: 0, target: 0, value: 0.875 },
    { source: 1, target: 0, value: -0.75 },
    { source: 1, target: 2, value: 0.25 },
    { source: 2, target: 1, value: 0.5 },
    { source: 3, target: 3, value: -0.375 }
  ],

  errors: [],
  warnings: [],
  sheetType: "weighted"
};

var unweightedTestSif = [
  "A",
  [ "B", "pd", "A", "C" ].join("\t"),
  [ "C", "pd", "B" ].join("\t"),
  "D"
].join("\n");

var weightedTestSif = [
  "A",
  [ "B", "-0.75", "A" ].join("\t"),
  [ "B", "0.25", "C" ].join("\t"),
  [ "C", "0.5", "B" ].join("\t"),
  "D"
].join("\n");

var inconsistentlyWeightedTestSif = [
  "A",
  [ "B", "-0.75", "A" ].join("\t"),
  [ "B", "pd", "C" ].join("\t"),
  [ "C", "0.5", "B" ].join("\t"),
  "D"
].join("\n");

var unweightedTestSifWithCycle = [
  [ "A", "pd", "A" ].join("\t"),
  [ "B", "pd", "A", "C" ].join("\t"),
  [ "C", "pd", "B" ].join("\t"),
  [ "D", "pd", "D" ].join("\t"),
  "E"
].join("\n");

var weightedTestSifWithCycle = [
  [ "A", "0.875", "A" ].join("\t"),
  [ "B", "-0.75", "A" ].join("\t"),
  [ "B", "0.25", "C" ].join("\t"),
  [ "C", "0.5", "B" ].join("\t"),
  [ "D", "-0.375", "D" ].join("\t"),
  "E"
].join("\n");

var inconsistentlyWeightedTestSifWithCycle = [
  [ "A", "0.875", "A" ].join("\t"),
  [ "B", "-0.75", "A" ].join("\t"),
  [ "B", "0.25", "C" ].join("\t"),
  [ "C", "0.5", "B" ].join("\t"),
  [ "D", "pd", "D" ].join("\t"),
  "E"
].join("\n");

describe("Import from SIF", function () {
  it("should import unweighted networks from SIF correctly", function () {
    expect(
      importController.sifToGrnsight(unweightedTestSif)
    ).to.deep.equal(expectedUnweightedNetwork);
  });

  it("should import weighted networks from SIF correctly", function () {
    expect(
      importController.sifToGrnsight(weightedTestSif)
    ).to.deep.equal(expectedWeightedNetwork);
  });

  it("should import inconsistently weighted networks from SIF as unweighted", function () {
    expect(
      importController.sifToGrnsight(inconsistentlyWeightedTestSif)
    ).to.deep.equal(expectedUnweightedNetwork);
  });

  it("should import unweighted networks with cycles from SIF correctly", function () {
    expect(
      importController.sifToGrnsight(unweightedTestSifWithCycle)
    ).to.deep.equal(expectedUnweightedNetworkWithCycle);
  });

  it("should import weighted networks with cycles from SIF correctly", function () {
    expect(
      importController.sifToGrnsight(weightedTestSifWithCycle)
    ).to.deep.equal(expectedWeightedNetworkWithCycle);
  });

  it("should import inconsistently weighted networks with cycles from SIF as unweighted", function () {
    expect(
      importController.sifToGrnsight(inconsistentlyWeightedTestSifWithCycle)
    ).to.deep.equal(expectedUnweightedNetworkWithCycle);
  });
});

var unweightedTestGraphMl = [
  '<?xml version="1.0" encoding="UTF-8"?>',
  '<graphml xmlns="http://graphml.graphdrawing.org/xmlns" ' +
    'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
    'xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns ' +
    'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">',
  '  <graph edgedefault="directed">',
  '    <node id="A"/>',
  '    <node id="B"/>',
  '    <node id="C"/>',
  '    <node id="D"/>',
  '    <edge source="B" target="A"/>',
  '    <edge source="B" target="C"/>',
  '    <edge source="C" target="B"/>',
  '  </graph>',
  '</graphml>'
].join("\n");

var weightedTestGraphMl = [
  '<?xml version="1.0" encoding="UTF-8"?>',
  '<graphml xmlns="http://graphml.graphdrawing.org/xmlns" ' +
    'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
    'xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns ' +
    'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">',
  '  <key id="edge-value-id" for="edge" attr.name="weight" attr.type="double"/>',
  '  <graph edgedefault="directed">',
  '    <node id="A"/>',
  '    <node id="B"/>',
  '    <node id="C"/>',
  '    <node id="D"/>',
  '    <edge source="B" target="A">',
  '      <data key="edge-value-id">-0.75</data>',
  '    </edge>',
  '    <edge source="B" target="C">',
  '      <data key="edge-value-id">0.25</data>',
  '    </edge>',
  '    <edge source="C" target="B">',
  '      <data key="edge-value-id">0.5</data>',
  '    </edge>',
  '  </graph>',
  '</graphml>'
].join("\n");

var unweightedTestGraphMlWithCycle = [
  '<?xml version="1.0" encoding="UTF-8"?>',
  '<graphml xmlns="http://graphml.graphdrawing.org/xmlns" ' +
    'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
    'xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns ' +
    'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">',
  '  <graph edgedefault="directed">',
  '    <node id="A"/>',
  '    <node id="B"/>',
  '    <node id="C"/>',
  '    <node id="D"/>',
  '    <node id="E"/>',
  '    <edge source="A" target="A"/>',
  '    <edge source="B" target="A"/>',
  '    <edge source="B" target="C"/>',
  '    <edge source="C" target="B"/>',
  '    <edge source="D" target="D"/>',
  '  </graph>',
  '</graphml>'
].join("\n");

var weightedTestGraphMlWithCycle = [
  '<?xml version="1.0" encoding="UTF-8"?>',
  '<graphml xmlns="http://graphml.graphdrawing.org/xmlns" ' +
    'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
    'xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns ' +
    'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">',
  '  <key id="edge-value-id" for="edge" attr.name="weight" attr.type="double"/>',
  '  <graph edgedefault="directed">',
  '    <node id="A"/>',
  '    <node id="B"/>',
  '    <node id="C"/>',
  '    <node id="D"/>',
  '    <node id="E"/>',
  '    <edge source="A" target="A">',
  '      <data key="edge-value-id">0.875</data>',
  '    </edge>',
  '    <edge source="B" target="A">',
  '      <data key="edge-value-id">-0.75</data>',
  '    </edge>',
  '    <edge source="B" target="C">',
  '      <data key="edge-value-id">0.25</data>',
  '    </edge>',
  '    <edge source="C" target="B">',
  '      <data key="edge-value-id">0.5</data>',
  '    </edge>',
  '    <edge source="D" target="D">',
  '      <data key="edge-value-id">-0.375</data>',
  '    </edge>',
  '  </graph>',
  '</graphml>'
].join("\n");

describe("Import from GraphML", function () {
  it("should import unweighted networks from GraphML correctly", function () {
    expect(
      importController.graphMlToGrnsight(unweightedTestGraphMl)
    ).to.deep.equal(expectedUnweightedNetwork);
  });

  it("should import weighted networks from GraphML correctly", function () {
    expect(
      importController.graphMlToGrnsight(weightedTestGraphMl)
    ).to.deep.equal(expectedWeightedNetwork);
  });

  it("should import unweighted networks with cycles from GraphML correctly", function () {
    expect(
      importController.graphMlToGrnsight(unweightedTestGraphMlWithCycle)
    ).to.deep.equal(expectedUnweightedNetworkWithCycle);
  });

  it("should import weighted networks with cycles from GraphML correctly", function () {
    expect(
      importController.graphMlToGrnsight(weightedTestGraphMlWithCycle)
    ).to.deep.equal(expectedWeightedNetworkWithCycle);
  });

  it("should issue a warning if edgedefault is not set to 'directed'", function () {
    var EDGE_DEFAULT_NOT_DIRECTED_WARNING = {
      warningCode: "EDGE_DEFAULT_NOT_DIRECTED",
      errorDescription: "GRNsight interprets the graph as directed unconditionally."
    };

    var undirected = unweightedTestGraphMl.replace('edgedefault="directed"', 'edgedefault="undirected"');
    expect(
      importController.graphMlToGrnsight(undirected).warnings
    ).to.deep.equal([EDGE_DEFAULT_NOT_DIRECTED_WARNING]);

    var noEdgedefault = unweightedTestGraphMl.replace('edgedefault="directed"', "");
    expect(
      importController.graphMlToGrnsight(noEdgedefault).warnings
    ).to.deep.equal([EDGE_DEFAULT_NOT_DIRECTED_WARNING]);
  });

  it("should issue a warning if a weighted graph has edges without weights", function () {
    var EDGES_WITHOUT_WEIGHTS_WARNING = {
      warningCode: "EDGES_WITHOUT_WEIGHTS",
      errorDescription: "GRNsight attempted to import the graph as weighted, but some edges did not have a weight."
    };

    var missingWeight = weightedTestGraphMl.replace('<data key="edge-value-id">0.5</data>', "");
    expect(
      importController.graphMlToGrnsight(missingWeight).warnings
    ).to.deep.equal([EDGES_WITHOUT_WEIGHTS_WARNING]);

    var nanWeight = weightedTestGraphMl.replace('<data key="edge-value-id">0.5</data>',
        '<data key="edge-value-id">pizza pizza</data>');
    expect(
      importController.graphMlToGrnsight(nanWeight).warnings
    ).to.deep.equal([EDGES_WITHOUT_WEIGHTS_WARNING]);
  });

  it("should ignore unsupported GraphML features", function () {
    var fs = require("fs");
    var UTF8 = { encoding: "utf-8" };

    fs.readFile(__dirname + "/../test-files/import-samples/hyper.graphml", UTF8, function (error, data) {
      expect(
        importController.graphMlToGrnsight(data)
      ).to.deep.equal({
        genes: [
          { name: "n0" },
          { name: "n1" },
          { name: "n2" },
          { name: "n3" },
          { name: "n4" },
          { name: "n5" },
          { name: "n6" }
        ],

        links: [
          { source: 0, target: 4 }
        ],

        errors: [],
        warnings: [],
        sheetType: "unweighted"
      }); // Look ma, no hyperedges.
    });

    fs.readFile(__dirname + "/../test-files/import-samples/nested.graphml", UTF8, function (error, data) {
      expect(
        importController.graphMlToGrnsight(data)
      ).to.deep.equal({
        genes: [
          { name: "n0" },
          { name: "n1" },
          { name: "n2" },
          { name: "n3" },
          { name: "n4" },
          { name: "n5" },
          { name: "n6" }
        ],

        links: [
          { source: 0, target: 2 },
          { source: 0, target: 1 },
          { source: 1, target: 3 },
          { source: 3, target: 2 },
          { source: 2, target: 4 }
        ],

        errors: [],
        warnings: [],
        sheetType: "unweighted"
      }); // Look ma, no nested graphs (nor edges that refer to them).
    });
  });
});
<|endoftext|>


<commit_before>var test = require('tape');

var testXHRCall = require('./lib/test-xhr-call');
var table = require('./tables/index.search.js');

table.calls.forEach(function(call) {
  test('index.search spec: ' + call.testName, function(t) {
    t.plan(testXHRCall.assertCount);

    testXHRCall({
      call: call,
      methodName: 'search',
      object: 'index',
      applicationID: table.applicationID,
      searchOnlyAPIKey: table.searchOnlyAPIKey,
      indexName: table.indexName,
      test: t
    });

  });
});
<commit_msg>Remove plan until we have some asyncs<commit_after>var test = require('tape');

var testXHRCall = require('./lib/test-xhr-call');
var table = require('./tables/index.search.js');

table.calls.forEach(function(call) {
  test('index.search spec: ' + call.testName, function(t) {

    testXHRCall({
      call: call,
      methodName: 'search',
      object: 'index',
      applicationID: table.applicationID,
      searchOnlyAPIKey: table.searchOnlyAPIKey,
      indexName: table.indexName,
      test: t
    });

    t.end();
  });
});
<|endoftext|>


<commit_before>/* eslint-env mocha */

const mineflayer = require('../')
const vec3 = require('vec3')
const mc = require('minecraft-protocol')
const assert = require('assert')

const { firstVersion, lastVersion } = require('./common/parallel')
mineflayer.supportedVersions.forEach((supportedVersion, i) => {
  if (!(i >= firstVersion && i <= lastVersion)) {
    return
  }
  const mcData = require('minecraft-data')(supportedVersion)
  const version = mcData.version
  const Chunk = require('prismarine-chunk')(supportedVersion)

  describe(`mineflayer_internal ${version.minecraftVersion}`, function () {
    this.timeout(10 * 1000)
    let bot
    let server
    beforeEach((done) => {
      server = mc.createServer({
        'online-mode': false,
        version: supportedVersion,
        // 25565 - local server, 25566 - proxy server
        port: 25567
      })
      server.on('listening', () => {
        bot = mineflayer.createBot({
          username: 'player',
          version: supportedVersion,
          port: 25567
        })
        done()
      })
    })
    afterEach((done) => {
      bot.on('end', done)
      server.close()
    })
    it('chat', (done) => {
      bot.once('chat', (username, message) => {
        assert.strictEqual(username, 'gary')
        assert.strictEqual(message, 'hello')
        bot.chat('hi')
      })
      server.on('login', (client) => {
        const message = JSON.stringify({
          translate: 'chat.type.text',
          with: [{
            text: 'gary'
          },
          'hello'
          ]
        })
        client.write('chat', { message, position: 0 })
        client.on('chat', (packet) => {
          assert.strictEqual(packet.message, 'hi')
          done()
        })
      })
    })
    it('entity effects', (done) => {
      bot.once('entityEffect', (entity, effect) => {
        assert.strictEqual(entity.mobType, 'Creeper')
        assert.strictEqual(effect.id, 10)
        assert.strictEqual(effect.amplifier, 1)
        assert.strictEqual(effect.duration, 11)
        done()
      })
      server.on('login', (client) => {
        client.write('spawn_entity_living', {
          entityId: 8, // random
          entityUUID: '00112233-4455-6677-8899-aabbccddeeff',
          type: 50, // creeper
          x: 10,
          y: 11,
          z: 12,
          yaw: 13,
          pitch: 14,
          headPitch: 14,
          velocityX: 16,
          velocityY: 17,
          velocityZ: 18,
          metadata: []
        })
        client.write('entity_effect', {
          entityId: 8,
          effectId: 10,
          amplifier: 1,
          duration: 11,
          hideParticles: false
        })
      })
    })
    it('blockAt', (done) => {
      const pos = vec3(1, 65, 1)
      const goldId = 41
      bot.on('chunkColumnLoad', (columnPoint) => {
        assert.strictEqual(columnPoint.x, 0)
        assert.strictEqual(columnPoint.z, 0)
        assert.strictEqual(bot.blockAt(pos).type, goldId)
        done()
      })
      server.on('login', (client) => {
        client.write('login', {
          entityId: 0,
          levelType: 'fogetaboutit',
          gameMode: 0,
          dimension: 0,
          difficulty: 0,
          maxPlayers: 20,
          reducedDebugInfo: true
        })
        const chunk = new Chunk()

        chunk.setBlockType(pos, goldId)
        client.write('map_chunk', {
          x: 0,
          z: 0,
          groundUp: true,
          bitMap: 0xffff,
          chunkData: chunk.dump(),
          blockEntities: []
        })
      })
    })
    describe('physics', () => {
      const pos = vec3(1, 65, 1)
      const goldId = 41
      it('gravity + land on solid block + jump', (done) => {
        let y = 80
        const terminal = 10
        let hitTerminal = false
        bot.on('move', () => {
          assert.ok(bot.entity.position.y <= y)
          assert.ok(bot.entity.position.y >= pos.y)
          y = bot.entity.position.y
          if (bot.entity.velocity.y > -terminal) hitTerminal = true
          if (bot.entity.velocity.y === 0) {
            assert.ok(hitTerminal)
            assert.ok(bot.entity.onGround)
            assert.ok(bot.entity.position.y, pos.y)
            done()
          } else {
            assert.strictEqual(bot.entity.onGround, false)
          }
        })
        server.on('login', (client) => {
          client.write('login', {
            entityId: 0,
            levelType: 'fogetaboutit',
            gameMode: 0,
            dimension: 0,
            difficulty: 0,
            maxPlayers: 20,
            reducedDebugInfo: true
          })
          const chunk = new Chunk()

          chunk.setBlockType(pos, goldId)
          client.write('map_chunk', {
            x: 0,
            z: 0,
            groundUp: true,
            bitMap: 0xffff,
            chunkData: chunk.dump(),
            blockEntities: []
          })
          client.write('position', {
            x: 1.5,
            y: 80,
            z: 1.5,
            pitch: 0,
            yaw: 0,
            flags: 0,
            teleportId: 0
          })
        })
      })
    })
    describe('entities', () => {
      it('player displayName', (done) => {
        server.on('login', (client) => {
          bot.on('entitySpawn', (entity) => {
            const player = bot.players[entity.username]
            assert.strictEqual(entity.username, player.displayName.toString())
            client.write('player_info', {
              id: 56,
              state: 'play',
              action: 3,
              length: 1,
              data: [{
                UUID: '1-2-3-4',
                name: 'bot5',
                propertiesLength: 0,
                properties: [],
                gamemode: 0,
                ping: 0,
                hasDisplayName: true,
                displayName: '{"text":"wvffle"}'
              }]
            })
          })

          bot.once('playerUpdated', (player) => {
            assert.strictEqual('wvffle', player.displayName.toString())
            client.write('player_info', {
              id: 56,
              state: 'play',
              action: 3,
              length: 1,
              data: [{
                UUID: '1-2-3-4',
                name: 'bot5',
                propertiesLength: 0,
                properties: [],
                gamemode: 0,
                ping: 0,
                hasDisplayName: false
              }]
            })

            bot.once('playerUpdated', (player) => {
              assert.strictEqual(player.entity.username, player.displayName.toString())
              done()
            })
          })

          client.write('player_info', {
            id: 56,
            state: 'play',
            action: 0,
            length: 1,
            data: [{
              UUID: '1-2-3-4',
              name: 'bot5',
              propertiesLength: 0,
              properties: [],
              gamemode: 0,
              ping: 0,
              hasDisplayName: false
            }]
          })

          client.write('named_entity_spawn', {
            entityId: 56,
            playerUUID: '1-2-3-4',
            x: 1,
            y: 2,
            z: 3,
            yaw: 0,
            pitch: 0,
            currentItem: -1,
            metadata: []
          })
        })
      })
      it('sets players[player].entity to null upon despawn', (done) => {
        let serverClient = null
        bot.once('entitySpawn', (entity) => {
          serverClient.write('entity_destroy', {
            entityIds: [8]
          })
        })
        bot.once('entityGone', (entity) => {
          assert.strictEqual(bot.players[entity.username], undefined)
          done()
        })
        server.on('login', (client) => {
          serverClient = client

          client.write('player_info', {
            id: 56,
            state: 'play',
            action: 0,
            length: 1,
            data: [{
              UUID: '1-2-3-4',
              name: 'bot5',
              propertiesLength: 0,
              properties: [],
              gamemode: 0,
              ping: 0,
              hasDisplayName: false
            }]
          })

          client.write('named_entity_spawn', {
            entityId: 56,
            playerUUID: '1-2-3-4',
            x: 1,
            y: 2,
            z: 3,
            yaw: 0,
            pitch: 0,
            currentItem: -1,
            metadata: []
          })
        })
      })
    })
  })
})
<commit_msg>Add test for entity metadata<commit_after>/* eslint-env mocha */

const mineflayer = require('../')
const vec3 = require('vec3')
const mc = require('minecraft-protocol')
const assert = require('assert')

const { firstVersion, lastVersion } = require('./common/parallel')
mineflayer.supportedVersions.forEach((supportedVersion, i) => {
  if (!(i >= firstVersion && i <= lastVersion)) {
    return
  }
  const mcData = require('minecraft-data')(supportedVersion)
  const version = mcData.version
  const Chunk = require('prismarine-chunk')(supportedVersion)

  describe(`mineflayer_internal ${version.minecraftVersion}`, function () {
    this.timeout(10 * 1000)
    let bot
    let server
    beforeEach((done) => {
      server = mc.createServer({
        'online-mode': false,
        version: supportedVersion,
        // 25565 - local server, 25566 - proxy server
        port: 25567
      })
      server.on('listening', () => {
        bot = mineflayer.createBot({
          username: 'player',
          version: supportedVersion,
          port: 25567
        })
        done()
      })
    })
    afterEach((done) => {
      bot.on('end', done)
      server.close()
    })
    it('chat', (done) => {
      bot.once('chat', (username, message) => {
        assert.strictEqual(username, 'gary')
        assert.strictEqual(message, 'hello')
        bot.chat('hi')
      })
      server.on('login', (client) => {
        const message = JSON.stringify({
          translate: 'chat.type.text',
          with: [{
            text: 'gary'
          },
          'hello'
          ]
        })
        client.write('chat', { message, position: 0 })
        client.on('chat', (packet) => {
          assert.strictEqual(packet.message, 'hi')
          done()
        })
      })
    })
    it('entity effects', (done) => {
      bot.once('entityEffect', (entity, effect) => {
        assert.strictEqual(entity.mobType, 'Creeper')
        assert.strictEqual(effect.id, 10)
        assert.strictEqual(effect.amplifier, 1)
        assert.strictEqual(effect.duration, 11)
        done()
      })
      server.on('login', (client) => {
        client.write('spawn_entity_living', {
          entityId: 8, // random
          entityUUID: '00112233-4455-6677-8899-aabbccddeeff',
          type: 50, // creeper
          x: 10,
          y: 11,
          z: 12,
          yaw: 13,
          pitch: 14,
          headPitch: 14,
          velocityX: 16,
          velocityY: 17,
          velocityZ: 18,
          metadata: []
        })
        client.write('entity_effect', {
          entityId: 8,
          effectId: 10,
          amplifier: 1,
          duration: 11,
          hideParticles: false
        })
      })
    })
    it('blockAt', (done) => {
      const pos = vec3(1, 65, 1)
      const goldId = 41
      bot.on('chunkColumnLoad', (columnPoint) => {
        assert.strictEqual(columnPoint.x, 0)
        assert.strictEqual(columnPoint.z, 0)
        assert.strictEqual(bot.blockAt(pos).type, goldId)
        done()
      })
      server.on('login', (client) => {
        client.write('login', {
          entityId: 0,
          levelType: 'fogetaboutit',
          gameMode: 0,
          dimension: 0,
          difficulty: 0,
          maxPlayers: 20,
          reducedDebugInfo: true
        })
        const chunk = new Chunk()

        chunk.setBlockType(pos, goldId)
        client.write('map_chunk', {
          x: 0,
          z: 0,
          groundUp: true,
          bitMap: 0xffff,
          chunkData: chunk.dump(),
          blockEntities: []
        })
      })
    })
    describe('physics', () => {
      const pos = vec3(1, 65, 1)
      const goldId = 41
      it('gravity + land on solid block + jump', (done) => {
        let y = 80
        const terminal = 10
        let hitTerminal = false
        bot.on('move', () => {
          assert.ok(bot.entity.position.y <= y)
          assert.ok(bot.entity.position.y >= pos.y)
          y = bot.entity.position.y
          if (bot.entity.velocity.y > -terminal) hitTerminal = true
          if (bot.entity.velocity.y === 0) {
            assert.ok(hitTerminal)
            assert.ok(bot.entity.onGround)
            assert.ok(bot.entity.position.y, pos.y)
            done()
          } else {
            assert.strictEqual(bot.entity.onGround, false)
          }
        })
        server.on('login', (client) => {
          client.write('login', {
            entityId: 0,
            levelType: 'fogetaboutit',
            gameMode: 0,
            dimension: 0,
            difficulty: 0,
            maxPlayers: 20,
            reducedDebugInfo: true
          })
          const chunk = new Chunk()

          chunk.setBlockType(pos, goldId)
          client.write('map_chunk', {
            x: 0,
            z: 0,
            groundUp: true,
            bitMap: 0xffff,
            chunkData: chunk.dump(),
            blockEntities: []
          })
          client.write('position', {
            x: 1.5,
            y: 80,
            z: 1.5,
            pitch: 0,
            yaw: 0,
            flags: 0,
            teleportId: 0
          })
        })
      })
    })
    describe('entities', () => {
      it('player displayName', (done) => {
        server.on('login', (client) => {
          bot.on('entitySpawn', (entity) => {
            const player = bot.players[entity.username]
            assert.strictEqual(entity.username, player.displayName.toString())
            client.write('player_info', {
              id: 56,
              state: 'play',
              action: 3,
              length: 1,
              data: [{
                UUID: '1-2-3-4',
                name: 'bot5',
                propertiesLength: 0,
                properties: [],
                gamemode: 0,
                ping: 0,
                hasDisplayName: true,
                displayName: '{"text":"wvffle"}'
              }]
            })
          })

          bot.once('playerUpdated', (player) => {
            assert.strictEqual('wvffle', player.displayName.toString())
            client.write('player_info', {
              id: 56,
              state: 'play',
              action: 3,
              length: 1,
              data: [{
                UUID: '1-2-3-4',
                name: 'bot5',
                propertiesLength: 0,
                properties: [],
                gamemode: 0,
                ping: 0,
                hasDisplayName: false
              }]
            })

            bot.once('playerUpdated', (player) => {
              assert.strictEqual(player.entity.username, player.displayName.toString())
              done()
            })
          })

          client.write('player_info', {
            id: 56,
            state: 'play',
            action: 0,
            length: 1,
            data: [{
              UUID: '1-2-3-4',
              name: 'bot5',
              propertiesLength: 0,
              properties: [],
              gamemode: 0,
              ping: 0,
              hasDisplayName: false
            }]
          })

          client.write('named_entity_spawn', {
            entityId: 56,
            playerUUID: '1-2-3-4',
            x: 1,
            y: 2,
            z: 3,
            yaw: 0,
            pitch: 0,
            currentItem: -1,
            metadata: []
          })
        })
      })
      it('sets players[player].entity to null upon despawn', (done) => {
        let serverClient = null
        bot.once('entitySpawn', (entity) => {
          serverClient.write('entity_destroy', {
            entityIds: [8]
          })
        })
        bot.once('entityGone', (entity) => {
          assert.strictEqual(bot.players[entity.username], undefined)
          done()
        })
        server.on('login', (client) => {
          serverClient = client

          client.write('player_info', {
            id: 56,
            state: 'play',
            action: 0,
            length: 1,
            data: [{
              UUID: '1-2-3-4',
              name: 'bot5',
              propertiesLength: 0,
              properties: [],
              gamemode: 0,
              ping: 0,
              hasDisplayName: false
            }]
          })

          client.write('named_entity_spawn', {
            entityId: 56,
            playerUUID: '1-2-3-4',
            x: 1,
            y: 2,
            z: 3,
            yaw: 0,
            pitch: 0,
            currentItem: -1,
            metadata: []
          })
        })
      })

      it('metadata', (done) => {
        server.on('login', (client) => {
          bot.on('entitySpawn', (entity) => {
            assert.strictEqual(entity.mobType, 'Creeper')

            client.write('entity_metadata', {
              entityId: 8,
              metadata: {
                data1: 'test',
                data2: 'test'
              }
            })
          })

          bot.once('entityUpdate', (entity) => {
            const lastMeta = entity.metadata
            bot.once('entityUpdate', (entity) => {
              assert.ok('data2' in entity.metadata)
              assert.strictEqual(entity.metadata.data1, 'test1')
              assert.strictEqual(entity.metadata.data2, lastMeta.data2)
              done()
            })

            client.write('entity_metadata', {
              entityId: 8,
              metadata: {
                data1: 'test1',
              }
            })
          })

          client.write('spawn_entity_living', {
            entityId: 8, // random
            entityUUID: '00112233-4455-6677-8899-aabbccddeeff',
            type: 50, // creeper
            x: 10,
            y: 11,
            z: 12,
            yaw: 13,
            pitch: 14,
            headPitch: 14,
            velocityX: 16,
            velocityY: 17,
            velocityZ: 18,
            metadata: []
          })
        })
      })
    })
  })
})
<|endoftext|>


<commit_before>require('proof')(27, async okay => {
    const fs = require('fs').promises
    const path = require('path')

    const Journalist = require('..')

    const directory = path.join(__dirname, 'tmp')

    async function createCommit () {
        await fs.rmdir(directory, { recursive: true })
        // TODO Make this `async` so we can create the directory.
        return await Journalist.create(directory)
    }

    async function create (directory, structure) {
        for (const name in structure) {
            const value = structure[name]
            const resolved = path.join(directory, name)
            if (typeof value == 'string')  {
                await fs.writeFile(resolved, value, 'utf8')
            } else {
                await fs.mkdir(resolved)
                await create(resolved, value)
            }
        }
    }

    async function list (directory) {
        const listing = {}
        for (const file of (await fs.readdir(directory))) {
            const resolved = path.join(directory, file)
            const stat = await fs.stat(resolved)
            if (stat.isDirectory()) {
                listing[file] = await list(resolved)
            } else {
                listing[file] = await fs.readFile(resolved, 'utf8')
            }
        }
        return listing
    }

    // TODO Add some files to dodge.
    // await fs.mkdir(path.join(directory, 'dir'))

    // Recover a commit directory with no commit.
    {
        const commit = await createCommit()
        okay(await Journalist.prepare(commit), 0, 'no prepare')
        okay(await Journalist.commit(commit), 0, 'no commit')
        await commit.dispose()
    }

    // Create a file.
    {
        const commit = await createCommit()
        const entry = await commit.writeFile('hello/world.txt', Buffer.from('hello, world'))
        okay(entry, {
            method: 'emplace',
            filename: 'hello/world.txt',
            options: { flag: 'wx', mode: 438, encoding: 'utf8' },
            hash: '4d0ea41d'
        }, 'write file')
        okay(await commit.relative('hello/world.txt'), 'tmp/staging/hello/world.txt', 'aliased')
        okay(await commit.relative('missing.txt'), null, 'missing aliased')
        // await commit.rename('hello/world.txt', 'hello/world.pdf')
        await commit.write()
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        await commit.dispose()
        okay(await list(directory), { hello: { 'world.txt': 'hello, world' } }, 'write file ')
    }

    // Create a file with hash in name.
    {
        const commit = await createCommit()
        const entry = await commit.writeFile(hash => `one.${hash}.txt`, Buffer.from('hello, world'))
        okay(entry, {
            method: 'emplace',
            filename: 'one.4d0ea41d.txt',
            options: { flag: 'wx', mode: 438, encoding: 'utf8' },
            hash: '4d0ea41d'
        }, 'entry for file with hash in filename')
        // await commit.rename('hello/world.txt', 'hello/world.pdf')
        await commit.write()
        await Journalist.prepare(commit)
        for (const operation of await commit.commit()) {
            if (await operation.commit() == 'rename') {
                break
            }
            await operation.dispose()
        }
        const recovery = await Journalist.create(directory)
        okay(await Journalist.prepare(recovery), 0, 'no recovery necessary')
        for (const operation of await recovery.commit()) {
            await operation.commit()
            await operation.dispose()
        }
        await recovery.dispose()
        okay(await list(directory), {
            'one.4d0ea41d.txt': 'hello, world'
        }, 'write file with hash in filename')
    }

    // Resolve a file name that is in the primary directory.
    {
        const commit = await createCommit()
        await create(directory, { hello: 'world' })
        okay(await commit.relative('hello'), 'hello', 'relative in primary directory')
        await commit.write()
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        await commit.dispose()
    }

    // Remove a file.
    {
        const commit = await createCommit()
        await create(directory, { hello: 'world' })
        await commit.unlink('hello')
        await commit.write()
        await Journalist.prepare(commit)
        for (const operation of await commit.commit()) {
            if (await operation.commit() == 'unlink') {
                break
            }
            await operation.dispose()
        }
        const recovery = await Journalist.create(directory)
        await Journalist.prepare(recovery)
        const commits = await recovery.commit()
        okay(commits.length, 2, 'recovery of unlink')
        await Journalist.commit(recovery)
        await recovery.dispose()
        okay(await list(directory), {}, 'unlink primary')
    }

    // Remove a staged file.
    {
        const commit = await createCommit()
        await create(directory, { hello: 'world' })
        await commit.writeFile('hello', Buffer.from('world'))
        await commit.unlink('hello')
        await commit.write()
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        await commit.dispose()
        okay(await list(directory), {}, 'unlink staged')
    }

    // Partition a commit.
    {
        const commit = await createCommit()
        await commit.writeFile('one.txt', Buffer.from('one'))
        commit.partition()
        await commit.writeFile('two.txt', Buffer.from('two'))
        await commit.write()
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        const listing = await list(directory)
        okay({
            commit: { staging: listing.tmp.staging },
            'one.txt': listing['one.txt']
        }, {
            commit: { staging: { commit: {}, 'two.txt': 'two' } },
            'one.txt': 'one'
        }, 'partial commit')
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        await commit.dispose()
        okay(await list(directory), {
            'one.txt': 'one',
            'two.txt': 'two'
        }, 'partitioned commit')
    }

    // Overwrite a staged file.
    {
        const commit = await createCommit()
        const errors = []
        await commit.writeFile('one.txt', Buffer.from('one'))
        try {
            await commit.writeFile('one.txt', Buffer.from('two'), { flag: 'wx' })
        } catch (error) {
            errors.push(error.code)
        }
        await commit.writeFile('one.txt', Buffer.from('two'), { flag: 'w' })
        okay(errors, [ 'EEXIST' ], 'overwrite existing')
        // await commit.rename('hello/world.txt', 'hello/world.pdf')
        await commit.write()
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        await commit.dispose()
        okay(await list(directory), { 'one.txt': 'two' }, 'overwite file in staging')
    }

    // Create a directory.
    {
        const commit = await createCommit()
        const errors = []
        const entry = await commit.mkdir('dir')
        try {
            await commit.mkdir('dir')
        } catch (error) {
            errors.push(error.code, error.errno)
        }
        try {
            await commit.writeFile('dir', Buffer.from('one'), { flag: 'w' })
        } catch (error) {
            errors.push(error.code, error.errno)
        }
        await fs.writeFile(path.join(await commit.absolute('dir'), 'one.txt'), 'one')
        okay(errors, [ 'EEXIST', -17, 'EISDIR', -21 ], 'overwrite existing')
        await commit.write()
        await Journalist.prepare(commit)
        for (const operation of await commit.commit()) {
            if (await operation.commit() == 'rename') {
                break
            }
            await operation.dispose()
        }
        const recovery = await Journalist.create(directory)
        await Journalist.prepare(recovery)
        for (const operation of await recovery.commit()) {
            await operation.commit()
            await operation.dispose()
        }
        await recovery.dispose()
        okay(await list(directory), { dir: { 'one.txt': 'one' } }, 'create directory')
    }

    // Catch failure to create a directory.
    {
        const commit = await createCommit()
        const entry = await commit.mkdir('dir')
        await commit.write()
        await Journalist.prepare(commit)
        for (const operation of await commit.commit()) {
            if (await operation.commit() == 'rename') {
                break
            }
            await operation.dispose()
        }
        await fs.rmdir(path.join(directory, 'dir'))
        const recovery = await Journalist.create(directory)
        await Journalist.prepare(recovery)
        const errors = []
        try {
            for (const operation of await recovery.commit()) {
                await operation.commit()
                await operation.dispose()
            }
        } catch (error) {
            errors.push(/^rename failed$/m.test(error.message))
        }
        okay(errors, [ true ], 'caught failure to create directory')
        await recovery.dispose()
    }

    // Rename a file.
    {
        const commit = await createCommit()
        const errors = []
        await create(directory, { one: 'one' })
        await commit.rename('one', 'two')
        await commit.write()
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        await commit.dispose()
        okay(await list(directory), { two: 'one' }, 'rename file in primary')
    }

    // Rename a staged file.
    {
        const commit = await createCommit()
        const errors = []
        await create(directory, { one: 'one' })
        await commit.writeFile('two', Buffer.from('two'))
        await commit.rename('two', 'three')
        await commit.write()
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        await commit.dispose()
        okay(await list(directory), { one: 'one', three: 'two' }, 'rename file in staging')
    }

    // TODO Really consider maybe not passing through if it is a staged
    // directory created by `mkdir`.

    // Remove a primary directory.
    {
        const commit = await createCommit()
        const errors = []
        await create(directory, { one: {}, two: {} })
        await commit.rmdir('two', 'three')
        await commit.write()
        await Journalist.prepare(commit)
        for (const operation of await commit.commit()) {
            if (await operation.commit() == 'rmdir') {
                break
            }
            await operation.dispose()
        }
        const recovery = await Journalist.create(directory)
        await Journalist.prepare(recovery)
        const commits = await recovery.commit()
        okay(commits.length, 2, 'mkdir recovery')
        for (const operation of commits) {
            await operation.commit()
            await operation.dispose()
        }
        await recovery.dispose()
        okay(await list(directory), { one: {} }, 'remove directory from primary')
    }

    // Remove a staged directory.
    {
        const commit = await createCommit()
        const errors = []
        await create(directory, { one: {}, two: {} })
        await commit.mkdir('two')
        await commit.rmdir('two')
        await commit.write()
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        await commit.dispose()
        okay(await list(directory), { one: {} }, 'remove directory from staging')
    }

    // Replay a prepare.
    {
        const commit = await createCommit()
        const errors = []
        await commit.writeFile('one', Buffer.from('one'))
        await commit.write()
        await Journalist.prepare(commit)
        const recovery = await Journalist.create(directory)
        await Journalist.prepare(recovery)
        const commits = await recovery.commit()
        okay(commits.length, 3, 'replay prepare')
        for (const operation of commits) {
            await operation.commit()
            await operation.dispose()
        }
        await recovery.dispose()
        okay(await list(directory), { one: 'one' }, 'replay a prepare')
    }
})
<commit_msg>Unit test failed rename and write file checksums.<commit_after>require('proof')(29, async okay => {
    const fs = require('fs').promises
    const path = require('path')

    const Journalist = require('..')

    const directory = path.join(__dirname, 'tmp')

    async function createCommit () {
        await fs.rmdir(directory, { recursive: true })
        // TODO Make this `async` so we can create the directory.
        return await Journalist.create(directory)
    }

    async function create (directory, structure) {
        for (const name in structure) {
            const value = structure[name]
            const resolved = path.join(directory, name)
            if (typeof value == 'string')  {
                await fs.writeFile(resolved, value, 'utf8')
            } else {
                await fs.mkdir(resolved)
                await create(resolved, value)
            }
        }
    }

    async function list (directory) {
        const listing = {}
        for (const file of (await fs.readdir(directory))) {
            const resolved = path.join(directory, file)
            const stat = await fs.stat(resolved)
            if (stat.isDirectory()) {
                listing[file] = await list(resolved)
            } else {
                listing[file] = await fs.readFile(resolved, 'utf8')
            }
        }
        return listing
    }

    // TODO Add some files to dodge.
    // await fs.mkdir(path.join(directory, 'dir'))

    // Recover a commit directory with no commit.
    {
        const commit = await createCommit()
        okay(await Journalist.prepare(commit), 0, 'no prepare')
        okay(await Journalist.commit(commit), 0, 'no commit')
        await commit.dispose()
    }

    // Create a file.
    {
        const commit = await createCommit()
        const entry = await commit.writeFile('hello/world.txt', Buffer.from('hello, world'))
        okay(entry, {
            method: 'emplace',
            filename: 'hello/world.txt',
            options: { flag: 'wx', mode: 438, encoding: 'utf8' },
            hash: '4d0ea41d'
        }, 'write file')
        okay(await commit.relative('hello/world.txt'), 'tmp/staging/hello/world.txt', 'aliased')
        okay(await commit.relative('missing.txt'), null, 'missing aliased')
        // await commit.rename('hello/world.txt', 'hello/world.pdf')
        await commit.write()
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        await commit.dispose()
        okay(await list(directory), { hello: { 'world.txt': 'hello, world' } }, 'write file ')
    }

    // Create a file with hash in name.
    {
        const commit = await createCommit()
        const entry = await commit.writeFile(hash => `one.${hash}.txt`, Buffer.from('hello, world'))
        okay(entry, {
            method: 'emplace',
            filename: 'one.4d0ea41d.txt',
            options: { flag: 'wx', mode: 438, encoding: 'utf8' },
            hash: '4d0ea41d'
        }, 'entry for file with hash in filename')
        // await commit.rename('hello/world.txt', 'hello/world.pdf')
        await commit.write()
        await Journalist.prepare(commit)
        for (const operation of await commit.commit()) {
            if (await operation.commit() == 'rename') {
                break
            }
            await operation.dispose()
        }
        const recovery = await Journalist.create(directory)
        okay(await Journalist.prepare(recovery), 0, 'no recovery necessary')
        for (const operation of await recovery.commit()) {
            await operation.commit()
            await operation.dispose()
        }
        await recovery.dispose()
        okay(await list(directory), {
            'one.4d0ea41d.txt': 'hello, world'
        }, 'write file with hash in filename')
    }

    // Resolve a file name that is in the primary directory.
    {
        const commit = await createCommit()
        await create(directory, { hello: 'world' })
        okay(await commit.relative('hello'), 'hello', 'relative in primary directory')
        await commit.write()
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        await commit.dispose()
    }

    // Remove a file.
    {
        const commit = await createCommit()
        await create(directory, { hello: 'world' })
        await commit.unlink('hello')
        await commit.write()
        await Journalist.prepare(commit)
        for (const operation of await commit.commit()) {
            if (await operation.commit() == 'unlink') {
                break
            }
            await operation.dispose()
        }
        const recovery = await Journalist.create(directory)
        await Journalist.prepare(recovery)
        const commits = await recovery.commit()
        okay(commits.length, 2, 'recovery of unlink')
        await Journalist.commit(recovery)
        await recovery.dispose()
        okay(await list(directory), {}, 'unlink primary')
    }

    // Remove a staged file.
    {
        const commit = await createCommit()
        await create(directory, { hello: 'world' })
        await commit.writeFile('hello', Buffer.from('world'))
        await commit.unlink('hello')
        await commit.write()
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        await commit.dispose()
        okay(await list(directory), {}, 'unlink staged')
    }

    // Partition a commit.
    {
        const commit = await createCommit()
        await commit.writeFile('one.txt', Buffer.from('one'))
        commit.partition()
        await commit.writeFile('two.txt', Buffer.from('two'))
        await commit.write()
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        const listing = await list(directory)
        okay({
            commit: { staging: listing.tmp.staging },
            'one.txt': listing['one.txt']
        }, {
            commit: { staging: { commit: {}, 'two.txt': 'two' } },
            'one.txt': 'one'
        }, 'partial commit')
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        await commit.dispose()
        okay(await list(directory), {
            'one.txt': 'one',
            'two.txt': 'two'
        }, 'partitioned commit')
    }

    // Overwrite a staged file.
    {
        const commit = await createCommit()
        const errors = []
        await commit.writeFile('one.txt', Buffer.from('one'))
        try {
            await commit.writeFile('one.txt', Buffer.from('two'), { flag: 'wx' })
        } catch (error) {
            errors.push(error.code)
        }
        await commit.writeFile('one.txt', Buffer.from('two'), { flag: 'w' })
        okay(errors, [ 'EEXIST' ], 'overwrite existing')
        // await commit.rename('hello/world.txt', 'hello/world.pdf')
        await commit.write()
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        await commit.dispose()
        okay(await list(directory), { 'one.txt': 'two' }, 'overwite file in staging')
    }

    // Create a directory.
    {
        const commit = await createCommit()
        const errors = []
        const entry = await commit.mkdir('dir')
        try {
            await commit.mkdir('dir')
        } catch (error) {
            errors.push(error.code, error.errno)
        }
        try {
            await commit.writeFile('dir', Buffer.from('one'), { flag: 'w' })
        } catch (error) {
            errors.push(error.code, error.errno)
        }
        await fs.writeFile(path.join(await commit.absolute('dir'), 'one.txt'), 'one')
        okay(errors, [ 'EEXIST', -17, 'EISDIR', -21 ], 'overwrite existing')
        await commit.write()
        await Journalist.prepare(commit)
        for (const operation of await commit.commit()) {
            if (await operation.commit() == 'rename') {
                break
            }
            await operation.dispose()
        }
        const recovery = await Journalist.create(directory)
        await Journalist.prepare(recovery)
        for (const operation of await recovery.commit()) {
            await operation.commit()
            await operation.dispose()
        }
        await recovery.dispose()
        okay(await list(directory), { dir: { 'one.txt': 'one' } }, 'create directory')
    }

    // Catch failure to create a directory.
    {
        const commit = await createCommit()
        const entry = await commit.mkdir('dir')
        await commit.write()
        await Journalist.prepare(commit)
        for (const operation of await commit.commit()) {
            if (await operation.commit() == 'rename') {
                break
            }
            await operation.dispose()
        }
        await fs.rmdir(path.join(directory, 'dir'))
        const recovery = await Journalist.create(directory)
        await Journalist.prepare(recovery)
        const errors = []
        try {
            for (const operation of await recovery.commit()) {
                await operation.commit()
                await operation.dispose()
            }
        } catch (error) {
            errors.push(/^rename failed$/m.test(error.message))
        }
        okay(errors, [ true ], 'caught failure to create directory')
        await recovery.dispose()
    }

    // Rename a file.
    {
        const commit = await createCommit()
        const errors = []
        await create(directory, { one: 'one' })
        await commit.rename('one', 'two')
        await commit.write()
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        await commit.dispose()
        okay(await list(directory), { two: 'one' }, 'rename file in primary')
    }

    // Rename a staged file.
    {
        const commit = await createCommit()
        const errors = []
        await create(directory, { one: 'one' })
        await commit.writeFile('two', Buffer.from('two'))
        await commit.rename('two', 'three')
        await commit.write()
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        await commit.dispose()
        okay(await list(directory), { one: 'one', three: 'two' }, 'rename file in staging')
    }

    // TODO Really consider maybe not passing through if it is a staged
    // directory created by `mkdir`.

    // Remove a primary directory.
    {
        const commit = await createCommit()
        const errors = []
        await create(directory, { one: {}, two: {} })
        await commit.rmdir('two', 'three')
        await commit.write()
        await Journalist.prepare(commit)
        for (const operation of await commit.commit()) {
            if (await operation.commit() == 'rmdir') {
                break
            }
            await operation.dispose()
        }
        const recovery = await Journalist.create(directory)
        await Journalist.prepare(recovery)
        const commits = await recovery.commit()
        okay(commits.length, 2, 'mkdir recovery')
        for (const operation of commits) {
            await operation.commit()
            await operation.dispose()
        }
        await recovery.dispose()
        okay(await list(directory), { one: {} }, 'remove directory from primary')
    }

    // Remove a staged directory.
    {
        const commit = await createCommit()
        const errors = []
        await create(directory, { one: {}, two: {} })
        await commit.mkdir('two')
        await commit.rmdir('two')
        await commit.write()
        await Journalist.prepare(commit)
        await Journalist.commit(commit)
        await commit.dispose()
        okay(await list(directory), { one: {} }, 'remove directory from staging')
    }

    // Replay a prepare.
    {
        const commit = await createCommit()
        const errors = []
        await commit.writeFile('one', Buffer.from('one'))
        await commit.write()
        await Journalist.prepare(commit)
        const recovery = await Journalist.create(directory)
        await Journalist.prepare(recovery)
        const commits = await recovery.commit()
        okay(commits.length, 3, 'replay prepare')
        for (const operation of commits) {
            await operation.commit()
            await operation.dispose()
        }
        await recovery.dispose()
        okay(await list(directory), { one: 'one' }, 'replay a prepare')
    }

    // Failed file write checksum.
    {
        const errors = []
        const commit = await createCommit()
        await commit.writeFile('one', Buffer.from('one'))
        await commit.write()
        await Journalist.prepare(commit)
        await fs.writeFile(path.join(directory, 'tmp', 'staging', 'one'), 'two')
        try {
            await Journalist.commit(commit)
        } catch (error) {
            errors.push(/^rename failed$/m.test(error.message))
        }
        okay(errors, [ true ], 'failed write file checksum')
    }

    // Failed rename checksum.
    {
        const errors = []
        const commit = await createCommit()
        await create(directory, { one: 'one' })
        await commit.rename('one', 'two')
        await commit.write()
        await Journalist.prepare(commit)
        await fs.writeFile(path.join(directory, 'one'), 'two')
        try {
            await Journalist.commit(commit)
        } catch (error) {
            errors.push(/^rename failed$/m.test(error.message))
        }
        okay(errors, [ true ], 'failed rename checksum')
    }
})
<|endoftext|>


<commit_before>const data = require('./data.json');

//https://www.googleapis.com/blogger/v3/blogs/5703646917195213185/posts?maxResults=500&key={YOUR_API_KEY}

data.items.forEach(function(d) {
  const title = d.title;
  const url = d.url.replace('http', 'https');
  const content = d.content;
  const img = content.split('src=\"')[1].split('\" style')[0];
  const fileId = content.split('/file/d/')[1].split('/preview')[0];
  console.log([url, img, fileId,title].join(' '));
});
<commit_msg>ignore file<commit_after>const data = require('./data.json');

//https://www.googleapis.com/blogger/v3/blogs/5703646917195213185/posts?maxResults=500&key={YOUR_API_KEY}

data.items.forEach(function(d) {
  const title = d.title;
  const url = d.url.replace('http', 'https');
  const content = d.content;
  if(content.indexOf('/file/d/') == -1) return;
  const img = content.split('src=\"')[1].split('\" style')[0];
  const fileId = content.split('/file/d/')[1].split('/preview')[0];
  console.log([url, img, fileId,title].join(' '));
});
<|endoftext|>


<commit_before>(function( $ ) {
    $.fn.select2entity = function (options) {
        this.each(function () {
            var request;

            // Keep a reference to the element so we can keep the cache local to this instance and so we can
            // fetch config settings since select2 doesn't expose its options to the transport method.
            var $s2 = $(this),
                limit = $s2.data('page-limit') || 0,
                scroll = $s2.data('scroll'),
                prefix = Date.now(),
                cache = [];

            var reqParams = $s2.data('req_params');
            if (reqParams) {
                $.each(reqParams, function (key, value) {
                    $('*[name="'+value+'"]').on('change', function () {
                        $s2.val(null);
                        $s2.trigger('change');
                    });
                });
            }

            // Deep-merge the options
            $s2.select2($.extend(true, {
                // Tags support
                createTag: function (data) {
                    if ($s2.data('tags') && data.term.length > 0) {
                        var text = data.term + $s2.data('tags-text');
                        return {id: $s2.data('new-tag-prefix') + data.term, text: text};
                    }
                },
                ajax: {
                    transport: function (params, success, failure) {
                        // is caching enabled?
                        if ($s2.data('ajax--cache')) {
                            // try to make the key unique to make it less likely for a page+q to match a real query
                            var key = prefix + ' page:' + (params.data.page || 1) + ' ' + params.data.q,
                                cacheTimeout = $s2.data('ajax--cacheTimeout');
                            // no cache entry for 'term' or the cache has timed out?
                            if (typeof cache[key] == 'undefined' || (cacheTimeout && Date.now() >= cache[key].time)) {
                                $.ajax(params).fail(failure).done(function (data) {
                                    cache[key] = {
                                        data: data,
                                        time: cacheTimeout ? Date.now() + cacheTimeout : null
                                    };
                                    success(data);
                                });
                            } else {
                                // return cached data with no ajax request
                                success(cache[key].data);
                            }
                        } else {
                            // no caching enabled. just do the ajax request
                            if (request) {
                                request.abort();
                            }
                            request = $.ajax(params).fail(failure).done(success).always(function () {
                                request = undefined;
                            });
                        }
                    },
                    data: function (params) {
                        var ret = {
                            'q': params.term,
                            'field_name': $s2.data('name')
                        };

                        var reqParams = $s2.data('req_params');
                        if (reqParams) {
                            $.each(reqParams, function (key, value) {
                                ret[key] = $('*[name="'+value+'"]').val()
                            });
                        }

                        // only send the 'page' parameter if scrolling is enabled
                        if (scroll) {
                            ret['page'] = params.page || 1;
                        }

                        return ret;
                    },
                    processResults: function (data, params) {
                        var results, more = false, response = {};
                        params.page = params.page || 1;

                        if ($.isArray(data)) {
                            results = data;
                        } else if (typeof data == 'object') {
                            // assume remote result was proper object
                            results = data.results;
                            more = data.more;
                        } else {
                            // failsafe
                            results = [];
                        }

                        if (scroll) {
                            response.pagination = {more: more};
                        }
                        response.results = results;

                        return response;
                    }
                }
            }, options || {}));
        });
        return this;
    };
})( jQuery );

(function( $ ) {
    $(document).ready(function () {
        $('.select2entity[data-autostart="true"]').select2entity();
    });
})( jQuery );
<commit_msg>Request not returned<commit_after>(function( $ ) {
    $.fn.select2entity = function (options) {
        this.each(function () {
            var request;

            // Keep a reference to the element so we can keep the cache local to this instance and so we can
            // fetch config settings since select2 doesn't expose its options to the transport method.
            var $s2 = $(this),
                limit = $s2.data('page-limit') || 0,
                scroll = $s2.data('scroll'),
                prefix = Date.now(),
                cache = [];

            var reqParams = $s2.data('req_params');
            if (reqParams) {
                $.each(reqParams, function (key, value) {
                    $('*[name="'+value+'"]').on('change', function () {
                        $s2.val(null);
                        $s2.trigger('change');
                    });
                });
            }

            // Deep-merge the options
            $s2.select2($.extend(true, {
                // Tags support
                createTag: function (data) {
                    if ($s2.data('tags') && data.term.length > 0) {
                        var text = data.term + $s2.data('tags-text');
                        return {id: $s2.data('new-tag-prefix') + data.term, text: text};
                    }
                },
                ajax: {
                    transport: function (params, success, failure) {
                        // is caching enabled?
                        if ($s2.data('ajax--cache')) {
                            // try to make the key unique to make it less likely for a page+q to match a real query
                            var key = prefix + ' page:' + (params.data.page || 1) + ' ' + params.data.q,
                                cacheTimeout = $s2.data('ajax--cacheTimeout');
                            // no cache entry for 'term' or the cache has timed out?
                            if (typeof cache[key] == 'undefined' || (cacheTimeout && Date.now() >= cache[key].time)) {
                                $.ajax(params).fail(failure).done(function (data) {
                                    cache[key] = {
                                        data: data,
                                        time: cacheTimeout ? Date.now() + cacheTimeout : null
                                    };
                                    success(data);
                                });
                            } else {
                                // return cached data with no ajax request
                                success(cache[key].data);
                            }
                        } else {
                            // no caching enabled. just do the ajax request
                            if (request) {
                                request.abort();
                            }
                            request = $.ajax(params).fail(failure).done(success).always(function () {
                                request = undefined;
                            });

                            return request;
                        }
                    },
                    data: function (params) {
                        var ret = {
                            'q': params.term,
                            'field_name': $s2.data('name')
                        };

                        var reqParams = $s2.data('req_params');
                        if (reqParams) {
                            $.each(reqParams, function (key, value) {
                                ret[key] = $('*[name="'+value+'"]').val()
                            });
                        }

                        // only send the 'page' parameter if scrolling is enabled
                        if (scroll) {
                            ret['page'] = params.page || 1;
                        }

                        return ret;
                    },
                    processResults: function (data, params) {
                        var results, more = false, response = {};
                        params.page = params.page || 1;

                        if ($.isArray(data)) {
                            results = data;
                        } else if (typeof data == 'object') {
                            // assume remote result was proper object
                            results = data.results;
                            more = data.more;
                        } else {
                            // failsafe
                            results = [];
                        }

                        if (scroll) {
                            response.pagination = {more: more};
                        }
                        response.results = results;

                        return response;
                    }
                }
            }, options || {}));
        });
        return this;
    };
})( jQuery );

(function( $ ) {
    $(document).ready(function () {
        $('.select2entity[data-autostart="true"]').select2entity();
    });
})( jQuery );
<|endoftext|>


<commit_before>function sendMsg(tabId, url) {
  var msg = {}
  if (config.patt.workout.test(url))
    msg.request = config.request.newWorkout;
  else if (config.patt.home.test(url))
    msg.request = config.request.home;

  if (msg.request) {
    console.log(msg);
    chrome.tabs.sendMessage(tabId, msg);
  }
};

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
  if (changeInfo.url)
    sendMsg(tabId, changeInfo.url);
});

chrome.tabs.onCreated.addListener(function (tab) {
  if (tab.url)
    sendMsg(tab.id, tab.url);
});

chrome.runtime.onConnect.addListener(function (port) {
  console.assert(port.name === config.port.name);
  port.onMessage.addListener(function (msg) {
    if (msg.msg === config.request.checkUrl) {
      chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        var msg = {
          response: config.patt.workout.test(tabs[0].url) ?
            config.response.workout :
            config.response.home
        }
        console.log(msg);
        port.postMessage(msg);
      });
    }
  });
});
<commit_msg>Remove unnecessary tabs.onCreated listener.<commit_after>function sendMsg(tabId, url) {
  var msg = {}
  if (config.patt.workout.test(url))
    msg.request = config.request.newWorkout;
  else if (config.patt.home.test(url))
    msg.request = config.request.home;

  if (msg.request) {
    console.log(msg);
    chrome.tabs.sendMessage(tabId, msg);
  }
};

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
  if (changeInfo.url)
    sendMsg(tabId, changeInfo.url);
});

chrome.runtime.onConnect.addListener(function (port) {
  console.assert(port.name === config.port.name);
  port.onMessage.addListener(function (msg) {
    if (msg.msg === config.request.checkUrl) {
      chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        var msg = {
          response: config.patt.workout.test(tabs[0].url) ?
            config.response.workout :
            config.response.home
        }
        console.log(msg);
        port.postMessage(msg);
      });
    }
  });
});
<|endoftext|>