<commit_before>/*jshint node: true */
/*globals describe, it, before, after, beforeEach */
'use strict';
var expect = require('expect.js');
var Database = require('../');
var ArangoError = require('../lib/error');
var Cursor = require('../lib/cursor');
var db = new Database();
var testCollectionName = 'test__collection_0';

describe('database', function () {
  describe('query', function () {
    it('returns a cursor on success', function (done) {
      db.query('RETURN "hello"', function (err, res) {
        expect(err).not.to.be.ok();
        expect(res).to.be.a(Cursor);
        done();
      });
    });
    it('returns an error if the query is invalid', function (done) {
      db.query('GARBAGE', function (err, res) {
        expect(err).to.be.an(ArangoError);
        expect(res).not.to.be.ok();
        done();
      });
    });
    it('returns an error if the query failed', function (done) {
      db.query('FOR x IN does_not_exist RETURN x', function (err, res) {
        expect(err).to.be.an(ArangoError);
        expect(res).not.to.be.ok();
        done();
      });
    });
  });
});

describe('cursor', function () {
  var cursor;
  before(function (done) {
    db.createCollection(testCollectionName, function () {
      db.query((
        'FOR i IN 1..1500 INSERT {_key: TO_STRING(i), value: i} INTO ' +
        testCollectionName
      ), function (err) {
        done(err);
      });
    });
  });
  after(function (done) {
    db.dropCollection(testCollectionName, function () {
      done();
    });
  });
  beforeEach(function (done) {
    db.query('FOR x IN ' + testCollectionName + ' SORT x.value ASC RETURN x', function (err, cur) {
      if (err) done(err);
      else {
        cursor = cur;
        done();
      }
    });
  });
  describe('all', function () {
    it('returns an array with all result records', function (done) {
      cursor.all(function (err, records) {
        expect(err).not.to.be.ok();
        expect(records).to.be.an(Array);
        expect(records).to.have.property('length', 1500);
        done();
      });
    });
  });
  describe('next', function () {
    it('returns the next record in the cursor', function (done) {
      cursor.next(function (err, record) {
        expect(err).not.to.be.ok();
        expect(record).to.have.property('value', 1);
        cursor.next(function (err2, record2) {
          expect(err2).not.to.be.ok();
          expect(record2).to.have.property('value', 2);
          done();
        });
      });
    });
    it('returns nothing if the cursor has been depleted', function (done) {
      cursor.all(function (err) {
        expect(err).not.to.be.ok();
        cursor.next(function (err, record) {
          expect(err).not.to.be.ok();
          expect(record).not.to.be.ok();
          done();
        });
      });
    });
  });
  describe('hasNext', function () {
    it('returns true if the cursor has not yet been depleted', function () {
      expect(cursor.hasNext()).to.be(true);
    });
    it('returns false if the cursor has been depleted', function (done) {
      cursor.all(function (err) {
        expect(err).not.to.be.ok();
        expect(cursor.hasNext()).to.be(false);
        done();
      });
    });
  });
  describe('each', function () {
    it('applies the function to each record', function (done) {
      var timesCalled = 0;
      cursor.each(function (record, index, records) {
        expect(record.value).to.equal(timesCalled + 1);
        expect(index).to.equal(timesCalled);
        expect(records).to.equal(cursor);
        timesCalled++;
      }, function (err) {
        expect(err).not.to.be.ok();
        expect(timesCalled).to.equal(1500);
        done();
      });
    });
  });
  describe('every', function () {
    it('returns true if the function returns true for every record', function (done) {
      var timesCalled = 0;
      cursor.every(function (record, index, records) {
        expect(record.value).to.equal(timesCalled + 1);
        expect(index).to.equal(timesCalled);
        expect(records).to.equal(cursor);
        timesCalled++;
        return true;
      }, function (err, result) {
        expect(err).not.to.be.ok();
        expect(result).to.equal(true);
        expect(timesCalled).to.equal(1500);
        expect(cursor._index).to.equal(1500);
        done();
      });
    });
    it('returns false if the function returns false for any record', function (done) {
      var timesCalled = 0;
      cursor.every(function (record, index, records) {
        expect(record.value).to.equal(timesCalled + 1);
        expect(index).to.equal(timesCalled);
        expect(records).to.equal(cursor);
        timesCalled++;
        return timesCalled < 100;
      }, function (err, result) {
        expect(err).not.to.be.ok();
        expect(result).to.equal(false);
        expect(timesCalled).to.equal(100);
        expect(cursor._index).to.equal(100);
        done();
      });
    });
  });
  describe('some', function () {
    it('returns false if the function returns false for every record', function (done) {
      var timesCalled = 0;
      cursor.some(function (record, index, records) {
        expect(record.value).to.equal(timesCalled + 1);
        expect(index).to.equal(timesCalled);
        expect(records).to.equal(cursor);
        timesCalled++;
        return false;
      }, function (err, result) {
        expect(err).not.to.be.ok();
        expect(result).to.equal(false);
        expect(timesCalled).to.equal(1500);
        expect(cursor._index).to.equal(1500);
        done();
      });
    });
    it('returns true if the function returns true for any record', function (done) {
      var timesCalled = 0;
      cursor.some(function (record, index, records) {
        expect(record.value).to.equal(timesCalled + 1);
        expect(index).to.equal(timesCalled);
        expect(records).to.equal(cursor);
        timesCalled++;
        return timesCalled === 100;
      }, function (err, result) {
        expect(err).not.to.be.ok();
        expect(result).to.equal(true);
        expect(timesCalled).to.equal(100);
        expect(cursor._index).to.equal(100);
        done();
      });
    });
  });
  describe('map', function () {
    it('returns the result of applying the function to each record', function (done) {
      var timesCalled = 0;
      cursor.map(function (record, index, records) {
        expect(record.value).to.equal(timesCalled + 1);
        expect(index).to.equal(timesCalled);
        expect(records).to.equal(cursor);
        timesCalled++;
        return 1;
      }, function (err, result) {
        expect(err).not.to.be.ok();
        expect(result).to.be.an(Array);
        expect(result.reduce(function (a, b) {return a + b;})).to.equal(1500);
        expect(timesCalled).to.equal(1500);
        done();
      });
    });
  });
  describe('reduce', function () {
    it('is missing tests');
  });
});<commit_msg>Consistent naming.<commit_after>/*jshint node: true */
/*globals describe, it, before, after, beforeEach */
'use strict';
var expect = require('expect.js');
var Database = require('../');
var ArangoError = require('../lib/error');
var Cursor = require('../lib/cursor');
var db = new Database();
var testCollectionName = 'test__collection_0';

describe('database', function () {
  describe('query', function () {
    it('returns a cursor on success', function (done) {
      db.query('RETURN "hello"', function (err, res) {
        expect(err).not.to.be.ok();
        expect(res).to.be.a(Cursor);
        done();
      });
    });
    it('returns an ArangoError if the query is invalid', function (done) {
      db.query('GARBAGE', function (err, res) {
        expect(err).to.be.an(ArangoError);
        expect(res).not.to.be.ok();
        done();
      });
    });
    it('returns an ArangoError if the query failed', function (done) {
      db.query('FOR x IN does_not_exist RETURN x', function (err, res) {
        expect(err).to.be.an(ArangoError);
        expect(res).not.to.be.ok();
        done();
      });
    });
  });
});

describe('cursor', function () {
  var cursor;
  before(function (done) {
    db.createCollection(testCollectionName, function () {
      db.query((
        'FOR i IN 1..1500 INSERT {_key: TO_STRING(i), value: i} INTO ' +
        testCollectionName
      ), function (err) {
        done(err);
      });
    });
  });
  after(function (done) {
    db.dropCollection(testCollectionName, function () {
      done();
    });
  });
  beforeEach(function (done) {
    db.query('FOR x IN ' + testCollectionName + ' SORT x.value ASC RETURN x', function (err, cur) {
      if (err) done(err);
      else {
        cursor = cur;
        done();
      }
    });
  });
  describe('all', function () {
    it('returns an array with all result records', function (done) {
      cursor.all(function (err, records) {
        expect(err).not.to.be.ok();
        expect(records).to.be.an(Array);
        expect(records).to.have.property('length', 1500);
        done();
      });
    });
  });
  describe('next', function () {
    it('returns the next record in the cursor', function (done) {
      cursor.next(function (err, record) {
        expect(err).not.to.be.ok();
        expect(record).to.have.property('value', 1);
        cursor.next(function (err2, record2) {
          expect(err2).not.to.be.ok();
          expect(record2).to.have.property('value', 2);
          done();
        });
      });
    });
    it('returns nothing if the cursor has been depleted', function (done) {
      cursor.all(function (err) {
        expect(err).not.to.be.ok();
        cursor.next(function (err, record) {
          expect(err).not.to.be.ok();
          expect(record).not.to.be.ok();
          done();
        });
      });
    });
  });
  describe('hasNext', function () {
    it('returns true if the cursor has not yet been depleted', function () {
      expect(cursor.hasNext()).to.be(true);
    });
    it('returns false if the cursor has been depleted', function (done) {
      cursor.all(function (err) {
        expect(err).not.to.be.ok();
        expect(cursor.hasNext()).to.be(false);
        done();
      });
    });
  });
  describe('each', function () {
    it('applies the function to each record', function (done) {
      var timesCalled = 0;
      cursor.each(function (record, index, records) {
        expect(record.value).to.equal(timesCalled + 1);
        expect(index).to.equal(timesCalled);
        expect(records).to.equal(cursor);
        timesCalled++;
      }, function (err) {
        expect(err).not.to.be.ok();
        expect(timesCalled).to.equal(1500);
        done();
      });
    });
  });
  describe('every', function () {
    it('returns true if the function returns true for every record', function (done) {
      var timesCalled = 0;
      cursor.every(function (record, index, records) {
        expect(record.value).to.equal(timesCalled + 1);
        expect(index).to.equal(timesCalled);
        expect(records).to.equal(cursor);
        timesCalled++;
        return true;
      }, function (err, result) {
        expect(err).not.to.be.ok();
        expect(result).to.equal(true);
        expect(timesCalled).to.equal(1500);
        expect(cursor._index).to.equal(1500);
        done();
      });
    });
    it('returns false if the function returns false for any record', function (done) {
      var timesCalled = 0;
      cursor.every(function (record, index, records) {
        expect(record.value).to.equal(timesCalled + 1);
        expect(index).to.equal(timesCalled);
        expect(records).to.equal(cursor);
        timesCalled++;
        return timesCalled < 100;
      }, function (err, result) {
        expect(err).not.to.be.ok();
        expect(result).to.equal(false);
        expect(timesCalled).to.equal(100);
        expect(cursor._index).to.equal(100);
        done();
      });
    });
  });
  describe('some', function () {
    it('returns false if the function returns false for every record', function (done) {
      var timesCalled = 0;
      cursor.some(function (record, index, records) {
        expect(record.value).to.equal(timesCalled + 1);
        expect(index).to.equal(timesCalled);
        expect(records).to.equal(cursor);
        timesCalled++;
        return false;
      }, function (err, result) {
        expect(err).not.to.be.ok();
        expect(result).to.equal(false);
        expect(timesCalled).to.equal(1500);
        expect(cursor._index).to.equal(1500);
        done();
      });
    });
    it('returns true if the function returns true for any record', function (done) {
      var timesCalled = 0;
      cursor.some(function (record, index, records) {
        expect(record.value).to.equal(timesCalled + 1);
        expect(index).to.equal(timesCalled);
        expect(records).to.equal(cursor);
        timesCalled++;
        return timesCalled === 100;
      }, function (err, result) {
        expect(err).not.to.be.ok();
        expect(result).to.equal(true);
        expect(timesCalled).to.equal(100);
        expect(cursor._index).to.equal(100);
        done();
      });
    });
  });
  describe('map', function () {
    it('returns the result of applying the function to each record', function (done) {
      var timesCalled = 0;
      cursor.map(function (record, index, records) {
        expect(record.value).to.equal(timesCalled + 1);
        expect(index).to.equal(timesCalled);
        expect(records).to.equal(cursor);
        timesCalled++;
        return 1;
      }, function (err, result) {
        expect(err).not.to.be.ok();
        expect(result).to.be.an(Array);
        expect(result.reduce(function (a, b) {return a + b;})).to.equal(1500);
        expect(timesCalled).to.equal(1500);
        done();
      });
    });
  });
  describe('reduce', function () {
    it('is missing tests');
  });
});<|endoftext|>


<commit_before>
var should = require('should')
var app = require('../../../purest/config/app')
var user = require('../../../purest/config/user')
var config = require('../../../purest/config/providers')
var purest = require('../')

describe('request', () => {
  it('__default alias', (done) => {
    var twitter = purest({
      provider: 'twitter', config: config,
      key: app.twitter.key, secret: app.twitter.secret
    })

    twitter
      .select('users/show')
      .where({screen_name: '_simov'})
      .auth(user.twitter.token, user.twitter.secret)
      .callback((err, res, body) => {
        should.equal(body.screen_name, '_simov')
        done()
      })
      .submit()
  })
})
<commit_msg>Update client test<commit_after>
var t = require('assert')
var app = require('../../../purest/config/app')
var user = require('../../../purest/config/user')
var config = require('../../../purest/config/providers')
var purest = require('../')(require('@request/client'))

describe('request', () => {
  it('__default alias', (done) => {
    var twitter = purest({
      provider: 'twitter', config: config,
      key: app.twitter.key, secret: app.twitter.secret
    })

    twitter
      .select('users/show')
      .where({screen_name: '_simov'})
      .auth(user.twitter.token, user.twitter.secret)
      .callback((err, res, body) => {
        t.equal(body.screen_name, '_simov')
        done()
      })
      .submit()
  })

  it.skip('specific alias', () => {
    var yandex = purest({provider: 'yandex'})

    yandex
      .query('login')
      .auth(app.yandex.token)
      .callback((err, res, body) => {
        debugger
        if (err) {
          console.log(err)
        }
        console.log(body)
      })
  })
})
<|endoftext|>


<commit_before>var WebKit = require('../');
var expect = require('expect.js');
var fs = require('fs');

describe("request listener", function suite() {
	it("should cancel the request when uri set to null or empty string", function(done) {
		this.timeout(15000);
		var cancelledRequests = 0;
		WebKit(function(err, w) {
			w.load("http://www.selmer.fr").on("request", function(request) {
				if (/\.js$/.test(request.uri)) {
					cancelledRequests++;
					request.uri = null;
				}
			}).on("response", function(response) {
				expect(/\.js$/.test(response.uri)).to.not.be(true);
			}).once("load", function() {
				expect(cancelledRequests).to.be.greaterThan(3);
				done();
			}).on("error", function() {
				// just ignore errors here
			});
		});
	});

	it("should ignore stalled requests", function(done) {
		this.timeout(6000);
		var doc = '\
		\
	move along'
		var server = require('http').createServer(function(req, res) {
			if (req.url == "/") {
				res.statusCode = 200;
				res.end(doc);
			} else if (req.url == "/test") {
				res.statusCode = 200;
				setTimeout(function() {
					res.end('{"hello": "tata"}');
				}, 2000);
			} else {
				expect("no 404").to.be("should happen");
				res.statusCode = 404;
				res.end();
			}
		}).listen(function() {
			WebKit(function(err, w) {
				w.load("http://localhost:" + server.address().port, {console:true, stall: 1000})
				.once('idle', function() {
					this.html(function(err, str) {
						expect(str).to.be(doc);
						setTimeout(function() {
							server.close();
							done();
						}, 100);
					});
				});
			});
		});
	});

	it("should allow to force ignore requests", function(done) {
		this.timeout(1000);
		var doc = '\
		\
		move along'
		var server = require('http').createServer(function(req, res) {
			if (req.url == "/") {
				res.statusCode = 200;
				res.end(doc);
			} else if (req.url == "/test") {
				res.statusCode = 200;
				setTimeout(function() {
					res.end('{"hello": "tata"}');
				}, 3000);
			} else {
				expect("no 404").to.be("should happen");
				res.statusCode = 404;
				res.end();
			}
		}).listen(function() {
			WebKit(function(err, w) {
				w.load("http://localhost:" + server.address().port, {console:true, stall: 2000})
				.on('request', function(req) {
					if (req.uri.indexOf('test') > 0) {
						req.ignore = true;
					}
				})
				.once('idle', function() {
					this.html(function(err, str) {
						expect(str).to.be(doc);
						setTimeout(function() {
							server.close();
							done();
						}, 100);
					});
				});
			});
		});
	});

	it("should cancel xhr requests immediately", function(done) {
		// this typically is not the case if ret = TRUE in src/webextension.cc
		// and works if uri is set to ""
		this.timeout(1000);
		var doc = '\
		\
		move along'
		var server = require('http').createServer(function(req, res) {
			if (req.url == "/") {
				res.statusCode = 200;
				res.end(doc);
			} else if (req.url == "/test") {
				res.statusCode = 200;
				setTimeout(function() {
					res.end('{"hello": "tata"}');
				}, 3000);
			} else {
				expect("no 404").to.be("should happen");
				res.statusCode = 404;
				res.end();
			}
		}).listen(function() {
			WebKit(function(err, w) {
				w.load("http://localhost:" + server.address().port, {console:true, stall: 2000})
				.on('request', function(req) {
					if (req.uri.indexOf('test') > 0) {
						req.cancel = true;
					}
				})
				.once('idle', function() {
					this.html(function(err, str) {
						expect(str).to.be(doc);
						setTimeout(function() {
							server.close();
							done();
						}, 100);
					});
				});
			});
		});
	});
});
<commit_msg>Format add semicolon<commit_after>var WebKit = require('../');
var expect = require('expect.js');
var fs = require('fs');

describe("request listener", function suite() {
	it("should cancel the request when uri set to null or empty string", function(done) {
		this.timeout(15000);
		var cancelledRequests = 0;
		WebKit(function(err, w) {
			w.load("http://www.selmer.fr").on("request", function(request) {
				if (/\.js$/.test(request.uri)) {
					cancelledRequests++;
					request.uri = null;
				}
			}).on("response", function(response) {
				expect(/\.js$/.test(response.uri)).to.not.be(true);
			}).once("load", function() {
				expect(cancelledRequests).to.be.greaterThan(3);
				done();
			}).on("error", function() {
				// just ignore errors here
			});
		});
	});

	it("should ignore stalled requests", function(done) {
		this.timeout(6000);
		var doc = '\
		\
	move along'
		var server = require('http').createServer(function(req, res) {
			if (req.url == "/") {
				res.statusCode = 200;
				res.end(doc);
			} else if (req.url == "/test") {
				res.statusCode = 200;
				setTimeout(function() {
					res.end('{"hello": "tata"}');
				}, 2000);
			} else {
				expect("no 404").to.be("should happen");
				res.statusCode = 404;
				res.end();
			}
		}).listen(function() {
			WebKit(function(err, w) {
				w.load("http://localhost:" + server.address().port, {console:true, stall: 1000})
				.once('idle', function() {
					this.html(function(err, str) {
						expect(str).to.be(doc);
						setTimeout(function() {
							server.close();
							done();
						}, 100);
					});
				});
			});
		});
	});

	it("should allow to force ignore requests", function(done) {
		this.timeout(1000);
		var doc = '\
		\
		move along'
		var server = require('http').createServer(function(req, res) {
			if (req.url == "/") {
				res.statusCode = 200;
				res.end(doc);
			} else if (req.url == "/test") {
				res.statusCode = 200;
				setTimeout(function() {
					res.end('{"hello": "tata"}');
				}, 3000);
			} else {
				expect("no 404").to.be("should happen");
				res.statusCode = 404;
				res.end();
			}
		}).listen(function() {
			WebKit(function(err, w) {
				w.load("http://localhost:" + server.address().port, {console:true, stall: 2000})
				.on('request', function(req) {
					if (req.uri.indexOf('test') > 0) {
						req.ignore = true;
					}
				})
				.once('idle', function() {
					this.html(function(err, str) {
						expect(str).to.be(doc);
						setTimeout(function() {
							server.close();
							done();
						}, 100);
					});
				});
			});
		});
	});

	it("should cancel xhr requests immediately", function(done) {
		// this typically is not the case if ret = TRUE in src/webextension.cc
		// and works if uri is set to ""
		this.timeout(1000);
		var doc = '\
		\
		move along';
		var server = require('http').createServer(function(req, res) {
			if (req.url == "/") {
				res.statusCode = 200;
				res.end(doc);
			} else if (req.url == "/test") {
				res.statusCode = 200;
				setTimeout(function() {
					res.end('{"hello": "tata"}');
				}, 3000);
			} else {
				expect("no 404").to.be("should happen");
				res.statusCode = 404;
				res.end();
			}
		}).listen(function() {
			WebKit(function(err, w) {
				w.load("http://localhost:" + server.address().port, {console:true, stall: 2000})
				.on('request', function(req) {
					if (req.uri.indexOf('test') > 0) {
						req.cancel = true;
					}
				})
				.once('idle', function() {
					this.html(function(err, str) {
						expect(str).to.be(doc);
						setTimeout(function() {
							server.close();
							done();
						}, 100);
					});
				});
			});
		});
	});
});
<|endoftext|>


<commit_before>/**
 * Rest driver.
 *
 * @todo put rest client in its own package.
 */

'use strict';

const FirebaseTokenGenerator = require('firebase-token-generator');
const hash = require('object-hash');
const rest = require('../rest');

const log = require('debug')('firebase-test:context:rest');

// admin auth data
const adminAuth = {uid: 'DB Admin'};

/**
 * Rest driver.
 *
 * Test operation by applying them to a live database.
 *
 */
class LiveDriver {

  /**
   * Create token generator and rest client.
   *
   * @param {{secret: string, projectId: string}} options Driver options
   */
  constructor(options = {}) {
    if (options.secret == null) {
      throw new Error('No Firebase secret provided.');
    }

    this.client = exports.client(options);
    this.generator = exports.tokenGenerator(options);
    this.secret = options.secret;
  }

  get id() {
    return 'rest';
  }

  /**
   * Placeholder for init hook - nothing to initialize on the Context object.
   */
  init() {}

  /**
   * Test the operation can be applied.
   *
   * @param  {Context} ctx Context holding rules, initial datas and the operations to test
   * @return {Promise<void,Error>}
   */
  exec(ctx) {
    const {ops, seed, rules} = ctx;
    const tokens = new Tokens(this.generator);

    const adminToken = tokens.get(adminAuth, {admin: true});
    const setup = Promise.all([
      deployRules({rules, client: this.client, secret: this.secret}),
      this.client.set({paths: '', payload: seed, auth: adminToken, silent: true})
    ]);

    return ops.reduce(
      (chain, operation) => {
        const {op, path: paths, value, auth: authData = null, options: {debug = false, silent = true} = {}} = operation;
        const auth = authData == null ? null : tokens.get(authData, {debug});

        switch (op) {

        case 'get':
          return chain.then(() => this.client.get({paths, auth, silent}));

        case 'push':
        case 'set':
        case 'update':
          return chain.then(() => this.client[op]({paths, payload: value, auth, silent: true}));

        default:
          return chain.then(() => Promise.reject(new Error(`Unknown operation type "${op}"`)));

        }
      },
      setup
    );
  }

}

/**
 * Cache auth tokens
 */
class Tokens {

  constructor(generator) {
    this.generator = generator;
    this.tokens = new Map();
  }

  /**
   * Get token from the cache or generate it if it doesn't exist.
   *
   * @param  {object} auth Auth data
   * @param  {object} opts token object
   * @return {string}
   */
  get(auth, opts) {
    const key = hash({auth, opts});

    if (this.tokens.has(key) === false) {
      this.tokens.set(key, this.generator.createToken(auth, opts));
    }

    return this.tokens.get(key);
  }

}

/**
 * Create the rest driver.
 *
 * @param {{secret: string, projectId: string}} opts Driver options
 * @return {LiveDriver}
 */
exports.create = function(opts) {
  return new LiveDriver(opts);
};

/**
 * Create a REST client for a Firebase database.
 *
 * @param  {string} options.projectId Firebase project id
 * @return {RestClient}
 */
exports.client = function({projectId, client}) {
  if (client != null) {
    log('Rest driver will use the provided client.');

    return client;
  }

  return rest.client({projectId});
};

/**
 * Create a Firebase legacy token generator
 *
 * @param  {string}                   options.secret          Secret to generate token with
 * @return {{createToken: function(data: object, opt: object): string}}
 */
exports.tokenGenerator = function({secret, tokenGenerator}) {
  if (tokenGenerator != null) {
    log('Rest driver will use the provided token generator.');

    return tokenGenerator;
  }

  if (secret == null) {
    throw new Error('The rest driver require a firebase secret');
  }

  log('Rest driver will use the default token generator.');

  return new FirebaseTokenGenerator(secret);
};

/**
 * Rules deployment cache.
 *
 * @type {Map<string,Promise<string>>}
 */
const rulesRequests = new Map();

/**
 * Reset rules deployment cache.
 */
exports.reset = function() {
  rulesRequests.clear();
};

/**
 * Deploy rules for a database project.
 *
 * It deploy the rules only if the previous deployed rules were different.
 *
 * @param  {object}     options          Request options
 * @param  {RestClient} options.client   Client
 * @param  {object}     options.rules    Rules to deploy
 * @param  {string}     options.secret   Secret to authenticate the request
 * @return {Promise<void,Error>}
 */
function deployRules({client, rules, secret}) {
  const lastRequest = rulesRequests.get(client.projectId);

  return Promise.resolve(lastRequest).then(oldRulesHash => {
    const newRuleHash = hash(rules);

    if (oldRulesHash === newRuleHash) {
      return oldRulesHash;
    }

    const request = client.rules({rules, secret});

    rulesRequests.set(client.projectId, request.then(
      () => newRuleHash,
      () => oldRulesHash
    ));

    return request;
  });
}
<commit_msg>Make sure rest sequences cannot be run concurrently.<commit_after>/**
 * Rest driver.
 *
 * @todo put rest client in its own package.
 */

'use strict';

const FirebaseTokenGenerator = require('firebase-token-generator');
const hash = require('object-hash');
const rest = require('../rest');

const log = require('debug')('firebase-test:context:rest');

// admin auth data
const adminAuth = {uid: 'DB Admin'};

const noop = () => {};

/**
 * Rest driver.
 *
 * Test operation by applying them to a live database.
 *
 */
class LiveDriver {

  /**
   * Create token generator and rest client.
   *
   * @param {{secret: string, projectId: string}} options Driver options
   */
  constructor(options = {}) {
    if (options.secret == null) {
      throw new Error('No Firebase secret provided.');
    }

    this.client = exports.client(options);
    this.generator = exports.tokenGenerator(options);
    this.secret = options.secret;
  }

  get id() {
    return 'rest';
  }

  /**
   * Placeholder for init hook - nothing to initialize on the Context object.
   */
  init() {}

  /**
   * Enqueue testing the operation can be applied.
   *
   * @param  {Context} ctx Context holding rules, initial datas and the operations to test
   * @return {Promise<void,Error>}
   */
  exec(ctx) {
    return lock(this.client, () => this.runOps(ctx));
  }

  /**
   * Test the operation can be applied.
   *
   * @param  {Context} ctx Context holding rules, initial datas and the operations to test
   * @return {Promise<void,Error>}
   */
  runOps(ctx) {
    const {ops, seed, rules} = ctx;
    const tokens = new Tokens(this.generator);

    const adminToken = tokens.get(adminAuth, {admin: true});
    const setup = Promise.all([
      deployRules({rules, client: this.client, secret: this.secret}),
      this.client.set({paths: '', payload: seed, auth: adminToken, silent: true})
    ]);

    return ops.reduce(
      (chain, operation) => {
        const {op, path: paths, value, auth: authData = null, options: {debug = false, silent = true} = {}} = operation;
        const auth = authData == null ? null : tokens.get(authData, {debug});

        switch (op) {

        case 'get':
          return chain.then(() => this.client.get({paths, auth, silent}));

        case 'push':
        case 'set':
        case 'update':
          return chain.then(() => this.client[op]({paths, payload: value, auth, silent: true}));

        default:
          return chain.then(() => Promise.reject(new Error(`Unknown operation type "${op}"`)));

        }
      },
      setup
    );
  }

}

/**
 * Cache auth tokens
 */
class Tokens {

  constructor(generator) {
    this.generator = generator;
    this.tokens = new Map();
  }

  /**
   * Get token from the cache or generate it if it doesn't exist.
   *
   * @param  {object} auth Auth data
   * @param  {object} opts token object
   * @return {string}
   */
  get(auth, opts) {
    const key = hash({auth, opts});

    if (this.tokens.has(key) === false) {
      this.tokens.set(key, this.generator.createToken(auth, opts));
    }

    return this.tokens.get(key);
  }

}

/**
 * Create the rest driver.
 *
 * @param {{secret: string, projectId: string}} opts Driver options
 * @return {LiveDriver}
 */
exports.create = function(opts) {
  return new LiveDriver(opts);
};

/**
 * Create a REST client for a Firebase database.
 *
 * @param  {string} options.projectId Firebase project id
 * @return {RestClient}
 */
exports.client = function({projectId, client}) {
  if (client != null) {
    log('Rest driver will use the provided client.');

    return client;
  }

  return rest.client({projectId});
};

/**
 * Create a Firebase legacy token generator
 *
 * @param  {string}                   options.secret          Secret to generate token with
 * @return {{createToken: function(data: object, opt: object): string}}
 */
exports.tokenGenerator = function({secret, tokenGenerator}) {
  if (tokenGenerator != null) {
    log('Rest driver will use the provided token generator.');

    return tokenGenerator;
  }

  if (secret == null) {
    throw new Error('The rest driver require a firebase secret');
  }

  log('Rest driver will use the default token generator.');

  return new FirebaseTokenGenerator(secret);
};

/**
 * Rules deployment cache.
 *
 * @type {Map<string,Promise<string>>}
 */
const rulesRequests = new Map();

/**
 * Sequence chains - used synchronize sequence execution.
 *
 * One sequence shouldn't run while an other (targeting the same project) does.
 *
 * @type {Map<string,Promise<void>>}
 */
const sequences = new Map();

/**
 * Reset rules deployment cache and sequence chain.
 *
 * Only useful for tests.
 */
exports.reset = function() {
  rulesRequests.clear();
  sequences.clear();
};

/**
 * Deploy rules for a database project.
 *
 * It deploy the rules only if the previous deployed rules were different.
 *
 * @param  {object}     options          Request options
 * @param  {RestClient} options.client   Client
 * @param  {object}     options.rules    Rules to deploy
 * @param  {string}     options.secret   Secret to authenticate the request
 * @return {Promise<void,Error>}
 */
function deployRules({client, rules, secret}) {
  const lastRequest = rulesRequests.get(client.projectId);

  return Promise.resolve(lastRequest).then(oldRulesHash => {
    const newRuleHash = hash(rules);

    if (oldRulesHash === newRuleHash) {
      return oldRulesHash;
    }

    const request = client.rules({rules, secret});

    rulesRequests.set(client.projectId, request.then(
      () => newRuleHash,
      () => oldRulesHash
    ));

    return request;
  });
}

/**
 * Run a sequence once the previous sequence for that project id ends.
 *
 * @param  {{projectId: string}}             client   Rest client
 * @param  {function(): Promise<void,Error>} sequence Sequence to run
 * @return {Promise<void,Error>}
 */
function lock(client, sequence) {
  const lastSequence = sequences.get(client.projectId);

  return Promise.resolve(lastSequence).then(() => {
    const result = sequence();

    sequences.set(client.projectId, result.then(noop, noop));

    return result;
  });
}
<|endoftext|>


<commit_before>/*global casper:false */
/*functional testing for the basic functionality of opentaba home page (without specific plan displaying)

 runs with casperjs test filename (or casperjs.bat on windows)
*/
//Some setup //TODO: move this to a global casper config
var url = '../index.html';
casper.options.clientScripts.push('./node_modules/sinon/lib/sinon.js');
casper.options.clientScripts.push('./fixture.js');
casper.options.logLevel = "debug";
casper.options.verbose = true;
casper.options.viewportSize = {width:1024, height:768};
//Starting the tests
casper.test.begin('Basic index.html elements test',23, function suite(test){

	casper.on('page.init',initMock).
	on('remote.message',log).
	start(url, function(){

		//casper.options.clientScripts.push('../testlibs/sinon-1.7.3.js');
		test.assertTitle('תב"ע פתוחה',"The title is what we expected");
		test.assertExists('form[id="addr-form"]', 'The Address form exists');
		test.assertExists('#right-bar','The right bar exists');
		test.assertVisible('#right-bar');
		test.assertExists('#header', 'The header div exists');
		test.assertVisible('#header');
		test.assertExists('#info', 'The info div exists');
		test.assertVisible('#info');
		//this.wait(5000);
		test.assertExists('#map.leaflet-container.leaflet-fade-anim','The map div exists with leaflet class');
		test.assertExists('#docModal','The doc modal exists');
		test.assertNotVisible('#docModal');
		test.assertExists('#faqModal','The faq modal exists');
		test.assertNotVisible('#faqModal');
		test.assertExists('.icon-twitter', 'The twitter icon exists');
		test.assertVisible('.icon-twitter');
		test.assertExists('.icon-facebook', 'The facebook icon exists');
		//very tied to implentation should think about this
		test.assertResourceExists('lib/pdfobject.js');
		test.assertResourceExists('lib/path.js');
		test.assertResourceExists('data/gushim.min.js');
		test.assertResourceExists('app.js');
		test.assertResourceExists('lib/bootstrap/js/bootstrap.min.js');
		//TODO: phantomcss check map rendering
	});

	casper.thenClick('a[href="#faqModal"]',function(){
		this.echo('clicked faqModal');
		this.waitUntilVisible('#faqModal');
	});

	casper.then(function(){
		test.assertVisible('#faqModal');
		this.click('button[class="close"]');
		this.echo('clicked to close faqModal');
	});

	casper.then(function(){
		test.assertNotVisible('faqModal');
	});
	//TODO: phantomcss testing for map rendering
	//TODO: basic form testing (needs sinon injections and mocking
	casper.run(function(){
		test.done();
	});
});

function initMock(){
	casper.evaluate(function(){
		var server = sinon.fakeServer.create(); server.autoRespond = true;
		console.log(planFixture_30338.length);
		var answer = planFixture_30338;
		var get_30338 = 'http://0.0.0.0:5000/gush/30338/plans'
		var content = {"content-type":"application/json"}
		//TODO: change the response for address locating
		server.respondWith('GET',get_30338 ,
			[200, content , answer]);
		server.respond();
		console.log('injected sinon');
		//console.log(server);
		//return server;

	});
	casper.log('injected sinon fakeserver now', 'debug');
}

function log(msg){
	console.log(msg);
}

<commit_msg>moved phantomcss testing to a seperate file<commit_after>/*global casper:false */
/*functional testing for the basic functionality of opentaba home page (without specific plan displaying)

 runs with casperjs test filename (or casperjs.bat on windows)
*/
//Some setup //TODO: move this to a global casper config
var url = '../index.html';
casper.options.clientScripts.push('./node_modules/sinon/lib/sinon.js');
casper.options.clientScripts.push('./fixture.js');
casper.options.logLevel = "debug";
casper.options.verbose = true;
casper.options.viewportSize = {width:1024, height:768};
//initializing phantomcss

//Starting the tests
casper.test.begin('Basic index.html elements test',23, function suite(test){

	casper.on('page.init',initMock).
	on('remote.message',log).
	start(url, function(){

		//casper.options.clientScripts.push('../testlibs/sinon-1.7.3.js');
		test.assertTitle('תב"ע פתוחה',"The title is what we expected");
		test.assertExists('form[id="addr-form"]', 'The Address form exists');
		test.assertExists('#right-bar','The right bar exists');
		test.assertVisible('#right-bar');
		test.assertExists('#header', 'The header div exists');
		test.assertVisible('#header');
		test.assertExists('#info', 'The info div exists');
		test.assertVisible('#info');
		//this.wait(5000);
		test.assertExists('#map.leaflet-container.leaflet-fade-anim','The map div exists with leaflet class');
		test.assertExists('#docModal','The doc modal exists');
		test.assertNotVisible('#docModal');
		test.assertExists('#faqModal','The faq modal exists');
		test.assertNotVisible('#faqModal');
		test.assertExists('.icon-twitter', 'The twitter icon exists');
		test.assertVisible('.icon-twitter');
		test.assertExists('.icon-facebook', 'The facebook icon exists');
		//very tied to implentation should think about this
		test.assertResourceExists('lib/pdfobject.js');
		test.assertResourceExists('lib/path.js');
		test.assertResourceExists('data/gushim.min.js');
		test.assertResourceExists('app.js');
		test.assertResourceExists('lib/bootstrap/js/bootstrap.min.js');

		//TODO: phantomcss check map rendering
	});

	casper.thenClick('a[href="#faqModal"]',function(){
		this.echo('clicked faqModal');
		this.waitUntilVisible('#faqModal');
	});

	casper.then(function(){
		test.assertVisible('#faqModal');
		this.click('button[class="close"]');
		this.echo('clicked to close faqModal');
	});

	casper.then(function(){
		test.assertNotVisible('faqModal');
	});

	//TODO: basic form testing (needs sinon injections and mocking
	casper.run(function(){
		test.done();
	});
});

function initMock(){
	casper.evaluate(function(){
		var server = sinon.fakeServer.create(); server.autoRespond = true;
		console.log(planFixture_30338.length);
		var answer = planFixture_30338;
		var get_30338 = 'http://0.0.0.0:5000/gush/30338/plans';
		var content = {"content-type":"application/json"};
		//TODO: change the response for address locating
		server.respondWith('GET',get_30338 ,
			[200, content , answer]);
		server.respond();
		console.log('injected sinon');
		//console.log(server);
		//return server;

	});
	casper.log('injected sinon fakeserver now', 'debug');
}

function log(msg){
	console.log(msg);
}

<|endoftext|>


<commit_before>import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import htmlToElement from './htmlToElement';
import {Linking, Platform, StyleSheet, View, ViewPropTypes} from 'react-native';

const boldStyle = {fontWeight: '500'};
const italicStyle = {fontStyle: 'italic'};
const underlineStyle = {textDecorationLine: 'underline'};
const strikethroughStyle = {textDecorationLine: 'line-through'};
const codeStyle = {fontFamily: Platform.OS === 'ios' ? 'Menlo' : 'monospace'};

const baseStyles = StyleSheet.create({
  b: boldStyle,
  strong: boldStyle,
  i: italicStyle,
  em: italicStyle,
  u: underlineStyle,
  s: strikethroughStyle,
  strike: strikethroughStyle,
  pre: codeStyle,
  code: codeStyle,
  a: {
    fontWeight: '500',
    color: '#007AFF',
  },
  h1: {fontWeight: '500', fontSize: 36},
  h2: {fontWeight: '500', fontSize: 30},
  h3: {fontWeight: '500', fontSize: 24},
  h4: {fontWeight: '500', fontSize: 18},
  h5: {fontWeight: '500', fontSize: 14},
  h6: {fontWeight: '500', fontSize: 12},
});

const htmlToElementOptKeys = [
  'lineBreak',
  'paragraphBreak',
  'bullet',
  'TextComponent',
  'textComponentProps',
  'NodeComponent',
  'nodeComponentProps',
];

class HtmlView extends PureComponent {
  constructor() {
    super();
    this.state = {
      element: null,
    };
  }

  componentDidMount() {
    this.mounted = true;
    this.startHtmlRender(this.props.value);
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.value !== nextProps.value || this.props.stylesheet !== nextProps.stylesheet || this.props.textComponentProps !== nextProps.textComponentProps || this.props.nodeComponentProps !== nextProps.nodeComponentProps) {
      this.startHtmlRender(nextProps.value, nextProps.stylesheet, nextProps.textComponentProps, nextProps.nodeComponentProps);
    }
  }

  componentWillUnmount() {
    this.mounted = false;
  }

  startHtmlRender(value, style, textComponentProps, nodeComponentProps) {
    const {
      addLineBreaks,
      onLinkPress,
      onLinkLongPress,
      stylesheet,
      renderNode,
      onError,
    } = this.props;

    if (!value) {
      this.setState({element: null});
    }

    const opts = {
      addLineBreaks,
      linkHandler: onLinkPress,
      linkLongPressHandler: onLinkLongPress,
      styles: {...baseStyles, ...stylesheet, ...style},
      customRenderer: renderNode,
    };

    htmlToElementOptKeys.forEach(key => {
      if (typeof this.props[key] !== 'undefined') {
        opts[key] = this.props[key];
      }
    });

    if (textComponentProps) {
      opts.textComponentProps = textComponentProps;
    }

    if (nodeComponentProps) {
      opts.nodeComponentProps = nodeComponentProps;
    }

    htmlToElement(value, opts, (err, element) => {
      if (err) {
        onError(err);
      }

      if (this.mounted) {
        this.setState({element});
      }
    });
  }

  render() {
    const {RootComponent, style} = this.props;
    const {element} = this.state;
    if (element) {
      return (
        <RootComponent
          {...this.props.rootComponentProps}
          style={style}
        >
          {element}
        </RootComponent>
      );
    }
    return (
      <RootComponent
        {...this.props.rootComponentProps}
        style={style}
      />
    );
  }
}

HtmlView.propTypes = {
  addLineBreaks: PropTypes.bool,
  bullet: PropTypes.string,
  lineBreak: PropTypes.string,
  NodeComponent: PropTypes.func,
  nodeComponentProps: PropTypes.object,
  onError: PropTypes.func,
  onLinkPress: PropTypes.func,
  onLinkLongPress: PropTypes.func,
  paragraphBreak: PropTypes.string,
  renderNode: PropTypes.func,
  RootComponent: PropTypes.func,
  rootComponentProps: PropTypes.object,
  style: ViewPropTypes.style,
  stylesheet: PropTypes.object,
  TextComponent: PropTypes.func,
  textComponentProps: PropTypes.object,
  value: PropTypes.string,
};

HtmlView.defaultProps = {
  addLineBreaks: true,
  onLinkPress: url => Linking.openURL(url),
  onLinkLongPress: null,
  onError: console.error.bind(console),
  RootComponent: element => <View {...element} />, // eslint-disable-line react/display-name
};

export default HtmlView;
<commit_msg>Update HTMLView.js<commit_after>import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import htmlToElement from './htmlToElement';
import {Linking, Platform, StyleSheet, View, ViewPropTypes} from 'react-native';

const boldStyle = {fontWeight: '500'};
const italicStyle = {fontStyle: 'italic'};
const underlineStyle = {textDecorationLine: 'underline'};
const strikethroughStyle = {textDecorationLine: 'line-through'};
const codeStyle = {fontFamily: Platform.OS === 'ios' ? 'Menlo' : 'monospace'};

const baseStyles = StyleSheet.create({
  b: boldStyle,
  strong: boldStyle,
  i: italicStyle,
  em: italicStyle,
  u: underlineStyle,
  s: strikethroughStyle,
  strike: strikethroughStyle,
  pre: codeStyle,
  code: codeStyle,
  a: {
    fontWeight: '500',
    color: '#007AFF',
  },
  h1: {fontWeight: '500', fontSize: 36},
  h2: {fontWeight: '500', fontSize: 30},
  h3: {fontWeight: '500', fontSize: 24},
  h4: {fontWeight: '500', fontSize: 18},
  h5: {fontWeight: '500', fontSize: 14},
  h6: {fontWeight: '500', fontSize: 12},
});

const htmlToElementOptKeys = [
  'lineBreak',
  'paragraphBreak',
  'bullet',
  'TextComponent',
  'textComponentProps',
  'NodeComponent',
  'nodeComponentProps',
];

class HtmlView extends PureComponent {
  constructor() {
    super();
    this.state = {
      element: null,
    };
  }

  componentDidMount() {
    this.mounted = true;
    this.startHtmlRender(this.props.value);
  }

  componentDidUpdate(prevProps) {
    if (this.props.value !== prevProps.value || this.props.stylesheet !== prevProps.stylesheet || this.props.textComponentProps !== prevProps.textComponentProps || this.props.nodeComponentProps !== prevProps.nodeComponentProps) {
      this.startHtmlRender(this.props.value, this.props.stylesheet, this.props.textComponentProps, this.props.nodeComponentProps);
    }
  }

  componentWillUnmount() {
    this.mounted = false;
  }

  startHtmlRender(value, style, textComponentProps, nodeComponentProps) {
    const {
      addLineBreaks,
      onLinkPress,
      onLinkLongPress,
      stylesheet,
      renderNode,
      onError,
    } = this.props;

    if (!value) {
      this.setState({element: null});
    }

    const opts = {
      addLineBreaks,
      linkHandler: onLinkPress,
      linkLongPressHandler: onLinkLongPress,
      styles: {...baseStyles, ...stylesheet, ...style},
      customRenderer: renderNode,
    };

    htmlToElementOptKeys.forEach(key => {
      if (typeof this.props[key] !== 'undefined') {
        opts[key] = this.props[key];
      }
    });

    if (textComponentProps) {
      opts.textComponentProps = textComponentProps;
    }

    if (nodeComponentProps) {
      opts.nodeComponentProps = nodeComponentProps;
    }

    htmlToElement(value, opts, (err, element) => {
      if (err) {
        onError(err);
      }

      if (this.mounted) {
        this.setState({element});
      }
    });
  }

  render() {
    const {RootComponent, style} = this.props;
    const {element} = this.state;
    if (element) {
      return (
        <RootComponent
          {...this.props.rootComponentProps}
          style={style}
        >
          {element}
        </RootComponent>
      );
    }
    return (
      <RootComponent
        {...this.props.rootComponentProps}
        style={style}
      />
    );
  }
}

HtmlView.propTypes = {
  addLineBreaks: PropTypes.bool,
  bullet: PropTypes.string,
  lineBreak: PropTypes.string,
  NodeComponent: PropTypes.func,
  nodeComponentProps: PropTypes.object,
  onError: PropTypes.func,
  onLinkPress: PropTypes.func,
  onLinkLongPress: PropTypes.func,
  paragraphBreak: PropTypes.string,
  renderNode: PropTypes.func,
  RootComponent: PropTypes.func,
  rootComponentProps: PropTypes.object,
  style: ViewPropTypes.style,
  stylesheet: PropTypes.object,
  TextComponent: PropTypes.func,
  textComponentProps: PropTypes.object,
  value: PropTypes.string,
};

HtmlView.defaultProps = {
  addLineBreaks: true,
  onLinkPress: url => Linking.openURL(url),
  onLinkLongPress: null,
  onError: console.error.bind(console),
  RootComponent: element => <View {...element} />, // eslint-disable-line react/display-name
};

export default HtmlView;
<|endoftext|>


<commit_before>if(typeof exports === 'object') {
	var assert = require("assert");
	var alasql = require('..');
}

var test = '607'; // insert test file number

describe('Test '+test+' - TRUNCATE on Local Storage table', function() {

	before(function(){
		alasql('create LOCAL STORAGE database test'+test);
		alasql('ATTACH LOCALSTORAGE DATABASE test'+test);
		alasql('use test'+test);
		alasql('create table one (a int)');
		alasql('insert into one values (1),(2),(3),(4),(5)');
	});

	after(function(){
		alasql('drop database test'+test);
	});

	it('A) attempt TRUNCATE on table', function(){
		var res = alasql('TRUNCATE TABLE one (a int)');
		assert.equal(res, 1);
	});
});
<commit_msg>corrected a bug<commit_after>if(typeof exports === 'object') {
	var assert = require("assert");
	var alasql = require('..');
}

var test = '607'; // insert test file number

describe('Test '+test+' - TRUNCATE on Local Storage table', function() {

	before(function(){
		alasql('create LOCAL STORAGE database test'+test);
		alasql('ATTACH LOCALSTORAGE DATABASE test'+test);
		alasql('use test'+test);
		alasql('create table one (a int)');
		alasql('insert into one values (1),(2),(3),(4),(5)');
	});

	after(function(){
		alasql('drop database test'+test);
	});

	it('A) attempt TRUNCATE on table', function(){
		var res = alasql('TRUNCATE TABLE one');
		assert.equal(res, 1);
	});
});
<|endoftext|>


<commit_before>
var fs = require('fs'),
    http = require('http'),
    exec = require('child_process').exec,
	_ = require('underscore'),
    Geo = require('./geo');

function dpc(t,fn) { if(typeof(t) == 'function') setTimeout(t,0); else setTimeout(fn,t); }

function Scanner(options) {

	var self = this;
    self.options = options;

    var config = eval('('+fs.readFileSync("scanner.cfg",'utf8')+')');
    var upload = fs.existsSync('upload.cfg') ? eval('('+fs.readFileSync("upload.cfg",'utf8')+')') : null;

    self.addr_pending = { }     // list of addresses waiting scan
    self.addr_digested = { }    // list of scanned addresses
    self.addr_working = { }     // list of working addresses

    self.geo = new Geo({ timeout : config.http_socket_timeout });

  	// -----------------------------------------
   	// local http server interface
    if(config.http_port)
    {
        var express = require('express');
        var app = express();
        app.configure(function(){
            app.use(express.bodyParser());
        });
        app.get('/', function(req, res) {
            var str = self.render();
            res.write(str);
            res.end();
        });

        http.createServer(app).listen(config.http_port, function() {
            console.log("HTTP server listening on port: ",config.http_port);
        });
    }

    var logo = fs.readFileSync("resources/"+config.currency.toLowerCase()+".png","base64");
    if(logo)
        logo = "data:image/png;base64,"+logo;

    self.render = function() {
        var str = ""
            +""
            +"";
        if(logo)
            str += "

";
        str += "PEER TO PEER "+(config.currency.toUpperCase())+" MINING NETWORK - PUBLIC NODE LIST
GENERATED ON: "+(new Date())+"
"
        if(self.poolstats)
            str += "Pool speed: "+(self.poolstats.pool_hash_rate/1000000).toFixed(2)+" "+config.speed_abbrev+"";
        str += "Currently observing "+(self.nodes_total || "N/A")+" nodes.
"+_.size(self.addr_working)+" nodes are public with following IPs:
";
        str += "
";
        str += "

IPs

Fee

Uptime

Location
";
        str += "

";

        var list = _.sortBy(_.toArray(self.addr_working), function(o) { return o.stats ? -o.stats.uptime : 0; })

        var row = 0;
        _.each(list, function(info) {
            var ip = info.ip;

            var uptime = info.stats ? (info.stats.uptime / 60 / 60 / 24).toFixed(1) : "N/A";
            var fee = (info.fee || 0).toFixed(2);

            str += "

"+ip+":9327

"+fee+"%

"+uptime+" days
";
            str += "
";
            if(info.geo) {
                str += ""+info.geo.country+" "+"";
            }
            str += "
";
            str += "
";
            str += "
";
        })
        str += "

";
        str += ""
        return str;
    }

    // setup flushing of rendered HTML page to a file (useful for uploading to other sites)
    if(config.flush_to_file_every_N_msec && config.flush_filename) {
        function flush_rendering() {
            var str = self.render();
            fs.writeFile(config.flush_filename, str, { encoding : 'utf8'});
            dpc(config.flush_to_file_every_N_msec, flush_rendering);
        }

        dpc(5000, flush_rendering);
    }

    // defer init
    dpc(function(){
        self.restore_working();
        self.update();
    })

    var p2pool_init = true;

    // main function that reloads 'addr' file from p2pool
    self.update = function() {
        var filename = config.addr_file;
        if(!fs.existsSync(filename)) {
            console.error("Unable to fetch p2pool address list from:",config.addr_file);
            filename = config.init_file;    // if we can't read p2pool's addr file, we just cycle on the local default init...
        }

        fs.readFile(filename, { encoding : 'utf8' }, function(err, data) {
            if(err) {
                console.error(err);
            }
            else {
                try {
                    var addr_list = JSON.parse(data);
                    self.inject(addr_list);

                    // main init
                    if(p2pool_init) {
                        p2pool_init = false;

                        // if we can read p2pool addr file, also add our pre-collected IPs
                        // if(filename != config.init_file) {
                            var init_addr = JSON.parse(fs.readFileSync(config.init_file, 'utf8'));
                            self.inject(init_addr);
                        //}

                        for(var i = 0; i < (config.probe_N_IPs_simultaneously || 1); i++)
                            self.digest();
                        dpc(60*1000, function() { self.store_working(); })
                    }
                }
                catch(ex) {
                    console.error("Unable to parse p2pool address list");
                    console.error(ex);
                }
            }

            dpc(1000 * 60, self.update);
        })
    }

    // store public pools in a file that reloads at startup
    self.store_working = function() {
        var data = JSON.stringify(self.addr_working);
        fs.writeFile(config.store_file, data, { encoding : 'utf8' }, function(err) {
            dpc(60*1000, self.store_working);
        })
    }

    // reload public list at startup
    self.restore_working = function() {
        try {
            self.addr_working = JSON.parse(fs.readFileSync(config.store_file, 'utf8'));
        } catch(ex) { /*console.log(ex);*/ }
    }

    // inject new IPs from p2pool addr file
    self.inject = function(addr_list) {
        _.each(addr_list, function(info) {
            var ip = info[0][0];
            var port = info[0][1];

            if(!self.addr_digested[ip] && !self.addr_pending[ip]) {
                self.addr_pending[ip] = { ip : ip, port : port }
            }

            self.nodes_total = _.size(self.addr_digested) + _.size(self.addr_pending);
        });
    }

    // as we scan pools, we fetch global info from them to update the page
    self.update_global_stats = function(poolstats) {
        self.poolstats = poolstats;
    }

    // execute scan of a single IP
    self.digest = function() {

        if(!_.size(self.addr_pending))
            return self.list_complete();

        var info = _.find(self.addr_pending, function() { return true; });
        delete self.addr_pending[info.ip];
        self.addr_digested[info.ip] = info;
        // console.log("P2POOL DIGESTING:",info.ip);

        digest_ip(info, function(err, fee){
            if(!err) {
                info.fee = fee;
                self.addr_working[info.ip] = info;
                // console.log("FOUND WORKING POOL: ", info.ip);

                digest_local_stats(info, function(err, stats) {
                    if(!err)
                        info.stats = stats;
                    digest_global_stats(info, function(err, stats) {
                        if(!err)
                            self.update_global_stats(stats);

                        if(!info.geo)
                            self.geo.get(info.ip, function(err, geo) {
                                if(!err)
                                    info.geo = geo;

                                continue_digest();
                            });
                        else
                            continue_digest();
                    });
                });
            }
            else {
                delete self.addr_working[info.ip];
                continue_digest();
            }

            function continue_digest() {
                self.working_size = _.size(self.addr_working);
                dpc(self.digest);
            }
        });
    }

    // schedule restar of the scan once all IPs are done
    self.list_complete = function() {
        self.addr_pending = self.addr_digested;
        self.addr_digested = { }
        dpc(config.rescan_list_delay, self.digest);
    }

    // functions to fetch data from target node IP

    function digest_ip(info, callback) {

        var options = {
          host: info.ip,
          port: 9327,
          path: '/fee',
          method: 'GET'
        };

        self.request(options, callback);
    }

    function digest_local_stats(info, callback) {

        var options = {
          host: info.ip,
          port: 9327,
          path: '/local_stats',
          method: 'GET'
        };

        self.request(options, callback);
    }

    function digest_global_stats(info, callback) {

        var options = {
          host: info.ip,
          port: 9327,
          path: '/global_stats',
          method: 'GET'
        };

        self.request(options, callback);
    }

    // make http request to the target node ip
    self.request = function(options, callback, is_plain)
    {
        http_handler = http;
        var req = http_handler.request(options, function(res) {
            res.setEncoding('utf8');
            var result = '';
            res.on('data', function (data) {
                result += data;
            });

            res.on('end', function () {
                if(options.plain)
                    callback(null, result);
                else {
                    try {
                        var o = JSON.parse(result);
                        callback(null, o);
                    } catch(ex) {
                        console.error(ex);
                        callback(ex);
                    }
                }
            });
        });

        req.on('socket', function (socket) {
            socket.setTimeout(config.http_socket_timeout);
            socket.on('timeout', function() {
                req.abort();
            });
        });

        req.on('error', function(e) {
            callback(e);
        });

        req.end();
    }

    if(upload && process.platform != 'win32') {

        function do_upload() {

            if(upload.ftp) {
                var ftp = upload.ftp;
                if(!ftp.address || !ftp.username || !ftp.password)
                    return console.error("upload.cfg ftp configuration must contain target address, username and password");
                var cmd = "curl -T "+config.flush_filename+" "+ftp.address+" --user "+ftp.address+":"+ftp.password;
                exec(cmd, function(error){ if(error) console.error(error); });
            }

            if(upload.scp) {
                var scp = upload.scp;
                if(!scp.address)
                    return console.error("upload.cfg scp configuration must contain target address");
                var cmd = "scp -q ./"+config.flush_filename+" "+scp.address;
                exec(cmd, function(error){ if(error) console.error(error); });
            }

            dpc(config.upload_interval, do_upload);
        }

        dpc(5000, do_upload);
    }
    else
        console.log("upload.cfg not found, rendering available only on the local interface");
}

GLOBAL.scanner = new Scanner();

//  <commit_msg>Show P2Pool version in node list<commit_after>
var fs = require('fs'),
    http = require('http'),
    exec = require('child_process').exec,
	_ = require('underscore'),
    Geo = require('./geo');

function dpc(t,fn) { if(typeof(t) == 'function') setTimeout(t,0); else setTimeout(fn,t); }

function Scanner(options) {

	var self = this;
    self.options = options;

    var config = eval('('+fs.readFileSync("scanner.cfg",'utf8')+')');
    var upload = fs.existsSync('upload.cfg') ? eval('('+fs.readFileSync("upload.cfg",'utf8')+')') : null;

    self.addr_pending = { }     // list of addresses waiting scan
    self.addr_digested = { }    // list of scanned addresses
    self.addr_working = { }     // list of working addresses

    self.geo = new Geo({ timeout : config.http_socket_timeout });

  	// -----------------------------------------
   	// local http server interface
    if(config.http_port)
    {
        var express = require('express');
        var app = express();
        app.configure(function(){
            app.use(express.bodyParser());
        });
        app.get('/', function(req, res) {
            var str = self.render();
            res.write(str);
            res.end();
        });

        http.createServer(app).listen(config.http_port, function() {
            console.log("HTTP server listening on port: ",config.http_port);
        });
    }

    var logo = fs.readFileSync("resources/"+config.currency.toLowerCase()+".png","base64");
    if(logo)
        logo = "data:image/png;base64,"+logo;

    self.render = function() {
        var str = ""
            +""
            +"";
        if(logo)
            str += "

";
        str += "PEER TO PEER "+(config.currency.toUpperCase())+" MINING NETWORK - PUBLIC NODE LIST
GENERATED ON: "+(new Date())+"
"
        if(self.poolstats)
            str += "Pool speed: "+(self.poolstats.pool_hash_rate/1000000).toFixed(2)+" "+config.speed_abbrev+"";
        str += "Currently observing "+(self.nodes_total || "N/A")+" nodes.
"+_.size(self.addr_working)+" nodes are public with following IPs:
";
        str += "
";
        str += "

IPs

Version

Fee

Uptime

Location
";
        str += "

";

        var list = _.sortBy(_.toArray(self.addr_working), function(o) { return o.stats ? -o.stats.uptime : 0; })

        var row = 0;
        _.each(list, function(info) {
            var ip = info.ip;

            var version = info.stats.version ? info.stats.version.replace(/-g.*/, "") : "N/A";
            var uptime = info.stats ? (info.stats.uptime / 60 / 60 / 24).toFixed(1) : "N/A";
            var fee = (info.fee || 0).toFixed(2);

            str += "

"+ip+":9327

"+version+"

"+fee+"%

"+uptime+" days
";
            str += "
";
            if(info.geo) {
                str += ""+info.geo.country+" "+"";
            }
            str += "
";
            str += "
";
            str += "
";
        })
        str += "

";
        str += ""
        return str;
    }

    // setup flushing of rendered HTML page to a file (useful for uploading to other sites)
    if(config.flush_to_file_every_N_msec && config.flush_filename) {
        function flush_rendering() {
            var str = self.render();
            fs.writeFile(config.flush_filename, str, { encoding : 'utf8'});
            dpc(config.flush_to_file_every_N_msec, flush_rendering);
        }

        dpc(5000, flush_rendering);
    }

    // defer init
    dpc(function(){
        self.restore_working();
        self.update();
    })

    var p2pool_init = true;

    // main function that reloads 'addr' file from p2pool
    self.update = function() {
        var filename = config.addr_file;
        if(!fs.existsSync(filename)) {
            console.error("Unable to fetch p2pool address list from:",config.addr_file);
            filename = config.init_file;    // if we can't read p2pool's addr file, we just cycle on the local default init...
        }

        fs.readFile(filename, { encoding : 'utf8' }, function(err, data) {
            if(err) {
                console.error(err);
            }
            else {
                try {
                    var addr_list = JSON.parse(data);
                    self.inject(addr_list);

                    // main init
                    if(p2pool_init) {
                        p2pool_init = false;

                        // if we can read p2pool addr file, also add our pre-collected IPs
                        // if(filename != config.init_file) {
                            var init_addr = JSON.parse(fs.readFileSync(config.init_file, 'utf8'));
                            self.inject(init_addr);
                        //}

                        for(var i = 0; i < (config.probe_N_IPs_simultaneously || 1); i++)
                            self.digest();
                        dpc(60*1000, function() { self.store_working(); })
                    }
                }
                catch(ex) {
                    console.error("Unable to parse p2pool address list");
                    console.error(ex);
                }
            }

            dpc(1000 * 60, self.update);
        })
    }

    // store public pools in a file that reloads at startup
    self.store_working = function() {
        var data = JSON.stringify(self.addr_working);
        fs.writeFile(config.store_file, data, { encoding : 'utf8' }, function(err) {
            dpc(60*1000, self.store_working);
        })
    }

    // reload public list at startup
    self.restore_working = function() {
        try {
            self.addr_working = JSON.parse(fs.readFileSync(config.store_file, 'utf8'));
        } catch(ex) { /*console.log(ex);*/ }
    }

    // inject new IPs from p2pool addr file
    self.inject = function(addr_list) {
        _.each(addr_list, function(info) {
            var ip = info[0][0];
            var port = info[0][1];

            if(!self.addr_digested[ip] && !self.addr_pending[ip]) {
                self.addr_pending[ip] = { ip : ip, port : port }
            }

            self.nodes_total = _.size(self.addr_digested) + _.size(self.addr_pending);
        });
    }

    // as we scan pools, we fetch global info from them to update the page
    self.update_global_stats = function(poolstats) {
        self.poolstats = poolstats;
    }

    // execute scan of a single IP
    self.digest = function() {

        if(!_.size(self.addr_pending))
            return self.list_complete();

        var info = _.find(self.addr_pending, function() { return true; });
        delete self.addr_pending[info.ip];
        self.addr_digested[info.ip] = info;
        // console.log("P2POOL DIGESTING:",info.ip);

        digest_ip(info, function(err, fee){
            if(!err) {
                info.fee = fee;
                self.addr_working[info.ip] = info;
                // console.log("FOUND WORKING POOL: ", info.ip);

                digest_local_stats(info, function(err, stats) {
                    if(!err)
                        info.stats = stats;
                    digest_global_stats(info, function(err, stats) {
                        if(!err)
                            self.update_global_stats(stats);

                        if(!info.geo)
                            self.geo.get(info.ip, function(err, geo) {
                                if(!err)
                                    info.geo = geo;

                                continue_digest();
                            });
                        else
                            continue_digest();
                    });
                });
            }
            else {
                delete self.addr_working[info.ip];
                continue_digest();
            }

            function continue_digest() {
                self.working_size = _.size(self.addr_working);
                dpc(self.digest);
            }
        });
    }

    // schedule restar of the scan once all IPs are done
    self.list_complete = function() {
        self.addr_pending = self.addr_digested;
        self.addr_digested = { }
        dpc(config.rescan_list_delay, self.digest);
    }

    // functions to fetch data from target node IP

    function digest_ip(info, callback) {

        var options = {
          host: info.ip,
          port: 9327,
          path: '/fee',
          method: 'GET'
        };

        self.request(options, callback);
    }

    function digest_local_stats(info, callback) {

        var options = {
          host: info.ip,
          port: 9327,
          path: '/local_stats',
          method: 'GET'
        };

        self.request(options, callback);
    }

    function digest_global_stats(info, callback) {

        var options = {
          host: info.ip,
          port: 9327,
          path: '/global_stats',
          method: 'GET'
        };

        self.request(options, callback);
    }

    // make http request to the target node ip
    self.request = function(options, callback, is_plain)
    {
        http_handler = http;
        var req = http_handler.request(options, function(res) {
            res.setEncoding('utf8');
            var result = '';
            res.on('data', function (data) {
                result += data;
            });

            res.on('end', function () {
                if(options.plain)
                    callback(null, result);
                else {
                    try {
                        var o = JSON.parse(result);
                        callback(null, o);
                    } catch(ex) {
                        console.error(ex);
                        callback(ex);
                    }
                }
            });
        });

        req.on('socket', function (socket) {
            socket.setTimeout(config.http_socket_timeout);
            socket.on('timeout', function() {
                req.abort();
            });
        });

        req.on('error', function(e) {
            callback(e);
        });

        req.end();
    }

    if(upload && process.platform != 'win32') {

        function do_upload() {

            if(upload.ftp) {
                var ftp = upload.ftp;
                if(!ftp.address || !ftp.username || !ftp.password)
                    return console.error("upload.cfg ftp configuration must contain target address, username and password");
                var cmd = "curl -T "+config.flush_filename+" "+ftp.address+" --user "+ftp.address+":"+ftp.password;
                exec(cmd, function(error){ if(error) console.error(error); });
            }

            if(upload.scp) {
                var scp = upload.scp;
                if(!scp.address)
                    return console.error("upload.cfg scp configuration must contain target address");
                var cmd = "scp -q ./"+config.flush_filename+" "+scp.address;
                exec(cmd, function(error){ if(error) console.error(error); });
            }

            dpc(config.upload_interval, do_upload);
        }

        dpc(5000, do_upload);
    }
    else
        console.log("upload.cfg not found, rendering available only on the local interface");
}

GLOBAL.scanner = new Scanner();

//
<|endoftext|>


<commit_before>/**
 * @fileoverview this file defines the mymaps webservice. this service
 * interacts with the Geoportail MyMaps webservice and exposes functions that
 * return objects representing maps and features.
 */

goog.provide('app.Mymaps');

goog.require('app');
goog.require('app.UserManager');

/**
 * @typedef {Array.<Object>}
 */
app.MapsResponse;

/**
 * @constructor
 * @param {angular.$http} $http
 * @param {string} mymapsMapsUrl URL to "mymaps" Maps service.
 * @param {string} mymapsUrl URL to "mymaps" Features service.
 * @param {app.DrawnFeatures} appDrawnFeatures Drawn features service.
 * @param {app.StateManager} appStateManager
 * @param {app.UserManager} appUserManager
 * @ngInject
 */
app.Mymaps = function($http, mymapsMapsUrl, mymapsUrl, appDrawnFeatures,
    appStateManager, appUserManager) {

  /**
   * @type {app.UserManager}
   * @private
   */
  this.appUserManager_ = appUserManager;

  /**
   * @type {ol.Collection.<ol.Feature>}
   * @private
   */
  this.drawnFeatures_ = appDrawnFeatures;

  /**
   * @type {app.StateManager}
   * @private
   */
  this.stateManager_ = appStateManager;

  /**
   * @type {angular.$http}
   * @private
   */
  this.$http_ = $http;

  /**
   * @type {string}
   * @private
   */
  this.mymapsMapsUrl_ = mymapsMapsUrl;

  /**
   * @type {string}
   * @private
   */
  this.mymapsFeaturesUrl_ = mymapsUrl + '/features/';

  /**
   * @type {string}
   * @private
   */
  this.mymapsMapInfoUrl_ = mymapsUrl + '/map/';

  /**
   * @type {string}
   * @private
   */
  this.mymapsDeleteFeatureUrl_ = mymapsUrl + '/delete_feature/';

  /**
   * @type {string}
   * @private
   */
  this.mymapsDeleteMapUrl_ = mymapsUrl + '/delete/';

  /**
   * @type {string}
   * @private
   */
  this.mymapsCreateMapUrl_ = mymapsUrl + '/create';

  /**
   * @type {string}
   * @private
   */
  this.mymapsUpdateMapUrl_ = mymapsUrl + '/update/';

  /**
   * @type {string}
   * @private
   */
  this.mymapsSaveFeatureUrl_ = mymapsUrl + '/save_feature/';

  /**
   * @type {string}
   * @private
   */
  this.mapId_ = '';

  /**
   * The currently displayed map title.
   * @type {string}
   */
  this.mapTitle = '';

  /**
   * The currently displayed map title.
   * @type {string}
   */
  this.mapOwner = '';

  /**
   * The currently displayed map description.
   * @type {string}
   */
  this.mapDescription = '';

  /**
   * @type {ol.FeatureStyleFunction}
   * @private
   */
  this.featureStyleFunction_ = app.DrawController.createStyleFunction();

  /**
   * @type {ol.proj.Projection}
   */
  this.mapProjection;
};

/**
 * @param {string} mapId the map id.
 */
app.Mymaps.prototype.setCurrentMapId = function(mapId) {
  this.mapId_ = mapId;
  if (this.isMymapsSelected()) {
    this.stateManager_.updateState({
      'map_id': this.mapId_
    });
    this.loadMapInformation_().then(
        goog.bind(function(mapinformation) {
          this.mapDescription = mapinformation['description'];
          this.mapTitle = mapinformation['title'];
          this.mapOwner = mapinformation['user_login'];
        }, this));
    this.loadFeatures_().then(goog.bind(function(features) {
      var encOpt = /** @type {olx.format.ReadOptions} */ ({
        dataProjection: 'EPSG:2169',
        featureProjection: this.mapProjection
      });
      var jsonFeatures = ((new ol.format.GeoJSON()).
          readFeatures(features, encOpt));
      for (var i in jsonFeatures) {
        jsonFeatures[i].set('__source__', 'mymaps');
        jsonFeatures[i].set('__editable__', true);
        jsonFeatures[i].setStyle(this.featureStyleFunction_);
      }
      this.drawnFeatures_.extend(/** @type {!Array<(null|ol.Feature)>} */
          (jsonFeatures));
    }, this));
  }else {
    this.stateManager_.deleteParam('map_id');
    this.mapId_ = '';
    this.mapTitle = '';
    this.mapDescription = '';
    this.mapOwner = '';
    this.drawnFeatures_.clear();
  }
};

/**
 * @return {boolean} return true if is editable by the user
 */
app.Mymaps.prototype.isEditable = function() {
  if (this.isMymapsSelected() && this.appUserManager_.isAuthenticated() &&
      (this.appUserManager_['isAdmin'] == 'TRUE' ||
       this.appUserManager_['login'] == this.mapOwner)) {
    return true;
  }
  return false;
};

/**
 * Get an array of map objects.
 * @return {angular.$q.Promise} Promise.
 */
app.Mymaps.prototype.getMaps = function() {
  return this.$http_.get(this.mymapsMapsUrl_).then(goog.bind(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {app.MapsResponse} The "mymaps" web service response.
         */
      function(resp) {
        return resp.data;
      }, this), goog.bind(
      function(error) {
        if (error.status == 401) {
          return null;
        }
        return [];
      }, this)
  );
};

/**
 * Load map features
 * @return {angular.$q.Promise} Promise.
 * @private
 */
app.Mymaps.prototype.loadFeatures_ = function() {
  return this.$http_.get(this.mymapsFeaturesUrl_ + this.mapId_).then(goog.bind(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {app.MapsResponse} The "mymaps" web service response.
         */
      function(resp) {
        return resp.data;
      }, this), goog.bind(
      function(error) {
        return [];
      }, this)
  );
};

/**
 * Load map information
 * @return {angular.$q.Promise} Promise.
 * @private
 */
app.Mymaps.prototype.loadMapInformation_ = function() {
  return this.$http_.get(this.mymapsMapInfoUrl_ + this.mapId_).then(goog.bind(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {app.MapsResponse} The "mymaps" web service response.
         */
      function(resp) {
        return resp.data;
      }, this), goog.bind(
      function(error) {
        return [];
      }, this)
  );
};

/**
 * Delete a map
 * @param {ol.Feature} feature the feature to delete.
 * @return {angular.$q.Promise} Promise.
 */
app.Mymaps.prototype.deleteFeature = function(feature) {
  return this.$http_.delete(this.mymapsDeleteFeatureUrl_ +
      feature.get('id')).then(goog.bind(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {app.MapsResponse} The "mymaps" web service response.
         */
      function(resp) {
        return resp.data;
      }, this), goog.bind(
      function(error) {
        return [];
      }, this)
  );
};

/**
 * create a new map
 * @param {string} title the title of the map.
 * @param {string} description a description about the map.
 * @return {angular.$q.Promise} Promise.
 */
app.Mymaps.prototype.createMap = function(title, description) {
  var req = $.param({
    'title': title,
    'description': description
  });
  var config = {
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
  };
  return this.$http_.post(this.mymapsCreateMapUrl_, req, config).then(
      goog.bind(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {app.MapsResponse} The "mymaps" web service response.
         */
      function(resp) {
        return resp.data;
      }, this), goog.bind(
      function(error) {
        return [];
      }, this)
  );
};

/**
 * delete a new map
 * @return {angular.$q.Promise} Promise.
 */
app.Mymaps.prototype.deleteMap = function() {
  return this.$http_.delete(this.mymapsDeleteMapUrl_ + this.mapId_).then(
      goog.bind(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {app.MapsResponse} The "mymaps" web service response.
         */
      function(resp) {
        return resp.data;
      }, this), goog.bind(
      function(error) {
        return [];
      }, this)
  );
};

/**
 * Save the map
 * @param {string} title the title of the map.
 * @param {string} description a description about the map.
 * @return {angular.$q.Promise} Promise.
 */
app.Mymaps.prototype.updateMap = function(title, description) {

  this.mapTitle = title;
  this.mapDescription = description;

  var req = $.param({
    'title': title,
    'description': description
  });
  var config = {
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
  };
  return this.$http_.put(this.mymapsUpdateMapUrl_ + this.mapId_,
      req, config).then(goog.bind(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {app.MapsResponse} The "mymaps" web service response.
         */
      function(resp) {
        return resp.data;
      }, this), goog.bind(
      function(error) {
        return [];
      }, this)
  );
};

/**
 * Save the map
 * @param {ol.Feature} feature the feature to save
 * @param {?ol.proj.Projection} featureProjection
 * @return {angular.$q.Promise} Promise.
 */
app.Mymaps.prototype.saveFeature = function(feature, featureProjection) {
  var encOpt = /** @type {olx.format.ReadOptions} */ ({
    dataProjection: 'EPSG:2169',
    featureProjection: featureProjection
  });
  var req = $.param({
    'feature': (new ol.format.GeoJSON()).writeFeature(feature, encOpt)
  });
  var config = {
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
  };
  return this.$http_.post(this.mymapsSaveFeatureUrl_ + this.mapId_,
      req, config).then(goog.bind(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {app.MapsResponse} The "mymaps" web service response.
         */
      function(resp) {
        return resp.data;
      }, this), goog.bind(
      function(error) {
        return [];
      }, this)
  );
};

/**
 * @return {boolean} return true if a map is selected
 */
app.Mymaps.prototype.isMymapsSelected = function() {
  return !goog.string.isEmpty(this.mapId_);
};

app.module.service('appMymaps', app.Mymaps);
<commit_msg>Remove unnecessary brackets<commit_after>/**
 * @fileoverview this file defines the mymaps webservice. this service
 * interacts with the Geoportail MyMaps webservice and exposes functions that
 * return objects representing maps and features.
 */

goog.provide('app.Mymaps');

goog.require('app');
goog.require('app.UserManager');

/**
 * @typedef {Array.<Object>}
 */
app.MapsResponse;

/**
 * @constructor
 * @param {angular.$http} $http
 * @param {string} mymapsMapsUrl URL to "mymaps" Maps service.
 * @param {string} mymapsUrl URL to "mymaps" Features service.
 * @param {app.DrawnFeatures} appDrawnFeatures Drawn features service.
 * @param {app.StateManager} appStateManager
 * @param {app.UserManager} appUserManager
 * @ngInject
 */
app.Mymaps = function($http, mymapsMapsUrl, mymapsUrl, appDrawnFeatures,
    appStateManager, appUserManager) {

  /**
   * @type {app.UserManager}
   * @private
   */
  this.appUserManager_ = appUserManager;

  /**
   * @type {ol.Collection.<ol.Feature>}
   * @private
   */
  this.drawnFeatures_ = appDrawnFeatures;

  /**
   * @type {app.StateManager}
   * @private
   */
  this.stateManager_ = appStateManager;

  /**
   * @type {angular.$http}
   * @private
   */
  this.$http_ = $http;

  /**
   * @type {string}
   * @private
   */
  this.mymapsMapsUrl_ = mymapsMapsUrl;

  /**
   * @type {string}
   * @private
   */
  this.mymapsFeaturesUrl_ = mymapsUrl + '/features/';

  /**
   * @type {string}
   * @private
   */
  this.mymapsMapInfoUrl_ = mymapsUrl + '/map/';

  /**
   * @type {string}
   * @private
   */
  this.mymapsDeleteFeatureUrl_ = mymapsUrl + '/delete_feature/';

  /**
   * @type {string}
   * @private
   */
  this.mymapsDeleteMapUrl_ = mymapsUrl + '/delete/';

  /**
   * @type {string}
   * @private
   */
  this.mymapsCreateMapUrl_ = mymapsUrl + '/create';

  /**
   * @type {string}
   * @private
   */
  this.mymapsUpdateMapUrl_ = mymapsUrl + '/update/';

  /**
   * @type {string}
   * @private
   */
  this.mymapsSaveFeatureUrl_ = mymapsUrl + '/save_feature/';

  /**
   * @type {string}
   * @private
   */
  this.mapId_ = '';

  /**
   * The currently displayed map title.
   * @type {string}
   */
  this.mapTitle = '';

  /**
   * The currently displayed map title.
   * @type {string}
   */
  this.mapOwner = '';

  /**
   * The currently displayed map description.
   * @type {string}
   */
  this.mapDescription = '';

  /**
   * @type {ol.FeatureStyleFunction}
   * @private
   */
  this.featureStyleFunction_ = app.DrawController.createStyleFunction();

  /**
   * @type {ol.proj.Projection}
   */
  this.mapProjection;
};

/**
 * @param {string} mapId the map id.
 */
app.Mymaps.prototype.setCurrentMapId = function(mapId) {
  this.mapId_ = mapId;
  if (this.isMymapsSelected()) {
    this.stateManager_.updateState({
      'map_id': this.mapId_
    });
    this.loadMapInformation_().then(
        goog.bind(function(mapinformation) {
          this.mapDescription = mapinformation['description'];
          this.mapTitle = mapinformation['title'];
          this.mapOwner = mapinformation['user_login'];
        }, this));
    this.loadFeatures_().then(goog.bind(function(features) {
      var encOpt = /** @type {olx.format.ReadOptions} */ ({
        dataProjection: 'EPSG:2169',
        featureProjection: this.mapProjection
      });
      var jsonFeatures = (new ol.format.GeoJSON()).
          readFeatures(features, encOpt);
      for (var i in jsonFeatures) {
        jsonFeatures[i].set('__source__', 'mymaps');
        jsonFeatures[i].set('__editable__', true);
        jsonFeatures[i].setStyle(this.featureStyleFunction_);
      }
      this.drawnFeatures_.extend(/** @type {!Array<(null|ol.Feature)>} */
          (jsonFeatures));
    }, this));
  }else {
    this.stateManager_.deleteParam('map_id');
    this.mapId_ = '';
    this.mapTitle = '';
    this.mapDescription = '';
    this.mapOwner = '';
    this.drawnFeatures_.clear();
  }
};

/**
 * @return {boolean} return true if is editable by the user
 */
app.Mymaps.prototype.isEditable = function() {
  if (this.isMymapsSelected() && this.appUserManager_.isAuthenticated() &&
      (this.appUserManager_['isAdmin'] == 'TRUE' ||
       this.appUserManager_['login'] == this.mapOwner)) {
    return true;
  }
  return false;
};

/**
 * Get an array of map objects.
 * @return {angular.$q.Promise} Promise.
 */
app.Mymaps.prototype.getMaps = function() {
  return this.$http_.get(this.mymapsMapsUrl_).then(goog.bind(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {app.MapsResponse} The "mymaps" web service response.
         */
      function(resp) {
        return resp.data;
      }, this), goog.bind(
      function(error) {
        if (error.status == 401) {
          return null;
        }
        return [];
      }, this)
  );
};

/**
 * Load map features
 * @return {angular.$q.Promise} Promise.
 * @private
 */
app.Mymaps.prototype.loadFeatures_ = function() {
  return this.$http_.get(this.mymapsFeaturesUrl_ + this.mapId_).then(goog.bind(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {app.MapsResponse} The "mymaps" web service response.
         */
      function(resp) {
        return resp.data;
      }, this), goog.bind(
      function(error) {
        return [];
      }, this)
  );
};

/**
 * Load map information
 * @return {angular.$q.Promise} Promise.
 * @private
 */
app.Mymaps.prototype.loadMapInformation_ = function() {
  return this.$http_.get(this.mymapsMapInfoUrl_ + this.mapId_).then(goog.bind(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {app.MapsResponse} The "mymaps" web service response.
         */
      function(resp) {
        return resp.data;
      }, this), goog.bind(
      function(error) {
        return [];
      }, this)
  );
};

/**
 * Delete a map
 * @param {ol.Feature} feature the feature to delete.
 * @return {angular.$q.Promise} Promise.
 */
app.Mymaps.prototype.deleteFeature = function(feature) {
  return this.$http_.delete(this.mymapsDeleteFeatureUrl_ +
      feature.get('id')).then(goog.bind(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {app.MapsResponse} The "mymaps" web service response.
         */
      function(resp) {
        return resp.data;
      }, this), goog.bind(
      function(error) {
        return [];
      }, this)
  );
};

/**
 * create a new map
 * @param {string} title the title of the map.
 * @param {string} description a description about the map.
 * @return {angular.$q.Promise} Promise.
 */
app.Mymaps.prototype.createMap = function(title, description) {
  var req = $.param({
    'title': title,
    'description': description
  });
  var config = {
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
  };
  return this.$http_.post(this.mymapsCreateMapUrl_, req, config).then(
      goog.bind(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {app.MapsResponse} The "mymaps" web service response.
         */
      function(resp) {
        return resp.data;
      }, this), goog.bind(
      function(error) {
        return [];
      }, this)
  );
};

/**
 * delete a new map
 * @return {angular.$q.Promise} Promise.
 */
app.Mymaps.prototype.deleteMap = function() {
  return this.$http_.delete(this.mymapsDeleteMapUrl_ + this.mapId_).then(
      goog.bind(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {app.MapsResponse} The "mymaps" web service response.
         */
      function(resp) {
        return resp.data;
      }, this), goog.bind(
      function(error) {
        return [];
      }, this)
  );
};

/**
 * Save the map
 * @param {string} title the title of the map.
 * @param {string} description a description about the map.
 * @return {angular.$q.Promise} Promise.
 */
app.Mymaps.prototype.updateMap = function(title, description) {

  this.mapTitle = title;
  this.mapDescription = description;

  var req = $.param({
    'title': title,
    'description': description
  });
  var config = {
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
  };
  return this.$http_.put(this.mymapsUpdateMapUrl_ + this.mapId_,
      req, config).then(goog.bind(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {app.MapsResponse} The "mymaps" web service response.
         */
      function(resp) {
        return resp.data;
      }, this), goog.bind(
      function(error) {
        return [];
      }, this)
  );
};

/**
 * Save the map
 * @param {ol.Feature} feature the feature to save
 * @param {?ol.proj.Projection} featureProjection
 * @return {angular.$q.Promise} Promise.
 */
app.Mymaps.prototype.saveFeature = function(feature, featureProjection) {
  var encOpt = /** @type {olx.format.ReadOptions} */ ({
    dataProjection: 'EPSG:2169',
    featureProjection: featureProjection
  });
  var req = $.param({
    'feature': (new ol.format.GeoJSON()).writeFeature(feature, encOpt)
  });
  var config = {
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
  };
  return this.$http_.post(this.mymapsSaveFeatureUrl_ + this.mapId_,
      req, config).then(goog.bind(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {app.MapsResponse} The "mymaps" web service response.
         */
      function(resp) {
        return resp.data;
      }, this), goog.bind(
      function(error) {
        return [];
      }, this)
  );
};

/**
 * @return {boolean} return true if a map is selected
 */
app.Mymaps.prototype.isMymapsSelected = function() {
  return !goog.string.isEmpty(this.mapId_);
};

app.module.service('appMymaps', app.Mymaps);
<|endoftext|>


<commit_before>
var sam = require("biojs-vis-sam");
var bw = 10;
var flanking_cache = 50;

var instance = new sam.BAMViewer({
  target : "bam_viewer_1",
  selectionBackgroundColor : '#99FF00',
  dataSet:"./data/minitest.txt",
  base_width: bw,
  flanking_cache: flanking_cache ,
  default_region: "chr_1:1-404",
  height: "500px",
  //width:"1000px",
  display_orientation: true
});
console.log(instance);
instance.load_default_region();

var region_selector = new sam.BAMRegionSelector({
  target :"selected_region",
 });

//Add listeners.
region_selector.add_center_callback(instance);
region_selector.setRegion("gnl|UG|Ta#S58863387:1-404");
instance.add_selected_change_callback(region_selector);
region_selector.add_center_callback(instance);
<commit_msg>Removed blank<commit_after>var sam = require("biojs-vis-sam");
var bw = 10;
var flanking_cache = 50;

var instance = new sam.BAMViewer({
  target : "bam_viewer_1",
  selectionBackgroundColor : '#99FF00',
  dataSet:"./data/minitest.txt",
  base_width: bw,
  flanking_cache: flanking_cache ,
  default_region: "chr_1:1-404",
  height: "500px",
  //width:"1000px",
  display_orientation: true
});
console.log(instance);
instance.load_default_region();

var region_selector = new sam.BAMRegionSelector({
  target :"selected_region",
 });

//Add listeners.
region_selector.add_center_callback(instance);
region_selector.setRegion("gnl|UG|Ta#S58863387:1-404");
instance.add_selected_change_callback(region_selector);
region_selector.add_center_callback(instance);
<|endoftext|>


<commit_before>'use strict';

const generateKey = require('./generate-key');

module.exports = function(mongoose, cache) {
  const exec = mongoose.Query.prototype.exec;

  mongoose.Query.prototype.exec = function(op, callback = function() { }) {
    if (!this.hasOwnProperty('_ttl')) return exec.apply(this, arguments);

    if (typeof op === 'function') {
      callback = op;
      op = null;
    } else if (typeof op === 'string') {
      this.op = op;
    }

    const key = this._key || this.getCacheKey();
    const ttl = this._ttl;
    const isCount = ['count', 'countDocuments', 'estimatedDocumentCount'].includes(this.op);
    const isLean = this._mongooseOptions.lean;
    const model = this.model.modelName;

    return new Promise((resolve, reject) => {
      cache.get(key, (err, cachedResults) => { //eslint-disable-line handle-callback-err
        if (cachedResults != null) {
          if (isCount) {
            callback(null, cachedResults);
            return resolve(cachedResults);
          }

          if (!isLean) {
            const constructor = mongoose.model(model);
            cachedResults = Array.isArray(cachedResults) ?
              cachedResults.map(inflateModel(constructor)) :
              inflateModel(constructor)(cachedResults);
          }

          callback(null, cachedResults);
          return resolve(cachedResults);
        }

        exec
          .call(this)
          .then((results) => {
            cache.set(key, results, ttl, () => {
              callback(null, results);
              return resolve(results);
            });
          })
          .catch((err) => {
            callback(err);
            reject(err);
          });
      });
    });
  };

  mongoose.Query.prototype.cache = function(ttl = 60, customKey = '') {
    if (typeof ttl === 'string') {
      customKey = ttl;
      ttl = 60;
    }

    this._ttl = ttl;
    this._key = customKey;
    return this;
  };

  mongoose.Query.prototype.getCacheKey = function() {
    const key = {
      model: this.model.modelName,
      op: this.op,
      skip: this.options.skip,
      limit: this.options.limit,
      sort: this.options.sort,
      _options: this._mongooseOptions,
      _conditions: this._conditions,
      _fields: this._fields,
      _path: this._path,
      _distinct: this._distinct
    };

    return generateKey(key);
  };
};

function inflateModel(constructor) {
  return (data) => {
    if (constructor.inflate) {
      return constructor.inflate(data);
    } else {
      const model = constructor(data);
      model.$__reset();
      model.isNew = false;
      return model;
    }
  };
}
<commit_msg>Call model.hydrate, inflate does not exist.<commit_after>'use strict';

const generateKey = require('./generate-key');

module.exports = function(mongoose, cache) {
  const exec = mongoose.Query.prototype.exec;

  mongoose.Query.prototype.exec = function(op, callback = function() { }) {
    if (!this.hasOwnProperty('_ttl')) return exec.apply(this, arguments);

    if (typeof op === 'function') {
      callback = op;
      op = null;
    } else if (typeof op === 'string') {
      this.op = op;
    }

    const key = this._key || this.getCacheKey();
    const ttl = this._ttl;
    const isCount = ['count', 'countDocuments', 'estimatedDocumentCount'].includes(this.op);
    const isLean = this._mongooseOptions.lean;
    const model = this.model.modelName;

    return new Promise((resolve, reject) => {
      cache.get(key, (err, cachedResults) => { //eslint-disable-line handle-callback-err
        if (cachedResults != null) {
          if (isCount) {
            callback(null, cachedResults);
            return resolve(cachedResults);
          }

          if (!isLean) {
            const constructor = mongoose.model(model);
            cachedResults = Array.isArray(cachedResults) ?
              cachedResults.map(hydrateModel(constructor)) :
              hydrateModel(constructor)(cachedResults);
          }

          callback(null, cachedResults);
          return resolve(cachedResults);
        }

        exec
          .call(this)
          .then((results) => {
            cache.set(key, results, ttl, () => {
              callback(null, results);
              return resolve(results);
            });
          })
          .catch((err) => {
            callback(err);
            reject(err);
          });
      });
    });
  };

  mongoose.Query.prototype.cache = function(ttl = 60, customKey = '') {
    if (typeof ttl === 'string') {
      customKey = ttl;
      ttl = 60;
    }

    this._ttl = ttl;
    this._key = customKey;
    return this;
  };

  mongoose.Query.prototype.getCacheKey = function() {
    const key = {
      model: this.model.modelName,
      op: this.op,
      skip: this.options.skip,
      limit: this.options.limit,
      sort: this.options.sort,
      _options: this._mongooseOptions,
      _conditions: this._conditions,
      _fields: this._fields,
      _path: this._path,
      _distinct: this._distinct
    };

    return generateKey(key);
  };
};

function hydrateModel(constructor) {
  return (data) => {
    return constructor.hydrate(data);
  };
}
<|endoftext|>