<commit_before>Template.review.onCreated(function () {

})

Template.review.onRendered(function () {
  var tpl = this
  tpl.autorun(function () {
    var tag = Session.get('tag')
    if (!tag) return
    tpl.subscribe('photosByTag', tag._id, function () {
      console.log('GIFs start', Animated_GIF)
      var imgs = document.querySelectorAll('img');
      // change workerPath to point to where Animated_GIF.worker.js is
      var ag = new Animated_GIF({ workerPath: '/Animated_GIF.worker.js' })
      ag.setSize(480, 480)
      for(var i = 0; i < imgs.length; i++) {
        ag.addFrame(imgs[i])
      }
      var animatedImage = document.createElement('img')
      // This is asynchronous, rendered with WebWorkers
      ag.getBase64GIF(function(image) {
        animatedImage.src = image
        document.getElementById('gif').appendChild(animatedImage)
      })
    })
  })
})

Template.review.helpers({
  photos: function () {
    return Photos.find({})
  },
  photoCount: function () {
    return Photos.find({}).count()
  },
  tag: function () {
    return Tags.findOne(Session.get('tag')._id)
  }
})

Template.review.events({
  'click .button-again': function (evt) {
    evt.preventDefault()
    Session.set('page', 'tag')
  }
})

<commit_msg>Wait for photos before gifing<commit_after>Template.review.onCreated(function () {

})

Template.review.onRendered(function () {
  var tpl = this
  tpl.autorun(function () {
    var tag = Session.get('tag')
    if (!tag) return
    tpl.subscribe('photosByTag', tag._id, function () {
      // wait for images
    })
    tpl.photoObserver = Photos.find({}).observe({
      added: function (doc) {
        if (Tracker.Computation.firstRun) return
        var count = Photos.find({}).count()
        var tag = Tags.findOne()
        console.log('photos recieved', count)
        if (!tag || count === 0) return
        if (count === tag.users.length) {
          makeGif()
        }
      }
    })
  })
})

Template.review.onDestroyed(function () {
  tpl.photoObserver.stop()
})

Template.review.helpers({
  photos: function () {
    return Photos.find({})
  },
  photoCount: function () {
    return Photos.find({}).count()
  },
  tag: function () {
    return Tags.findOne(Session.get('tag')._id)
  }
})

Template.review.events({
  'click .button-again': function (evt) {
    evt.preventDefault()
    Session.set('page', 'tag')
  }
})

function makeGif () {
  console.log('GIFs start')
  var imgs = document.querySelectorAll('img');
  // change workerPath to point to where Animated_GIF.worker.js is
  var ag = new Animated_GIF({ workerPath: '/Animated_GIF.worker.js' })
  ag.setSize(480, 480)
  for(var i = 0; i < imgs.length; i++) {
    ag.addFrame(imgs[i])
  }
  var animatedImage = document.createElement('img')
  // This is asynchronous, rendered with WebWorkers
  ag.getBase64GIF(function(image) {
    animatedImage.src = image
    document.getElementById('gif').appendChild(animatedImage)
  })
}<|endoftext|>


<commit_before>var
	path = require('path')
	, util = require('util')
	, mkdirp = require('mkdirp')
	, upnode = require('upnode')
	, creds = require(path.resolve(__dirname, '..', '..', 'lib', 'credentials'))
	, logger = require(path.resolve(__dirname, '..', '..', 'lib', 'logger'))
	, handlers = require('./module/handlers')
	, stream = require('stream')
	, tls = require('tls')
	, net = require('net')
	, fs = require('fs')
	, existsSync = fs.existsSync || path.existsSync
;

function client(opts, app) {

	var
		modules = {}
		, mod = this;
	;

	if(!opts || Object.keys(opts).length === 0) {

		app.log.error("Invalid opts object provided");
		return false;
	}

	if(!creds || typeof creds !== 'function') {

		app.log.error("Invalid credential provider specified");
		return false;
	}

	stream.call(this);

	this.app = app;
	this.opts = opts || undefined;
	this.sendBuffer = [ ];
	this.modules = { };
	this.devices = { };
	this.log = app.log;
	creds.call(this,opts);

	this.node = undefined; // upnode
	this.transport = opts.secure ? tls : net;
	this.parameters = this.getParameters.call(this, opts);
};

util.inherits(client, stream);
handlers(client);

client.prototype.block = require('./block');

client.prototype.getHandlers = function() {

	return {

		revokeCredentials : function revokeCredentials() {

			this.log.info('Invalid token');
			this.app.emit('client::invalidToken', true);

		}.bind(this)
		, execute : function execute(cmd, cb) {

			// console.log("Command request: %s", cmd);
			this.command(cmd);

		}.bind(this)
		, update : function update(to) {

			// update client
		}.bind(this)
		, config : this.moduleHandlers.config.bind(this)
		, install : this.moduleHandlers.install.bind(this)
		, uninstall : this.moduleHandlers.uninstall.bind(this)
	}
};

/**
 * Connect the block to the cloud
 */
client.prototype.connect = function connect() {
	var client = this;
	this.node = upnode(this.getHandlers()).connect(this.parameters);
	this.node.on('reconnect', client.reconnect.bind(client));
	this.node.on('down', client.down.bind(client));
	this.node.on('up', client.up.bind(client));
	this.initialize();
};

/**
 * Initialize the session with the cloud after a connection
 * has been established.
 */
client.prototype.initialize = function initialize() {

	var
		mod = this
		, flushBuffer = function flushBuffer() {

			if(!this.sendBuffer) { this.sendBuffer = [ ]; return; }
			if(this.sendBuffer.length > 0) {

				this.log.debug("Sending buffered commands...");
				this.cloud.data({

					'DEVICE' : this.sendBuffer
				});
				this.sendBuffer = [ ];
			}
			else {

				this.log.debug("No buffered commands to send");
			}
		}
		, initSession = function initSession(cloud) {

			mod.cloud = cloud;

			if(mod.pulse) { clearInterval(mod.pulse); }
			mod.pulse = setInterval(beat.bind(mod), 5000);
			flushBuffer.call(mod);
		}
		, beat = function beat() {

			// this.log.debug("Sending heartbeat");
			this.cloud.heartbeat(JSON.stringify({

				"TIMESTAMP" : (new Date().getTime())
				, "DEVICE" : [ ]

			}));
		}
	;

	this.app.on('client::up', initSession);
};

/**
 * cloud event handlers
 */
client.prototype.up = function up(cloud) {

	try {
		this.app.emit('client::up', cloud);
	} catch(err) {
		this.log.error('An unknown module had the following error:\n\n%s\n',err.stack);
	}

	this.log.info("Client connected to the Ninja Platform");
};

client.prototype.down = function down() {

	this.app.emit('client::down', true);
	this.log.info("Client disconnected from the Ninja Platform");
	if(this.pulse) {

		clearInterval(this.pulse);
	}
};

client.prototype.reconnect = function reconnect() {

	this.app.emit('client::reconnecting', true);

	this.log.info("Connecting to cloud...");
};

/**
 * Generate scoped parameters for dnode connection
 */
client.prototype.getParameters = function getParameters(opts) {

	var
		cloudPort = this.opts.cloudPort
		, cloudHost = this.opts.cloudHost
		, transport = this.transport
	;

	return {

		ping : 10000
		, timeout : 5000
		, reconnect : 2000
		, createStream : function createStream() {

			return transport.connect(cloudPort, cloudHost);
		}
		, block : this.block.bind(this)
	};
};

client.prototype.dataHandler = function dataHandler(device) {

	var self = this;
	return function(data) {

		try {

			self.sendData({

				G : device.G
				, V : device.V
				, D : device.D
				, DA : data
			});
		}
		catch(e) {

			self.log.debug("Error sending data (%s)", self.getGuid(device));
			self.log.error(e);
		}
	}
};

client.prototype.sendData = function sendData(dat) {

	if(!dat) { return false; }

	dat.GUID = this.getGuid(dat);
	dat.TIMESTAMP = (new Date().getTime());
	var msg = { 'DEVICE' : [ dat ] };

	if((this.cloud) && this.cloud.data) {

		return this.cloud.data(msg);
	}

	this.bufferData(msg);
};

client.prototype.sendConfig = function sendConfig(dat) {

	if(!dat) { return false; }

	dat.GUID = this.getGuid(dat);
	dat.TIMESTAMP = (new Date().getTime());
	if((this.cloud) && this.cloud.config) {

		return this.cloud.config(JSON.stringify(dat));
	}
};

client.prototype.bufferData = function bufferData(msg) {

	this.sendBuffer.push(msg);

	if(this.sendBuffer.length > 9) {

		this.sendBuffer.shift();
	}
};

client.prototype.command = function command(dat) {

	var
		self = this
		, data = this.getJSON(dat)
	;

	for(var d = 0, ds = data.DEVICE; d < ds.length; d++) {

		// console.log("Executing: ");
		// console.log(ds[d]);

		var
			guid = ds[d].GUID
			, device
		;
		// delete ds[d].GUID;

		ds[d].G = ds[d].G.toString();

		if((device = this.devices[guid]) && typeof device.write == "function") {

			try {

				this.devices[guid].write(ds[d].DA);
				return true;
			}
			catch(e) {

				this.log.error("error actuating: %s (%s)", guid, err.message);
			}
		}
		else {

			// most likely an arduino device (or a bad module)
			this.log.debug("actuating %s (%s)", guid, ds[d].DA);
			this.app.emit('device::command', ds[d]);
		}
	}
};

client.prototype.getGuid = function getGuid(device) {

	return [

		this.serial
		, device.G
		, device.V
		, device.D

	].join('_');
};

client.prototype.getJSON = function getJSON(dat) {

	try {
		if(dat instanceof Buffer) { dat = dat.toString(); }
		return JSON.parse(dat);
	}
	catch(e) {

		this.log.debug('Invalid JSON: %s', e);
		return false;
	}
};

module.exports = client;
<commit_msg>Added versioning to client startup. Tiny styling fix.<commit_after>var
	path = require('path')
	, util = require('util')
	, mkdirp = require('mkdirp')
	, upnode = require('upnode')
	, handlers = require('./module/handlers')
	, stream = require('stream')
	, tls = require('tls')
	, net = require('net')
	, fs = require('fs')
	, existsSync = fs.existsSync || path.existsSync
	, versioning = require(path.resolve(
		__dirname, '..', '..', 'lib', 'versioning'
	))
	, creds = require(path.resolve(
		__dirname, '..', '..', 'lib', 'credentials'
	))
	, logger = require(path.resolve(
		__dirname, '..', '..', 'lib', 'logger'
	))
;

function client(opts, app) {

	var
		modules = {}
		, mod = this;
	;

	if(!opts || Object.keys(opts).length === 0) {

		app.log.error("Invalid opts object provided");
		return false;
	}

	if(!creds || typeof creds !== 'function') {

		app.log.error("Invalid credential provider specified");
		return false;
	}

	stream.call(this);

	this.app = app;
	this.opts = opts || undefined;
	this.sendBuffer = [ ];
	this.modules = { };
	this.devices = { };
	this.log = app.log;
	creds.call(this, opts);
	versioning.call(this, opts);

	this.node = undefined; // upnode
	this.transport = opts.secure ? tls : net;
	this.parameters = this.getParameters.call(this, opts);

	this.versionClient();
};

util.inherits(client, stream);
handlers(client);

client.prototype.block = require('./block');

client.prototype.getHandlers = function() {

	return {

		revokeCredentials : function revokeCredentials() {

			this.log.info('Invalid token');
			this.app.emit('client::invalidToken', true);

		}.bind(this)
		, execute : function execute(cmd, cb) {

			// console.log("Command request: %s", cmd);
			this.command(cmd);

		}.bind(this)
		, update : function update(to) {

			// update client
		}.bind(this)
		, config : this.moduleHandlers.config.bind(this)
		, install : this.moduleHandlers.install.bind(this)
		, uninstall : this.moduleHandlers.uninstall.bind(this)
	}
};

/**
 * Connect the block to the cloud
 */
client.prototype.connect = function connect() {

	var client = this;
	this.node = upnode(this.getHandlers()).connect(this.parameters);
	this.node.on('reconnect', client.reconnect.bind(client));
	this.node.on('down', client.down.bind(client));
	this.node.on('up', client.up.bind(client));
	this.initialize();
};

/**
 * Initialize the session with the cloud after a connection
 * has been established.
 */
client.prototype.initialize = function initialize() {

	var
		mod = this
		, flushBuffer = function flushBuffer() {

			if(!this.sendBuffer) { this.sendBuffer = [ ]; return; }
			if(this.sendBuffer.length > 0) {

				this.log.debug("Sending buffered commands...");
				this.cloud.data({

					'DEVICE' : this.sendBuffer
				});
				this.sendBuffer = [ ];
			}
			else {

				this.log.debug("No buffered commands to send");
			}
		}
		, initSession = function initSession(cloud) {

			mod.cloud = cloud;

			if(mod.pulse) { clearInterval(mod.pulse); }
			mod.pulse = setInterval(beat.bind(mod), 5000);
			flushBuffer.call(mod);
		}
		, beat = function beat() {

			// this.log.debug("Sending heartbeat");
			this.cloud.heartbeat(JSON.stringify({

				"TIMESTAMP" : (new Date().getTime())
				, "DEVICE" : [ ]

			}));
		}
	;

	this.app.on('client::up', initSession);
};

/**
 * cloud event handlers
 */
client.prototype.up = function up(cloud) {

	try {

		this.app.emit('client::up', cloud);
	} catch(err) {

		this.log.error('An unknown module had the following error:\n\n%s\n', err.stack);
	}

	this.log.info("Client connected to the Ninja Platform");
};

client.prototype.down = function down() {

	this.app.emit('client::down', true);
	this.log.info("Client disconnected from the Ninja Platform");
	if(this.pulse) {

		clearInterval(this.pulse);
	}
};

client.prototype.reconnect = function reconnect() {

	this.app.emit('client::reconnecting', true);

	this.log.info("Connecting to cloud...");
};

/**
 * Generate scoped parameters for dnode connection
 */
client.prototype.getParameters = function getParameters(opts) {

	var
		cloudPort = this.opts.cloudPort
		, cloudHost = this.opts.cloudHost
		, transport = this.transport
	;

	return {

		ping : 10000
		, timeout : 5000
		, reconnect : 2000
		, createStream : function createStream() {

			return transport.connect(cloudPort, cloudHost);
		}
		, block : this.block.bind(this)
	};
};

client.prototype.dataHandler = function dataHandler(device) {

	var self = this;
	return function(data) {

		try {

			self.sendData({

				G : device.G
				, V : device.V
				, D : device.D
				, DA : data
			});
		}
		catch(e) {

			self.log.debug("Error sending data (%s)", self.getGuid(device));
			self.log.error(e);
		}
	}
};

client.prototype.sendData = function sendData(dat) {

	if(!dat) { return false; }

	dat.GUID = this.getGuid(dat);
	dat.TIMESTAMP = (new Date().getTime());
	var msg = { 'DEVICE' : [ dat ] };

	if((this.cloud) && this.cloud.data) {

		return this.cloud.data(msg);
	}

	this.bufferData(msg);
};

client.prototype.sendConfig = function sendConfig(dat) {

	if(!dat) { return false; }

	dat.GUID = this.getGuid(dat);
	dat.TIMESTAMP = (new Date().getTime());
	if((this.cloud) && this.cloud.config) {

		return this.cloud.config(JSON.stringify(dat));
	}
};

client.prototype.bufferData = function bufferData(msg) {

	this.sendBuffer.push(msg);

	if(this.sendBuffer.length > 9) {

		this.sendBuffer.shift();
	}
};

client.prototype.command = function command(dat) {

	var
		self = this
		, data = this.getJSON(dat)
	;

	for(var d = 0, ds = data.DEVICE; d < ds.length; d++) {

		// console.log("Executing: ");
		// console.log(ds[d]);

		var
			guid = ds[d].GUID
			, device
		;
		// delete ds[d].GUID;

		ds[d].G = ds[d].G.toString();

		if((device = this.devices[guid]) && typeof device.write == "function") {

			try {

				this.devices[guid].write(ds[d].DA);
				return true;
			}
			catch(e) {

				this.log.error("error actuating: %s (%s)", guid, err.message);
			}
		}
		else {

			// most likely an arduino device (or a bad module)
			this.log.debug("actuating %s (%s)", guid, ds[d].DA);
			this.app.emit('device::command', ds[d]);
		}
	}
};

client.prototype.getGuid = function getGuid(device) {

	return [

		this.serial
		, device.G
		, device.V
		, device.D

	].join('_');
};

client.prototype.getJSON = function getJSON(dat) {

	try {
		if(dat instanceof Buffer) { dat = dat.toString(); }
		return JSON.parse(dat);
	}
	catch(e) {

		this.log.debug('Invalid JSON: %s', e);
		return false;
	}
};

module.exports = client;
<|endoftext|>


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

import 'babel-polyfill';
import _ from 'lodash';
import xray from 'x-ray';

import superagent from 'superagent';
import superagentRetry from 'superagent-retry';
const request = superagentRetry(superagent);
superagentRetry.retries.push(function internalServerError(error) {
  return error && error.status === 500;
});

import rdf from 'rdf-ext';
import N3Parser from 'rdf-parser-n3';
import RdfXmlParser from 'rdf-parser-rdfxml';
rdf.parsers = new rdf.Parsers({
  'text/n3': N3Parser,
  'text/turtle': N3Parser,
  'application/n-triples': N3Parser,
  'application/rdf+xml': RdfXmlParser,
});

class Scraper {
  constructor() {
    this.countries = [];
    this.scraper = xray();
  }

  /**
  * _getCountryList() scrapes names and codes of countries in ISO 3166-1 from Wikipedia.
  *
  * @access private
  * @return {Promise}
  */
  _getCountryList() {
    return new Promise((resolve, reject) => {
      this.scraper('https://en.wikipedia.org/wiki/ISO_3166-1',
        'h3:has(#Officially_assigned_code_elements) ~ table.wikitable:first-of-type > tr',
        [{
          englishShortName: 'td:nth-child(1)',
          isoTwoLetterCountryCode: 'td:nth-child(2)',
          isoThreeLetterCountryCode: 'td:nth-child(3)',
          isoThreeDigitCountryCode: 'td:nth-child(4)',
          isoCountrySubdivisionCode: 'td:nth-child(5)',
          _wikipediaUri: 'td:nth-child(1) a@href',
        }])((error, data) => {
          if (error) {
            reject(error);
          } else {
            resolve(data);
          }
        });
    });
  }

  /**
  * _getWikiIds() scrapes the Wikipedia canonical slug and the Wikidata ID of each country.
  *
  * @access private
  * @param {Array} countries
  * @return {Promise} a promise that waits for all promises for countries to be fulfilled
  */
  _getWikiIds(countries) {
    const promises = [];

    countries.map((country) => {
      promises.push(new Promise((resolve, reject) => {
        const scraper = xray();
        scraper(country._wikipediaUri, {
          wikipediaSlug: 'link[rel="canonical"]@href',
          wikidataId: '#t-wikibase > a@href',
        })((error, data) => {
          if (error) {
            reject(error);
          } else {
            const newCountry = Object.assign({}, country);
            delete newCountry._wikipediaUri;

            const wikipediaSlug = _.trimRight(data.wikipediaSlug, '/');
            newCountry.wikipediaSlug = wikipediaSlug.substring(wikipediaSlug.lastIndexOf('/') + 1);

            const wikidataId = _.trimRight(data.wikidataId, '/');
            newCountry.wikidataId = wikidataId.substring(wikidataId.lastIndexOf('/') + 1);

            resolve(newCountry);
          }
        });
      }));
    });

    return Promise.all(promises);
  }

  /**
  * _getGeoNamesIds() scrapes the GeoNames ID of each country.
  *
  * @access private
  * @param {Array} countries
  * @return {Promise} a promise that waits for all promises for countries to be fulfilled
  */
  _getGeoNamesIds(countries) {
    const promises = [];

    countries.map((country) => {
      promises.push(new Promise((resolve, reject) => {
        // TODO: It takes too long so we need to use the SPARQL endpoint instead to only select sameAs triples.
        const dbpediaUri = `http://wikidata.dbpedia.org/resource/${country.wikidataId}`;

        request.get(dbpediaUri)
          .accept('text/turtle, text/n3, application/rdf+xml, application/n-triples')
          .buffer(true)
          .retry(5)
          .end((error, response) => {
            if (error) {
              reject(error);
            } else {
              rdf.parsers.parse(response.type, response.text).then((graph) => {
                const filtered = graph.filter((triple) => {
                  return triple.subject.equals(dbpediaUri) &&
                    triple.predicate.equals(rdf.resolve('owl:sameAs')) &&
                    triple.object.toString().match(/http:\/\/sws\.geonames\.org/i);
                }).toArray();

                if (!filtered.length) {
                  throw new Error('Cannot find a GeoNames ID for this country');
                }

                const newCountry = Object.assign({}, country);

                const geoNamesUrl = _.trimRight(filtered[0].object.toString(), '/');
                newCountry.geoNamesId = geoNamesUrl.substring(geoNamesUrl.lastIndexOf('/') + 1);

                resolve(newCountry);
              }).catch((exception) => {
                reject(exception);
              });
            }
          });
      }));
    });

    return Promise.all(promises);
  }

  /**
  * getCountries() scrapes data about countries in ISO 3166-1.
  *
  * @access public
  * @return {Promise}
  */
  getCountries() {
    if (!this.countries.length) {
      return this._getCountryList()
        .then((countries) => {
          return this._getWikiIds(countries);
        })
        .then((countries) => {
          return this._getGeoNamesIds(countries);
        })
        .then((countries) => {
          this.countries = countries;
          return this.countries;
        });
    }

    return Promise.resolve(this.countries);
  }
}

export default Scraper;
<commit_msg>[assets/data] Revised a message for no GeoName error<commit_after>#!/usr/bin/env node

import 'babel-polyfill';
import _ from 'lodash';
import xray from 'x-ray';

import superagent from 'superagent';
import superagentRetry from 'superagent-retry';
const request = superagentRetry(superagent);
superagentRetry.retries.push(function internalServerError(error) {
  return error && error.status === 500;
});

import rdf from 'rdf-ext';
import N3Parser from 'rdf-parser-n3';
import RdfXmlParser from 'rdf-parser-rdfxml';
rdf.parsers = new rdf.Parsers({
  'text/n3': N3Parser,
  'text/turtle': N3Parser,
  'application/n-triples': N3Parser,
  'application/rdf+xml': RdfXmlParser,
});

class Scraper {
  constructor() {
    this.countries = [];
    this.scraper = xray();
  }

  /**
  * _getCountryList() scrapes names and codes of countries in ISO 3166-1 from Wikipedia.
  *
  * @access private
  * @return {Promise}
  */
  _getCountryList() {
    return new Promise((resolve, reject) => {
      this.scraper('https://en.wikipedia.org/wiki/ISO_3166-1',
        'h3:has(#Officially_assigned_code_elements) ~ table.wikitable:first-of-type > tr',
        [{
          englishShortName: 'td:nth-child(1)',
          isoTwoLetterCountryCode: 'td:nth-child(2)',
          isoThreeLetterCountryCode: 'td:nth-child(3)',
          isoThreeDigitCountryCode: 'td:nth-child(4)',
          isoCountrySubdivisionCode: 'td:nth-child(5)',
          _wikipediaUri: 'td:nth-child(1) a@href',
        }])((error, data) => {
          if (error) {
            reject(error);
          } else {
            resolve(data);
          }
        });
    });
  }

  /**
  * _getWikiIds() scrapes the Wikipedia canonical slug and the Wikidata ID of each country.
  *
  * @access private
  * @param {Array} countries
  * @return {Promise} a promise that waits for all promises for countries to be fulfilled
  */
  _getWikiIds(countries) {
    const promises = [];

    countries.map((country) => {
      promises.push(new Promise((resolve, reject) => {
        const scraper = xray();
        scraper(country._wikipediaUri, {
          wikipediaSlug: 'link[rel="canonical"]@href',
          wikidataId: '#t-wikibase > a@href',
        })((error, data) => {
          if (error) {
            reject(error);
          } else {
            const newCountry = Object.assign({}, country);
            delete newCountry._wikipediaUri;

            const wikipediaSlug = _.trimRight(data.wikipediaSlug, '/');
            newCountry.wikipediaSlug = wikipediaSlug.substring(wikipediaSlug.lastIndexOf('/') + 1);

            const wikidataId = _.trimRight(data.wikidataId, '/');
            newCountry.wikidataId = wikidataId.substring(wikidataId.lastIndexOf('/') + 1);

            resolve(newCountry);
          }
        });
      }));
    });

    return Promise.all(promises);
  }

  /**
  * _getGeoNamesIds() scrapes the GeoNames ID of each country.
  *
  * @access private
  * @param {Array} countries
  * @return {Promise} a promise that waits for all promises for countries to be fulfilled
  */
  _getGeoNamesIds(countries) {
    const promises = [];

    countries.map((country) => {
      promises.push(new Promise((resolve, reject) => {
        // TODO: It takes too long so we need to use the SPARQL endpoint instead to only select sameAs triples.
        const dbpediaUri = `http://wikidata.dbpedia.org/resource/${country.wikidataId}`;

        request.get(dbpediaUri)
          .accept('text/turtle, text/n3, application/rdf+xml, application/n-triples')
          .buffer(true)
          .retry(5)
          .end((error, response) => {
            if (error) {
              reject(error);
            } else {
              rdf.parsers.parse(response.type, response.text).then((graph) => {
                const filtered = graph.filter((triple) => {
                  return triple.subject.equals(dbpediaUri) &&
                    triple.predicate.equals(rdf.resolve('owl:sameAs')) &&
                    triple.object.toString().match(/http:\/\/sws\.geonames\.org/i);
                }).toArray();

                if (!filtered.length) {
                  throw new Error(`Cannot find a GeoNames ID for this country: ${country.englishShortName}`);
                }

                const newCountry = Object.assign({}, country);

                const geoNamesUrl = _.trimRight(filtered[0].object.toString(), '/');
                newCountry.geoNamesId = geoNamesUrl.substring(geoNamesUrl.lastIndexOf('/') + 1);

                resolve(newCountry);
              }).catch((exception) => {
                reject(exception);
              });
            }
          });
      }));
    });

    return Promise.all(promises);
  }

  /**
  * getCountries() scrapes data about countries in ISO 3166-1.
  *
  * @access public
  * @return {Promise}
  */
  getCountries() {
    if (!this.countries.length) {
      return this._getCountryList()
        .then((countries) => {
          return this._getWikiIds(countries);
        })
        .then((countries) => {
          return this._getGeoNamesIds(countries);
        })
        .then((countries) => {
          this.countries = countries;
          return this.countries;
        });
    }

    return Promise.resolve(this.countries);
  }
}

export default Scraper;
<|endoftext|>


<commit_before>(function() {
  'use strict';
  angular.module('app.components').controller('MapController', MapController);
  MapController.$inject = ['$scope', '$state', '$timeout', '$location', 'entitiesLayers', 'Overlays', 'asset', '$mdDialog', 'leafletData', 'mapUtils', 'markerUtils', 'alert', 'animation'];

  function MapController($scope, $state, $timeout, $location, entitiesLayers, Overlays, asset, $mdDialog, leafletData, mapUtils, markerUtils, alert, animation) {
    var vm = this;
    var updateType;
    var mapMoved = false;
    var entityLoaded = false;
    var mapClicked = false;

    vm.tiles = mapUtils.getBaseLayers().oc.url;

    vm.controls = {};

    vm.layers = {
      baselayers: mapUtils.getBaseLayers(),
      overlays: new Overlays(entitiesLayers, 'Asset Types')
    };

    vm.center = {
      lat: 48,
      lng: 18.5,
      zoom: 4
    };

    vm.defaults = {
      dragging: true,
      touchZoom: true,
      scrollWheelZoom: true,
      doubleClickZoom: true,
      boxZoom: true,
      layers: {
        visible: true,
        position: 'topleft',
        collapsed: false
      }
    };

    vm.events = {
      map: {
        enable: ['dragend', 'zoomend', 'moveend', 'popupopen', 'popupclose', 'mousedown', 'dblclick', 'click', 'touchstart', 'mouseup'],
        logic: 'emit'
      }
    };

    animation.viewLoaded();

    leafletData.getMap().then(function() {
      vm.controls.minimap = {
        type: 'minimap',
        layer: mapUtils.getBaseLayers().oc,
        toggleDisplay: true,
        minimized: true,
        zoomLevelOffset: -4
      };
    });

    $scope.$on('goToLocation', function(event, data) {
      goToLocation(event, data);
    });

    $scope.$on('centerUrlHash', function(event, centerHash) {
        $location.search({ map: centerHash });
    });

    $scope.changeLocation = function(centerHash) {
        $location.search({ map: centerHash });
    };

    $scope.$watch('vm.center.zoom', function() {
      updateMarkers();
    });

    $scope.$watch('vm.bounds', function() {
      updateMarkers();
    });

    $scope.$on('centerMap', function(event, data) {
      vm.center = data.center;
    });

    $scope.$on('entityLoaded', function(event, data) {

      vm.entityLoading = false;
      vm.center = {
        lat: parseFloat(data.lat),
        lng: parseFloat(data.lng),
        zoom: 20
      };

      updateMarkers();

      $timeout(function(currentMarker) {
        leafletData.getLayers('organicityMap')
          .then(function(layers) {
            var overlays = layers.overlays;
            for (var o in overlays) {
              var currentMarker = _.find(overlays[o].getLayers(), function(marker) {
                if (data.id === marker.feature.properties.id) {
                  console.log(marker);
                  marker.focus = true;
                  marker.openPopup();
                  return marker;
                }
              });
            }
            entityLoaded = true;
          }, function(error) {
            console.log(error);
          });
      }, 250);
    });

    function updateMarkers() {
      if (vm.center.zoom >= 8) {
        safeFunction(updateAreaMarkers, 'lastMarkersUpdate', 1500);
      } else {
        safeFunction(updateClusters, 'lastClustersUpdate', 1500);
      }

      if (vm.controls.minimap) {
        vm.controls.minimap.toggleDisplay = (vm.center.zoom >= 8) ? true : false;
      }

    }

    function safeFunction(fn, time, interval) {
      if (!vm[time] || new Date().getTime() - vm[time] > interval) {
        fn();
        vm[time] = new Date().getTime();
      }
    }

    function updateAreaMarkers() {
      vm.center.radius = (vm.bounds) ? getDistanceInKm(vm.center, vm.bounds.southWest) : 10;

      var params = {
        lat: vm.center.lat,
        long: vm.center.lng,
        radius: vm.center.radius,
        km: 'true',
        per: 500
      };

      asset.getGeoJSON(params).then(function(data) {
        asset.setAllEntities(data);
        vm.layers = {
          baselayers: mapUtils.getBaseLayers(),
          overlays: new Overlays(JSON.parse(JSON.stringify(data)), 'Asset Types')
        };
      }, function(error) {
        console.log(error);
      });
    }

    function updateClusters() {
      // This is tmp.
      var clusters = asset.getAllClusters();
      if (clusters) {
//        console.warn(clusters);
        vm.layers = {
          baselayers: mapUtils.getBaseLayers(),
          overlays: new Overlays(clusters, 'Asset Types')
        };
      } else {
        asset.getClusterGeoJSON().then(function(data) {
          console.warn(data);
          asset.setAllClusters(data);
          vm.layers = {
            baselayers: mapUtils.getBaseLayers(),
            overlays: new Overlays(data, 'Asset Types')
          };
        }, function(error) {
          console.log(error);
        });
      }

    }

    function goToLocation(event, data){
      vm.center.lat = data.lat;
      vm.center.lng = data.lng;
      vm.center.zoom = getZoomLevel(data);
    }

    function getZoomLevel(data) {
      console.log(data);
      var LAYER_ZOOMS = [{name:'venue', zoom:18}, {name:'address', zoom:18}, {name:'neighbourhood', zoom:13}, {name:'locality', zoom:13}, {name:'localadmin', zoom:10}, {name:'county', zoom:10}, {name:'region', zoom:8}, {name:'country', zoom:7}, {name:'coarse', zoom:7}];
      if (!data.layer) {
        return 10;
      }
      return _.find(LAYER_ZOOMS, function(layer) {
        return layer.name === data.layer;
      }).zoom;
    }

    function getDistanceInKm(pointA, pointB) {
      var R = 6378.1; // Radius of the earth in km
      var dLat = deg2rad(pointB.lat - pointA.lat); // deg2rad below
      var dLng = deg2rad(pointB.lng - pointA.lng);
      var a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(deg2rad(pointA.lat)) * Math.cos(deg2rad(pointB.lat)) *
        Math.sin(dLng / 2) * Math.sin(dLng / 2);
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      var d = R * c; // Distance in km
      return d;
    }

    function deg2rad(deg) {
      return deg * (Math.PI / 180);
    }

  }
})();
<commit_msg>Fix leaflet duplicate error<commit_after>(function() {
  'use strict';
  angular.module('app.components').controller('MapController', MapController);
  MapController.$inject = ['$scope', '$state', '$timeout', '$location', 'entitiesLayers', 'Overlays', 'asset', '$mdDialog', 'leafletData', 'mapUtils', 'markerUtils', 'alert', 'animation'];

  function MapController($scope, $state, $timeout, $location, entitiesLayers, Overlays, asset, $mdDialog, leafletData, mapUtils, markerUtils, alert, animation) {
    var vm = this;
    var updateType;
    var mapMoved = false;
    var entityLoaded = false;
    var mapClicked = false;

    vm.tiles = mapUtils.getBaseLayers().oc.url;

    vm.controls = {};

    vm.layers = {
      baselayers: mapUtils.getBaseLayers(),
      overlays: new Overlays(entitiesLayers, 'Asset Types')
    };

    vm.center = {
      lat: 48,
      lng: 18.5,
      zoom: 4
    };

    vm.defaults = {
      dragging: true,
      touchZoom: true,
      scrollWheelZoom: true,
      doubleClickZoom: true,
      boxZoom: true,
      layers: {
        visible: true,
        position: 'topleft',
        collapsed: false
      }
    };

    vm.events = {
      map: {
        enable: ['dragend', 'zoomend', 'moveend', 'popupopen', 'popupclose', 'mousedown', 'dblclick', 'click', 'touchstart', 'mouseup'],
        logic: 'emit'
      }
    };

    animation.viewLoaded();

    leafletData.getMap("organicityMap").then(function() {
      vm.controls.minimap = {
        type: 'minimap',
        layer: mapUtils.getBaseLayers().oc,
        toggleDisplay: true,
        minimized: true,
        zoomLevelOffset: -4
      };
    });

    $scope.$on('goToLocation', function(event, data) {
      goToLocation(event, data);
    });

    $scope.$on('centerUrlHash', function(event, centerHash) {
        $location.search({ map: centerHash });
    });

    $scope.changeLocation = function(centerHash) {
        $location.search({ map: centerHash });
    };

    $scope.$watch('vm.center.zoom', function() {
      updateMarkers();
    });

    $scope.$watch('vm.bounds', function() {
      updateMarkers();
    });

    $scope.$on('centerMap', function(event, data) {
      vm.center = data.center;
    });

    $scope.$on('entityLoaded', function(event, data) {

      vm.entityLoading = false;
      vm.center = {
        lat: parseFloat(data.lat),
        lng: parseFloat(data.lng),
        zoom: 20
      };

      updateMarkers();

      $timeout(function(currentMarker) {
        leafletData.getLayers('organicityMap')
          .then(function(layers) {
            var overlays = layers.overlays;
            for (var o in overlays) {
              var currentMarker = _.find(overlays[o].getLayers(), function(marker) {
                if (data.id === marker.feature.properties.id) {
                  console.log(marker);
                  marker.focus = true;
                  marker.openPopup();
                  return marker;
                }
              });
            }
            entityLoaded = true;
          }, function(error) {
            console.log(error);
          });
      }, 250);
    });

    function updateMarkers() {
      if (vm.center.zoom >= 8) {
        safeFunction(updateAreaMarkers, 'lastMarkersUpdate', 1500);
      } else {
        safeFunction(updateClusters, 'lastClustersUpdate', 1500);
      }

      if (vm.controls.minimap) {
        vm.controls.minimap.toggleDisplay = (vm.center.zoom >= 8) ? true : false;
      }

    }

    function safeFunction(fn, time, interval) {
      if (!vm[time] || new Date().getTime() - vm[time] > interval) {
        fn();
        vm[time] = new Date().getTime();
      }
    }

    function updateAreaMarkers() {
      vm.center.radius = (vm.bounds) ? getDistanceInKm(vm.center, vm.bounds.southWest) : 10;

      var params = {
        lat: vm.center.lat,
        long: vm.center.lng,
        radius: vm.center.radius,
        km: 'true',
        per: 500
      };

      asset.getGeoJSON(params).then(function(data) {
        asset.setAllEntities(data);
        vm.layers = {
          baselayers: mapUtils.getBaseLayers(),
          overlays: new Overlays(JSON.parse(JSON.stringify(data)), 'Asset Types')
        };
      }, function(error) {
        console.log(error);
      });
    }

    function updateClusters() {
      // This is tmp.
      var clusters = asset.getAllClusters();
      if (clusters) {
//        console.warn(clusters);
        vm.layers = {
          baselayers: mapUtils.getBaseLayers(),
          overlays: new Overlays(clusters, 'Asset Types')
        };
      } else {
        asset.getClusterGeoJSON().then(function(data) {
          console.warn(data);
          asset.setAllClusters(data);
          vm.layers = {
            baselayers: mapUtils.getBaseLayers(),
            overlays: new Overlays(data, 'Asset Types')
          };
        }, function(error) {
          console.log(error);
        });
      }

    }

    function goToLocation(event, data){
      vm.center.lat = data.lat;
      vm.center.lng = data.lng;
      vm.center.zoom = getZoomLevel(data);
    }

    function getZoomLevel(data) {
      console.log(data);
      var LAYER_ZOOMS = [{name:'venue', zoom:18}, {name:'address', zoom:18}, {name:'neighbourhood', zoom:13}, {name:'locality', zoom:13}, {name:'localadmin', zoom:10}, {name:'county', zoom:10}, {name:'region', zoom:8}, {name:'country', zoom:7}, {name:'coarse', zoom:7}];
      if (!data.layer) {
        return 10;
      }
      return _.find(LAYER_ZOOMS, function(layer) {
        return layer.name === data.layer;
      }).zoom;
    }

    function getDistanceInKm(pointA, pointB) {
      var R = 6378.1; // Radius of the earth in km
      var dLat = deg2rad(pointB.lat - pointA.lat); // deg2rad below
      var dLng = deg2rad(pointB.lng - pointA.lng);
      var a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(deg2rad(pointA.lat)) * Math.cos(deg2rad(pointB.lat)) *
        Math.sin(dLng / 2) * Math.sin(dLng / 2);
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      var d = R * c; // Distance in km
      return d;
    }

    function deg2rad(deg) {
      return deg * (Math.PI / 180);
    }

  }
})();
<|endoftext|>


<commit_before>/*!
 * daily-glry v0.3.1 (https://github.com/omichelsen/daily-glry)
 * Copyright 2014 Ole Michelsen <ole@michelsen.dk>
 * Licensed under MIT
 */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['Glry', 'moment'], factory);
    } else {
        root.DailyGlry = factory(root.Glry, root.moment);
    }
}(this, function (Glry, moment) {
    'use strict';

    function DailyGlry(options) {
        var options = Glry.prototype.extend({
            target: '#figure',
            host: null,
            enableHash: true,
            hashFormat: 'YYYY-MM-DD',
            nameFormat: 'YYYY/YYYYMMDD',
            extension: '.png',
            onOutOfRange: false,
            load: load
        }, options);

        options.dateMin = options.dateMin ? moment(options.dateMin) : moment();
        options.dateMax = options.dateMax ? moment(options.dateMax) : moment();

        var glry = new Glry(options);

        window.addEventListener('hashchange', glry.loadImage.bind(this));
        window.addEventListener('shake', glry.loadImage.bind(this, 'random'));
        window.addEventListener('keyup', handleKeyboard);

        var elm = typeof options.target === 'object' ? options.target : document.querySelector(options.target);
        elm.querySelector('.rand').addEventListener('tap', handleNavigationClick.bind(this, 'random'));
        elm.querySelector('.today').addEventListener('tap', handleNavigationClick.bind(this, 'today'));
        elm.querySelector('.share').addEventListener('tap', function (e) {
            var date = getStripDate().format(options.hashFormat);
            var title = encodeURIComponent(document.title);
            window.location.href = 'mailto:?subject=Shared ' + title + ' Strip: ' + date + '&body=See this funny strip: ' + window.location.href;
        });

        function load(direction) {
            var date;

            switch (direction) {
            case 'left':
                date = getStripDate().add(-1, 'days');
                break;
            case 'right':
                date = getStripDate().add(1, 'days');
                break;
            case 'random':
                date = getRandomDate();
                break;
            case 'today':
                date = options.dateMax;
                break;
            default:
                date = getStripDate();
                break;
            }

            if (date < options.dateMin || date > options.dateMax) {
                if (options.onOutOfRange !== false) options.onOutOfRange();
                return false;
            }

            if (options.enableHash)
                window.location.hash = date.format(options.hashFormat);

            return getImageUrl(date);
        }

        function handleKeyboard(e) {
            e.preventDefault();
            if (e.keyCode === 82) {
                glry.loadImage('random');
            } else if (e.keyCode === 84) {
                glry.loadImage('today');
            }
        }

        function handleNavigationClick(direction, e) {
            e.stopPropagation();
            glry.loadImage(direction);
        }

        function getStripDate() {
            return options.enableHash && getDateFromString(window.location.hash) || options.dateMax;
        }

        function getDateFromString(string) {
            if (!string) return null;
            return moment(string, options.hashFormat);
        }

        function getRandomDate() {
            var min = options.dateMin.valueOf(),
                max = options.dateMax.valueOf();
            return moment(new Date(Math.random() * (max - min) + min));
        }

        function getImageUrl(date) {
            return options.host + date.format(options.nameFormat) + options.extension;
        }
    }

    return DailyGlry;

}));
<commit_msg>Formatting.<commit_after>/*!
 * daily-glry v0.3.1 (https://github.com/omichelsen/daily-glry)
 * Copyright 2014 Ole Michelsen <ole@michelsen.dk>
 * Licensed under MIT
 */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['Glry', 'moment'], factory);
    } else {
        root.DailyGlry = factory(root.Glry, root.moment);
    }
}(this, function (Glry, moment) {
    'use strict';

    function DailyGlry(options) {
        var options = Glry.prototype.extend({
            target: '#figure',
            host: null,
            enableHash: true,
            hashFormat: 'YYYY-MM-DD',
            nameFormat: 'YYYY/YYYYMMDD',
            extension: '.png',
            onOutOfRange: false,
            load: load
        }, options);

        options.dateMin = options.dateMin ? moment(options.dateMin) : moment();
        options.dateMax = options.dateMax ? moment(options.dateMax) : moment();

        var glry = new Glry(options);

        window.addEventListener('hashchange', glry.loadImage.bind(this));
        window.addEventListener('shake', glry.loadImage.bind(this, 'random'));
        window.addEventListener('keyup', handleKeyboard);

        var elm = typeof options.target === 'object' ? options.target : document.querySelector(options.target);
        elm.querySelector('.rand').addEventListener('tap', handleNavigationClick.bind(this, 'random'));
        elm.querySelector('.today').addEventListener('tap', handleNavigationClick.bind(this, 'today'));
        elm.querySelector('.share').addEventListener('tap', function (e) {
            var date = getStripDate().format(options.hashFormat);
            var title = encodeURIComponent(document.title);
            window.location.href = 'mailto:?subject=Shared ' + title + ' Strip: ' + date + '&body=See this funny strip: ' + window.location.href;
        });

        function load(direction) {
            var date;

            switch (direction) {
                case 'left':    date = getStripDate().add(-1, 'days'); break;
                case 'right':   date = getStripDate().add(1, 'days'); break;
                case 'random':  date = getRandomDate(); break;
                case 'today':   date = options.dateMax; break;
                default:        date = getStripDate(); break;
            }

            if (date < options.dateMin || date > options.dateMax) {
                if (options.onOutOfRange !== false) options.onOutOfRange();
                return false;
            }

            if (options.enableHash)
                window.location.hash = date.format(options.hashFormat);

            return getImageUrl(date);
        }

        function handleKeyboard(e) {
            e.preventDefault();
            if (e.keyCode === 82) {
                glry.loadImage('random');
            } else if (e.keyCode === 84) {
                glry.loadImage('today');
            }
        }

        function handleNavigationClick(direction, e) {
            e.stopPropagation();
            glry.loadImage(direction);
        }

        function getStripDate() {
            return options.enableHash && getDateFromString(window.location.hash) || options.dateMax;
        }

        function getDateFromString(string) {
            if (!string) return null;
            return moment(string, options.hashFormat);
        }

        function getRandomDate() {
            var min = options.dateMin.valueOf(),
                max = options.dateMax.valueOf();
            return moment(new Date(Math.random() * (max - min) + min));
        }

        function getImageUrl(date) {
            return options.host + date.format(options.nameFormat) + options.extension;
        }
    }

    return DailyGlry;

}));
<|endoftext|>


<commit_before>var debug     = require('debug')('metalsmith-pandoc');
var which     = require('which');
var install   = require('system-install')();

// Make sure pandoc is installed
which('pandoc', function(err, cmd){
  if (err) {
    // TODO: ask user to accept installation via system package manager.
    console.error('metalsmith-pandoc: ERROR, pandoc not found.');
    console.error('Install pandoc on your system with `' + install + ' pandoc`.');
    process.exit(1);
  }
  debug('Found pandoc: ' + cmd)
});<commit_msg>Removed dependency on pandoc-bin and clean up of postinstall check<commit_after>var debug     = require('debug')('metalsmith-pandoc');
var which     = require('which');
var install   = require('system-install')();

// Make sure pandoc is installed
which('pandoc', function(err, cmd){
  if (err) {
    // TODO: ask user to accept installation via system package manager.
    console.error('metalsmith-pandoc: ERROR, pandoc not found.');
    console.error('Install pandoc on your system with `' + install + ' pandoc`.');
    process.exit(1);
  }
  debug('Found pandoc: ' + cmd)
});
<|endoftext|>


<commit_before>angular.module('MyApp')
  .controller('AddCtrl', ['$rootScope', '$scope', '$alert', '$location', '$window', function($rootScope, $scope, $alert, $location, $window) {
    $scope.addShow = function() {
      $http.post('/api/shows', $scope.showName)
        .success(function() {
          $location.path('/');
          $alert({
            content: 'TV show has been added.',
            placement: 'top-right',
            type: 'success',
            duration: 3
          });
        });
    };
  }]);<commit_msg>Fixed addShow controller $http params<commit_after>angular.module('MyApp')
  .controller('AddCtrl', ['$scope', '$alert', '$location', '$http', function($scope, $alert, $location, $http) {
    $scope.addShow = function() {
      $http.post('/api/shows', { showName: $scope.showName })
        .success(function() {
          $alert({
            content: 'TV show has been added.',
            placement: 'top-right',
            type: 'success',
            duration: 3
          });
        })
    };
  }]);<|endoftext|>


<commit_before>(function( $, undefined ) {
    $.KBWidget({
        name: "KBaseLitWidget",
        parent: "kbaseWidget",
        version: "1.0.0",

        options: {
            genomeID: null,
            workspaceID: null,
			kbCache: null,
            loadingImage: "../../widgets/images/ajax-loader.gif",
            isInCard: false,
			width: 600,
			height: 700,
        },

		init: function(options) {
			this._super(options);

			if (this.options.row === null) {
				//throw an error
				return;
			}
            return this.render();
		},

		addInfoRow: function(a, b) {
            return "
" + a + "	" + b + "
";
        },

		xmlToJson: function(xml) {
				self = this;
				// Create the return object
				var obj = {};

				if (xml.nodeType == 1) { // element
					// do attributes
					if (xml.attributes.length > 0) {
					obj["@attributes"] = {};
						for (var j = 0; j < xml.attributes.length; j++) {
							var attribute = xml.attributes.item(j);
							obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
						}
					}
				} else if (xml.nodeType == 3) { // text
					obj = xml.nodeValue;
				}

				// do children
				if (xml.hasChildNodes()) {
					for(var i = 0; i < xml.childNodes.length; i++) {
						var item = xml.childNodes.item(i);
						var nodeName = item.nodeName;
						if (typeof(obj[nodeName]) == "undefined") {
							obj[nodeName] = self.xmlToJson(item);
						} else {
							if (typeof(obj[nodeName].push) == "undefined") {
								var old = obj[nodeName];
								obj[nodeName] = [];
								obj[nodeName].push(old);
							}
							obj[nodeName].push(self.xmlToJson(item));
						}
					}
				}
				return obj;
		},

		render: function(options) {

			self = this;

			var lit = self.options.literature

			var resultsDiv = $("
").append('
')
			var searchBarDiv = $("
").append("<input type='text' id='lit-query-box'>")
			var searchBarButton = $("<input type='button' id='lit-search-button' value='Update Search'>")
									.on("click",function() {
										lit = $('#lit-query-box').val()
										tableInput = []
										litDataTable.fnDestroy()
										populateSearch(lit)
									})

			var tableInput = []
			var litDataTable;

			self.$elem.append(searchBarDiv.append(searchBarButton)).append(resultsDiv)

			$('#lit-query-box').val(lit)
			$('#lit-query-box').css({"width":"300px"})
			populateSearch(lit)

			function parseLitSearchDataTable(query) {
				var tableInputRow = {}

				$.ajax({
					async: false,
					url: query,
					type: 'GET',
					success:
					function(data) {
						var htmlJson = self.xmlToJson(data)
						var litInfo = htmlJson.eSummaryResult[1].DocSum.Item
						// if (data[0].length == 0) {
								// self.$elem.append("
There are no other data objects (you can access) that reference this object.");
						// } else {
						for (i=0;i<litInfo.length;i++) {
							if ("#text" in litInfo[i]) {
								if (litInfo[i]["@attributes"].Name == "Source") tableInputRow["jo"] = litInfo[i]["#text"]
								if (litInfo[i]["@attributes"].Name == "AuthorList") {
									if ($.isArray(litInfo[i].Item)) {
										var authors = ""
										for (j=0;j<litInfo[i].Item.length;j++) {
											authors+=litInfo[i].Item[j]["#text"]
											if (j!=litInfo[i].Item.length-1) authors+=", "
										}
										tableInputRow["au"] = authors
									}
									else {tableInputRow["au"] = litInfo[i].Item["#text"]}
								}
								if (litInfo[i]["@attributes"].Name == "Title") {
									var pubmedLink = "http://www.ncbi.nlm.nih.gov/pubmed/"+htmlJson.eSummaryResult[1].DocSum.Id["#text"]
									tableInputRow["ti"] = "" + litInfo[i]["#text"] + ""
								}
							}
						}
					}
				})
				return tableInputRow
			}

			function populateSearch(lit) {

				$.ajax({
					async: true,
					url: 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&retmax=100000&term='+lit.replace(/\s+/g, "+"),
					type: 'GET',
					success:
					function(data) {

						var htmlJson = self.xmlToJson(data)
						console.log(htmlJson)
						if ($.isArray(htmlJson.eSearchResult[1].IdList.Id)) {

							for (x=0;x<htmlJson.eSearchResult[1].IdList.Id.length;x++) {
								var query = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id='+htmlJson.eSearchResult[1].IdList.Id[x]['#text']
								tableInput.push(parseLitSearchDataTable(query))
							}
						}
						else {
							console.log(htmlJson)
							var query = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id='+htmlJson.eSearchResult[1].IdList.Id['#text']
							tableInput.push(parseLitSearchDataTable(query))
						}
						var sDom = 't<flip>'
						if (tableInput.length<=10) { sDom = 'tfi'; }
						console.log(tableInput)
						var tableSettings = {
							"sPaginationType": "full_numbers",
							"iDisplayLength": 10,
							"sDom": sDom,
							"aoColumns": [
								{sTitle: "Journal", mData: "jo"},
								{sTitle: "Authors", mData: "au"},
								{sTitle: "Title", mData: "ti"}
							],
							"aaData": tableInput
						}
						litDataTable = self.$elem.find('#literature-table').dataTable(tableSettings)

					}
				})
			}

			return this;
		},

	    getData: function() {
            return {
                type: "LitWidget",
                id: this.options.genomeID,
                workspace: this.options.workspaceID,
                title: "Literature"
            };
        },
	});
})(jQuery);<commit_msg>changed synchronous back to asynch loading and added loader icon and date field<commit_after>(function( $, undefined ) {
    $.KBWidget({
        name: "KBaseLitWidget",
        parent: "kbaseWidget",
        version: "1.0.0",

        options: {
            genomeID: null,
            workspaceID: null,
			kbCache: null,
            loadingImage: "../../widgets/images/ajax-loader.gif",
            isInCard: false,
			width: 600,
			height: 700,
        },

		init: function(options) {
			this._super(options);

			if (this.options.row === null) {
				//throw an error
				return;
			}
            return this.render();
		},

		addInfoRow: function(a, b) {
            return "
" + a + "	" + b + "
";
        },

		xmlToJson: function(xml) {
				self = this;
				// Create the return object
				var obj = {};

				if (xml.nodeType == 1) { // element
					// do attributes
					if (xml.attributes.length > 0) {
					obj["@attributes"] = {};
						for (var j = 0; j < xml.attributes.length; j++) {
							var attribute = xml.attributes.item(j);
							obj["@attributes"][attribute.nodeName] = attribute.value;
						}
					}
				} else if (xml.nodeType == 3) { // text
					obj = xml.nodeValue;
				}

				// do children
				if (xml.hasChildNodes()) {
					for(var i = 0; i < xml.childNodes.length; i++) {
						var item = xml.childNodes.item(i);
						var nodeName = item.nodeName;
						if (typeof(obj[nodeName]) == "undefined") {
							obj[nodeName] = self.xmlToJson(item);
						} else {
							if (typeof(obj[nodeName].push) == "undefined") {
								var old = obj[nodeName];
								obj[nodeName] = [];
								obj[nodeName].push(old);
							}
							obj[nodeName].push(self.xmlToJson(item));
						}
					}
				}
				return obj;
		},

		render: function(options) {

			self = this;

			var lit = self.options.literature
			var loader = $("

").css({"width":"100%","margin":"0 auto"})
			var resultsDiv = $("
").append('
')
			var searchBarDiv = $("
").append("<input type='text' id='lit-query-box'>")
			var searchBarButton = $("<input type='button' id='lit-search-button' value='Update Search'>")
									.on("click",function() {
										lit = $('#lit-query-box').val()
										tableInput = []
										litDataTable.fnDestroy()
										populateSearch(lit)
									})

			var tableInput = []
			var litDataTable;

			self.$elem.append(searchBarDiv.append(searchBarButton)).append(loader).append(resultsDiv)

			$('#lit-query-box').val(lit)
			$('#lit-query-box').css({"width":"300px"})
			populateSearch(lit)

			function populateSearch(lit) {
				loader.show()
				$.ajax({
					async: true,
					url: 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&retmax=100000&term='+lit.replace(/\s+/g, "+"),
					type: 'GET',
					success:
					function(data) {

						var htmlJson = self.xmlToJson(data)
						var query = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id='
						if ($.isArray(htmlJson.eSearchResult[1].IdList.Id)) {

							for (x=0;x<htmlJson.eSearchResult[1].IdList.Id.length;x++) {
								query += htmlJson.eSearchResult[1].IdList.Id[x]['#text']
								if (x != htmlJson.eSearchResult[1].IdList.Id.length-1) query += ','
								// tableInput.push(parseLitSearchDataTable(query))
							}
						}
						else {
							query += htmlJson.eSearchResult[1].IdList.Id['#text']
							// tableInput.push(parseLitSearchDataTable(query))
						}
						var tableInput = []
						$.when($.ajax({
							async: true,
							url: query,
							type: 'GET'
						}))
						.then(
							function(data) {
								htmlJson = self.xmlToJson(data)
								var summaries = htmlJson.eSummaryResult[1].DocSum // Add pub date field into table as well.
								for (summary in summaries) {
									var tableInputRow = {}
									var summaryList = summaries[summary].Item

									for (item in summaryList) {
										infoRow = summaryList[item]
										if (infoRow["@attributes"].Name == "PubDate") tableInputRow["date"] = infoRow["#text"]
										if (infoRow["@attributes"].Name == "Source") tableInputRow["source"] = infoRow["#text"]
										if (infoRow["@attributes"].Name == "Title") tableInputRow["title"] = "" + infoRow["#text"] + ""
										if (infoRow["@attributes"].Name == "AuthorList") {
											var authors = ""
											commaDelay = 1
											for (author_idx in infoRow.Item) {
												author = infoRow.Item[author_idx]
												if (commaDelay == 0) authors+=", "
												else commaDelay--
												authors+=author["#text"]
											}
											tableInputRow["author"] = authors
										}
									}
									tableInput.push(tableInputRow)
								}

								var sDom = 't<flip>'
								if (tableInput.length<=10) { sDom = 'tfi'; }
								var tableSettings = {
									"sPaginationType": "full_numbers",
									"iDisplayLength": 10,
									"sDom": sDom,
									"aoColumns": [
										{sTitle: "Journal", mData: "source"},
										{sTitle: "Authors", mData: "author"},
										{sTitle: "Title", mData: "title"},
										{sTitle: "Date", mData: "date"}
									],
									"aaData": tableInput
								}
								loader.hide()
								litDataTable = self.$elem.find('#literature-table').dataTable(tableSettings)
							},
							function() {
								self.$elem.append("
There are no other data objects (you can access) that reference this object.");
							}
						)
					}
				})
			}

			return this;
		},

	    getData: function() {
            return {
                type: "LitWidget",
                id: this.options.genomeID,
                workspace: this.options.workspaceID,
                title: "Literature"
            };
        },
	});
})(jQuery);<|endoftext|>


<commit_before>'use strict';
/**
 * 通过 alias 发送推送
 *
 * @type {[type]}
 */
var JPush = require("jpush-sdk");
var config = require('config'),
    events = require('../libs/events');
var client = JPush.buildClient(config.PUSHKEY, config.PUSHSECRET);

// target : user_2132010105 / project_56713c947f0fd05911d382f4
// message : {
//     content : 'test',
//     title : '账户充值推送通知：您云能源账户已成功充值220元人民币，查看账户详情'
// }

exports.Send = function Send (doc, eventname) {

    let params = doc.param,
        eventtype = doc.type,
        targetId = params.uid || params.account,
        target = params.to.toString(),
        production = config.push === 'production',
        message = {
            title: events[eventname] && events[eventname].title,
            content: params,
            param: {
                type: eventtype,
                param: params,
                timestamp: doc.timestamp
            }
        };

    log.debug('发送消息 生产环境: ', production, doc._doc);
    //
    client.push().setPlatform('ios', 'android')
    .setAudience(JPush.alias(target))
    // .setAudience(JPush.ALL)
    .setNotification(
        message.title,
        JPush.ios(message.title, 'sound', "+1", false, {
            action: doc.type,   // 根据不同事件修改 action
            param: JSON.stringify(message.param)
        }),
        JPush.android(message.title, '', null, {
            action: doc.type,   // 同上
            param: JSON.stringify(message.param)
        })
    )
    // .setMessage(message.content)
    .setOptions(null, 60, null, production)
    .send(function(err, res) {
        if (err) {
            log.error('push error: ', err, doc);
        } else {
            log.info('push ', res, doc);
        }
    });
};<commit_msg>修改IOS推送参数<commit_after>'use strict';
/**
 * 通过 alias 发送推送
 *
 * @type {[type]}
 */
var JPush = require("jpush-sdk");
var config = require('config'),
    events = require('../libs/events');
var client = JPush.buildClient(config.PUSHKEY, config.PUSHSECRET);

// target : user_2132010105 / project_56713c947f0fd05911d382f4
// message : {
//     content : 'test',
//     title : '账户充值推送通知：您云能源账户已成功充值220元人民币，查看账户详情'
// }

exports.Send = function Send (doc, eventname) {

    let params = doc.param,
        eventtype = doc.type,
        targetId = params.uid || params.account,
        target = params.to.toString(),
        production = config.push === 'production',
        message = {
            title: events[eventname] && events[eventname].title,
            content: params,
            param: {
                type: eventtype,
                param: params,
                timestamp: doc.timestamp
            }
        };

    log.debug('发送消息 生产环境: ', production, doc._doc);
    //
    client.push().setPlatform('ios', 'android')
    .setAudience(JPush.alias(target))
    // .setAudience(JPush.ALL)
    .setNotification(
        message.title,
        JPush.ios(message.title, 'sound', "+1", true, {
            action: doc.type,   // 根据不同事件修改 action
            param: JSON.stringify(message.param)
        }),
        JPush.android(message.title, '', null, {
            action: doc.type,   // 同上
            param: JSON.stringify(message.param)
        })
    )
    // .setMessage(message.content)
    .setOptions(null, 60, null, production)
    .send(function(err, res) {
        if (err) {
            log.error('push error: ', err, doc);
        } else {
            log.info('push ', res, doc);
        }
    });
};<|endoftext|>


<commit_before>var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;

function drawBall() {
  ctx.beginPath();
  ctx.arc(x, y, 10, 0, Math.PI*2);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();
}

function draw() {
  ctx.clearRect(0,0,canvas.width, canvas.height);
  drawBall();
  x += dx;
  y += dy;
}

setInterval(draw, 10);
<commit_msg>Add ball radius<commit_after>var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var ballRadius = 10;

function drawBall() {
  ctx.beginPath();
  ctx.arc(x, y, ballRadius, 0, Math.PI*2);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();
}

function draw() {
  ctx.clearRect(0,0,canvas.width, canvas.height);
  drawBall();
  x += dx;
  y += dy;
}

setInterval(draw, 10);
<|endoftext|>


<commit_before>import $ from 'jquery';
import axios from 'axios';
import when from 'when';

const API_URL = window.location + 'api/todos/';

export function _get(taskID) {
	return axios.get( API_URL + (taskID || '') );
}

export function _post(task) {
	return axios.post(API_URL, {
		task,
		complete: false
	});
}

export function _update(todo) {
	return axios.put(API_URL + todo._id,todo);
}

export function _delete(taskID) {
	return axios.delete(API_URL + taskID);
}

export function _whenAll(requestArray) {
	return axios.all(requestArray);
}<commit_msg>remove old dependencies<commit_after>import axios from 'axios';

const API_URL = window.location + 'api/todos/';

export function _get(taskID) {
	return axios.get( API_URL + (taskID || '') );
}

export function _post(task) {
	return axios.post(API_URL, {
		task,
		complete: false
	});
}

export function _update(todo) {
	return axios.put(API_URL + todo._id,todo);
}

export function _delete(taskID) {
	return axios.delete(API_URL + taskID);
}

export function _whenAll(requestArray) {
	return axios.all(requestArray);
}
<|endoftext|>


<commit_before>var Class = require("./Class");
eval(Class.$import("./classdef"));
eval(Class.$import("./util"));

"use strict";

// FIXME add support for arrays and parameterized types
var Type = exports.Type = Class.extend({

	$_initialize: function () {
		this.voidType = new VoidType();
		this.undefinedType = new UndefinedType();
		this.nullType = new NullType();
		this.booleanType = new BooleanType();
		this.integerType = new IntegerType();
		this.numberType = new NumberType();
		this.stringType = new StringType();
	},

	$_initializeBuiltin: function (classDefs) {
		BooleanType._classDef = ClassDefinition.getClass(classDefs, "String");
		NumberType._classDef = ClassDefinition.getClass(classDefs, "Number");
		StringType._classDef = ClassDefinition.getClass(classDefs, "String");
	},

	serialize: function () {
		return this.toString();
	},

	isAssignable: null, // bool isAssignable()
	isConvertibleTo: null, // bool isConvertibleTo(type)
	getClassDef: null, // ClassDefinition getClassDef()

	equals: function (x) {
		return this == x || ((x instanceof Type) && this.toString() == x.toString());
	},

	resolveIfMayBeUndefined: function () {
		if (this instanceof MayBeUndefinedType)
			return this.getBaseType();
		return this;
	},

	asAssignableType: function () {
		return this;
	},

	$templateTypeToString: function (parameterizedTypeName, typeArgs) {
		var s = parameterizedTypeName + ".<";
		for (var i = 0; i < typeArgs.length; ++i) {
			if (i != 0)
				s += ",";
			s += typeArgs[i].toString();
		}
		s += ">";
		return s;
	},

	$isIntegerOrNumber: function (type) {
		return type instanceof IntegerType || type instanceof NumberType;
	}

});

// void and null are special types

var VoidType = exports.VoidType = Type.extend({

	instantiate: function (instantiationContext) {
		return this;
	},

	isAssignable: function () {
		return false;
	},

	isConvertibleTo: function (type) {
		return false;
	},

	getClassDef: function () {
		throw new Error("not supported");
	},

	toString: function () {
		return "void";
	}

});

var NullType = exports.NullType = Type.extend({

	instantiate: function (instantiationContext) {
		return this;
	},

	isAssignable: function () {
		return false;
	},

	isConvertibleTo: function (type) {
		type = type.resolveIfMayBeUndefined();
		return type instanceof StringType || type instanceof ObjectType;
	},

	getClassDef: function () {
		throw new Error("not supported");
	},

	toString: function () {
		return "null";
	}

});

// primitive types

var PrimitiveType = exports.PrimitiveType = Type.extend({

	instantiate: function (instantiationContext) {
		return this;
	},

	isAssignable: function () {
		return true; // still does not support "const" qualifier
	}

});

var BooleanType = exports.BooleanType = PrimitiveType.extend({

	$_classDef: null,

	isConvertibleTo: function (type) {
		type = type.resolveIfMayBeUndefined();
		return type instanceof BooleanType || type instanceof IntegerType || type instanceof NumberType;
	},

	getClassDef: function () {
		return BooleanType._classDef;
	},

	toString: function () {
		return "boolean";
	}

});

var IntegerType = exports.IntegerType = PrimitiveType.extend({

	$_classDef: null,

	isConvertibleTo: function (type) {
		type = type.resolveIfMayBeUndefined();
		return type instanceof IntegerType || type instanceof NumberType;
	},

	getClassDef: function () {
		return NumberType._classDef;
	},

	toString: function () {
		return "int";
	}

});

var NumberType = exports.NumberType = PrimitiveType.extend({

	$_classDef: null,

	isConvertibleTo: function (type) {
		type = type.resolveIfMayBeUndefined();
		return type instanceof IntegerType || type instanceof NumberType;
	},

	getClassDef: function () {
		return NumberType._classDef;
	},

	toString: function () {
		return "number";
	}

});

var StringType = exports.StringType = PrimitiveType.extend({

	$_classDef: null,

	isConvertibleTo: function (type) {
		type = type.resolveIfMayBeUndefined();
		if (type instanceof BooleanType)
			return true;
		if (type instanceof StringType)
			return true;
		return false;
	},

	getClassDef: function () {
		return StringType._classDef;
	},

	toString: function () {
		return "String";
	}

});

// undefined and MayBeUndefined

var UndefinedType = exports.UndefinedType = Type.extend({

	instantiate: function (instantiationContext) {
		return this;
	},

	isAssignable: function () {
		return false;
	},

	isConvertibleTo: function (type) {
		return type instanceof MayBeUndefinedType;
	},

	getClassDef: function () {
		throw new Error("not supported");
	},

	toString: function () {
		return "undefined";
	}

});

var MayBeUndefinedType = exports.MayBeUndefinedType = Type.extend({

	initialize: function (type) {
		this._baseType = type instanceof MayBeUndefinedType ? type._baseType : type;
	},

	instantiate: function (instantiationContext) {
		return new MayBeUndefinedType(this._baseType.instantiate(instantiationContext));
	},

	isConvertibleTo: function (type) {
		return this._baseType.isConvertibleTo(type instanceof MayBeUndefinedType ? type._baseType : type);
	},

	isAssignable: function () {
		return true;
	},

	getClassDef: function () {
		return this._baseType.getClassDef();
	},

	getBaseType: function () {
		return this._baseType;
	},

	toString: function () {
		return "MayBeUndefined<" + this._baseType.toString() + ">";
	}

});

// array and hash type

var HashType = exports.HashType = Type.extend({

	initialize: function (elementType) {
		this._elementType = elementType;
	},

	instantiate: function (instantiationContext) {
		return new HashType(this._elementType.instantiate(instantiationContext));
	},

	isConvertibleTo: function (type) {
		type = type.resolveIfMayBeUndefined();
		if (type instanceof BooleanType)
			return true;
		if (type instanceof HashType && type._elementType.equals(this._elementType))
			return true;
		return false;
	},

	isAssignable: function () {
		return true; // still does not support "const" qualifier
	},

	getClassDef: function () {
		throw new Error("FIXME");
	},

	getElementType: function () {
		return this._elementType;
	},

	toString: function () {
		return "Hash<" + this._elementType.toString() + ">";
	}

});

// class and object types

var ClassDefType = exports.ClassDefType = Type.extend({

	initialize: function (classDef) {
		this._classDef = classDef;
	},

	instantiate: function (instantiationContext) {
		throw new Error("logic flaw; ClassDefType is created during semantic analysis, after template instantiation");
	},

	isConvertibleTo: function (type) {
		return false;
	},

	isAssignable: function () {
		return false;
	},

	getClassDef: function () {
		return this._classDef;
	},

	toString: function () {
		return this._classDef.className();
	}

});

var ObjectType = exports.ObjectType = Type.extend({

	initialize: function (classDef) {
		this._classDef = classDef;
	},

	instantiate: function (instantiationContext) {
		throw new Error("logic flaw; ObjectType is created during semantic analysis, after template instantiation");
	},

	resolveType: function (context) {
		if (this._classDef == null)
			throw new Error("logic flaw");
	},

	isConvertibleTo: function (type) {
		type = type.resolveIfMayBeUndefined();
		if (type instanceof BooleanType)
			return true;
		if (! (type instanceof ObjectType))
			return false;
		return this._classDef.isConvertibleTo(type._classDef);
	},

	isAssignable: function () {
		return true; // still does not support "const" qualifier
	},

	getClassDef: function () {
		return this._classDef;
	},

	toString: function () {
		return this._classDef.className();
	}

});

var ParsedObjectType = exports.ParsedObjectType = ObjectType.extend({

	initialize: function (className, token) {
		ObjectType.prototype.initialize.call(this, null);
		this._className = className;
		this._token = token;
	},

	instantiate: function (instantiationContext) {
		var actualType = instantiationContext.typemap[this._className];
		if (actualType != undefined)
			return actualType;
		var objectType = new ParsedObjectType(this._className, this._token);
		instantiationContext.objectTypesUsed.push(objectType);
		return objectType;
	},

	resolveType: function (context) {
		if (this._classDef == null
			&& (this._classDef = ClassDefinition.getClass(context.classDefs, this._className)) == null)
			context.errors.push(new CompileError(this._token, "'" + this.toString() + "' is not defined"));
	},

	toString: function () {
		return this._className;
	}

});

var ParsedTemplateObjectType = exports.ParsedTemplateObjectType = Type.extend({

	initialize: function (className, typeArguments, token) {
		this._className = className;
		this._typeArguments = typeArguments;
		this._token = token;
	},

	instantiate: function (instantiationContext) {
		var actualType = instantiationContext.typemap[this._className];
		if (actualType == undefined)
			actualType = this._className;
		var typeArgs = [];
		for (var i = 0; i < this._typeArguments.length; ++i) {
			var t = this._typeArguments[i].instantiate(instantiationContext);
			if (t == null)
				return null;
			typeArgs[i] = t;
		}
		var objectType = new ParsedObjectType(Type.templateTypeToString(actualType, typeArgs));
		instantiationContext.objectTypesUsed.push(objectType);
		return objectType;
	},

	toString: function () {
		return Type.templateTypeToString(this._className, this._typeArguments);
	}

});

// function types

var FunctionType = exports.FunctionType = Type.extend({
});

var FunctionChoiceType = exports.FunctionChoiceType = FunctionType.extend({

	initialize: function (types) {
		this._types = types;
	},

	isAssignable: function () {
		return false;
	},

	asAssignableType: function () {
		throw new Error("logic flaw");
	},

	getClassDef: function () {
		throw new Error("FIXME");
	},

	deduceByArgumentTypes: function (context, operatorToken, argTypes, isStatic) {
		// try an exact match
		for (var i = 0; i < this._types.length; ++i)
			if (this._types[i]._deduceByArgumentTypes(argTypes, isStatic, true))
				return this._types[i];
		// try loose match
		var matched = [];
		for (var i = 0; i < this._types.length; ++i)
			if (this._types[i]._deduceByArgumentTypes(argTypes, isStatic, false))
				matched.push(this._types[i]);
		switch (matched.length) {
		case 0:
			context.errors.push(new CompileError(operatorToken, "no function with matching arguments"));
			break;
		case 1:
			return matched[0];
		default:
			context.errors.push(new CompileError(operatorToken, "result of function resolution using the arguments is ambiguous"));
			break;
		}
		return null;
	},

	toString: function () {
		return this._types.length == 1 ? this._types[0].toString() : "<<multiple choices>>";
	}

});

var ResolvedFunctionType = exports.ResolvedFunctionType = FunctionType.extend({

	initialize: function (returnType, argTypes, isAssignable) {
		this._returnType = returnType;
		this._argTypes = argTypes;
		this._isAssignable = isAssignable;
	},

	setIsAssignable: function (isAssignable) {
		this._isAssignable = isAssignable;
		return this;
	},

	isAssignable: function () {
		return this._isAssignable;
	},

	asAssignableType: function () {
		return this._clone().setIsAssignable(true);
	},

	getClassDef: function () {
		throw new Error("FIXME");
	},

	getReturnType: function () {
		return this._returnType;
	},

	getArgumentTypes: function () {
		return this._argTypes;
	},

	deduceByArgumentTypes: function (context, operatorToken, argTypes, isStatic) {
		if (! this._deduceByArgumentTypes(argTypes, isStatic, false)) {
			context.errors.push(new CompileError(operatorToken, "no function with matching arguments"));
			return null;
		}
		return this;
	},

	_deduceByArgumentTypes: function (argTypes, isStatic, exact) {
		if ((this instanceof StaticFunctionType) != isStatic)
			return false;
		if (this._argTypes.length != argTypes.length)
			return false;
		for (var i = 0; i < argTypes.length; i++) {
			if (this._argTypes[i].equals(argTypes[i])) {
				// ok
			} else {
				if (exact)
					return false;
				if (! argTypes[i].isConvertibleTo(this._argTypes[i]))
					return false;
			}
		}
		return true;
	},

	toString: function () {
		var args = [];
		for (var i = 0; i < this._argTypes.length; ++i)
			args[i] = " : " + this._argTypes[i].toString();
		return this._toStringPrefix() + "function (" + args.join(", ") + ") : " + this._returnType.toString();
	}

});

var StaticFunctionType = exports.StaticFunctionType = ResolvedFunctionType.extend({

	initialize: function (returnType, argTypes, isAssignable) {
		ResolvedFunctionType.prototype.initialize.call(this, returnType, argTypes, isAssignable);
	},

	_clone: function () {
		return new StaticFunctionType(this._returnType, this._argTypes, this._isAssignable);
	},

	isConvertibleTo: function (type) {
		type = type.resolveIfMayBeUndefined();
		if (! (type instanceof StaticFunctionType))
			return false;
		if (this._deduceByArgumentTypes(type.getArgumentTypes(), true, true) == null)
			return false;
		return true;
	},

	_toStringPrefix: function () {
		return "static ";
	}

});

var MemberFunctionType = exports.MemberFunctionType = ResolvedFunctionType.extend({

	initialize: function (objectType, returnType, argTypes, isAssignable) {
		ResolvedFunctionType.prototype.initialize.call(this, returnType, argTypes, isAssignable);
		this._objectType = objectType;
	},

	_clone: function () {
		return new MemberFunctionType(this._objectType, this._returnType, this._argTypes, this._isAssignable);
	},

	_toStringPrefix: function () {
		return this._objectType.toString() + ".";
	}

});

Type._initialize();
<commit_msg>remove HashType (no longer used)<commit_after>var Class = require("./Class");
eval(Class.$import("./classdef"));
eval(Class.$import("./util"));

"use strict";

// FIXME add support for arrays and parameterized types
var Type = exports.Type = Class.extend({

	$_initialize: function () {
		this.voidType = new VoidType();
		this.undefinedType = new UndefinedType();
		this.nullType = new NullType();
		this.booleanType = new BooleanType();
		this.integerType = new IntegerType();
		this.numberType = new NumberType();
		this.stringType = new StringType();
	},

	$_initializeBuiltin: function (classDefs) {
		BooleanType._classDef = ClassDefinition.getClass(classDefs, "String");
		NumberType._classDef = ClassDefinition.getClass(classDefs, "Number");
		StringType._classDef = ClassDefinition.getClass(classDefs, "String");
	},

	serialize: function () {
		return this.toString();
	},

	isAssignable: null, // bool isAssignable()
	isConvertibleTo: null, // bool isConvertibleTo(type)
	getClassDef: null, // ClassDefinition getClassDef()

	equals: function (x) {
		return this == x || ((x instanceof Type) && this.toString() == x.toString());
	},

	resolveIfMayBeUndefined: function () {
		if (this instanceof MayBeUndefinedType)
			return this.getBaseType();
		return this;
	},

	asAssignableType: function () {
		return this;
	},

	$templateTypeToString: function (parameterizedTypeName, typeArgs) {
		var s = parameterizedTypeName + ".<";
		for (var i = 0; i < typeArgs.length; ++i) {
			if (i != 0)
				s += ",";
			s += typeArgs[i].toString();
		}
		s += ">";
		return s;
	},

	$isIntegerOrNumber: function (type) {
		return type instanceof IntegerType || type instanceof NumberType;
	}

});

// void and null are special types

var VoidType = exports.VoidType = Type.extend({

	instantiate: function (instantiationContext) {
		return this;
	},

	isAssignable: function () {
		return false;
	},

	isConvertibleTo: function (type) {
		return false;
	},

	getClassDef: function () {
		throw new Error("not supported");
	},

	toString: function () {
		return "void";
	}

});

var NullType = exports.NullType = Type.extend({

	instantiate: function (instantiationContext) {
		return this;
	},

	isAssignable: function () {
		return false;
	},

	isConvertibleTo: function (type) {
		type = type.resolveIfMayBeUndefined();
		return type instanceof StringType || type instanceof ObjectType;
	},

	getClassDef: function () {
		throw new Error("not supported");
	},

	toString: function () {
		return "null";
	}

});

// primitive types

var PrimitiveType = exports.PrimitiveType = Type.extend({

	instantiate: function (instantiationContext) {
		return this;
	},

	isAssignable: function () {
		return true; // still does not support "const" qualifier
	}

});

var BooleanType = exports.BooleanType = PrimitiveType.extend({

	$_classDef: null,

	isConvertibleTo: function (type) {
		type = type.resolveIfMayBeUndefined();
		return type instanceof BooleanType || type instanceof IntegerType || type instanceof NumberType;
	},

	getClassDef: function () {
		return BooleanType._classDef;
	},

	toString: function () {
		return "boolean";
	}

});

var IntegerType = exports.IntegerType = PrimitiveType.extend({

	$_classDef: null,

	isConvertibleTo: function (type) {
		type = type.resolveIfMayBeUndefined();
		return type instanceof IntegerType || type instanceof NumberType;
	},

	getClassDef: function () {
		return NumberType._classDef;
	},

	toString: function () {
		return "int";
	}

});

var NumberType = exports.NumberType = PrimitiveType.extend({

	$_classDef: null,

	isConvertibleTo: function (type) {
		type = type.resolveIfMayBeUndefined();
		return type instanceof IntegerType || type instanceof NumberType;
	},

	getClassDef: function () {
		return NumberType._classDef;
	},

	toString: function () {
		return "number";
	}

});

var StringType = exports.StringType = PrimitiveType.extend({

	$_classDef: null,

	isConvertibleTo: function (type) {
		type = type.resolveIfMayBeUndefined();
		if (type instanceof BooleanType)
			return true;
		if (type instanceof StringType)
			return true;
		return false;
	},

	getClassDef: function () {
		return StringType._classDef;
	},

	toString: function () {
		return "String";
	}

});

// undefined and MayBeUndefined

var UndefinedType = exports.UndefinedType = Type.extend({

	instantiate: function (instantiationContext) {
		return this;
	},

	isAssignable: function () {
		return false;
	},

	isConvertibleTo: function (type) {
		return type instanceof MayBeUndefinedType;
	},

	getClassDef: function () {
		throw new Error("not supported");
	},

	toString: function () {
		return "undefined";
	}

});

var MayBeUndefinedType = exports.MayBeUndefinedType = Type.extend({

	initialize: function (type) {
		this._baseType = type instanceof MayBeUndefinedType ? type._baseType : type;
	},

	instantiate: function (instantiationContext) {
		return new MayBeUndefinedType(this._baseType.instantiate(instantiationContext));
	},

	isConvertibleTo: function (type) {
		return this._baseType.isConvertibleTo(type instanceof MayBeUndefinedType ? type._baseType : type);
	},

	isAssignable: function () {
		return true;
	},

	getClassDef: function () {
		return this._baseType.getClassDef();
	},

	getBaseType: function () {
		return this._baseType;
	},

	toString: function () {
		return "MayBeUndefined<" + this._baseType.toString() + ">";
	}

});

// class and object types

var ClassDefType = exports.ClassDefType = Type.extend({

	initialize: function (classDef) {
		this._classDef = classDef;
	},

	instantiate: function (instantiationContext) {
		throw new Error("logic flaw; ClassDefType is created during semantic analysis, after template instantiation");
	},

	isConvertibleTo: function (type) {
		return false;
	},

	isAssignable: function () {
		return false;
	},

	getClassDef: function () {
		return this._classDef;
	},

	toString: function () {
		return this._classDef.className();
	}

});

var ObjectType = exports.ObjectType = Type.extend({

	initialize: function (classDef) {
		this._classDef = classDef;
	},

	instantiate: function (instantiationContext) {
		throw new Error("logic flaw; ObjectType is created during semantic analysis, after template instantiation");
	},

	resolveType: function (context) {
		if (this._classDef == null)
			throw new Error("logic flaw");
	},

	isConvertibleTo: function (type) {
		type = type.resolveIfMayBeUndefined();
		if (type instanceof BooleanType)
			return true;
		if (! (type instanceof ObjectType))
			return false;
		return this._classDef.isConvertibleTo(type._classDef);
	},

	isAssignable: function () {
		return true; // still does not support "const" qualifier
	},

	getClassDef: function () {
		return this._classDef;
	},

	toString: function () {
		return this._classDef.className();
	}

});

var ParsedObjectType = exports.ParsedObjectType = ObjectType.extend({

	initialize: function (className, token) {
		ObjectType.prototype.initialize.call(this, null);
		this._className = className;
		this._token = token;
	},

	instantiate: function (instantiationContext) {
		var actualType = instantiationContext.typemap[this._className];
		if (actualType != undefined)
			return actualType;
		var objectType = new ParsedObjectType(this._className, this._token);
		instantiationContext.objectTypesUsed.push(objectType);
		return objectType;
	},

	resolveType: function (context) {
		if (this._classDef == null
			&& (this._classDef = ClassDefinition.getClass(context.classDefs, this._className)) == null)
			context.errors.push(new CompileError(this._token, "'" + this.toString() + "' is not defined"));
	},

	toString: function () {
		return this._className;
	}

});

var ParsedTemplateObjectType = exports.ParsedTemplateObjectType = Type.extend({

	initialize: function (className, typeArguments, token) {
		this._className = className;
		this._typeArguments = typeArguments;
		this._token = token;
	},

	instantiate: function (instantiationContext) {
		var actualType = instantiationContext.typemap[this._className];
		if (actualType == undefined)
			actualType = this._className;
		var typeArgs = [];
		for (var i = 0; i < this._typeArguments.length; ++i) {
			var t = this._typeArguments[i].instantiate(instantiationContext);
			if (t == null)
				return null;
			typeArgs[i] = t;
		}
		var objectType = new ParsedObjectType(Type.templateTypeToString(actualType, typeArgs));
		instantiationContext.objectTypesUsed.push(objectType);
		return objectType;
	},

	toString: function () {
		return Type.templateTypeToString(this._className, this._typeArguments);
	}

});

// function types

var FunctionType = exports.FunctionType = Type.extend({
});

var FunctionChoiceType = exports.FunctionChoiceType = FunctionType.extend({

	initialize: function (types) {
		this._types = types;
	},

	isAssignable: function () {
		return false;
	},

	asAssignableType: function () {
		throw new Error("logic flaw");
	},

	getClassDef: function () {
		throw new Error("FIXME");
	},

	deduceByArgumentTypes: function (context, operatorToken, argTypes, isStatic) {
		// try an exact match
		for (var i = 0; i < this._types.length; ++i)
			if (this._types[i]._deduceByArgumentTypes(argTypes, isStatic, true))
				return this._types[i];
		// try loose match
		var matched = [];
		for (var i = 0; i < this._types.length; ++i)
			if (this._types[i]._deduceByArgumentTypes(argTypes, isStatic, false))
				matched.push(this._types[i]);
		switch (matched.length) {
		case 0:
			context.errors.push(new CompileError(operatorToken, "no function with matching arguments"));
			break;
		case 1:
			return matched[0];
		default:
			context.errors.push(new CompileError(operatorToken, "result of function resolution using the arguments is ambiguous"));
			break;
		}
		return null;
	},

	toString: function () {
		return this._types.length == 1 ? this._types[0].toString() : "<<multiple choices>>";
	}

});

var ResolvedFunctionType = exports.ResolvedFunctionType = FunctionType.extend({

	initialize: function (returnType, argTypes, isAssignable) {
		this._returnType = returnType;
		this._argTypes = argTypes;
		this._isAssignable = isAssignable;
	},

	setIsAssignable: function (isAssignable) {
		this._isAssignable = isAssignable;
		return this;
	},

	isAssignable: function () {
		return this._isAssignable;
	},

	asAssignableType: function () {
		return this._clone().setIsAssignable(true);
	},

	getClassDef: function () {
		throw new Error("FIXME");
	},

	getReturnType: function () {
		return this._returnType;
	},

	getArgumentTypes: function () {
		return this._argTypes;
	},

	deduceByArgumentTypes: function (context, operatorToken, argTypes, isStatic) {
		if (! this._deduceByArgumentTypes(argTypes, isStatic, false)) {
			context.errors.push(new CompileError(operatorToken, "no function with matching arguments"));
			return null;
		}
		return this;
	},

	_deduceByArgumentTypes: function (argTypes, isStatic, exact) {
		if ((this instanceof StaticFunctionType) != isStatic)
			return false;
		if (this._argTypes.length != argTypes.length)
			return false;
		for (var i = 0; i < argTypes.length; i++) {
			if (this._argTypes[i].equals(argTypes[i])) {
				// ok
			} else {
				if (exact)
					return false;
				if (! argTypes[i].isConvertibleTo(this._argTypes[i]))
					return false;
			}
		}
		return true;
	},

	toString: function () {
		var args = [];
		for (var i = 0; i < this._argTypes.length; ++i)
			args[i] = " : " + this._argTypes[i].toString();
		return this._toStringPrefix() + "function (" + args.join(", ") + ") : " + this._returnType.toString();
	}

});

var StaticFunctionType = exports.StaticFunctionType = ResolvedFunctionType.extend({

	initialize: function (returnType, argTypes, isAssignable) {
		ResolvedFunctionType.prototype.initialize.call(this, returnType, argTypes, isAssignable);
	},

	_clone: function () {
		return new StaticFunctionType(this._returnType, this._argTypes, this._isAssignable);
	},

	isConvertibleTo: function (type) {
		type = type.resolveIfMayBeUndefined();
		if (! (type instanceof StaticFunctionType))
			return false;
		if (this._deduceByArgumentTypes(type.getArgumentTypes(), true, true) == null)
			return false;
		return true;
	},

	_toStringPrefix: function () {
		return "static ";
	}

});

var MemberFunctionType = exports.MemberFunctionType = ResolvedFunctionType.extend({

	initialize: function (objectType, returnType, argTypes, isAssignable) {
		ResolvedFunctionType.prototype.initialize.call(this, returnType, argTypes, isAssignable);
		this._objectType = objectType;
	},

	_clone: function () {
		return new MemberFunctionType(this._objectType, this._returnType, this._argTypes, this._isAssignable);
	},

	_toStringPrefix: function () {
		return this._objectType.toString() + ".";
	}

});

Type._initialize();
<|endoftext|>


<commit_before>var exec = require('child_process').exec,
  Path = require('path')
;

exec( 'git submodule init', function(){
  exec( 'git submodule update', function(){
    exec( 'npm install', {cwd: Path.join(__dirname, 'src/react-svge')}, function( err ){
      if( err )
        console.log( err );
      else
        console.log( 'Todo bien' );
    });
  });
});
<commit_msg>Updates installation script.<commit_after>var exec = require('child_process').exec,
  Path = require('path')
;

exec( 'git submodule init', function(){
  console.log("Importing react-svge...");
  exec( 'git submodule update', function(){
    console.log("react-svge imported. Installing dependencies...");
    exec( 'npm install', {cwd: Path.join(__dirname, '../src/react-svge')}, function( err ){
      if( err )
        console.log( err );
      else
        console.log( 'OK' );
    });
  });
});
<|endoftext|>


<commit_before>//////// Module Definition ////////////
define([
	'search/search.module',
	'search/wikidataSearch.service',
	'util/util.service',
	'i18n/i18n.service',
	'i18n/translate.config'
], function() {
///////////////////////////////////////

angular.module('search').controller('searchField', [
'$scope', '$translate', '$window', 'wikidataSearch', 'wikidataapi', 'i18n', 'util',
function($scope, $translate, $window, wikidataSearch, wikidataapi, i18n, util){
	$scope.selectedEntity = "";
	var lang = i18n.getLanguage();
	$scope.localSearch = function(str, timeoutPromise){
		var promise = wikidataapi.searchEntities(str, lang).then(function(data){
			suggestions = [];
			for (var i= 0; i < data.length; i++){
				var alias = '';
				if (data[i].aliases){
					alias = ' (' + data[i].aliases[0] + ')';
				}
				suggestions.push({name: data[i].label + alias, idName: data[i].id, id: String(i)});
			}
			return {data: suggestions};
		});
		return promise;
	};
	$scope.searchEntity= function () {
		$window.location.href = '/#/view?id=' + $scope.selectedEntity.originalObject.idName + '&lang=' + lang;
	};
  }]);

return {}; }); // module definition end
<commit_msg>prevent error if no element is selected<commit_after>//////// Module Definition ////////////
define([
	'search/search.module',
	'search/wikidataSearch.service',
	'util/util.service',
	'i18n/i18n.service',
	'i18n/translate.config'
], function() {
///////////////////////////////////////

angular.module('search').controller('searchField', [
'$scope', '$translate', '$window', 'wikidataSearch', 'wikidataapi', 'i18n', 'util',
function($scope, $translate, $window, wikidataSearch, wikidataapi, i18n, util){
	$scope.selectedEntity = "";
	var lang = i18n.getLanguage();
	$scope.localSearch = function(str, timeoutPromise){
		var promise = wikidataapi.searchEntities(str, lang).then(function(data){
			suggestions = [];
			for (var i= 0; i < data.length; i++){
				var alias = '';
				if (data[i].aliases){
					alias = ' (' + data[i].aliases[0] + ')';
				}
				suggestions.push({name: data[i].label + alias, idName: data[i].id, id: String(i)});
			}
			return {data: suggestions};
		});
		return promise;
	};
	$scope.searchEntity= function () {
		if ($scope.selectedEntity){
			$window.location.href = '/#/view?id=' + $scope.selectedEntity.originalObject.idName + '&lang=' + lang;
		}
	};
  }]);

return {}; }); // module definition end
<|endoftext|>