<commit_before>/* globals describe, it */
var assert = require('assert');
var t = require('../index');
var throwsWithMessage = require('./util').throwsWithMessage;

describe('t.update(instance, spec)', function () {

  var update = t.update;
  var Tuple = t.tuple([t.String, t.Number]);
  var List = t.list(t.Number);
  var Dict = t.dict(t.String, t.Number);
  var Point = t.struct({
    x: t.Number,
    y: t.Number
  });

  it('should throw if spec is invalid', function () {
    throwsWithMessage(function () {
      t.update({});
    }, '[tcomb] Invalid argument spec undefined supplied to function update(instance, spec): expected an object containing commands');
  });

  it('should handle $set command', function () {
    var instance = 1;
    var actual = update(instance, {$set: 2});
    assert.deepEqual(actual, 2);
    instance = [1, 2, 3];
    actual = update(instance, {1: {'$set': 4}});
    assert.deepEqual(instance, [1, 2, 3]);
    assert.deepEqual(actual, [1, 4, 3]);
  });

  it('$set and null value, fix #65', function () {
    var NullStruct = t.struct({a: t.Number, b: t.maybe(t.Number)});
    var instance = new NullStruct({a: 1});
    var updated = update(instance, {b: {$set: 2}});
    assert.deepEqual(instance, {a: 1, b: null});
    assert.deepEqual(updated, {a: 1, b: 2});
  });

  it('should handle $apply command', function () {
    var $apply = function (n) { return n + 1; };
    var instance = 1;
    var actual = update(instance, {$apply: $apply});
    assert.deepEqual(actual, 2);
    instance = [1, 2, 3];
    actual = update(instance, {1: {'$apply': $apply}});
    assert.deepEqual(instance, [1, 2, 3]);
    assert.deepEqual(actual, [1, 3, 3]);
  });

  it('should handle $unshift command', function () {
    var actual = update([1, 2, 3], {'$unshift': [4]});
    assert.deepEqual(actual, [4, 1, 2, 3]);
    actual = update([1, 2, 3], {'$unshift': [4, 5]});
    assert.deepEqual(actual, [4, 5, 1, 2, 3]);
    actual = update([1, 2, 3], {'$unshift': [[4, 5]]});
    assert.deepEqual(actual, [[4, 5], 1, 2, 3]);
  });

  it('should handle $push command', function () {
    var actual = update([1, 2, 3], {'$push': [4]});
    assert.deepEqual(actual, [1, 2, 3, 4]);
    actual = update([1, 2, 3], {'$push': [4, 5]});
    assert.deepEqual(actual, [1, 2, 3, 4, 5]);
    actual = update([1, 2, 3], {'$push': [[4, 5]]});
    assert.deepEqual(actual, [1, 2, 3, [4, 5]]);
  });

  it('should handle $splice command', function () {
    var instance = [1, 2, {a: [12, 17, 15]}];
    var actual = update(instance, {2: {a: {$splice: [[1, 1, 13, 14]]}}});
    assert.deepEqual(instance, [1, 2, {a: [12, 17, 15]}]);
    assert.deepEqual(actual, [1, 2, {a: [12, 13, 14, 15]}]);
  });

  it('should handle bad $splice command', function () {
    var instance = [1, 2, {a: [12, 17, 15]}];
    throwsWithMessage(function () {
      update(instance, {2: {a: {$splice: [1, 1, 13, 14]}}});
    }, '[tcomb] Invalid argument splices supplied to immutability helper { $splice: splices } (expected an array of arrays)');
  });

  it('should handle $remove command', function () {
    var instance = {a: 1, b: 2};
    var actual = update(instance, {'$remove': ['a']});
    assert.deepEqual(instance, {a: 1, b: 2});
    assert.deepEqual(actual, {b: 2});
  });

  it('should handle $swap command', function () {
    var instance = [1, 2, 3, 4];
    var actual = update(instance, {'$swap': {from: 1, to: 2}});
    assert.deepEqual(instance, [1, 2, 3, 4]);
    assert.deepEqual(actual, [1, 3, 2, 4]);
  });

  it('can $merge and $remove at once', function () {
    var instance = {a: [1, 2], b: true};
    var actual = update(instance, { $merge: {a: [1, 2, 3] }, $remove: ['b'] });
    assert.deepEqual(instance, {a: [1, 2], b: true});
    assert.deepEqual(actual, {a: [1, 2, 3]});
  });

  it('should not change the reference when no changes occurs', function () {
    var p1 = {x: 0, y: 1};
    var p2 = update(p1, {});
    assert.strictEqual(p1, p2);
    var p3 = update(p1, {x: {$set: 0}});
    assert.strictEqual(p1, p3);

    var n1 = {a: {b: {c: 1}}};
    var n2 = t.update(n1, {a: {b: {c: {$set: 1}}}});
    assert.strictEqual(n1, n2);

    var m1 = {a: 1, b: 2};
    var m2 = t.update(m1, {a: {$set: 2}, b: {$set: 2}});
    assert.equal(m1 === m2, false);
  });

  describe('structs', function () {

    var instance = new Point({x: 0, y: 1});

    it('should handle $set command', function () {
      var updated = update(instance, {x: {$set: 1}});
      assert.deepEqual(instance, {x: 0, y: 1});
      assert.deepEqual(updated, {x: 1, y: 1});
    });

    it('should handle $apply command', function () {
      var updated = update(instance, {x: {$apply: function (x) {
        return x + 2;
      }}});
      assert.deepEqual(instance, {x: 0, y: 1});
      assert.deepEqual(updated, {x: 2, y: 1});
    });

    it('should handle $merge command', function () {
      var updated = update(instance, {'$merge': {x: 2, y: 2}});
      assert.deepEqual(instance, {x: 0, y: 1});
      assert.deepEqual(updated, {x: 2, y: 2});
      var Nested = t.struct({
        a: t.Number,
        b: t.struct({
          c: t.Number,
          d: t.Number,
          e: t.Number
        })
      });
      instance = new Nested({a: 1, b: {c: 2, d: 3, e: 4}});
      updated = update(instance, {b: {'$merge': {c: 5, e: 6}}});
      assert.deepEqual(instance, {a: 1, b: {c: 2, d: 3, e: 4}});
      assert.deepEqual(updated, {a: 1, b: {c: 5, d: 3, e: 6}});
    });

    it('should not change the reference when no changes occurs', function () {
      var p1 = new Point({x: 0, y: 1});
      var p2 = Point.update(p1, {});
      assert.strictEqual(p1, p2);
      var p3 = Point.update(p1, {x: {$set: 0}});
      assert.strictEqual(p1, p3);
    });

  });

  describe('tuples', function () {

    var instance = Tuple(['a', 1]);

    it('should handle $set command', function () {
      var updated = update(instance, {0: {$set: 'b'}});
      assert.deepEqual(updated, ['b', 1]);
    });

  });

  describe('lists', function () {

    var instance = List([1, 2, 3, 4]);

    it('should handle $set command', function () {
      var updated = update(instance, {2: {$set: 5}});
      assert.deepEqual(updated, [1, 2, 5, 4]);
    });

    it('should handle $splice command', function () {
      var updated = update(instance, {$splice: [[1, 2, 5, 6]]});
      assert.deepEqual(updated, [1, 5, 6, 4]);
    });

    it('should handle $concat command', function () {
      var updated = update(instance, {$push: [5]});
      assert.deepEqual(updated, [1, 2, 3, 4, 5]);
      updated = update(instance, {$push: [5, 6]});
      assert.deepEqual(updated, [1, 2, 3, 4, 5, 6]);
    });

    it('should handle $prepend command', function () {
      var updated = update(instance, {$unshift: [5]});
      assert.deepEqual(updated, [5, 1, 2, 3, 4]);
      updated = update(instance, {$unshift: [5, 6]});
      assert.deepEqual(updated, [5, 6, 1, 2, 3, 4]);
    });

    it('should handle $swap command', function () {
      var updated = update(instance, {$swap: {from: 1, to: 2}});
      assert.deepEqual(updated, [1, 3, 2, 4]);
    });

  });

  describe('dicts', function () {

    var instance = Dict({a: 1, b: 2});

    it('should handle $set command', function () {
      var updated = update(instance, {a: {$set: 2}});
      assert.deepEqual(updated, {a: 2, b: 2});
      updated = update(instance, {c: {$set: 3}});
      assert.deepEqual(updated, {a: 1, b: 2, c: 3});
    });

    it('should handle $remove command', function () {
      var updated = update(instance, {$remove: ['a']});
      assert.deepEqual(updated, {b: 2});
    });

    it('can $merge and $remove at once', function () {
      var updated = update(instance, { $merge: {a: [1, 2, 3] }, $remove: ['b'] });
      assert.deepEqual(updated, {a: [1, 2, 3]});
    });

  });

  describe('memory saving', function () {

    it('should reuse members that are not updated', function () {
      var Struct = t.struct({
        a: t.Number,
        b: t.String,
        c: t.tuple([t.Number, t.Number])
      });
      var List = t.list(Struct);
      var instance = List([{
        a: 1,
        b: 'one',
        c: [1000, 1000000]
      }, {
        a: 2,
        b: 'two',
        c: [2000, 2000000]
      }]);

      var updated = update(instance, {
        1: {
          a: {$set: 119}
        }
      });

      assert.strictEqual(updated[0], instance[0]);
      assert.notStrictEqual(updated[1], instance[1]);
      assert.strictEqual(updated[1].c, instance[1].c);
    });
  });

  describe('all together now', function () {

    it('should handle mixed commands', function () {
      var Struct = t.struct({
        a: t.Number,
        b: Tuple,
        c: List,
        d: Dict
      });
      var instance = new Struct({
        a: 1,
        b: ['a', 1],
        c: [1, 2, 3, 4],
        d: {a: 1, b: 2}
      });
      var updated = update(instance, {
        a: {$set: 1},
        b: {0: {$set: 'b'}},
        c: {2: {$set: 5}},
        d: {$remove: ['a']}
      });
      assert.deepEqual(updated, {
        a: 1,
        b: ['b', 1],
        c: [1, 2, 5, 4],
        d: {b: 2}
      });
    });

    it('should handle nested structures', function () {
      var Struct = t.struct({
        a: t.struct({
          b: t.tuple([
            t.String,
            t.list(t.Number)
          ])
        })
      });
      var instance = new Struct({
        a: {
          b: ['a', [1, 2, 3]]
        }
      });
      var updated = update(instance, {
        a: {b: {1: {2: {$set: 4}}}}
      });
      assert.deepEqual(updated, {
        a: {
          b: ['a', [1, 2, 4]]
        }
      });
    });

  });

});
<commit_msg>add failing tests, ref #172<commit_after>/* globals describe, it */
var assert = require('assert');
var t = require('../index');
var throwsWithMessage = require('./util').throwsWithMessage;

describe('t.update(instance, spec)', function () {

  var update = t.update;
  var Tuple = t.tuple([t.String, t.Number]);
  var List = t.list(t.Number);
  var Dict = t.dict(t.String, t.Number);
  var Point = t.struct({
    x: t.Number,
    y: t.Number
  });

  it('should throw if spec is invalid', function () {
    throwsWithMessage(function () {
      t.update({});
    }, '[tcomb] Invalid argument spec undefined supplied to function update(instance, spec): expected an object containing commands');
  });

  it('should handle $set command', function () {
    var instance = 1;
    var actual = update(instance, {$set: 2});
    assert.deepEqual(actual, 2);
    instance = [1, 2, 3];
    actual = update(instance, {1: {'$set': 4}});
    assert.deepEqual(instance, [1, 2, 3]);
    assert.deepEqual(actual, [1, 4, 3]);
  });

  it('$set and null value, fix #65', function () {
    var NullStruct = t.struct({a: t.Number, b: t.maybe(t.Number)});
    var instance = new NullStruct({a: 1});
    var updated = update(instance, {b: {$set: 2}});
    assert.deepEqual(instance, {a: 1, b: null});
    assert.deepEqual(updated, {a: 1, b: 2});
  });

  it('should handle $apply command', function () {
    var $apply = function (n) { return n + 1; };
    var instance = 1;
    var actual = update(instance, {$apply: $apply});
    assert.deepEqual(actual, 2);
    instance = [1, 2, 3];
    actual = update(instance, {1: {'$apply': $apply}});
    assert.deepEqual(instance, [1, 2, 3]);
    assert.deepEqual(actual, [1, 3, 3]);
  });

  it('should $apply dates', function () {
    var instance = new Date(1973, 10, 30);
    var actual = update(instance, { $apply: function (date) { return date.getFullYear(); } });
    assert.equal(actual, 1973);
  });

  it('should $apply regexps', function () {
    var instance = /a/;
    var actual = update(instance, { $apply: function (regexp) { return regexp.source; } });
    assert.equal(actual, 'a');
  });

  it('should handle $unshift command', function () {
    var actual = update([1, 2, 3], {'$unshift': [4]});
    assert.deepEqual(actual, [4, 1, 2, 3]);
    actual = update([1, 2, 3], {'$unshift': [4, 5]});
    assert.deepEqual(actual, [4, 5, 1, 2, 3]);
    actual = update([1, 2, 3], {'$unshift': [[4, 5]]});
    assert.deepEqual(actual, [[4, 5], 1, 2, 3]);
  });

  it('should handle $push command', function () {
    var actual = update([1, 2, 3], {'$push': [4]});
    assert.deepEqual(actual, [1, 2, 3, 4]);
    actual = update([1, 2, 3], {'$push': [4, 5]});
    assert.deepEqual(actual, [1, 2, 3, 4, 5]);
    actual = update([1, 2, 3], {'$push': [[4, 5]]});
    assert.deepEqual(actual, [1, 2, 3, [4, 5]]);
  });

  it('should handle $splice command', function () {
    var instance = [1, 2, {a: [12, 17, 15]}];
    var actual = update(instance, {2: {a: {$splice: [[1, 1, 13, 14]]}}});
    assert.deepEqual(instance, [1, 2, {a: [12, 17, 15]}]);
    assert.deepEqual(actual, [1, 2, {a: [12, 13, 14, 15]}]);
  });

  it('should handle bad $splice command', function () {
    var instance = [1, 2, {a: [12, 17, 15]}];
    throwsWithMessage(function () {
      update(instance, {2: {a: {$splice: [1, 1, 13, 14]}}});
    }, '[tcomb] Invalid argument splices supplied to immutability helper { $splice: splices } (expected an array of arrays)');
  });

  it('should handle $remove command', function () {
    var instance = {a: 1, b: 2};
    var actual = update(instance, {'$remove': ['a']});
    assert.deepEqual(instance, {a: 1, b: 2});
    assert.deepEqual(actual, {b: 2});
  });

  it('should handle $swap command', function () {
    var instance = [1, 2, 3, 4];
    var actual = update(instance, {'$swap': {from: 1, to: 2}});
    assert.deepEqual(instance, [1, 2, 3, 4]);
    assert.deepEqual(actual, [1, 3, 2, 4]);
  });

  it('can $merge and $remove at once', function () {
    var instance = {a: [1, 2], b: true};
    var actual = update(instance, { $merge: {a: [1, 2, 3] }, $remove: ['b'] });
    assert.deepEqual(instance, {a: [1, 2], b: true});
    assert.deepEqual(actual, {a: [1, 2, 3]});
  });

  it('should not change the reference when no changes occurs', function () {
    var p1 = {x: 0, y: 1};
    var p2 = update(p1, {});
    assert.strictEqual(p1, p2);
    var p3 = update(p1, {x: {$set: 0}});
    assert.strictEqual(p1, p3);

    var n1 = {a: {b: {c: 1}}};
    var n2 = t.update(n1, {a: {b: {c: {$set: 1}}}});
    assert.strictEqual(n1, n2);

    var m1 = {a: 1, b: 2};
    var m2 = t.update(m1, {a: {$set: 2}, b: {$set: 2}});
    assert.equal(m1 === m2, false);
  });

  describe('structs', function () {

    var instance = new Point({x: 0, y: 1});

    it('should handle $set command', function () {
      var updated = update(instance, {x: {$set: 1}});
      assert.deepEqual(instance, {x: 0, y: 1});
      assert.deepEqual(updated, {x: 1, y: 1});
    });

    it('should handle $apply command', function () {
      var updated = update(instance, {x: {$apply: function (x) {
        return x + 2;
      }}});
      assert.deepEqual(instance, {x: 0, y: 1});
      assert.deepEqual(updated, {x: 2, y: 1});
    });

    it('should handle $merge command', function () {
      var updated = update(instance, {'$merge': {x: 2, y: 2}});
      assert.deepEqual(instance, {x: 0, y: 1});
      assert.deepEqual(updated, {x: 2, y: 2});
      var Nested = t.struct({
        a: t.Number,
        b: t.struct({
          c: t.Number,
          d: t.Number,
          e: t.Number
        })
      });
      instance = new Nested({a: 1, b: {c: 2, d: 3, e: 4}});
      updated = update(instance, {b: {'$merge': {c: 5, e: 6}}});
      assert.deepEqual(instance, {a: 1, b: {c: 2, d: 3, e: 4}});
      assert.deepEqual(updated, {a: 1, b: {c: 5, d: 3, e: 6}});
    });

    it('should not change the reference when no changes occurs', function () {
      var p1 = new Point({x: 0, y: 1});
      var p2 = Point.update(p1, {});
      assert.strictEqual(p1, p2);
      var p3 = Point.update(p1, {x: {$set: 0}});
      assert.strictEqual(p1, p3);
    });

  });

  describe('tuples', function () {

    var instance = Tuple(['a', 1]);

    it('should handle $set command', function () {
      var updated = update(instance, {0: {$set: 'b'}});
      assert.deepEqual(updated, ['b', 1]);
    });

  });

  describe('lists', function () {

    var instance = List([1, 2, 3, 4]);

    it('should handle $set command', function () {
      var updated = update(instance, {2: {$set: 5}});
      assert.deepEqual(updated, [1, 2, 5, 4]);
    });

    it('should handle $splice command', function () {
      var updated = update(instance, {$splice: [[1, 2, 5, 6]]});
      assert.deepEqual(updated, [1, 5, 6, 4]);
    });

    it('should handle $concat command', function () {
      var updated = update(instance, {$push: [5]});
      assert.deepEqual(updated, [1, 2, 3, 4, 5]);
      updated = update(instance, {$push: [5, 6]});
      assert.deepEqual(updated, [1, 2, 3, 4, 5, 6]);
    });

    it('should handle $prepend command', function () {
      var updated = update(instance, {$unshift: [5]});
      assert.deepEqual(updated, [5, 1, 2, 3, 4]);
      updated = update(instance, {$unshift: [5, 6]});
      assert.deepEqual(updated, [5, 6, 1, 2, 3, 4]);
    });

    it('should handle $swap command', function () {
      var updated = update(instance, {$swap: {from: 1, to: 2}});
      assert.deepEqual(updated, [1, 3, 2, 4]);
    });

  });

  describe('dicts', function () {

    var instance = Dict({a: 1, b: 2});

    it('should handle $set command', function () {
      var updated = update(instance, {a: {$set: 2}});
      assert.deepEqual(updated, {a: 2, b: 2});
      updated = update(instance, {c: {$set: 3}});
      assert.deepEqual(updated, {a: 1, b: 2, c: 3});
    });

    it('should handle $remove command', function () {
      var updated = update(instance, {$remove: ['a']});
      assert.deepEqual(updated, {b: 2});
    });

    it('can $merge and $remove at once', function () {
      var updated = update(instance, { $merge: {a: [1, 2, 3] }, $remove: ['b'] });
      assert.deepEqual(updated, {a: [1, 2, 3]});
    });

  });

  describe('memory saving', function () {

    it('should reuse members that are not updated', function () {
      var Struct = t.struct({
        a: t.Number,
        b: t.String,
        c: t.tuple([t.Number, t.Number])
      });
      var List = t.list(Struct);
      var instance = List([{
        a: 1,
        b: 'one',
        c: [1000, 1000000]
      }, {
        a: 2,
        b: 'two',
        c: [2000, 2000000]
      }]);

      var updated = update(instance, {
        1: {
          a: {$set: 119}
        }
      });

      assert.strictEqual(updated[0], instance[0]);
      assert.notStrictEqual(updated[1], instance[1]);
      assert.strictEqual(updated[1].c, instance[1].c);
    });
  });

  describe('all together now', function () {

    it('should handle mixed commands', function () {
      var Struct = t.struct({
        a: t.Number,
        b: Tuple,
        c: List,
        d: Dict
      });
      var instance = new Struct({
        a: 1,
        b: ['a', 1],
        c: [1, 2, 3, 4],
        d: {a: 1, b: 2}
      });
      var updated = update(instance, {
        a: {$set: 1},
        b: {0: {$set: 'b'}},
        c: {2: {$set: 5}},
        d: {$remove: ['a']}
      });
      assert.deepEqual(updated, {
        a: 1,
        b: ['b', 1],
        c: [1, 2, 5, 4],
        d: {b: 2}
      });
    });

    it('should handle nested structures', function () {
      var Struct = t.struct({
        a: t.struct({
          b: t.tuple([
            t.String,
            t.list(t.Number)
          ])
        })
      });
      var instance = new Struct({
        a: {
          b: ['a', [1, 2, 3]]
        }
      });
      var updated = update(instance, {
        a: {b: {1: {2: {$set: 4}}}}
      });
      assert.deepEqual(updated, {
        a: {
          b: ['a', [1, 2, 4]]
        }
      });
    });

  });

});
<|endoftext|>


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

var request = require('request')
  , upload = require('../lib/upload').upload

var RES_URL = 'http://gyazo.com/4127de4be736f098edf9492f6cdf4925'

var requestURL = null
  , form = {}

// stub request
request.post = function (url, callback) {
  requestURL = url

  process.nextTick(function () {
    if (callback) callback(null, {}, RES_URL)
  })

  return {
    form: function () {
      form = {}
      return {
        append: function (key, value) {
          form[key] = value
        }
      }
    }
  }
}

test('upload', function (t) {
  t.plan(4)

  upload(__dirname + '/cat.gif', function (err, url) {
    t.equal(url, RES_URL)
  })

  t.equal(requestURL, 'http://upload.gyazo.com/upload.cgi')

  t.ok(form.imagedata)
  t.ok(form.id)
})

test('upload with host option', function (t) {
  t.plan(3)

  process.env.GYAZO_HOST = 'http://syazo.com/'

  upload(__dirname + '/cat.gif', function (err, url) {
    t.equal(url, RES_URL)
  })

  t.equal(requestURL, 'http://syazo.com/upload.cgi')

  process.env.GYAZO_HOST = 'http://syazo.com'
  upload(__dirname + '/cat.gif')

  t.equal(requestURL, 'http://syazo.com/upload.cgi')
})
<commit_msg>Add id option test<commit_after>var test = require('tape')

var request = require('request')
  , fs = require('fs')
  , upload = require('../lib/upload').upload

var RES_URL = 'http://gyazo.com/4127de4be736f098edf9492f6cdf4925'

var requestURL = null
  , form = {}

// stub request
request.post = function (url, callback) {
  requestURL = url

  process.nextTick(function () {
    if (callback) callback(null, {}, RES_URL)
  })

  return {
    form: function () {
      form = {}
      return {
        append: function (key, value) {
          form[key] = value
        }
      }
    }
  }
}

// stub id
fs.readFileSync = function () {
  return 'gyazo id'
}

test('upload', function (t) {
  t.plan(4)

  upload(__dirname + '/cat.gif', function (err, url) {
    t.equal(url, RES_URL)
  })

  t.equal(requestURL, 'http://upload.gyazo.com/upload.cgi')

  t.ok(form.imagedata)
  t.equal(form.id, 'gyazo id')
})

test('upload with host option', function (t) {
  t.plan(3)

  process.env.GYAZO_HOST = 'http://syazo.com/'

  upload(__dirname + '/cat.gif', function (err, url) {
    t.equal(url, RES_URL)
  })

  t.equal(requestURL, 'http://syazo.com/upload.cgi')

  process.env.GYAZO_HOST = 'http://syazo.com'
  upload(__dirname + '/cat.gif')

  t.equal(requestURL, 'http://syazo.com/upload.cgi')
})

test('upload with id option', function (t) {
  process.env.GYAZO_ID = '/path/to/idfile'

  var readPath
  fs.readFileSync = function (filePath) {
    readPath = filePath
    return 'gyazo id'
  }

  upload(__dirname + '/cat.gif')

  t.equal(readPath, '/path/to/idfile')

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


<commit_before>'use strict';

var request = require('supertest');
var AnyFetchProvider = require('anyfetch-provider');
var Anyfetch = require('anyfetch');
var sinon = require('sinon');
require('should');

var config = require('../config/configuration.js');
var serverConfig = require('../lib/');

describe("Workflow", function () {
  before(AnyFetchProvider.debug.cleanTokens);

  // Create a fake HTTP server
  Anyfetch.setApiUrl('http://localhost:1337');
  var apiServer = Anyfetch.createMockServer();
  apiServer.listen(1337);

  before(function(done) {
    AnyFetchProvider.debug.createToken({
      anyfetchToken: 'fake_gc_access_token',
      data: {
        callbackUrl: config.providerUrl + "/init/callback",
        tokens: {
          refresh_token: config.testRefreshToken
        }
      },
      accountName: 'account_name',
      cursor: '66'
    }, done);
  });

  it("should upload data to AnyFetch", function(done) {
    var originalQueueWorker = serverConfig.workers.addition;
    serverConfig.workers.addition = function(job) {
      var spy = sinon.spy(job.anyfetchClient, "sendDocumentAndFile");

      job.task.should.have.property('id');
      job.task.should.have.property('title');
      job.task.should.have.property('downloadUrl');
      job.task.should.have.property('type');
      job.task.should.have.property('date');

      originalQueueWorker(job, function(err) {
        spy.callCount.should.eql(1);
        done(err);
      });
    };
    var server = AnyFetchProvider.createServer(serverConfig.connectFunctions, serverConfig.updateAccount, serverConfig.workers, serverConfig.config);

    request(server)
      .post('/update')
      .send({
        access_token: 'fake_gc_access_token',
        api_url: 'http://localhost:1337'
      })
      .expect(202)
      .end(function(err) {
        if(err) {
          throw err;
        }
      });
  });
});
<commit_msg>fix test with new lib<commit_after>'use strict';

var request = require('supertest');
var AnyFetchProvider = require('anyfetch-provider');
var Anyfetch = require('anyfetch');
var sinon = require('sinon');
require('should');

var config = require('../config/configuration.js');
var serverConfig = require('../lib/');

describe("Workflow", function () {
  before(AnyFetchProvider.debug.cleanTokens);

  // Create a fake HTTP server
  Anyfetch.setApiUrl('http://localhost:1337');
  var apiServer = Anyfetch.createMockServer();
  apiServer.listen(1337);

  before(function(done) {
    AnyFetchProvider.debug.createToken({
      anyfetchToken: 'fake_gc_access_token',
      data: {
        callbackUrl: config.providerUrl + "/init/callback",
        tokens: {
          refresh_token: config.testRefreshToken
        }
      },
      accountName: 'account_name',
      cursor: '66'
    }, done);
  });

  it("should upload data to AnyFetch", function(done) {
    var originalQueueWorker = serverConfig.workers.addition;
    serverConfig.workers.addition = function(job) {
      var spy = sinon.spy(job.anyfetchClient, "sendDocumentAndFile");

      job.task.should.have.property('id');
      job.task.should.have.property('title');
      job.task.should.have.property('downloadUrl');
      job.task.should.have.property('type');
      job.task.should.have.property('date');

      originalQueueWorker(job, function(err) {
        spy.callCount.should.eql(1);
        done(err);
      });
    };
    var server = AnyFetchProvider.createServer(serverConfig.connectFunctions, serverConfig.updateAccount, serverConfig.workers, serverConfig.config);

    request(server)
      .post('/update')
      .send({
        access_token: 'fake_gc_access_token',
        api_url: 'http://localhost:1337',
        documents_per_update: 2500
      })
      .expect(202)
      .end(function(err) {
        if(err) {
          throw err;
        }
      });
  });
});
<|endoftext|>


<commit_before>$('escape').wrapper(function(){

    this.self= this, 'use strict';

    var isDown= false;

// get all dom elements
    var allElements= self.document.body.querySelectorAll('*');

//  events
    self.events= {
        SCROLL : 'phT_scroll',
        TAPP : 'phT_tapp',
        STROCKE : 'phT_strocke',
        MOVE : 'phT_move',
        TOUCH : 'phT_touch',
        RELEASE : 'phT_release',
        TOUCHSTART : (self.navigator.isTouch ? 'touchstart' : 'mousedown'),
        TOUCHMOVE : (self.navigator.isTouch ? 'touchmove' : 'mousemove'),
        TOUCHEND : (self.navigator.isTouch ? 'touchend' : 'mouseup')
    };

//  physical touch meta data
    var touchMeta= [];
    var overScrollMeta= [];

/*  ---     Classes     --- */

    var EventObjectExtension= function(index){
/*      new properties are:
            event.timeout
            event.speed
            event.movement          */
        var now= new Date().getTime();
        this.timeout= (now - touchMeta[index].lastTime) / 1000;

        if(this.timeout === 0){
            this.timeout= touchMeta[index].lastTimeout;
        }else{
            touchMeta[index].lastTimeout= this.timeout;
            }
        this.position= { x: this.screenX, y: this.screenY };

        if( (touchMeta[index].lastPos.y != this.position.y && touchMeta[index].lastMovement.x != this.position.x) || (this.timeout > 0.1) ){
            this.movement= touchMeta[index].lastMovement= {x: (this.position.x - touchMeta[index].lastPos.x),
                                                           y: (this.position.y - touchMeta[index].lastPos.y)};
        }else{
            this.movement= touchMeta[index].lastMovement;
            }

        this.speed= {x: (this.movement.x / this.timeout),
                     y: (this.movement.y / this.timeout)};

        touchMeta[index].lastPos= this.position;
        touchMeta[index].lastTime= now;
        };

    var OverScrollData= function(target, direction, y, speed){
        this.cursorY= y;
        this.cursorSpeed= speed;
        this.lastUpdate= 0;
        this.direction= direction;
        this.target= target;
        this.release= function(){
            const backSpeed= 2000;

            var now= new Date().getTime();
            var timeout= (now - this.lastUpdate) / 1000;
            this.lastUpdate= now;
            this.cursorY+= this.cursorSpeed * timeout;
            var newStretch= stretching(this.cursorY);

            if(this.direction == OverScrollData.DOWN){
                var stretchDelta= Math.abs(newStretch - parseInt(self.getComputedStyle(this.target.firstElementChild).marginTop.replace('px', '')));
                var block= this.target.firstElementChild;
                var margin= 'marginTop';
            }else if(this.direction == OverScrollData.UP){
                var stretchDelta= Math.abs(newStretch - parseInt(self.getComputedStyle(this.target.lastElementChild).marginBottom.replace('px', '')));
                var block= this.target.lastElementChild;
                var margin= 'marginBottom';
                }

            if(this.cursorSpeed === 0 || stretchDelta <= 1){
                this.cursorY-= backSpeed * timeout;
                if(this.cursorY < 0) this.cursorY= 0;
                self.console.log('cursorY: '+this.cursorY);
                block.style[margin]= stretching(this.cursorY)+'px';
                }else{
                    block.style[margin]= newStretch;
                    }
            if(newStretch > 0.5){
                var target= this;
                self.requestAnimationFrame(function(){ target.release(); });
            }else{
                block.style[margin]= '0';
                overScrollMeta.splice(overScrollMeta.indexOf(this), 1);
                }
            };
        };
    OverScrollData.UP= '1';
    OverScrollData.DOWN= '0';

/*  ---     Hooks   --- */

//  global init hook
    var initHook= function(e, index){
        touchMeta[index]= {
            lastTime : (new Date().getTime()),
            lastPos : { x: e.screenX, y: e.screenY },
            lastMovement : {x: 0, y: 0},
            lastTimeout : 0
            };
        };

//  global movment hook
    var movmentHook= function(e, index){
        EventObjectExtension.apply(e, [index]);

//      grabbed scroll
        if( (e.movement.y !== 0) && (self.getComputedStyle(this).getPropertyValue('overflow') == 'hidden') && (!this.hasAttribute('physicalTouch') || this.getAttribute('physicalTouch') != 'false') ){
            physicalScroll(this, e.movement.y, true);
            }
        };

//  global release hook
    var releaseHook= function(e, index){
        EventObjectExtension.apply(e, [index]);

//      released remaining velocity scroll
        if( (self.getComputedStyle(this).getPropertyValue('overflow') == 'hidden') && (!this.hasAttribute('physicalTouch') || this.getAttribute('physicalTouch') != 'false')){
            physicalScroll(this, e.speed.y, false);
            }
        };

//  attaching all Hooks
    allElements.forEach(function(item){
        item._physicalID= -1;

        item.addEventListener(self.events.TOUCHSTART, function(e){
            if(self.navigator.isTouch){
                var emitter= this;
                e.touches.forEach(function(item, i){
                    initHook.apply(emitter, [item, i]);
                    });
            }else{
                isDown= true;
                initHook.apply(this, [e, 0]);
                }
            });

        item.addEventListener(self.events.TOUCHMOVE, function(e){
            if(self.navigator.isTouch){
                var emitter= this;
                e.touches.forEach(function(item, i){
                    movmentHook.apply(emitter, [item, i]);
                    });
            }else if(isDown){
                movmentHook.apply(this, [e, 0]);
                }
            });

        item.addEventListener(self.events.TOUCHEND, function(e){
            if(self.navigator.isTouch){
                var emitter= this;
                e.touches.forEach(function(item, i){
                    releaseHook.apply(emitter, [item, i]);
                    });
            }else{
                isDown= false;
                releaseHook.apply(this, [e, 0]);
                }
            });
        });

/* ---      physical functions      --- */

    var physicalScroll= function(target, movement, isGrabbed){

//      invert movement direction to scroll direction
        var change= movement * -1;

//      if the scrolled element is still grabbed
        if(isGrabbed){
            target.scrollTop+= change;

//          on overscrolling at the top
            if(target.scrollTop === 0 && movement > 0){
                if(target._physicalID < 0 || !overScrollMeta[target._physicalID]){
                    overScrollMeta.push(new OverScrollData(target, OverScrollData.DOWN, 0, 0));
                    target._physicalID= overScrollMeta.length - 1;
                    }
                var sData= overScrollMeta[target._physicalID];
                sData.cursorY+= Math.abs(change);
                target.firstElementChild.style.marginTop= stretching(sData.cursorY)+'px';
                target.scrollTop= 0;

//          on overscrolling at the bottom
            }else if(target.scrollTop == target.scrollTopMax && movement < 0){
                if(target._physicalID < 0 || !overScrollMeta[target._physicalID]){
                    overScrollMeta.push(new OverScrollData(target, OverScrollData.UP, 0, 0));
                    target._physicalID= overScrollMeta.length - 1;
                    }
                var sData= overScrollMeta[target._physicalID];
                sData.cursorY+= Math.abs(change);
                target.lastElementChild.style.marginBottom= stretching(sData.cursorY)+'px';
                target.scrollTop= target.scrollTopMax;
                }

//      if the object was released
        }else{
            if(target._physicalID > -1 && overScrollMeta[target._physicalID]){
                var sData= overScrollMeta[target._physicalID];
                sData.lastUpdate= new Date().getTime();
                sData.release();
                }
            }
        };

    var stretching= function(F){
        const D= 3;

        return F / D;
        };
});
<commit_msg>touch release fix<commit_after>$('escape').wrapper(function(){

    this.self= this, 'use strict';

    var isDown= false;

// get all dom elements
    var allElements= self.document.body.querySelectorAll('*');

//  events
    self.events= {
        SCROLL : 'phT_scroll',
        TAPP : 'phT_tapp',
        STROCKE : 'phT_strocke',
        MOVE : 'phT_move',
        TOUCH : 'phT_touch',
        RELEASE : 'phT_release',
        TOUCHSTART : (self.navigator.isTouch ? 'touchstart' : 'mousedown'),
        TOUCHMOVE : (self.navigator.isTouch ? 'touchmove' : 'mousemove'),
        TOUCHEND : (self.navigator.isTouch ? 'touchend' : 'mouseup')
    };

//  physical touch meta data
    var touchMeta= [];
    var overScrollMeta= [];

/*  ---     Classes     --- */

    var EventObjectExtension= function(index){
/*      new properties are:
            event.timeout
            event.speed
            event.movement          */
        var now= new Date().getTime();
        this.timeout= (now - touchMeta[index].lastTime) / 1000;

        if(this.timeout === 0){
            this.timeout= touchMeta[index].lastTimeout;
        }else{
            touchMeta[index].lastTimeout= this.timeout;
            }
        this.position= { x: this.screenX, y: this.screenY };

        if( (touchMeta[index].lastPos.y != this.position.y && touchMeta[index].lastMovement.x != this.position.x) || (this.timeout > 0.1) ){
            this.movement= touchMeta[index].lastMovement= {x: (this.position.x - touchMeta[index].lastPos.x),
                                                           y: (this.position.y - touchMeta[index].lastPos.y)};
        }else{
            this.movement= touchMeta[index].lastMovement;
            }

        this.speed= {x: (this.movement.x / this.timeout),
                     y: (this.movement.y / this.timeout)};

        touchMeta[index].lastPos= this.position;
        touchMeta[index].lastTime= now;
        };

    var OverScrollData= function(target, direction, y, speed){
        this.cursorY= y;
        this.cursorSpeed= speed;
        this.lastUpdate= 0;
        this.direction= direction;
        this.target= target;
        this.release= function(){
            const backSpeed= 2000;

            var now= new Date().getTime();
            var timeout= (now - this.lastUpdate) / 1000;
            this.lastUpdate= now;
            this.cursorY+= this.cursorSpeed * timeout;
            var newStretch= stretching(this.cursorY);

            if(this.direction == OverScrollData.DOWN){
                var stretchDelta= Math.abs(newStretch - parseInt(self.getComputedStyle(this.target.firstElementChild).marginTop.replace('px', '')));
                var block= this.target.firstElementChild;
                var margin= 'marginTop';
            }else if(this.direction == OverScrollData.UP){
                var stretchDelta= Math.abs(newStretch - parseInt(self.getComputedStyle(this.target.lastElementChild).marginBottom.replace('px', '')));
                var block= this.target.lastElementChild;
                var margin= 'marginBottom';
                }

            if(this.cursorSpeed === 0 || stretchDelta <= 1){
                this.cursorY-= backSpeed * timeout;
                if(this.cursorY < 0) this.cursorY= 0;
                self.console.log('cursorY: '+this.cursorY);
                block.style[margin]= stretching(this.cursorY)+'px';
                }else{
                    block.style[margin]= newStretch;
                    }
            if(newStretch > 0.5){
                var target= this;
                self.requestAnimationFrame(function(){ target.release(); });
            }else{
                block.style[margin]= '0';
                overScrollMeta.splice(overScrollMeta.indexOf(this), 1);
                }
            };
        };
    OverScrollData.UP= '1';
    OverScrollData.DOWN= '0';

/*  ---     Hooks   --- */

//  global init hook
    var initHook= function(e, index){
        touchMeta[index]= {
            lastTime : (new Date().getTime()),
            lastPos : { x: e.screenX, y: e.screenY },
            lastMovement : {x: 0, y: 0},
            lastTimeout : 0
            };
        };

//  global movment hook
    var movmentHook= function(e, index){
        EventObjectExtension.apply(e, [index]);

//      grabbed scroll
        if( (e.movement.y !== 0) && (self.getComputedStyle(this).getPropertyValue('overflow') == 'hidden') && (!this.hasAttribute('physicalTouch') || this.getAttribute('physicalTouch') != 'false') ){
            physicalScroll(this, e.movement.y, true);
            }
        };

//  global release hook
    var releaseHook= function(e, index){
        EventObjectExtension.apply(e, [index]);

//      released remaining velocity scroll
        if( (self.getComputedStyle(this).getPropertyValue('overflow') == 'hidden') && (!this.hasAttribute('physicalTouch') || this.getAttribute('physicalTouch') != 'false')){
            physicalScroll(this, e.speed.y, false);
            }
        };

//  attaching all Hooks
    allElements.forEach(function(item){
        item._physicalID= -1;

        item.addEventListener(self.events.TOUCHSTART, function(e){
            if(self.navigator.isTouch){
                var emitter= this;
                e.touches.forEach(function(item, i){
                    initHook.apply(emitter, [item, i]);
                    });
            }else{
                isDown= true;
                initHook.apply(this, [e, 0]);
                }
            });

        item.addEventListener(self.events.TOUCHMOVE, function(e){
            if(self.navigator.isTouch){
                var emitter= this;
                e.touches.forEach(function(item, i){
                    movmentHook.apply(emitter, [item, i]);
                    });
            }else if(isDown){
                movmentHook.apply(this, [e, 0]);
                }
            });

        item.addEventListener(self.events.TOUCHEND, function(e){
            if(self.navigator.isTouch){
                var emitter= this;
                touchMeta.forEach(function(item, i){
                    if(!e.touches[i]){
                        releaseHook.apply(emitter, [e, i]);
                        }
                    });
            }else{
                isDown= false;
                releaseHook.apply(this, [e, 0]);
                }
            });
        });

/* ---      physical functions      --- */

    var physicalScroll= function(target, movement, isGrabbed){

//      invert movement direction to scroll direction
        var change= movement * -1;

//      if the scrolled element is still grabbed
        if(isGrabbed){
            target.scrollTop+= change;

//          on overscrolling at the top
            if(target.scrollTop === 0 && movement > 0){
                if(target._physicalID < 0 || !overScrollMeta[target._physicalID]){
                    overScrollMeta.push(new OverScrollData(target, OverScrollData.DOWN, 0, 0));
                    target._physicalID= overScrollMeta.length - 1;
                    }
                var sData= overScrollMeta[target._physicalID];
                sData.cursorY+= Math.abs(change);
                target.firstElementChild.style.marginTop= stretching(sData.cursorY)+'px';
                target.scrollTop= 0;

//          on overscrolling at the bottom
            }else if(target.scrollTop == target.scrollTopMax && movement < 0){
                if(target._physicalID < 0 || !overScrollMeta[target._physicalID]){
                    overScrollMeta.push(new OverScrollData(target, OverScrollData.UP, 0, 0));
                    target._physicalID= overScrollMeta.length - 1;
                    }
                var sData= overScrollMeta[target._physicalID];
                sData.cursorY+= Math.abs(change);
                target.lastElementChild.style.marginBottom= stretching(sData.cursorY)+'px';
                target.scrollTop= target.scrollTopMax;
                }

//      if the object was released
        }else{
            if(target._physicalID > -1 && overScrollMeta[target._physicalID]){
                var sData= overScrollMeta[target._physicalID];
                sData.lastUpdate= new Date().getTime();
                sData.release();
                }
            }
        };

    var stretching= function(F){
        const D= 3;

        return F / D;
        };
});
<|endoftext|>


<commit_before>import CONFIG from '../config';

class Preload extends Phaser.State{
  preload() {
    // Trainers Sprites and Animated Tiles
    this.game.load.spritesheet('trchar000', 'Resources/Graphics/Characters/trchar000.png', 32, 48)
    this.game.load.spritesheet('trchar001', 'Resources/Graphics/Characters/trchar001.png', 32, 48)
    this.game.load.spritesheet('boy_run', 'Resources/Graphics/Characters/boy_run.png', 32, 48)
    this.game.load.spritesheet('doors5', 'Resources/Graphics/Characters/doors5.png', 32, 32)
    this.game.load.spritesheet('Flowers1', 'Resources/Graphics/Autotiles/Flowers1.png', 32, 32)
    this.game.load.spritesheet('WaterCurrentSouth', 'Resources/Graphics/Autotiles/Water current south.png', 32, 32)
    this.game.load.spritesheet('DustandGrass', 'Resources/Graphics/Animations/DustandGrass.png', 32, 32)

    // Pokemon 3d prerendered Sprites
    this.game.load.spritesheet('383', 'Resources/Graphics/Battlers/383.png', 107, 94)
    this.game.load.spritesheet('460_1', 'Resources/Graphics/Battlers/460_1.png', 125, 110)
    this.game.load.spritesheet('460b_1', 'Resources/Graphics/Battlers/460b_1.png', 124, 118)
    this.game.load.spritesheet('504', 'Resources/Graphics/Battlers/504.png', 46, 55)
    this.game.load.spritesheet('727', 'Resources/Graphics/Battlers/727.png', 131, 96)
    this.game.load.spritesheet('pikachu', 'Resources/Graphics/Battlers/pikachu.png', 60, 60)

    // Tilesets
    this.game.load.image('Outside', 'Resources/Graphics/Tilesets/Outside.png')
    this.game.load.image('battlebgField', 'Resources/Graphics/Battlebacks/battlebgField.png')
    this.game.load.image('playerbaseCityGrass', 'Resources/Graphics/Battlebacks/playerbaseCityGrass.png')
    this.game.load.image('enemybaseCityGrass', 'Resources/Graphics/Battlebacks/enemybaseCityGrass.png')
    this.game.load.image('interior_general', 'Resources/Graphics/Tilesets/Interior_general.png')
    this.game.load.image('movement_permissions', 'Resources/Graphics/Tilesets/movement_permissions.png')

    // General Pictures
    this.game.load.image('shadeFull', 'Resources/Graphics/Pictures/shadeFull.png')
    this.game.load.image('newBattleMessageBox', 'Resources/Graphics/Pictures/newBattleMessageBox.png')
    this.game.load.image('loadbg', 'Resources/Graphics/Pictures/loadbg.png')
    this.game.load.image('bg', 'Resources/Graphics/Pictures/bg.png')
    this.game.load.image('bg1', 'Resources/Graphics/Pictures/bg1.png')
    this.game.load.image('white_bg', 'Resources/Graphics/Pictures/white_bg.png')
    this.game.load.image('moving_bg', 'Resources/Graphics/Pictures/moving_bg.png')
    this.game.load.image('introbg', 'Resources/Graphics/Pictures/introbg.png')
    this.game.load.image('introBoy', 'Resources/Graphics/Pictures/introBoy.png')
    this.game.load.image('introGirl', 'Resources/Graphics/Pictures/introGirl.png')
    this.game.load.image('introOak', 'Resources/Graphics/Pictures/introOak.png')
    this.game.load.image('introProf', 'Resources/Graphics/Pictures/introProf.png')
    this.game.load.image('introbase', 'Resources/Graphics/Pictures/introbase.png')
    this.game.load.image('selarrow', 'Resources/Graphics/Pictures/selarrow.png')
    this.game.load.spritesheet('load_button', 'Resources/Graphics/Pictures/load_button.png', 384, 45)

    // Title assets
    this.game.load.image('pokestart', 'Resources/Graphics/Titles/pokestart.png')
    this.game.load.image('custom_background', 'Resources/Graphics/Titles/custom_background.png')
    this.game.load.image('custom_clouds_1', 'Resources/Graphics/Titles/custom_clouds_1.png')
    this.game.load.image('custom_clouds_2', 'Resources/Graphics/Titles/custom_clouds_2.png')
    this.game.load.image('custom_effect', 'Resources/Graphics/Titles/custom_effect.png')
    this.game.load.image('custom_plane', 'Resources/Graphics/Titles/custom_plane.png')
    this.game.load.image('custom_bars', 'Resources/Graphics/Titles/custom_bars.png')
    this.game.load.image('custom_bars_shine', 'Resources/Graphics/Titles/custom_bars_shine.png')
    this.game.load.image('gen_6_shine', 'Resources/Graphics/Titles/gen_6_shine.png')
    this.game.load.image('gen_6_effect2', 'Resources/Graphics/Titles/gen_6_effect2.png')
    this.game.load.image('pokemonjs', 'Resources/Graphics/Titles/pokemonjs.png')
    this.game.load.image('custom_pokelogo', 'Resources/Graphics/Titles/custom_pokelogo.png')
    this.game.load.image('custom_pokelogo_shine', 'Resources/Graphics/Titles/custom_pokelogo_shine.png')
    this.game.load.image('gen_5_bg', 'Resources/Graphics/Titles/gen_5_bg.png')
    this.game.load.image('gen_6_particle', 'Resources/Graphics/Titles/gen_6_particle.png')
    this.game.load.image('gen_6_particle', 'Resources/Graphics/Titles/gen_6_particle.png')
    this.game.load.image('gen_6_particle2', 'Resources/Graphics/Titles/gen_6_particle2.png')

    this.game.load.image('choice_1', 'Resources/Graphics/Windowskins/choice 1.png')
    this.game.load.image('speech_hgss_1', 'Resources/Graphics/Windowskins/speech hgss 1.png')

    this.game.load.audio('title_origin', 'Resources/Audio/BGM/title_origin.ogg')
    this.game.load.audio('select', 'Resources/Audio/BGS/select.ogg')
    this.game.load.audio('Choose', 'Resources/Audio/BGS/Choose.ogg')

    this.game.load.tilemap('Pallet_Town/pallet_town_01', 'Resources/Maps/Pallet_Town/pallet_town_01.json', null, Phaser.Tilemap.TILED_JSON)
    this.game.load.tilemap('Pallet_Town/pallet_town_02', 'Resources/Maps/Pallet_Town/pallet_town_02.json', null, Phaser.Tilemap.TILED_JSON)
    this.game.load.tilemap('Route_1/route_1', 'Resources/Maps/Route_1/route_1.json', null, Phaser.Tilemap.TILED_JSON)

  }

  loadRender() {
    let t = this.game.add.text(this.game.world.centerX, this.game.world.centerY, "Loading...", CONFIG.FONT_STYLE);
    t.anchor.set(.5, .5);
  }

  create() {
    this.game.add.plugin(PhaserInput.Plugin);

    //Windows skins
    this.game.cache.addNinePatch('choice_1', 'choice_1', null, 16, 16, 16, 16)
    this.game.cache.addNinePatch('speech_hgss_1', 'speech_hgss_1', null, 32, 48, 16, 16)

    this.state.start('Intro');
  }
}
export default Preload;
<commit_msg>Fix loading text color<commit_after>import CONFIG from '../config';

class Preload extends Phaser.State{
  preload() {
    // Trainers Sprites and Animated Tiles
    this.game.load.spritesheet('trchar000', 'Resources/Graphics/Characters/trchar000.png', 32, 48)
    this.game.load.spritesheet('trchar001', 'Resources/Graphics/Characters/trchar001.png', 32, 48)
    this.game.load.spritesheet('boy_run', 'Resources/Graphics/Characters/boy_run.png', 32, 48)
    this.game.load.spritesheet('doors5', 'Resources/Graphics/Characters/doors5.png', 32, 32)
    this.game.load.spritesheet('Flowers1', 'Resources/Graphics/Autotiles/Flowers1.png', 32, 32)
    this.game.load.spritesheet('WaterCurrentSouth', 'Resources/Graphics/Autotiles/Water current south.png', 32, 32)
    this.game.load.spritesheet('DustandGrass', 'Resources/Graphics/Animations/DustandGrass.png', 32, 32)

    // Pokemon 3d prerendered Sprites
    this.game.load.spritesheet('383', 'Resources/Graphics/Battlers/383.png', 107, 94)
    this.game.load.spritesheet('460_1', 'Resources/Graphics/Battlers/460_1.png', 125, 110)
    this.game.load.spritesheet('460b_1', 'Resources/Graphics/Battlers/460b_1.png', 124, 118)
    this.game.load.spritesheet('504', 'Resources/Graphics/Battlers/504.png', 46, 55)
    this.game.load.spritesheet('727', 'Resources/Graphics/Battlers/727.png', 131, 96)
    this.game.load.spritesheet('pikachu', 'Resources/Graphics/Battlers/pikachu.png', 60, 60)

    // Tilesets
    this.game.load.image('Outside', 'Resources/Graphics/Tilesets/Outside.png')
    this.game.load.image('battlebgField', 'Resources/Graphics/Battlebacks/battlebgField.png')
    this.game.load.image('playerbaseCityGrass', 'Resources/Graphics/Battlebacks/playerbaseCityGrass.png')
    this.game.load.image('enemybaseCityGrass', 'Resources/Graphics/Battlebacks/enemybaseCityGrass.png')
    this.game.load.image('interior_general', 'Resources/Graphics/Tilesets/Interior_general.png')
    this.game.load.image('movement_permissions', 'Resources/Graphics/Tilesets/movement_permissions.png')

    // General Pictures
    this.game.load.image('shadeFull', 'Resources/Graphics/Pictures/shadeFull.png')
    this.game.load.image('newBattleMessageBox', 'Resources/Graphics/Pictures/newBattleMessageBox.png')
    this.game.load.image('loadbg', 'Resources/Graphics/Pictures/loadbg.png')
    this.game.load.image('bg', 'Resources/Graphics/Pictures/bg.png')
    this.game.load.image('bg1', 'Resources/Graphics/Pictures/bg1.png')
    this.game.load.image('white_bg', 'Resources/Graphics/Pictures/white_bg.png')
    this.game.load.image('moving_bg', 'Resources/Graphics/Pictures/moving_bg.png')
    this.game.load.image('introbg', 'Resources/Graphics/Pictures/introbg.png')
    this.game.load.image('introBoy', 'Resources/Graphics/Pictures/introBoy.png')
    this.game.load.image('introGirl', 'Resources/Graphics/Pictures/introGirl.png')
    this.game.load.image('introOak', 'Resources/Graphics/Pictures/introOak.png')
    this.game.load.image('introProf', 'Resources/Graphics/Pictures/introProf.png')
    this.game.load.image('introbase', 'Resources/Graphics/Pictures/introbase.png')
    this.game.load.image('selarrow', 'Resources/Graphics/Pictures/selarrow.png')
    this.game.load.spritesheet('load_button', 'Resources/Graphics/Pictures/load_button.png', 384, 45)

    // Title assets
    this.game.load.image('pokestart', 'Resources/Graphics/Titles/pokestart.png')
    this.game.load.image('custom_background', 'Resources/Graphics/Titles/custom_background.png')
    this.game.load.image('custom_clouds_1', 'Resources/Graphics/Titles/custom_clouds_1.png')
    this.game.load.image('custom_clouds_2', 'Resources/Graphics/Titles/custom_clouds_2.png')
    this.game.load.image('custom_effect', 'Resources/Graphics/Titles/custom_effect.png')
    this.game.load.image('custom_plane', 'Resources/Graphics/Titles/custom_plane.png')
    this.game.load.image('custom_bars', 'Resources/Graphics/Titles/custom_bars.png')
    this.game.load.image('custom_bars_shine', 'Resources/Graphics/Titles/custom_bars_shine.png')
    this.game.load.image('gen_6_shine', 'Resources/Graphics/Titles/gen_6_shine.png')
    this.game.load.image('gen_6_effect2', 'Resources/Graphics/Titles/gen_6_effect2.png')
    this.game.load.image('pokemonjs', 'Resources/Graphics/Titles/pokemonjs.png')
    this.game.load.image('custom_pokelogo', 'Resources/Graphics/Titles/custom_pokelogo.png')
    this.game.load.image('custom_pokelogo_shine', 'Resources/Graphics/Titles/custom_pokelogo_shine.png')
    this.game.load.image('gen_5_bg', 'Resources/Graphics/Titles/gen_5_bg.png')
    this.game.load.image('gen_6_particle', 'Resources/Graphics/Titles/gen_6_particle.png')
    this.game.load.image('gen_6_particle', 'Resources/Graphics/Titles/gen_6_particle.png')
    this.game.load.image('gen_6_particle2', 'Resources/Graphics/Titles/gen_6_particle2.png')

    this.game.load.image('choice_1', 'Resources/Graphics/Windowskins/choice 1.png')
    this.game.load.image('speech_hgss_1', 'Resources/Graphics/Windowskins/speech hgss 1.png')

    this.game.load.audio('title_origin', 'Resources/Audio/BGM/title_origin.ogg')
    this.game.load.audio('select', 'Resources/Audio/BGS/select.ogg')
    this.game.load.audio('Choose', 'Resources/Audio/BGS/Choose.ogg')

    this.game.load.tilemap('Pallet_Town/pallet_town_01', 'Resources/Maps/Pallet_Town/pallet_town_01.json', null, Phaser.Tilemap.TILED_JSON)
    this.game.load.tilemap('Pallet_Town/pallet_town_02', 'Resources/Maps/Pallet_Town/pallet_town_02.json', null, Phaser.Tilemap.TILED_JSON)
    this.game.load.tilemap('Route_1/route_1', 'Resources/Maps/Route_1/route_1.json', null, Phaser.Tilemap.TILED_JSON)

  }

  loadRender() {
    let style = { font: "40px power_clearregular", fill: "#fff"}
    let t = this.game.add.text(this.game.world.centerX, this.game.world.centerY, "Loading...", style);
    t.anchor.set(.5, .5);
  }

  create() {
    this.game.add.plugin(PhaserInput.Plugin);

    //Windows skins
    this.game.cache.addNinePatch('choice_1', 'choice_1', null, 16, 16, 16, 16)
    this.game.cache.addNinePatch('speech_hgss_1', 'speech_hgss_1', null, 32, 48, 16, 16)

    this.state.start('Intro');
  }
}
export default Preload;
<|endoftext|>


<commit_before>/* eslint max-nested-callbacks: ["error", 8] */
'use strict'

const promisify = require('promisify-es6')
const { DAGNode, DAGLink } = require('ipld-dag-pb')
const CID = require('cids')
const multihashes = require('multihashes')
const async = require('async')
const { Key } = require('interface-datastore')

const createPinSet = require('./pin-set')
const { resolvePath } = require('../utils')

// arbitrary limit to the number of concurrent dag operations
const concurrencyLimit = 300
const pinDataStoreKey = new Key('/local/pins')

function toB58String (hash) {
  return new CID(hash).toBaseEncodedString()
}

module.exports = function pin (self) {
  const repo = self._repo
  const dag = self.dag
  const pinset = createPinSet(dag)
  const types = {
    direct: 'direct',
    recursive: 'recursive',
    indirect: 'indirect',
    all: 'all'
  }

  let directPins = new Set()
  let recursivePins = new Set()

  const directKeys = () =>
    Array.from(directPins).map(key => multihashes.fromB58String(key))
  const recursiveKeys = () =>
    Array.from(recursivePins).map(key => multihashes.fromB58String(key))

  function getIndirectKeys (callback) {
    const indirectKeys = new Set()
    async.eachLimit(recursiveKeys(), concurrencyLimit, (multihash, cb) => {
      dag._getRecursive(multihash, (err, nodes) => {
        if (err) { return cb(err) }

        nodes
          .map(({ multihash }) => toB58String(multihash))
          // recursive pins pre-empt indirect pins
          .filter(key => !recursivePins.has(key))
          .forEach(key => indirectKeys.add(key))

        cb()
      })
    }, (err) => {
      if (err) { return callback(err) }
      callback(null, Array.from(indirectKeys))
    })
  }

  // Encode and write pin key sets to the datastore:
  // a DAGLink for each of the recursive and direct pinsets
  // a DAGNode holding those as DAGLinks, a kind of root pin
  function flushPins (callback) {
    let dLink, rLink, root
    async.series([
      // create a DAGLink to the node with direct pins
      cb => async.waterfall([
        cb => pinset.storeSet(directKeys(), cb),
        (node, cb) => DAGLink.create(types.direct, node.size, node.multihash, cb),
        (link, cb) => { dLink = link; cb(null) }
      ], cb),

      // create a DAGLink to the node with recursive pins
      cb => async.waterfall([
        cb => pinset.storeSet(recursiveKeys(), cb),
        (node, cb) => DAGLink.create(types.recursive, node.size, node.multihash, cb),
        (link, cb) => { rLink = link; cb(null) }
      ], cb),

      // the pin-set nodes link to a special 'empty' node, so make sure it exists
      cb => DAGNode.create(Buffer.alloc(0), (err, empty) => {
        if (err) { return cb(err) }
        dag.put(empty, { cid: new CID(empty.multihash) }, cb)
      }),

      // create a root node with DAGLinks to the direct and recursive DAGs
      cb => DAGNode.create(Buffer.alloc(0), [dLink, rLink], (err, node) => {
        if (err) { return cb(err) }
        root = node
        dag.put(root, { cid: new CID(root.multihash) }, cb)
      }),

      // hack for CLI tests
      cb => repo.closed ? repo.open(cb) : cb(null, null),

      // save root to datastore under a consistent key
      cb => repo.datastore.put(pinDataStoreKey, root.multihash, cb)
    ], (err, res) => {
      if (err) { return callback(err) }
      self.log(`Flushed pins with root: ${root}`)
      return callback(null, root)
    })
  }

  const pin = {
    add: promisify((paths, options, callback) => {
      if (typeof options === 'function') {
        callback = options
        options = null
      }
      const recursive = options ? options.recursive : true

      resolvePath(self.object, paths, (err, mhs) => {
        if (err) { return callback(err) }

        // verify that each hash can be pinned
        async.map(mhs, (multihash, cb) => {
          const key = toB58String(multihash)
          if (recursive) {
            if (recursivePins.has(key)) {
              // it's already pinned recursively
              return cb(null, key)
            }

            // entire graph of nested links should be pinned,
            // so make sure we have all the objects
            dag._getRecursive(key, (err) => {
              if (err) { return cb(err) }
              // found all objects, we can add the pin
              return cb(null, key)
            })
          } else {
            if (recursivePins.has(key)) {
              // recursive supersedes direct, can't have both
              return cb(new Error(`${key} already pinned recursively`))
            }
            if (directPins.has(key)) {
              // already directly pinned
              return cb(null, key)
            }

            // make sure we have the object
            dag.get(new CID(multihash), (err) => {
              if (err) { return cb(err) }
              // found the object, we can add the pin
              return cb(null, key)
            })
          }
        }, (err, results) => {
          if (err) { return callback(err) }

          // update the pin sets in memory
          const pinset = recursive ? recursivePins : directPins
          results.forEach(key => pinset.add(key))

          // persist updated pin sets to datastore
          flushPins((err, root) => {
            if (err) { return callback(err) }
            return callback(null, results.map(hash => ({ hash })))
          })
        })
      })
    }),

    rm: promisify((paths, options, callback) => {
      let recursive = true
      if (typeof options === 'function') {
        callback = options
      } else if (options && options.recursive === false) {
        recursive = false
      }

      resolvePath(self.object, paths, (err, mhs) => {
        if (err) { return callback(err) }

        // verify that each hash can be unpinned
        async.map(mhs, (multihash, cb) => {
          pin._isPinnedWithType(multihash, types.all, (err, res) => {
            if (err) { return cb(err) }
            const { pinned, reason } = res
            const key = toB58String(multihash)
            if (!pinned) {
              return cb(new Error(`${key} is not pinned`))
            }

            switch (reason) {
              case (types.recursive):
                if (recursive) {
                  return cb(null, key)
                } else {
                  return cb(new Error(`${key} is pinned recursively`))
                }
              case (types.direct):
                return cb(null, key)
              default:
                return cb(new Error(
                  `${key} is pinned indirectly under ${reason}`
                ))
            }
          })
        }, (err, results) => {
          if (err) { return callback(err) }

          // update the pin sets in memory
          results.forEach(key => {
            if (recursive && recursivePins.has(key)) {
              recursivePins.delete(key)
            } else {
              directPins.delete(key)
            }
          })

          // persist updated pin sets to datastore
          flushPins((err, root) => {
            if (err) { return callback(err) }
            self.log(`Removed pins: ${results}`)
            return callback(null, results.map(hash => ({ hash })))
          })
        })
      })
    }),

    ls: promisify((paths, options, callback) => {
      let type = types.all
      if (typeof paths === 'function') {
        callback = paths
        options = null
        paths = null
      }
      if (typeof options === 'function') {
        callback = options
      }
      if (paths && paths.type) {
        options = paths
        paths = null
      }
      if (options && options.type) {
        type = options.type.toLowerCase()
      }
      if (!types[type]) {
        return callback(new Error(
          `Invalid type '${type}', must be one of {direct, indirect, recursive, all}`
        ))
      }

      if (paths) {
        // check the pinned state of specific hashes
        resolvePath(self.object, paths, (err, mhs) => {
          if (err) { return callback(err) }

          async.mapSeries(mhs, (multihash, cb) => {
            pin._isPinnedWithType(multihash, types.all, (err, res) => {
              if (err) { return cb(err) }
              const { pinned, reason } = res
              const key = toB58String(multihash)
              if (!pinned) {
                return cb(new Error(`Path ${key} is not pinned`))
              }

              switch (reason) {
                case types.direct:
                case types.recursive:
                  return cb(null, {
                    hash: key,
                    type: reason
                  })
                default:
                  return cb(null, {
                    hash: key,
                    type: `${types.indirect} through ${reason}`
                  })
              }
            })
          }, callback)
        })
      } else {
        // show all pinned items of type
        let pins = []
        if (type === types.direct || type === types.all) {
          pins = pins.concat(
            Array.from(directPins).map(hash => ({
              type: types.direct,
              hash
            }))
          )
        }
        if (type === types.recursive || type === types.all) {
          pins = pins.concat(
            Array.from(recursivePins).map(hash => ({
              type: types.recursive,
              hash
            }))
          )
        }
        if (type === types.indirect || type === types.all) {
          getIndirectKeys((err, indirects) => {
            if (err) { return callback(err) }
            pins = pins
              // if something is pinned both directly and indirectly,
              // report the indirect entry
              .filter(({ hash }) =>
                !indirects.includes(hash) ||
                (indirects.includes(hash) && !directPins.has(hash))
              )
              .concat(indirects.map(hash => ({
                type: types.indirect,
                hash
              })))
            return callback(null, pins)
          })
        } else {
          return callback(null, pins)
        }
      }
    }),

    _isPinnedWithType: promisify((multihash, type, callback) => {
      const key = toB58String(multihash)
      const { recursive, direct, all } = types
      // recursive
      if ((type === recursive || type === all) && recursivePins.has(key)) {
        return callback(null, {pinned: true, reason: recursive})
      }
      if ((type === recursive)) {
        return callback(null, {pinned: false})
      }
      // direct
      if ((type === direct || type === all) && directPins.has(key)) {
        return callback(null, {pinned: true, reason: direct})
      }
      if ((type === direct)) {
        return callback(null, {pinned: false})
      }

      // indirect (default)
      // check each recursive key to see if multihash is under it
      // arbitrary limit, enables handling 1000s of pins.
      let foundPin
      async.someLimit(recursiveKeys(), concurrencyLimit, (key, cb) => {
        dag.get(new CID(key), (err, res) => {
          if (err) { return cb(err) }

          pinset.hasDescendant(res.value, multihash, (err, has) => {
            if (has) {
              foundPin = toB58String(res.value.multihash)
            }
            cb(err, has)
          })
        })
      }, (err, found) => {
        if (err) { return callback(err) }
        return callback(null, { pinned: found, reason: foundPin })
      })
    }),

    _load: promisify(callback => {
      async.waterfall([
        // hack for CLI tests
        (cb) => repo.closed ? repo.datastore.open(cb) : cb(null, null),
        (_, cb) => repo.datastore.has(pinDataStoreKey, cb),
        (has, cb) => has ? cb() : cb(new Error('No pins to load')),
        (cb) => repo.datastore.get(pinDataStoreKey, cb),
        (mh, cb) => dag.get(new CID(mh), cb)
      ], (err, pinRoot) => {
        if (err) {
          if (err.message === 'No pins to load') {
            self.log('No pins to load')
            return callback()
          } else {
            return callback(err)
          }
        }

        async.parallel([
          cb => pinset.loadSet(pinRoot.value, types.recursive, cb),
          cb => pinset.loadSet(pinRoot.value, types.direct, cb)
        ], (err, keys) => {
          if (err) { return callback(err) }
          const [ rKeys, dKeys ] = keys

          directPins = new Set(dKeys.map(toB58String))
          recursivePins = new Set(rKeys.map(toB58String))

          self.log('Loaded pins from the datastore')
          return callback(null)
        })
      })
    })
  }

  return pin
}
<commit_msg>fix: aegir docs fails if outer funtion is called pin (#1429)<commit_after>/* eslint max-nested-callbacks: ["error", 8] */
'use strict'

const promisify = require('promisify-es6')
const { DAGNode, DAGLink } = require('ipld-dag-pb')
const CID = require('cids')
const multihashes = require('multihashes')
const async = require('async')
const { Key } = require('interface-datastore')

const createPinSet = require('./pin-set')
const { resolvePath } = require('../utils')

// arbitrary limit to the number of concurrent dag operations
const concurrencyLimit = 300
const pinDataStoreKey = new Key('/local/pins')

function toB58String (hash) {
  return new CID(hash).toBaseEncodedString()
}

module.exports = (self) => {
  const repo = self._repo
  const dag = self.dag
  const pinset = createPinSet(dag)
  const types = {
    direct: 'direct',
    recursive: 'recursive',
    indirect: 'indirect',
    all: 'all'
  }

  let directPins = new Set()
  let recursivePins = new Set()

  const directKeys = () =>
    Array.from(directPins).map(key => multihashes.fromB58String(key))
  const recursiveKeys = () =>
    Array.from(recursivePins).map(key => multihashes.fromB58String(key))

  function getIndirectKeys (callback) {
    const indirectKeys = new Set()
    async.eachLimit(recursiveKeys(), concurrencyLimit, (multihash, cb) => {
      dag._getRecursive(multihash, (err, nodes) => {
        if (err) { return cb(err) }

        nodes
          .map(({ multihash }) => toB58String(multihash))
          // recursive pins pre-empt indirect pins
          .filter(key => !recursivePins.has(key))
          .forEach(key => indirectKeys.add(key))

        cb()
      })
    }, (err) => {
      if (err) { return callback(err) }
      callback(null, Array.from(indirectKeys))
    })
  }

  // Encode and write pin key sets to the datastore:
  // a DAGLink for each of the recursive and direct pinsets
  // a DAGNode holding those as DAGLinks, a kind of root pin
  function flushPins (callback) {
    let dLink, rLink, root
    async.series([
      // create a DAGLink to the node with direct pins
      cb => async.waterfall([
        cb => pinset.storeSet(directKeys(), cb),
        (node, cb) => DAGLink.create(types.direct, node.size, node.multihash, cb),
        (link, cb) => { dLink = link; cb(null) }
      ], cb),

      // create a DAGLink to the node with recursive pins
      cb => async.waterfall([
        cb => pinset.storeSet(recursiveKeys(), cb),
        (node, cb) => DAGLink.create(types.recursive, node.size, node.multihash, cb),
        (link, cb) => { rLink = link; cb(null) }
      ], cb),

      // the pin-set nodes link to a special 'empty' node, so make sure it exists
      cb => DAGNode.create(Buffer.alloc(0), (err, empty) => {
        if (err) { return cb(err) }
        dag.put(empty, { cid: new CID(empty.multihash) }, cb)
      }),

      // create a root node with DAGLinks to the direct and recursive DAGs
      cb => DAGNode.create(Buffer.alloc(0), [dLink, rLink], (err, node) => {
        if (err) { return cb(err) }
        root = node
        dag.put(root, { cid: new CID(root.multihash) }, cb)
      }),

      // hack for CLI tests
      cb => repo.closed ? repo.open(cb) : cb(null, null),

      // save root to datastore under a consistent key
      cb => repo.datastore.put(pinDataStoreKey, root.multihash, cb)
    ], (err, res) => {
      if (err) { return callback(err) }
      self.log(`Flushed pins with root: ${root}`)
      return callback(null, root)
    })
  }

  const pin = {
    add: promisify((paths, options, callback) => {
      if (typeof options === 'function') {
        callback = options
        options = null
      }
      const recursive = options ? options.recursive : true

      resolvePath(self.object, paths, (err, mhs) => {
        if (err) { return callback(err) }

        // verify that each hash can be pinned
        async.map(mhs, (multihash, cb) => {
          const key = toB58String(multihash)
          if (recursive) {
            if (recursivePins.has(key)) {
              // it's already pinned recursively
              return cb(null, key)
            }

            // entire graph of nested links should be pinned,
            // so make sure we have all the objects
            dag._getRecursive(key, (err) => {
              if (err) { return cb(err) }
              // found all objects, we can add the pin
              return cb(null, key)
            })
          } else {
            if (recursivePins.has(key)) {
              // recursive supersedes direct, can't have both
              return cb(new Error(`${key} already pinned recursively`))
            }
            if (directPins.has(key)) {
              // already directly pinned
              return cb(null, key)
            }

            // make sure we have the object
            dag.get(new CID(multihash), (err) => {
              if (err) { return cb(err) }
              // found the object, we can add the pin
              return cb(null, key)
            })
          }
        }, (err, results) => {
          if (err) { return callback(err) }

          // update the pin sets in memory
          const pinset = recursive ? recursivePins : directPins
          results.forEach(key => pinset.add(key))

          // persist updated pin sets to datastore
          flushPins((err, root) => {
            if (err) { return callback(err) }
            return callback(null, results.map(hash => ({ hash })))
          })
        })
      })
    }),

    rm: promisify((paths, options, callback) => {
      let recursive = true
      if (typeof options === 'function') {
        callback = options
      } else if (options && options.recursive === false) {
        recursive = false
      }

      resolvePath(self.object, paths, (err, mhs) => {
        if (err) { return callback(err) }

        // verify that each hash can be unpinned
        async.map(mhs, (multihash, cb) => {
          pin._isPinnedWithType(multihash, types.all, (err, res) => {
            if (err) { return cb(err) }
            const { pinned, reason } = res
            const key = toB58String(multihash)
            if (!pinned) {
              return cb(new Error(`${key} is not pinned`))
            }

            switch (reason) {
              case (types.recursive):
                if (recursive) {
                  return cb(null, key)
                } else {
                  return cb(new Error(`${key} is pinned recursively`))
                }
              case (types.direct):
                return cb(null, key)
              default:
                return cb(new Error(
                  `${key} is pinned indirectly under ${reason}`
                ))
            }
          })
        }, (err, results) => {
          if (err) { return callback(err) }

          // update the pin sets in memory
          results.forEach(key => {
            if (recursive && recursivePins.has(key)) {
              recursivePins.delete(key)
            } else {
              directPins.delete(key)
            }
          })

          // persist updated pin sets to datastore
          flushPins((err, root) => {
            if (err) { return callback(err) }
            self.log(`Removed pins: ${results}`)
            return callback(null, results.map(hash => ({ hash })))
          })
        })
      })
    }),

    ls: promisify((paths, options, callback) => {
      let type = types.all
      if (typeof paths === 'function') {
        callback = paths
        options = null
        paths = null
      }
      if (typeof options === 'function') {
        callback = options
      }
      if (paths && paths.type) {
        options = paths
        paths = null
      }
      if (options && options.type) {
        type = options.type.toLowerCase()
      }
      if (!types[type]) {
        return callback(new Error(
          `Invalid type '${type}', must be one of {direct, indirect, recursive, all}`
        ))
      }

      if (paths) {
        // check the pinned state of specific hashes
        resolvePath(self.object, paths, (err, mhs) => {
          if (err) { return callback(err) }

          async.mapSeries(mhs, (multihash, cb) => {
            pin._isPinnedWithType(multihash, types.all, (err, res) => {
              if (err) { return cb(err) }
              const { pinned, reason } = res
              const key = toB58String(multihash)
              if (!pinned) {
                return cb(new Error(`Path ${key} is not pinned`))
              }

              switch (reason) {
                case types.direct:
                case types.recursive:
                  return cb(null, {
                    hash: key,
                    type: reason
                  })
                default:
                  return cb(null, {
                    hash: key,
                    type: `${types.indirect} through ${reason}`
                  })
              }
            })
          }, callback)
        })
      } else {
        // show all pinned items of type
        let pins = []
        if (type === types.direct || type === types.all) {
          pins = pins.concat(
            Array.from(directPins).map(hash => ({
              type: types.direct,
              hash
            }))
          )
        }
        if (type === types.recursive || type === types.all) {
          pins = pins.concat(
            Array.from(recursivePins).map(hash => ({
              type: types.recursive,
              hash
            }))
          )
        }
        if (type === types.indirect || type === types.all) {
          getIndirectKeys((err, indirects) => {
            if (err) { return callback(err) }
            pins = pins
              // if something is pinned both directly and indirectly,
              // report the indirect entry
              .filter(({ hash }) =>
                !indirects.includes(hash) ||
                (indirects.includes(hash) && !directPins.has(hash))
              )
              .concat(indirects.map(hash => ({
                type: types.indirect,
                hash
              })))
            return callback(null, pins)
          })
        } else {
          return callback(null, pins)
        }
      }
    }),

    _isPinnedWithType: promisify((multihash, type, callback) => {
      const key = toB58String(multihash)
      const { recursive, direct, all } = types
      // recursive
      if ((type === recursive || type === all) && recursivePins.has(key)) {
        return callback(null, {pinned: true, reason: recursive})
      }
      if ((type === recursive)) {
        return callback(null, {pinned: false})
      }
      // direct
      if ((type === direct || type === all) && directPins.has(key)) {
        return callback(null, {pinned: true, reason: direct})
      }
      if ((type === direct)) {
        return callback(null, {pinned: false})
      }

      // indirect (default)
      // check each recursive key to see if multihash is under it
      // arbitrary limit, enables handling 1000s of pins.
      let foundPin
      async.someLimit(recursiveKeys(), concurrencyLimit, (key, cb) => {
        dag.get(new CID(key), (err, res) => {
          if (err) { return cb(err) }

          pinset.hasDescendant(res.value, multihash, (err, has) => {
            if (has) {
              foundPin = toB58String(res.value.multihash)
            }
            cb(err, has)
          })
        })
      }, (err, found) => {
        if (err) { return callback(err) }
        return callback(null, { pinned: found, reason: foundPin })
      })
    }),

    _load: promisify(callback => {
      async.waterfall([
        // hack for CLI tests
        (cb) => repo.closed ? repo.datastore.open(cb) : cb(null, null),
        (_, cb) => repo.datastore.has(pinDataStoreKey, cb),
        (has, cb) => has ? cb() : cb(new Error('No pins to load')),
        (cb) => repo.datastore.get(pinDataStoreKey, cb),
        (mh, cb) => dag.get(new CID(mh), cb)
      ], (err, pinRoot) => {
        if (err) {
          if (err.message === 'No pins to load') {
            self.log('No pins to load')
            return callback()
          } else {
            return callback(err)
          }
        }

        async.parallel([
          cb => pinset.loadSet(pinRoot.value, types.recursive, cb),
          cb => pinset.loadSet(pinRoot.value, types.direct, cb)
        ], (err, keys) => {
          if (err) { return callback(err) }
          const [ rKeys, dKeys ] = keys

          directPins = new Set(dKeys.map(toB58String))
          recursivePins = new Set(rKeys.map(toB58String))

          self.log('Loaded pins from the datastore')
          return callback(null)
        })
      })
    })
  }

  return pin
}
<|endoftext|>


<commit_before>import ExecutionEnvironment from '../util/ExecutionEnvironment';
import { createVariable } from './variables';
import scanTreeForDynamicNodes from './scanTreeForDynamicNodes';
import isVoid from '../util/isVoid';

// Date.now() is the slowest thing on earth
// http://jsperf.com/math-random-vs-date-now-vs-new-date/4
let uniqueId = Date.now();

/*
 let UUID = (function() {
 var self = {};
 var lut = []; for (var i=0; i<256; i++) { lut[i] = (i<16?'0':'')+(i).toString(16); }
 self.generate = function() {
 var d0 = Math.random()*0xffffffff|0;
 var d1 = Math.random()*0xffffffff|0;
 var d2 = Math.random()*0xffffffff|0;
 var d3 = Math.random()*0xffffffff|0;
 return lut[d0&0xff]+lut[d0>>8&0xff]+lut[d0>>16&0xff]+lut[d0>>24&0xff]+'-'+
 lut[d1&0xff]+lut[d1>>8&0xff]+'-'+lut[d1>>16&0x0f|0x40]+lut[d1>>24&0xff]+'-'+
 lut[d2&0x3f|0x80]+lut[d2>>8&0xff]+'-'+lut[d2>>16&0xff]+lut[d2>>24&0xff]+
 lut[d3&0xff]+lut[d3>>8&0xff]+lut[d3>>16&0xff]+lut[d3>>24&0xff];
 }
 return self;
 })();
 let uniqueId = UUID.generate();
 */
const treeConstructors = {};
const validTreeNames = {
	dom: true,
	html: true
};

export function addTreeConstructor(name, treeConstructor) {
	treeConstructors[name] = treeConstructor;
}

function applyTreeConstructors(schema, dynamicNodeMap) {
	const tree = {};

	for (let treeConstructor in treeConstructors) {
		tree[treeConstructor] = treeConstructors[treeConstructor](schema, true, dynamicNodeMap);
	}
	return tree;
}

export default function createTemplate(callback) {
	if (typeof callback === 'function') {
		let construct = callback.construct || null;

		if (isVoid(construct)) {
			const callbackLength = callback.length;
			const callbackArguments = new Array(callbackLength);

			for (let i = 0; i < callbackLength; i++) {
				callbackArguments[i] = createVariable(i);
			}
			const schema = callback(...callbackArguments);
			const dynamicNodeMap = [];

			scanTreeForDynamicNodes(schema, dynamicNodeMap);
			const tree = applyTreeConstructors(schema, dynamicNodeMap);
			const key = schema.key;
			const keyIndex = key ? key.index : -1;

			switch (callbackLength) {
				case 0:
					construct = () => ({
						parent: null,
						tree,
						id: uniqueId++,
						key: null,
						nextItem: null,
						rootNode: null
					});
					break;
				case 1:
					construct = (v0) => {
						let key;

						if (keyIndex === 0) {
							key = v0;
						}
						return {
							parent: null,
							tree,
							id: uniqueId++,
							key,
							nextItem: null,
							rootNode: null,
							v0
						};
					};
					break;
				case 2:
					construct = (v0, v1) => {
						let key;

						if (keyIndex === 0) {
							key = v0;
						} else if (keyIndex === 1) {
							key = v1;
						}
						return {
							parent: null,
							tree,
							id: uniqueId++,
							key,
							nextItem: null,
							rootNode: null,
							v0,
							v1
						};
					};
					break;
				default:
					construct = (v0, v1, ...values) => {
						let key;

						if (keyIndex === 0) {
							key = v0;
						} else if (keyIndex === 1) {
							key = v1;
						} else if (keyIndex > 1) {
							key = values[keyIndex];
						}
						return {
							parent: null,
							tree,
							id: uniqueId++,
							key,
							nextItem: null,
							rootNode: null,
							v0,
							v1,
							values
						};
					};
					break;
			}
			if (!isVoid(construct)) {
				callback.construct = construct;
			}
		}

		return construct;
	}
}<commit_msg>remove parent from fragment, no longer used<commit_after>import ExecutionEnvironment from '../util/ExecutionEnvironment';
import { createVariable } from './variables';
import scanTreeForDynamicNodes from './scanTreeForDynamicNodes';
import isVoid from '../util/isVoid';

// Date.now() is the slowest thing on earth
// http://jsperf.com/math-random-vs-date-now-vs-new-date/4
let uniqueId = Date.now();

/*
 let UUID = (function() {
 var self = {};
 var lut = []; for (var i=0; i<256; i++) { lut[i] = (i<16?'0':'')+(i).toString(16); }
 self.generate = function() {
 var d0 = Math.random()*0xffffffff|0;
 var d1 = Math.random()*0xffffffff|0;
 var d2 = Math.random()*0xffffffff|0;
 var d3 = Math.random()*0xffffffff|0;
 return lut[d0&0xff]+lut[d0>>8&0xff]+lut[d0>>16&0xff]+lut[d0>>24&0xff]+'-'+
 lut[d1&0xff]+lut[d1>>8&0xff]+'-'+lut[d1>>16&0x0f|0x40]+lut[d1>>24&0xff]+'-'+
 lut[d2&0x3f|0x80]+lut[d2>>8&0xff]+'-'+lut[d2>>16&0xff]+lut[d2>>24&0xff]+
 lut[d3&0xff]+lut[d3>>8&0xff]+lut[d3>>16&0xff]+lut[d3>>24&0xff];
 }
 return self;
 })();
 let uniqueId = UUID.generate();
 */
const treeConstructors = {};
const validTreeNames = {
	dom: true,
	html: true
};

export function addTreeConstructor(name, treeConstructor) {
	treeConstructors[name] = treeConstructor;
}

function applyTreeConstructors(schema, dynamicNodeMap) {
	const tree = {};

	for (let treeConstructor in treeConstructors) {
		tree[treeConstructor] = treeConstructors[treeConstructor](schema, true, dynamicNodeMap);
	}
	return tree;
}

export default function createTemplate(callback) {
	if (typeof callback === 'function') {
		let construct = callback.construct || null;

		if (isVoid(construct)) {
			const callbackLength = callback.length;
			const callbackArguments = new Array(callbackLength);

			for (let i = 0; i < callbackLength; i++) {
				callbackArguments[i] = createVariable(i);
			}
			const schema = callback(...callbackArguments);
			const dynamicNodeMap = [];

			scanTreeForDynamicNodes(schema, dynamicNodeMap);
			const tree = applyTreeConstructors(schema, dynamicNodeMap);
			const key = schema.key;
			const keyIndex = key ? key.index : -1;

			switch (callbackLength) {
				case 0:
					construct = () => ({
						tree,
						id: uniqueId++,
						key: null,
						nextItem: null,
						rootNode: null
					});
					break;
				case 1:
					construct = (v0) => {
						let key;

						if (keyIndex === 0) {
							key = v0;
						}
						return {
							tree,
							id: uniqueId++,
							key,
							nextItem: null,
							rootNode: null,
							v0
						};
					};
					break;
				case 2:
					construct = (v0, v1) => {
						let key;

						if (keyIndex === 0) {
							key = v0;
						} else if (keyIndex === 1) {
							key = v1;
						}
						return {
							tree,
							id: uniqueId++,
							key,
							nextItem: null,
							rootNode: null,
							v0,
							v1
						};
					};
					break;
				default:
					construct = (v0, v1, ...values) => {
						let key;

						if (keyIndex === 0) {
							key = v0;
						} else if (keyIndex === 1) {
							key = v1;
						} else if (keyIndex > 1) {
							key = values[keyIndex];
						}
						return {
							tree,
							id: uniqueId++,
							key,
							nextItem: null,
							rootNode: null,
							v0,
							v1,
							values
						};
					};
					break;
			}
			if (!isVoid(construct)) {
				callback.construct = construct;
			}
		}

		return construct;
	}
}<|endoftext|>


<commit_before>/**
 * Login Form
 *
 * @class Hatimeria.core.form.LoginForm
 * @extends Hatimeria.core.form.BaseForm
 */
(function() {

    Ext.define("Hatimeria.core.form.LoginForm", {
        extend: "Hatimeria.core.form.BaseForm",
        transNS: "form.login",
        transDomain: 'HatimeriaExtJSBundle',

        /**
         * name of route for redirect after succesfull login
         *
         * @cfg {String} afterLogin
         */
        afterLogin: 'hatimeria_admin',

        /**
         * Absolute path to logo
         *
         * @cfg {String} logoUri
         */
        logoUri: "/bundles/hatimeriaadmin/images/hatimeria_v_220.png",

        /**
         * Text which appears under form (like copyrights)
         *
         * @cfg {String} footer
         */
        footer: null,

        /**
         * Constructor
         *
         * @param {Object} cfg
         */
        constructor: function(cfg)
        {
            var me = this;
            var config = {
                submitConfig: {
                    text: this.__('submit'),
                    failureWindowTitle: this.__("failureTitle"),
                    success: function() {
                        window.location = Routing.generate(cfg.afterLogin || me.afterLogin);
                    }
                },
                buttonConfig: {
                    text: 'Zaloguj'
                },
                waitMessage: this.__('wait'),
                url: Routing.generate('fos_user_security_check')
            };

            Ext.apply(config, cfg || {});
            this.callParent([config]);
        },

        /**
         * Initialize component
         *
         * @private
         */
        initComponent: function()
        {
            var config = {
                layout: 'auto',
                bodyPadding: 10,
                border: 0,
                defaults: {
                    labelWidth: 80,
                    labelAlign: 'right',
                    width: 300,
                    border: 0
                },
                items: this.getFieldsConfig([
                    {
                        xtype: 'textfield',
                        fieldLabel: this.__('login'),
                        name: '_username',
                        allowBlank: false,
                        listeners: {
                            specialkey: {scope: this, fn: this.onFieldEnter}
                        }
                    },
                    {
                        xtype: 'textfield',
                        fieldLabel: this.__('password'),
                        inputType: 'password',
                        name: '_password',
                        allowBlank: false,
                        listeners: {
                            specialkey: {scope: this, fn: this.onFieldEnter}
                        }
                    }
                ])
            };

            Ext.apply(this, Ext.apply(config, this.initialConfig));

            if (!this.footer) {
                this.footer = this.__('copyright');
            }

            this.callParent();
        },

        /**
         * Hit enter on field
         *
         * @private
         */
        onFieldEnter: function(field, event)
        {
            if (event.getKey() == event.ENTER)
            {
                this.submitForm();
            }
        },

        /**
         * Fields configuration
         * Method adds branded theme
         *
         * @param {Array} fieldsConfig
         */
        getFieldsConfig: function(fieldsConfig)
        {
            var fields = [
                {
                    xtype: 'image',
                    border: 0,
                    width: 220,
                    height: 50,
                    src: this.logoUri ,
                    style: {margin: '20px auto'}
                }
            ];

            fields.push(fieldsConfig);

            fields.push({
                border: 0,
                width: 350,
                height: 27,
                id: 'hatimeria-powered-by',
                style: {margin: '20px 65px'},
                html: this.footer
            });

            return fields;
        }
    });

})();<commit_msg>fix in foter (login form)<commit_after>/**
 * Login Form
 *
 * @class Hatimeria.core.form.LoginForm
 * @extends Hatimeria.core.form.BaseForm
 */
(function() {

    Ext.define("Hatimeria.core.form.LoginForm", {
        extend: "Hatimeria.core.form.BaseForm",
        transNS: "form.login",
        transDomain: 'HatimeriaExtJSBundle',

        /**
         * name of route for redirect after succesfull login
         *
         * @cfg {String} afterLogin
         */
        afterLogin: 'hatimeria_admin',

        /**
         * Absolute path to logo
         *
         * @cfg {String} logoUri
         */
        logoUri: "/bundles/hatimeriaadmin/images/hatimeria_v_220.png",

        /**
         * Text which appears under form (like copyrights)
         *
         * @cfg {String} footer
         */
        footer: null,

        /**
         * Constructor
         *
         * @param {Object} cfg
         */
        constructor: function(cfg)
        {
            var me = this;
            var config = {
                submitConfig: {
                    text: this.__('submit'),
                    failureWindowTitle: this.__("failureTitle"),
                    success: function() {
                        window.location = Routing.generate(cfg.afterLogin || me.afterLogin);
                    }
                },
                buttonConfig: {
                    text: 'Zaloguj'
                },
                waitMessage: this.__('wait'),
                url: Routing.generate('fos_user_security_check')
            };

            Ext.apply(config, cfg || {});
            this.callParent([config]);
        },

        /**
         * Initialize component
         *
         * @private
         */
        initComponent: function()
        {
            if (!this.footer) {
                this.footer = this.__('copyright');
            }

            var config = {
                layout: 'auto',
                bodyPadding: 10,
                border: 0,
                defaults: {
                    labelWidth: 80,
                    labelAlign: 'right',
                    width: 300,
                    border: 0
                },
                items: this.getFieldsConfig([
                    {
                        xtype: 'textfield',
                        fieldLabel: this.__('login'),
                        name: '_username',
                        allowBlank: false,
                        listeners: {
                            specialkey: {scope: this, fn: this.onFieldEnter}
                        }
                    },
                    {
                        xtype: 'textfield',
                        fieldLabel: this.__('password'),
                        inputType: 'password',
                        name: '_password',
                        allowBlank: false,
                        listeners: {
                            specialkey: {scope: this, fn: this.onFieldEnter}
                        }
                    }
                ])
            };

            Ext.apply(this, Ext.apply(config, this.initialConfig));

            this.callParent();
        },

        /**
         * Hit enter on field
         *
         * @private
         */
        onFieldEnter: function(field, event)
        {
            if (event.getKey() == event.ENTER)
            {
                this.submitForm();
            }
        },

        /**
         * Fields configuration
         * Method adds branded theme
         *
         * @param {Array} fieldsConfig
         */
        getFieldsConfig: function(fieldsConfig)
        {
            var fields = [
                {
                    xtype: 'image',
                    border: 0,
                    width: 220,
                    height: 50,
                    src: this.logoUri ,
                    style: {margin: '20px auto'}
                }
            ];

            fields.push(fieldsConfig);

            fields.push({
                border: 0,
                width: 350,
                height: 27,
                id: 'hatimeria-powered-by',
                style: {margin: '20px 65px'},
                html: this.footer
            });

            return fields;
        }
    });

})();<|endoftext|>


<commit_before>/* not type checking this file because flow doesn't play well with Proxy */

import { warn, makeMap } from '../util/index'

let hasProxy, proxyHandlers, initProxy

if (process.env.NODE_ENV !== 'production') {
  const allowedGlobals = makeMap(
    'Infinity,undefined,NaN,isFinite,isNaN,' +
    'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
    'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl'
  )

  hasProxy =
    typeof Proxy !== 'undefined' &&
    Proxy.toString().match(/native code/)

  proxyHandlers = {
    has (target, key) {
      const has = key in target
      const isAllowedGlobal = allowedGlobals(key)
      if (!has && !isAllowedGlobal) {
        warn(
          `Trying to access non-existent property "${key}" while rendering.`,
          target
        )
      }
      return !isAllowedGlobal
    }
  }

  initProxy = function initProxy (vm) {
    if (hasProxy) {
      vm._renderProxy = new Proxy(vm, proxyHandlers)
    } else {
      vm._renderProxy = vm
    }
  }
}

export { initProxy }
<commit_msg>improve proxy property warning<commit_after>/* not type checking this file because flow doesn't play well with Proxy */

import { warn, makeMap } from '../util/index'

let hasProxy, proxyHandlers, initProxy

if (process.env.NODE_ENV !== 'production') {
  const allowedGlobals = makeMap(
    'Infinity,undefined,NaN,isFinite,isNaN,' +
    'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
    'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl'
  )

  hasProxy =
    typeof Proxy !== 'undefined' &&
    Proxy.toString().match(/native code/)

  proxyHandlers = {
    has (target, key) {
      const has = key in target
      const isAllowedGlobal = allowedGlobals(key)
      if (!has && !isAllowedGlobal) {
        warn(
          `Trying to access non-existent property "${key}" while rendering. ` +
          `Make sure to declare reactive data properties in the data option.`,
          target
        )
      }
      return !isAllowedGlobal
    }
  }

  initProxy = function initProxy (vm) {
    if (hasProxy) {
      vm._renderProxy = new Proxy(vm, proxyHandlers)
    } else {
      vm._renderProxy = vm
    }
  }
}

export { initProxy }
<|endoftext|>