<commit_before>var expect = require('chai').expect,
    linz = require('../linz'),
    mongoose;

// init linz
linz.init({
    'mongo': 'mongodb://127.0.0.1/mongoose-formtools-test',
    'user model': 'user',
    'load models': false,
    'load configs': false
});

mongoose = linz.mongoose;

describe('Linz has an api', function () {

    var UserSchema = new mongoose.Schema({ label: String }),
        UserModel = mongoose.model('user', UserSchema);

	describe('has a getAdminLink method', function () {

        it('it should default to the admin path', function () {
            expect(linz.api.url.getAdminLink()).to.equal('/admin');
        });

        describe("on models", function () {

            it('it should allow a list action', function () {
                expect(linz.api.url.getAdminLink(mongoose.model('user'))).to.equal('/admin/model/user/list');
                expect(linz.api.url.getAdminLink(mongoose.model('user'), 'list')).to.equal('/admin/model/user/list');
            });

            it('it should allow a create action', function () {
                expect(linz.api.url.getAdminLink(mongoose.model('user'), 'create')).to.equal('/admin/model/user/create');
            });

            it('it should return the model listing url', function () {
                expect(linz.api.url.getAdminLink(undefined, 'list')).to.equal('/admin/models/list');
            });
        });

        describe("on records", function () {

            it('it should allow an overview action', function () {
                expect(linz.api.url.getAdminLink(mongoose.model('user'), undefined, 'id')).to.equal('/admin/model/user/id/overview');
                expect(linz.api.url.getAdminLink(mongoose.model('user'), 'overview', 'id')).to.equal('/admin/model/user/id/overview');
            });

            it('it should allow an edit action', function () {
                expect(linz.api.url.getAdminLink(mongoose.model('user'), 'edit', 'id')).to.equal('/admin/model/user/id/edit');
            });

            it('it should allow a save action', function () {
                expect(linz.api.url.getAdminLink(mongoose.model('user'), 'save', 'id')).to.equal('/admin/model/user/id/save');
            });

            it('it should allow a delete action', function () {
                expect(linz.api.url.getAdminLink(mongoose.model('user'), 'delete', 'id')).to.equal('/admin/model/user/id/delete');
            });

        });

        describe("on configs", function () {

            var config = {
                    schema: new mongoose.Schema({ label: String }),
                    config: { label: ''},
                    modelName: 'config'
            };

            it('it should allow an overview action', function () {
                expect(linz.api.url.getAdminLink(config, undefined, 'id')).to.equal('/admin/config/id/overview');
                expect(linz.api.url.getAdminLink(config, 'overview', 'id')).to.equal('/admin/config/id/overview');
            });

            it('it should allow an edit action', function () {
                expect(linz.api.url.getAdminLink(config, 'edit', 'id')).to.equal('/admin/config/id/edit');
            });

            it('it should allow a save action', function () {
                expect(linz.api.url.getAdminLink(config, 'save', 'id')).to.equal('/admin/config/id/save');
            });

            it('it should allow a delete action', function () {
                expect(linz.api.url.getAdminLink(config, 'delete', 'id')).to.equal('/admin/config/id/delete');
            });

            it('it should return the config listing url', function () {
                expect(linz.api.url.getAdminLink(config, 'list')).to.equal('/admin/configs/list');
            });

        });

	}); // end describe('has a getAdminLink method')

    describe('has a getLink method', function () {

        it('it should default to the admin path', function () {
            expect(linz.api.url.getLink()).to.equal('/admin');
        });

        it('it should generate url with one query parameter', function () {
            expect(linz.api.url.getLink(['one'])).to.equal('/admin/one');
        });

        it('it should generate url with multiple query parameters', function () {
            expect(linz.api.url.getLink(['one','two','three'])).to.equal('/admin/one/two/three');
        });

    });

});
<commit_msg>Fixed a wrong test case.<commit_after>var expect = require('chai').expect,
    linz = require('../linz'),
    mongoose;

// init linz
linz.init({
    'mongo': 'mongodb://127.0.0.1/mongoose-formtools-test',
    'user model': 'user',
    'load models': false,
    'load configs': false
});

mongoose = linz.mongoose;

describe('Linz has an api', function () {

    var UserSchema = new mongoose.Schema({ label: String }),
        UserModel = mongoose.model('user', UserSchema);

	describe('has a getAdminLink method', function () {

        it('it should default to the admin path', function () {
            expect(linz.api.url.getAdminLink()).to.equal('/admin');
        });

        describe("on models", function () {

            it('it should allow a list action', function () {
                expect(linz.api.url.getAdminLink(mongoose.model('user'))).to.equal('/admin/model/user/list');
                expect(linz.api.url.getAdminLink(mongoose.model('user'), 'list')).to.equal('/admin/model/user/list');
            });

            it('it should allow a create action', function () {
                expect(linz.api.url.getAdminLink(mongoose.model('user'), 'create')).to.equal('/admin/model/user/create');
            });

            it('it should return the model listing url', function () {
                expect(linz.api.url.getAdminLink(undefined, 'list')).to.equal('/admin/models/list');
            });
        });

        describe("on records", function () {

            it('it should allow an overview action', function () {
                expect(linz.api.url.getAdminLink(mongoose.model('user'), undefined, 'id')).to.equal('/admin/model/user/id/overview');
                expect(linz.api.url.getAdminLink(mongoose.model('user'), 'overview', 'id')).to.equal('/admin/model/user/id/overview');
            });

            it('it should allow an edit action', function () {
                expect(linz.api.url.getAdminLink(mongoose.model('user'), 'edit', 'id')).to.equal('/admin/model/user/id/edit');
            });

            it('it should allow a save action', function () {
                expect(linz.api.url.getAdminLink(mongoose.model('user'), 'save', 'id')).to.equal('/admin/model/user/id/save');
            });

            it('it should allow a delete action', function () {
                expect(linz.api.url.getAdminLink(mongoose.model('user'), 'delete', 'id')).to.equal('/admin/model/user/id/delete');
            });

        });

        describe("on configs", function () {

            var config = {
                    schema: new mongoose.Schema({ label: String }),
                    config: { label: ''},
                    modelName: 'config'
            };

            it('it should allow an overview action', function () {
                expect(linz.api.url.getAdminLink(config, undefined, 'id')).to.equal('/admin/config/id/overview');
                expect(linz.api.url.getAdminLink(config, 'overview', 'id')).to.equal('/admin/config/id/overview');
            });

            it('it should allow an edit action', function () {
                expect(linz.api.url.getAdminLink(config, 'edit', 'id')).to.equal('/admin/config/id/edit');
            });

            it('it should allow a save action', function () {
                expect(linz.api.url.getAdminLink(config, 'save', 'id')).to.equal('/admin/config/id/save');
            });

            it('it should allow a delete action', function () {
                expect(linz.api.url.getAdminLink(config, 'delete', 'id')).to.equal('/admin/config/id/delete');
            });

            it('it should return the config listing url', function () {
                expect(linz.api.url.getAdminLink(config, 'list')).to.equal('/admin/configs/list');
            });

        });

	}); // end describe('has a getAdminLink method')

    describe('has a getLink method', function () {

        it('it should default to the admin path', function () {
            expect(linz.api.url.getLink()).to.equal('/admin');
        });

        it('it should generate url with one query parameter', function () {
            expect(linz.api.url.getLink('one')).to.equal('/admin/one');
        });

        it('it should generate url with multiple query parameters', function () {
            expect(linz.api.url.getLink('one', 'two', 'three')).to.equal('/admin/one/two/three');
        });

    });

});
<|endoftext|>


<commit_before>var dict = ["unloaded"];
var button, textarea, result;

// construct XMLHttpRequest variable
var xhr;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
    xhr = new XMLHttpRequest();
}
else { // code for IE6, IE5
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

xhr.onreadystatechange = function()
{
    if (xhr.readyState==4 && xhr.status==200)
    {
        dict = xhr.responseText.split(" ");
        console.log("dict received. length: " + dict.length);
    }
}

xhr.open("GET","dict.txt",true);
xhr.send();

var displayResult = function() {
    var numberString = textarea.value;
    var number;

    // check if number is a positive integer >= 10
    if(numberString.length > 1 && isNormaInteger(numberString)) {
        number = parseInt(numberString);
    } else {
        console.log("invalid string");
        return;
    }

    // how many digits/words long the number is
    // = logBase(num, base=dict-length) + 1, rounded down
    var digitCount = Math.floor(Math.log(number) / Math.log(dict.length) + 1);

    var numPhrase = "";

    for(var i = 0; i < digitCount; i++) {
        var newWord = dict[number % dict.length];
        numPhrase = newWord = " " + numPhrase;
        number = Math.floor(number/dict.length);
    }

    console.log("finished! Number: " + numPhrase);
    result.innerText = "Your number: " + numPhrase;
}

// returns whether a string is an integer > 0
// might not work with 0 or 1 index-long non-integer strings
var isNormalInteger = function (str) {
    var n = ~~Number(str);
    return String(n) === str && n >= 0;
}

window.onload = function(e){
    button = document.getElementById("submit");
    textarea = document.getElementById("number");
    result = document.getElementById("result");

    // add event listener to the button to execute displayResult()
    if (button.addEventListener) {
        button.addEventListener("submit", function (evt) {
                                evt.preventDefault();
                                displayResult();
                                }, true);
    } else {
        button.attachEvent('onsubmit', function (evt) {
                           evt.preventDefault();
                           displayResult();
                           });
    }
}
<commit_msg>Rearranged function order<commit_after>var dict = ["unloaded"];
var button, textarea, result;

// construct XMLHttpRequest variable
var xhr;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
    xhr = new XMLHttpRequest();
}
else { // code for IE6, IE5
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

xhr.onreadystatechange = function()
{
    if (xhr.readyState==4 && xhr.status==200)
    {
        dict = xhr.responseText.split(" ");
        console.log("dict received. length: " + dict.length);
    }
}

xhr.open("GET","dict.txt",true);
xhr.send();

// returns whether a string is an integer > 0
// might not work with 0 or 1 index-long non-integer strings
var isNormalInteger = function (str) {
    var n = ~~Number(str);
    return String(n) === str && n >= 0;
}

var displayResult = function() {
    var numberString = textarea.value;
    var number;

    // check if number is a positive integer >= 10
    if(numberString.length > 1 && isNormaInteger(numberString)) {
        number = parseInt(numberString);
    } else {
        console.log("invalid string");
        return;
    }

    // how many digits/words long the number is
    // = logBase(num, base=dict-length) + 1, rounded down
    var digitCount = Math.floor(Math.log(number) / Math.log(dict.length) + 1);

    var numPhrase = "";

    for(var i = 0; i < digitCount; i++) {
        var newWord = dict[number % dict.length];
        numPhrase = newWord = " " + numPhrase;
        number = Math.floor(number/dict.length);
    }

    console.log("finished! Number: " + numPhrase);
    result.innerText = "Your number: " + numPhrase;
}

window.onload = function(e){
    button = document.getElementById("submit");
    textarea = document.getElementById("number");
    result = document.getElementById("result");

    // add event listener to the button to execute displayResult()
    if (button.addEventListener) {
        button.addEventListener("submit", function (evt) {
                                evt.preventDefault();
                                displayResult();
                                }, true);
    } else {
        button.attachEvent('onsubmit', function (evt) {
                           evt.preventDefault();
                           displayResult();
                           });
    }
}
<|endoftext|>


<commit_before>

// Player(id, path, parts);

// Parameters:
//     - id {String} id of div for video player
//     - path {String} path with video files
//     - parts {Number} count of 10sec parts

// Examples:
//     var player = new Player('video', '/users/1/video/2/', 40);
//     player.startVideo();

function Player(elementId , video_path, duration){
  this.videoPath  = video_path;
  this.highPath   = this.videoPath+'/720/';
  this.mediumPath = this.videoPath+'/360/';
  this.poorPath   = this.videoPath+'/240/';
  this.globalId   = elementId;
  this.counter = 0;
  this.partCounter = 0;
  this.playable = true;
  this.inner = '';
  this.parts = duration;
  this.quality = 1;
  this.lock = true;
  this.newTime = false;

  this.createDom();
}
Player.prototype.createVideo = function(itemId){
  item = document.getElementById(itemId);
  if(item){
    return false;
  }
  item = document.createElement('video');
  item.setAttribute('id', itemId);
  inner = '<source src="'+(this.getPath()+this.counter)+'.mp4" type="video/mp4">'
  item.innerHTML = inner;
  item.style.display = 'none';

  startTime = (new Date()).getTime();
  this.lock = false;
  item.load()
  this.lock = true;

  endTime = (new Date()).getTime();
  this.setPath(endTime-startTime);

  player.playerItem.appendChild(item);
}

Player.prototype.hideVideo = function(itemId){
  item = document.getElementById(itemId);
  if(item){
    item.pause();
    item.currentTime = 0;
    item.style.display = 'none';
  }
}

Player.prototype.showVideo = function(itemId){
  item = document.getElementById(itemId);
  item.play();
  item.style.display = 'block';
  item.style.width   = '100%';
  item.style.height  = '100%';
}
Player.prototype.update = function() {

  if((this.counter<this.parts)&&(this.partCounter%10==0)&&this.playable){
    this.partCounter = 0;

    if(this.counter == 0 || this.newTime) {
      this.newTime = false;

      newVideoId = this.globalId+this.counter;

      this.createVideo(newVideoId);
      this.showVideo(newVideoId);

      this.counter++;
      this.newVideoId = this.globalId+this.counter;

      this.createVideo(this.newVideoId);

    } else {

      this.oldVideoId = this.globalId+(this.counter-1);
      this.hideVideo(this.oldVideoId);

      this.currentVideoId = this.globalId+this.counter;
      this.showVideo(this.currentVideoId);

      this.counter++;
      this.newVideoId = this.globalId+this.counter;

      this.createVideo(player.newVideoId);
    }
  }

  // console.log($('.player-controls.rewind'));
  $('.player-controls.rewind').val(this.counter);

  if(this.playable&&this.lock){
    this.partCounter++;
  }
}

Player.prototype.pauseVideo = function(){
  itemId = player.globalId+(player.counter-1);
  item = document.getElementById(itemId);
  item.pause();
  player.playable = false;
}
Player.prototype.playVideo = function(){
  itemId = player.globalId+(player.counter-1);
  item = document.getElementById(itemId);
  item.play();
  player.playable = true;
}

Player.prototype.startVideo = function(){
  this.update();
  var fuck = this; // hack for 'this' forwarding into update
  setInterval(function(){fuck.update.call(fuck)}, 1000);

}

Player.prototype.setPath = function(time){

 if(time<5){
    switch(this.quality){
      case 0:
        this.quality=1;
        break;
      case 1:
        this.quality=2;
        break;
    }
  } else {
    switch(this.quality){
      case 2:
        this.quality=1;
        break;
      case 1:
        this.quality=0;
        break;
    }
  }
}

Player.prototype.getPath = function(){
  switch(this.quality){
    case 0:
      return this.poorPath;
    case 1:
      return this.mediumPath;
    case 2:
      return this.highPath;
  }
}

Player.prototype.goTo = function(value) {
  this.partCounter = 0;
  this.hideVideo(this.globalId + (this.counter - 1));
  this.newTime = true;
  this.counter = value;
}

Player.prototype.createDom = function(){
  $('#' + this.globalId).append('

')
  $('#' + this.globalId).append('

')
  $('#' + this.globalId).append('

')
  $('#' + this.globalId + ' .play-controls').append('<button class="player-controls play">Play</button>')
  $('#' + this.globalId + ' .play-controls').append('<button class="player-controls pause">Pause</button>')
  $('#' + this.globalId + ' .rewind-controls').append('<input class="player-controls rewind" type="range" min="0" max="'+this.parts+'" value="0" />')

  this.playerItem = document.getElementById('player_videos');
  this.setEvents()
}

Player.prototype.setEvents = function(){
  $('.player-controls.play').on('click', { player: this }, function(event){
    event.data.player.playVideo();
  })

  $('.player-controls.pause').on('click', { player: this }, function(event){
    event.data.player.pauseVideo();
  })

  $('.player-controls.rewind').on('change', { player: this }, function(event){
    event.data.player.goTo($(this).val());
  })
}<commit_msg>player fix<commit_after>

// Player(id, path, parts);

// Parameters:
//     - id {String} id of div for video player
//     - path {String} path with video files
//     - parts {Number} count of 10sec parts

// Examples:
//     var player = new Player('video', '/users/1/video/2/', 40);
//     player.startVideo();

function Player(elementId , video_path, duration){
  this.videoPath  = video_path;
  this.highPath   = this.videoPath+'/720/';
  this.mediumPath = this.videoPath+'/360/';
  this.poorPath   = this.videoPath+'/240/';
  this.globalId   = elementId;
  this.counter = 0;
  this.partCounter = 0;
  this.playable = true;
  this.inner = '';
  this.parts = duration;
  this.quality = 1;
  this.lock = true;
  this.newTime = false;

  this.createDom();
}
Player.prototype.createVideo = function(itemId){
  item = document.getElementById(itemId);
  if(item){
    return false;
  }
  item = document.createElement('video');
  item.setAttribute('id', itemId);
  inner = '<source src="'+(this.getPath()+this.counter)+'.mp4" type="video/mp4">'
  item.innerHTML = inner;
  item.style.display = 'none';

  startTime = (new Date()).getTime();
  this.lock = false;
  item.load()
  this.lock = true;

  endTime = (new Date()).getTime();
  this.setPath(endTime-startTime);

  this.playerItem.appendChild(item);
}

Player.prototype.hideVideo = function(itemId){
  item = document.getElementById(itemId);
  if(item){
    item.pause();
    item.currentTime = 0;
    item.style.display = 'none';
  }
}

Player.prototype.showVideo = function(itemId){
  item = document.getElementById(itemId);
  item.play();
  item.style.display = 'block';
  item.style.width   = '100%';
  item.style.height  = '100%';
}
Player.prototype.update = function() {

  if((this.counter<this.parts)&&(this.partCounter%10==0)&&this.playable){
    this.partCounter = 0;

    if(this.counter == 0 || this.newTime) {
      this.newTime = false;

      newVideoId = this.globalId+this.counter;

      this.createVideo(newVideoId);
      this.showVideo(newVideoId);

      this.counter++;
      this.newVideoId = this.globalId+this.counter;

      this.createVideo(this.newVideoId);

    } else {

      this.oldVideoId = this.globalId+(this.counter-1);
      this.hideVideo(this.oldVideoId);

      this.currentVideoId = this.globalId+this.counter;
      this.showVideo(this.currentVideoId);

      this.counter++;
      this.newVideoId = this.globalId+this.counter;

      this.createVideo(this.newVideoId);
    }
  }

  // console.log($('.player-controls.rewind'));
  $('.player-controls.rewind').val(this.counter);

  if(this.playable&&this.lock){
    this.partCounter++;
  }
}

Player.prototype.pauseVideo = function(){
  itemId = this.globalId+(this.counter-1);
  item = document.getElementById(itemId);
  item.pause();
  this.playable = false;
}
Player.prototype.playVideo = function(){
  itemId = this.globalId+(this.counter-1);
  item = document.getElementById(itemId);
  item.play();
  this.playable = true;
}

Player.prototype.startVideo = function(){
  this.update();
  var self = this; // hack for 'this' forwarding into update
  setInterval(function(){self.update.call(self)}, 1000);

}

Player.prototype.setPath = function(time){

 if(time<5){
    switch(this.quality){
      case 0:
        this.quality=1;
        break;
      case 1:
        this.quality=2;
        break;
    }
  } else {
    switch(this.quality){
      case 2:
        this.quality=1;
        break;
      case 1:
        this.quality=0;
        break;
    }
  }
}

Player.prototype.getPath = function(){
  switch(this.quality){
    case 0:
      return this.poorPath;
    case 1:
      return this.mediumPath;
    case 2:
      return this.highPath;
  }
}

Player.prototype.goTo = function(value) {
  this.partCounter = 0;
  this.hideVideo(this.globalId + (this.counter - 1));
  this.newTime = true;
  this.counter = value;
}

Player.prototype.createDom = function(){
  $('#' + this.globalId).append('

')
  $('#' + this.globalId).append('

')
  $('#' + this.globalId).append('

')
  $('#' + this.globalId + ' .play-controls').append('<button class="player-controls play">Play</button>')
  $('#' + this.globalId + ' .play-controls').append('<button class="player-controls pause">Pause</button>')
  $('#' + this.globalId + ' .rewind-controls').append('<input class="player-controls rewind" type="range" min="0" max="'+this.parts+'" value="0" />')

  this.playerItem = document.getElementById('player_videos');
  this.setEvents()
}

Player.prototype.setEvents = function(){
  $('.player-controls.play').on('click', { player: this }, function(event){
    event.data.player.playVideo();
  })

  $('.player-controls.pause').on('click', { player: this }, function(event){
    event.data.player.pauseVideo();
  })

  $('.player-controls.rewind').on('change', { player: this }, function(event){
    event.data.player.goTo($(this).val());
  })
}<|endoftext|>


<commit_before>/**
 * VirtualBlink1 -- on-screen representation of what's going on with blink(1) device
 * - represents current colors (from Blink1Service) on-screen
 * - runs multi-channel fading algorithm, similar to real blink(1)
 * - updates Blink1ColorPicker with fade updates
 *
 */

"use strict";

// var _ = require('lodash');

var React = require('react');

var Blink1Service = require('../../server/blink1Service');

var tinycolor = require('tinycolor2');

// var blackc = tinycolor('#000000');

var VirtualBlink1 = React.createClass({
	getInitialState: function() {
		return {
			// colors: ['#ff00ff', '#00ffff', 0,0,  0,0,0,0, 0,0,0,0 ], // FIXME: should be blink1service.getCurrentColors()
			// colors: [ tinycolor('#ff00ff'), tinycolor('#00ffff') ],
			// nextColors: [ tinycolor('#ff00ff'), tinycolor('#00ffff') ],
			// lastColors:[ tinycolor('#ff00ff'), tinycolor('#00ffff')],
			colors: new Array(2).fill(tinycolor('#000033')),
			// millis: []
		};
	},
	componentDidMount: function() {
		Blink1Service.addChangeListener( this.fetchBlink1Color, "virtualBlink1" );
	},
	// callback to Blink1Service
	// fetchBlink1Color: function(lastColor, newcolors /*, ledn */) { // FIXME: where's millis?
	fetchBlink1Color: function() {
		this.lastColors = this.state.colors;
		this.nextColors = Blink1Service.getCurrentColors( Blink1Service.getCurrentBlink1Id() );
		this.blink1Idx = Blink1Service.getCurrentBlink1Id();
		// this.nextColors = newcolors;
		// // this.setState( {
		// // 	// colors: colors,
		// // 	ledn: ledn // unused currently
		// // });
		this._colorFaderStart();
	},
	handleBlink1IdxChange: function(idx) {
		Blink1Service.setCurrentBlink1Id(idx);
	},

	blink1Idx: 0,
	ledn: 0,
	nextColors: new Array(2).fill(tinycolor('#ff00ff')), // ledn colors
	lastColors: new Array(2).fill(tinycolor('#ff00ff')), // last ledn colors
	timer: null,
	faderMillis: 0,
	currentMillis: 0,
	stepMillis: 20,
	_colorFaderStart: function() {
		clearTimeout(this.timer);
		this.faderMillis = 0;  // goes from 0 to currentMillis
		this.currentMillis = Blink1Service.getCurrentMillis() || this.stepMillis; // FIXME: HACK
        this.currentMillis /= 2; // FIXME: to match what blink1service does
		this._colorFader();
		// console.log("---start:",new Date().getTime() );
	},
	_colorFader: function() {
		var self = this;
		var p = (this.faderMillis/this.currentMillis);  // ranges from 0.0 to 1.0 -ish
		var ledn = this.state.ledn;
		var ledst = ledn-1;
		var ledend = ledn;
		var colors = this.state.colors;
		if( ledn===0 ) { ledst = 0; ledend = colors.length-1; }
		colors.slice(ledst, ledend).map( function(c,i) {
			var oldc = self.lastColors[i].toRgb();
			var newc = self.nextColors[i].toRgb();
			var r = (1-p) * (oldc.r) + (p * newc.r);
			var g = (1-p) * (oldc.g) + (p * newc.g);
			var b = (1-p) * (oldc.b) + (p * newc.b);
			var tmpc =  tinycolor( {r:r,g:g,b:b} );
			colors[i] = tmpc;
		});
		this.setState({colors: colors});

		self.faderMillis += self.stepMillis;
		// this.notifyChange();
		if( p < 1 ) {
			this.timer = setTimeout(function() {
				// console.log("    _colorFader: r:",r);
				self._colorFader();
			}, this.stepMillis);
		}
		// else {
		//   console.log("---  end:",new Date().getTime() );
		// }
	},

	render: function() {
        var topLum = this.state.colors[0].toHsl().l; //was .getLuminance();
        var botLum = this.state.colors[1].toHsl().l;
        var topColor = tinycolor(this.state.colors[0]).setAlpha(topLum);
        var botColor = tinycolor(this.state.colors[1]).setAlpha(botLum); // was (Math.pow(botLum,0.5));
        // var topColor = tinycolor(this.state.colors[0]).setAlpha(Math.pow(topLum,0.5));
        // var botColor = tinycolor(this.state.colors[1]).setAlpha(Math.pow(botLum,0.5));
        var colorDesc = "A:"+this.state.colors[0] + "\nB:"+ this.state.colors[1];

        // console.log("VirtualBlink1: color0:",topColor.toRgbString());
        var topgradient =  // (this.state.colors[0].toHexString() === '#000000') ?
		"radial-gradient(160px 90px at 150px 50px," + topColor.toRgbString() + " 20%, rgba(255,255,255,0.2) 55% )";
		var botgradient = //(this.state.colors[1].toHexString() === '#000000') ? 'url()' :
		"radial-gradient(160px 90px at 150px 110px," + botColor.toRgbString() + " 20%, rgba(255,255,255,0.2) 55% )";

        // "radial-gradient(160px 90px at 150px 110px," + this.state.colors[1].toRgbString() + " 0%, rgba(255,255,255,0.2) 55% )";
		// linear-gradient(to bottom, rgba(30,87,153,1) 0%,rgba(66,124,183,0) 38%,rgba(125,185,232,0) 100%);

		var img0style = { width: 240, height: 150, margin: 0, padding: 0, marginTop:-15, // FIXME why do I need marginTop-15?
			border: '0px solid grey',
			//background: this.props.blink1Color
			backgroundImage: [
    			topgradient,
                "url(images/device-light-bg.png)",
				// topgradient,
				"url(images/device-light-mask.png)",
				// "url(images/device-preview.png)",
				"url(images/device-light-bg-bottom.png)",
				"url(images/device-light-bg-top.png)",
				botgradient,
			]
		};
			//
			//
			// var img1style = { width: 240, height: 192 };
			// var img2style = { width: 240, height: 192, position: "relative", top: 0 };
			// var img3style = { width: 240, height: 192, position: "relative", top: 0 };

		var makeMiniBlink1 = function(serial,idx) {
			var colrs = Blink1Service.getCurrentColors(idx);
			var colrA = colrs[0];
            var colrB = colrs[1];
			if( colrA.getBrightness() === 0 ) { colrA = '#888'; }
			if( colrB.getBrightness() === 0 ) { colrB = '#888'; }
			var titlestr = 'serial:'+serial +' A:'+colrs[0].toHexString()+'/B:'+colrs[1].toHexString();
			var borderStyle = (idx===this.blink1Idx) ? '2px solid #aaa' : '2px solid #eee';
			return (

			);

		};
		var serials = Blink1Service.getAllSerials();
		var miniBlink1s = (serials.length > 1 ) ? serials.map(makeMiniBlink1, this) : null;
		return (

					{miniBlink1s}

		);
	}
});

module.exports = VirtualBlink1;
<commit_msg>virtualblink1 multi now lists colors in hover text<commit_after>/**
 * VirtualBlink1 -- on-screen representation of what's going on with blink(1) device
 * - represents current colors (from Blink1Service) on-screen
 * - runs multi-channel fading algorithm, similar to real blink(1)
 * - updates Blink1ColorPicker with fade updates
 *
 */

"use strict";

// var _ = require('lodash');

var React = require('react');

var Blink1Service = require('../../server/blink1Service');

var tinycolor = require('tinycolor2');

// var blackc = tinycolor('#000000');

var VirtualBlink1 = React.createClass({
	getInitialState: function() {
		return {
			// colors: ['#ff00ff', '#00ffff', 0,0,  0,0,0,0, 0,0,0,0 ], // FIXME: should be blink1service.getCurrentColors()
			// colors: [ tinycolor('#ff00ff'), tinycolor('#00ffff') ],
			// nextColors: [ tinycolor('#ff00ff'), tinycolor('#00ffff') ],
			// lastColors:[ tinycolor('#ff00ff'), tinycolor('#00ffff')],
			colors: new Array(2).fill(tinycolor('#000033')),
			// millis: []
		};
	},
	componentDidMount: function() {
		Blink1Service.addChangeListener( this.fetchBlink1Color, "virtualBlink1" );
	},
	// callback to Blink1Service
	// fetchBlink1Color: function(lastColor, newcolors /*, ledn */) { // FIXME: where's millis?
	fetchBlink1Color: function() {
		this.lastColors = this.state.colors;
		this.nextColors = Blink1Service.getCurrentColors( Blink1Service.getCurrentBlink1Id() );
		this.blink1Idx = Blink1Service.getCurrentBlink1Id();
		// this.nextColors = newcolors;
		// // this.setState( {
		// // 	// colors: colors,
		// // 	ledn: ledn // unused currently
		// // });
		this._colorFaderStart();
	},
	handleBlink1IdxChange: function(idx) {
		Blink1Service.setCurrentBlink1Id(idx);
	},

	blink1Idx: 0,
	ledn: 0,
	nextColors: new Array(2).fill(tinycolor('#ff00ff')), // ledn colors
	lastColors: new Array(2).fill(tinycolor('#ff00ff')), // last ledn colors
	timer: null,
	faderMillis: 0,
	currentMillis: 0,
	stepMillis: 20,
	_colorFaderStart: function() {
		clearTimeout(this.timer);
		this.faderMillis = 0;  // goes from 0 to currentMillis
		this.currentMillis = Blink1Service.getCurrentMillis() || this.stepMillis; // FIXME: HACK
        this.currentMillis /= 2; // FIXME: to match what blink1service does
		this._colorFader();
		// console.log("---start:",new Date().getTime() );
	},
	_colorFader: function() {
		var self = this;
		var p = (this.faderMillis/this.currentMillis);  // ranges from 0.0 to 1.0 -ish
		var ledn = this.state.ledn;
		var ledst = ledn-1;
		var ledend = ledn;
		var colors = this.state.colors;
		if( ledn===0 ) { ledst = 0; ledend = colors.length-1; }
		colors.slice(ledst, ledend).map( function(c,i) {
			var oldc = self.lastColors[i].toRgb();
			var newc = self.nextColors[i].toRgb();
			var r = (1-p) * (oldc.r) + (p * newc.r);
			var g = (1-p) * (oldc.g) + (p * newc.g);
			var b = (1-p) * (oldc.b) + (p * newc.b);
			var tmpc =  tinycolor( {r:r,g:g,b:b} );
			colors[i] = tmpc;
		});
		this.setState({colors: colors});

		self.faderMillis += self.stepMillis;
		// this.notifyChange();
		if( p < 1 ) {
			this.timer = setTimeout(function() {
				// console.log("    _colorFader: r:",r);
				self._colorFader();
			}, this.stepMillis);
		}
		// else {
		//   console.log("---  end:",new Date().getTime() );
		// }
	},

	render: function() {
        var topLum = this.state.colors[0].toHsl().l; //was .getLuminance();
        var botLum = this.state.colors[1].toHsl().l;
        var topColor = tinycolor(this.state.colors[0]).setAlpha(topLum);
        var botColor = tinycolor(this.state.colors[1]).setAlpha(botLum); // was (Math.pow(botLum,0.5));
        // var topColor = tinycolor(this.state.colors[0]).setAlpha(Math.pow(topLum,0.5));
        // var botColor = tinycolor(this.state.colors[1]).setAlpha(Math.pow(botLum,0.5));
        var colorDesc = "A:"+this.state.colors[0] + "\nB:"+ this.state.colors[1];

        // console.log("VirtualBlink1: color0:",topColor.toRgbString());
        var topgradient =  // (this.state.colors[0].toHexString() === '#000000') ?
		"radial-gradient(160px 90px at 150px 50px," + topColor.toRgbString() + " 20%, rgba(255,255,255,0.2) 55% )";
		var botgradient = //(this.state.colors[1].toHexString() === '#000000') ? 'url()' :
		"radial-gradient(160px 90px at 150px 110px," + botColor.toRgbString() + " 20%, rgba(255,255,255,0.2) 55% )";

        // "radial-gradient(160px 90px at 150px 110px," + this.state.colors[1].toRgbString() + " 0%, rgba(255,255,255,0.2) 55% )";
		// linear-gradient(to bottom, rgba(30,87,153,1) 0%,rgba(66,124,183,0) 38%,rgba(125,185,232,0) 100%);

		var img0style = { width: 240, height: 150, margin: 0, padding: 0, marginTop:-15, // FIXME why do I need marginTop-15?
			border: '0px solid grey',
			//background: this.props.blink1Color
			backgroundImage: [
    			topgradient,
                "url(images/device-light-bg.png)",
				// topgradient,
				"url(images/device-light-mask.png)",
				// "url(images/device-preview.png)",
				"url(images/device-light-bg-bottom.png)",
				"url(images/device-light-bg-top.png)",
				botgradient,
			]
		};
			//
			//
			// var img1style = { width: 240, height: 192 };
			// var img2style = { width: 240, height: 192, position: "relative", top: 0 };
			// var img3style = { width: 240, height: 192, position: "relative", top: 0 };

		var makeMiniBlink1 = function(serial,idx) {
			var colrs = Blink1Service.getCurrentColors(idx);
			var colrA = colrs[0];
            var colrB = colrs[1];
			if( colrA.getBrightness() === 0 ) { colrA = '#888'; }
			if( colrB.getBrightness() === 0 ) { colrB = '#888'; }
			var titlestr = 'serial:'+serial +' A/B:'+colrs[0].toHexString().toUpperCase()+'/'+colrs[1].toHexString().toUpperCase();
			var borderStyle = (idx===this.blink1Idx) ? '2px solid #aaa' : '2px solid #eee';
			return (

			);

		};
		var serials = Blink1Service.getAllSerials();
		var miniBlink1s = (serials.length > 1 ) ? serials.map(makeMiniBlink1, this) : null;
		return (

					{miniBlink1s}

		);
	}
});

module.exports = VirtualBlink1;
<|endoftext|>


<commit_before>import path from 'path';
import test from 'ava';
import fn from '../';

function hasRule(results, ruleId) {
	return results[0].messages.some(x => x.ruleId === ruleId);
}

test('.lintText()', t => {
	const results = fn.lintText(`'use strict'\nconsole.log('unicorn');\n`).results;
	t.true(hasRule(results, 'semi'));
});

test('.lintText() - `esnext` option', t => {
	const results = fn.lintText('function dec() {}\nconst x = {\n\t@dec()\n\ta: 1\n};\n', {esnext: true}).results;
	t.true(hasRule(results, 'no-unused-vars'));
});

test('.lintText() - JSX support', t => {
	const results = fn.lintText('var app =
Hello, React!
;\n', {esnext: false}).results;
	t.true(hasRule(results, 'no-unused-vars'));
});

test('.lintText() - plugin support', t => {
	const results = fn.lintText('var React;\nReact.render(<App/>);\n', {
		plugins: ['react'],
		rules: {'react/jsx-no-undef': 2}
	}).results;
	t.true(hasRule(results, 'react/jsx-no-undef'));
});

test('.lintText() - prevent use of extended native objects', t => {
	const results = fn.lintText('[].unicorn();\n').results;
	t.true(hasRule(results, 'no-use-extend-native/no-use-extend-native'));
});

test('.lintText() - extends support', t => {
	const results = fn.lintText('var React;\nReact.render(<App/>);\n', {
		extends: 'xo-react'
	}).results;
	t.true(hasRule(results, 'react/jsx-no-undef'));
});

test('.lintText() - extends support with `esnext` option', t => {
	const results = fn.lintText('import path from \'path\';\nvar React;\nReact.render(<App/>);\n', {
		esnext: true,
		extends: 'xo-react'
	}).results;
	t.true(hasRule(results, 'react/jsx-no-undef'));
});

test('always use the Babel parser so esnext syntax won\'t throw in normal mode', t => {
	// TODO: remove the `filename` option when https://github.com/sindresorhus/eslint-plugin-xo/issues/19 is fixed
	const results = fn.lintText('async function foo() {}\n\nfoo();\n', {filename: 'x'}).results;
	t.is(results[0].errorCount, 0);
});

test('.lintText() - regression test for #71', t => {
	// TODO: remove the `filename` option when https://github.com/sindresorhus/eslint-plugin-xo/issues/19 is fixed
	const results = fn.lintText(`var foo = { key: 'value' };\nconsole.log(foo);\n`, {
		extends: path.join(__dirname, 'fixtures/extends.js'),
		filename: 'x'
	}).results;
	t.is(results[0].errorCount, 0, results[0]);
});
<commit_msg>minor test tweaks<commit_after>import path from 'path';
import test from 'ava';
import fn from '../';

const hasRule = (results, ruleId) => results[0].messages.some(x => x.ruleId === ruleId);

test('.lintText()', t => {
	const results = fn.lintText(`'use strict'\nconsole.log('unicorn');\n`).results;
	t.true(hasRule(results, 'semi'));
});

test('.lintText() - `esnext` option', t => {
	const results = fn.lintText('function dec() {}\nconst x = {\n\t@dec()\n\ta: 1\n};\n', {esnext: true}).results;
	t.true(hasRule(results, 'no-unused-vars'));
});

test('.lintText() - JSX support', t => {
	const results = fn.lintText('var app =
Hello, React!
;\n', {esnext: false}).results;
	t.true(hasRule(results, 'no-unused-vars'));
});

test('.lintText() - plugin support', t => {
	const results = fn.lintText('var React;\nReact.render(<App/>);\n', {
		plugins: ['react'],
		rules: {'react/jsx-no-undef': 2}
	}).results;
	t.true(hasRule(results, 'react/jsx-no-undef'));
});

test('.lintText() - prevent use of extended native objects', t => {
	const results = fn.lintText('[].unicorn();\n').results;
	t.true(hasRule(results, 'no-use-extend-native/no-use-extend-native'));
});

test('.lintText() - extends support', t => {
	const results = fn.lintText('var React;\nReact.render(<App/>);\n', {
		extends: 'xo-react'
	}).results;
	t.true(hasRule(results, 'react/jsx-no-undef'));
});

test('.lintText() - extends support with `esnext` option', t => {
	const results = fn.lintText('import path from \'path\';\nvar React;\nReact.render(<App/>);\n', {
		esnext: true,
		extends: 'xo-react'
	}).results;
	t.true(hasRule(results, 'react/jsx-no-undef'));
});

test('always use the Babel parser so esnext syntax won\'t throw in normal mode', t => {
	const results = fn.lintText('async function foo() {}\n\nfoo();\n').results;
	t.is(results[0].errorCount, 0);
});

test('.lintText() - regression test for #71', t => {
	const results = fn.lintText(`var foo = { key: 'value' };\nconsole.log(foo);\n`, {
		extends: path.join(__dirname, 'fixtures/extends.js')
	}).results;
	t.is(results[0].errorCount, 0, results[0]);
});
<|endoftext|>


<commit_before>document.getElementById('search_query_query').addEventListener('keydown', function (e) {
    if (e.keyCode === 13) {
        e.preventDefault();
    }
});

var searchParameters = {};

if (decodeURI(location.search).match(/[<>]/)) {
    location.replace(location.pathname);
}

var searchThrottle = null;
var search = instantsearch({
    appId: algoliaConfig.app_id,
    apiKey: algoliaConfig.search_key,
    indexName: algoliaConfig.index_name,
    routing: {
        stateMapping: {
            stateToRoute: function (uiState) {
                return {
                    query: uiState.query,
                    type: uiState.menu && uiState.menu.type,
                    tags: uiState.refinementList && uiState.refinementList.tags && uiState.refinementList.tags.join('~'),
                    page: uiState.page,
                };
            },
            routeToState: function (routeState) {
                if (routeState.q) {
                    routeState.query = routeState.q;
                }

                if (
                    (routeState.query === undefined || routeState.query === '')
                    && (routeState.type === undefined || routeState.type === '')
                    && (routeState.tags === undefined || routeState.tags === '')
                ) {
                    return {};
                }

                return {
                    query: routeState.query || '',
                    menu: {
                        type: routeState.type
                    },
                    refinementList: {
                        tags: routeState.tags && routeState.tags.split('~'),
                    },
                    page: routeState.page
                };
            },
        },
    },
    searchFunction: function(helper) {
        var searchResults = $('#search-container');

        if (helper.state.query === ''
            && helper.state.hierarchicalFacetsRefinements.type === undefined
            && (helper.state.disjunctiveFacetsRefinements.tags === undefined || helper.state.disjunctiveFacetsRefinements.tags.length === 0)
        ) {
            searchResults.addClass('hidden');
        } else {
            searchResults.removeClass('hidden');
        }

        if (searchThrottle) {
            clearTimeout(searchThrottle);
        }

        searchThrottle = setTimeout(function () {
            helper.search();
        }, 300);
    },
    searchParameters: searchParameters
});

var autofocus = false;
if (location.pathname == "/" || location.pathname == "/app_dev.php/") {
    autofocus = true;
}
search.addWidget(
    instantsearch.widgets.searchBox({
        container: '#search_query_query',
        magnifier: false,
        reset: false,
        wrapInput: false,
        autofocus: autofocus
    })
);

search.addWidget(
    instantsearch.widgets.hits({
        container: '.search-list',
        transformData: function (hit) {
            hit.url = '/packages/' + hit.name;
            if (hit.type === 'virtual-package') {
                hit.virtual = true;
                hit.url = '/providers/' + hit.name;
            }

            if (hit._highlightResult && hit._highlightResult.description.value && hit._highlightResult.description.value.length > 200) {
                hit._highlightResult.description.value = hit._highlightResult.description.value.substring(0, 200).replace(/<[a-z ]+$/, '');
            }

            return hit;
        },
        templates: {
            empty: 'No packages found.',
            item: `

{{ language }}

                {{{ _highlightResult.name.value }}}
                {{#virtual}}
                    (Virtual Package)
                {{/virtual}}

{{{ _highlightResult.description.value }}}

            {{#abandoned}}

                 Abandoned!
                {{#replacementPackage}}
                    See {{ replacementPackage }}
                {{/replacementPackage}}

            {{/abandoned}}

            {{#meta}}

                     {{ meta.downloads_formatted }}
                     {{ meta.favers_formatted }}

            {{/meta}}

`
        },
        cssClasses: {
            root: 'packages',
            item: 'row'
        }
    })
);

search.addWidget(
    instantsearch.widgets.pagination({
        container: '.pagination',
        maxPages: 200,
        scrollTo: document.getElementById('search_query_query'),
        showFirstLast: false,
    })
);

search.addWidget(
    instantsearch.widgets.currentRefinedValues({
        container: '.search-facets-active-filters',
        clearAll: 'before',
        clearsQuery: false,
        cssClasses: {
            clearAll: 'pull-right'
        },
        templates: {
            header: 'Active filters',
            item: function (filter) {
                if ('tags' == filter.attributeName) {
                    return 'tag: ' + filter.name
                } else {
                    return filter.attributeName + ': ' + filter.name
                }
            }
        },
        onlyListedAttributes: true,
    })
);

search.addWidget(
    instantsearch.widgets.menu({
        container: '.search-facets-type',
        attributeName: 'type',
        limit: 15,
        showMore: true,
        templates: {
            header: 'Package type'
        }
    })
);

search.addWidget(
    instantsearch.widgets.refinementList({
        container: '.search-facets-tags',
        attributeName: 'tags',
        limit: 15,
        showMore: true,
        templates: {
            header: 'Tags'
        },
        searchForFacetValues:true
    })
);

search.start();
<commit_msg>Fix support for replacements as links in search results<commit_after>document.getElementById('search_query_query').addEventListener('keydown', function (e) {
    if (e.keyCode === 13) {
        e.preventDefault();
    }
});

var searchParameters = {};

if (decodeURI(location.search).match(/[<>]/)) {
    location.replace(location.pathname);
}

var searchThrottle = null;
var search = instantsearch({
    appId: algoliaConfig.app_id,
    apiKey: algoliaConfig.search_key,
    indexName: algoliaConfig.index_name,
    routing: {
        stateMapping: {
            stateToRoute: function (uiState) {
                return {
                    query: uiState.query,
                    type: uiState.menu && uiState.menu.type,
                    tags: uiState.refinementList && uiState.refinementList.tags && uiState.refinementList.tags.join('~'),
                    page: uiState.page,
                };
            },
            routeToState: function (routeState) {
                if (routeState.q) {
                    routeState.query = routeState.q;
                }

                if (
                    (routeState.query === undefined || routeState.query === '')
                    && (routeState.type === undefined || routeState.type === '')
                    && (routeState.tags === undefined || routeState.tags === '')
                ) {
                    return {};
                }

                return {
                    query: routeState.query || '',
                    menu: {
                        type: routeState.type
                    },
                    refinementList: {
                        tags: routeState.tags && routeState.tags.split('~'),
                    },
                    page: routeState.page
                };
            },
        },
    },
    searchFunction: function(helper) {
        var searchResults = $('#search-container');

        if (helper.state.query === ''
            && helper.state.hierarchicalFacetsRefinements.type === undefined
            && (helper.state.disjunctiveFacetsRefinements.tags === undefined || helper.state.disjunctiveFacetsRefinements.tags.length === 0)
        ) {
            searchResults.addClass('hidden');
        } else {
            searchResults.removeClass('hidden');
        }

        if (searchThrottle) {
            clearTimeout(searchThrottle);
        }

        searchThrottle = setTimeout(function () {
            helper.search();
        }, 300);
    },
    searchParameters: searchParameters
});

var autofocus = false;
if (location.pathname == "/" || location.pathname == "/app_dev.php/") {
    autofocus = true;
}
search.addWidget(
    instantsearch.widgets.searchBox({
        container: '#search_query_query',
        magnifier: false,
        reset: false,
        wrapInput: false,
        autofocus: autofocus
    })
);

search.addWidget(
    instantsearch.widgets.hits({
        container: '.search-list',
        transformData: function (hit) {
            hit.url = '/packages/' + hit.name;
            if (hit.type === 'virtual-package') {
                hit.virtual = true;
                hit.url = '/providers/' + hit.name;
            }

            if (hit._highlightResult && hit._highlightResult.description.value && hit._highlightResult.description.value.length > 200) {
                hit._highlightResult.description.value = hit._highlightResult.description.value.substring(0, 200).replace(/<[a-z ]+$/, '');
            }

            hit.replacementPackageUrl = null

            if (hit.replacementPackage) {
                hit.replacementPackageUrl = hit.replacementPackage.indexOf('://') !== -1 ? hit.replacementPackage : ('/packages/' + hit.replacementPackage)
            }

            return hit;
        },
        templates: {
            empty: 'No packages found.',
            item: `

{{ language }}

                {{{ _highlightResult.name.value }}}
                {{#virtual}}
                    (Virtual Package)
                {{/virtual}}

{{{ _highlightResult.description.value }}}

            {{#abandoned}}

                 Abandoned!
                {{#replacementPackage}}
                    See {{ replacementPackage }}
                {{/replacementPackage}}

            {{/abandoned}}

            {{#meta}}

                     {{ meta.downloads_formatted }}
                     {{ meta.favers_formatted }}

            {{/meta}}

`
        },
        cssClasses: {
            root: 'packages',
            item: 'row'
        }
    })
);

search.addWidget(
    instantsearch.widgets.pagination({
        container: '.pagination',
        maxPages: 200,
        scrollTo: document.getElementById('search_query_query'),
        showFirstLast: false,
    })
);

search.addWidget(
    instantsearch.widgets.currentRefinedValues({
        container: '.search-facets-active-filters',
        clearAll: 'before',
        clearsQuery: false,
        cssClasses: {
            clearAll: 'pull-right'
        },
        templates: {
            header: 'Active filters',
            item: function (filter) {
                if ('tags' == filter.attributeName) {
                    return 'tag: ' + filter.name
                } else {
                    return filter.attributeName + ': ' + filter.name
                }
            }
        },
        onlyListedAttributes: true,
    })
);

search.addWidget(
    instantsearch.widgets.menu({
        container: '.search-facets-type',
        attributeName: 'type',
        limit: 15,
        showMore: true,
        templates: {
            header: 'Package type'
        }
    })
);

search.addWidget(
    instantsearch.widgets.refinementList({
        container: '.search-facets-tags',
        attributeName: 'tags',
        limit: 15,
        showMore: true,
        templates: {
            header: 'Tags'
        },
        searchForFacetValues:true
    })
);

search.start();
<|endoftext|>


<commit_before>import React from 'react-native';
import Swiper from 'react-native-swiper';
import Login from './Login';
import Dimensions from 'Dimensions';
import Main from '../main/Main';

import globals from '../../../globalVariables';

var window = Dimensions.get('window');

var dishes = [{
  name: 'Italiano',
  image: require('image!GodMother'),
  location: 'Santa Monica, CA',
  date: '2d ago'
},{
  name: 'Dbl Cheese',
  image: require('image!InNOut'),
  location: 'Salt Lake City, Ut',
  date: '1w ago'
},
{
  name: 'Pad Thai',
  image: require('image!padThai'),
  location: 'New York, NY',
  date: '2w ago'
}];

var {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableHighlight,
} = React

class Walkthrough extends React.Component {

  onMomentumScrollEnd(e, state, context) {
    // console.log(state, context.state);
  }
  onButtonPress() {
    this.props.navigator.pop();
  }

  render() {
    return (
      <View
        style={styles.container}>
          <Swiper
            loop={false}
            onMomentumScrollEnd={this.onMomentumScrollEnd.bind(this)}
            showsPagination={true}
            buttonWrapperStyle={styles.button}
            dot={<View style={styles.dot}></View>}
            activeDot={<View style={[styles.dot, styles.activeDot]}></View>}>
            <View style={[styles.slide]}>
              <Image
                style={styles.bg}
                source={require('image!food-bg')}>
                <View style={styles.imageContainer}>
                  <Image
                    source={require('image!card')}>
                  </Image>
                </View>
                <View style={styles.textContainer}>
                  <Text style={styles.headline}>Taken at face value</Text>
                  <Text style={styles.paragraph}>
                    <Text style={styles.emphasis}>No stars.</Text> <Text style={styles.emphasis}>No reviews. </Text>
                    <Text>No restaurant name. Swipe right based solely off the looks of the plate to begin your adventure!</Text>
                  </Text>
                </View>
              </Image>
            </View>
            <View style={[styles.slide]}>
              <Image
                style={styles.bg}
                source={require('image!walkthrough-bg-2')}>
                <View style={styles.imageContainer}>
                  <Image
                    source={require('image!step-card')}>
                  </Image>
                </View>
                <View style={styles.textContainer}>
                  <Text style={styles.headline}>Follow the markers</Text>
                  <Text style={styles.paragraph}>
                    To keep it a mmmystery, you'll be given walking directions
                    one step at a time right up until you arrive at your restaurant!
                  </Text>
                </View>
              </Image>
            </View>
            <View style={[styles.slide]}>
              <Image
                style={styles.bg}
                source={require('image!walkthrough-bg-3')}>
                <View style={styles.imageContainer}>
                  {dishes.map(function(dish, i) {
                    return (
                      <View style={styles.shareCard} key={i}>
                        <View style={styles.imageInner}>
                          <Image
                            style={styles.shareImage}
                            source={dish.image}>
                          </Image>
                        </View>
                        <View style={styles.middleShareText}>
                          <View style={styles.textLightContainer}>
                            <Text style={styles.textLight}>Shared by you</Text>
                          </View>
                          <View style={styles.plateNameContainer}>
                            <Text style={styles.plateName}>{dish.name}</Text>
                            <Text style={styles.text}>{dish.location}</Text>
                          </View>
                        </View>
                        <View style={styles.date}>
                          <Text style={styles.textLight}>{dish.date}</Text>
                        </View>
                      </View>
                    );
                  })}
                </View>
                <View style={styles.textContainer}>
                  <Text style={styles.headline}>Sharing is caring</Text>
                  <Text style={styles.paragraph}>
                    Help fellow mmmystery members start their own adventures by snapping and uploading pictures of your meals.
                  </Text>
                </View>
              </Image>
            </View>
          </Swiper>
          <Image
            style={styles.logo}
            source={require('image!logo-orange')}>
          </Image>
          <TouchableHighlight
            underlayColor={globals.primaryDark}
            style={styles.button}
            onPress={this.onButtonPress.bind(this)}>
            <Text style={styles.buttonText}>{this.props.route.props.isSignedIn ? 'Back' : 'Sign in!'}</Text>
          </TouchableHighlight>
      </View>
    );
  }
}

export default Walkthrough;

var padding = 20;
var middleWidth = (window.width * 1/3) + 20;

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    position: 'relative',
  },
  bg: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    overflow: 'visible'
  },
  emphasis: {
    fontWeight: 'bold',
  },
  slide: {
    flex: 1,
    justifyContent: 'space-around',
    alignItems: 'center',
  },
  headline: {
    marginBottom: 10,
    color: '#fff',
    fontSize: 25,
    textAlign: 'center',
    fontFamily: globals.fontDisplaySemibold,
  },
  paragraph: {
    marginBottom: 20,
    color: '#fff',
    fontSize: 18,
    textAlign: 'center',
    fontFamily: globals.fontTextMedium,
  },
  dot: {
    backgroundColor: globals.primaryLight,
    width: 12,
    height: 12,
    borderRadius: 6,
    marginRight: 3,
    marginTop: 3,
    marginBottom: 3,
    marginLeft: 3,
  },
  shareCard: {
    flexDirection: 'row',
    flex: 0,
    height: 110,
    marginBottom: 10,
    paddingRight: 5,
    paddingLeft: 5,
    paddingTop: 5,
    borderRadius: 3,
    backgroundColor: '#fff',
    justifyContent: 'center'
  },
  activeDot: {
    backgroundColor: globals.primaryDark,
  },
  button: {
    width: 90,
    position: 'absolute',
    top: 30,
    left: padding,
    padding: 7,
    borderWidth: 1,
    borderColor: globals.primaryLight,
    borderRadius: 2
  },
  logo: {
    position: 'absolute',
    top: 30,
    right: padding,
  },
  buttonText: {
    color: '#fff',
    fontSize: 18,
    textAlign: 'center',
    fontFamily: globals.fontDisplaySemibold,
  },
  imageContainer: {
    flex: 2,
    justifyContent: 'center',
    marginTop: 100,
    alignSelf: 'center',
  },
  imageInner: {
    justifyContent: 'center',
    alignItems: 'center',
    flex: 0,
    width: 100,
    height: 100,
    backgroundColor: 'white',
    borderRadius: 3,
    marginLeft: -20,
  },
  shareImage: {
    width: 87,
    height: 87,
    borderRadius: 2,
  },
  text: {
    fontFamily: globals.fontTextRegular,
  },
  textLightContainer: {
    alignSelf: 'flex-start',
    justifyContent: 'flex-start',
    flexDirection: 'column',
    flex: 1,
  },
  textLight: {
    fontFamily: globals.fontTextRegular,
    color: globals.lightText,

    marginBottom: 5,
  },
  date: {
    width: 50,
    paddingTop: 5,
  },
  plateNameContainer: {
    flex:3,
    justifyContent: 'flex-start',
    flexDirection: 'column'
  },
  plateName: {
    fontSize: 22,
    fontFamily: globals.fontTextSemibold,
    color: globals.primaryDark,
    marginBottom: 4,
  },
  middleShareText: {
    flexDirection: 'column',
    width: middleWidth,
    paddingHorizontal: 5,
    paddingTop: 5,
    justifyContent: 'center',
    flex: 1
  },
  textContainer: {
    flex: 1,
    justifyContent: 'flex-start',
    paddingHorizontal: padding,
  }
});
<commit_msg>[Feature] Adds responsivness to walkthrough feature<commit_after>import React from 'react-native';
import Swiper from 'react-native-swiper';
import Login from './Login';
import Dimensions from 'Dimensions';
import Main from '../main/Main';

import globals from '../../../globalVariables';

var window = Dimensions.get('window');

var dishes = [{
  name: 'Italiano',
  image: require('image!GodMother'),
  location: 'Santa Monica, CA',
  date: '2d ago'
},{
  name: 'Dbl Cheese',
  image: require('image!InNOut'),
  location: 'Salt Lake City, Ut',
  date: '1w ago'
},
{
  name: 'Pad Thai',
  image: require('image!padThai'),
  location: 'New York, NY',
  date: '2w ago'
}];

var {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableHighlight,
} = React

class Walkthrough extends React.Component {

  onMomentumScrollEnd(e, state, context) {
    // console.log(state, context.state);
  }
  onButtonPress() {
    this.props.navigator.pop();
  }

  render() {
    return (
      <View
        style={styles.container}>
          <Swiper
            loop={false}
            onMomentumScrollEnd={this.onMomentumScrollEnd.bind(this)}
            showsPagination={true}
            buttonWrapperStyle={styles.button}
            dot={<View style={styles.dot}></View>}
            activeDot={<View style={[styles.dot, styles.activeDot]}></View>}>
            <View style={[styles.slide]}>
              <Image
                style={styles.bg}
                source={require('image!food-bg')}>
                <View style={styles.imageContainer}>
                  <Image
                    style={styles.imageCard1}
                    source={require('image!card')}>
                  </Image>
                </View>
                <View style={styles.textContainer}>
                  <Text style={styles.headline}>Taken at face value</Text>
                  <Text style={styles.paragraph}>
                    <Text style={styles.emphasis}>No stars.</Text> <Text style={styles.emphasis}>No reviews. </Text>
                    <Text>No restaurant name. Swipe right based solely off the looks of the plate to begin your adventure!</Text>
                  </Text>
                </View>
              </Image>
            </View>
            <View style={[styles.slide]}>
              <Image
                style={styles.bg}
                source={require('image!walkthrough-bg-2')}>
                <View style={styles.imageContainer}>
                  <Image
                    style={styles.imageCard2}
                    source={require('image!step-card')}>
                  </Image>
                </View>
                <View style={styles.textContainer}>
                  <Text style={styles.headline}>Follow the markers</Text>
                  <Text style={styles.paragraph}>
                    To keep it a mmmystery, you'll be given walking directions
                    one step at a time right up until you arrive at your restaurant!
                  </Text>
                </View>
              </Image>
            </View>
            <View style={[styles.slide]}>
              <Image
                style={styles.bg}
                source={require('image!walkthrough-bg-3')}>
                <View style={styles.imageContainer}>
                  {dishes.map(function(dish, i) {
                    return (
                      <View style={styles.shareCard} key={i}>
                        <View style={styles.imageInner}>
                          <Image
                            style={styles.shareImage}
                            source={dish.image}>
                          </Image>
                        </View>
                        <View style={styles.middleShareText}>
                          <View style={styles.textLightContainer}>
                            <Text style={styles.textLight}>Shared by you</Text>
                          </View>
                          <View style={styles.plateNameContainer}>
                            <Text style={styles.plateName}>{dish.name}</Text>
                            <Text style={styles.text}>{dish.location}</Text>
                          </View>
                        </View>
                        <View style={styles.date}>
                          <Text style={styles.textLight}>{dish.date}</Text>
                        </View>
                      </View>
                    );
                  })}
                </View>
                <View style={styles.textContainer}>
                  <Text style={styles.headline}>Sharing is caring</Text>
                  <Text style={styles.paragraph}>
                    Help fellow mmmystery members start their own adventures by snapping and uploading pictures of your meals.
                  </Text>
                </View>
              </Image>
            </View>
          </Swiper>
          <Image
            style={styles.logo}
            source={require('image!logo-orange')}>
          </Image>
          <TouchableHighlight
            underlayColor={globals.primaryDark}
            style={styles.button}
            onPress={this.onButtonPress.bind(this)}>
            <Text style={styles.buttonText}>{this.props.route.props.isSignedIn ? 'Back' : 'Sign in!'}</Text>
          </TouchableHighlight>
      </View>
    );
  }
}

export default Walkthrough;
// Adjustments
var imageCard1Width =309 * window.width/375,
    imageCard1Height = 365 * window.height/667,
    shareImageWidth = 87 * window.width/375,
    shareImageHeight = 87 * window.width/375,
    imageInnerWidth = 100 * window.width/375,
    imageInnerHeight = 100 * window.height/667;
switch(window.height) {
    case 480: // iPhone 4s
        imageCard1Width = 220;
        imageCard1Height = 260;
        shareImageWidth = 60;
        shareImageHeight = 60;
        imageInnerWidth = 70;
        imageInnerHeight = 70;
        break;
    case 568: // iPhone 5 and 5s
        break;
    case 667: // iPhone 6
        break;
    case 736: // iPhone 6s
        break;
    default:
        break;
}
//-----
var padding = 20;
var middleWidth = (window.width * 1/3) + 20;

var styles = StyleSheet.create({
  imageCard2: {
    width: 325 * window.width/375,
    height: 142 * window.height/667,
  },
  imageCard1: {
    width: imageCard1Width,
    height: imageCard1Height,
  },
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    position: 'relative',
  },
  bg: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    overflow: 'visible'
  },
  emphasis: {
    fontWeight: 'bold',
  },
  slide: {
    flex: 1,
    justifyContent: 'space-around',
    alignItems: 'center',
  },
  headline: {
    marginBottom: 10,
    color: '#fff',
    fontSize: 25 * window.width/375,
    textAlign: 'center',
    fontFamily: globals.fontDisplaySemibold,
  },
  paragraph: {
    marginBottom: 20,
    color: '#fff',
    fontSize: 18 * window.width/375,
    textAlign: 'center',
    fontFamily: globals.fontTextMedium,
    paddingHorizontal: 20 * window.width/375,
  },
  dot: {
    backgroundColor: globals.primaryLight,
    width: 12 * window.width/375,
    height: 12 * window.height/667,
    borderRadius: 6,
    marginRight: 3,
    marginTop: 3,
    marginBottom: -5 -(5*window.height/667),
    marginLeft: 3,
  },
  shareCard: {
    flexDirection: 'row',
    flex: 0,
    height: 110 * window.height/667,
    marginBottom: 10 * window.height/667,
    paddingHorizontal: 5 * window.width/375,
    paddingTop: 5 * window.height/667,
    borderRadius: 3,
    backgroundColor: '#fff',
    justifyContent: 'center'
  },
  activeDot: {
    backgroundColor: globals.primaryDark,
  },
  button: {
    width: 90,
    position: 'absolute',
    top: 30,
    left: padding,
    padding: 7,
    borderWidth: 1,
    borderColor: globals.primaryLight,
    borderRadius: 2
  },
  logo: {
    position: 'absolute',
    top: 30,
    right: padding,
  },
  buttonText: {
    color: '#fff',
    fontSize: 18,
    textAlign: 'center',
    fontFamily: globals.fontDisplaySemibold,
  },
  imageContainer: {
    flex: 2,
    justifyContent: 'center',
    marginTop: 100 * window.height/667,
    alignSelf: 'center',
  },
  imageInnerCard1: {
    justifyContent: 'center',
    alignItems: 'center',
    flex: 0,
    width: imageInnerWidth,
    height: imageInnerHeight,
    backgroundColor: 'white',
    borderRadius: 3,
    marginLeft: -20,
  },
  imageInner: {
    justifyContent: 'center',
    alignItems: 'center',
    flex: 0,
    width: imageInnerWidth,
    height: imageInnerHeight,
    backgroundColor: 'white',
    borderRadius: 3,
    marginLeft: -20,
  },
  shareImage: {
    width: shareImageWidth,
    height: shareImageHeight,
    borderRadius: 2,
  },
  text: {
    fontFamily: globals.fontTextRegular,
  },
  textLightContainer: {
    alignSelf: 'flex-start',
    justifyContent: 'flex-start',
    flexDirection: 'column',
    flex: 1,
  },
  textLight: {
    fontFamily: globals.fontTextRegular,
    color: globals.lightText,

    marginBottom: 5,
  },
  date: {
    width: 50,
    paddingTop: 5,
  },
  plateNameContainer: {
    flex:3,
    justifyContent: 'flex-start',
    flexDirection: 'column'
  },
  plateName: {
    fontSize: 22,
    fontFamily: globals.fontTextSemibold,
    color: globals.primaryDark,
    marginBottom: 4,
  },
  middleShareText: {
    flexDirection: 'column',
    width: middleWidth,
    paddingHorizontal: 5,
    paddingTop: 5,
    justifyContent: 'center',
    flex: 1
  },
  textContainer: {
    flex: 1,
    justifyContent: 'flex-start',
    paddingHorizontal: padding,
  }
});
<|endoftext|>


<commit_before>'use strict'

require('should')

describe('API', function () {
  var mockFS = require('mock-fs')
  var syp = require('../api')
    , utils = require('../api/utils')

  var testVar = Math.random()
    , realHome

  before(function () {
    realHome = utils.HOME
    utils.HOME = 'home'

    var fs = {}
    fs[utils.HOME] = {
      '.syp-cfg.json': JSON.stringify({
        extend: 'extend-test.json',
        X_test_var: testVar
      }),
      'extend-test.json': JSON.stringify({
        X_test_var: testVar + 1,
        X_test_var_2: testVar + 1
      })
    }
    mockFS(fs)
  })

  after(function () {
    mockFS.restore()
    utils.HOME = realHome
  })

  describe('.load()', function () {
    it('should load the default SYP config file', function () {
      syp.load()
      syp.config.X_test_var.should.equal(testVar)
    })
    it('should ensure the entire config file is valid')
    it('should load the default SYP index file')
    it('should ensure the entire SYP index file is valid')
    it('should load all SYP index files specified in config')
    it('should not allow any indexes to have duplicate project names')
    it('should load source SYP config files (config.extend)', function () {
      syp.load()
      syp.config.X_test_var.should.equal(testVar)
      syp.config.X_test_var_2.should.equal(testVar + 1)
    })
    it('should load all SYP index files in extend path')
  })

  describe('.ProjectIndex', function () {
    describe('#constructor()', function () {
      it('should instantiate an empty index')
      it('should begin populating the index with passed parameters')
    })

    describe('#load()', function () {
      it('should load the given index-like object as an index')
      it('should ensure the given object is valid')
      it('should complain if any IDs already exist')
    })

    describe('#get()', function () {
      it('should return the project with the given ID')
      it('should not try to guess the project if an ID is not found')
    })

    describe('#whichIndex()', function () {
      it('should return the index where the given ID exists')
    })

    describe('#move()', function () {
      it('should change the index where a given project is held')
      it('should not complain if the given index is the current index')
    })

    describe('#add()', function () {
      it('should insert a project into the index, retrieveable later')
      it('should use a specific index, if asked')
      it('should fail if the project ID exists already')
    })

    describe('#unindex()', function () {
      it('should remove the project from the index')
      it('should return the project that was removed')
      it('should not do anything to the project files')
    })
  })

  describe('.Project', function () {
    describe('#constructor()', function () {
      it('should load all standard attributes', function () {
        var project = new syp.Project({
          name: 'Test project',
          path: '~/Projects/test-project',
          categories: ['Category 1', 'Category 2'],
          description: 'A test project description'
        })

        project.name.should.equal('Test project')
        project.path.should.equal('~/Projects/test-project')
        project.categories.should.have.length(2)
        project.description.should.equal('A test project description')
      })
      it('should ensure the entire object is valid', function () {
        (function () {
          new syp.Project({ name: 1234, path: '~' })
        }).should.throw({ attr: 'name', problem: 'type' })
        ;(function () {
          new syp.Project({ path: 1234 })
        }).should.throw({ attr: 'path', problem: 'type' })
        ;(function () {
          new syp.Project({ path: null })
        }).should.throw({ attr: 'path', problem: 'required' })
        ;(function () {
          new syp.Project({ description: 1234, path: '~' })
        }).should.throw({ attr: 'description', problem: 'type' })
        ;(function () {
          new syp.Project({ categories: 1234, path: '~' })
        }).should.throw({ attr: 'categories', problem: 'type' })
        ;(function () {
          new syp.Project({ categories: ['cat', 1234], path: '~' })
        }).should.throw({ attr: 'categories', problem: 'nested-type', key: 1 })
      })
      it('should fill in any attributes with their defaults')
      it('should register the project with the index, unless told otherwise')
      it("should create any directories that don't already exist")
    })

    describe('#remove()', function () {
      it('should remove all files and directories contained in the project')
      it('should not try to modify the index')
    })
  })
})
<commit_msg>Test of config extend is slightly better<commit_after>'use strict'

require('should')

describe('API', function () {
  var mockFS = require('mock-fs')
  var syp = require('../api')
    , utils = require('../api/utils')

  var testVar = Math.random()
    , realHome

  before(function () {
    realHome = utils.HOME
    utils.HOME = 'home'

    var fs = {}
    fs[utils.HOME] = {
      '.syp-cfg.json': JSON.stringify({
        extend: 'extend-test.json',
        X_test_var: testVar
      }),
      'extend-test.json': JSON.stringify({
        extend: 'extend-test-2.json',
        X_test_var: testVar + 1,
        X_test_var_2: testVar + 1
      }),
      'extend-test-2.json': JSON.stringify({
        X_test_var_2: testVar + 2,
        X_test_var_3: testVar + 2
      })
    }
    mockFS(fs)
  })

  after(function () {
    mockFS.restore()
    utils.HOME = realHome
  })

  describe('.load()', function () {
    it('should load the default SYP config file', function () {
      syp.load()
      syp.config.X_test_var.should.equal(testVar)
    })
    it('should ensure the entire config file is valid')
    it('should load the default SYP index file')
    it('should ensure the entire SYP index file is valid')
    it('should load all SYP index files specified in config')
    it('should not allow any indexes to have duplicate project names')
    it('should load source SYP config files (config.extend)', function () {
      syp.load()
      syp.config.X_test_var.should.equal(testVar)
      syp.config.X_test_var_2.should.equal(testVar + 1)
      syp.config.X_test_var_3.should.equal(testVar + 2)
    })
    it('should load all SYP index files in extend path')
  })

  describe('.ProjectIndex', function () {
    describe('#constructor()', function () {
      it('should instantiate an empty index')
      it('should begin populating the index with passed parameters')
    })

    describe('#load()', function () {
      it('should load the given index-like object as an index')
      it('should ensure the given object is valid')
      it('should complain if any IDs already exist')
    })

    describe('#get()', function () {
      it('should return the project with the given ID')
      it('should not try to guess the project if an ID is not found')
    })

    describe('#whichIndex()', function () {
      it('should return the index where the given ID exists')
    })

    describe('#move()', function () {
      it('should change the index where a given project is held')
      it('should not complain if the given index is the current index')
    })

    describe('#add()', function () {
      it('should insert a project into the index, retrieveable later')
      it('should use a specific index, if asked')
      it('should fail if the project ID exists already')
    })

    describe('#unindex()', function () {
      it('should remove the project from the index')
      it('should return the project that was removed')
      it('should not do anything to the project files')
    })
  })

  describe('.Project', function () {
    describe('#constructor()', function () {
      it('should load all standard attributes', function () {
        var project = new syp.Project({
          name: 'Test project',
          path: '~/Projects/test-project',
          categories: ['Category 1', 'Category 2'],
          description: 'A test project description'
        })

        project.name.should.equal('Test project')
        project.path.should.equal('~/Projects/test-project')
        project.categories.should.have.length(2)
        project.description.should.equal('A test project description')
      })
      it('should ensure the entire object is valid', function () {
        (function () {
          new syp.Project({ name: 1234, path: '~' })
        }).should.throw({ attr: 'name', problem: 'type' })
        ;(function () {
          new syp.Project({ path: 1234 })
        }).should.throw({ attr: 'path', problem: 'type' })
        ;(function () {
          new syp.Project({ path: null })
        }).should.throw({ attr: 'path', problem: 'required' })
        ;(function () {
          new syp.Project({ description: 1234, path: '~' })
        }).should.throw({ attr: 'description', problem: 'type' })
        ;(function () {
          new syp.Project({ categories: 1234, path: '~' })
        }).should.throw({ attr: 'categories', problem: 'type' })
        ;(function () {
          new syp.Project({ categories: ['cat', 1234], path: '~' })
        }).should.throw({ attr: 'categories', problem: 'nested-type', key: 1 })
      })
      it('should fill in any attributes with their defaults')
      it('should register the project with the index, unless told otherwise')
      it("should create any directories that don't already exist")
    })

    describe('#remove()', function () {
      it('should remove all files and directories contained in the project')
      it('should not try to modify the index')
    })
  })
})
<|endoftext|>


<commit_before>var clip = new ZeroClipboard.Client();
var level = new Array(30);
var insp;
var levelParam;
var afterEditorLoad;
var canvasContext;
var minimap;
var context;
var tool;

function setLevel(lvl) {
  level = lvl;

  drawCanvas(camx, camy);
}

function gup( name ) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if (null == results)
    return "";
  else
    return results[1];
}

var UpdateMap = UndoableAction.extend({
  init: function(value, options) {
    var self = this;
    self.value = value;
    // console.log('Redrawing map...');

    this._super(function() {
      // console.log('map up');
      self.oldValue = UpdateMap.priorOldValue;
      setLevel(getLevelCopy(self.value));
      reloadMap();
      UpdateMap.priorOldValue = self.value;

      // reportLevel(self.value, 'new');
      // reportLevel(level, 'current');
      // reportLevel(self.oldValue, 'old');
    }, function() {
      // console.log('map down');
      setLevel(self.oldValue); // setLevel(getLevelCopy(self.oldValue));
      reloadMap();
      UpdateMap.priorOldValue = getLevelCopy(self.oldValue);
    });

    self.do();
  }
});

var canvas, tool, px, py, tcolor, brush, camx, camy;
var tool_default = 'rock';
var total_brushes = 10;
var brushes = new Array(total_brushes);
var brushes_img = new Array(total_brushes);

// Keep everything in anonymous function, called on window load.
if(window.addEventListener) {
window.addEventListener('load', function () {

  // Load the default brush, #1
  brush = '4';

  camx = 0;
  camy = 0;
  px = -100;
  py = -100;

  levelParam = gup("level");
  clip.setHandCursor(true);
  clip.glue('d_clip_button', 'd_clip_container');

  function init () {
    // Find the elements
    canvas = document.getElementById('imageView');
    for (var i = 0; i < total_brushes; i++) {
      brushes[i] = document.getElementById('brush'+i);
      brushes[i].addEventListener('mousedown', ev_brush, false);
      brushes_img[i] = new Image();
      brushes_img[i].src = brushes[i].src;
      }

  // init the global level data structure
  for (var i = 0; i < 30; i++) {
    level[i] = "0000000000000000000000000000000000000000";
    }

  if(levelParam.length == 1200)
  {
  for (var c = 0; c < 1200; c += 40)
    {
    level[c/40] = levelParam.substr(c,40);
    }
  }

    if (!canvas) {
      alert('Error: I cannot find the canvas element!');
      return;
    }

    if (!canvas.getContext) {
      alert('Error: no canvas.getContext!');
      return;
    }

    // Get the 2D canvas context.
    context = canvas.getContext('2d');
    if (!context) {
      alert('Error: failed to getContext!');
      return;
    }

    // Pencil tool instance.
    tool = new tool_pencil();

    canvas.addEventListener('mousedown', ev_canvas, false);
    canvas.addEventListener('mousemove', ev_canvas, false);
    canvas.addEventListener('mouseup',   ev_canvas, false);

    drawCanvas(camx,camy);
  }

  function replaceOneChar(s, c, n) {
    (s = s.split(''))[n] = c;
    return s.join('');
  };

function ev_brush (ev) {
  brush = this.src.substr(this.src.length - 5, 1);
}

  // This painting tool works like a drawing pencil which tracks the mouse
  // movements.
  function tool_pencil () {
    tool = this;
    this.started = false;

    // This is called when you start holding down the mouse button.
    this.mousedown = function (ev) {
        level[Math.floor(ev._y/32)+camy] = replaceOneChar(level[Math.floor(ev._y/32)+camy], brush, [Math.floor(ev._x/32)+camx]);
        tool.started = true;
        drawCanvas(camx,camy);
    };

    // This function is called every time you move the mouse. Obviously, it only
    // draws if the tool.started state is set to true (when you are holding down
    // the mouse button).
    this.mousemove = function (ev) {

    px = ev._x;
    py = ev._y;

    if (!tool.started) {
    // move the camera when you hit the edge of the screen
      if (ev._x > 600 && camx < 20) {
        camx += 1;
        //drawCanvas(camx,camy);
      }
      else if (ev._x < 40 && camx > 0) {
          camx -= 1;
         // drawCanvas(camx,camy);
        }
      if (ev._y > 440 && camy < 15) {
        camy += 1;
       // drawCanvas(camx,camy);
      }
      else if (ev._y < 40 && camy > 0) {
          camy -= 1;
         // drawCanvas(camx,camy);
        }
     }

      if (tool.started) {
        level[Math.floor(ev._y/32)+camy] = replaceOneChar(level[Math.floor(ev._y/32)+camy], brush, [Math.floor(ev._x/32)+camx]);
        }
       drawCanvas(camx,camy);
       context.lineWidth = 2;
    context.strokeStyle = '#800';
    context.strokeRect((Math.floor(ev._x/32))*32, Math.floor(ev._y/32)*32, 32, 32);

    };

    // This is called when you release the mouse button.
    this.mouseup = function (ev) {
      if (canvasContext) genMiniMap();
      if (tool.started) {
        tool.mousemove(ev);
        tool.started = false;
      }
    };
  }

  // The general-purpose event handler. This function just determines the mouse
  // position relative to the canvas element.
  function ev_canvas (ev) {
    if (ev.layerX || ev.layerX == 0) { // Firefox
      ev._x = ev.layerX;
      ev._y = ev.layerY;
    } else if (ev.offsetX || ev.offsetX == 0) { // Opera
      ev._x = ev.offsetX;
      ev._y = ev.offsetY;
    }

    // Call the event handler of the tool.
    var func = tool[ev.type];
    if (func) {
      func(ev);
    }

  }

  function genMiniMap () {
      reloadMap();
      minimap = canvasContext.getImageData(0, 0, 640*2, 480*2);
      var pix = minimap.data;

      // Loop over pixels, skipping every Nth since we're shrinking the image
      for (var i = 0, n = pix.length; i < n; i += 4)
          if (i % 32 == 0)
          {
          pix[(i/8)  ] = pix[i  ]; // r
          pix[(i/8)+1] = pix[i+1]; // g
          pix[(i/8)+2] = pix[i+2]; // b
          pix[(i/8)+3] = pix[i+3]; // a
          }
  }

  init();

  if (!UpdateMap.priorOldValue) {
    UpdateMap.priorOldValue = getLevelCopy();
  }

  if (afterEditorLoad) {
    afterEditorLoad();
  }

}, false); }

function drawCanvas(cx, cy) {
  for (var y = cy; y < cy+15; y++)
    for (var x = cx; x < cx+20; x++)
      context.drawImage(brushes_img[parseInt(level[y][x])], (x-camx)*32, (y-camy)*32);

  levelParam = "";
  for (var i = 0; i < 30; i++) {
    levelParam += level[i];
  }

  setLongURL(window.location.protocol + "//" + window.location.host + window.location.pathname + "?level=" + levelParam);

  if (minimap) context.putImageData(minimap,480,0,0,0,160,120);

  context.strokeStyle = '#000';
  context.strokeRect(480,0,160,120);
  context.strokeRect(480+((camx*32)/8),0+((camy*32)/8),640/8,480/8);
}

function redrawMap() {
  new UpdateMap(getLevelCopy());
}

// vim:set spell spl=en fo=wan1croql tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
<commit_msg>Minor editor fix<commit_after>var clip = new ZeroClipboard.Client();
var level = new Array(30);
var insp;
var levelParam;
var afterEditorLoad;
var canvasContext;
var minimap;
var context;
var tool;

function setLevel(lvl) {
  level = lvl;

  drawCanvas(camx, camy);
}

function gup( name ) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if (null == results)
    return "";
  else
    return results[1];
}

var UpdateMap = UndoableAction.extend({
  init: function(value, options) {
    var self = this;
    self.value = value;
    // console.log('Redrawing map...');

    this._super(function() {
      // console.log('map up');
      self.oldValue = UpdateMap.priorOldValue;
      setLevel(getLevelCopy(self.value));
      reloadMap();
      UpdateMap.priorOldValue = self.value;

      // reportLevel(self.value, 'new');
      // reportLevel(level, 'current');
      // reportLevel(self.oldValue, 'old');
    }, function() {
      // console.log('map down');
      setLevel(self.oldValue); // setLevel(getLevelCopy(self.oldValue));
      reloadMap();
      UpdateMap.priorOldValue = getLevelCopy(self.oldValue);
    });

    self.do();
  }
});

var canvas, tool, px, py, tcolor, brush, camx, camy;
var tool_default = 'rock';
var total_brushes = 10;
var brushes = new Array(total_brushes);
var brushes_img = new Array(total_brushes);

// Keep everything in anonymous function, called on window load.
if(window.addEventListener) {
window.addEventListener('load', function () {

  // Load the default brush, #1
  brush = '4';

  camx = 0;
  camy = 0;
  px = -100;
  py = -100;

  levelParam = gup("level");
  clip.setHandCursor(true);
  clip.glue('d_clip_button', 'd_clip_container');

  function init () {
    // Find the elements
    canvas = document.getElementById('imageView');
    for (var i = 0; i < total_brushes; i++) {
      brushes[i] = document.getElementById('brush'+i);
      brushes[i].addEventListener('mousedown', ev_brush, false);
      brushes_img[i] = new Image();
      brushes_img[i].src = brushes[i].src;
      }

  // init the global level data structure
  for (var i = 0; i < 30; i++) {
    level[i] = "0000000000000000000000000000000000000000";
    }

  if(levelParam.length == 1200)
  {
  for (var c = 0; c < 1200; c += 40)
    {
    level[c/40] = levelParam.substr(c,40);
    }
  }

    if (!canvas) {
      alert('Error: I cannot find the canvas element!');
      return;
    }

    if (!canvas.getContext) {
      alert('Error: no canvas.getContext!');
      return;
    }

    // Get the 2D canvas context.
    context = canvas.getContext('2d');
    if (!context) {
      alert('Error: failed to getContext!');
      return;
    }

    // Pencil tool instance.
    tool = new tool_pencil();

    canvas.addEventListener('mousedown', ev_canvas, false);
    canvas.addEventListener('mousemove', ev_canvas, false);
    canvas.addEventListener('mouseup',   ev_canvas, false);

    drawCanvas(camx,camy);
  }

  function replaceOneChar(s, c, n) {
    (s = s.split(''))[n] = c;
    return s.join('');
  };

function ev_brush (ev) {
  brush = this.src.substr(this.src.length - 5, 1);
}

  // This painting tool works like a drawing pencil which tracks the mouse
  // movements.
  function tool_pencil () {
    tool = this;
    this.started = false;

    // This is called when you start holding down the mouse button.
    this.mousedown = function (ev) {
        level[Math.floor(ev._y/32)+camy] = replaceOneChar(level[Math.floor(ev._y/32)+camy], brush, [Math.floor(ev._x/32)+camx]);
        tool.started = true;
        drawCanvas(camx,camy);
    };

    // This function is called every time you move the mouse. Obviously, it only
    // draws if the tool.started state is set to true (when you are holding down
    // the mouse button).
    this.mousemove = function (ev) {

    px = ev._x;
    py = ev._y;

    if (!tool.started) {
    // move the camera when you hit the edge of the screen
      if (ev._x > 600 && camx < 20) {
        camx += 1;
        //drawCanvas(camx,camy);
      }
      else if (ev._x < 40 && camx > 0) {
          camx -= 1;
         // drawCanvas(camx,camy);
        }
      if (ev._y > 440 && camy < 15) {
        camy += 1;
       // drawCanvas(camx,camy);
      }
      else if (ev._y < 40 && camy > 0) {
          camy -= 1;
         // drawCanvas(camx,camy);
        }
     }

      if (tool.started) {
        level[Math.floor(ev._y/32)+camy] = replaceOneChar(level[Math.floor(ev._y/32)+camy], brush, [Math.floor(ev._x/32)+camx]);
        }
       drawCanvas(camx,camy);
       context.lineWidth = 2;
    context.strokeStyle = '#800';
    context.strokeRect((Math.floor(ev._x/32))*32, Math.floor(ev._y/32)*32, 32, 32);

    };

    // This is called when you release the mouse button.
    this.mouseup = function (ev) {
      if (canvasContext) {genMiniMap();}
      if (tool.started) {
        tool.mousemove(ev);
        tool.started = false;
      }
    };
  }

  // The general-purpose event handler. This function just determines the mouse
  // position relative to the canvas element.
  function ev_canvas (ev) {
    if (ev.layerX || ev.layerX == 0) { // Firefox
      ev._x = ev.layerX;
      ev._y = ev.layerY;
    } else if (ev.offsetX || ev.offsetX == 0) { // Opera
      ev._x = ev.offsetX;
      ev._y = ev.offsetY;
    }

    // Call the event handler of the tool.
    var func = tool[ev.type];
    if (func) {
      func(ev);
    }

  }

  function genMiniMap () {
      reloadMap();
      minimap = canvasContext.getImageData(0, 0, 640*2, 480*2);
      var pix = minimap.data;

      // Loop over pixels, skipping every Nth since we're shrinking the image
      for (var i = 0, n = pix.length; i < n; i += 4)
          if (i % 32 == 0)
          {
          pix[(i/8)  ] = pix[i  ]; // r
          pix[(i/8)+1] = pix[i+1]; // g
          pix[(i/8)+2] = pix[i+2]; // b
          pix[(i/8)+3] = pix[i+3]; // a
          }
  }

  init();

  if (!UpdateMap.priorOldValue) {
    UpdateMap.priorOldValue = getLevelCopy();
  }

  if (afterEditorLoad) {
    afterEditorLoad();
  }

}, false); }

function drawCanvas(cx, cy) {
  for (var y = cy; y < cy+15; y++)
    for (var x = cx; x < cx+20; x++)
      context.drawImage(brushes_img[parseInt(level[y][x])], (x-camx)*32, (y-camy)*32);

  levelParam = "";
  for (var i = 0; i < 30; i++) {
    levelParam += level[i];
  }

  setLongURL(window.location.protocol + "//" + window.location.host + window.location.pathname + "?level=" + levelParam);

  if (minimap) context.putImageData(minimap,480,0,0,0,160,120);

  context.strokeStyle = '#000';
  context.strokeRect(480,0,160,120);
  context.strokeRect(480+((camx*32)/8),0+((camy*32)/8),640/8,480/8);
}

function redrawMap() {
  new UpdateMap(getLevelCopy());
}

// vim:set spell spl=en fo=wan1croql tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:
<|endoftext|>


<commit_before>'use strict';
var stubRuns = require('../services/stub');
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

describe('generator-makrina:app', function () {
  // test both branches to increase coverage
  var runs = [
    {it: 'no suffix in git prompt', git: 'https://github.com/Wtower/generator-makrina'},
    {it: 'suffix in git prompt', git: 'https://github.com/Wtower/generator-makrina.git'}
  ];
  var stub = stubRuns(runs, 1);

  beforeEach(function () {
    var run = stub();
    var dependencies = [
      [helpers.createDummyGenerator(), 'makrina:angular-app'],
      [helpers.createDummyGenerator(), 'makrina:angular-core-service'],
      [helpers.createDummyGenerator(), 'makrina:angular-component-list'],
      [helpers.createDummyGenerator(), 'makrina:angular-component-detail'],
      [helpers.createDummyGenerator(), 'makrina:model']
    ];
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withGenerators(dependencies)
      .withPrompts({
        name: 'yeotests',
        git: run.git
      })
      .toPromise();
  });

  runs.forEach(function (run) {
    it('creates files with ' + run.it, function () {
      var paths = [
        'bin/',
        'e2e-tests/protractor.conf.js',
        'public/images/',
        'public/javascripts/yeotests.js',
        'public/stylesheets/yeotests.sass',
        'routes/',
        'services/',
        'spec/',
        'views/',
        '.editorconfig',
        '.gitignore',
        '.gitlab-ci.yml',
        'app.js',
        'CHANGELOG',
        'CONTRIBUTING.md',
        'fonts.list',
        'gulpfile.js',
        'karma.conf.js',
        'LICENSE',
        'newrelic.js',
        'package.json',
        'README.md',
        'public/images/'
      ];
      assert.file(paths);
      assert.fileContent('package.json', run.git);
    });
  });
});
<commit_msg>Improved default prompt git value<commit_after>'use strict';
var stubRuns = require('../services/stub');
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

describe('generator-makrina:app', function () {
  // test branches to increase coverage
  var runs = [
    {it: 'no suffix in git prompt', git: 'https://github.com/Wtower/generator-makrina'},
    {it: 'prefix in git prompt', git: 'git+https://github.com/Wtower/generator-makrina.git'},
    {it: 'suffix in git prompt', git: 'https://github.com/Wtower/generator-makrina.git'}
  ];
  var stub = stubRuns(runs, 1);

  beforeEach(function () {
    var run = stub();
    var dependencies = [
      [helpers.createDummyGenerator(), 'makrina:angular-app'],
      [helpers.createDummyGenerator(), 'makrina:angular-core-service'],
      [helpers.createDummyGenerator(), 'makrina:angular-component-list'],
      [helpers.createDummyGenerator(), 'makrina:angular-component-detail'],
      [helpers.createDummyGenerator(), 'makrina:model']
    ];
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withGenerators(dependencies)
      .withPrompts({
        name: 'yeotests',
        git: run.git
      })
      .toPromise();
  });

  runs.forEach(function (run) {
    it('creates files with ' + run.it, function () {
      var paths = [
        'bin/',
        'e2e-tests/protractor.conf.js',
        'public/images/',
        'public/javascripts/yeotests.js',
        'public/stylesheets/yeotests.sass',
        'routes/',
        'services/',
        'spec/',
        'views/',
        '.editorconfig',
        '.gitignore',
        '.gitlab-ci.yml',
        'app.js',
        'CHANGELOG',
        'CONTRIBUTING.md',
        'fonts.list',
        'gulpfile.js',
        'karma.conf.js',
        'LICENSE',
        'newrelic.js',
        'package.json',
        'README.md',
        'public/images/'
      ];
      assert.file(paths);
      assert.fileContent('package.json', run.git);
    });
  });
});
<|endoftext|>


<commit_before>import 'babel-polyfill'
import Raven from 'raven-js'
import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import Root from './root'
import { initializeFirebase } from 'authentication/firebaseConfig'

// Start Sentry logger
// https://docs.sentry.io/clients/javascript/config/
Raven.config(process.env.WEB_SENTRY_DSN, {
  environment: process.env.STAGE,
  debug: process.env.WEB_SENTRY_DEBUG === 'true'
}).install()

const initApp = () => {
  // Init Firebase
  initializeFirebase()

  require('./index.css')

  const rootNode = document.createElement('div')
  document.body.appendChild(rootNode)

  const render = (Component) => {
    ReactDOM.render(
      <AppContainer >
        <Component />
      </AppContainer>,
      rootNode
    )
  }

  render(Root)

  // Hot Module Replacement API
  if (module.hot) {
    module.hot.accept('./root', () => {
      render(root)
    })
  }
}

Raven.context(() => {
  if (process.env.WEB_SENTRY_DEBUG === 'true') {
    console.log(`Initialized Raven for Sentry DSN ${process.env.WEB_SENTRY_DSN}`)
  }
  initApp()
})
<commit_msg>Try/catch Raven initialization<commit_after>import 'babel-polyfill'
import Raven from 'raven-js'
import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import Root from './root'
import { initializeFirebase } from 'authentication/firebaseConfig'

// Start Sentry logger
// https://docs.sentry.io/clients/javascript/config/
const sentryDSN = process.env.WEB_SENTRY_DSN
const sentryDebug = process.env.WEB_SENTRY_DEBUG === 'true'
try {
  Raven.config(sentryDSN, {
    environment: process.env.STAGE,
    debug: sentryDebug
  }).install()
} catch (e) {
  console.error(e)
}

const initApp = () => {
  // Init Firebase
  initializeFirebase()

  require('./index.css')

  const rootNode = document.createElement('div')
  document.body.appendChild(rootNode)

  const render = (Component) => {
    ReactDOM.render(
      <AppContainer >
        <Component />
      </AppContainer>,
      rootNode
    )
  }

  render(Root)

  // Hot Module Replacement API
  if (module.hot) {
    module.hot.accept('./root', () => {
      render(root)
    })
  }
}

try {
  Raven.context(() => {
    if (sentryDebug) {
      console.log(`Initialized Raven for Sentry DSN ${sentryDSN}`)
    }
    initApp()
  })
} catch (e) {
  console.error(e)
  initApp()
}
<|endoftext|>