<commit_before>/* Soakbot - The Modular IRC Bot
 *   Sorta like Hubot, but for IRC and JavaScript
 *   instead of Campfire and CoffeeScript.
 *
 * Copyright 2013-2015 Augustin Cavalier <waddlesplash>.
 * Licensed under the MIT license.
 */

// Catch-all for exceptions
process.on('uncaughtException', function (err) {
  console.trace(err);
});

var fs = require('fs');
var irc = require("irc");
var config;

/* Server list */
config = fs.readFileSync('config.json', {'encoding': 'utf8'});
if (!config) {
  console.log("FATAL: No configuration file!");
  process.exit(1);
}
config = JSON.parse(config);

/* Initiate: connect to all specified servers */
for (var URL in config.networks) {
  var serverSettings = config.networks[URL];
  startOnServer(serverSettings, URL, config.settings);
}

function startOnServer(serverSettings, serverURL, globalSettings) {
  var bot = new irc.Client(serverURL, serverSettings.nick, {
    realName: 'https://github.com/waddlesplash/soakbot',
    port: 6697, /* IRC over SSL */
    autoRejoin: false, /* Allows bot to be kicked. */
    secure: true,
    floodProtection: true,
    floodProtectionDelay: 500,
    stripColors: true
  });

  bot.on('registered', function(msg) {
    if ("password" in serverSettings) {
      bot.say("NickServ", "release " + serverSettings.nick + " " + serverSettings.password);
      bot.say("NickServ", "identify " + serverSettings.nick + " " +  serverSettings.password);
    }

    for (var i in serverSettings.channels) {
      handleChannel(bot, serverSettings.channels[i], serverSettings, globalSettings);
    }
  });

  /* Give help when someone PMs the bot */
  bot.on('pm', function(userNick, msg, raw) {
    if ((msg == serverSettings.nick + ': about') || (msg == serverSettings.nick + ': help') ||
       (msg == "about") || (msg == "help")) {
      bot.say(channel, "I'm a modular NodeJS-based IRC bot. Operator(s): " + globalSettings.operators.join(', ') + ".");
      bot.say(userNick, 'Source code & issue tracker at https://github.com/waddlesplash/soakbot');
    }
  });
  bot.on('nick', function(oldNick, newNick) {
    /* Somebody force-changed the bot's nickname... */
    if (oldNick == serverSettings.nick)
      serverSettings.nick = newNick;
  });
}

/* Per-channel functionality. */
function handleChannel(bot, channelSettings, serverSettings, globalSettings) {
  var channel = channelSettings.channel, topic, modules = {}, users = [];

  bot.join(channel);
  if ("ignored" in channelSettings) {
    channelSettings.ignored = channelSettings.ignored.toLowerCase().split(" ");
  }

  bot.on('topic', function(chan, chanTopic, whoSetIt) {
    if (chan == channel) {
      topic = chanTopic;
    }
  });

  var onMessage = function(from, msg) {
    if ('ignored' in channelSettings) {
      for (var i in channelSettings.ignored) {
        if (from.toLowerCase().indexOf(channelSettings.ignored[i]) == 0)
          return;
      }
    }

    var parameters = {from: from, message: msg, originalMessage: msg, channel: channel, topic: topic, bot: bot, nick: serverSettings.nick};

    if ((msg == serverSettings.nick + ': about') ||
      (msg == serverSettings.nick + ': help')) {
      bot.say(channel, "I'm a modular NodeJS-based IRC bot. Operator(s): " + globalSettings.operators.join(', ') + ".");
      bot.say(channel, 'Source code & issue tracker at https://github.com/waddlesplash/soakbot');
      bot.say(channel, 'Enabled modules: ' + channelSettings.modules);
    } else {
      for (var i in modules)
        modules[i].onMessage(channelSettings, globalSettings, parameters);
    }
  };

  /* Load the modules! */
  if (channelSettings.modules.length > 1) {
    var loadme = channelSettings.modules.split(" ");
    for (var i in loadme) {
      var module = require("./modules/" + loadme[i]);
      modules[loadme[i]] = module;
      if ("onLoad" in module)
        module.onLoad(channelSettings, globalSettings);
    }
  }

  bot.on('message' + channel, onMessage);
}
<commit_msg>Fixes to authentication.<commit_after>/* Soakbot - The Modular IRC Bot
 *   Sorta like Hubot, but for IRC and JavaScript
 *   instead of Campfire and CoffeeScript.
 *
 * Copyright 2013-2015 Augustin Cavalier <waddlesplash>.
 * Licensed under the MIT license.
 */

// Catch-all for exceptions
process.on('uncaughtException', function (err) {
  console.trace(err);
});

var fs = require('fs');
var irc = require("irc");
var config;

/* Server list */
config = fs.readFileSync('config.json', {'encoding': 'utf8'});
if (!config) {
  console.log("FATAL: No configuration file!");
  process.exit(1);
}
config = JSON.parse(config);

/* Initiate: connect to all specified servers */
for (var URL in config.networks) {
  var serverSettings = config.networks[URL];
  startOnServer(serverSettings, URL, config.settings);
}

function startOnServer(serverSettings, serverURL, globalSettings) {
  var tempNick = "skbot" + Math.floor(Math.random()*1000);
  var bot = new irc.Client(serverURL, tempNick, {
    userName: 'soakbot',
    realName: 'https://github.com/waddlesplash/soakbot',
    port: 6697, /* IRC over SSL */
    autoRejoin: false, /* Allows bot to be kicked. */
    secure: true,
    floodProtection: true,
    floodProtectionDelay: 500,
    stripColors: true
  });

  bot.on('registered', function(msg) {
    if ("password" in serverSettings) {
      bot.say("NickServ", "release " + serverSettings.nick + " " + serverSettings.password);
      bot.say("NickServ", "identify " + serverSettings.nick + " " +  serverSettings.password);
      bot.send("NICK", serverSettings.nick);
    }

    for (var i in serverSettings.channels) {
      handleChannel(bot, serverSettings.channels[i], serverSettings, globalSettings);
    }
  });

  /* Give help when someone PMs the bot */
  bot.on('pm', function(nick, msg, raw) {
    if ((msg == serverSettings.nick + ': about') || (msg == serverSettings.nick + ': help') ||
       (msg == "about") || (msg == "help")) {
      bot.say(nick, "I'm a modular NodeJS-based IRC bot. Operator(s): " +
        globalSettings.operators.join(', ') + ".");
      bot.say(nick, 'Source code & issue tracker at https://github.com/waddlesplash/soakbot');
    } else {
      console.log("WARN: " + nick + " msg'd me: \"" + msg + '"');
    }
  });
  bot.on('notice', function(nick, to, msg, raw) {
    console.log("WARN: " + nick + " notice'd me: \"" + msg + '"');
  });

  bot.on('nick', function (oldNick, newNick) {
    serverSettings.nick = newNick;
  });
}

/* Per-channel functionality. */
function handleChannel(bot, channelSettings, serverSettings, globalSettings) {
  var channel = channelSettings.channel, topic, modules = {}, users = [];

  bot.join(channel);
  if ("ignored" in channelSettings) {
    channelSettings.ignored = channelSettings.ignored.toLowerCase().split(" ");
  }

  bot.on('topic', function(chan, chanTopic, whoSetIt) {
    if (chan == channel) {
      topic = chanTopic;
    }
  });

  var onMessage = function(from, msg) {
    if ('ignored' in channelSettings) {
      for (var i in channelSettings.ignored) {
        if (from.toLowerCase().indexOf(channelSettings.ignored[i]) == 0)
          return;
      }
    }

    var parameters = {from: from, message: msg, originalMessage: msg, channel: channel, topic: topic, bot: bot, nick: serverSettings.nick};

    if ((msg == serverSettings.nick + ': about') ||
      (msg == serverSettings.nick + ': help')) {
      bot.say(channel, "I'm a modular NodeJS-based IRC bot. Operator(s): " + globalSettings.operators.join(', ') + ".");
      bot.say(channel, 'Source code & issue tracker at https://github.com/waddlesplash/soakbot');
      bot.say(channel, 'Enabled modules: ' + channelSettings.modules);
    } else {
      for (var i in modules)
        modules[i].onMessage(channelSettings, globalSettings, parameters);
    }
  };

  /* Load the modules! */
  if (channelSettings.modules.length > 1) {
    var loadme = channelSettings.modules.split(" ");
    for (var i in loadme) {
      var module = require("./modules/" + loadme[i]);
      modules[loadme[i]] = module;
      if ("onLoad" in module)
        module.onLoad(channelSettings, globalSettings);
    }
  }

  bot.on('message' + channel, onMessage);
}
<|endoftext|>


<commit_before><commit_msg>Get Programming<commit_after><|endoftext|>


<commit_before>new (function() {
	var ext = this;
	ext.socket = null;

  var getUrlParameter = function getUrlParameter(sParam) {
	    var sPageURL = decodeURIComponent(document.currentScript.src.split("?")[1]),
	        sURLVariables = sPageURL.split('&'),
	        sParameterName,
	        i;

	    for (i = 0; i < sURLVariables.length; i++) {
	        sParameterName = sURLVariables[i].split('=');

	        if (sParameterName[0] === sParam) {
	            return sParameterName[1] === undefined ? true : sParameterName[1];
	        }
	    }
	};

	ext.name = getUrlParameter('name');
	ext.ip = getUrlParameter('ip');

	if(ext.name != undefined) {
		// we'll use the name supplied by preference
		ext.url = "http://" + ext.name;
		console.log('got name');
	}
	else {
		// no name supplied so use the IP address
		ext.url = "http://" + ext.ip;
		console.log("didn't get name");
	}

	console.log('name ' + ext.name);
	console.log('ip ' + ext.ip);
	console.log('using url ' + ext.url);

	var descriptor = {
		blocks: [
			[' ', ext.name != null ? ext.name : ext.ip + ': connect', 'connect'],
			[' ', ext.name != null ? ext.name : ext.ip + ': disconnect', 'disconnect'],
			['b', ext.name != null ? ext.name : ext.ip + ': isConnected', 'isConnected'],
			[' ', ext.name != null ? ext.name : ext.ip + ': digital pin %m.pin setting %m.dsetting', 'setDigital', '1', 'off'],
			[' ', ext.name != null ? ext.name : ext.ip + ': pwm pin %m.ppin setting %n', 'setPwm', '1', '100'],
			[' ', ext.name != null ? ext.name : ext.ip + ': digital pin %m.pin get', 'getDigital', '1'],
			[' ', ext.name != null ? ext.name : ext.ip + ': pwm pin %m.ppin get', 'getPwm', '1']
		],
		'menus': {
		'pin': ['1', '2', '3'],
		'dsetting': ['on', 'off'],
		'ppin': ['1', '2']
		},
		url: 'http://www.warwick.ac.uk/tilesfortales'
	};

	ext.connect = function() {
		if(ext.socket == null) {
			ext.socket = new WebSocket("ws://" + ext.ip, 'firmata');
			ext.socket.binaryType = "arraybuffer";
			ext.socket.onopen = function(evt) {ext.onOpen(evt)};
			ext.socket.onmessage = function(evt) {ext.onMessage(evt)};
			ext.socket.onclose = function(evt) {ext.onClose(evt)};
		}
		else if(ext.socket.readyState == ext.socket.CLOSING || ext.socket.readyState == ext.socket.CLOSED) {
			ext.socket = null;
			ext.connect();
		}
		// if socket is in open or connecting state we're not going to do anything
	}

	ext.isConnected = function() {
		var retval = false;
		if(ext.socket != null && ext.socket.readyState == ext.socket.OPEN) {
			retval = true;
		}
		return retval;
	}

	ext.disconnect = function() {
		if(ext.socket != null) {
			ext.socket.close();
			ext.socket = null;
		}
	}

  if(ext.name != undefined) {
		ScratchExtensions.register(ext.name, descriptor, ext);
	}
	else {
		ScratchExtensions.register(ext.ip, descriptor, ext);
	}

})();
<commit_msg>connect<commit_after>new (function() {
	var ext = this;
	ext.socket = null;

  var getUrlParameter = function getUrlParameter(sParam) {
	    var sPageURL = decodeURIComponent(document.currentScript.src.split("?")[1]),
	        sURLVariables = sPageURL.split('&'),
	        sParameterName,
	        i;

	    for (i = 0; i < sURLVariables.length; i++) {
	        sParameterName = sURLVariables[i].split('=');

	        if (sParameterName[0] === sParam) {
	            return sParameterName[1] === undefined ? true : sParameterName[1];
	        }
	    }
	};

	ext.name = getUrlParameter('name');
	ext.ip = getUrlParameter('ip');

	if(ext.name != undefined) {
		// we'll use the name supplied by preference
		ext.url = "http://" + ext.name;
		console.log('got name');
	}
	else {
		// no name supplied so use the IP address
		ext.url = "http://" + ext.ip;
		console.log("didn't get name");
	}

	console.log('name ' + ext.name);
	console.log('ip ' + ext.ip);
	console.log('using url ' + ext.url);

	var descriptor = {
		blocks: [
			[' ', ext.name != null ? ext.name : ext.ip + ': connect', 'connect'],
			[' ', ext.name != null ? ext.name : ext.ip + ': disconnect', 'disconnect'],
			['b', ext.name != null ? ext.name : ext.ip + ': isConnected', 'isConnected'],
			[' ', ext.name != null ? ext.name : ext.ip + ': digital pin %m.pin setting %m.dsetting', 'setDigital', '1', 'off'],
			[' ', ext.name != null ? ext.name : ext.ip + ': pwm pin %m.ppin setting %n', 'setPwm', '1', '100'],
			[' ', ext.name != null ? ext.name : ext.ip + ': digital pin %m.pin get', 'getDigital', '1'],
			[' ', ext.name != null ? ext.name : ext.ip + ': pwm pin %m.ppin get', 'getPwm', '1']
		],
		'menus': {
		'pin': ['1', '2', '3'],
		'dsetting': ['on', 'off'],
		'ppin': ['1', '2']
		},
		url: 'http://www.warwick.ac.uk/tilesfortales'
	};

	ext.connect = function() {
		if(ext.socket == null) {
			ext.socket = new WebSocket("ws://" + ext.ip, 'firmata');
			ext.socket.binaryType = "arraybuffer";
			ext.socket.onopen = function(evt) {ext.onOpen(evt)};
			ext.socket.onmessage = function(evt) {ext.onMessage(evt)};
			ext.socket.onclose = function(evt) {ext.onClose(evt)};
		}
		else if(ext.socket.readyState == ext.socket.CLOSING || ext.socket.readyState == ext.socket.CLOSED) {
			ext.socket = null;
			ext.connect();
		}
		// if socket is in open or connecting state we're not going to do anything
	}

	ext.isConnected = function() {
		var retval = false;
		if(ext.socket != null && ext.socket.readyState == ext.socket.OPEN) {
			retval = true;
		}
		return retval;
	}

	ext.disconnect = function() {
		if(ext.socket != null) {
			ext.socket.close();
			ext.socket = null;
		}
	}

	ScratchExtensions.register(ext.name != null ext.name : ext.ip, descriptor, ext);
  /*
  if(ext.name != undefined) {
		ScratchExtensions.register(ext.name, descriptor, ext);
	}
	else {
		ScratchExtensions.register(ext.ip, descriptor, ext);
	}
  */
})();
<|endoftext|>


<commit_before>define(function(require) {
  var Backbone = require('backbone'),
      Handlebars = require('handlebars'),
      $ = require('jquery'),
      d3 = require('d3'),
      _ = require('underscore'),
      Where = require('summary/where'),
      util = require('summary/util'),
      DrawingView = require('summary/drawingview'),
      QueryForm = require('summary/queryform');

  var QueryView = Backbone.View.extend({
    errtemplate: Handlebars.compile($("#q-err-template").html()),

    defaults: function() {
      return {
        xdomain: null,
        ydomain: null,
        xscales: null,
        yscales: null,
        cscales: d3.scale.category10(),
        xaxis: null,
        yaxis: null,
        series: null,
        w: 500,
        h: 400,
        lp: 60,
        tp: 20,
        bp: 15,
        ip: 5,  // data-container inner padding
        marktype: 'circle'
      };
    },

    initialize: function() {
      this.state = this.defaults();

      this.$svg = $("<svg id='viz'></svg>").prependTo(this.$el);
      this.svg = this.$svg.get()[0];
      this.d3svg = d3.select(this.svg);
      this.d3svg
        .attr('class', 'viz-container')
        .attr('width', this.state.w + this.state.lp)
        .attr('height', this.state.h + this.state.tp + this.state.bp);
      this.c = this.d3svg.append('g')
          .classed("plot-container", true)
          .attr('transform', "translate("+this.state.lp+", 0)");
      this.c.append('rect')
        .attr('width', this.state.w)
        .attr('height', this.state.h)
        .attr('fill', 'none')
        .attr('stroke', 'none')
        .style('pointer-events', 'all')

      this.queryform = new QueryForm({model: this.model});
      this.listenTo(this.queryform, 'submit', this.resetState.bind(this));
      this.$el.append(this.queryform.render().el)

      this.$toggle = $("#q-toggle")
        .addClass("btn btn-primary")
        .css("margin-left", this.state.lp)
        .click((function() {
          this.queryform.render().$el.toggle();
          this.$('.legend').toggle();
          this.$svg.toggle();
        }).bind(this));

      this.listenTo(this.model, 'change:db', this.resetState);
      this.listenTo(this.model, 'change:table', this.resetState);
      this.listenTo(this.model, 'change:data', this.render);
      this.listenTo(this.model, 'fetch:start', this.fetchStart);
      this.listenTo(this.model, 'fetch:end', this.fetchEnd);
    },

    resetState: function() {
      this.state = this.defaults();
      this.trigger("resetState");
    },

    onChange: function() {
      return;
      this.model.get('where').fetch({
        data: {
          db: this.model.get('db'),
          table: this.model.get('table'),
          nbuckets: 500
        }
      });
    },

    fetchStart: function() {
      $("#q_loading").show();
    },

    fetchEnd: function() {
      $("#q_loading").hide();
    },

    // persistently update scales information
    setupScales: function(data) {
      var schema = this.model.get('schema'),
          xcol = this.model.get('x'),
          xalias = xcol.alias,
          ycols = this.model.get('ys'),
          yaliases = _.pluck(ycols, 'alias'),
          type = schema[xcol.col],
          _this = this,
          ip = this.state.ip,
          xs = _.pluck(data, xalias),
          yss = _.map(yaliases, function(yalias) { return _.pluck(data, yalias) }),
          newCDomain = _.compact(_.union(this.state.cscales.domain(), yaliases));

      this.state.cscales.domain(newCDomain);

      var getx = function(d) { return d[xalias]; },
          xdomain = util.getXDomain(data, type, getx);
      this.state.xdomain = util.mergeDomain(this.state.xdomain, xdomain, type);

      _.each(yss, function(ys) {
        if (this.state.ydomain == null) this.state.ydomain = [Infinity, -Infinity];
        ys = _.filter(ys, _.isFinite);
        if (ys.length) {
          this.state.ydomain[0] = Math.min(this.state.ydomain[0], d3.min(ys));
          this.state.ydomain[1] = Math.max(this.state.ydomain[1], d3.max(ys));
        }
      }, this);

      if (this.state.xscales == null) {
        var xscales = d3.scale.linear();
        if (util.isTime(type)) {
          xscales = d3.time.scale();
        }
        xscales.range([0+ip, this.state.w-ip]);

        if (util.isStr(type)) {
          xscales = d3.scale.ordinal();
          xscales.rangeRoundBands([0+ip, this.state.w-ip], 0.1);
        }
        this.state.xscales = xscales;
      }
      this.state.xscales.domain(this.state.xdomain);

      if (this.state.yscales == null) {
        this.state.yscales = d3.scale.linear()
          .range([this.state.h-ip, 0+ip])
      }
      this.state.yscales.domain(this.state.ydomain);

      if (!this.state.xaxis) {
        this.state.xaxis = d3.svg.axis()
          .scale(this.state.xscales)
          .tickSize(0,0)
          .orient('bottom')
        var nticks = util.estNumXTicks(this.state.xaxis, type, this.state.w);
        util.setAxisLabels(this.state.xaxis, type, nticks);
      }
      if (!this.state.yaxis) {
        this.state.yaxis = d3.svg.axis()
          .scale(this.state.yscales)
          .tickSize(0,0)
          .orient('left');
      }

    },

    renderAxes: function(el) {
      var xel = el.append('g')
        .attr('class', 'axis x xaxis')
        .attr('transform', "translate(0,"+this.state.h+")");
      xel.append('rect')
        .attr('width', this.state.w)
        .attr('height', this.state.bp)
        .attr('fill', 'none')
        .attr('stroke', 'none')
        .style('pointer-events', 'all')
      xel.call(this.state.xaxis)

      var yel = el.append('g')
        .attr('class', 'axis y yaxis')
      yel.append('rect')
        .attr('width', this.state.lp)
        .attr('height', this.state.h)
        .attr('x', -this.state.lp)
        .attr('fill', 'none')
        .attr('stroke', 'none')
        .style('pointer-events', 'all')
      yel.call(this.state.yaxis)

      el.append('g')
        .attr('transform', 'translate('+(this.state.w/2)+','+(this.state.h+25)+')')
        .append('text')
        .data([1])
        .text(this.model.get('x')['expr'])
    },

    renderModifiedData: function(data) {
      this.$(".updated").remove();
      this.c.selectAll('g.data-container')
        .classed('background', false)
      if (!data) {
        return;
      }

      this.setupScales(data);
      this.render();
      this.c.selectAll('g.data-container')
        .classed('background', true)
      var xalias = this.model.get('x').alias;
      var el = this.c.append('g')
          .classed('updated', true)

      _.each(this.model.get('ys'), function(ycol) {
        this.renderData(el, data, xalias, ycol.alias);
      }, this);
    },

    renderData: function(el, data, xalias, yalias) {
      var _this = this;
      var data = _.map(data, function(d) {
        var ret = {
          x: d[xalias],
          y: d[yalias],
          px: _this.state.xscales(d[xalias]),
          py: _this.state.yscales(d[yalias]),
          yalias: yalias
        };
        ret[xalias] = d[xalias];
        ret[yalias] = d[yalias];
        return ret
      });

      var dc = el.append('g')
        .attr('class', 'data-container')

      if (this.state.marktype == 'circle') {
        dc.selectAll('circle')
            .data(data)
          .enter().append('circle')
            .classed('mark', true)
            .attr({
              cx: function(d) { return d.px },
              cy: function(d) { return d.py },
              r: 2,
              fill: this.state.cscales(yalias),
              stroke: this.state.cscales(yalias)
            })
      }
    },

    renderBrush: function(el) {
      var type = this.model.get('schema')[this.model.get('x').col],
          _this = this,
          xscales = this.state.xscales,
          yscales = this.state.yscales,
          xr = 5,
          yr = Math.abs(yscales.invert(0)-yscales.invert(5));

      var brushf = function(p) {
        var e = brush.extent()
        var selected = {};
        el.selectAll('.data-container:not(.background)')
            .selectAll('.mark')
          .classed('selected', function(d){
            if (util.isNum(type)) {
              var minx = xscales(e[0][0]),
                  maxx = xscales(e[1][0]),
                  x    = d.px;
            } else if (util.isTime(type)) {
              var minx = xscales(e[0][0]),
                  maxx = xscales(e[1][0]),
                  x    = d.px;
            } else {
              var minx = e[0][0],
                  maxx = e[1][0],
                  x    = d.px;
            }

            var y = d.y,
                bx = minx <= x+xr && maxx >= x-xr,
                by = e[0][1] <= y+yr && e[1][1] >= y-yr,
                b = bx && by;

            if (b) {
              //console.log([minx, maxx, x, xr, d.x, d.px]);
              var yalias = d.yalias;
              if (!selected[yalias]) selected[yalias] = [];
              selected[yalias].push(d);
            }
            return b;
          })
        if (d3.event.type == 'brushend') {
          _this.trigger('change:selection', selected);
        }
      }

      var brush = d3.svg.brush()
          .x(this.state.xscales)
          .y(this.state.yscales)
          .on('brush', brushf)
          .on('brushend', brushf)
          .on('brushstart', brushf)
      var gbrush = this.gbrush = el.append('g')
          .attr('class', 'brush')
          .call(brush)
      gbrush.selectAll('rect')
          .attr('height', this.state.h)
    },

    disableBrush: function() {
      if (this.gbrush)
        this.gbrush.style("pointer-events", null);
    },
    enableBrush: function() {
      if (this.gbrush)
        this.gbrush.style("pointer-events", 'all');
    },

    brushStatus: function() {
      if (this.gbrush)
        return this.gbrush.style("pointer-events");
    },

    renderZoom: function(el) {
      var _this = this
          yscales = this.state.yscales,
          yaxis = this.state.yaxis,
          xscales = this.state.xscales,
          xaxis = this.state.xaxis;

      function yzoomf() {
        el.select('.axis.y').call(yaxis);
        el.selectAll('.mark')
          .attr('cy', function(d) {
            return yscales(d.y);
          })
          .style('opacity', function(d) {
            if (yscales.range()[0] >= yscales(d.y) &&
                yscales(d.y) >= yscales.range()[1])
              return 1;
            return 0;
          })

      };

      function xzoomf() {
        el.select('.axis.x').call(xaxis);
        el.selectAll('.mark')
          .attr('cx', function(d) {
            return xscales(d.x);
          })
          .style('opacity', function(d) {
            if (xscales.range()[0] <= xscales(d.x) &&
                xscales(d.x) <= xscales.range()[1])
              return 1;
            return 0;
          })
      };

      var yzoom = d3.behavior.zoom()
        .y(this.state.yscales)
        .scaleExtent([1, 100])
        .on('zoom', yzoomf);

      el.select('.axis.y').call(yzoom)
        .on("mousedown.zoom", null)
        .on("touchstart.zoom", null)
        .on("touchmove.zoom", null)
        .on("touchend.zoom", null)

      var xzoom = d3.behavior.zoom()
        .x(this.state.xscales)
        .scaleExtent([1, 100])
        .on('zoom', xzoomf);

      el.select('.axis.x').call(xzoom)
        .on("mousedown.zoom", null)
        .on("touchstart.zoom", null)
        .on("touchmove.zoom", null)
        .on("touchend.zoom", null)
    },

    renderLabels: function() {
      var ys = this.model.get('ys'),
          cscales = this.state.cscales;

      this.$('.legend').remove();
      d3.select(this.el).append("div")
          .attr('class', 'legend')
          .style("margin-left", this.state.lp)
        .selectAll("span")
          .data(ys)
        .enter().append("span")
          .text(function(d) { return d.expr; })
          .style("background", function(d) { return cscales(d.alias); });
    },

    toggleBrushDrawing: function() {
      if (!this.dv) {
        this.enableBrush();
        return;
      }

      if (this.dv.status() == 'all') {
        this.dv.disable();
        this.enableBrush();
      } else {
        this.dv.enable();
        this.disableBrush();
      }
    },

    render: function() {
      if (!this.model.isValid()) {
        this.queryform.render().$el.show()
        this.$svg.hide();
        return this;
      }
      this.$svg.show();
      this.queryform.$el.hide();
      console.log("rendering " + this.model.get('where'))

      $(this.c[0]).empty()

      this.setupScales(this.model.get('data'))
      this.renderAxes(this.c)
      _.each(this.model.get('ys'), function(ycol) {
        this.renderData(
          this.c,
          this.model.get('data'),
          this.model.get('x').alias,
          ycol.alias
        );
      }, this);
      this.renderBrush(this.c);
      this.renderLabels(this.c);
      this.renderZoom(this.c);

      this.dv = new DrawingView({state: this.state});
      this.listenTo(this.dv, "change:drawing", (function() {
        this.trigger('change:drawing', this.dv.model);
      }).bind(this))
      $(this.c[0]).append(this.dv.render().$("g"));
      this.dv.disable();
      this.enableBrush();

      return this;
    }

  });

  return QueryView;
})
<commit_msg>added panning and zooming along y axis<commit_after>define(function(require) {
  var Backbone = require('backbone'),
      Handlebars = require('handlebars'),
      $ = require('jquery'),
      d3 = require('d3'),
      _ = require('underscore'),
      Where = require('summary/where'),
      util = require('summary/util'),
      DrawingView = require('summary/drawingview'),
      QueryForm = require('summary/queryform');

  var QueryView = Backbone.View.extend({
    errtemplate: Handlebars.compile($("#q-err-template").html()),

    defaults: function() {
      return {
        xdomain: null,
        ydomain: null,
        xscales: null,
        yscales: null,
        cscales: d3.scale.category10(),
        xaxis: null,
        yaxis: null,
        series: null,
        w: 500,
        h: 400,
        lp: 60,
        tp: 20,
        bp: 15,
        ip: 5,  // data-container inner padding
        marktype: 'circle'
      };
    },

    initialize: function() {
      this.state = this.defaults();

      this.$svg = $("<svg id='viz'></svg>").prependTo(this.$el);
      this.svg = this.$svg.get()[0];
      this.d3svg = d3.select(this.svg);
      this.d3svg
        .attr('class', 'viz-container')
        .attr('width', this.state.w + this.state.lp)
        .attr('height', this.state.h + this.state.tp + this.state.bp);
      this.c = this.d3svg.append('g')
          .classed("plot-container", true)
          .attr('transform', "translate("+this.state.lp+", 0)");
      this.c.append('rect')
        .attr('width', this.state.w)
        .attr('height', this.state.h)
        .attr('fill', 'none')
        .attr('stroke', 'none')
        .style('pointer-events', 'all')

      this.queryform = new QueryForm({model: this.model});
      this.listenTo(this.queryform, 'submit', this.resetState.bind(this));
      this.$el.append(this.queryform.render().el)

      this.$toggle = $("#q-toggle")
        .addClass("btn btn-primary")
        .css("margin-left", this.state.lp)
        .click((function() {
          this.queryform.render().$el.toggle();
          this.$('.legend').toggle();
          this.$svg.toggle();
        }).bind(this));

      this.listenTo(this.model, 'change:db', this.resetState);
      this.listenTo(this.model, 'change:table', this.resetState);
      this.listenTo(this.model, 'change:data', this.render);
      this.listenTo(this.model, 'fetch:start', this.fetchStart);
      this.listenTo(this.model, 'fetch:end', this.fetchEnd);
    },

    resetState: function() {
      this.state = this.defaults();
      this.yscale = null;
      this.trigger("resetState");
    },

    onChange: function() {
      return;
      this.model.get('where').fetch({
        data: {
          db: this.model.get('db'),
          table: this.model.get('table'),
          nbuckets: 500
        }
      });
    },

    fetchStart: function() {
      $("#q_loading").show();
    },

    fetchEnd: function() {
      $("#q_loading").hide();
    },

    // persistently update scales information
    setupScales: function(data) {
      var schema = this.model.get('schema'),
          xcol = this.model.get('x'),
          xalias = xcol.alias,
          ycols = this.model.get('ys'),
          yaliases = _.pluck(ycols, 'alias'),
          type = schema[xcol.col],
          _this = this,
          ip = this.state.ip,
          xs = _.pluck(data, xalias),
          yss = _.map(yaliases, function(yalias) { return _.pluck(data, yalias) }),
          newCDomain = _.compact(_.union(this.state.cscales.domain(), yaliases)),
          prevxdomain = this.state.xdomain,
          prevydomain = this.state.ydomain;

      this.state.cscales.domain(newCDomain);

      var getx = function(d) { return d[xalias]; },
          xdomain = util.getXDomain(data, type, getx);
      this.state.xdomain = util.mergeDomain(this.state.xdomain, xdomain, type);

      _.each(yss, function(ys) {
        if (this.state.ydomain == null) this.state.ydomain = [Infinity, -Infinity];
        ys = _.filter(ys, _.isFinite);
        if (ys.length) {
          this.state.ydomain[0] = Math.min(this.state.ydomain[0], d3.min(ys));
          this.state.ydomain[1] = Math.max(this.state.ydomain[1], d3.max(ys));
        }
      }, this);

      if (this.state.xscales == null) {
        var xscales = d3.scale.linear();
        if (util.isTime(type)) {
          xscales = d3.time.scale();
        }
        xscales.range([0+ip, this.state.w-ip]);

        if (util.isStr(type)) {
          xscales = d3.scale.ordinal();
          xscales.rangeRoundBands([0+ip, this.state.w-ip], 0.1);
        }
        this.state.xscales = xscales;
      }
      if (this.state.yscales == null) {
        this.state.yscales = d3.scale.linear()
          .range([this.state.h-ip, 0+ip])
      }

      this.state.xscales.domain(this.state.xdomain);
      this.state.yscales.domain(this.state.ydomain);

      if (!this.state.xaxis) {
        this.state.xaxis = d3.svg.axis()
          .scale(this.state.xscales)
          .tickSize(0,0)
          .orient('bottom')
        var nticks = util.estNumXTicks(this.state.xaxis, type, this.state.w);
        util.setAxisLabels(this.state.xaxis, type, nticks);
      }
      if (!this.state.yaxis) {
        this.state.yaxis = d3.svg.axis()
          .scale(this.state.yscales)
          .tickSize(0,0)
          .orient('left');
      }

    },

    renderAxes: function(el) {
      if(el.select('.xaxis').size() == 0) {
        var xel = el.append('g')
          .attr('class', 'axis x xaxis')
          .attr('transform', "translate(0,"+this.state.h+")");
        xel.append('rect')
          .attr('width', this.state.w)
          .attr('height', this.state.bp)
          .attr('fill', 'none')
          .attr('stroke', 'none')
          .style('pointer-events', 'all')
        xel.call(this.state.xaxis)
      } else {
        el.select('.axis.x').call(this.state.xaxis);
      }

      if (el.select('.yaxis').size() == 0) {
        var yel = el.append('g')
          .attr('class', 'axis y yaxis')
        yel.append('rect')
          .attr('width', this.state.lp)
          .attr('height', this.state.h)
          .attr('x', -this.state.lp)
          .attr('fill', 'none')
          .attr('stroke', 'none')
          .style('pointer-events', 'all')
        yel.call(this.state.yaxis)
      } else {
        el.select('.axis.y').call(this.state.yaxis);
      }

      if (el.select('.xaxis-label').size() == 0) {
        el.append('g')
          .classed('xaxis-label', true)
          .attr('transform', 'translate('+(this.state.w/2)+','+(this.state.h+25)+')')
          .append('text')
          .data([1])
          .text(this.model.get('x')['expr'])
      }
    },

    renderModifiedData: function(data) {
      this.$(".updated").remove();
      this.c.selectAll('g.data-container')
        .classed('background', false)
      if (!data) {
        return;
      }

      this.setupScales(data);
      this.render();
      this.c.selectAll('g.data-container')
        .classed('background', true)
      var xalias = this.model.get('x').alias;
      var el = this.c.append('g')
          .classed('updated', true)

      _.each(this.model.get('ys'), function(ycol) {
        this.renderData(el, data, xalias, ycol.alias);
      }, this);
    },

    renderData: function(el, data, xalias, yalias) {
      var _this = this;
      var data = _.map(data, function(d) {
        var ret = {
          x: d[xalias],
          y: d[yalias],
          px: _this.state.xscales(d[xalias]),
          py: _this.state.yscales(d[yalias]),
          yalias: yalias
        };
        ret[xalias] = d[xalias];
        ret[yalias] = d[yalias];
        return ret
      });

      var dc = el.append('g')
        .attr('class', 'data-container')

      if (this.state.marktype == 'circle') {
        dc.selectAll('circle')
            .data(data)
          .enter().append('circle')
            .classed('mark', true)
            .attr({
              cx: function(d) { return d.px },
              cy: function(d) { return d.py },
              r: 2,
              fill: this.state.cscales(yalias),
              stroke: this.state.cscales(yalias)
            })
      }
    },

    renderBrush: function(el) {
      if (el.select('.brush').size() > 0) return;
      var type = this.model.get('schema')[this.model.get('x').col],
          _this = this,
          xscales = this.state.xscales,
          yscales = this.state.yscales,
          xr = 5,
          yr = Math.abs(yscales.invert(0)-yscales.invert(5));

      var brushf = function(p) {
        var e = brush.extent()
        var selected = {};
        el.selectAll('.data-container:not(.background)')
            .selectAll('.mark')
          .classed('selected', function(d){
            if (util.isNum(type)) {
              var minx = xscales(e[0][0]),
                  maxx = xscales(e[1][0]),
                  x    = d.px;
            } else if (util.isTime(type)) {
              var minx = xscales(e[0][0]),
                  maxx = xscales(e[1][0]),
                  x    = d.px;
            } else {
              var minx = e[0][0],
                  maxx = e[1][0],
                  x    = d.px;
            }

            var y = d.y,
                bx = minx <= x+xr && maxx >= x-xr,
                by = e[0][1] <= y+yr && e[1][1] >= y-yr,
                b = bx && by;

            if (b) {
              //console.log([minx, maxx, x, xr, d.x, d.px]);
              var yalias = d.yalias;
              if (!selected[yalias]) selected[yalias] = [];
              selected[yalias].push(d);
            }
            return b;
          })
        if (d3.event.type == 'brushend') {
          _this.trigger('change:selection', selected);
        }
      }

      var brush = d3.svg.brush()
          .x(this.state.xscales)
          .y(this.state.yscales)
          .on('brush', brushf)
          .on('brushend', brushf)
          .on('brushstart', brushf)
      var gbrush = this.gbrush = el.append('g')
          .attr('class', 'brush')
          .call(brush)
      gbrush.selectAll('rect')
          .attr('height', this.state.h)
    },

    disableBrush: function() {
      if (this.gbrush)
        this.gbrush.style("pointer-events", null);
    },
    enableBrush: function() {
      if (this.gbrush)
        this.gbrush.style("pointer-events", 'all');
    },

    brushStatus: function() {
      if (this.gbrush)
        return this.gbrush.style("pointer-events");
    },

    renderZoom: function(el) {
      if (this.yscale) {
        if (el.select('.axis.y').size() > 0) {
          this.yzoom.event(el);
          this.yzoom.scale(this.yscale);
          this.yzoom.event(el);
        }

        return;
      }

      var _this = this
          yscales = this.state.yscales,
          yaxis = this.state.yaxis,
          xscales = this.state.xscales,
          xaxis = this.state.xaxis;

      function yzoomf() {
        el.select('.axis.y').call(yaxis);
        el.selectAll('.mark')
          .attr('cy', function(d) {
            return yscales(d.y);
          })
          .style('opacity', function(d) {
            if (yscales.range()[0] >= yscales(d.y) &&
                yscales(d.y) >= yscales.range()[1])
              return 1;
            return 0;
          })
        _this.yscale = d3.event.scale;

      };

      function xzoomf() {
        el.select('.axis.x').call(xaxis);
        el.selectAll('.mark')
          .attr('cx', function(d) {
            return xscales(d.x);
          })
          .style('opacity', function(d) {
            if (xscales.range()[0] <= xscales(d.x) &&
                xscales(d.x) <= xscales.range()[1])
              return 1;
            return 0;
          })
        _this.xscale = d3.event.scale;
      };

      this.yzoom = yzoom = d3.behavior.zoom()
        .y(this.state.yscales)
        //.scaleExtent([1, 100])
        .on('zoom', yzoomf);

      el.select('.axis.y').call(yzoom)
        .style('cursor', 'ns-resize')

      /*
       this.xzoom = xzoom = d3.behavior.zoom()
        .x(this.state.xscales)
        .scaleExtent([1, 100])
        .on('zoom', xzoomf);

      el.select('.axis.x').call(xzoom)
        .on("mousedown.zoom", null)
        .on("touchstart.zoom", null)
        .on("touchmove.zoom", null)
        .on("touchend.zoom", null)
        */
    },

    renderLabels: function() {
      var ys = this.model.get('ys'),
          cscales = this.state.cscales;

      this.$('.legend').remove();
      d3.select(this.el).append("div")
          .attr('class', 'legend')
          .style("margin-left", this.state.lp)
        .selectAll("span")
          .data(ys)
        .enter().append("span")
          .text(function(d) { return d.expr; })
          .style("background", function(d) { return cscales(d.alias); });
    },

    toggleBrushDrawing: function() {
      if (!this.dv) {
        this.enableBrush();
        return;
      }

      if (this.dv.status() == 'all') {
        this.dv.disable();
        this.enableBrush();
      } else {
        this.dv.enable();
        this.disableBrush();
      }
    },

    render: function() {
      if (!this.model.isValid()) {
        this.queryform.render().$el.show()
        this.$svg.hide();
        return this;
      }
      this.$svg.show();
      this.queryform.$el.hide();
      console.log("rendering " + this.model.get('where'))

      if (!this.state.xaxis) {
        $(this.c[0]).empty();
      } else {
        this.$('.data-container').remove()
      }

      this.setupScales(this.model.get('data'))
      this.renderAxes(this.c)
      _.each(this.model.get('ys'), function(ycol) {
        this.renderData(
          this.c,
          this.model.get('data'),
          this.model.get('x').alias,
          ycol.alias
        );
      }, this);
      this.renderBrush(this.c);
      this.renderLabels(this.c);
      this.renderZoom(this.c);

      this.dv = new DrawingView({state: this.state});
      this.listenTo(this.dv, "change:drawing", (function() {
        this.trigger('change:drawing', this.dv.model);
      }).bind(this))
      $(this.c[0]).append(this.dv.render().$("g"));
      this.dv.disable();
      this.enableBrush();

      return this;
    }

  });

  return QueryView;
})
<|endoftext|>


<commit_before>import React from "react";

import CSSModules from 'react-css-modules';
import styles from "../../../scss/_code-box.scss";

import _ from "lodash";

class SASSView extends React.Component {
  constructor(){
    super();
  }
  render() {
    const{dispatch, sassView, pixelCount, columnCount, rowCount, xPos, yPos, rectColor} = this.props;
    if(sassView){
      let colorStore     = _.uniq(rectColor);
      let xPosSorted     = _.sortBy(xPos);
      let yPosSorted     = _.sortBy(yPos);
      let sassColorStore = []
      let colorVar       = [];
      let xVar           = [];
      let yVar           = [];
      let boxShadowVar   = [];
      let varRectColor   = [];

      colorStore.map(function(value,idx){
        colorVar.push(
          `$color-${idx}: ${value}; `
        )
      });
      rectColor.map(function(value,idx){
         sassColorStore.push(
           `$color-${colorStore.indexOf(value)}`
         )
      });
      //x value array
      for(let x = 0; x < columnCount; x++){
          xVar.push(
            `X${x}: $num*${x}; `
          )
      }
      //y value array
      for(let y = 0; y < rowCount; y++){
        yVar.push(
          `O${y}: $num*${y}; `
        )
      }
      xPos.map(function(value, idx){
        boxShadowVar.push(
          `$X${xPosSorted[idx] / pixelCount} $Y${yPosSorted[idx] / pixelCount} ${sassColorStore[idx]}, `
        )
      });

      return(

         $num: `${pixelCount}`;

         {colorVar}

         {xVar}

         {yVar}

         box-shadow: {boxShadowVar}

      );
    }
    return(

    );

  }

}

export default SASSView;
<commit_msg>Update y value to be O.<commit_after>import React from "react";

import CSSModules from 'react-css-modules';
import styles from "../../../scss/_code-box.scss";

import _ from "lodash";

class SASSView extends React.Component {
  constructor(){
    super();
  }
  render() {
    const{dispatch, sassView, pixelCount, columnCount, rowCount, xPos, yPos, rectColor} = this.props;
    if(sassView){
      let colorStore     = _.uniq(rectColor);
      let xPosSorted     = _.sortBy(xPos);
      let yPosSorted     = _.sortBy(yPos);
      let sassColorStore = []
      let colorVar       = [];
      let xVar           = [];
      let yVar           = [];
      let boxShadowVar   = [];
      let varRectColor   = [];

      colorStore.map(function(value,idx){
        colorVar.push(
          `$color-${idx}: ${value}; `
        )
      });
      rectColor.map(function(value,idx){
         sassColorStore.push(
           `$color-${colorStore.indexOf(value)}`
         )
      });
      //x value array
      for(let x = 0; x < columnCount; x++){
          xVar.push(
            `X${x}: $num*${x}; `
          )
      }
      //y value array
      for(let y = 0; y < rowCount; y++){
        yVar.push(
          `O${y}: $num*${y}; `
        )
      }
      xPos.map(function(value, idx){
        boxShadowVar.push(
          `$X${xPosSorted[idx] / pixelCount} $O${yPosSorted[idx] / pixelCount} ${sassColorStore[idx]}, `
        )
      });

      return(

         $num: `${pixelCount}`;

         {colorVar}

         {xVar}

         {yVar}

         box-shadow: {boxShadowVar}

      );
    }
    return(

    );

  }

}

export default SASSView;
<|endoftext|>


<commit_before>var core = require('../core'),
    tempPoint = new core.Point(),
    CanvasTinter = require('../core/sprites/canvas/CanvasTinter'),
    TilingShader = require('./webgl/TilingShader'),
    tempArray = new Float32Array(4);
/**
 * A tiling sprite is a fast way of rendering a tiling image
 *
 * @class
 * @extends PIXI.Sprite
 * @memberof PIXI.extras
 * @param texture {PIXI.Texture} the texture of the tiling sprite
 * @param width {number}  the width of the tiling sprite
 * @param height {number} the height of the tiling sprite
 */
function TilingSprite(texture, width, height)
{
    core.Sprite.call(this, texture);

    /**
     * The scaling of the image that is being tiled
     *
     * @member {PIXI.Point}
     */
    this.tileScale = new core.Point(1,1);

    /**
     * The offset position of the image that is being tiled
     *
     * @member {PIXI.Point}
     */
    this.tilePosition = new core.Point(0,0);

    ///// private

    /**
     * The with of the tiling sprite
     *
     * @member {number}
     * @private
     */
    this._width = width || 100;

    /**
     * The height of the tiling sprite
     *
     * @member {number}
     * @private
     */
    this._height = height || 100;

    /**
     * An internal WebGL UV cache.
     *
     * @member {PIXI.TextureUvs}
     * @private
     */
    this._uvs = new core.TextureUvs();

    this._canvasPattern = null;

    this._glDatas = [];
}

TilingSprite.prototype = Object.create(core.Sprite.prototype);
TilingSprite.prototype.constructor = TilingSprite;
module.exports = TilingSprite;

Object.defineProperties(TilingSprite.prototype, {
    /**
     * The width of the sprite, setting this will actually modify the scale to achieve the value set
     *
     * @member {number}
     * @memberof PIXI.extras.TilingSprite#
     */
    width: {
        get: function ()
        {
            return this._width;
        },
        set: function (value)
        {
            this._width = value;
        }
    },

    /**
     * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set
     *
     * @member {number}
     * @memberof PIXI.extras.TilingSprite#
     */
    height: {
        get: function ()
        {
            return this._height;
        },
        set: function (value)
        {
            this._height = value;
        }
    }
});

TilingSprite.prototype._onTextureUpdate = function ()
{
    return;
};

/**
 * Renders the object using the WebGL renderer
 *
 * @param renderer {PIXI.WebGLRenderer} The renderer
 * @private
 */
TilingSprite.prototype._renderWebGL = function (renderer)
{

    // tweak our texture temporarily..
    var texture = this._texture;

    if(!texture || !texture._uvs)
    {
        return;
    }

     // get rid of any thing that may be batching.
    renderer.flush();

    var gl = renderer.gl;
    var glData = this._glDatas[renderer.CONTEXT_UID];

    if(!glData)
    {
        glData = {
            shader:new TilingShader(gl),
            quad:new core.Quad(gl)
        };

        this._glDatas[renderer.CONTEXT_UID] = glData;

        glData.quad.initVao(glData.shader);
    }

    // if the sprite is trimmed and is not a tilingsprite then we need to add the extra space before transforming the sprite coords..
    var vertices = glData.quad.vertices;

    vertices[0] = vertices[6] = ( this._width ) * -this.anchor.x;
    vertices[1] = vertices[3] = this._height * -this.anchor.y;

    vertices[2] = vertices[4] = ( this._width ) * (1-this.anchor.x);
    vertices[5] = vertices[7] = this._height * (1-this.anchor.y);

    glData.quad.upload();

    renderer.bindShader(glData.shader);

    var textureUvs = texture._uvs,
        textureWidth = texture._frame.width,
        textureHeight = texture._frame.height,
        textureBaseWidth = texture.baseTexture.width,
        textureBaseHeight = texture.baseTexture.height;

    var uPixelSize = glData.shader.uniforms.uPixelSize;
    uPixelSize[0] = 1.0/textureBaseWidth;
    uPixelSize[1] = 1.0/textureBaseHeight;
    glData.shader.uniforms.uPixelSize = uPixelSize;

    var uFrame = glData.shader.uniforms.uFrame;
    uFrame[0] = textureUvs.x0;
    uFrame[1] = textureUvs.y0;
    uFrame[2] = textureUvs.x1 - textureUvs.x0;
    uFrame[3] = textureUvs.y2 - textureUvs.y0;
    glData.shader.uniforms.uFrame = uFrame;

    var uTransform = glData.shader.uniforms.uTransform;
    uTransform[0] = (this.tilePosition.x % (textureWidth * this.tileScale.x)) / this._width;
    uTransform[1] = (this.tilePosition.y % (textureHeight * this.tileScale.y)) / this._height;
    uTransform[2] = ( textureBaseWidth / this._width ) * this.tileScale.x;
    uTransform[3] = ( textureBaseHeight / this._height ) * this.tileScale.y;
    glData.shader.uniforms.uTransform = uTransform;

    glData.shader.uniforms.translationMatrix = this.worldTransform.toArray(true);

    var color = tempArray;

    core.utils.hex2rgb(this.tint, color);
    color[3] = this.worldAlpha;

    glData.shader.uniforms.uColor = color;

    renderer.bindTexture(this._texture, 0);

    renderer.state.setBlendMode( this.blendMode );
    glData.quad.draw();
};

/**
 * Renders the object using the Canvas renderer
 *
 * @param renderer {PIXI.CanvasRenderer} a reference to the canvas renderer
 * @private
 */
TilingSprite.prototype._renderCanvas = function (renderer)
{
    var texture = this._texture;

    if (!texture.baseTexture.hasLoaded)
    {
      return;
    }

    var context = renderer.context,
        transform = this.worldTransform,
        resolution = renderer.resolution,
        baseTexture = texture.baseTexture,
        modX = (this.tilePosition.x / this.tileScale.x) % texture._frame.width,
        modY = (this.tilePosition.y / this.tileScale.y) % texture._frame.height;

    // create a nice shiny pattern!
    // TODO this needs to be refreshed if texture changes..
    if(!this._canvasPattern)
    {
        // cut an object from a spritesheet..
        var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height);

        // Tint the tiling sprite
        if (this.tint !== 0xFFFFFF)
        {
            if (this.cachedTint !== this.tint)
            {
                this.cachedTint = this.tint;

                this.tintedTexture = CanvasTinter.getTintedTexture(this, this.tint);
            }
            tempCanvas.context.drawImage(this.tintedTexture, 0, 0);
        }
        else
        {
            tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x, -texture._frame.y);
        }
        this._canvasPattern = tempCanvas.context.createPattern( tempCanvas.canvas, 'repeat' );
    }

    // set context state..
    context.globalAlpha = this.worldAlpha;
    context.setTransform(transform.a * resolution,
                       transform.b * resolution,
                       transform.c * resolution,
                       transform.d * resolution,
                       transform.tx * resolution,
                       transform.ty * resolution);

    // TODO - this should be rolled into the setTransform above..
    context.scale(this.tileScale.x,this.tileScale.y);

    context.translate(modX + (this.anchor.x * -this._width ),
                      modY + (this.anchor.y * -this._height));

    // check blend mode
    var compositeOperation = renderer.blendModes[this.blendMode];
    if (compositeOperation !== renderer.context.globalCompositeOperation)
    {
        context.globalCompositeOperation = compositeOperation;
    }

    // fill the pattern!
    context.fillStyle = this._canvasPattern;
    context.fillRect(-modX,
                     -modY,
                     this._width / this.tileScale.x,
                     this._height / this.tileScale.y);

    //TODO - pretty sure this can be deleted...
    //context.translate(-this.tilePosition.x + (this.anchor.x * this._width), -this.tilePosition.y + (this.anchor.y * this._height));
    //context.scale(1 / this.tileScale.x, 1 / this.tileScale.y);
};

/**
 * Returns the framing rectangle of the sprite as a Rectangle object
*
 * @return {PIXI.Rectangle} the framing rectangle
 */
TilingSprite.prototype.getBounds = function ()
{
    var width = this._width;
    var height = this._height;

    var w0 = width * (1-this.anchor.x);
    var w1 = width * -this.anchor.x;

    var h0 = height * (1-this.anchor.y);
    var h1 = height * -this.anchor.y;

    var worldTransform = this.worldTransform;

    var a = worldTransform.a;
    var b = worldTransform.b;
    var c = worldTransform.c;
    var d = worldTransform.d;
    var tx = worldTransform.tx;
    var ty = worldTransform.ty;

    var x1 = a * w1 + c * h1 + tx;
    var y1 = d * h1 + b * w1 + ty;

    var x2 = a * w0 + c * h1 + tx;
    var y2 = d * h1 + b * w0 + ty;

    var x3 = a * w0 + c * h0 + tx;
    var y3 = d * h0 + b * w0 + ty;

    var x4 =  a * w1 + c * h0 + tx;
    var y4 =  d * h0 + b * w1 + ty;

    var minX,
        maxX,
        minY,
        maxY;

    minX = x1;
    minX = x2 < minX ? x2 : minX;
    minX = x3 < minX ? x3 : minX;
    minX = x4 < minX ? x4 : minX;

    minY = y1;
    minY = y2 < minY ? y2 : minY;
    minY = y3 < minY ? y3 : minY;
    minY = y4 < minY ? y4 : minY;

    maxX = x1;
    maxX = x2 > maxX ? x2 : maxX;
    maxX = x3 > maxX ? x3 : maxX;
    maxX = x4 > maxX ? x4 : maxX;

    maxY = y1;
    maxY = y2 > maxY ? y2 : maxY;
    maxY = y3 > maxY ? y3 : maxY;
    maxY = y4 > maxY ? y4 : maxY;

    var bounds = this._bounds;

    bounds.x = minX;
    bounds.width = maxX - minX;

    bounds.y = minY;
    bounds.height = maxY - minY;

    // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
    this._currentBounds = bounds;

    return bounds;
};

/**
 * Checks if a point is inside this tiling sprite
 * @param point {PIXI.Point} the point to check
 */
TilingSprite.prototype.containsPoint = function( point )
{
    this.worldTransform.applyInverse(point,  tempPoint);

    var width = this._width;
    var height = this._height;
    var x1 = -width * this.anchor.x;
    var y1;

    if ( tempPoint.x > x1 && tempPoint.x < x1 + width )
    {
        y1 = -height * this.anchor.y;

        if ( tempPoint.y > y1 && tempPoint.y < y1 + height )
        {
            return true;
        }
    }

    return false;
};

/**
 * Destroys this tiling sprite
 *
 */
TilingSprite.prototype.destroy = function () {
    core.Sprite.prototype.destroy.call(this);

    this.tileScale = null;
    this._tileScaleOffset = null;
    this.tilePosition = null;

    this._uvs = null;
};

/**
 * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId
 * The frame ids are created when a Texture packer file has been loaded
 *
 * @static
 * @param frameId {string} The frame Id of the texture in the cache
 * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId
 * @param width {number}  the width of the tiling sprite
 * @param height {number} the height of the tiling sprite
 * @return {PIXI.extras.TilingSprite} A new TilingSprite
 */
TilingSprite.fromFrame = function (frameId,width,height)
{
    var texture = core.utils.TextureCache[frameId];

    if (!texture)
    {
        throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this);
    }

    return new TilingSprite(texture,width,height);
};

/**
 * Helper function that creates a sprite that will contain a texture based on an image url
 * If the image is not in the texture cache it will be loaded
 *
 * @static
 * @param imageId {string} The image url of the texture
 * @param width {number}  the width of the tiling sprite
 * @param height {number} the height of the tiling sprite
 * @param [crossorigin=(auto)] {boolean} if you want to specify the cross-origin parameter
 * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} if you want to specify the scale mode, see {@link PIXI.SCALE_MODES} for possible values
 * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id
 */
TilingSprite.fromImage = function (imageId, width, height, crossorigin, scaleMode)
{
    return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode),width,height);
};
<commit_msg>added from function to tiling sprite<commit_after>var core = require('../core'),
    tempPoint = new core.Point(),
    Texture = require('../core/textures/Texture'),
    CanvasTinter = require('../core/sprites/canvas/CanvasTinter'),
    TilingShader = require('./webgl/TilingShader'),
    tempArray = new Float32Array(4);
/**
 * A tiling sprite is a fast way of rendering a tiling image
 *
 * @class
 * @extends PIXI.Sprite
 * @memberof PIXI.extras
 * @param texture {PIXI.Texture} the texture of the tiling sprite
 * @param width {number}  the width of the tiling sprite
 * @param height {number} the height of the tiling sprite
 */
function TilingSprite(texture, width, height)
{
    core.Sprite.call(this, texture);

    /**
     * The scaling of the image that is being tiled
     *
     * @member {PIXI.Point}
     */
    this.tileScale = new core.Point(1,1);

    /**
     * The offset position of the image that is being tiled
     *
     * @member {PIXI.Point}
     */
    this.tilePosition = new core.Point(0,0);

    ///// private

    /**
     * The with of the tiling sprite
     *
     * @member {number}
     * @private
     */
    this._width = width || 100;

    /**
     * The height of the tiling sprite
     *
     * @member {number}
     * @private
     */
    this._height = height || 100;

    /**
     * An internal WebGL UV cache.
     *
     * @member {PIXI.TextureUvs}
     * @private
     */
    this._uvs = new core.TextureUvs();

    this._canvasPattern = null;

    this._glDatas = [];
}

TilingSprite.prototype = Object.create(core.Sprite.prototype);
TilingSprite.prototype.constructor = TilingSprite;
module.exports = TilingSprite;

Object.defineProperties(TilingSprite.prototype, {
    /**
     * The width of the sprite, setting this will actually modify the scale to achieve the value set
     *
     * @member {number}
     * @memberof PIXI.extras.TilingSprite#
     */
    width: {
        get: function ()
        {
            return this._width;
        },
        set: function (value)
        {
            this._width = value;
        }
    },

    /**
     * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set
     *
     * @member {number}
     * @memberof PIXI.extras.TilingSprite#
     */
    height: {
        get: function ()
        {
            return this._height;
        },
        set: function (value)
        {
            this._height = value;
        }
    }
});

TilingSprite.prototype._onTextureUpdate = function ()
{
    return;
};

/**
 * Renders the object using the WebGL renderer
 *
 * @param renderer {PIXI.WebGLRenderer} The renderer
 * @private
 */
TilingSprite.prototype._renderWebGL = function (renderer)
{

    // tweak our texture temporarily..
    var texture = this._texture;

    if(!texture || !texture._uvs)
    {
        return;
    }

     // get rid of any thing that may be batching.
    renderer.flush();

    var gl = renderer.gl;
    var glData = this._glDatas[renderer.CONTEXT_UID];

    if(!glData)
    {
        glData = {
            shader:new TilingShader(gl),
            quad:new core.Quad(gl)
        };

        this._glDatas[renderer.CONTEXT_UID] = glData;

        glData.quad.initVao(glData.shader);
    }

    // if the sprite is trimmed and is not a tilingsprite then we need to add the extra space before transforming the sprite coords..
    var vertices = glData.quad.vertices;

    vertices[0] = vertices[6] = ( this._width ) * -this.anchor.x;
    vertices[1] = vertices[3] = this._height * -this.anchor.y;

    vertices[2] = vertices[4] = ( this._width ) * (1-this.anchor.x);
    vertices[5] = vertices[7] = this._height * (1-this.anchor.y);

    glData.quad.upload();

    renderer.bindShader(glData.shader);

    var textureUvs = texture._uvs,
        textureWidth = texture._frame.width,
        textureHeight = texture._frame.height,
        textureBaseWidth = texture.baseTexture.width,
        textureBaseHeight = texture.baseTexture.height;

    var uPixelSize = glData.shader.uniforms.uPixelSize;
    uPixelSize[0] = 1.0/textureBaseWidth;
    uPixelSize[1] = 1.0/textureBaseHeight;
    glData.shader.uniforms.uPixelSize = uPixelSize;

    var uFrame = glData.shader.uniforms.uFrame;
    uFrame[0] = textureUvs.x0;
    uFrame[1] = textureUvs.y0;
    uFrame[2] = textureUvs.x1 - textureUvs.x0;
    uFrame[3] = textureUvs.y2 - textureUvs.y0;
    glData.shader.uniforms.uFrame = uFrame;

    var uTransform = glData.shader.uniforms.uTransform;
    uTransform[0] = (this.tilePosition.x % (textureWidth * this.tileScale.x)) / this._width;
    uTransform[1] = (this.tilePosition.y % (textureHeight * this.tileScale.y)) / this._height;
    uTransform[2] = ( textureBaseWidth / this._width ) * this.tileScale.x;
    uTransform[3] = ( textureBaseHeight / this._height ) * this.tileScale.y;
    glData.shader.uniforms.uTransform = uTransform;

    glData.shader.uniforms.translationMatrix = this.worldTransform.toArray(true);

    var color = tempArray;

    core.utils.hex2rgb(this.tint, color);
    color[3] = this.worldAlpha;

    glData.shader.uniforms.uColor = color;

    renderer.bindTexture(this._texture, 0);

    renderer.state.setBlendMode( this.blendMode );
    glData.quad.draw();
};

/**
 * Renders the object using the Canvas renderer
 *
 * @param renderer {PIXI.CanvasRenderer} a reference to the canvas renderer
 * @private
 */
TilingSprite.prototype._renderCanvas = function (renderer)
{
    var texture = this._texture;

    if (!texture.baseTexture.hasLoaded)
    {
      return;
    }

    var context = renderer.context,
        transform = this.worldTransform,
        resolution = renderer.resolution,
        baseTexture = texture.baseTexture,
        modX = (this.tilePosition.x / this.tileScale.x) % texture._frame.width,
        modY = (this.tilePosition.y / this.tileScale.y) % texture._frame.height;

    // create a nice shiny pattern!
    // TODO this needs to be refreshed if texture changes..
    if(!this._canvasPattern)
    {
        // cut an object from a spritesheet..
        var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height);

        // Tint the tiling sprite
        if (this.tint !== 0xFFFFFF)
        {
            if (this.cachedTint !== this.tint)
            {
                this.cachedTint = this.tint;

                this.tintedTexture = CanvasTinter.getTintedTexture(this, this.tint);
            }
            tempCanvas.context.drawImage(this.tintedTexture, 0, 0);
        }
        else
        {
            tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x, -texture._frame.y);
        }
        this._canvasPattern = tempCanvas.context.createPattern( tempCanvas.canvas, 'repeat' );
    }

    // set context state..
    context.globalAlpha = this.worldAlpha;
    context.setTransform(transform.a * resolution,
                       transform.b * resolution,
                       transform.c * resolution,
                       transform.d * resolution,
                       transform.tx * resolution,
                       transform.ty * resolution);

    // TODO - this should be rolled into the setTransform above..
    context.scale(this.tileScale.x,this.tileScale.y);

    context.translate(modX + (this.anchor.x * -this._width ),
                      modY + (this.anchor.y * -this._height));

    // check blend mode
    var compositeOperation = renderer.blendModes[this.blendMode];
    if (compositeOperation !== renderer.context.globalCompositeOperation)
    {
        context.globalCompositeOperation = compositeOperation;
    }

    // fill the pattern!
    context.fillStyle = this._canvasPattern;
    context.fillRect(-modX,
                     -modY,
                     this._width / this.tileScale.x,
                     this._height / this.tileScale.y);

    //TODO - pretty sure this can be deleted...
    //context.translate(-this.tilePosition.x + (this.anchor.x * this._width), -this.tilePosition.y + (this.anchor.y * this._height));
    //context.scale(1 / this.tileScale.x, 1 / this.tileScale.y);
};

/**
 * Returns the framing rectangle of the sprite as a Rectangle object
*
 * @return {PIXI.Rectangle} the framing rectangle
 */
TilingSprite.prototype.getBounds = function ()
{
    var width = this._width;
    var height = this._height;

    var w0 = width * (1-this.anchor.x);
    var w1 = width * -this.anchor.x;

    var h0 = height * (1-this.anchor.y);
    var h1 = height * -this.anchor.y;

    var worldTransform = this.worldTransform;

    var a = worldTransform.a;
    var b = worldTransform.b;
    var c = worldTransform.c;
    var d = worldTransform.d;
    var tx = worldTransform.tx;
    var ty = worldTransform.ty;

    var x1 = a * w1 + c * h1 + tx;
    var y1 = d * h1 + b * w1 + ty;

    var x2 = a * w0 + c * h1 + tx;
    var y2 = d * h1 + b * w0 + ty;

    var x3 = a * w0 + c * h0 + tx;
    var y3 = d * h0 + b * w0 + ty;

    var x4 =  a * w1 + c * h0 + tx;
    var y4 =  d * h0 + b * w1 + ty;

    var minX,
        maxX,
        minY,
        maxY;

    minX = x1;
    minX = x2 < minX ? x2 : minX;
    minX = x3 < minX ? x3 : minX;
    minX = x4 < minX ? x4 : minX;

    minY = y1;
    minY = y2 < minY ? y2 : minY;
    minY = y3 < minY ? y3 : minY;
    minY = y4 < minY ? y4 : minY;

    maxX = x1;
    maxX = x2 > maxX ? x2 : maxX;
    maxX = x3 > maxX ? x3 : maxX;
    maxX = x4 > maxX ? x4 : maxX;

    maxY = y1;
    maxY = y2 > maxY ? y2 : maxY;
    maxY = y3 > maxY ? y3 : maxY;
    maxY = y4 > maxY ? y4 : maxY;

    var bounds = this._bounds;

    bounds.x = minX;
    bounds.width = maxX - minX;

    bounds.y = minY;
    bounds.height = maxY - minY;

    // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
    this._currentBounds = bounds;

    return bounds;
};

/**
 * Checks if a point is inside this tiling sprite
 * @param point {PIXI.Point} the point to check
 */
TilingSprite.prototype.containsPoint = function( point )
{
    this.worldTransform.applyInverse(point,  tempPoint);

    var width = this._width;
    var height = this._height;
    var x1 = -width * this.anchor.x;
    var y1;

    if ( tempPoint.x > x1 && tempPoint.x < x1 + width )
    {
        y1 = -height * this.anchor.y;

        if ( tempPoint.y > y1 && tempPoint.y < y1 + height )
        {
            return true;
        }
    }

    return false;
};

/**
 * Destroys this tiling sprite
 *
 */
TilingSprite.prototype.destroy = function () {
    core.Sprite.prototype.destroy.call(this);

    this.tileScale = null;
    this._tileScaleOffset = null;
    this.tilePosition = null;

    this._uvs = null;
};

/**
 * Helper function that creates a new tiling sprite based on the source you provide.
 * The source can be - frame id, image url, video url, canvas element, video element, base texture
 *
 * @static
 * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from
* @param width {number}  the width of the tiling sprite
 * @param height {number} the height of the tiling sprite
 * @return {PIXI.Texture} The newly created texture
 */
TilingSprite.from = function (source,width,height)
{
    return new TilingSprite(Texture.from(source),width,height);
};

/**
 * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId
 * The frame ids are created when a Texture packer file has been loaded
 *
 * @static
 * @param frameId {string} The frame Id of the texture in the cache
 * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId
 * @param width {number}  the width of the tiling sprite
 * @param height {number} the height of the tiling sprite
 * @return {PIXI.extras.TilingSprite} A new TilingSprite
 */
TilingSprite.fromFrame = function (frameId,width,height)
{
    var texture = core.utils.TextureCache[frameId];

    if (!texture)
    {
        throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this);
    }

    return new TilingSprite(texture,width,height);
};

/**
 * Helper function that creates a sprite that will contain a texture based on an image url
 * If the image is not in the texture cache it will be loaded
 *
 * @static
 * @param imageId {string} The image url of the texture
 * @param width {number}  the width of the tiling sprite
 * @param height {number} the height of the tiling sprite
 * @param [crossorigin=(auto)] {boolean} if you want to specify the cross-origin parameter
 * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} if you want to specify the scale mode, see {@link PIXI.SCALE_MODES} for possible values
 * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id
 */
TilingSprite.fromImage = function (imageId, width, height, crossorigin, scaleMode)
{
    return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode),width,height);
};
<|endoftext|>


<commit_before>import { useFocusEffect } from '@react-navigation/native';
import { Button, Divider, Layout, Text } from '@ui-kitten/components';
import Constants from 'expo-constants';
import { brand, modelName, osVersion } from 'expo-device';
import { channel, checkForUpdateAsync, fetchUpdateAsync, reloadAsync } from 'expo-updates';
import { useState } from 'react';
import { Alert, ScrollView, StyleSheet, View } from 'react-native';
import 'yup-phone';
import Spinner from '../components/Spinner';
import ValueContainer from '../components/ValueContainer';
import { clearBaseMapCache, getBaseMapCacheSize } from '../services/offline';
import { PADDING } from '../services/styles';

const deleteCacheMessage = 'Deleting cache files...';
const updateMessage = 'Checking for updates...';
export default function AppInfoScreen() {
  const [loaderMessage, setLoaderMessage] = useState(null);
  const [cacheSize, setCacheSize] = useState('calculating...');

  async function forceUpdate() {
    setLoaderMessage(updateMessage);

    if (__DEV__) {
      Alert.alert('Cannot update in development mode.');
    } else {
      const updateCheckResult = await checkForUpdateAsync();
      if (updateCheckResult.isAvailable) {
        await fetchUpdateAsync();
        await reloadAsync();
      } else {
        Alert.alert('No update available', 'You are already running the latest version of the app.');
      }
    }

    setLoaderMessage(null);
  }

  useFocusEffect(() => {
    const getSize = async () => {
      const size = await getBaseMapCacheSize();
      setCacheSize(size);
    };
    getSize();
  });

  const handleClearCache = async () => {
    setLoaderMessage(deleteCacheMessage);
    await clearBaseMapCache();

    setCacheSize(await getBaseMapCacheSize());
    setLoaderMessage(null);
  };

  return (
    <Layout style={styles.container}>
      <ScrollView style={styles.container}>
        <Text style={styles.paragraph} category="p1">
          The Utah Wildlife-Vehicle Collision Reporter app (WVCR) is a smartphone-based system for reporting animals
          that have been involved in vehicle collisions. Data collected from this app will allow UDWR and UDOT to reduce
          wildlife-vehicle collisions and make highways safer for drivers and wildlife.
        </Text>
        <Text category="h5" style={styles.header}>
          App
        </Text>
        <Divider />
        <ValueContainer label="Application Version" value={Constants.manifest2.extra.expoClient.version} />
        <ValueContainer label="Runtime Version" value={Constants.manifest2.runtimeVersion} />
        <ValueContainer label="Build Number" value={Constants.manifest2.extra.expoClient.ios.buildNumber} />
        <ValueContainer label="Release Channel" value={channel || 'dev'} />

        <View style={styles.buttonContainer}>
          <Button onPress={forceUpdate}>Force App Update</Button>
        </View>

        <Text category="h5" style={styles.header}>
          Device
        </Text>
        <Divider />
        <ValueContainer label="Brand" value={brand} />
        <ValueContainer label="Model" value={modelName} />
        <ValueContainer label="OS Version" value={osVersion} />

        <Text category="h5" style={styles.header}>
          Offline Base Map Cache
        </Text>
        <Divider />
        <ValueContainer label="Size" value={cacheSize} />
        <View style={styles.buttonContainer}>
          <Button onPress={handleClearCache}>Clear Cache</Button>
        </View>
      </ScrollView>
      <Spinner show={!!loaderMessage} message={loaderMessage} />
    </Layout>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  header: {
    margin: PADDING,
    marginTop: PADDING * 2,
  },
  buttonContainer: {
    padding: PADDING,
    paddingTop: PADDING * 2,
  },
  paragraph: {
    paddingHorizontal: PADDING,
    paddingTop: PADDING,
    textAlign: 'justify',
  },
});
<commit_msg>fix(front): prefer updates manifest and fall back to constants version<commit_after>import { useFocusEffect } from '@react-navigation/native';
import { Button, Divider, Layout, Text } from '@ui-kitten/components';
import Constants from 'expo-constants';
import { brand, modelName, osVersion } from 'expo-device';
import { channel, checkForUpdateAsync, fetchUpdateAsync, manifest as updatesManifest, reloadAsync } from 'expo-updates';
import { useState } from 'react';
import { Alert, ScrollView, StyleSheet, View } from 'react-native';
import 'yup-phone';
import Spinner from '../components/Spinner';
import ValueContainer from '../components/ValueContainer';
import { clearBaseMapCache, getBaseMapCacheSize } from '../services/offline';
import { PADDING } from '../services/styles';

const deleteCacheMessage = 'Deleting cache files...';
const updateMessage = 'Checking for updates...';
console.log('Constants.manifest2', JSON.stringify(Constants.manifest2, null, 2));
console.log('manifest from Updates', JSON.stringify(updatesManifest, null, 2));
const manifest = Object.keys(updatesManifest).length ? updatesManifest : Constants.manifest2;

export default function AppInfoScreen() {
  const [loaderMessage, setLoaderMessage] = useState(null);
  const [cacheSize, setCacheSize] = useState('calculating...');

  async function forceUpdate() {
    setLoaderMessage(updateMessage);

    if (__DEV__) {
      Alert.alert('Cannot update in development mode.');
    } else {
      const updateCheckResult = await checkForUpdateAsync();
      if (updateCheckResult.isAvailable) {
        await fetchUpdateAsync();
        await reloadAsync();
      } else {
        Alert.alert('No update available', 'You are already running the latest version of the app.');
      }
    }

    setLoaderMessage(null);
  }

  useFocusEffect(() => {
    const getSize = async () => {
      const size = await getBaseMapCacheSize();
      setCacheSize(size);
    };
    getSize();
  });

  const handleClearCache = async () => {
    setLoaderMessage(deleteCacheMessage);
    await clearBaseMapCache();

    setCacheSize(await getBaseMapCacheSize());
    setLoaderMessage(null);
  };

  return (
    <Layout style={styles.container}>
      <ScrollView style={styles.container}>
        <Text style={styles.paragraph} category="p1">
          The Utah Wildlife-Vehicle Collision Reporter app (WVCR) is a smartphone-based system for reporting animals
          that have been involved in vehicle collisions. Data collected from this app will allow UDWR and UDOT to reduce
          wildlife-vehicle collisions and make highways safer for drivers and wildlife.
        </Text>
        <Text category="h5" style={styles.header}>
          App
        </Text>
        <Divider />
        <ValueContainer label="Application Version" value={manifest.extra.expoClient.version} />
        <ValueContainer label="Runtime Version" value={manifest.runtimeVersion} />
        <ValueContainer label="Build Number" value={manifest.extra.expoClient.ios.buildNumber} />
        <ValueContainer label="Release Channel" value={channel || 'dev'} />

        <View style={styles.buttonContainer}>
          <Button onPress={forceUpdate}>Force App Update</Button>
        </View>

        <Text category="h5" style={styles.header}>
          Device
        </Text>
        <Divider />
        <ValueContainer label="Brand" value={brand} />
        <ValueContainer label="Model" value={modelName} />
        <ValueContainer label="OS Version" value={osVersion} />

        <Text category="h5" style={styles.header}>
          Offline Base Map Cache
        </Text>
        <Divider />
        <ValueContainer label="Size" value={cacheSize} />
        <View style={styles.buttonContainer}>
          <Button onPress={handleClearCache}>Clear Cache</Button>
        </View>
      </ScrollView>
      <Spinner show={!!loaderMessage} message={loaderMessage} />
    </Layout>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  header: {
    margin: PADDING,
    marginTop: PADDING * 2,
  },
  buttonContainer: {
    padding: PADDING,
    paddingTop: PADDING * 2,
  },
  paragraph: {
    paddingHorizontal: PADDING,
    paddingTop: PADDING,
    textAlign: 'justify',
  },
});
<|endoftext|>


<commit_before>const EventEmitter = require('eventemitter2').EventEmitter2;

function filter(v, min, max) {
    v = Math.min(v, max);
    v = Math.max(v, min);
    return v;
}

class HitPoint extends EventEmitter {
    constructor(current, max) {
        super();
        this.max = max;
        this.min = 0;
        this.current = this.change(current);
    };

    change(next) {
        this.current = filter(next, 0, this.max);;
        this.emit("changed", {
            next: this
        });
        return this;
    }

    empty() {
        return this.current <= this.min;
    };
}

module.exports = HitPoint;
<commit_msg>Fix for test<commit_after>const EventEmitter = require('eventemitter2').EventEmitter2;

function filter(v, min, max) {
    v = Math.min(v, max);
    v = Math.max(v, min);
    return v;
}

class HitPoint extends EventEmitter {
    constructor(current, max) {
        super();
        this.max = max;
        this.min = 0;
        this.current = filter(current, 0, this.max);
    };

    change(next) {
        this.current = filter(next, 0, this.max);;
        this.emit("changed", {
            next: this
        });
        return this;
    }

    empty() {
        return this.current <= this.min;
    };
}

module.exports = HitPoint;
<|endoftext|>


<commit_before>/**
 * Created by truthlighting on 9/20/2016.
 */
module.exports =
{
    initSpawnQue: function()
    {
        if(Memory.spawnQue == undefined)
            Memory.spawnQue = [ ];
    },

    addToQue: function(creep, unshift)
    {
        this.initSpawnQue();

        if(unshift != undefined && unshift === true)
            Memory.spawnQue.unshift(creep);
        else
            Memory.spawnQue.push(creep);
    },

    spawnNextInQue: function()
    {

        this.initSpawnQue();

        if(!Memory.spawnQue.length)
            return;

        var spawns = Game.rooms['W2N48'].find(FIND_MY_SPAWNS, {
            filter: function(spawn)
            {
                return spawn.spawning === undefined || spawn.spawning === null;
            }
        });
        //console.log(spawns);

        if(!spawns.length)
            return;

        var role = Memory.spawnQue[0];

        if(typeof role == "string")
        {
            role = { type: role, memory: { } };
        }

        var me = this;
        //console.log(spawns);
        var toSpawnAt = spawns.filter(function(spawn)
        {
            //console.log("spawn: " + spawn + " role.type: " + role.type);
            //console.log(me.canSpawn(spawn, role.type));
            return me.canSpawn(spawn, role.type);
        });
        //console.log(toSpawnAt.length);
        if(!toSpawnAt.length)
            return;
        //console.log("getting here1");
        toSpawnAt = toSpawnAt[0];
        this.spawn(role.type, role.memory, toSpawnAt);

        Memory.spawnQue.shift();
    },

    spawn: function(role, memory, spawnPoint)
    {
        if(!spawnPoint)
            spawnPoint = Game.spawns['Harmony'];

        var manager = require('roleManager');

        if(!manager.roleExists(role))
        {
            return;
        }

        if(!this.canSpawn(spawnPoint, role))
        {
            return;
        }

        if(memory == undefined)
            memory = { };

        memory['role'] = role;

        var nameCount = 0;
        var name = null;
        while(name == null)
        {
            nameCount++;
            var tryName = role + nameCount;
            if(Game.creeps[tryName] == undefined)
                name = tryName;
        }

        console.log('Spawning ' + role);
        console.log(spawnPoint.createCreep(manager.getRoleBodyParts(role), name, memory));
    },

    canSpawn: function(spawnPoint, role)
    {
        if(typeof spawnPoint == "string" && role == undefined)
        {
            role = spawnPoint;
            spawnPoint = Game.spawns['Harmony'];
        }
        //console.log(role);
        return spawnPoint.energy >= this.spawnCost(role)
            && (spawnPoint.spawning == null
            || spawnPoint.spawning == undefined);
    },

    spawnCost: function(role)
    {
        var manager = require('roleManager');
        var parts = manager.getRoleBodyParts(role);

        var total = 0;
        for(var index in parts)
        {
            var part = parts[index];
            switch(part)
            {
                case MOVE:
                    total += 50
                    break;

                case WORK:
                    total += 100
                    break;

                case CARRY:
                    total += 50
                    break;

                case ATTACK:
                    total += 80
                    break;

                case RANGED_ATTACK:
                    total += 150
                    break;

                case HEAL:
                    total += 250
                    break;

                case TOUGH:
                    total += 10
                    break;

                case CLAIM:
                    total += 600
            }
        }
        console.log("total cost for " + role + ": " + total);
        return total;
    },

    killAll: function(role)
    {
        for(var i in Game.creeps) {
            if(role == undefined || Game.creeps[i].memory.role == role)
                Game.creeps[i].suicide();
        }
    }
}<commit_msg>Fixing miner<commit_after>/**
 * Created by truthlighting on 9/20/2016.
 */
module.exports =
{
    initSpawnQue: function()
    {
        if(Memory.spawnQue == undefined)
            Memory.spawnQue = [ ];
    },

    addToQue: function(creep, unshift)
    {
        this.initSpawnQue();

        if(unshift != undefined && unshift === true)
            Memory.spawnQue.unshift(creep);
        else
            Memory.spawnQue.push(creep);
    },

    spawnNextInQue: function()
    {

        this.initSpawnQue();

        if(!Memory.spawnQue.length)
            return;

        var spawns = Game.rooms['W2N48'].find(FIND_MY_SPAWNS, {
            filter: function(spawn)
            {
                return spawn.spawning === undefined || spawn.spawning === null;
            }
        });
        //console.log(spawns);

        if(!spawns.length)
            return;

        var role = Memory.spawnQue[0];

        if(typeof role == "string")
        {
            role = { type: role, memory: { } };
        }

        var me = this;
        //console.log(spawns);
        var toSpawnAt = spawns.filter(function(spawn)
        {
            //console.log("spawn: " + spawn + " role.type: " + role.type);
            //console.log(me.canSpawn(spawn, role.type));
            return me.canSpawn(spawn, role.type);
        });
        //console.log(toSpawnAt.length);
        if(!toSpawnAt.length)
            return;
        //console.log("getting here1");
        toSpawnAt = toSpawnAt[0];
        this.spawn(role.type, role.memory, toSpawnAt);

        Memory.spawnQue.shift();
    },

    spawn: function(role, memory, spawnPoint)
    {
        if(!spawnPoint)
            spawnPoint = Game.spawns['Harmony'];

        var manager = require('roleManager');

        if(!manager.roleExists(role))
        {
            return;
        }

        if(!this.canSpawn(spawnPoint, role))
        {
            return;
        }

        if(memory == undefined)
            memory = { };

        memory['role'] = role;

        var nameCount = 0;
        var name = null;
        while(name == null)
        {
            nameCount++;
            var tryName = role + nameCount;
            if(Game.creeps[tryName] == undefined)
                name = tryName;
        }

        console.log('Spawning ' + role);
        console.log(spawnPoint.createCreep(manager.getRoleBodyParts(role), name, memory));
    },

    canSpawn: function(spawnPoint, role)
    {
        if(typeof spawnPoint == "string" && role == undefined)
        {
            role = spawnPoint;
            spawnPoint = Game.spawns['Harmony'];
        }
        //console.log(role);
        return spawnPoint.energy >= this.spawnCost(role)
            && (spawnPoint.spawning == null
            || spawnPoint.spawning == undefined);
    },

    spawnCost: function(role)
    {
        var manager = require('roleManager');
        var parts = manager.getRoleBodyParts(role);

        var total = 0;
        for(var index in parts)
        {
            var part = parts[index];
            switch(part)
            {
                case MOVE:
                    total += 50
                    break;

                case WORK:
                    total += 100
                    break;

                case CARRY:
                    total += 50
                    break;

                case ATTACK:
                    total += 80
                    break;

                case RANGED_ATTACK:
                    total += 150
                    break;

                case HEAL:
                    total += 250
                    break;

                case TOUGH:
                    total += 10
                    break;

                case CLAIM:
                    total += 600
            }
        }
        console.log("parts: " + parts);
        console.log("total cost for " + role + ": " + total);
        return total;
    },

    killAll: function(role)
    {
        for(var i in Game.creeps) {
            if(role == undefined || Game.creeps[i].memory.role == role)
                Game.creeps[i].suicide();
        }
    }
}<|endoftext|>


<commit_before>/**
 * Untappd beer IDs.
 */
exports.ids = [
  // Workhorse IPA
  8784,
  // Anthem Pear Cider
  47454
];

<commit_msg>Updating beer.<commit_after>/**
 * Untappd beer IDs.
 */
exports.ids = [
  // Workhorse IPA
  8784,
  // Widmer Hefeweizen
  6395
];

<|endoftext|>