<commit_before>DDH.stopwatch_goodie = DDH.stopwatch_goodie || {};

DDH.stopwatch_goodie.build = function(ops) {
    function onShow(){
        // Wait for the goodie to load before displaying things
        // This makes sure the divs display at the right time so the layout doesn't break
        $(".zci--stopwatch_goodie .goodie-pane-right").css("display", "inline-block");
        $(".zci--stopwatch_goodie .stopwatch__left").css("display", "inline");

        var running = false,
            start_time = null,
            last_lap = null,
            interval_id = null,
            lap_num = 1,
            old_time = 0,
            $total_time = $('#total_time'),
            $current_time = $('#current_time'),
            $split_list = $('#split_list'),
            $lap_btn = $('#lap_btn'),
            $reset_btn = $('#reset_btn');

        //add zeros to the end of the number
        function padZeros(n, len){
            var s = n.toString();
            while (s.length < len){
                s = '0' + s;
            }
            return s;
        }

        //go from a time in ms to human-readable
        function formatTime(t){
            // var hrs = Math.floor(t / (1000*60*60));
            // t = t % (1000*60*60);
            var mins = Math.floor(t / (1000*60));
            t = t % (1000*60);
            var secs = Math.floor(t / 1000);
            t = padZeros((t % 1000).toString(), 3).substring(0, 2);
            return padZeros(mins, 2) + ":" + padZeros(secs, 2) + '.' + t;
        }

        //called on every interval
        function updateStopwatch(){
            var t = new Date().getTime() - start_time + old_time;
            $total_time.html(formatTime(t));
            $current_time.html(formatTime(t-last_lap))
            return t;
        }

        //trigger for lap button (extracted so the stop button trigger can access it)
        function addLap(){
            if (!running) return;
            var current_time = updateStopwatch();
            var current_lap = current_time - last_lap;
            $split_list.prepend('
' + lap_num + '	' +
                $total_time.html() + '	' + formatTime(current_lap) + '
');
            $split_list.removeClass('is-hidden');
            last_lap = current_time;
            lap_num++;
            return current_time;
        }

        //when we click the start button, we save the time we started and start updating it
        $('.btn-wrapper').on('click', '.stopwatch__btn.start', function(){
            if (running) return;
            running = true;
            start_time = new Date().getTime();
            if (!last_lap) last_lap = 0;
            interval_id = setInterval(updateStopwatch, 10);

            $(this).html('STOP').removeClass('start').addClass('stop');
            $reset_btn.prop('disabled', false);
            $lap_btn.prop('disabled', false);
        });

        //stop the stopwatch and save the time in case we start it again
        $('.btn-wrapper').on('click', '.stopwatch__btn.stop', function(){
            if (!running) return;
            //add a lap (useful for people who want to stop and get a split at the same time)
            old_time = addLap();
            running = false;
            clearInterval(interval_id);

            $(this).html('START').removeClass('stop').addClass('start');
            $reset_btn.prop('disabled', false);
            $lap_btn.prop('disabled', true);
        });

        //reset everything
        $reset_btn.click(function(){
            running = false;
            old_time = 0;
            last_lap = null;
            lap_num = 1;
            $total_time.html(formatTime(0));
            $current_time.html(formatTime(0));
            $split_list.find('tbody').children().remove();
            clearInterval(interval_id);

            $('.stopwatch__btn.stop').removeClass('stop').addClass('start').html('START');
            $(this).prop('disabled', true);
            $lap_btn.prop('disabled', true);
            $split_list.addClass('is-hidden');
        });

        //add a split (the time that was on the watch) and lap (time between laps)
        $lap_btn.click(addLap);
    }

    return {
        onShow: onShow
    }
}
<commit_msg>Stopwatch: fix duplicate lap rows<commit_after>DDH.stopwatch_goodie = DDH.stopwatch_goodie || {};

DDH.stopwatch_goodie.build = function(ops) {
    function stopwatchBuildOnce(){
        var running = false,
            start_time = null,
            last_lap = null,
            interval_id = null,
            lap_num = 1,
            old_time = 0,
            $total_time = $('#total_time'),
            $current_time = $('#current_time'),
            $split_list = $('#split_list'),
            $lap_btn = $('#lap_btn'),
            $reset_btn = $('#reset_btn');

        //add zeros to the end of the number
        function padZeros(n, len){
            var s = n.toString();
            while (s.length < len){
                s = '0' + s;
            }
            return s;
        }

        //go from a time in ms to human-readable
        function formatTime(t){
            // var hrs = Math.floor(t / (1000*60*60));
            // t = t % (1000*60*60);
            var mins = Math.floor(t / (1000*60));
            t = t % (1000*60);
            var secs = Math.floor(t / 1000);
            t = padZeros((t % 1000).toString(), 3).substring(0, 2);
            return padZeros(mins, 2) + ":" + padZeros(secs, 2) + '.' + t;
        }

        //called on every interval
        function updateStopwatch(){
            var t = new Date().getTime() - start_time + old_time;
            $total_time.html(formatTime(t));
            $current_time.html(formatTime(t-last_lap))
            return t;
        }

        //trigger for lap button (extracted so the stop button trigger can access it)
        function addLap(){
            if (!running) return;
            var current_time = updateStopwatch();
            var current_lap = current_time - last_lap;
            $split_list.prepend('
' + lap_num + '	' +
                $total_time.html() + '	' + formatTime(current_lap) + '
');
            $split_list.removeClass('is-hidden');
            last_lap = current_time;
            lap_num++;
            return current_time;
        }

        //when we click the start button, we save the time we started and start updating it
        $('.btn-wrapper').on('click', '.stopwatch__btn.start', function(){
            if (running) return;
            running = true;
            start_time = new Date().getTime();
            if (!last_lap) last_lap = 0;
            interval_id = setInterval(updateStopwatch, 10);

            $(this).html('STOP').removeClass('start').addClass('stop');
            $reset_btn.prop('disabled', false);
            $lap_btn.prop('disabled', false);
        });

        //stop the stopwatch and save the time in case we start it again
        $('.btn-wrapper').on('click', '.stopwatch__btn.stop', function(){
            if (!running) return;
            //add a lap (useful for people who want to stop and get a split at the same time)
            old_time = addLap();
            running = false;
            clearInterval(interval_id);

            $(this).html('START').removeClass('stop').addClass('start');
            $reset_btn.prop('disabled', false);
            $lap_btn.prop('disabled', true);
        });

        //reset everything
        $reset_btn.click(function(){
            running = false;
            old_time = 0;
            last_lap = null;
            lap_num = 1;
            $total_time.html(formatTime(0));
            $current_time.html(formatTime(0));
            $split_list.find('tbody').children().remove();
            clearInterval(interval_id);

            $('.stopwatch__btn.stop').removeClass('stop').addClass('start').html('START');
            $(this).prop('disabled', true);
            $lap_btn.prop('disabled', true);
            $split_list.addClass('is-hidden');
        });

        //add a split (the time that was on the watch) and lap (time between laps)
        $lap_btn.click(addLap);
    }

    var firstStopwatchRun = false;

    return {
        onShow: function(){
            // Wait for the goodie to load before displaying things
            // This makes sure the divs display at the right time so the layout doesn't break
            $(".zci--stopwatch_goodie .goodie-pane-right").css("display", "inline-block");
            $(".zci--stopwatch_goodie .stopwatch__left").css("display", "inline");
            if (!firstStopwatchRun){
                firstStopwatchRun = true;
                stopwatchBuildOnce();
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>[*] remove useless files of vue-lib<commit_after><|endoftext|>


<commit_before>// -----------------------------------------------------------------------------
/* custom.js */
// -----------------------------------------------------------------------------

$( document).bind( 'pagebeforechange', function( e, data)
{
	if( typeof data.toPage === "string") {
		var url = $.mobile.path.parseUrl( data.toPage);
		var vars = [];
		var hash;
		var q = url.hash.split( '?')[ 1];

		if( q != undefined) {
			q = q.split( '&');
			for( var i = 0; i < q.length; ++i) {
				hash = q[ i].split( '=');
				vars.push( hash[ 1]);
				vars[ hash[ 0]] = hash[ 1];
			}
		}

		var re = /^#loadJSON/;
		if( url.hash.search(re) !== -1) {
			$( '#pageLoadJSON').data( 'data-query', vars);
			$.mobile.changePage( '#pageLoadJSON', data.options);
			e.preventDefault();
		}
	}
});

// -----------------------------------------------------------------------------

$( document).on( "pagecreate", "#pageHome", function()
{
});

// -----------------------------------------------------------------------------

$( document).on( "pageshow", "#pageHome", function()
{
		var txt = '';
		txt += '
Wähle:
';

		txt += '
';
//		txt += '
Bestimmungsschlüssel
';
		txt += '
Häufige Vögel in Gärten und Siedlungen
';
		txt += '
Amphibien und Reptilien
';
		txt += '
Holzige Pflanzen in Deutschland
';
		txt += '
';

		$( '#pageHomeContent').html( txt);
		$( '#pageHomeContent').trigger( 'create');
		$( '#pageHomeContent').trigger( 'updatelayout');
});

// -----------------------------------------------------------------------------

$( document).on( "pageshow", "#pageLoadJSON", function()
{
	var data = $( '#pageLoadJSON').data( 'data-query');
	var txt = '';

	txt += 'Lade ' + data + '...';

	$( '#pageLoadJSONContent').html( txt);
	$( '#pageLoadJSONContent').trigger( 'create');
	$( '#pageLoadJSONContent').trigger( 'updatelayout');
});

// -----------------------------------------------------------------------------

$( document).on( "pagehide", "#pageLoadJSON", function()
{
	$( '#pageLoadJSONContent').html( '');
	$( '#pageLoadJSONContent').trigger( 'create');
	$( '#pageLoadJSONContent').trigger( 'updatelayout');
});

// -----------------------------------------------------------------------------
<commit_msg>load json<commit_after>// -----------------------------------------------------------------------------
/* custom.js */
// -----------------------------------------------------------------------------

$( document).bind( 'pagebeforechange', function( e, data)
{
	if( typeof data.toPage === "string") {
		var url = $.mobile.path.parseUrl( data.toPage);
		var vars = [];
		var hash;
		var q = url.hash.split( '?')[ 1];

		if( q != undefined) {
			q = q.split( '&');
			for( var i = 0; i < q.length; ++i) {
				hash = q[ i].split( '=');
				vars.push( hash[ 1]);
				vars[ hash[ 0]] = hash[ 1];
			}
		}

		var re = /^#loadJSON/;
		if( url.hash.search(re) !== -1) {
			$( '#pageLoadJSON').data( 'data-query', vars);
			$.mobile.changePage( '#pageLoadJSON', data.options);
			e.preventDefault();
		}
	}
});

// -----------------------------------------------------------------------------

$( document).on( "pagecreate", "#pageHome", function()
{
});

// -----------------------------------------------------------------------------

$( document).on( "pageshow", "#pageHome", function()
{
		var txt = '';
		txt += '
Wähle:
';

		txt += '
';
//		txt += '
Bestimmungsschlüssel
';
		txt += '
Häufige Vögel in Gärten und Siedlungen
';
		txt += '
Amphibien und Reptilien
';
		txt += '
Holzige Pflanzen in Deutschland
';
		txt += '
';

		$( '#pageHomeContent').html( txt);
		$( '#pageHomeContent').trigger( 'create');
		$( '#pageHomeContent').trigger( 'updatelayout');
});

// -----------------------------------------------------------------------------

$( document).on( "pageshow", "#pageLoadJSON", function()
{
	var data = $( '#pageLoadJSON').data( 'data-query');
	var txt = '';

	txt += 'Lade ' + data + '...';

	$( '#pageLoadJSONContent').html( txt);
	$( '#pageLoadJSONContent').trigger( 'create');
	$( '#pageLoadJSONContent').trigger( 'updatelayout');

	$.mobile.loading( "show", {
		text: 'Bin gleich fertig',
		textVisible: true,
		theme: 'b',
		textonly: false,
		html: ''});

	var url = 'https://b-content.com/projects/davinci/compress_Haeufige_Voegel_in_Gaerten_und_Siedlungen.json';
	var jqxhr = $.ajax( url)
	.done( function( data) {
//		var result = $.parseJSON( data);
	})
//	.fail( function() {
//		alert( "error" );
//	})
	.always( function() {
	$.mobile.loading( "hide" );
	});

});

// -----------------------------------------------------------------------------

$( document).on( "pagehide", "#pageLoadJSON", function()
{
	$( '#pageLoadJSONContent').html( '');
	$( '#pageLoadJSONContent').trigger( 'create');
	$( '#pageLoadJSONContent').trigger( 'updatelayout');
});

// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before>/*
---
description: Compiles an array of Wicks into an Element.

license: MIT-style

authors:
- Jose Prado

requires:
- core/1.3: '*'
- Compiler

provides: [Compiler.Lines]
...
*/
Compiler.Lines = new Class({

    Extends: Compiler,

    options: {
        altLines: null,
        containerTag: {
            parent: 'div',
            child:  null
        },
        linesTag: {
            parent: 'div',
            child:  'span'
        },
        numbersTag: 'span'
    },

    initialize: function(options)
    {
        this.parent(options);
    },

    _compile: function(fuel, flame, wicks)
    {
        var el           = new Element(this.options.containerTag.parent),
	        innerHtml    = '',
    	    lineNum      = 1,
    	    lines        = null,
    	    containerTag = this.options.containerTag;

    	// If lines need to be wrapped in an inner parent, create that element
    	// with this test. (E.g, tbody in a table)
    	if (containerTag.child !== null) {
    	    el = new Element(containerTag.child).inject(el);
    	}

    	innerHtml += '<' + this.options.linesTag.parent + '>';

    	innerHtml += '<' + this.options.numbersTag + ' class="' + flame + 'num">'
			+ lineNum++
			+ '</' + this.options.numbersTag + '>';

		innerHtml += '<' + this.options.linesTag.child
    		+ ' class="' + flame + 'line">';

    	// Step through each match and add wicks to the Element by breaking
    	// them up into individual lines.
		for (var i = 0; i < wicks.length; i++) {
    		var wick = wicks[i];
    		lines = wick.text.split('\n');

    		for (var j = 0; j < lines.length; j++) {

    			if (lines[j].length > 0) {
	    			var className = wick.type ? fuel.aliases[wick.type] || wick.type : '';
	    			innerHtml += '' + lines[j] + '';
    			}

    			if (j < lines.length - 1) {
    		    	innerHtml += '</' + this.options.linesTag.child + '>';
    		    	innerHtml += '</' + this.options.linesTag.parent + '>';
    		    	innerHtml += '<' + this.options.linesTag.parent + '>';

    		    	innerHtml += '<' + this.options.numbersTag
	    	    		+ ' class="' + flame + 'num">'
	    	    		+ lineNum++
	    	    		+ '</' + this.options.numbersTag + '>';

    				innerHtml += '<' + this.options.linesTag.child
    	    			+ ' class="' + flame + 'line">';
    			}
    		}
    	};

    	innerHtml += '</' + this.options.linesTag.child + '>';
    	innerHtml += '</' + this.options.linesTag.parent + '>';
    	el.set('html', innerHtml);

    	// Add alternate line styles based on pseudo-selector.
    	switch (this.options.altLines) {
    	    case null:
    	        break;

    	    case 'hover':
    	        el.getElements(containerTag.child || containerTag.parent).addEvents({
    				'mouseover': function() { this.toggleClass('alt'); },
    				'mouseout':  function() { this.toggleClass('alt'); }
    			});
    			break;

    	    default:
				el.getChildren(':' + this.options.altLines)
				    .getElement('.' + flame + 'line')
				    .addClass('alt');
    			break;
    	}

    	// Add first/last line classes to correct element based on mode.
		el.getFirst().getChildren().addClass(flame + 'first');
		el.getLast().getChildren().addClass(flame + 'last');

    	// Ensure we return the real parent, not just an inner element like a tbody.
    	if (containerTag.child) {
    	    el = el.getParent();
    	}

    	return el;
    }
});
<commit_msg>Added escaping of < since it messes with set('html'). set('html') expects valid HTML so an escape entities method must be implemented to avert this.<commit_after>/*
---
description: Compiles an array of Wicks into an Element.

license: MIT-style

authors:
- Jose Prado

requires:
- core/1.3: '*'
- Compiler

provides: [Compiler.Lines]
...
*/
Compiler.Lines = new Class({

    Extends: Compiler,

    options: {
        altLines: null,
        containerTag: {
            parent: 'div',
            child:  null
        },
        linesTag: {
            parent: 'div',
            child:  'span'
        },
        numbersTag: 'span'
    },

    initialize: function(options)
    {
        this.parent(options);
    },

    _compile: function(fuel, flame, wicks)
    {
        var el           = new Element(this.options.containerTag.parent),
	        innerHtml    = '',
    	    lineNum      = 1,
    	    lines        = null,
    	    containerTag = this.options.containerTag;

    	// If lines need to be wrapped in an inner parent, create that element
    	// with this test. (E.g, tbody in a table)
    	if (containerTag.child !== null) {
    	    el = new Element(containerTag.child).inject(el);
    	}

    	innerHtml += '<' + this.options.linesTag.parent + '>';

    	innerHtml += '<' + this.options.numbersTag + ' class="' + flame + 'num">'
			+ lineNum++
			+ '</' + this.options.numbersTag + '>';

		innerHtml += '<' + this.options.linesTag.child
    		+ ' class="' + flame + 'line">';

    	// Step through each match and add wicks to the Element by breaking
    	// them up into individual lines.
		for (var i = 0; i < wicks.length; i++) {
    		var wick = wicks[i];
    		lines = wick.text.split('\n');

    		for (var j = 0; j < lines.length; j++) {

    			if (lines[j].length > 0) {
	    			var className = wick.type ? fuel.aliases[wick.type] || wick.type : '',
	    				text = lines[j].replace('<', '<');
	    			innerHtml += '' + text + '';
    			}

    			if (j < lines.length - 1) {
    		    	innerHtml += '</' + this.options.linesTag.child + '>';
    		    	innerHtml += '</' + this.options.linesTag.parent + '>';
    		    	innerHtml += '<' + this.options.linesTag.parent + '>';

    		    	innerHtml += '<' + this.options.numbersTag
	    	    		+ ' class="' + flame + 'num">'
	    	    		+ lineNum++
	    	    		+ '</' + this.options.numbersTag + '>';

    				innerHtml += '<' + this.options.linesTag.child
    	    			+ ' class="' + flame + 'line">';
    			}
    		}
    	};

    	innerHtml += '</' + this.options.linesTag.child + '>';
    	innerHtml += '</' + this.options.linesTag.parent + '>';
    	el.set('html', innerHtml);

    	// Add alternate line styles based on pseudo-selector.
    	switch (this.options.altLines) {
    	    case null:
    	        break;

    	    case 'hover':
    	        el.getElements(containerTag.child || containerTag.parent).addEvents({
    				'mouseover': function() { this.toggleClass('alt'); },
    				'mouseout':  function() { this.toggleClass('alt'); }
    			});
    			break;

    	    default:
				el.getChildren(':' + this.options.altLines)
				    .getElement('.' + flame + 'line')
				    .addClass('alt');
    			break;
    	}

    	// Add first/last line classes to correct element based on mode.
		el.getFirst().getChildren().addClass(flame + 'first');
		el.getLast().getChildren().addClass(flame + 'last');

    	// Ensure we return the real parent, not just an inner element like a tbody.
    	if (containerTag.child) {
    	    el = el.getParent();
    	}

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


<commit_before>// Start of values.js

var typToType = { '  i8' : Int8Array ,
                  ' i16' : Int16Array ,
                  ' i32' : Int32Array ,
                  ' i64' : BigInt64Array ,
                  '  u8' : Uint8Array ,
                  ' u16' : Uint16Array ,
                  ' u32' : Uint32Array ,
                  ' u64' : BigUint64Array ,
                  ' f16' : Uint16Array ,
                  ' f32' : Float32Array ,
                  ' f64' : Float64Array ,
                  'bool' : Uint8Array
                };

function binToStringArray(buff, array) {
  for (var i = 0; i < array.length; i++) {
    array[i] = buff[i];
  }
}

function fileToBuff(fname) {
  var readline = require('readline');
  var fs = require('fs');
  var buff =  fs.readFileSync(fname);
  return buff;
}

var typToSize = {
  "bool" : 1,
  "  u8" : 1,
  "  i8" : 1,
  " u16" : 2,
  " i16" : 2,
  " u32" : 4,
  " i32" : 4,
  " f16" : 2,
  " f32" : 4,
  " u64" : 8,
  " i64" : 8,
  " f64" : 8,
}

function toU8(ta) {
  return new Uint8Array(ta.buffer, ta.byteOffset, ta.byteLength);
}

function construct_binary_value(v, typ) {
  var dims;
  var payload_bytes;
  var filler;
  if (v instanceof FutharkOpaque) {
    throw "Opaques are not supported";
  } else if (v instanceof FutharkArray) {
    var t = v.futharkType();
    var ftype = "    ".slice(t.length) + t;
    var shape = v.shape();
    var ta = v.toTypedArray(shape);
    var da = new BigInt64Array(shape);
    dims = shape.length;
    payload_bytes = da.byteLength + ta.byteLength;
    filler = (bytes) => {
      bytes.set(toU8(da), 7);
      bytes.set(toU8(ta), 7 + da.byteLength);
    }
  } else {
    var ftype = "    ".slice(typ.length) + typ;
    dims = 0;
    payload_bytes = typToSize[ftype];
    filler = (bytes) => {
      var scalar = new (typToType[ftype])([v]);
      bytes.set(toU8(scalar), 7);
    }
  }
  var total_bytes = 7 + payload_bytes;
  var bytes = new Uint8Array(total_bytes);
  bytes[0] = Buffer.from('b').readUInt8();
  bytes[1] = 2;
  bytes[2] = dims;
  for (var i = 0; i < 4; i++) {
    bytes[3+i] = ftype.charCodeAt(i);
  }
  filler(bytes);
  return Buffer.from(bytes);
}

class Reader {
  constructor(f) {
    this.f = f;
    this.buff = fileToBuff(f);
  }

  read_bin_array(num_dim, typ) {
    var u8_array = new Uint8Array(num_dim * 8);
    binToStringArray(this.buff.slice(0, num_dim * 8), u8_array);
    var shape = new BigInt64Array(u8_array.buffer);
    var length = shape[0];
    for (var i = 1; i < shape.length; i++) {
      length = length * shape[i];
    }
    length = Number(length);
    var dbytes = typToSize[typ];
    var u8_data = new Uint8Array(length * dbytes);
    binToStringArray(this.buff.slice(num_dim * 8, num_dim * 8 + dbytes * length), u8_data);
    var data  = new (typToType[typ])(u8_data.buffer);
    var tmp_buff = this.buff.slice(num_dim * 8, num_dim * 8 + dbytes * length);
    this.buff = this.buff.slice(num_dim * 8 + dbytes * length);
   return [shape, data];
  }

  read_bin_scalar(typ) {
    var size = typToSize[typ];
    var u8_array = new Uint8Array(size);
    binToStringArray(this.buff, u8_array);
    var array = new (typToType[typ])(u8_array.buffer);
    this.buff = this.buff.slice(u8_array.length); // Update buff to be unread part of the string
    return array[0];
  }

  skip_spaces() {
    while (this.buff.length > 0 && this.buff.slice(0, 1).toString().trim() == "") {
      this.buff = this.buff.slice(1);
    }
  }

  read_binary() {
    // Skip leading white space
    while (this.buff.slice(0, 1).toString().trim() == "") {
      this.buff = this.buff.slice(1);
    }
    if (this.buff[0] != 'b'.charCodeAt(0)) {
      throw "Not in binary format"
    }
    var version = this.buff[1];
    if (version != 2) {
      throw "Not version 2";
    }
    var num_dim = this.buff[2];
    var typ = this.buff.slice(3, 7);
    this.buff = this.buff.slice(7);
    if (num_dim == 0) {
      return this.read_bin_scalar(typ);
    } else {
      return this.read_bin_array(num_dim, typ);
    }
  }

  get_buff() {
    return this.buff;
  }
}

// Function is redudant but is helpful for keeping consistent with python implementation
function skip_spaces(reader) {
  reader.skip_spaces();
}

function read_value(typename, reader) {
  // TODO include typename in implementation
  var val = reader.read_binary();
  return val;
}

// End of values.js
<commit_msg>Add typename checking to values.js. (#1456)<commit_after>// Start of values.js
var futharkPrimtypes =
  new Set([
    'i8',
    'i16',
    'i32',
    'i64',
    'u8',
    'u16',
    'u32',
    'u64',
    'f16',
    'f32',
    'f64',
    'bool']);

var typToType = { '  i8' : Int8Array ,
                  ' i16' : Int16Array ,
                  ' i32' : Int32Array ,
                  ' i64' : BigInt64Array ,
                  '  u8' : Uint8Array ,
                  ' u16' : Uint16Array ,
                  ' u32' : Uint32Array ,
                  ' u64' : BigUint64Array ,
                  ' f16' : Uint16Array ,
                  ' f32' : Float32Array ,
                  ' f64' : Float64Array ,
                  'bool' : Uint8Array
                };

function binToStringArray(buff, array) {
  for (var i = 0; i < array.length; i++) {
    array[i] = buff[i];
  }
}

function fileToBuff(fname) {
  var readline = require('readline');
  var fs = require('fs');
  var buff =  fs.readFileSync(fname);
  return buff;
}

var typToSize = {
  "bool" : 1,
  "  u8" : 1,
  "  i8" : 1,
  " u16" : 2,
  " i16" : 2,
  " u32" : 4,
  " i32" : 4,
  " f16" : 2,
  " f32" : 4,
  " u64" : 8,
  " i64" : 8,
  " f64" : 8,
}

function toU8(ta) {
  return new Uint8Array(ta.buffer, ta.byteOffset, ta.byteLength);
}

function construct_binary_value(v, typ) {
  var dims;
  var payload_bytes;
  var filler;
  if (v instanceof FutharkOpaque) {
    throw "Opaques are not supported";
  } else if (v instanceof FutharkArray) {
    var t = v.futharkType();
    var ftype = "    ".slice(t.length) + t;
    var shape = v.shape();
    var ta = v.toTypedArray(shape);
    var da = new BigInt64Array(shape);
    dims = shape.length;
    payload_bytes = da.byteLength + ta.byteLength;
    filler = (bytes) => {
      bytes.set(toU8(da), 7);
      bytes.set(toU8(ta), 7 + da.byteLength);
    }
  } else {
    var ftype = "    ".slice(typ.length) + typ;
    dims = 0;
    payload_bytes = typToSize[ftype];
    filler = (bytes) => {
      var scalar = new (typToType[ftype])([v]);
      bytes.set(toU8(scalar), 7);
    }
  }
  var total_bytes = 7 + payload_bytes;
  var bytes = new Uint8Array(total_bytes);
  bytes[0] = Buffer.from('b').readUInt8();
  bytes[1] = 2;
  bytes[2] = dims;
  for (var i = 0; i < 4; i++) {
    bytes[3+i] = ftype.charCodeAt(i);
  }
  filler(bytes);
  return Buffer.from(bytes);
}

class Reader {
  constructor(f) {
    this.f = f;
    this.buff = fileToBuff(f);
  }

  read_bin_array(num_dim, typ) {
    var u8_array = new Uint8Array(num_dim * 8);
    binToStringArray(this.buff.slice(0, num_dim * 8), u8_array);
    var shape = new BigInt64Array(u8_array.buffer);
    var length = shape[0];
    for (var i = 1; i < shape.length; i++) {
      length = length * shape[i];
    }
    length = Number(length);
    var dbytes = typToSize[typ];
    var u8_data = new Uint8Array(length * dbytes);
    binToStringArray(this.buff.slice(num_dim * 8, num_dim * 8 + dbytes * length), u8_data);
    var data  = new (typToType[typ])(u8_data.buffer);
    var tmp_buff = this.buff.slice(num_dim * 8, num_dim * 8 + dbytes * length);
    this.buff = this.buff.slice(num_dim * 8 + dbytes * length);
   return [shape, data];
  }

  read_bin_scalar(typ) {
    var size = typToSize[typ];
    var u8_array = new Uint8Array(size);
    binToStringArray(this.buff, u8_array);
    var array = new (typToType[typ])(u8_array.buffer);
    this.buff = this.buff.slice(u8_array.length); // Update buff to be unread part of the string
    return array[0];
  }

  skip_spaces() {
    while (this.buff.length > 0 && this.buff.slice(0, 1).toString().trim() == "") {
      this.buff = this.buff.slice(1);
    }
  }

  read_binary(typename, dim) {
    // Skip leading white space
    while (this.buff.slice(0, 1).toString().trim() == "") {
      this.buff = this.buff.slice(1);
    }
    if (this.buff[0] != 'b'.charCodeAt(0)) {
      throw "Not in binary format"
    }
    var version = this.buff[1];
    if (version != 2) {
      throw "Not version 2";
    }
    var num_dim = this.buff[2];
    var typ = this.buff.slice(3, 7);
    this.buff = this.buff.slice(7);
    var exp_typ = "[]".repeat(dim) + typename;
    var given_typ = "[]".repeat(num_dim) + typ.toString().trim();
    console.log(exp_typ);
    console.log(given_typ);
    if (exp_typ !== given_typ) {
      throw ("Expected type : " + exp_typ + ", Actual type : " + given_typ);
    }
    if (num_dim === 0) {
      return this.read_bin_scalar(typ);
    } else {
      return this.read_bin_array(num_dim, typ);
    }
  }

  get_buff() {
    return this.buff;
  }
}

// Function is redudant but is helpful for keeping consistent with python implementation
function skip_spaces(reader) {
  reader.skip_spaces();
}

function read_value(typename, reader) {
  var typ = typename;
  var dim = 0;
  while (typ.slice(0, 2) === "[]") {
    dim = dim + 1;
    typ = typ.slice(2);
  }
  if (!futharkPrimtypes.has(typ)) {
    throw ("Unkown type: " + typ);
  }

  var val = reader.read_binary(typ, dim);
  return val;
}

// End of values.js
<|endoftext|>


<commit_before>import {
  Api,
  Exp,
  Logger,
  NotificationCode,
  UserSettings,
  MessageCode,
} from 'xdl';

import _ from 'lodash';
import os from 'os';
import path from 'path';
import React, { PropTypes } from 'react';
import LoadingIndicator from 'react-loading-indicator';

import Commands from './Commands';
import StyleConstants from './StyleConstants';
import SharedStyles from './Styles';
import * as IdentifierRules from 'xde/utils/IdentifierRules';

const ICON_SIZE = 120;
const MAX_PROJECT_LENGTH = 44;
const HALF_MAX_PROJECT_LENGTH = 20;

class NewProjectModal extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      isLoading: true,
      projectName: 'my-new-project',
      projectDirectory: null,
      errorMessage: null,
      loadingMessage: null,
      notificationType: null,
      showRetryPrompt: false,
      progress: null,
      templates: null,
      selectedTemplate: null,
    };
  }

  static propTypes = {
    onClose: PropTypes.func.isRequired,
    onSelectProject: PropTypes.func.isRequired,
  };

  _currentRequestID = 0;

  componentDidMount() {
    Logger.notifications.addStream({
      stream: {
        write: chunk => {
          switch (chunk.code) {
            case NotificationCode.PROGRESS:
              this.setState({
                loadingMessage: chunk.msg,
                notificationType: NotificationCode.PROGRESS,
              });
              break;
            case NotificationCode.DOWNLOAD:
              this.setState({
                loadingMessage: 'Downloading... ' + chunk.msg + '%',
                progress: chunk.msg,
                notificationType: NotificationCode.DOWNLOAD,
              });
              break;
            case NotificationCode.RETRY_DOWNLOAD:
              this.setState({
                showRetryPrompt: true,
              });
              break;
          }
        },
      },
      type: 'raw',
    });

    this._loadTemplatesAsync();
  }

  _loadTemplatesAsync = async () => {
    let versions = await Api.versionsAsync();
    let dir = await UserSettings.getAsync('defaultNewProjectDir', os.homedir());

    this.setState({
      isLoading: false,
      templates: versions.templatesv2,
      selectedTemplate: versions.templatesv2[0],
      projectDirectory: dir,
    });
  };

  render() {
    return (

        {this.state.isLoading ? this._renderLoading() : this._renderForm()}

    );
  }

  _selectTemplate = template => {
    this.setState({
      selectedTemplate: template,
    });
  };

  _renderTemplate = template => {
    let isSelected = this.state.selectedTemplate.id === template.id;

    return (

 this._selectTemplate(template)}>

          {template.name}

    );
  };

  _renderForm = () => {
    let { templates, selectedTemplate } = this.state;

    if (!templates) {
      return
;
    }

    return (
      <form
        name="newProject"
        style={Styles.form}
        onSubmit={this._onSubmitNewProject}>

          Choose a template for your project

            {_.map(templates, this._renderTemplate)}

          {selectedTemplate.description}

          Choose a project name and directory

        <input
          autoFocus
          type="text"
          className="form-control"
          style={Styles.input}
          ref="projectName"
          onChange={this._onProjectNameChange}
          value={this.state.projectName}
        />

          <input
            disabled
            type="text"
            className="form-control"
            style={{ color: StyleConstants.colorSubtitle }}
            ref="projectDirectory"
            value={this._getShortProjectDirectory()}
          />

            ...

        {this._renderErrors()}

          <button
            onClick={this._onClickCancel}
            type="button"
            style={Styles.cancelButton}>

Cancel

          </button>
          <button type="submit" style={Styles.submitButton}>

Create

          </button>

      </form>
    );
  };

  _renderErrors = () => {
    if (this.state.errorMessage) {
      return (

{this.state.errorMessage}

      );
    } else {
      return null;
    }
  };

  _renderLoading = () => {
    let downloading = this.state.notificationType === NotificationCode.DOWNLOAD;
    return (

        {downloading
          ?

          : <LoadingIndicator
              color={{
                red: 17,
                green: 114,
                blue: 182,
                alpha: 1.0,
              }}
              segmentWidth={6}
              segmentLength={15}
              spacing={9}
          />}
        {this.state.loadingMessage &&

            {this.state.loadingMessage}

}
        {this.state.showRetryPrompt
          ?

              {MessageCode.DOWNLOAD_IS_SLOW}

              <button
              onClick={this._onClickRetry}
              type="button"
              style={Styles.retryButton}>

Retry

            </button>

          :
}

    );
  };

  _onProjectNameChange = event => {
    let newValue = IdentifierRules.normalizeProjectNameWhileTyping(
      event.target.value
    );
    let errorMessage = null;
    if (newValue.length === 0) {
      errorMessage = 'Project name cannot be blank';
    }

    this.setState({
      projectName: newValue,
      errorMessage,
    });
  };

  _getShortProjectDirectory = () => {
    let { projectName, projectDirectory } = this.state;
    let dir = path.join(projectDirectory, projectName);
    if (dir.length < MAX_PROJECT_LENGTH) {
      return dir;
    } else {
      return `${dir.substr(0, HALF_MAX_PROJECT_LENGTH)}...${dir.substr(dir.length - HALF_MAX_PROJECT_LENGTH)}`;
    }
  };

  _onClickChangeProjectDirectoryAsync = async () => {
    try {
      let directory = await Commands.getDirectoryAsync(
        this.state.projectDirectory
      );
      if (!directory) {
        return;
      }

      await UserSettings.setAsync('defaultNewProjectDir', directory);
      this.setState({
        projectDirectory: directory,
      });
    } catch (e) {}
  };

  _onClickCancel = event => {
    event.preventDefault();
    this.props.onClose();
  };

  _onClickRetry = async event => {
    Exp.clearXDLCacheAsync();
    this.setState({ showRetryPrompt: false });
    this._onSubmitNewProject(event);
  };

  _onSubmitNewProject = async event => {
    event.preventDefault();
    const requestID = this._currentRequestID + 1;
    this._currentRequestID = requestID;

    if (this.state.projectName.length === 0) {
      this.setState({
        errorMessage: 'Project name cannot be blank',
      });
      return;
    } else {
      this.setState({
        errorMessage: null,
        loadingMessage: null,
        isLoading: true,
      });
    }

    try {
      let templateDownload = await Exp.downloadTemplateApp(
        this.state.selectedTemplate.id,
        this.state.projectDirectory,
        {
          name: this.state.projectName,
          progressFunction: progress => {
            if (this._currentRequestID === requestID) {
              Logger.notifications.info(
                { code: NotificationCode.DOWNLOAD },
                Math.round(progress * 100)
              );
            }
          },
          retryFunction: () =>
            Logger.notifications.info(
              { code: NotificationCode.RETRY_DOWNLOAD },
              MessageCode.DOWNLOAD_IS_SLOW
            ),
        }
      );

      if (this._currentRequestID !== requestID) {
        return;
      }

      let projectRoot = await Exp.extractTemplateApp(
        templateDownload.starterAppPath,
        templateDownload.name,
        templateDownload.root
      );
      if (!projectRoot) {
        this.setState({
          isLoading: false,
        });
        return;
      }

      await this.props.onSelectProject(projectRoot);
      this.props.onClose();
    } catch (e) {
      Exp.clearXDLCacheAsync();
      this.setState({
        isLoading: false,
        errorMessage: e.message,
      });
    }
  };
}

let Styles = {
  container: {
    fontFamily: 'Verdana',
    padding: StyleConstants.gutterLg,
    overflowWrap: 'break-word',

    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
  },
  loadingContainer: {
    padding: StyleConstants.gutterLg,
    minWidth: 250,

    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
  },
  form: {
    width: 400,
    display: 'flex',
    flexDirection: 'column',
  },
  templatesContainer: {
    display: 'flex',
    flexDirection: 'row',
    //alignItems: 'center',
    //justifyContent: 'center',
    marginTop: 5,
    marginBottom: 10,
    overflowX: 'auto',
    backgroundColor: '#f1f1f1',
    borderRadius: 3,
    paddingTop: 5,
    paddingBottom: 5,
  },
  templateContainer: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    marginLeft: 20,
    marginRight: 20,
    marginTop: 10,
    marginBottom: 10,
    paddingLeft: 20,
    paddingRight: 20,
    paddingTop: StyleConstants.gutterMd * 2,
    paddingBottom: StyleConstants.gutterMd,
    borderRadius: 4,
    cursor: 'pointer',
  },
  largeText: {
    fontWeight: 'bold',
    color: StyleConstants.colorText,
    fontSize: StyleConstants.fontSizeLg,
    paddingBottom: StyleConstants.gutterSm,
  },
  mediumText: {
    color: StyleConstants.colorSubtitle,
    fontSize: StyleConstants.fontSizeMd,
  },
  loadingText: {
    paddingTop: StyleConstants.gutterLg,
    color: StyleConstants.colorText,
    fontSize: StyleConstants.fontSizeMd,
  },
  buttonsContainer: {
    marginTop: 10,
    width: '100%',
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  cancelButton: {
    border: 'none',
    borderRadius: 5,
    color: 'black',
    padding: StyleConstants.gutterSm,
    width: '40%',

    backgroundColor: StyleConstants.colorCancel,
  },
  submitButton: {
    border: 'none',
    borderRadius: 5,
    color: 'white',
    padding: StyleConstants.gutterSm,
    width: '40%',

    backgroundColor: StyleConstants.colorPrimary,
  },
  retryButton: {
    border: 'none',
    borderRadius: 5,
    color: 'white',
    padding: StyleConstants.gutterSm,
    marginTop: 20,
    width: '40%',
    backgroundColor: StyleConstants.colorPrimary,
  },
  input: {
    marginBottom: StyleConstants.gutterMd,
  },
  icon: {
    width: ICON_SIZE,
    height: ICON_SIZE,
    marginBottom: StyleConstants.gutterMd,
    borderStyle: 'solid',
    borderWidth: 1,
    borderColor: 'black',
  },
  progress: {
    backgroundColor: StyleConstants.colorPrimary,
    height: 30,
  },
  progressBar: {
    backgroundColor: StyleConstants.colorLightBackground,
    height: 30,
    width: 200,
  },
};

export default NewProjectModal;
<commit_msg>Use Chromium's XMLHttpRequest in XDE, Node's http in exp (#1057)<commit_after>import {
  Api,
  Exp,
  Logger,
  NotificationCode,
  UserSettings,
  MessageCode,
} from 'xdl';

import _ from 'lodash';
import os from 'os';
import path from 'path';
import React, { PropTypes } from 'react';
import LoadingIndicator from 'react-loading-indicator';

import Commands from './Commands';
import StyleConstants from './StyleConstants';
import SharedStyles from './Styles';
import * as IdentifierRules from 'xde/utils/IdentifierRules';

const ICON_SIZE = 120;
const MAX_PROJECT_LENGTH = 44;
const HALF_MAX_PROJECT_LENGTH = 20;

class NewProjectModal extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      isLoading: true,
      projectName: 'my-new-project',
      projectDirectory: null,
      errorMessage: null,
      loadingMessage: null,
      notificationType: null,
      showRetryPrompt: false,
      progress: null,
      templates: null,
      selectedTemplate: null,
    };
  }

  static propTypes = {
    onClose: PropTypes.func.isRequired,
    onSelectProject: PropTypes.func.isRequired,
  };

  _currentRequestID = 0;

  componentDidMount() {
    Logger.notifications.addStream({
      stream: {
        write: chunk => {
          switch (chunk.code) {
            case NotificationCode.PROGRESS:
              this.setState({
                loadingMessage: chunk.msg,
                notificationType: NotificationCode.PROGRESS,
              });
              break;
            case NotificationCode.DOWNLOAD:
              this.setState({
                loadingMessage: 'Downloading... ' + chunk.msg + '%',
                progress: chunk.msg,
                notificationType: NotificationCode.DOWNLOAD,
              });
              break;
            case NotificationCode.RETRY_DOWNLOAD:
              this.setState({
                showRetryPrompt: true,
              });
              break;
          }
        },
      },
      type: 'raw',
    });

    this._loadTemplatesAsync();
  }

  _loadTemplatesAsync = async () => {
    let versions = await Api.versionsAsync();
    let dir = await UserSettings.getAsync('defaultNewProjectDir', os.homedir());

    this.setState({
      isLoading: false,
      templates: versions.templatesv2,
      selectedTemplate: versions.templatesv2[0],
      projectDirectory: dir,
    });
  };

  render() {
    return (

        {this.state.isLoading ? this._renderLoading() : this._renderForm()}

    );
  }

  _selectTemplate = template => {
    this.setState({
      selectedTemplate: template,
    });
  };

  _renderTemplate = template => {
    let isSelected = this.state.selectedTemplate.id === template.id;

    return (

 this._selectTemplate(template)}>

          {template.name}

    );
  };

  _renderForm = () => {
    let { templates, selectedTemplate } = this.state;

    if (!templates) {
      return
;
    }

    return (
      <form
        name="newProject"
        style={Styles.form}
        onSubmit={this._onSubmitNewProject}>

          Choose a template for your project

            {_.map(templates, this._renderTemplate)}

          {selectedTemplate.description}

          Choose a project name and directory

        <input
          autoFocus
          type="text"
          className="form-control"
          style={Styles.input}
          ref="projectName"
          onChange={this._onProjectNameChange}
          value={this.state.projectName}
        />

          <input
            disabled
            type="text"
            className="form-control"
            style={{ color: StyleConstants.colorSubtitle }}
            ref="projectDirectory"
            value={this._getShortProjectDirectory()}
          />

            ...

        {this._renderErrors()}

          <button
            onClick={this._onClickCancel}
            type="button"
            style={Styles.cancelButton}>

Cancel

          </button>
          <button type="submit" style={Styles.submitButton}>

Create

          </button>

      </form>
    );
  };

  _renderErrors = () => {
    if (this.state.errorMessage) {
      return (

{this.state.errorMessage}

      );
    } else {
      return null;
    }
  };

  _renderLoading = () => {
    let downloading = this.state.notificationType === NotificationCode.DOWNLOAD;
    return (

        {downloading
          ?

          : <LoadingIndicator
              color={{
                red: 17,
                green: 114,
                blue: 182,
                alpha: 1.0,
              }}
              segmentWidth={6}
              segmentLength={15}
              spacing={9}
          />}
        {this.state.loadingMessage &&

            {this.state.loadingMessage}

}
        {this.state.showRetryPrompt
          ?

              {MessageCode.DOWNLOAD_IS_SLOW}

              <button
              onClick={this._onClickRetry}
              type="button"
              style={Styles.retryButton}>

Retry

            </button>

          :
}

    );
  };

  _onProjectNameChange = event => {
    let newValue = IdentifierRules.normalizeProjectNameWhileTyping(
      event.target.value
    );
    let errorMessage = null;
    if (newValue.length === 0) {
      errorMessage = 'Project name cannot be blank';
    }

    this.setState({
      projectName: newValue,
      errorMessage,
    });
  };

  _getShortProjectDirectory = () => {
    let { projectName, projectDirectory } = this.state;
    let dir = path.join(projectDirectory, projectName);
    if (dir.length < MAX_PROJECT_LENGTH) {
      return dir;
    } else {
      return `${dir.substr(0, HALF_MAX_PROJECT_LENGTH)}...${dir.substr(dir.length - HALF_MAX_PROJECT_LENGTH)}`;
    }
  };

  _onClickChangeProjectDirectoryAsync = async () => {
    try {
      let directory = await Commands.getDirectoryAsync(
        this.state.projectDirectory
      );
      if (!directory) {
        return;
      }

      await UserSettings.setAsync('defaultNewProjectDir', directory);
      this.setState({
        projectDirectory: directory,
      });
    } catch (e) {}
  };

  _onClickCancel = event => {
    event.preventDefault();
    this.props.onClose();
  };

  _onClickRetry = async event => {
    Exp.clearXDLCacheAsync();
    this.setState({ showRetryPrompt: false });
    this._onSubmitNewProject(event);
  };

  _onSubmitNewProject = async event => {
    event.preventDefault();
    const requestID = this._currentRequestID + 1;
    this._currentRequestID = requestID;

    if (this.state.projectName.length === 0) {
      this.setState({
        errorMessage: 'Project name cannot be blank',
      });
      return;
    } else {
      this.setState({
        errorMessage: null,
        loadingMessage: null,
        isLoading: true,
      });
    }

    try {
      let templateDownload = await Exp.downloadTemplateApp(
        this.state.selectedTemplate.id,
        this.state.projectDirectory,
        {
          name: this.state.projectName,
          progressFunction: progress => {
            if (this._currentRequestID === requestID) {
              Logger.notifications.info(
                { code: NotificationCode.DOWNLOAD },
                progress
              );
            }
          },
          retryFunction: () =>
            Logger.notifications.info(
              { code: NotificationCode.RETRY_DOWNLOAD },
              MessageCode.DOWNLOAD_IS_SLOW
            ),
        }
      );

      if (this._currentRequestID !== requestID) {
        return;
      }

      let projectRoot = await Exp.extractTemplateApp(
        templateDownload.starterAppPath,
        templateDownload.name,
        templateDownload.root
      );
      if (!projectRoot) {
        this.setState({
          isLoading: false,
        });
        return;
      }

      await this.props.onSelectProject(projectRoot);
      this.props.onClose();
    } catch (e) {
      Exp.clearXDLCacheAsync();
      this.setState({
        isLoading: false,
        errorMessage: e.message,
      });
    }
  };
}

let Styles = {
  container: {
    fontFamily: 'Verdana',
    padding: StyleConstants.gutterLg,
    overflowWrap: 'break-word',

    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
  },
  loadingContainer: {
    padding: StyleConstants.gutterLg,
    minWidth: 250,

    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
  },
  form: {
    width: 400,
    display: 'flex',
    flexDirection: 'column',
  },
  templatesContainer: {
    display: 'flex',
    flexDirection: 'row',
    //alignItems: 'center',
    //justifyContent: 'center',
    marginTop: 5,
    marginBottom: 10,
    overflowX: 'auto',
    backgroundColor: '#f1f1f1',
    borderRadius: 3,
    paddingTop: 5,
    paddingBottom: 5,
  },
  templateContainer: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    marginLeft: 20,
    marginRight: 20,
    marginTop: 10,
    marginBottom: 10,
    paddingLeft: 20,
    paddingRight: 20,
    paddingTop: StyleConstants.gutterMd * 2,
    paddingBottom: StyleConstants.gutterMd,
    borderRadius: 4,
    cursor: 'pointer',
  },
  largeText: {
    fontWeight: 'bold',
    color: StyleConstants.colorText,
    fontSize: StyleConstants.fontSizeLg,
    paddingBottom: StyleConstants.gutterSm,
  },
  mediumText: {
    color: StyleConstants.colorSubtitle,
    fontSize: StyleConstants.fontSizeMd,
  },
  loadingText: {
    paddingTop: StyleConstants.gutterLg,
    color: StyleConstants.colorText,
    fontSize: StyleConstants.fontSizeMd,
  },
  buttonsContainer: {
    marginTop: 10,
    width: '100%',
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  cancelButton: {
    border: 'none',
    borderRadius: 5,
    color: 'black',
    padding: StyleConstants.gutterSm,
    width: '40%',

    backgroundColor: StyleConstants.colorCancel,
  },
  submitButton: {
    border: 'none',
    borderRadius: 5,
    color: 'white',
    padding: StyleConstants.gutterSm,
    width: '40%',

    backgroundColor: StyleConstants.colorPrimary,
  },
  retryButton: {
    border: 'none',
    borderRadius: 5,
    color: 'white',
    padding: StyleConstants.gutterSm,
    marginTop: 20,
    width: '40%',
    backgroundColor: StyleConstants.colorPrimary,
  },
  input: {
    marginBottom: StyleConstants.gutterMd,
  },
  icon: {
    width: ICON_SIZE,
    height: ICON_SIZE,
    marginBottom: StyleConstants.gutterMd,
    borderStyle: 'solid',
    borderWidth: 1,
    borderColor: 'black',
  },
  progress: {
    backgroundColor: StyleConstants.colorPrimary,
    height: 30,
  },
  progressBar: {
    backgroundColor: StyleConstants.colorLightBackground,
    height: 30,
    width: 200,
  },
};

export default NewProjectModal;
<|endoftext|>


<commit_before>var module = angular.module("OpenChainWallet.Models", []);
var bitcore = require("bitcore");

module.value("walletSettings", {
    hdKey: null,
    derivedKey: null,
    rootAccount: null,
    initialized: false,
    versionPrefix: "v1",
    network: null,
    setRootKey: function (key) {
        this.hdKey = key;
        this.network = key.network;
        this.derivedKey = key.derive(44, true).derive(22, true).derive(0, true).derive(0).derive(0);
        this.rootAccount = "/p2pkh/" + this.derivedKey.privateKey.toAddress().toString() + "/";
        this.initialized = true;
    },
    getAssetKey: function (index) {
        return this.hdKey.derive(44, true).derive(22, true).derive(1, true).derive(0).derive(index);
    }
});

module.factory("Endpoint", function ($q, apiService, encodingService) {

    var Endpoint = function (properties) {
        var _this = this;

        this.properties = properties;
        this.rootUrl = properties.rootUrl;
        this.assets = {};

        this.downloadAssetDefinition = function (assetPath) {
            return apiService.getValue(_this, encodingService.encodeData(assetPath, "asdef")).then(function (result) {
                if (result.value.remaining() == 0) {
                    return { key: result.key, value: null, version: result.version };
                }
                else {
                    return { key: result.key, value: JSON.parse(encodingService.decodeString(result.value)), version: result.version };
                }
            })
        };

        this.getAssetDefinition = function (assetPath, noCache) {
            if (!noCache && assetPath in _this.assets) {
                return $q.resolve(_this.assets[assetPath]);
            }
            else {
                return _this.downloadAssetDefinition(assetPath).then(function (result) {

                    if (result.value != null) {
                        assetInfo = {
                            name: result.value.name,
                            nameShort: result.value.name_short,
                            iconUrl: result.value.icon_url,
                            path: assetPath,
                            key: result.key,
                            version: result.version
                        };
                    }
                    else {
                        assetInfo = {
                            version: result.version
                        };
                    }

                    _this.assets[assetPath] = assetInfo;

                    return $q.resolve(assetInfo);
                })
            };
        };
    }

    return Endpoint;
});

module.factory("AssetData", function ($q, apiService, encodingService) {

    var AssetData = function (endpoint, assetPath) {
        var _this = this;

        this.asset = assetPath;
        this.endpoint = endpoint;

        if (endpoint.rootUrl.slice(endpoint.rootUrl.length - 1, endpoint.rootUrl.length) == "/") {
            this.fullPath = endpoint.rootUrl + assetPath.slice(1, assetPath.length);
        }
        else {
            this.fullPath = endpoint.rootUrl + assetPath;
        }

        this.setAccountBalance = function (balanceData) {
            _this.currentRecord = balanceData;
        };

        this.fetchAssetDefinition = function () {
            return this.endpoint.getAssetDefinition(this.asset).then(function(result) {
                _this.assetDefinition = result;
            });
        };
    }

    return AssetData;
});

module.factory("LedgerRecord", function (LedgerPath, encodingService) {
    var LedgerRecord = function (path, recordType, name) {
        var _this = this;

        this.path = LedgerPath.parse(path);
        this.recordType = recordType;
        this.name = name;

        this.toString = function () {
            return _this.path.toString() + ":" + _this.recordType + ":" + _this.name;
        };

        this.toByteBuffer = function () {
            return ByteBuffer.wrap(_this.toString(), "utf8", true);
        };
    }

    LedgerRecord.parse = function (value) {
        var text = value;
        if (typeof text !== "string") {
            text = encodingService.decodeString(text);
        }

        var parts = text.split(":");

        if (parts.length < 3) {
            throw "Invalid record key";
        }

        return new LedgerRecord(parts[0], parts[1], parts.slice(2, parts.length).join(":"));
    };

    return LedgerRecord;
});

module.factory("LedgerPath", function () {
    var LedgerPath = function (parts) {
        var _this = this;

        this.parts = parts;

        this.toString = function () {
            return "/" + _this.parts.map(function (item) { return item + "/" }).join("");
        };
    }

    LedgerPath.parse = function (value) {
        var parts = value.split("/");

        if (parts.length < 2 || parts[0] != "" || parts[parts.length - 1] != "") {
            throw "Invalid path";
        }

        return new LedgerPath(parts.slice(1, parts.length - 1));
    };

    return LedgerPath;
});

module.service("TransactionBuilder", function ($q, $rootScope, $location, apiService, protobufBuilder, encodingService) {

    var TransactionBuilder = function (endpoint) {
        var _this = this;

        this.endpoint = endpoint;
        this.records = [];

        this.addRecord = function (key, value, version) {
            var newRecord = {
                "key": key,
                "version": version
            };

            if (value != null) {
                newRecord["value"] = { "data": value };
            }
            else {
                newRecord["value"] = null;
            }

            _this.records.push(newRecord);

            return _this;
        };

        this.addAccountRecord = function(previous, change) {
            return _this.addRecord(
                previous.key,
                encodingService.encodeInt64(previous.balance.add(change)),
                previous.version);
        };

        this.fetchAndAddAccountRecord = function (account, asset, change) {
            if (account.slice(0, 1) == "@") {
                var resolvedAccount = apiService.getData(_this.endpoint, "/aka/" + account.slice(1, account.length) + "/", "goto").then(function (result) {
                    if (result.data == null) {
                        return $q.reject("Unable to resolve the alias");
                    }
                    else {
                        _this.addRecord(result.key, null, result.version);
                        return $q.when(result.data);
                    }
                });
            }
            else {
                var resolvedAccount = $q.when(account);
            }

            return resolvedAccount.then(function (accountResult) {
                return apiService.getAccount(_this.endpoint, accountResult, asset);
            })
            .then(function (currentRecord) {
                _this.addAccountRecord(currentRecord, change);
            });
        }

        this.submit = function (key) {
            var constructedTransaction = new protobufBuilder.Mutation({
                "namespace": encodingService.encodeString(_this.endpoint.rootUrl),
                "records": _this.records,
                "metadata": ByteBuffer.fromHex("")
            });

            return apiService.postTransaction(_this.endpoint, constructedTransaction.encode(), key);
        };

        this.uiSubmit = function (key) {
            $rootScope.submitTransaction = { transaction: _this, key: key };
            $location.path("/submit");
        };
    }

    return TransactionBuilder;
});<commit_msg>Change the way aliases work<commit_after>var module = angular.module("OpenChainWallet.Models", []);
var bitcore = require("bitcore");

module.value("walletSettings", {
    hdKey: null,
    derivedKey: null,
    rootAccount: null,
    initialized: false,
    versionPrefix: "v1",
    network: null,
    setRootKey: function (key) {
        this.hdKey = key;
        this.network = key.network;
        this.derivedKey = key.derive(44, true).derive(22, true).derive(0, true).derive(0).derive(0);
        this.rootAccount = "/p2pkh/" + this.derivedKey.privateKey.toAddress().toString() + "/";
        this.initialized = true;
    },
    getAssetKey: function (index) {
        return this.hdKey.derive(44, true).derive(22, true).derive(1, true).derive(0).derive(index);
    }
});

module.factory("Endpoint", function ($q, apiService, encodingService) {

    var Endpoint = function (properties) {
        var _this = this;

        this.properties = properties;
        this.rootUrl = properties.rootUrl;
        this.assets = {};

        this.downloadAssetDefinition = function (assetPath) {
            return apiService.getValue(_this, encodingService.encodeData(assetPath, "asdef")).then(function (result) {
                if (result.value.remaining() == 0) {
                    return { key: result.key, value: null, version: result.version };
                }
                else {
                    return { key: result.key, value: JSON.parse(encodingService.decodeString(result.value)), version: result.version };
                }
            })
        };

        this.getAssetDefinition = function (assetPath, noCache) {
            if (!noCache && assetPath in _this.assets) {
                return $q.resolve(_this.assets[assetPath]);
            }
            else {
                return _this.downloadAssetDefinition(assetPath).then(function (result) {

                    if (result.value != null) {
                        assetInfo = {
                            name: result.value.name,
                            nameShort: result.value.name_short,
                            iconUrl: result.value.icon_url,
                            path: assetPath,
                            key: result.key,
                            version: result.version
                        };
                    }
                    else {
                        assetInfo = {
                            version: result.version
                        };
                    }

                    _this.assets[assetPath] = assetInfo;

                    return $q.resolve(assetInfo);
                })
            };
        };
    }

    return Endpoint;
});

module.factory("AssetData", function ($q, apiService, encodingService) {

    var AssetData = function (endpoint, assetPath) {
        var _this = this;

        this.asset = assetPath;
        this.endpoint = endpoint;

        if (endpoint.rootUrl.slice(endpoint.rootUrl.length - 1, endpoint.rootUrl.length) == "/") {
            this.fullPath = endpoint.rootUrl + assetPath.slice(1, assetPath.length);
        }
        else {
            this.fullPath = endpoint.rootUrl + assetPath;
        }

        this.setAccountBalance = function (balanceData) {
            _this.currentRecord = balanceData;
        };

        this.fetchAssetDefinition = function () {
            return this.endpoint.getAssetDefinition(this.asset).then(function(result) {
                _this.assetDefinition = result;
            });
        };
    }

    return AssetData;
});

module.factory("LedgerRecord", function (LedgerPath, encodingService) {
    var LedgerRecord = function (path, recordType, name) {
        var _this = this;

        this.path = LedgerPath.parse(path);
        this.recordType = recordType;
        this.name = name;

        this.toString = function () {
            return _this.path.toString() + ":" + _this.recordType + ":" + _this.name;
        };

        this.toByteBuffer = function () {
            return ByteBuffer.wrap(_this.toString(), "utf8", true);
        };
    }

    LedgerRecord.parse = function (value) {
        var text = value;
        if (typeof text !== "string") {
            text = encodingService.decodeString(text);
        }

        var parts = text.split(":");

        if (parts.length < 3) {
            throw "Invalid record key";
        }

        return new LedgerRecord(parts[0], parts[1], parts.slice(2, parts.length).join(":"));
    };

    return LedgerRecord;
});

module.factory("LedgerPath", function () {
    var LedgerPath = function (parts) {
        var _this = this;

        this.parts = parts;

        this.toString = function () {
            return "/" + _this.parts.map(function (item) { return item + "/" }).join("");
        };
    }

    LedgerPath.parse = function (value) {
        var parts = value.split("/");

        if (parts.length < 2 || parts[0] != "" || parts[parts.length - 1] != "") {
            throw "Invalid path";
        }

        return new LedgerPath(parts.slice(1, parts.length - 1));
    };

    return LedgerPath;
});

module.service("TransactionBuilder", function ($q, $rootScope, $location, apiService, protobufBuilder, encodingService) {

    var TransactionBuilder = function (endpoint) {
        var _this = this;

        this.endpoint = endpoint;
        this.records = [];

        this.addRecord = function (key, value, version) {
            var newRecord = {
                "key": key,
                "version": version
            };

            if (value != null) {
                newRecord["value"] = { "data": value };
            }
            else {
                newRecord["value"] = null;
            }

            _this.records.push(newRecord);

            return _this;
        };

        this.addAccountRecord = function(previous, change) {
            return _this.addRecord(
                previous.key,
                encodingService.encodeInt64(previous.balance.add(change)),
                previous.version);
        };

        this.fetchAndAddAccountRecord = function (account, asset, change) {
            // Resolve name accounts
            if (account.slice(0, 1) == "@") {
                account = "/aka/" + account.slice(1, account.length) + "/";
            }

            return apiService.getData(_this.endpoint, account, "goto").then(function (result) {
                if (result.data == null) {
                    return account;
                }
                else {
                    // If a goto DATA record exists, we use the redirected path
                    _this.addRecord(result.key, null, result.version);
                    return result.data;
                }
            }).then(function (accountResult) {
                return apiService.getAccount(_this.endpoint, accountResult, asset);
            })
            .then(function (currentRecord) {
                _this.addAccountRecord(currentRecord, change);
            });
        }

        this.submit = function (key) {
            var constructedTransaction = new protobufBuilder.Mutation({
                "namespace": encodingService.encodeString(_this.endpoint.rootUrl),
                "records": _this.records,
                "metadata": ByteBuffer.fromHex("")
            });

            return apiService.postTransaction(_this.endpoint, constructedTransaction.encode(), key);
        };

        this.uiSubmit = function (key) {
            $rootScope.submitTransaction = { transaction: _this, key: key };
            $location.path("/submit");
        };
    }

    return TransactionBuilder;
});<|endoftext|>


<commit_before>/*
 * Please see the included LICENSE.md file for license terms and conditions.
 */

(function() {

	// Wait for DOM tree is ready for access
    document.addEventListener('DOMContentLoaded', function() {
        var canvas = document.getElementById('gameScene');
        // make canvas full screen
        var width = screen.availWidth;
        var height = screen.availHeight;
        canvas.width = width;
        canvas.height = height;

        // get canvas 2d context
        // With canvas 2d context, you can draw anything freely on the canvas.
        // See https://docs.webplatform.org/wiki/tutorials/canvas/canvas_tutorial
        // for tutorials of using canvas.
        var context = canvas.getContext('2d');
        var gravity = 10;

        var playerImg = new Image();
        playerImg.src = "asset/9ja.png";

        var player = {
            tapLength: 0,
            x: 0,
            y: 0,
            velX: 0,
            velY: 0,
            w: 128,
            h: 128,
            runSpeed: 0,
            maxXSpeed: 20,
            maxYSpeed: 20,

            tap: function() {
                //on an enemy
                    //Sword dashes to the enemy
                //on ceiling
                    //player.grapple(x,y)
                //on anything else (or nothing)
                    //player.jump()
            },

            act: function() {
                // Set the player's X velocity

                player.velX += player.runSpeed; // If touching, runSpeed is positive, otherwise smaller negative

                // Limit velX 0-maxSpeed
                if (player.velX < 0) {
                    player.velX = 0;
                }
                if (player.velX > player.maxXSpeed) {
                    player.velX = player.maxXSpeed;
                }

                // If the player has velocity, move them appropriately
                player.x += player.velX;
                player.y += player.velY;

                // Set the player's Y velocity
                player.velY += gravity;
                if (player.velY > player.maxYSpeed) {
                    player.velY = player.maxYSpeed;
                }
                if (player.velY < -player.maxYSpeed) {
                    player.velY = -player.maxYSpeed;
                }

                // Limit player position

                if (player.x + player.w > canvas.width) {
                        console.log("Player hit right edge of screen");
                        player.x = canvas.width - player.w;
                        player.velX *= -1;
                }
                if (player.x < 0) {
                        console.log("Player hit left edge of screen");
                        player.x = 0;
                        player.velX *= -1;
                }
                if (player.y + player.h > canvas.height) {
                        console.log("Player hit bottom edge of screen");
                        player.y = canvas.height - player.h;
                        player.velY = 0;
                }
                if (player.y < 0) {
                        console.log("Player hit top edge of screen");
                        player.y = 0;
                        player.velY *= -0.75;
                }
            },

            draw: function() {
                context.drawImage(playerImg, player.x, player.y);
            }
        };

/*
        function floor(ix, iy, itype) {
            this.x = ix;
            this.y = iy;
            this.w = 32;
            this.h = 32;
            this.type = itype;

            this.draw = function() {
				context.fillRect(this.x,this.y,this.w,this.h);
            };

        }

        var world = {
            myFloors: [],

            draw: function() {
                var i = 0;
                for (i = 0; i < this.myFloors.length; i++) {
                    this.myFloors[i].draw();
                }
            },

            init: function() {
                var i = 0;
                for (i = 0; i < width/32; i++) {
                    this.myFloors[i] = new floor(i*32, height - 64, 1);
                }
            }

        };

        var myFloor = new floor(32, 32, 1);

        world.init();
*/
        function draw(){
				context.clearRect(0,0,canvas.width,canvas.height);
				//context.fillRect(player.x,player.y,player.w,player.h);
                player.draw();
//                myFloor.draw();
//                world.draw();
                //context.drawImage(player.img, 0, 0);
                //handler.draw();

        }

        this.addEventListener("touchstart", touchstarthandler,false);
        this.addEventListener("touchend", touchendhandler,false);

        var end, start;
        function touchstarthandler(event)
        {
            if(event.screenX>width/2){
                player.runSpeed = 10;
                start = new Date();
            }
        }
        function touchendhandler(event)
        {
            player.runSpeed = -5;
            end = new Date();
            player.tapLength = end.getTime()-start.getTime();
            if(player.tapLength < 300){
                // do tap things: jump, attack, grapple, etc.
                //console.log("TAP! ");

            }
        }

        function game() {
            //console.log("Player: X: " + player.x + ", Y: " + player.y + ", velX: " + player.velX + ", velY: " + player.velY);
            player.act();
        }

        var gameTimer = setInterval(game,1000/30);
		var drawTimer = setInterval(draw,1000/30);

    }, false);

}());
<commit_msg>Camera follow<commit_after>/*
 * Please see the included LICENSE.md file for license terms and conditions.
 */

(function() {

	// Wait for DOM tree is ready for access
    document.addEventListener('DOMContentLoaded', function() {
        var canvas = document.getElementById('gameScene');

        // make canvas full screen
        var width = screen.availWidth;
        var height = screen.availHeight;

        /*
        //Lock in landscape orientation
        document.addEventListener("intel.xdk.device.ready", onDeviceReady, false);
        function onDeviceReady(){
            intel.xdk.device.setRotateOrientation('landscape');
            intel.xdk.device.hideSplashScreen();
        }
        */

        canvas.width = width;
        canvas.height = height;

        // get canvas 2d context
        // With canvas 2d context, you can draw anything freely on the canvas.
        // See https://docs.webplatform.org/wiki/tutorials/canvas/canvas_tutorial
        // for tutorials of using canvas.
        var context = canvas.getContext('2d');
        var gravity = 10;

        function Rectangle(left, top, width, height){
			this.left = left || 0;
			this.top = top || 0;
            this.width = width || 0;
			this.height = height || 0;
			this.right = this.left + this.width;
			this.bottom = this.top + this.height;
		}

		Rectangle.prototype.set = function(left, top, /*optional*/width, /*optional*/height){
			this.left = left;
            this.top = top;
            this.width = width || this.width;
            this.height = height || this.height;
            this.right = (this.left + this.width);
            this.bottom = (this.top + this.height);
		};

		Rectangle.prototype.within = function(r) {
			return (r.left <= this.left &&
					r.right >= this.right &&
					r.top <= this.top &&
					r.bottom >= this.bottom);
		};

		Rectangle.prototype.overlaps = function(r) {
			return (this.left < r.right &&
					r.left < this.right &&
					this.top < r.bottom &&
					r.top < this.bottom);
		};

        // possibles axis to move the camera
        var AXIS = {
            NONE: "none",
            HORIZONTAL: "horizontal",
            VERTICAL: "vertical",
            BOTH: "both"
        };

        // Camera constructor
        function Camera(xView, yView, canvasWidth, canvasHeight, worldWidth, worldHeight)
        {
            // position of camera (left-top coordinate)
            this.xView = xView || 0;
            this.yView = yView || 0;

            // distance from followed object to border before camera starts move
            this.xDeadZone = 0; // min distance to horizontal borders
            this.yDeadZone = 0; // min distance to vertical borders

            // viewport dimensions
            this.wView = canvasWidth;
            this.hView = canvasHeight;

            // allow camera to move in vertical and horizontal axis
            this.axis = AXIS.BOTH;

            // object that should be followed
            this.followed = null;

            // rectangle that represents the viewport
            this.viewportRect = new Rectangle(this.xView, this.yView, this.wView, this.hView);

            // rectangle that represents the world's boundary (room's boundary)
            this.worldRect = new Rectangle(0, 0, worldWidth, worldHeight);

        }

        // gameObject needs to have "x" and "y" properties (as world(or room) position)
        Camera.prototype.follow = function(gameObject, xDeadZone, yDeadZone)
        {
            this.followed = gameObject;
            this.xDeadZone = xDeadZone;
            this.yDeadZone = yDeadZone;
        };

        Camera.prototype.update = function()
        {
            // keep following the player (or other desired object)
            if(this.followed !== null)
            {
                if(this.axis == AXIS.HORIZONTAL || this.axis == AXIS.BOTH)
                {
                    // moves camera on horizontal axis based on followed object position
                    if(this.followed.x - this.xView  + this.xDeadZone > this.wView)
                        this.xView = this.followed.x - (this.wView - this.xDeadZone);
                    else if(this.followed.x  - this.xDeadZone < this.xView)
                        this.xView = this.followed.x  - this.xDeadZone;

                }
                if(this.axis == AXIS.VERTICAL || this.axis == AXIS.BOTH)
                {
                    // moves camera on vertical axis based on followed object position
                    if(this.followed.y - this.yView + this.yDeadZone > this.hView)
                        this.yView = this.followed.y - (this.hView - this.yDeadZone);
                    else if(this.followed.y - this.yDeadZone < this.yView)
                        this.yView = this.followed.y - this.yDeadZone;
                }

            }

            // update viewportRect
            this.viewportRect.set(this.xView, this.yView);
            console.log("Xv: " + this.xView + ", Yv: " + this.yView);

            // don't let camera leaves the world's boundary
            if(!this.viewportRect.within(this.worldRect))
            {
                console.warn("Camera left world boundaries");
                if(this.viewportRect.left < this.worldRect.left)
                    this.xView = this.worldRect.left;
                if(this.viewportRect.top < this.worldRect.top)
                    this.yView = this.worldRect.top;
                if(this.viewportRect.right > this.worldRect.right)
                    this.xView = this.worldRect.right - this.wView;
                if(this.viewportRect.bottom > this.worldRect.bottom)
                    this.yView = this.worldRect.bottom - this.hView;
            }

        };

        var playerImg = new Image();
        playerImg.src = "asset/9ja.png";

        var player = {
            tapLength: 0,
            x: 0,
            y: 0,
            velX: 0,
            velY: 0,
            w: 128,
            h: 128,
            runSpeed: 0,
            maxXSpeed: 20,
            maxYSpeed: 20,

            tap: function() {
                //on an enemy
                    //Sword dashes to the enemy
                //on ceiling
                    //player.grapple(x,y)
                //on anything else (or nothing)
                    //player.jump()
            },

            update: function() {
                // Set the player's X velocity

                player.velX += player.runSpeed; // If touching, runSpeed is positive, otherwise smaller negative

                // Limit velX 0-maxSpeed
                if (player.velX < 0) {
                    player.velX = 0;
                }
                if (player.velX > player.maxXSpeed) {
                    player.velX = player.maxXSpeed;
                }

                // If the player has velocity, move them appropriately
                player.x += player.velX;
                player.y += player.velY;

                // Set the player's Y velocity
                player.velY += gravity;
                if (player.velY > player.maxYSpeed) {
                    player.velY = player.maxYSpeed;
                }
                if (player.velY < -player.maxYSpeed) {
                    player.velY = -player.maxYSpeed;
                }

                // Limit player position

                if (player.x + player.w > 2000) {
                        console.log("Player hit right edge of screen");
                        player.x = canvas.width - player.w;
                        //player.velX *= -1;
                }
                if (player.x < 0) {
                        console.log("Player hit left edge of screen");
                        player.x = 0;
                        player.velX *= -1;
                }

                if (player.y + player.h > canvas.height) {
                        console.log("Player hit bottom edge of screen");
                        player.y = canvas.height - player.h;
                        player.velY = 0;
                }
                if (player.y < 0) {
                        console.log("Player hit top edge of screen");
                        player.y = 0;
                        player.velY *= -0.75;
                }
            },

            draw: function() {
                //context.drawImage(playerImg, player.x, player.y);
                //context.fillRect(, , this.width, this.height);
                context.drawImage(playerImg, (this.x-this.w/2) - camera.xView, (this.y-this.h/2) - camera.yView);

            }
        };

        function floor(ix, iy, itype) {
            this.x = ix;
            this.y = iy;
            this.w = 32;
            this.h = 32;
            this.type = itype;

            this.draw = function() {
				context.fillRect((this.x-this.w/2) - camera.xView, (this.y-this.h/2) - camera.yView, this.w, this.h);
            };

        }

/*
        var world = {
            myFloors: [],

            draw: function() {
                var i = 0;
                for (i = 0; i < this.myFloors.length; i++) {
                    this.myFloors[i].draw();
                }
            },

            init: function() {
                var i = 0;
                for (i = 0; i < width/32; i++) {
                    this.myFloors[i] = new floor(i*32, height - 64, 1);
                }
            }

        };
        world.init();

*/

        var myFloor = new floor(100, 400, 1);

        function draw(){
				context.clearRect(0,0,canvas.width,canvas.height);
				//context.fillRect(player.x,player.y,player.w,player.h);
                player.draw();
                myFloor.draw();
//                world.draw();
                //context.drawImage(player.img, 0, 0);
                //handler.draw();

        }

        this.addEventListener("touchstart", touchstarthandler,false);
        this.addEventListener("touchend", touchendhandler,false);

        var camera = new Camera(0, 0, canvas.width, canvas.height, 2000, 2000);
		camera.follow(player, canvas.width/2, canvas.height/2);

        var end, start;
        function touchstarthandler(event)
        {
            if(event.screenX>width/2){
                player.runSpeed = 10;
                start = new Date();
            }
        }

        function touchendhandler(event)
        {
            player.runSpeed = -5;
            end = new Date();
            player.tapLength = end.getTime()-start.getTime();
            if(player.tapLength < 300){
                // do tap things: jump, attack, grapple, etc.
                //console.log("TAP! ");
            }
        }

        function game() {
            console.log("Player: X: " + player.x + ", Y: " + player.y + ", velX: " + player.velX + ", velY: " + player.velY);
            player.update();
            camera.update();

        }

        var gameTimer = setInterval(game,1000/30);
		var drawTimer = setInterval(draw,1000/30);

    }, false);

}());
<|endoftext|>


<commit_before>/*
---

script: Fieldset.js

description: Wrapper around set of form fields

license: Public domain (http://unlicense.org).

requires:
  - LSD.Mixin

provides:
  - LSD.Mixin.Fieldset

...
*/
!function() {

LSD.Mixin.Fieldset = new Class({
  options: {
    has: {
      many: {
        elements: {
          selector: ':form-associated',
          scopes: {
            submittable: {
              filter: '[name]'
            },
            invalid: {
              filter: ':invalid'
            }
          },
          callbacks: {
            add: 'addField',
            remove: 'removeField'
          }
        }
      }
    },
    expects: {
      ':form': function(widget, state) {
        widget[state ? 'addRelation' : 'removeRelation']('elements', {as: 'form'});
      }
    }
  },

  constructors: {
    fieldset: function(options, state) {
      if (state) {
        this.values = new LSD.Object.Params;
        this.fields = new LSD.Object.Params;
      }
      this.variables[state ? 'merge' : 'unmerge']({values: this.values, fields: this.fields});
      if (!state) {
        delete this.values;
        delete this.field;
      }
      this[state ? 'addEvents' : 'removeEvents'](LSD.Mixin.Fieldset.events);
    }
  },

  checkValidity: function() {
    return this.elements.every(function(element) {
      return element.checkValidity();
    });
  },

  getData: function() {
    this.submittedFields = new LSD.Object.Params(this.fields.toObject(true, true));
    return this.submittedFields;
  },

  getRequestData: function() {
    return this.getData.apply(this, arguments);
  },

  reset: function() {

  },

  addFieldErrors: function(errors) {
    for (var name in errors) {
      var field = this.submittedFields && this.submittedFields.get(name) || this.fields.get(name);
      if (!field) continue;
      if (!field.lsd) {
        for (var i in field)
          if (field[i] != null && field[i].lsd) {
            field = field[i];
            break;
          }
        if (field == null || !field.lsd) continue;
      }
      field.invalidate(errors[name]);
    }
    this.errors = errors;
    this.addEvent('beforeSubmit:once', this.removeFieldErrors);
  },

  removeFieldErrors: function() {
    var errors = this.errors;
    for (var name in errors) {
      var field = this.submittedFields && this.submittedFields.get(name) || this.fields.get(name);
      if (!field) continue;
      if (!field.lsd) {
        for (var i in field)
          if (field[i] != null && field[i].lsd) {
            field = field[i];
            break;
          }
        if (field == null || !field.lsd) continue;
      }
      if (field.invalid) field.setStateTo('invalid', false);
    }
    delete this.errors
  },

  parseFieldErrors: function(response, result, root) {
    var errors = response.errors;
    if (typeof response == "object") {
      if (typeof result != 'object') result = {};
      if (errors) {
        if (errors.push) {
          for (var i = 0, error; error = errors[i++];)
            result[Fieldset.getName(root || this.getModelName(error[0]), error[0])] = error[1];
        } else {
          for (var name in errors)
            result[Fieldset.getName(root || this.getModelName(name), name)] = errors[name];
        }
      }
      Object.each(response, function(value, key) {
        if (typeof value == "object" && value != null && key != 'errors') {
          this.parseFieldErrors(value, result, root ? root + '[' + key + ']' : key);
        }
      }, this)
    }
    if (result != null && Object.getLength(result) > 0 && root == null) this.addFieldErrors(result);
  },

  addField: function(widget) {
    var name = widget.attributes.name;
    if (!name || !widget.toData) return;
    var callback = function(value, old) {
      if (typeof value == 'undefined') {
        if (typeof old != 'undefined') this.values.unset(name, widget.getValue());
      } else {
        this.values.set(name, widget.getValue());
      }
    }.bind(this)
    callback._callback = this;
    if (LSD.Mixin.Command.getCommandType.call(widget) == 'command')
      this.values.set(name, widget.getValue());
    widget.states.watch('checked', callback);
    var key = widget.lsd + ':value:callback'
    var callback = this.retrieve(key);
    if (!callback) {
      callback = function(value, old) {
        if (typeof old != 'undefined')
          this.values.unset(name, old);
        this.values.set(name, value)
      }.bind(this)
      this.store(key, callback)
    }
    widget.addEvent('change', callback);
    this.fields.set(name, widget)
  },

  getParams: function(object) {
    if (!object) object = this.values;
    var result = {};
    for (var name in object) {
      var value = object[name];
      if (value && !value.indexOf) value = value.nodeType ? value.getValue() : this.getParams(value);
      result[name] = value;
    }
    return result;
  },

  removeField: function(widget) {
    var name = widget.attributes.name;
    if (!name) return;
    widget.states.unwatch('checked', this);
    this.fields.unset(name, widget)
    this.values.unset(name, widget.getValue());
    var key = widget.lsd + ':value:callback'
    var callback = this.retrieve(key);
    if (callback) widget.removeEvent('change', callback);
  },

  getFieldsByName: function(fields, callback, root) {
    if (fields.call && (callback = fields)) fields = null;
    if (!fields) fields = this.elements;
    if (!callback && fields.indexOf) return root[fields]
    if (fields.map && fields.each && (!callback || !root)) return fields.map(function(field) {
      return this.getFieldsByName(field, callback, root)
    }.bind(this));
  },

  getModelName: function() {
    for (var name in this.fields)
      if (this.fields.has(name))
        if (!this.fields[name].nodeType) return name;
  }
});

var Fieldset = Object.append(LSD.Mixin.Fieldset, {
  rNameIndexBumper: /(\[)(\d+?)(\])/,
  rIdIndexBumper:   /(_)(\d+?)(_|$)/,
  rNameMultiplier:  /(?:\[\])?$/,
  rPrefixAppender:  /^[^\[]+/,
  getName: function(model, name) {
    return model + name.replace(Fieldset.rPrefixAppender, function(match) {return '[' + match + ']'});
  },
  bumpName: function(string) {
    return string.replace(Fieldset.rNameIndexBumper, function(m, a, index, b) {
      return a + (parseInt(index) + 1) + b;
    })
  },
  bumpId: function(string) {
    return string.replace(Fieldset.rIdIndexBumper, function(m, a, index, b) {
      return a + (parseInt(index) + 1) + b;
    })
  },
  multiplyName: function(string) {
    return string.replace(Fieldset.rNameMultiplier, '[]')
  }
});

Fieldset.events = {
  request: {
    badRequest: 'parseFieldErrors'
  },
  self: {
    beforeNodeBuild: function(query, widget) {
      if (!widget.options.clone) return;
      var attrs = query.attributes, attributes = widget.attributes;
      var name = attributes.name, id = attributes.id;
      if (widget.tagName == 'label') var four = attributes['for'];
      for (var taken = this.fields.get(name); taken;) {
        // bump name index
        name = Fieldset.bumpName(name);
        // bump id index
        if (id) id = Fieldset.bumpId(id);
        // bump for attribute
        if (four) four = Fieldset.bumpId(four) || four;
        if (!name || !(taken = this.fields.get(name))) {
          if (name) (attrs || (attrs = {})).name = name;
          if (id) (attrs || (attrs = {})).id = id;
          if (four != null) (attrs || (attrs = {}))['for'] = four;
          if (attrs) query.attributes = attrs;
        }
      }
    }
  }
};

LSD.Behavior.define(':fieldset', 'fieldset');

}();<commit_msg>Keep prefix in validation errors for nested object<commit_after>/*
---

script: Fieldset.js

description: Wrapper around set of form fields

license: Public domain (http://unlicense.org).

requires:
  - LSD.Mixin

provides:
  - LSD.Mixin.Fieldset

...
*/
!function() {

LSD.Mixin.Fieldset = new Class({
  options: {
    has: {
      many: {
        elements: {
          selector: ':form-associated',
          scopes: {
            submittable: {
              filter: '[name]'
            },
            invalid: {
              filter: ':invalid'
            }
          },
          callbacks: {
            add: 'addField',
            remove: 'removeField'
          }
        }
      }
    },
    expects: {
      ':form': function(widget, state) {
        widget[state ? 'addRelation' : 'removeRelation']('elements', {as: 'form'});
      }
    }
  },

  constructors: {
    fieldset: function(options, state) {
      if (state) {
        this.values = new LSD.Object.Params;
        this.fields = new LSD.Object.Params;
      }
      this.variables[state ? 'merge' : 'unmerge']({values: this.values, fields: this.fields});
      if (!state) {
        delete this.values;
        delete this.field;
      }
      this[state ? 'addEvents' : 'removeEvents'](LSD.Mixin.Fieldset.events);
    }
  },

  checkValidity: function() {
    return this.elements.every(function(element) {
      return element.checkValidity();
    });
  },

  getData: function() {
    this.submittedFields = new LSD.Object.Params(this.fields.toObject(true, true));
    return this.submittedFields;
  },

  getRequestData: function() {
    return this.getData.apply(this, arguments);
  },

  reset: function() {

  },

  addFieldErrors: function(errors) {
    for (var name in errors) {
      var field = this.submittedFields && this.submittedFields.get(name) || this.fields.get(name);
      if (!field) continue;
      if (!field.lsd) {
        for (var i in field)
          if (field[i] != null && field[i].lsd) {
            field = field[i];
            break;
          }
        if (field == null || !field.lsd) continue;
      }
      field.invalidate(errors[name]);
    }
    this.errors = errors;
    this.addEvent('beforeSubmit:once', this.removeFieldErrors);
  },

  removeFieldErrors: function() {
    var errors = this.errors;
    for (var name in errors) {
      var field = this.submittedFields && this.submittedFields.get(name) || this.fields.get(name);
      if (!field) continue;
      if (!field.lsd) {
        for (var i in field)
          if (field[i] != null && field[i].lsd) {
            field = field[i];
            break;
          }
        if (field == null || !field.lsd) continue;
      }
      if (field.invalid) field.setStateTo('invalid', false);
    }
    delete this.errors
  },

  parseFieldErrors: function(response, result, root) {
    var errors = response.errors;
    debugger
    if (typeof response == "object") {
      if (typeof result != 'object') result = {};
      if (errors) {
        if (errors.push) {
          for (var i = 0, error; error = errors[i++];)
            result[Fieldset.getName(root || this.getModelName(error[0]), error[0])] = error[1];
        } else {
          for (var name in errors)
            result[Fieldset.getName(root || this.getModelName(name), name)] = errors[name];
        }
      }
      Object.each(response, function(value, key) {
        if (typeof value == "object" && value != null && key != 'errors') {
          this.parseFieldErrors(value, result, Fieldset.getName(root || this.getModelName(key), key));
        }
      }, this)
    }
    if (result != null && Object.getLength(result) > 0 && root == null) this.addFieldErrors(result);
  },

  addField: function(widget) {
    var name = widget.attributes.name;
    if (!name || !widget.toData) return;
    var callback = function(value, old) {
      if (typeof value == 'undefined') {
        if (typeof old != 'undefined') this.values.unset(name, widget.getValue());
      } else {
        this.values.set(name, widget.getValue());
      }
    }.bind(this)
    callback._callback = this;
    if (LSD.Mixin.Command.getCommandType.call(widget) == 'command')
      this.values.set(name, widget.getValue());
    widget.states.watch('checked', callback);
    var key = widget.lsd + ':value:callback'
    var callback = this.retrieve(key);
    if (!callback) {
      callback = function(value, old) {
        if (typeof old != 'undefined')
          this.values.unset(name, old);
        this.values.set(name, value)
      }.bind(this)
      this.store(key, callback)
    }
    widget.addEvent('change', callback);
    this.fields.set(name, widget)
  },

  getParams: function(object) {
    if (!object) object = this.values;
    var result = {};
    for (var name in object) {
      var value = object[name];
      if (value && !value.indexOf) value = value.nodeType ? value.getValue() : this.getParams(value);
      result[name] = value;
    }
    return result;
  },

  removeField: function(widget) {
    var name = widget.attributes.name;
    if (!name) return;
    widget.states.unwatch('checked', this);
    this.fields.unset(name, widget)
    this.values.unset(name, widget.getValue());
    var key = widget.lsd + ':value:callback'
    var callback = this.retrieve(key);
    if (callback) widget.removeEvent('change', callback);
  },

  getFieldsByName: function(fields, callback, root) {
    if (fields.call && (callback = fields)) fields = null;
    if (!fields) fields = this.elements;
    if (!callback && fields.indexOf) return root[fields]
    if (fields.map && fields.each && (!callback || !root)) return fields.map(function(field) {
      return this.getFieldsByName(field, callback, root)
    }.bind(this));
  },

  getModelName: function() {
    for (var name in this.fields)
      if (this.fields.has(name))
        if (!this.fields[name].nodeType) return name;
  }
});

var Fieldset = Object.append(LSD.Mixin.Fieldset, {
  rNameIndexBumper: /(\[)(\d+?)(\])/,
  rIdIndexBumper:   /(_)(\d+?)(_|$)/,
  rNameMultiplier:  /(?:\[\])?$/,
  rPrefixAppender:  /^[^\[]+/,
  getName: function(model, name) {
    return model + name.replace(Fieldset.rPrefixAppender, function(match) {return '[' + match + ']'});
  },
  bumpName: function(string) {
    return string.replace(Fieldset.rNameIndexBumper, function(m, a, index, b) {
      return a + (parseInt(index) + 1) + b;
    })
  },
  bumpId: function(string) {
    return string.replace(Fieldset.rIdIndexBumper, function(m, a, index, b) {
      return a + (parseInt(index) + 1) + b;
    })
  },
  multiplyName: function(string) {
    return string.replace(Fieldset.rNameMultiplier, '[]')
  }
});

Fieldset.events = {
  request: {
    badRequest: 'parseFieldErrors'
  },
  self: {
    beforeNodeBuild: function(query, widget) {
      if (!widget.options.clone) return;
      var attrs = query.attributes, attributes = widget.attributes;
      var name = attributes.name, id = attributes.id;
      if (widget.tagName == 'label') var four = attributes['for'];
      for (var taken = this.fields.get(name); taken;) {
        // bump name index
        name = Fieldset.bumpName(name);
        // bump id index
        if (id) id = Fieldset.bumpId(id);
        // bump for attribute
        if (four) four = Fieldset.bumpId(four) || four;
        if (!name || !(taken = this.fields.get(name))) {
          if (name) (attrs || (attrs = {})).name = name;
          if (id) (attrs || (attrs = {})).id = id;
          if (four != null) (attrs || (attrs = {}))['for'] = four;
          if (attrs) query.attributes = attrs;
        }
      }
    }
  }
};

LSD.Behavior.define(':fieldset', 'fieldset');

}();<|endoftext|>