<commit_before>var tape = require('tape'),
	weblas = require('../index'),
	loader = require('floader'); // browserify aware file loader (xhr in browser)

var RTOL = 1e-05,
	ATOL = 1e-07;

var gl = weblas.gpu.gl;

tape("Tensor.combine: 8 x 8", function(t){
	t.plan(1);
	var x1 = new Float32Array([  1.0,  2.0,  3.0,  4.0,
								 9.0, 10.0, 11.0, 12.0,
								17.0, 18.0, 19.0, 20.0,
								25.0, 26.0, 27.0, 28.0,
								33.0, 34.0, 35.0, 36.0,
								41.0, 42.0, 43.0, 44.0,
								49.0, 50.0, 51.0, 52.0,
								57.0, 58.0, 59.0, 60.0,]),
		x2 = new Float32Array([  5.0,  6.0,  7.0,  8.0,
								13.0, 14.0, 15.0, 16.0,
								21.0, 22.0, 23.0, 24.0,
								29.0, 30.0, 31.0, 32.0,
								37.0, 38.0, 39.0, 40.0,
								45.0, 46.0, 47.0, 48.0,
								53.0, 54.0, 55.0, 56.0,
								61.0, 62.0, 63.0, 64.0]),
		expected = new Float32Array([ 1.0,  2.0,  3.0,  4.0,  5.0,  6.0,  7.0,  8.0,
									   9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
									  17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0,
									  25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0,
									  33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0,
									  41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0,
									  49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0,
									  57.0, 58.0, 59.0, 60.0, 61.0, 62.0, 63.0, 64.0]);

	var M = 8, N = 4,
		t1 = new weblas.pipeline.Tensor([M, N], x1),
		t2 = new weblas.pipeline.Tensor([M, N], x2);

	try{
		// when splitting texture for t0 is deleted by default
		t0 = weblas.pipeline.Tensor.combine(t1, t2, N);
		// when transfering texture for t1 is deleted by default
		var result = t0.transfer();
	}
	catch(ex){
		t.error(ex);

		return;
	}

	weblas.test.assert.allclose(t, result, expected, null, RTOL, ATOL);
});

matrixFiles = ['a0.arr', 'a1.arr', 'out.arr'];

var m = 13,
	n = 13,
	channels = 192;
var testDirectory = "./test/data/combine/" + "0001" + '/';

//console.log("a: " + a + "; b: " + b);
var testName = "Tensor.combine: " + m + "x" + n + "x" + channels;
tape(testName, generateCombineTestCase(testDirectory, m, n * channels, channels));

m = 27;
n = 27;
channels = 128;
var testDirectory = "./test/data/combine/" + "0002" + '/';

//console.log("a: " + a + "; b: " + b);
var testName = "Tensor.combine: " + m + "x" + n + "x" + channels;
tape(testName, generateCombineTestCase(testDirectory, m, n * channels, channels));

m = 27;
n = 27;
channels = 128;
var testDirectory = "./test/data/combine/" + "0003" + '/';

//console.log("a: " + a + "; b: " + b);
var testName = "Tensor.combine: " + m + "x" + n + "x" + channels;
tape(testName, generateCombineTestCase(testDirectory, m, n * channels, channels));

m = 13;
n = 13;
channels = 128;
var testDirectory = "./test/data/combine/" + "0004" + '/';

//console.log("a: " + a + "; b: " + b);
var testName = "Tensor.combine: " + m + "x" + n + "x" + channels;
tape(testName, generateCombineTestCase(testDirectory, m, n * channels, channels));

function generateCombineTestCase(testDirectory, M, N, channels){
	return function(t){
		var pad = weblas.gpu.gl.getPad(N * 2);
		if(pad == 0){
			t.plan(1);
		} else {
			t.plan(2);
		}

		var X0, X1, expected; // typed arrays

		// directory containing matrix data files for current test

		// load matrices from files
		weblas.test.load(testDirectory, matrixFiles, function(err, matrices){

			if(err){
				t.error(err);
				if(pad != 0) t.notOk(false, "skipping padding test");

				return;
			}

			// matrices is an array which matches matrixFiles
			var X0 = matrices[0],
				X1 = matrices[1],
				expected = matrices[2];

			if(!(X0 && X0.length && X0.length == M * N) ||
				!(X1 && X1.length && X1.length == M * N)){

				throw new Error("malformed data");
			}

			var t0 = new weblas.pipeline.Tensor([M, N], X0),
				t1 = new weblas.pipeline.Tensor([M, N], X1),
				t2;

			try{
				t2 = weblas.pipeline.Tensor.combine(t0, t1, channels);
			} catch(ex){
				t.error(ex);
				if(pad != 0) t.notOk(false, "skipping padding test");

				return;
			}

			// when transfering texture for t1 is deleted by default
			var result = t2.transfer(true);

			testWithPad(t, M, N * 2, pad, result, expected, t2.texture, RTOL, ATOL);
			t2.delete();

		});
	};
}

function testWithPad(t,  M, N, pad, result, expected, texture, RTOL, ATOL){

	weblas.test.assert.allclose(t, result, expected, null, RTOL, ATOL);

	if(pad > 0){

		// use internals to check that texture is padded correctly
		var padded;

		try{
			padded = weblas.test.padData(M, N, pad, expected);
			out = weblas.gpu.gl.createOutputTexture(M, N + pad);

			// float extraction
			weblas.gpu.encode(M, N + pad, texture, out);
			result = new Float32Array(weblas.gpu.gl.readData(M, N + pad));

			weblas.gpu.gl.context.deleteTexture(out);
		}
		catch(ex){
			t.assert(false, ex);
		}

		weblas.test.assert.allclose(t, result, padded, null, RTOL, ATOL);
	}
}
<commit_msg>tensor.combine: skip test on missing files<commit_after>var tape = require('tape'),
	weblas = require('../index'),
	loader = require('floader'); // browserify aware file loader (xhr in browser)

var RTOL = 1e-05,
	ATOL = 1e-07;

var gl = weblas.gpu.gl;

tape("Tensor.combine: 8 x 8", function(t){
	t.plan(1);
	var x1 = new Float32Array([  1.0,  2.0,  3.0,  4.0,
								 9.0, 10.0, 11.0, 12.0,
								17.0, 18.0, 19.0, 20.0,
								25.0, 26.0, 27.0, 28.0,
								33.0, 34.0, 35.0, 36.0,
								41.0, 42.0, 43.0, 44.0,
								49.0, 50.0, 51.0, 52.0,
								57.0, 58.0, 59.0, 60.0,]),
		x2 = new Float32Array([  5.0,  6.0,  7.0,  8.0,
								13.0, 14.0, 15.0, 16.0,
								21.0, 22.0, 23.0, 24.0,
								29.0, 30.0, 31.0, 32.0,
								37.0, 38.0, 39.0, 40.0,
								45.0, 46.0, 47.0, 48.0,
								53.0, 54.0, 55.0, 56.0,
								61.0, 62.0, 63.0, 64.0]),
		expected = new Float32Array([ 1.0,  2.0,  3.0,  4.0,  5.0,  6.0,  7.0,  8.0,
									   9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
									  17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0,
									  25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0,
									  33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0,
									  41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0,
									  49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0,
									  57.0, 58.0, 59.0, 60.0, 61.0, 62.0, 63.0, 64.0]);

	var M = 8, N = 4,
		t1 = new weblas.pipeline.Tensor([M, N], x1),
		t2 = new weblas.pipeline.Tensor([M, N], x2);

	try{
		// when splitting texture for t0 is deleted by default
		t0 = weblas.pipeline.Tensor.combine(t1, t2, N);
		// when transfering texture for t1 is deleted by default
		var result = t0.transfer();
	}
	catch(ex){
		t.error(ex);

		return;
	}

	weblas.test.assert.allclose(t, result, expected, null, RTOL, ATOL);
});

matrixFiles = ['a0.arr', 'a1.arr', 'out.arr'];

var m = 13,
	n = 13,
	channels = 192;
var testDirectory = "./test/data/combine/" + "0001" + '/';

//console.log("a: " + a + "; b: " + b);
var testName = "Tensor.combine: " + m + "x" + n + "x" + channels;
tape(testName, generateCombineTestCase(testDirectory, m, n * channels, channels));

m = 27;
n = 27;
channels = 128;
var testDirectory = "./test/data/combine/" + "0002" + '/';

//console.log("a: " + a + "; b: " + b);
var testName = "Tensor.combine: " + m + "x" + n + "x" + channels;
tape(testName, generateCombineTestCase(testDirectory, m, n * channels, channels));

m = 27;
n = 27;
channels = 128;
var testDirectory = "./test/data/combine/" + "0003" + '/';

//console.log("a: " + a + "; b: " + b);
var testName = "Tensor.combine: " + m + "x" + n + "x" + channels;
tape(testName, generateCombineTestCase(testDirectory, m, n * channels, channels));

m = 13;
n = 13;
channels = 128;
var testDirectory = "./test/data/combine/" + "0004" + '/';

//console.log("a: " + a + "; b: " + b);
var testName = "Tensor.combine: " + m + "x" + n + "x" + channels;
tape(testName, generateCombineTestCase(testDirectory, m, n * channels, channels));

function generateCombineTestCase(testDirectory, M, N, channels){
	return function(t){

		var X0, X1, expected; // typed arrays

		// directory containing matrix data files for current test

		// load matrices from files
		weblas.test.load(testDirectory, matrixFiles, function(err, matrices){

			if(err){
				t.skip("Unable to load files: " + err.message);
				t.end();

				return;
			}

			var pad = weblas.gpu.gl.getPad(N * 2);
			if(pad == 0){
				t.plan(1);
			} else {
				t.plan(2);
			}

			// matrices is an array which matches matrixFiles
			var X0 = matrices[0],
				X1 = matrices[1],
				expected = matrices[2];

			if(!(X0 && X0.length && X0.length == M * N) ||
				!(X1 && X1.length && X1.length == M * N)){

				throw new Error("malformed data");
			}

			var t0 = new weblas.pipeline.Tensor([M, N], X0),
				t1 = new weblas.pipeline.Tensor([M, N], X1),
				t2;

			try{
				t2 = weblas.pipeline.Tensor.combine(t0, t1, channels);
			} catch(ex){
				t.error(ex);
				if(pad != 0) t.notOk(false, "skipping padding test");

				return;
			}

			// when transfering texture for t1 is deleted by default
			var result = t2.transfer(true);

			testWithPad(t, M, N * 2, pad, result, expected, t2.texture, RTOL, ATOL);
			t2.delete();

		});
	};
}

function testWithPad(t,  M, N, pad, result, expected, texture, RTOL, ATOL){

	weblas.test.assert.allclose(t, result, expected, null, RTOL, ATOL);

	if(pad > 0){

		// use internals to check that texture is padded correctly
		var padded;

		try{
			padded = weblas.test.padData(M, N, pad, expected);
			out = weblas.gpu.gl.createOutputTexture(M, N + pad);

			// float extraction
			weblas.gpu.encode(M, N + pad, texture, out);
			result = new Float32Array(weblas.gpu.gl.readData(M, N + pad));

			weblas.gpu.gl.context.deleteTexture(out);
		}
		catch(ex){
			t.assert(false, ex);
		}

		weblas.test.assert.allclose(t, result, padded, null, RTOL, ATOL);
	}
}
<|endoftext|>


<commit_before>"use strict"

var stronglyConnectedComponents = require("strongly-connected-components")
var bounds = require("binary-search-bounds")

module.exports = solve2Sat

function clauseToVariable(x, n) {
  if(x < 0) {
    return (-1 - x) + n
  } else {
    return x - 1
  }
}

function negate(x, n) {
  if(x < n) {
    return x + n
  } else {
    return x - n
  }
}

function compareInt(a,b) {
  return a - b
}

function contains(cc, v) {
  var b = bounds.le(cc, v)
  if(b < cc.length) {
    return cc[b] === v
  }
  return false
}

function solve2Sat(numVariables, clauses) {
  //Build implication graph
  var edges = []
  var adj = new Array(2 * numVariables)
  for(var i=0; i<2*numVariables; ++i) {
    adj[i] = []
  }
  for(var i=0; i<clauses.length; ++i) {
    var c = clauses[i]
    var a = clauseToVariable(c[0], numVariables)
    var b = clauseToVariable(c[1], numVariables)
    var na = negate(a,numVariables)
    edges.push([na, b])
    adj[na].push(b)
    var nb = negate(b,numVariables)
    console.log(c,a,b,na,nb)
    edges.push([nb, a])
    adj[nb].push(a)
  }

  //Extract strongly connected components
  var scc = stronglyConnectedComponents(2*numVariables, edges)

  //Mark cells and check satisfiability
  var solution = new Array(2 * numVariables)
  for(var i=0; i<solution.length; ++i) {
    solution[i] = -1
  }

  for(var i=0; i<scc.length; ++i) {
    var cc = scc[i]
    cc.sort(compareInt)

    //Visit all nodes in queue
    var to_visit = []
    var color = 0
    for(var j=0; j<cc.length; ++j) {
      var v = cc[j]
      if(v < numVariables && contains(cc, numVariables + v)) {
        return false
      }
      var s = solution[v]
      if(s >= 0) {
        color = s
      }
    }

    //Update solution in component
    for(var j=0; j<cc.length; ++j) {
      var v = cc[j]
      var nv = negate(v, numVariables)
      solution[v] = color
      solution[nv] = color^1
      var e = color ? adj[v] : adj[nv]
      for(var k=0; k<e.length; ++k) {
        solution[e[k]] = 1
      }
    }
  }

  solution.length = numVariables
  return solution
}<commit_msg>sonofaconsole.log<commit_after>"use strict"

var stronglyConnectedComponents = require("strongly-connected-components")
var bounds = require("binary-search-bounds")

module.exports = solve2Sat

function clauseToVariable(x, n) {
  if(x < 0) {
    return (-1 - x) + n
  } else {
    return x - 1
  }
}

function negate(x, n) {
  if(x < n) {
    return x + n
  } else {
    return x - n
  }
}

function compareInt(a,b) {
  return a - b
}

function contains(cc, v) {
  var b = bounds.le(cc, v)
  if(b >= 0) {
    return cc[b] === v
  }
  return false
}

function solve2Sat(numVariables, clauses) {
  //Build implication graph
  var edges = []
  var adj = new Array(2 * numVariables)
  for(var i=0; i<2*numVariables; ++i) {
    adj[i] = []
  }
  for(var i=0; i<clauses.length; ++i) {
    var c = clauses[i]
    var a = clauseToVariable(c[0], numVariables)
    var b = clauseToVariable(c[1], numVariables)
    var na = negate(a,numVariables)
    edges.push([na, b])
    adj[na].push(b)
    var nb = negate(b,numVariables)
    edges.push([nb, a])
    adj[nb].push(a)
  }

  //Extract strongly connected components
  var scc = stronglyConnectedComponents(2*numVariables, edges)

  //Mark cells and check satisfiability
  var solution = new Array(2 * numVariables)
  for(var i=0; i<solution.length; ++i) {
    solution[i] = -1
  }

  for(var i=0; i<scc.length; ++i) {
    var cc = scc[i]
    cc.sort(compareInt)

    //Visit all nodes in queue
    var to_visit = []
    var color = 0
    for(var j=0; j<cc.length; ++j) {
      var v = cc[j]
      if(v < numVariables && contains(cc, numVariables + v)) {
        return false
      }
      var s = solution[v]
      if(s >= 0) {
        color = s
      }
    }

    //Update solution in component
    for(var j=0; j<cc.length; ++j) {
      var v = cc[j]
      var nv = negate(v, numVariables)
      solution[v] = color
      solution[nv] = color^1
      var e = color ? adj[v] : adj[nv]
      for(var k=0; k<e.length; ++k) {
        solution[e[k]] = 1
      }
    }
  }

  solution.length = numVariables
  return solution
}<|endoftext|>


<commit_before>import VueMdc from 'src'
import { Vue } from '../helpers/utils.js'

function comp (name) {
  return function () {
    should.exist(Vue.component(name))
  }
}

function dir (name) {
  return function () {
    should.exist(Vue.directive(name))
  }
}

describe('VueMdc', function () {
  describe('Register components', function () {
    before(function () {
      Vue.use(VueMdc)
    })

    it('registers MdcButton', comp('MdcButton'))

    it('registers MdcCheckbox', comp('MdcCheckbox'))

    it('registers MdcCard', comp('MdcCard'))
    it('registers MdcCard', comp('MdcCard'))
    it('registers MdcCardActions', comp('MdcCardActions'))
    it('registers MdcCardHorizontalBlock', comp('MdcCardHorizontalBlock'))
    it('registers MdcCardMedia', comp('MdcCardMedia'))
    it('registers MdcCardPrimary', comp('MdcCardPrimary'))
    it('registers MdcCardSubtitle', comp('MdcCardSubtitle'))
    it('registers MdcCardSupportingText', comp('MdcCardSupportingText'))
    it('registers MdcCardTitle', comp('MdcCardTitle'))

    it('registers MdcDrawer', comp('MdcDrawer'))
    it('registers MdcDrawerHeader', comp('MdcDrawerHeader'))
    it('registers MdcDrawerNav', comp('MdcDrawerNav'))
    it('registers MdcDrawerNavItem', comp('MdcDrawerNavItem'))

    it('registers MdcList', comp('MdcList'))
    it('registers MdcListDivider', comp('MdcListDivider'))

    it('registers v-ripple', dir('ripple'))
  })
  describe('Prefixes', function () {
    before(function () {
      VueMdc.installed = false
      Vue.use(VueMdc, {
        prefix: 'Ui',
      })
    })
    it('registers UiButton', comp('UiButton'))
    console.log(Vue.compile('<ui-button>Hey</ui-button>'))
  })
})
<commit_msg>✅ Refactor component testing<commit_after>import VueMdc from 'src'
import { Vue } from '../helpers/utils.js'

function comp (name) {
  return function () {
    should.exist(Vue.component(name))
  }
}

function dir (name) {
  return function () {
    should.exist(Vue.directive(name))
  }
}

const components = [
  'Button',

  'Checkbox',

  'Card',
  'Card',
  'CardActions',
  'CardHorizontalBlock',
  'CardMedia',
  'CardPrimary',
  'CardSubtitle',
  'CardSupportingText',
  'CardTitle',

  'Drawer',
  'DrawerHeader',
  'DrawerNav',
  'DrawerNavItem',

  'List',
  'ListDivider',
]

describe('VueMdc', function () {
  describe('Register components', function () {
    before(function () {
      Vue.use(VueMdc)
    })

    components.forEach(name => {
      it(`registers Mdc${name}`, comp(`Mdc${name}`))
    })

    it('registers v-ripple', dir('ripple'))
  })
  describe('Prefixes', function () {
    before(function () {
      VueMdc.installed = false
      Vue.use(VueMdc, {
        prefix: 'Ui',
      })
    })
    it('registers UiButton', comp('UiButton'))
    console.log(Vue.compile('<ui-button>Hey</ui-button>'))
  })
})
<|endoftext|>


<commit_before>const test = require('ava');
const NullSafeObject = require('..');

const srcObj = {
    key: 'value',
    deep: {
        property: {
            access: true
        }
    },
    arr: [
        'apple',
        'banana',
        'cherry'
    ]
};

test('NullSafeObject.wrap() creates a object', t => {
    const obj = NullSafeObject.wrap(srcObj);
    t.truthy(obj);
    t.is(typeof obj, 'object');
});
// test('Created object is deep equals to source object', t => {
//     const obj = NullSafeObject.wrap(srcObj);
//     t.deepEqual(obj, srcObj);
// });
test('Wrapped object is instance of NullSafeObject', t => {
    const obj = NullSafeObject.wrap(srcObj);
    t.truthy(obj instanceof NullSafeObject);
});
test('Instance of NullSafeObject has unwrap() method', t => {
    const obj = NullSafeObject.wrap(srcObj);
    t.is(typeof obj.unwrap, 'function');
});
test('NullSafeObject#unwrap() return built-in type', t => {
    const obj = NullSafeObject.wrap(srcObj);
    t.is(typeof obj.unwrap(), 'object');
    t.deepEqual(obj.unwrap(), srcObj);
    t.is(obj.key.unwrap(), 'value');
    t.is(obj.deep.property.access.unwrap(), true);
});
test('it allows to access/call child property but it returns NullSafeObject', t => {
    const obj = NullSafeObject.wrap(srcObj);
    t.truthy(obj.key.length);
    t.is(typeof obj.key.length, 'object');
    t.truthy(obj.key.length instanceof NullSafeObject);
    t.is(obj.key.length.unwrap(), srcObj.key.length);

    t.truthy(obj.arr.map);
    // t.is(typeof obj.arr.map, 'object');
    // t.is(typeof obj.arr.map, 'function');
    t.deepEqual(obj.arr.map(str => str.toUpperCase()).unwrap(), ['APPLE', 'BANANA', 'CHERRY']);
});
test('It can null-safe method chaining', t => {
    const obj = NullSafeObject.wrap(srcObj);
    t.deepEqual(obj.arr.map(str => str.toUpperCase()).reverse().unwrap(), ['CHERRY', 'BANANA', 'APPLE']);
    t.is(obj.arr.map(str => str.toUpperCase()).not_found_method().reverse().unwrap(), null);
});
test('Return null when unwrap() method called by undefined property', t => {
    const obj = NullSafeObject.wrap(srcObj);
    t.is(obj.deep.other_property.access.unwrap(), null);
});
test('Grow new property in source object when set new property to wrapped object', t => {
    const obj = NullSafeObject.wrap(srcObj);
    obj.new_property = 'created';
    t.is(srcObj.new_property, 'created');
});

<commit_msg>add fail case test<commit_after>const test = require('ava');
const NullSafeObject = require('..');

const srcObj = {
    key: 'value',
    deep: {
        property: {
            access: true
        }
    },
    arr: [
        'apple',
        'banana',
        'cherry'
    ]
};

test('NullSafeObject.wrap() creates a object', t => {
    const obj = NullSafeObject.wrap(srcObj);
    t.truthy(obj);
    t.is(typeof obj, 'object');
});
// test('Created object is deep equals to source object', t => {
//     const obj = NullSafeObject.wrap(srcObj);
//     t.deepEqual(obj, srcObj);
// });
test('Wrapped object is instance of NullSafeObject', t => {
    const obj = NullSafeObject.wrap(srcObj);
    t.truthy(obj instanceof NullSafeObject);
});
test('Instance of NullSafeObject has unwrap() method', t => {
    const obj = NullSafeObject.wrap(srcObj);
    t.is(typeof obj.unwrap, 'function');
});
test('NullSafeObject#unwrap() return built-in type', t => {
    const obj = NullSafeObject.wrap(srcObj);
    t.is(typeof obj.unwrap(), 'object');
    t.deepEqual(obj.unwrap(), srcObj);
    t.is(obj.key.unwrap(), 'value');
    t.is(obj.deep.property.access.unwrap(), true);
});
test('it allows to access/call child property but it returns NullSafeObject', t => {
    const obj = NullSafeObject.wrap(srcObj);
    t.truthy(obj.key.length);
    t.is(typeof obj.key.length, 'object');
    t.truthy(obj.key.length instanceof NullSafeObject);
    t.is(obj.key.length.unwrap(), srcObj.key.length);

    t.truthy(obj.arr.map);
    // t.is(typeof obj.arr.map, 'object');
    // t.is(typeof obj.arr.map, 'function');
    t.deepEqual(obj.arr.map(str => str.toUpperCase()).unwrap(), ['APPLE', 'BANANA', 'CHERRY']);
});
test('It can null-safe method chaining', t => {
    const obj = NullSafeObject.wrap(srcObj);
    t.deepEqual(obj.arr.map(str => str.toUpperCase()).reverse().unwrap(), ['CHERRY', 'BANANA', 'APPLE']);
    t.is(obj.arr.map(str => str.toUpperCase()).not_found_method().reverse().unwrap(), null);
});
test('Return null when unwrap() method called by undefined property', t => {
    const obj = NullSafeObject.wrap(srcObj);
    t.is(obj.deep.other_property.access.unwrap(), null);
});
test('Grow new property in source object when set new property to wrapped object', t => {
    const obj = NullSafeObject.wrap(srcObj);
    obj.new_property = 'created';
    t.is(srcObj.new_property, 'created');
});
test('Grow new deep property in source object when set new deep property to wrapped object', t => {
    const obj = NullSafeObject.wrap(srcObj);
    obj.new_deep.property = 'created';
    t.is(srcObj.new_deep.property, 'created');
});

<|endoftext|>


<commit_before>const fs = require('fs-extra')
const path = require('path')

const watcher = require('../lib')

const {prepareFixtureDir, reportLogs, cleanupFixtureDir} = require('./helper')

describe('unwatching a directory', function () {
  let subs, fixtureDir, watchDir, mainLogFile, workerLogFile, pollingLogFile

  beforeEach(async function () {
    ({fixtureDir, watchDir, mainLogFile, workerLogFile, pollingLogFile} = await prepareFixtureDir())
    subs = []

    await watcher.configure({mainLog: mainLogFile, workerLog: workerLogFile, pollingLog: pollingLogFile})
  })

  afterEach(async function () {
    await Promise.all(subs.map(sub => sub.unwatch()))
    await reportLogs(this.currentTest, mainLogFile, workerLogFile, pollingLogFile)
    await cleanupFixtureDir(fixtureDir)
  })

  it('unwatches a previously watched directory', async function () {
    let error = null
    const events = []

    const sub = await watcher.watch(watchDir, {}, (err, es) => {
      error = err
      events.push(...es)
    })
    subs.push(sub)

    const filePath = path.join(watchDir, 'file.txt')
    await fs.writeFile(filePath, 'original')

    await until('the event arrives', () => events.some(event => event.path === filePath))
    const eventCount = events.length
    assert.isNull(error)

    await sub.unwatch()

    await fs.writeFile(filePath, 'the modification')

    // Give the modification event a chance to arrive.
    // Not perfect, but adequate.
    await new Promise(resolve => setTimeout(resolve, 100))

    assert.lengthOf(events, eventCount)
  })

  it('is a no-op if the directory is not being watched', async function () {
    let error = null
    const sub = await watcher.watch(watchDir, {}, err => (error = err))
    subs.push(sub)
    assert.isNull(error)

    await sub.unwatch()
    assert.isNull(error)

    await sub.unwatch()
    assert.isNull(error)
  })
})
<commit_msg>Measure the event count after unwatching<commit_after>const fs = require('fs-extra')
const path = require('path')

const watcher = require('../lib')

const {prepareFixtureDir, reportLogs, cleanupFixtureDir} = require('./helper')

describe('unwatching a directory', function () {
  let subs, fixtureDir, watchDir, mainLogFile, workerLogFile, pollingLogFile

  beforeEach(async function () {
    ({fixtureDir, watchDir, mainLogFile, workerLogFile, pollingLogFile} = await prepareFixtureDir())
    subs = []

    await watcher.configure({mainLog: mainLogFile, workerLog: workerLogFile, pollingLog: pollingLogFile})
  })

  afterEach(async function () {
    await Promise.all(subs.map(sub => sub.unwatch()))
    await reportLogs(this.currentTest, mainLogFile, workerLogFile, pollingLogFile)
    await cleanupFixtureDir(fixtureDir)
  })

  it('unwatches a previously watched directory', async function () {
    let error = null
    const events = []

    const sub = await watcher.watch(watchDir, {}, (err, es) => {
      error = err
      events.push(...es)
    })
    subs.push(sub)

    const filePath = path.join(watchDir, 'file.txt')
    await fs.writeFile(filePath, 'original')

    await until('the event arrives', () => events.some(event => event.path === filePath))
    assert.isNull(error)

    await sub.unwatch()
    const eventCount = events.length

    await fs.writeFile(filePath, 'the modification')

    // Give the modification event a chance to arrive.
    // Not perfect, but adequate.
    await new Promise(resolve => setTimeout(resolve, 100))

    assert.lengthOf(events, eventCount)
  })

  it('is a no-op if the directory is not being watched', async function () {
    let error = null
    const sub = await watcher.watch(watchDir, {}, err => (error = err))
    subs.push(sub)
    assert.isNull(error)

    await sub.unwatch()
    assert.isNull(error)

    await sub.unwatch()
    assert.isNull(error)
  })
})
<|endoftext|>


<commit_before>var canvasSize = 250,
    centre = 125,
    radius = 100,
    startY = centre-radius,
    runBtn = document.getElementById('run'),
    percDiv = document.getElementById('percent'),
    lapsed = document.getElementById('lapsed');

    var svg = document.getElementById('svg');
    var arc = document.getElementById('arc');

 var lastSmoke = new Date(localStorage['lastSmoke']);

 if (isNaN(lastSmoke.getTime()))
 {
    lastSmoke = new Date();
 }

 var hour = 60 * 60;

 var ff = function()
 {
    var d = new Date();

    var seconds = Math.floor((d - lastSmoke) / 1000);

    run(seconds / hour);

    var h = Math.floor(seconds / 60 / 60);

    var m = Math.floor((seconds - h * 3600) / 60);

    var s = (seconds % 60);

    lapsed.innerHTML = h + 'h '+m+'m ' + s + 's';

    setTimeout(ff, 1000);
 }

 ff();

var oldVal = 0;
runBtn.onclick = function() {
   lastSmoke = new Date();
   localStorage['lastSmoke'] = lastSmoke;
};

function run(percent) {
    var endpoint = percent*360;

    //console.log(arc);

    var d = endpoint,
            dr = d-90;
            radians = Math.PI*(dr)/180,
            endx = centre + radius*Math.cos(radians),
            endy = centre + radius * Math.sin(radians),
            largeArc = d>180 ? 1 : 0;
            path = "M"+centre+","+startY+" A"+radius+","+radius+" 0 "+largeArc+",1 "+endx+","+endy;

    arc.setAttribute('d', path);
}

run(0);

var scrollOld = 0;

  runBtn.addEventListener('touchmove', function(event) {
    var touch = event.targetTouches[0];

    // Place element where the finger is
    runBtn.style.left = touch.pageX-25 + 'px';
    runBtn.style.top = touch.pageY-25 + 'px';
    event.preventDefault();
  }, false);
/* */<commit_msg>bigger that 360 degrees fix<commit_after>var canvasSize = 250,
    centre = 125,
    radius = 100,
    startY = centre-radius,
    runBtn = document.getElementById('run'),
    percDiv = document.getElementById('percent'),
    lapsed = document.getElementById('lapsed');

    var svg = document.getElementById('svg');
    var arc = document.getElementById('arc');

 var lastSmoke = new Date(localStorage['lastSmoke']);

 if (isNaN(lastSmoke.getTime()))
 {
    lastSmoke = new Date();
 }

 var hour = 60 * 60;

 var ff = function()
 {
    var d = new Date();

    var seconds = Math.floor((d - lastSmoke) / 1000);

    run(seconds / hour);

    var h = Math.floor(seconds / 60 / 60);

    var m = Math.floor((seconds - h * 3600) / 60);

    var s = (seconds % 60);

    lapsed.innerHTML = h + 'h '+m+'m ' + s + 's';

    setTimeout(ff, 1000);
 }

 ff();

var oldVal = 0;
runBtn.onclick = function() {
   lastSmoke = new Date();
   localStorage['lastSmoke'] = lastSmoke;
};

function run(percent) {
    var endpoint = percent*360;

    if (endpoint > 359) endpoint = 359;

    //console.log(arc);

    var d = endpoint,
            dr = d-90;
            radians = Math.PI*(dr)/180,
            endx = centre + radius*Math.cos(radians),
            endy = centre + radius * Math.sin(radians),
            largeArc = d>180 ? 1 : 0;
            path = "M"+centre+","+startY+" A"+radius+","+radius+" 0 "+largeArc+",1 "+endx+","+endy;

    arc.setAttribute('d', path);
}

run(0);

var scrollOld = 0;

  runBtn.addEventListener('touchmove', function(event) {
    var touch = event.targetTouches[0];

    // Place element where the finger is
    runBtn.style.left = touch.pageX-25 + 'px';
    runBtn.style.top = touch.pageY-25 + 'px';
    event.preventDefault();
  }, false);
/* */<|endoftext|>


<commit_before>// import Events         from 'backbone-esnext-events';
import { assert }     from 'chai';

import PluginManager  from '../../src/PluginManager.js';

class PluginTest { test(event) { event.data.result.count++; assert.strictEqual(event.pluginName, 'PluginTest'); } }

const pluginTest = { test: (event) => { event.data.result.count++; assert.strictEqual(event.pluginName, 'pluginTest'); } };

// class PluginTestNoName { test(event) { event.data.result.count++; } }
class PluginTestNoName2 { test2(event) { event.data.result.count++; } }

class PluginTestSync
{
   constructor() { this.c = 3; }
   test(a, b) { return a + b + this.c; }
}

suite('PluginManager:', () =>
{
   let pluginManager, testData;

   beforeEach(() => { pluginManager = new PluginManager(); testData = { result: { count: 0 } }; });

   test('PluginManager constructor function is exported', () =>
   {
      assert.isFunction(PluginManager);
   });

   test('PluginManager instance is object', () =>
   {
      assert.isObject(pluginManager);
   });

   test('PluginManager throws when invoke is called with empty parameters', () =>
   {
      assert.throws(() => { pluginManager.invokeSyncEvent(); });
   });

   test('PluginManager throws w/ add (no options)', () =>
   {
      assert.throws(() => { pluginManager.add(); });
   });

   test('PluginManager has empty result', () =>
   {
      const event = pluginManager.invokeSyncEvent('test');

      assert.isObject(event);
      assert.lengthOf(Object.keys(event), 2);
      assert(event.$$plugin_invoke_count === 0);
   });

   test('PluginManager w/ plugin and missing method has empty event result', () =>
   {
      pluginManager.add({ name: 'PluginTest', instance: new PluginTest() });

      const event = pluginManager.invokeSyncEvent('nop');

      assert.isObject(event);
      assert.lengthOf(Object.keys(event), 2);
      assert.strictEqual(event.$$plugin_invoke_count, 0);
   });

   test('PluginManager has valid test / class result (pass through)', () =>
   {
      pluginManager.add({ name: 'PluginTest', instance: new PluginTest() });

      const event = pluginManager.invokeSyncEvent('test', void 0, testData);

      assert.isObject(event);
      assert.strictEqual(event.result.count, 1);
      assert.strictEqual(testData.result.count, 1);
      assert.strictEqual(event.$$plugin_invoke_count, 1);
   });

   test('PluginManager has valid test / object result (pass through)', () =>
   {
      pluginManager.add({ name: 'pluginTest', instance: pluginTest });

      const event = pluginManager.invokeSyncEvent('test', void 0, testData);

      assert.isObject(event);
      assert.strictEqual(event.result.count, 1);
      assert.strictEqual(testData.result.count, 1);
   });

   test('PluginManager has invoked both plugins (pass through)', () =>
   {
      pluginManager.add({ name: 'PluginTest', instance: new PluginTest() });
      pluginManager.add({ name: 'pluginTest', instance: pluginTest });

      const event = pluginManager.invokeSyncEvent('test', void 0, testData);

      assert.isObject(event);
      assert.strictEqual(event.result.count, 2);
      assert.strictEqual(testData.result.count, 2);
   });

   test('PluginManager has valid test / class result (copy)', () =>
   {
      pluginManager.add({ name: 'PluginTest', instance: new PluginTest() });

      const event = pluginManager.invokeSyncEvent('test', testData);

      assert.isObject(event);
      assert.strictEqual(event.result.count, 1);
      assert.strictEqual(testData.result.count, 0);
      assert.strictEqual(event.$$plugin_invoke_count, 1);
      assert.strictEqual(event.$$plugin_invoke_names[0], 'PluginTest');
   });

   test('PluginManager has valid test / object result (copy)', () =>
   {
      pluginManager.add({ name: 'pluginTest', instance: pluginTest });

      const event = pluginManager.invokeSyncEvent('test', testData);

      assert.isObject(event);
      assert.strictEqual(event.result.count, 1);
      assert.strictEqual(testData.result.count, 0);
   });

   test('PluginManager has invoked both plugins (copy)', () =>
   {
      pluginManager.add({ name: 'PluginTest', instance: new PluginTest() });
      pluginManager.add({ name: 'pluginTest', instance: pluginTest });

      const event = pluginManager.invokeSyncEvent('test', testData);

      assert.isObject(event);
      assert.strictEqual(event.result.count, 2);
      assert.strictEqual(testData.result.count, 0);
   });

   test('PluginManager has invoked one result (sync)', () =>
   {
      pluginManager.add({ name: 'PluginTestSync', instance: new PluginTestSync() });

      const result = pluginManager.invokeSync('PluginTestSync', 'test', 1, 2);

      assert.isNumber(result);
      assert.strictEqual(result, 6);
   });

   test('PluginManager has invoked two results (sync)', () =>
   {
      pluginManager.add({ name: 'PluginTestSync', instance: new PluginTestSync() });
      pluginManager.add({ name: 'PluginTestSync2', instance: new PluginTestSync() });

      const result = pluginManager.invokeSync(void 0, 'test', 1, 2);

      assert.isArray(result);
      assert.strictEqual(result[0], 6);
      assert.strictEqual(result[1], 6);
   });

   test('PluginManager get unique method names', () =>
   {
      pluginManager.add({ name: 'PluginTestSync', instance: new PluginTestSync() });
      pluginManager.add({ name: 'PluginTestNoName2', instance: new PluginTestNoName2() });

      const results = pluginManager.getMethodNames();

      assert.isArray(results);
      assert.lengthOf(results, 2);
      assert.strictEqual(results[0], 'test');
      assert.strictEqual(results[1], 'test2');
   });

   test('PluginManager get plugin names', () =>
   {
      pluginManager.add({ name: 'PluginTestSync', instance: new PluginTestSync() });
      pluginManager.add({ name: 'PluginTestSync2', instance: new PluginTestSync() });

      const results = pluginManager.getPluginNames();

      assert.isArray(results);
      assert.lengthOf(results, 2);
      assert.strictEqual(results[0], 'PluginTestSync');
      assert.strictEqual(results[1], 'PluginTestSync2');
   });

   test('PluginManager get plugin / method names', () =>
   {
      pluginManager.add({ name: 'PluginTestSync', instance: new PluginTestSync() });
      pluginManager.add({ name: 'PluginTestNoName2', instance: new PluginTestNoName2() });

      const results = pluginManager.getPluginMethodNames();

      assert.isArray(results);
      assert.lengthOf(results, 2);
      assert.strictEqual(results[0].plugin, 'PluginTestSync');
      assert.strictEqual(results[0].method, 'test');
      assert.strictEqual(results[1].plugin, 'PluginTestNoName2');
      assert.strictEqual(results[1].method, 'test2');
   });
});
<commit_msg>removed pluginmanager<commit_after><|endoftext|>


<commit_before>var dotenv = require('dotenv');
dotenv.config();

const express = require('express');
const path = require('path');
const app = express();
var bodyParser = require('body-parser');
var proxy = require('http-proxy-middleware');

if (process.env.DISABLE_LOGS) {
  console.log = function() {};
  console.info = function() {};
}

const disableCache = (req, res, next) => {
  res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
  res.header('Pragma', 'no-cache');
  res.header('Expires', 0);
  next();
};
const printer = (req, res, next) => {
  console.log('Requesting', req.originalUrl);
  res.on('finish', () => {
    console.info(
      `Returning ${res.statusCode} ${res.statusMessage}; ${res.get(
        'Content-Length'
      ) || 0}b sent`
    );
  });
  next();
};

const apiAddress = `${process.env.BACKEND_API_PROTOCOL}://${
  process.env.BACKEND_API_DOMAIN
}`;
const apiHost = `${process.env.BACKEND_API_DOMAIN}`;

// Since the cloud system is configured by hostname, change the request when it's going to AWS so
// that it appears to be targeted to the right hostname instead of localhost:3000
const hostnameApiSwitch = (req, res, next) => {
  req.headers['x-forwarded-host'] = req.headers['host'];
  req.headers['original-host'] = req.headers['host'];
  req.headers['host'] = apiHost;
  next();
};

if (process.env.DEPLOYED === 'yes') {
  app.use((req, res, next) => {
    if (typeof req.headers['x-envoy-original-path'] !== "undefined") {
      // if (req.url != req.headers['x-envoy-original-path']) {
        req.url = req.headers['x-envoy-original-path'];
      // }
    }
    console.log(req.url)
    next();
  })

  // MDB starts with /v1, while /api is used by the API gateway
  const mdb_proxy = proxy({
    target: process.env.MDB_ADDRESS,
    pathRewrite: {'^/api/v1/modeldb' : '/v1'},
    // logLevel: "debug",
    changeOrigin: false,
    ws: true,
  })
  app.use(
    '/api/v1/modeldb/*',
    [disableCache, hostnameApiSwitch, printer],
    (req, res, next) => {
      return mdb_proxy(req, res, next);
    }
  );

  const artifactory_proxy = proxy({
    target: process.env.ARTIFACTORY_ADDRESS,
    // pathRewrite: {'^/api/v1/artifact' : '/v1'},
    // logLevel: "debug",
    changeOrigin: false,
    ws: true,
  })
  app.use(
    '/api/v1/artifact/*',
    [disableCache, hostnameApiSwitch, printer],
    (req, res, next) => {
      return artifactory_proxy(req, res, next);
    }
  );

  const graphql_proxy = proxy({
    target: process.env.GQL_ADDRESS,
    pathRewrite: {'^/api/v1/graphql/' : '/'},
    // logLevel: "debug",
    changeOrigin: false,
    ws: true,
  })
  app.use(
    '/api/v1/graphql/*',
    [disableCache, hostnameApiSwitch, printer],
    (req, res, next) => {
      return graphql_proxy(req, res, next);
    }
  );

  app.use(express.static('client/build'));

  // Any left over is sent to index
  app.get('*', (req, res) => {
    res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
    res.header('Pragma', 'no-cache');
    res.header('Expires', 0);
    res.sendFile(path.join(__dirname + '/client/build' + '/index.html'));
  });
} else {
  const aws_proxy = proxy({
    target: apiAddress,
    changeOrigin: false,
    ws: true,
  });

  app.use(
    '/api/v1/*',
    [disableCache, hostnameApiSwitch, printer],
    (req, res, next) => {
      return aws_proxy(req, res, next);
    }
  );
  app.use(
    '/api/auth/*',
    [disableCache, hostnameApiSwitch, printer],
    (req, res, next) => {
      return aws_proxy(req, res, next);
    }
  );

  // app.use(bodyParser.json());

  const local_proxy = proxy({
    target: 'http://localhost:3001',
    changeOrigin: false,
    ws: true,
  });
  app.use('*', (req, res, next) => {
    return local_proxy(req, res, next);
  });
}

const port = process.env.PORT || 3000;
app.listen(port);
<commit_msg>feat: added env vars for proxy changeOrigin. Default is false for backwards compatibility. (#997)<commit_after>var dotenv = require('dotenv');
dotenv.config();

const express = require('express');
const path = require('path');
const app = express();
var bodyParser = require('body-parser');
var proxy = require('http-proxy-middleware');

if (process.env.DISABLE_LOGS) {
  console.log = function() {};
  console.info = function() {};
}

const disableCache = (req, res, next) => {
  res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
  res.header('Pragma', 'no-cache');
  res.header('Expires', 0);
  next();
};
const printer = (req, res, next) => {
  console.log('Requesting', req.originalUrl);
  res.on('finish', () => {
    console.info(
      `Returning ${res.statusCode} ${res.statusMessage}; ${res.get(
        'Content-Length'
      ) || 0}b sent`
    );
  });
  next();
};

const apiAddress = `${process.env.BACKEND_API_PROTOCOL}://${
  process.env.BACKEND_API_DOMAIN
}`;
const apiHost = `${process.env.BACKEND_API_DOMAIN}`;

// Since the cloud system is configured by hostname, change the request when it's going to AWS so
// that it appears to be targeted to the right hostname instead of localhost:3000
const hostnameApiSwitch = (req, res, next) => {
  req.headers['x-forwarded-host'] = req.headers['host'];
  req.headers['original-host'] = req.headers['host'];
  req.headers['host'] = apiHost;
  next();
};

if (process.env.DEPLOYED === 'yes') {
  app.use((req, res, next) => {
    if (typeof req.headers['x-envoy-original-path'] !== "undefined") {
      // if (req.url != req.headers['x-envoy-original-path']) {
        req.url = req.headers['x-envoy-original-path'];
      // }
    }
    console.log(req.url)
    next();
  })

  // MDB starts with /v1, while /api is used by the API gateway
  const mdb_proxy = proxy({
    target: process.env.MDB_ADDRESS,
    pathRewrite: {'^/api/v1/modeldb' : '/v1'},
    // logLevel: "debug",
    changeOrigin: process.env.MDB_CHANGE_ORIGIN || false,
    ws: true,
  })
  app.use(
    '/api/v1/modeldb/*',
    [disableCache, hostnameApiSwitch, printer],
    (req, res, next) => {
      return mdb_proxy(req, res, next);
    }
  );

  const artifactory_proxy = proxy({
    target: process.env.ARTIFACTORY_ADDRESS,
    // pathRewrite: {'^/api/v1/artifact' : '/v1'},
    // logLevel: "debug",
    changeOrigin: process.env.ARTIFACTORY_CHANGE_ORIGIN || false,
    ws: true,
  })
  app.use(
    '/api/v1/artifact/*',
    [disableCache, hostnameApiSwitch, printer],
    (req, res, next) => {
      return artifactory_proxy(req, res, next);
    }
  );

  const graphql_proxy = proxy({
    target: process.env.GQL_ADDRESS,
    pathRewrite: {'^/api/v1/graphql/' : '/'},
    // logLevel: "debug",
    changeOrigin: process.env.GRAPHQL_CHANGE_ORIGIN || false,
    ws: true,
  })
  app.use(
    '/api/v1/graphql/*',
    [disableCache, hostnameApiSwitch, printer],
    (req, res, next) => {
      return graphql_proxy(req, res, next);
    }
  );

  app.use(express.static('client/build'));

  // Any left over is sent to index
  app.get('*', (req, res) => {
    res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
    res.header('Pragma', 'no-cache');
    res.header('Expires', 0);
    res.sendFile(path.join(__dirname + '/client/build' + '/index.html'));
  });
} else {
  const aws_proxy = proxy({
    target: apiAddress,
    changeOrigin: process.env.AWS_CHANGE_ORIGIN || false,
    ws: true,
  });

  app.use(
    '/api/v1/*',
    [disableCache, hostnameApiSwitch, printer],
    (req, res, next) => {
      return aws_proxy(req, res, next);
    }
  );
  app.use(
    '/api/auth/*',
    [disableCache, hostnameApiSwitch, printer],
    (req, res, next) => {
      return aws_proxy(req, res, next);
    }
  );

  // app.use(bodyParser.json());

  const local_proxy = proxy({
    target: 'http://localhost:3001',
    changeOrigin: process.env.LOCAL_CHANGE_ORIGIN || false,
    ws: true,
  });
  app.use('*', (req, res, next) => {
    return local_proxy(req, res, next);
  });
}

const port = process.env.PORT || 3000;
app.listen(port);
<|endoftext|>


<commit_before>
var raf = require('raf');
var createCaption = require('../../dom/caption');

var scene, camera, renderer;
var material, light;
var textures = [];
var textureMeshes = [];
var originMeshes = [];

var imageURLs = [
    "assets/texture00.jpg",
    "assets/texture01.jpg",
    "assets/texture02.jpg",
    "assets/texture03.jpg",
    "assets/texture04.jpg"
];
var totalLength = 0;
var loader = new THREE.TextureLoader();
var object, id;
var stats, wrapper;
var mouse = new THREE.Vector2();
var INTERSECTED, raycaster;

var isAnimation = true;

function init(){
    scene = new THREE.Scene();

    camera = new THREE.OrthographicCamera( -window.innerWidth/2, window.innerWidth/2, window.innerHeight/2, -window.innerHeight/2, -10000, 10000 );
    camera.updateProjectionMatrix();
    camera.position.z = 200;

    renderer = new THREE.WebGLRenderer({alpha: true});
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    raycaster = new THREE.Raycaster();
    var count = 0;
    imageURLs.forEach(function(imageURL, index){
        loader.load(imageURL, function(texture){
            textures.push(texture);
            count++;
            if(imageURLs.length == count) createTexture();
        })
    });

    setComponent();
}

function createTexture(){
    var scale = 1/8;
    var margin = 20;
    textures.forEach(function(texture, index){
        var wid = texture.image.width * scale;
        var hig = texture.image.height * scale;
        var plane = new THREE.PlaneGeometry( wid, hig);
        var originPlane = new THREE.PlaneGeometry( texture.image.width, texture.image.height );
        plane.size = {width : wid, height : hig};
        texture.minFilter = THREE.LinearFilter
        var mat = new THREE.MeshBasicMaterial({side : THREE.DoubleSide, map : texture});
        var mesh = new THREE.Mesh(plane, mat);
        var objMat=new THREE.MeshBasicMaterial({side : THREE.DoubleSide, map : texture});
        var originMesh = new THREE.Mesh(originPlane, objMat);

        mesh.objectId = index;

        textureMeshes.push(mesh);
        originMeshes.push(originMesh);

        scene.add(mesh);
        totalLength += wid + margin;
    })

    var curPosition = -totalLength/2;

    textureMeshes.forEach(function(mesh){
        var meshSize = mesh.geometry.size;
        mesh.position.x =curPosition + meshSize.width/2;

        curPosition += meshSize.width + margin;
    });

    document.addEventListener( 'mousemove', onDocumentMouseMove, false );

    raf(animate);
}

function setComponent(){
    var title = '';
    var caption = '';
    var url = '';

    wrapper = createCaption(title, caption, url);
    wrapper.style.width = (window.innerWidth/2 - 50) + "px";
    wrapper.style.position = "absolute";
    wrapper.style.top = '50px';
    wrapper.style.left = '30px';

    stats = new Stats();
    stats.setMode( 0 ); // 0: fps, 1: ms, 2: mb

    // align top-left
    stats.domElement.style.position = 'absolute';
    stats.domElement.style.bottom  = '30px';
    stats.domElement.style.left = '30px';
    stats.domElement.style.zIndex= 9999;

    document.body.appendChild( stats.domElement );
}

function animate() {
    stats.begin();

    renderer.render(scene, camera);

    raycaster.setFromCamera( mouse, camera );
    var intersects = raycaster.intersectObjects( scene.children );
    if ( intersects.length > 0 ) {
        if ( INTERSECTED != intersects[ 0 ].object ) {
            // if ( INTERSECTED ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );
            INTERSECTED = intersects[ 0 ].object;
            document.body.style.cursor = "pointer";
            window.addEventListener("click", onClick);
        }
    } else {
        document.body.style.cursor = "default";
        window.removeEventListener("click", onClick);
        INTERSECTED = null;
    }

    stats.end();

    id = raf(animate);
}

var prevObjectId;
function onClick(ev){
    var objectId = INTERSECTED.objectId;
    if(prevObjectId >= 0 && prevObjectId != objectId){
        scene.remove(originMeshes[prevObjectId]);
    }
    originMeshes[objectId].position.z = -100;
    scene.add(originMeshes[objectId]);
    prevObjectId = objectId;
}

window.addEventListener('keydown', function(ev){
    if(ev.keyCode == 27){
        if(isAnimation) raf.cancel(id);
        else    id = raf(animate);

        isAnimation = !isAnimation;
    }
});

function onDocumentMouseMove( event ) {
    event.preventDefault();
    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}

window.addEventListener("resize", function(ev){
    camera.left = window.innerWidth/-2;
    camera.right = window.innerWidth/2;
    camera.top = window.innerHeight/2;
    camera.bottom = -window.innerHeight/2;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );
});

init()
<commit_msg>add url for interactive.<commit_after>
var raf = require('raf');
var createCaption = require('../../dom/caption');

var scene, camera, renderer;
var material, light;
var textures = [];
var textureMeshes = [];
var originMeshes = [];

var imageURLs = [
    "assets/texture00.jpg",
    "assets/texture01.jpg",
    "assets/texture02.jpg",
    "assets/texture03.jpg",
    "assets/texture04.jpg"
];
var totalLength = 0;
var loader = new THREE.TextureLoader();
var object, id;
var stats, wrapper;
var mouse = new THREE.Vector2();
var INTERSECTED, raycaster;

var isAnimation = true;

function init(){
    scene = new THREE.Scene();

    camera = new THREE.OrthographicCamera( -window.innerWidth/2, window.innerWidth/2, window.innerHeight/2, -window.innerHeight/2, -10000, 10000 );
    camera.updateProjectionMatrix();
    camera.position.z = 200;

    renderer = new THREE.WebGLRenderer({alpha: true});
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    raycaster = new THREE.Raycaster();
    var count = 0;
    imageURLs.forEach(function(imageURL, index){
        loader.load(imageURL, function(texture){
            textures.push(texture);
            count++;
            if(imageURLs.length == count) createTexture();
        })
    });

    setComponent();
}

function createTexture(){
    var scale = 1/8;
    var margin = 20;
    textures.forEach(function(texture, index){
        var wid = texture.image.width * scale;
        var hig = texture.image.height * scale;
        var plane = new THREE.PlaneGeometry( wid, hig);
        var originPlane = new THREE.PlaneGeometry( texture.image.width, texture.image.height );
        plane.size = {width : wid, height : hig};
        texture.minFilter = THREE.LinearFilter
        var mat = new THREE.MeshBasicMaterial({side : THREE.DoubleSide, map : texture});
        var mesh = new THREE.Mesh(plane, mat);
        var objMat=new THREE.MeshBasicMaterial({side : THREE.DoubleSide, map : texture});
        var originMesh = new THREE.Mesh(originPlane, objMat);

        mesh.objectId = index;

        textureMeshes.push(mesh);
        originMeshes.push(originMesh);

        scene.add(mesh);
        totalLength += wid + margin;
    })

    var curPosition = -totalLength/2;

    textureMeshes.forEach(function(mesh){
        var meshSize = mesh.geometry.size;
        mesh.position.x =curPosition + meshSize.width/2;

        curPosition += meshSize.width + margin;
    });

    document.addEventListener( 'mousemove', onDocumentMouseMove, false );

    raf(animate);
}

function setComponent(){
    var title = 'Interaction';
    var caption = 'Interaction with RayCaster';
    var url = 'https://github.com/kenjiSpecial/webgl-sketch-dojo/tree/master/sketches/boilerplate/interactive';

    wrapper = createCaption(title, caption, url);
    wrapper.style.width = (window.innerWidth/2 - 50) + "px";
    wrapper.style.position = "absolute";
    wrapper.style.top = '50px';
    wrapper.style.left = '30px';

    stats = new Stats();
    stats.setMode( 0 ); // 0: fps, 1: ms, 2: mb

    // align top-left
    stats.domElement.style.position = 'absolute';
    stats.domElement.style.bottom  = '30px';
    stats.domElement.style.left = '30px';
    stats.domElement.style.zIndex= 9999;

    document.body.appendChild( stats.domElement );
}

function animate() {
    stats.begin();

    renderer.render(scene, camera);

    raycaster.setFromCamera( mouse, camera );
    var intersects = raycaster.intersectObjects( scene.children );
    if ( intersects.length > 0 ) {
        if ( INTERSECTED != intersects[ 0 ].object ) {
            // if ( INTERSECTED ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );
            INTERSECTED = intersects[ 0 ].object;
            document.body.style.cursor = "pointer";
            window.addEventListener("click", onClick);
        }
    } else {
        document.body.style.cursor = "default";
        window.removeEventListener("click", onClick);
        INTERSECTED = null;
    }

    stats.end();

    id = raf(animate);
}

var prevObjectId;
function onClick(ev){
    var objectId = INTERSECTED.objectId;
    if(prevObjectId >= 0 && prevObjectId != objectId){
        scene.remove(originMeshes[prevObjectId]);
    }
    originMeshes[objectId].position.z = -100;
    scene.add(originMeshes[objectId]);
    prevObjectId = objectId;
}

window.addEventListener('keydown', function(ev){
    if(ev.keyCode == 27){
        if(isAnimation) raf.cancel(id);
        else    id = raf(animate);

        isAnimation = !isAnimation;
    }
});

function onDocumentMouseMove( event ) {
    event.preventDefault();
    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}

window.addEventListener("resize", function(ev){
    camera.left = window.innerWidth/-2;
    camera.right = window.innerWidth/2;
    camera.top = window.innerHeight/2;
    camera.bottom = -window.innerHeight/2;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );
});

init()
<|endoftext|>


<commit_before>describe('ax5.util.param TEST', function() {
    it('ax5.util.param({a: 1, b: \'123\'"2&\'}, "param") expect "a=1&b=123%27%222%26"', function() {
        var actual = ax5.util.param({a: 1, b: '123\'"2&'}, 'param');

        actual.should.equal('a=1&b=123%27%222%26');
    });
    it('ax5.util.param("a=1&b=12\'"32", "param") expect "a=1&b=12\'"32"', function() {
        var actual = ax5.util.param("a=1&b=12'\"32", 'param');

        actual.should.equal('a=1&b=12\'"32');
    });
    it('ax5.util.param("a=1&b=1232") expect {"a":"1","b":"1232"}', function() {
        var actual = ax5.util.param("a=1&b=1232");

        should.deepEqual(actual, {"a":"1","b":"1232"});
    });
});

describe('ax5.util.parseJson TEST', function() {
    it('ax5.util.util.parseJson("[{"a":"99"},"2","3"]") expect [{"a":"99"},"2","3"]', function() {
        var actual = ax5.util.parseJson('[{"a":"99"},"2","3"]');

        actual.should.deepEqual([{"a":"99"},"2","3"]);
    });
    it('ax5.util.parseJson("{"a":1, "b":function(){return 1;}}", false) expect {"error": 500, "msg": "syntax error"}', function() {
        var actual = ax5.util.parseJson('{"a":1, "b":function(){return 1;}}', false);

        actual.should.deepEqual({"error": 500, "msg": "syntax error"});
    });
    it('ax5.util.parseJson("{"a":1, "b":function(){return 1;}}", true) expect {"a": 1, "b": "{Function}"}', function() {
        var actual = ax5.util.parseJson('{"a":1, "b":function(){return 1;}}', true);

        actual.a.should.equal(1);
        actual.b.should.Function();
    });

    it('ax5.util.parseJson("{"key": [true, false, true, false], "fn": function(){return "fn";}}", true);', function() {
        var actual = ax5.util.parseJson('{"key": [true, false, true, false], "fn": function(){return "fn";}}', true);

        actual.key.should.deepEqual([true, false, true, false]);
        actual.fn.should.Function();
    });
});

describe('ax5.util.toJson TEST', function() {
    var testCases = [
        {
            args: 1,
            expect: 1
        },
        {
            args: "A",
            expect: '"A"'
        },
        {
            args: [1, 2, 3, "A"],
            expect: '[1,2,3,"A"]'
        },
        {
            args: {a: "a", x: "x"},
            expect: '{"a": "a", "x": "x"}'
        },
        {
            args: [1,{"a": "a", "x": "x"}],
            expect: '[1,{"a": "a", "x": "x"}]'
        },
        {
            args: {"a": "a", "x": "x", "list": [1,2,3]},
            expect: '{"a": "a", "x": "x", "list": [1,2,3]}'
        },
        {
            args: function func() {},
            expect: '"{Function}"'
        },
        {
            args: [true, false, true],
            expect: '[true,false,true]'
        }
    ];

    _.each(testCases, function(testCase){
        it('ax5.util.toJson(' + (JSON.stringify(testCase.args) || testCase.args.toString()) + ') expect ' + testCase.expect, function() {
            var actual = ax5.util.toJson(testCase.args);

            actual.should.deepEqual(testCase.expect);
        });
    });
});

describe('ax5.util.alert TEST', function(){
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.toArray TEST', function() {
    it('ax5.util.toArray converts [Array-like objects] to [Array]', function() {
        function something() {
            return ax5.util.toArray(arguments);
        }
        var actual = something("A", "X", "I", "S", "J");

        actual.should.deepEqual(["A", "X", "I", "S", "J"]);
    });
});

describe('ax5.util.xxxCookie TEST', function() {

    describe('ax5.util.setCookie TEST', function() {
        it('ax5.util.setCookie("ax5-cookie", "eng+한글")', function() {
            ax5.util.setCookie('ax5-cookie', 'eng+한글');

            document.cookie.indexOf('ax5-cookie=eng+%uD55C%uAE00').should.above(-1);
        });
    });

    describe('ax5.util.getCookie TEST', function() {
        it('ax5.util.getCookie("ax5-cookie") expect "eng+한글"', function() {
            var actual = ax5.util.getCookie('ax5-cookie');

            actual.should.equal('eng+한글');
        });
    });

});

describe('ax5.util.findParentNode TEST', function() {
    it('ax5.util.findParentNode($(".first").get(0), { tagname: "div", clazz: "test-mockup-1" }) expect $("div.test-mockup-1").get(0)', function() {
        var actual = ax5.util.findParentNode($('.first').get(0), { tagname: 'div', clazz: 'test-mockup-1' });
        var expect = $('div.test-mockup-1').get(0);

        should.equal(actual, expect);
    });
});

describe('ax5.util.cssNumber TEST', function() {
    var testCases = [
        {
            args: '100px',
            expect: '100px'
        },
        {
            args: 100,
            expect: '100px'
        },
        {
            args: "100",
            expect: '100px'
        },
        {
            args: '100%',
            expect: '100%'
        },
        {
            args: '##100@',
            expect: '100px'
        }
    ];

    _.each(testCases, function(testCase){
        it('ax5.util.toJson(' + JSON.stringify(testCase.args) + ') expect ' + testCase.expect, function() {
            var actual = ax5.util.cssNumber(testCase.args);

            should.equal(actual, testCase.expect);
        });
    });
});

describe('ax5.util.css TEST', function() {

    it('ax5.util.css({background:"#ccc",padding:"50px",width:"100px" }) expect background:#ccc;padding:50px;width:100px;', function() {
        var actual = ax5.util.css({background:"#ccc",padding:"50px",width:"100px" });

        should.equal(actual, 'background:#ccc;padding:50px;width:100px;');
    });

    it('ax5.util.css("width:100px;padding: 50px; background: #ccc") expect {width: "100px", padding: "50px", background: "#ccc"}', function() {
        var actual = ax5.util.css('width:100px;padding: 50px; background: #ccc');

        should.deepEqual(actual, {width: "100px", padding: "50px", background: "#ccc"});
    });

});

describe('ax5.util.stopEvent TEST', function(){
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.selectRange TEST', function() {
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.debounce TEST', function() {
    // TODO 대략 난감... HJ.Park 2016-09-26
});
<commit_msg>update test code<commit_after>describe('ax5.util.param TEST', function () {
    it('ax5.util.param({a: 1, b: \'123\'"2&\'}, "param") expect "a=1&b=123%27%222%26"', function () {
        var actual = ax5.util.param({a: 1, b: '123\'"2&'}, 'param');

        actual.should.equal('a=1&b=123%27%222%26');
    });
    it('ax5.util.param("a=1&b=12\'"32", "param") expect "a=1&b=12\'"32"', function () {
        var actual = ax5.util.param("a=1&b=12'\"32", 'param');

        actual.should.equal('a=1&b=12\'"32');
    });
    it('ax5.util.param("a=1&b=1232") expect {"a":"1","b":"1232"}', function () {
        var actual = ax5.util.param("a=1&b=1232");

        should.deepEqual(actual, {"a": "1", "b": "1232"});
    });
});

describe('ax5.util.parseJson TEST', function () {
    it('ax5.util.util.parseJson("[{"a":"99"},"2","3"]") expect [{"a":"99"},"2","3"]', function () {
        var actual = ax5.util.parseJson('[{"a":"99"},"2","3"]');

        actual.should.deepEqual([{"a": "99"}, "2", "3"]);
    });
    it('ax5.util.parseJson("{"a":1, "b":function(){return 1;}}", false) expect {"error": 500, "msg": "syntax error"}', function () {
        var actual = ax5.util.parseJson('{"a":1, "b":function(){return 1;}}', false);

        actual.should.deepEqual({"error": 500, "msg": "syntax error"});
    });
    it('ax5.util.parseJson("{"a":1, "b":function(){return 1;}}", true) expect {"a": 1, "b": "{Function}"}', function () {
        var actual = ax5.util.parseJson('{"a":1, "b":function(){return 1;}}', true);

        actual.a.should.equal(1);
        actual.b.should.Function();
    });

    it('ax5.util.parseJson("{"key": [true, false, true, false], "fn": function(){return "fn";}}", true);', function () {
        var actual = ax5.util.parseJson('{"key": [true, false, true, false], "fn": function(){return "fn";}}', true);

        actual.key.should.deepEqual([true, false, true, false]);
        actual.fn.should.Function();
    });
});

describe('ax5.util.toJson TEST', function () {
    var testCases = [
        {
            args: 1,
            expect: 1
        },
        {
            args: "A",
            expect: '"A"'
        },
        {
            args: [1, 2, 3, "A"],
            expect: '[1,2,3,"A"]'
        },
        {
            args: {a: "a", x: "x"},
            expect: '{"a": "a", "x": "x"}'
        },
        {
            args: [1, {"a": "a", "x": "x"}],
            expect: '[1,{"a": "a", "x": "x"}]'
        },
        {
            args: {"a": "a", "x": "x", "list": [1, 2, 3]},
            expect: '{"a": "a", "x": "x", "list": [1,2,3]}'
        },
        {
            args: function func() {
            },
            expect: '"{Function}"'
        },
        {
            args: [true, false, true],
            expect: '[true,false,true]'
        }
    ];

    _.each(testCases, function (testCase) {
        it('ax5.util.toJson(' + (JSON.stringify(testCase.args) || testCase.args.toString()) + ') expect ' + testCase.expect, function () {
            var actual = ax5.util.toJson(testCase.args);

            actual.should.deepEqual(testCase.expect);
        });
    });
});

describe('ax5.util.alert TEST', function () {
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.toArray TEST', function () {
    it('ax5.util.toArray converts [Array-like objects] to [Array]', function () {
        function something() {
            return ax5.util.toArray(arguments);
        }

        var actual = something("A", "X", "I", "S", "J");

        actual.should.deepEqual(["A", "X", "I", "S", "J"]);
    });
});

describe('ax5.util.xxxCookie TEST', function () {

    describe('ax5.util.setCookie TEST', function () {
        it('ax5.util.setCookie("ax5-cookie", "eng+한글")', function () {
            ax5.util.setCookie('ax5-cookie', 'eng+한글');

            document.cookie.indexOf('ax5-cookie=eng+%uD55C%uAE00').should.above(-1);
        });
    });

    describe('ax5.util.getCookie TEST', function () {
        it('ax5.util.getCookie("ax5-cookie") expect "eng+한글"', function () {
            var actual = ax5.util.getCookie('ax5-cookie');

            actual.should.equal('eng+한글');
        });
    });

});

describe('ax5.util.findParentNode TEST', function () {
    it('ax5.util.findParentNode($(".first").get(0), { tagname: "div", clazz: "test-mockup-1" }) expect $("div.test-mockup-1").get(0)', function () {
        var actual = ax5.util.findParentNode($('.first').get(0), {tagname: 'div', clazz: 'test-mockup-1'});
        var expect = $('div.test-mockup-1').get(0);

        should.equal(actual, expect);
    });
});

describe('ax5.util.cssNumber TEST', function () {
    var testCases = [
        {
            args: '100px',
            expect: '100px'
        },
        {
            args: 100,
            expect: '100px'
        },
        {
            args: "100",
            expect: '100px'
        },
        {
            args: '100%',
            expect: '100%'
        },
        {
            args: '##100@',
            expect: '100px'
        }
    ];

    _.each(testCases, function (testCase) {
        it('ax5.util.toJson(' + JSON.stringify(testCase.args) + ') expect ' + testCase.expect, function () {
            var actual = ax5.util.cssNumber(testCase.args);

            should.equal(actual, testCase.expect);
        });
    });
});

describe('ax5.util.css TEST', function () {

    it('ax5.util.css({background:"#ccc",padding:"50px",width:"100px" }) expect background:#ccc;padding:50px;width:100px;', function () {
        var actual = ax5.util.css({background: "#ccc", padding: "50px", width: "100px"});

        should.equal(actual, 'background:#ccc;padding:50px;width:100px;');
    });

    it('ax5.util.css("width:100px;padding: 50px; background: #ccc") expect {width: "100px", padding: "50px", background: "#ccc"}', function () {
        var actual = ax5.util.css('width:100px;padding: 50px; background: #ccc');

        should.deepEqual(actual, {width: "100px", padding: "50px", background: "#ccc"});
    });

    it('ax5.util.css({"border-radius": "20", "font-family": "malgun-gothic"}) expect border-radius:20;font-family:malgun-gothic;', function () {
        var actual = ax5.util.css({"border-radius": "20", "font-family": "malgun-gothic"});

        should.deepEqual(actual, 'border-radius:20;font-family:malgun-gothic;');
    });
});

describe('ax5.util.stopEvent TEST', function () {
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.selectRange TEST', function () {
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.debounce TEST', function () {
    // TODO 대략 난감... HJ.Park 2016-09-26
});
<|endoftext|>


<commit_before>const debug = require('debug')('arxivum:webseed')
const Koa = require('koa')
// const range = require('koa-range')
const range = require('../../../contributions/koa-range')
const koaRouter = require('koa-router')()
const cors = require('koa-cors')
const fs = require('fs')
const path = require('path')

const app = new Koa()

app.use(cors()) // TODO : Optional | Dependent of dev/prod

koaRouter.get('/webseed/:file',
async (ctx, next) => {
  console.log('entra aqui almenos?')
  next()
},
range,
async (ctx, next) => {
  ctx.body = fs.createReadStream(path.join('./files', ctx.params.file))
})

app.use(koaRouter.routes(), koaRouter.allowedMethods())

app.listen(5000)

debug('Webseed listening on port 5000')
<commit_msg>removed unused log<commit_after>const debug = require('debug')('arxivum:webseed')
const Koa = require('koa')
// const range = require('koa-range')
const range = require('../../../contributions/koa-range')
const koaRouter = require('koa-router')()
const cors = require('koa-cors')
const fs = require('fs')
const path = require('path')

const app = new Koa()

app.use(cors()) // TODO : Optional | Dependent of dev/prod

koaRouter.get('/webseed/:file', range, async (ctx, next) => {
  ctx.body = fs.createReadStream(path.join('./files', ctx.params.file))
})

app.use(koaRouter.routes(), koaRouter.allowedMethods())

app.listen(5000)

debug('Webseed listening on port 5000')
<|endoftext|>


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

var express = require('express');
var http = require('http')
var path = require('path');
var utils = require('./utils');
var serialport = require('serialport');
var SerialPort = serialport.SerialPort;
var net = require('net');

// Webserver:

var app = express();

app.configure(function(){
	app.set('port', process.env.PORT || 3000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'jade');
	app.use(express.favicon());
	// app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(app.router);
	app.use(require('stylus').middleware(__dirname + '/public'));
	app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
	app.use(express.errorHandler());
});

var webserver = http.createServer(app).listen(app.get('port'), function(){
	console.log("Express server listening on port " + app.get('port') + " - v 0.0.4");
});

// Serial:

var sp = new SerialPort("/dev/ttyATH0", {
	// parser: serialport.parsers.readline("\n"),
	baudrate: 9600
});

app.get('/', function (req, res){
	res.render('index', { title: 'Hello World' });
});

app.post('/rest/led', function (req, res){
	var state = req.body.state;

	console.log(state);

	sp.write( (state=='on')?'a':'b', function (err, results) {
		if(err) return console.log('serial write err', err);
	});

	res.json(state);
});

sp.on("open", function () {
	console.log('serialport is open');
});

sp.on('data', function (data) {
	console.log('serial data', data);
});

<commit_msg>Node.js: parsing soundlevel and/or soundstate<commit_after>#!/usr/bin/env node

var express = require('express');
var http = require('http')
var path = require('path');
var utils = require('./utils');
var serialport = require('serialport');
var SerialPort = serialport.SerialPort;
var net = require('net');

// Webserver:

var app = express();

app.configure(function(){
	app.set('port', process.env.PORT || 3000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'jade');
	app.use(express.favicon());
	// app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(app.router);
	app.use(require('stylus').middleware(__dirname + '/public'));
	app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
	app.use(express.errorHandler());
});

var webserver = http.createServer(app).listen(app.get('port'), function(){
	console.log("Express server listening on port " + app.get('port') + " - v 0.0.4");
});

// Serial:

// byteLength parser (waits for x bytes and then emits them as data)
function byteLength (length) {
	var data = new Buffer(0);

	return function (emitter, buffer){
		data = Buffer.concat([data, buffer]);
		while (data.length >= length) {
			var out = data.slice(0,length);
			data = data.slice(length);
			emitter.emit('data', out);
		}
	};
}

var sp = new SerialPort("/dev/ttyATH0", {
	parser: byteLength(4),
	baudrate: 9600
});

app.get('/', function (req, res){
	res.render('index', { title: 'Hello World' });
});

app.post('/rest/led', function (req, res){
	var state = req.body.state;

	console.log(state);

	sp.write( (state=='on')?'a':'b', function (err, results) {
		if(err) return console.log('serial write err', err);
	});

	res.json(state);
});

sp.on("open", function () {
	console.log('serialport is open');
});

sp.on('data', function (data) {
	if(data[0] == 03){
		return parseSoundLevel(data);
	}

	if(data[0] == 02){
		return parseSoundState(data);
	}
});

function parseSoundLevel (data) {
	var soundlevel = {
		channel: data[1],
		value: data.readUInt16BE(2) // last two bytes are a 16bit integer encoded big endian
	};
	console.log('sound level changed', soundlevel);
}

function parseSoundState (data) {
	var state = {
		channel: data[1],
		soundon: (data[2] == 1) // boolean, true or false
	};
	console.log('sound state changed', state);

	//data[3] should be emtpy
}

sp.on("close", function () {
	console.log('serialport closed');
});

<|endoftext|>


<commit_before>switch (window.location.hash) {
case '#darwin':
case '#linux':
case '#win32':
    break;
default:
    if (navigator.appVersion.indexOf('Win') != -1) {
        window.location.hash = '#win32';
    } else if (navigator.appVersion.indexOf('Mac') != -1) {
        window.location.hash = '#darwin';
    } else if (navigator.appVersion.indexOf('X11') != -1 || navigator.appVersion.indexOf('Linux') != -1) {
        window.location.hash = '#linux';
    } else {
        window.location.hash = '#darwin';
    }
    break;
}
<commit_msg>website: Defer OS detection until page is ready. Fixes download link for firefox.<commit_after>$(function() {

switch (window.location.hash) {
case '#darwin':
case '#linux':
case '#win32':
    break;
default:
    if (navigator.appVersion.indexOf('Win') != -1) {
        window.location.hash = '#win32';
    } else if (navigator.appVersion.indexOf('Mac') != -1) {
        window.location.hash = '#darwin';
    } else if (navigator.appVersion.indexOf('X11') != -1 || navigator.appVersion.indexOf('Linux') != -1) {
        window.location.hash = '#linux';
    } else {
        window.location.hash = '#darwin';
    }
    break;
}

});
<|endoftext|>


<commit_before><commit_msg>chain a function and return the sum of its arguments<commit_after><|endoftext|>


<commit_before>/* ***********************************************************************************************

    Unify Project

    Homepage: unify-project.org
    License: MIT + Apache (V2)
    Copyright: 2009-2011 Deutsche Telekom AG, Germany, http://telekom.com

*********************************************************************************************** */

/**
 * Manager for view managers which functions as a so-called pop over.
 *
 */

qx.Class.define("unify.view.PopOverManager",
{
  extend : qx.core.Object,
  type : "singleton",

  /*
  *****************************************************************************
     CONSTRUCTOR
  *****************************************************************************
  */

  construct : function()
  {
    this.base(arguments);

    this.__root = qx.core.Init.getApplication().getRoot();
    this.__visibleViewManagers = [];
    this.__overlays={};
    this.__styleRegistry = {};

    var setStyles = qx.lang.Function.bind(qx.bom.element.Style.setStyles, qx.bom.element.Style);

    var pblocker = this.__pblocker = document.createElement("div");
    setStyles(pblocker, {
      "position": "absolute",
      "left": 0,
      "top": 0,
      "width": "100%",
      "height": "100%",
      "display": "none"
    });
    pblocker.id = "popover-blocker";
    var mblocker = this.__mblocker = document.createElement("div");
    setStyles(mblocker, {
      "position": "absolute",
      "left": 0,
      "top": 0,
      "width": "100%",
      "height": "100%",
      "display": "none",
      "backgroundColor": "#000",
      "opacity": 0.5
    });
    mblocker.id = "modal-blocker";
    qx.event.Registration.addListener(pblocker,'tap',this.__onTapBlocker,this);
    this.__root.getElement().appendChild(pblocker);
    this.__root.getElement().appendChild(mblocker);
  },

  /*
  *****************************************************************************
     MEMBERS
  *****************************************************************************
  */

  members :
  {
    __root : null,
    __visibleViewManagers : null,
    __pblocker : null,
    __mblocker : null,

    /** {Map} ID to view manager registry */
    __viewManagers : null,

    /** {Map} Style registry */
    __styleRegistry : null,

    /**
     * Set styles for a specific viewManager
     *
     * @param viewManager {unify.view.ViewManager} View manager to get styles for
     * @param styleMap {Map[]} CSS style map for specific view manager
     */
    setStyles : function(viewManager, styleMap) {
      this.__styleRegistry[viewManager] = styleMap;
    },

    /**
     * Return styles set via setStyles for a specific viewManager
     *
     * @param viewManager {unify.view.ViewManager} View manager to get styles for
     * @return {Map[]} CSS style map for specific view manager
     */
    getStyles : function(viewManager) {
      return this.__styleRegistry[viewManager];
    },

    /**
     * Applies correct zIndex to all visible pop-overs
     * and positions blocker below the topmost visible popover.
     */
    __sortPopOvers : function()
    {
      var zIndexBase=100;//TODO read base value from config or some other global strategy to play nice with other zIndex dependant features like transition animations
      var visible = this.__visibleViewManagers;
      var pblocker = this.__pblocker;
      var mblocker = this.__mblocker;

      var numVisible=visible.length;
      for (var i=0; i<numVisible; i++) {
        var viewManager=visible[i];
        var elem=viewManager.getElement();
        if(viewManager.getDisplayMode()=='popover'){
          elem=elem.parentNode;//adjust wrapper for popovers
        }
        elem.style.zIndex = zIndexBase + 2*i;//leave a gap of 1 between layers so the blocker fits between 2 visible popovers
      }

      if(numVisible>0){
        var mSet=false;
        var pSet=false;
        for(var i=numVisible-1;i>=0;i--){
          var mode=visible[i].getDisplayMode();

          if(!mSet && mode == 'modal'){
            mblocker.style.zIndex = (zIndexBase-1)+2*i;
            mblocker.style.display = 'block';
            mSet=true;
          } else if (!pSet && mode =='popover'){
            pblocker.style.zIndex = (zIndexBase-1)+2*i;
            pblocker.style.display = 'block';
            pSet=true;
          }
          if(mSet&&pSet){
            break;
          }
        }
        if(!mSet){
          mblocker.style.zIndex =undefined;
          mblocker.style.display='none';
        }
        if(!pSet){
          pblocker.style.zIndex = undefined;
          pblocker.style.display='none';
        }
      } else {
        pblocker.style.zIndex = undefined;
        mblocker.style.zIndex = undefined;
        pblocker.style.display='none';
        mblocker.style.display='none';
      }
    },

    /**
     * Closes topmost popover
     */
    __onTapBlocker : function(){
      var numVisible=this.__visibleViewManagers.length;
      if(numVisible>0){
        var topMost=this.__visibleViewManagers[numVisible-1];

        this.hide(topMost.getId());
      } else {
        this.error("tapped on blocker without visible viewmanager");
        //sort popovers again to make sure the blocker is gone
        this.__sortPopOvers();
      }
    },

    /**
     * Shows the view manager with the given ID.
     *
     * @param id {String} ID of view manager
     * @param trigger {unify.ui.Widget?null} Widget that triggers the opening of the popover
     * @param triggerPosition {String?null} Position on trigger to attach popover to
     * @param popoverPosition {String?null} Position on popover to attach to the trigger position
     */
    show : function(id, trigger, triggerPosition, popoverPosition)
    {
      var modLeft = null;
      var modTop = null;

      var viewManager = unify.view.ViewManager.get(id);
      if (!viewManager.isInitialized()) {
        viewManager.init();
      }

      if (qx.core.Environment.get("qx.debug"))
      {
        if (!viewManager) {
          throw new Error("Unknown view manager: " + id);
        }
      }
      if (this.__visibleViewManagers.indexOf(viewManager) >-1) {
        if (qx.core.Environment.get("qx.debug")){
            this.debug("called show with viewmanager that is already visible: "+id);
        }
        return;//already visible
      }
      if (qx.core.Environment.get("qx.debug")) {
        this.debug("Show: " + id);
      }
      var elem = viewManager.getElement();
      var overlay;
      if(viewManager.getDisplayMode()=='popover'){
        if (popoverPosition) {
          var map = {
            "l" : "left",
            "c" : "center",
            "r" : "right",
            "t" : "top",
            "b" : "bottom"
          };

          var direction = map[popoverPosition[0] || ""];
          var alignment = map[popoverPosition[1] || ""];

          overlay=this.__getOverlay(viewManager, direction, alignment);
        } else {
          overlay=this.__getOverlay(viewManager);
        }

        var style = this.__styleRegistry[viewManager] || {};

        if (trigger && triggerPosition && popoverPosition) {
          var position = trigger.getPositionInfo();

          var direction = triggerPosition[0] || "r";
          var alignment = triggerPosition[1] || "c";

          var left;
          var top;

          if (direction == "r" || direction == "l") {
            if (direction == "r") {
              left = position.left + position.width;
            } else {
              left = position.left;
            }

            if (alignment == "t") {
              top = position.top;
            } else if (alignment == "c") {
              top = position.top + Math.round(position.height / 2);
            } else if (alignment == "b") {
              top = position.top + position.height;
            }
          } else {
            if (direction == "t") {
              top = position.top;
            } else {
              top = position.top + position.height;
            }

            if (alignment == "l") {
              left = position.left;
            } else if (alignment == "c") {
              left = position.left + Math.round(position.width / 2);
            } else if (alignment == "r") {
              left = position.left + position.width;
            }
          }

          var modLeft = left;
          var modTop = top;
        }

        if (style) {
          var mystyle = qx.lang.Object.clone(style);
          delete mystyle.left;
          delete mystyle.top;

          overlay.setStyle(mystyle);
          this.__root.add(overlay);
        } else {
          this.error("No style of overlay for view " + viewManager);
        }

        overlay.add(viewManager.getWidgetElement());
      } else {
        if(!this.__root==elem.parentNode){
          this.__root.appendChild(elem);
        }
      }
      this.__visibleViewManagers.push(viewManager);
      this.__sortPopOvers();
      viewManager.show();
      if(overlay){
         overlay.show(modLeft, modTop);
      }
    },

    /**
     * Hides the view manager with the given ID.
     *
     * @param id {String} ID of view manager
     * @param skipAnimation {Boolean} True if the animation should be skipped
     */
    hide : function(id,skipAnimation)
    {
      var viewManager=unify.view.ViewManager.get(id);

      if (qx.core.Environment.get("qx.debug"))
      {
        if (!viewManager) {
          throw new Error("Unknown view manager: " + id);
        }
      }
      if (this.__visibleViewManagers.indexOf(viewManager) < 0) {
        if (qx.core.Environment.get("qx.debug")){
            this.debug("called hide with viewmanager that is not visible: "+id);
        }
        return;
      }
      var mode=viewManager.getDisplayMode();

      var self=this;
      var hideCallback=function(){
        viewManager.hide();

        qx.lang.Array.remove(self.__visibleViewManagers, viewManager);
        self.__sortPopOvers();
      };

      if(mode=='popover'){
        var overlay=this.__overlays[viewManager];
        if(skipAnimation){
          var animate=overlay.getEnableAnimation();
          overlay.setEnableAnimation(false);
          overlay.hide();
          overlay.setEnableAnimation(animate);
          hideCallback();
        } else {
          overlay.addListenerOnce("hidden",hideCallback,this);
          overlay.hide();
        }
      } else {
        viewManager.hide(hideCallback);
      }
    },

    /**
     * Get overlay element
     *
     * @param viewManager {unify.view.ViewManager} View manager to generate overlay for
     * @param arrowDirection {String} Direction of arrow of popover (left, top, right, bottom)
     * @param arrowAlignment {String} Alignment of arrow on popover (top, center, bottom or left, center, right)
     *
     * @return {unify.ui.container.Overlay} Overlay widget
     */
    __getOverlay : function(viewManager, arrowDirection, arrowAlignment){
      var overlay=this.__overlays[viewManager];
      if(!overlay){
        overlay=new unify.ui.container.Overlay(arrowDirection, arrowAlignment);
        var elem=overlay.getElement();
        elem.id='popover-overlay';
        /*var indicator=document.createElement("div");
        indicator.className="popover-indicator";
        elem.appendChild(indicator);*/
        this.__overlays[viewManager]=overlay;
      }
      return overlay;
    }
  },

  /*
  *****************************************************************************
     DESTRUCTOR
  *****************************************************************************
  */

  destruct : function() {
    qx.event.Registration.removeListener(this.__pblocker,'tap',this.__onTapBlocker,this);
    this.__root.removeChild(this.__pblocker);
    this.__root.removeChild(this.__mblocker);
    this.__root = this.__pblocker= this.__mblocker=this.__viewManager=this.__styleRegistry = null;
  }
});
<commit_msg>Fix element request via widget<commit_after>/* ***********************************************************************************************

    Unify Project

    Homepage: unify-project.org
    License: MIT + Apache (V2)
    Copyright: 2009-2011 Deutsche Telekom AG, Germany, http://telekom.com

*********************************************************************************************** */

/**
 * Manager for view managers which functions as a so-called pop over.
 *
 */

qx.Class.define("unify.view.PopOverManager",
{
  extend : qx.core.Object,
  type : "singleton",

  /*
  *****************************************************************************
     CONSTRUCTOR
  *****************************************************************************
  */

  construct : function()
  {
    this.base(arguments);

    this.__root = qx.core.Init.getApplication().getRoot();
    this.__visibleViewManagers = [];
    this.__overlays={};
    this.__styleRegistry = {};

    var setStyles = qx.lang.Function.bind(qx.bom.element.Style.setStyles, qx.bom.element.Style);

    var pblocker = this.__pblocker = document.createElement("div");
    setStyles(pblocker, {
      "position": "absolute",
      "left": 0,
      "top": 0,
      "width": "100%",
      "height": "100%",
      "display": "none"
    });
    pblocker.id = "popover-blocker";
    var mblocker = this.__mblocker = document.createElement("div");
    setStyles(mblocker, {
      "position": "absolute",
      "left": 0,
      "top": 0,
      "width": "100%",
      "height": "100%",
      "display": "none",
      "backgroundColor": "#000",
      "opacity": 0.5
    });
    mblocker.id = "modal-blocker";
    qx.event.Registration.addListener(pblocker,'tap',this.__onTapBlocker,this);
    this.__root.getElement().appendChild(pblocker);
    this.__root.getElement().appendChild(mblocker);
  },

  /*
  *****************************************************************************
     MEMBERS
  *****************************************************************************
  */

  members :
  {
    __root : null,
    __visibleViewManagers : null,
    __pblocker : null,
    __mblocker : null,

    /** {Map} ID to view manager registry */
    __viewManagers : null,

    /** {Map} Style registry */
    __styleRegistry : null,

    /**
     * Set styles for a specific viewManager
     *
     * @param viewManager {unify.view.ViewManager} View manager to get styles for
     * @param styleMap {Map[]} CSS style map for specific view manager
     */
    setStyles : function(viewManager, styleMap) {
      this.__styleRegistry[viewManager] = styleMap;
    },

    /**
     * Return styles set via setStyles for a specific viewManager
     *
     * @param viewManager {unify.view.ViewManager} View manager to get styles for
     * @return {Map[]} CSS style map for specific view manager
     */
    getStyles : function(viewManager) {
      return this.__styleRegistry[viewManager];
    },

    /**
     * Applies correct zIndex to all visible pop-overs
     * and positions blocker below the topmost visible popover.
     */
    __sortPopOvers : function()
    {
      var zIndexBase=100;//TODO read base value from config or some other global strategy to play nice with other zIndex dependant features like transition animations
      var visible = this.__visibleViewManagers;
      var pblocker = this.__pblocker;
      var mblocker = this.__mblocker;

      var numVisible=visible.length;
      for (var i=0; i<numVisible; i++) {
        var viewManager=visible[i];
        var elem=viewManager.getElement();
        if(viewManager.getDisplayMode()=='popover'){
          elem=elem.parentNode;//adjust wrapper for popovers
        }
        elem.style.zIndex = zIndexBase + 2*i;//leave a gap of 1 between layers so the blocker fits between 2 visible popovers
      }

      if(numVisible>0){
        var mSet=false;
        var pSet=false;
        for(var i=numVisible-1;i>=0;i--){
          var mode=visible[i].getDisplayMode();

          if(!mSet && mode == 'modal'){
            mblocker.style.zIndex = (zIndexBase-1)+2*i;
            mblocker.style.display = 'block';
            mSet=true;
          } else if (!pSet && mode =='popover'){
            pblocker.style.zIndex = (zIndexBase-1)+2*i;
            pblocker.style.display = 'block';
            pSet=true;
          }
          if(mSet&&pSet){
            break;
          }
        }
        if(!mSet){
          mblocker.style.zIndex =undefined;
          mblocker.style.display='none';
        }
        if(!pSet){
          pblocker.style.zIndex = undefined;
          pblocker.style.display='none';
        }
      } else {
        pblocker.style.zIndex = undefined;
        mblocker.style.zIndex = undefined;
        pblocker.style.display='none';
        mblocker.style.display='none';
      }
    },

    /**
     * Closes topmost popover
     */
    __onTapBlocker : function(){
      var numVisible=this.__visibleViewManagers.length;
      if(numVisible>0){
        var topMost=this.__visibleViewManagers[numVisible-1];

        this.hide(topMost.getId());
      } else {
        this.error("tapped on blocker without visible viewmanager");
        //sort popovers again to make sure the blocker is gone
        this.__sortPopOvers();
      }
    },

    /**
     * Shows the view manager with the given ID.
     *
     * @param id {String} ID of view manager
     * @param trigger {unify.ui.Widget?null} Widget that triggers the opening of the popover
     * @param triggerPosition {String?null} Position on trigger to attach popover to
     * @param popoverPosition {String?null} Position on popover to attach to the trigger position
     */
    show : function(id, trigger, triggerPosition, popoverPosition)
    {
      var modLeft = null;
      var modTop = null;

      var viewManager = unify.view.ViewManager.get(id);
      if (!viewManager.isInitialized()) {
        viewManager.init();
      }

      if (qx.core.Environment.get("qx.debug"))
      {
        if (!viewManager) {
          throw new Error("Unknown view manager: " + id);
        }
      }
      if (this.__visibleViewManagers.indexOf(viewManager) >-1) {
        if (qx.core.Environment.get("qx.debug")){
            this.debug("called show with viewmanager that is already visible: "+id);
        }
        return;//already visible
      }
      if (qx.core.Environment.get("qx.debug")) {
        this.debug("Show: " + id);
      }
      var elem = viewManager.getWidgetElement().getElement();
      var overlay;
      if(viewManager.getDisplayMode()=='popover'){
        if (popoverPosition) {
          var map = {
            "l" : "left",
            "c" : "center",
            "r" : "right",
            "t" : "top",
            "b" : "bottom"
          };

          var direction = map[popoverPosition[0] || ""];
          var alignment = map[popoverPosition[1] || ""];

          overlay=this.__getOverlay(viewManager, direction, alignment);
        } else {
          overlay=this.__getOverlay(viewManager);
        }

        var style = this.__styleRegistry[viewManager] || {};

        if (trigger && triggerPosition && popoverPosition) {
          var position = trigger.getPositionInfo();

          var direction = triggerPosition[0] || "r";
          var alignment = triggerPosition[1] || "c";

          var left;
          var top;

          if (direction == "r" || direction == "l") {
            if (direction == "r") {
              left = position.left + position.width;
            } else {
              left = position.left;
            }

            if (alignment == "t") {
              top = position.top;
            } else if (alignment == "c") {
              top = position.top + Math.round(position.height / 2);
            } else if (alignment == "b") {
              top = position.top + position.height;
            }
          } else {
            if (direction == "t") {
              top = position.top;
            } else {
              top = position.top + position.height;
            }

            if (alignment == "l") {
              left = position.left;
            } else if (alignment == "c") {
              left = position.left + Math.round(position.width / 2);
            } else if (alignment == "r") {
              left = position.left + position.width;
            }
          }

          var modLeft = left;
          var modTop = top;
        }

        if (style) {
          var mystyle = qx.lang.Object.clone(style);
          delete mystyle.left;
          delete mystyle.top;

          overlay.setStyle(mystyle);
          this.__root.add(overlay);
        } else {
          this.error("No style of overlay for view " + viewManager);
        }

        overlay.add(viewManager.getWidgetElement());
      } else {
        if(!this.__root==elem.parentNode){
          this.__root.appendChild(elem);
        }
      }
      this.__visibleViewManagers.push(viewManager);
      this.__sortPopOvers();
      viewManager.show();
      if(overlay){
         overlay.show(modLeft, modTop);
      }
    },

    /**
     * Hides the view manager with the given ID.
     *
     * @param id {String} ID of view manager
     * @param skipAnimation {Boolean} True if the animation should be skipped
     */
    hide : function(id,skipAnimation)
    {
      var viewManager=unify.view.ViewManager.get(id);

      if (qx.core.Environment.get("qx.debug"))
      {
        if (!viewManager) {
          throw new Error("Unknown view manager: " + id);
        }
      }
      if (this.__visibleViewManagers.indexOf(viewManager) < 0) {
        if (qx.core.Environment.get("qx.debug")){
            this.debug("called hide with viewmanager that is not visible: "+id);
        }
        return;
      }
      var mode=viewManager.getDisplayMode();

      var self=this;
      var hideCallback=function(){
        viewManager.hide();

        qx.lang.Array.remove(self.__visibleViewManagers, viewManager);
        self.__sortPopOvers();
      };

      if(mode=='popover'){
        var overlay=this.__overlays[viewManager];
        if(skipAnimation){
          var animate=overlay.getEnableAnimation();
          overlay.setEnableAnimation(false);
          overlay.hide();
          overlay.setEnableAnimation(animate);
          hideCallback();
        } else {
          overlay.addListenerOnce("hidden",hideCallback,this);
          overlay.hide();
        }
      } else {
        viewManager.hide(hideCallback);
      }
    },

    /**
     * Get overlay element
     *
     * @param viewManager {unify.view.ViewManager} View manager to generate overlay for
     * @param arrowDirection {String} Direction of arrow of popover (left, top, right, bottom)
     * @param arrowAlignment {String} Alignment of arrow on popover (top, center, bottom or left, center, right)
     *
     * @return {unify.ui.container.Overlay} Overlay widget
     */
    __getOverlay : function(viewManager, arrowDirection, arrowAlignment){
      var overlay=this.__overlays[viewManager];
      if(!overlay){
        overlay=new unify.ui.container.Overlay(arrowDirection, arrowAlignment);
        var elem=overlay.getElement();
        elem.id='popover-overlay';
        /*var indicator=document.createElement("div");
        indicator.className="popover-indicator";
        elem.appendChild(indicator);*/
        this.__overlays[viewManager]=overlay;
      }
      return overlay;
    }
  },

  /*
  *****************************************************************************
     DESTRUCTOR
  *****************************************************************************
  */

  destruct : function() {
    qx.event.Registration.removeListener(this.__pblocker,'tap',this.__onTapBlocker,this);
    this.__root.removeChild(this.__pblocker);
    this.__root.removeChild(this.__mblocker);
    this.__root = this.__pblocker= this.__mblocker=this.__viewManager=this.__styleRegistry = null;
  }
});
<|endoftext|>


<commit_before>

/**
 * Retrieves all new traces for the displayed flights
 */
function updateFlightsFromJSON() {
  flights.each(function(flight) {
    var url = '/tracking/' + flight.getID() + '/json';

    $.ajax(url, {
      data: { last_update: flight.getLastUpdate() || null },
      success: function(data) {
        updateFlight(data.sfid, data.points,
                     data.barogram_t, data.barogram_h,
                     data.enl, data.elevations);

        updateBaroData();
        updateBaroScale();
        baro.draw();
      }
    });
  });
}

/**
 * Updates a tracking flight.
 *
 * Note: _lonlat, _levels, _time, _enl and _height MUST have the same number of
 *   elements when decoded.
 *
 * @param {int} tracking_id SkyLines tracking ID.
 * @param {String} _lonlat Google polyencoded string of geolocations
 *   (lon + lat, WSG 84).
 * @param {String} _time Google polyencoded string of time values.
 * @param {String} _height Google polyencoded string of height values.
 * @param {String} _enl Google polyencoded string of enl values.
 * @param {String} _elevations Google polyencoded string of elevations.
 */

function updateFlight(tracking_id, _lonlat, _time,
    _height, _enl, _elevations) {
  // find the flight to update
  var flight = flights.get(tracking_id);
  if (!flight)
    return;

  flight.update(_lonlat, _time, _height, _enl, _elevations);
  setTime(global_time);
}
<commit_msg>tracking.js: simplify updateFlight()<commit_after>

/**
 * Retrieves all new traces for the displayed flights
 */
function updateFlightsFromJSON() {
  flights.each(function(flight) {
    var url = '/tracking/' + flight.getID() + '/json';

    $.ajax(url, {
      data: { last_update: flight.getLastUpdate() || null },
      success: function(data) {
        updateFlight(data);
        updateBaroData();
        updateBaroScale();
        baro.draw();
      }
    });
  });
}

/**
 * Updates a tracking flight.
 *
 * @param {Object} data The data returned by the JSON request.
 */

function updateFlight(data) {
  // find the flight to update
  var flight = flights.get(data.sfid);
  if (!flight)
    return;

  flight.update(data.points, data.barogram_t, data.barogram_h,
                data.enl, data.elevations);
  setTime(global_time);
}
<|endoftext|>