<commit_before>/*
editableFactory is used to generate editable directives (see `/directives` folder)
Inside it does several things:
- detect form for editable element. Form may be one of three types:
  1. autogenerated form (for single editable elements)
  2. wrapper form (element wrapped by <form> tag)
  3. linked form (element has `e-form` attribute pointing to existing form)

- attach editableController to element

Depends on: editableController, editableFormFactory
*/
angular.module('xeditable').factory('editableDirectiveFactory',
['$parse', '$compile', 'editableThemes', '$rootScope', '$document', 'editableController', 'editableFormController', 'editableOptions',
function($parse, $compile, editableThemes, $rootScope, $document, editableController, editableFormController, editableOptions) {

  //directive object
  return function(overwrites) {
    return {
      restrict: 'A',
      scope: true,
      require: [overwrites.directiveName, '?^form'],
      controller: editableController,
      link: function(scope, elem, attrs, ctrl) {
        // editable controller
        var eCtrl = ctrl[0];

        // form controller
        var eFormCtrl;

        // this variable indicates is element is bound to some existing form,
        // or it's single element who's form will be generated automatically
        // By default consider single element without any linked form.ß
        var hasForm = false;

        var isSingle = attrs.eSingle !== undefined;

        // element wrapped by form
        if(ctrl[1]) {
          eFormCtrl = ctrl[1];
          hasForm = !isSingle;
        } else if(attrs.eForm) { // element not wrapped by <form>, but we hane `e-form` attr
          var getter = $parse(attrs.eForm)(scope);
          if(getter) { // form exists in scope (above), e.g. editable column
            eFormCtrl = getter;
            hasForm = true;
          } else { // form exists below or not exist at all: check document.forms
            for(var i=0; i<$document[0].forms.length;i++){
              if($document[0].forms[i].name === attrs.eForm) {
                // form is below and not processed yet
                eFormCtrl = null;
                hasForm = true;
                break;
              }
            }
          }
        }

        /*
        if(hasForm && !attrs.eName) {
          throw 'You should provide `e-name` for editable element inside form!';
        }
        */

        //check for `editable-form` attr in form
        /*
        if(eFormCtrl && ) {
          throw 'You should provide `e-name` for editable element inside form!';
        }
        */

        // store original props to `parent` before merge
        angular.forEach(overwrites, function(v, k) {
          if(eCtrl[k] !== undefined) {
            eCtrl.parent[k] = eCtrl[k];
          }
        });

        // merge overwrites to base editable controller
        angular.extend(eCtrl, overwrites);

        // x-editable can be disabled using editableOption or edit-disabled attribute
        var disabled = angular.isDefined(attrs.editDisabled) ?
          scope.$eval(attrs.editDisabled) :
          editableOptions.isDisabled;

        if (disabled) {
          return;
        }

        // init editable ctrl
        eCtrl.init(!hasForm);

        // publich editable controller as `$editable` to be referenced in html
        scope.$editable = eCtrl;

        // add `editable` class to element
        elem.addClass('editable');

        // hasForm
        if(hasForm) {
          if(eFormCtrl) {
            scope.$form = eFormCtrl;
            if(!scope.$form.$addEditable) {
              throw 'Form with editable elements should have `editable-form` attribute.';
            }
            scope.$form.$addEditable(eCtrl);
          } else {
            // future form (below): add editable controller to buffer and add to form later
            $rootScope.$$editableBuffer = $rootScope.$$editableBuffer || {};
            $rootScope.$$editableBuffer[attrs.eForm] = $rootScope.$$editableBuffer[attrs.eForm] || [];
            $rootScope.$$editableBuffer[attrs.eForm].push(eCtrl);
            scope.$form = null; //will be re-assigned later
          }
        // !hasForm
        } else {
          // create editableform controller
          scope.$form = editableFormController();
          // add self to editable controller
          scope.$form.$addEditable(eCtrl);

          // if `e-form` provided, publish local $form in scope
          if(attrs.eForm) {
            scope.$parent[attrs.eForm] = scope.$form;
          }

          // bind click - if no external form defined
          if(!attrs.eForm || attrs.eClickable) {
            elem.addClass('editable-click');
            elem.bind(editableOptions.activationEvent, function(e) {
              e.preventDefault();
              e.editable = eCtrl;
              scope.$apply(function(){
                scope.$form.$show();
              });
            });
          }
        }

      }
    };
  };
}]);
<commit_msg>even simpler yet!<commit_after>/*
editableFactory is used to generate editable directives (see `/directives` folder)
Inside it does several things:
- detect form for editable element. Form may be one of three types:
  1. autogenerated form (for single editable elements)
  2. wrapper form (element wrapped by <form> tag)
  3. linked form (element has `e-form` attribute pointing to existing form)

- attach editableController to element

Depends on: editableController, editableFormFactory
*/
angular.module('xeditable').factory('editableDirectiveFactory',
['$parse', '$compile', 'editableThemes', '$rootScope', '$document', 'editableController', 'editableFormController', 'editableOptions',
function($parse, $compile, editableThemes, $rootScope, $document, editableController, editableFormController, editableOptions) {

  //directive object
  return function(overwrites) {
    return {
      restrict: 'A',
      scope: true,
      require: [overwrites.directiveName, '?^form'],
      controller: editableController,
      link: function(scope, elem, attrs, ctrl) {
        // editable controller
        var eCtrl = ctrl[0];

        // form controller
        var eFormCtrl;

        // this variable indicates is element is bound to some existing form,
        // or it's single element who's form will be generated automatically
        // By default consider single element without any linked form.ß
        var hasForm = false;

        // element wrapped by form
        if(ctrl[1]) {
          eFormCtrl = ctrl[1];
          hasForm = attrs.eSingle === undefined;
        } else if(attrs.eForm) { // element not wrapped by <form>, but we hane `e-form` attr
          var getter = $parse(attrs.eForm)(scope);
          if(getter) { // form exists in scope (above), e.g. editable column
            eFormCtrl = getter;
            hasForm = true;
          } else { // form exists below or not exist at all: check document.forms
            for(var i=0; i<$document[0].forms.length;i++){
              if($document[0].forms[i].name === attrs.eForm) {
                // form is below and not processed yet
                eFormCtrl = null;
                hasForm = true;
                break;
              }
            }
          }
        }

        /*
        if(hasForm && !attrs.eName) {
          throw 'You should provide `e-name` for editable element inside form!';
        }
        */

        //check for `editable-form` attr in form
        /*
        if(eFormCtrl && ) {
          throw 'You should provide `e-name` for editable element inside form!';
        }
        */

        // store original props to `parent` before merge
        angular.forEach(overwrites, function(v, k) {
          if(eCtrl[k] !== undefined) {
            eCtrl.parent[k] = eCtrl[k];
          }
        });

        // merge overwrites to base editable controller
        angular.extend(eCtrl, overwrites);

        // x-editable can be disabled using editableOption or edit-disabled attribute
        var disabled = angular.isDefined(attrs.editDisabled) ?
          scope.$eval(attrs.editDisabled) :
          editableOptions.isDisabled;

        if (disabled) {
          return;
        }

        // init editable ctrl
        eCtrl.init(!hasForm);

        // publich editable controller as `$editable` to be referenced in html
        scope.$editable = eCtrl;

        // add `editable` class to element
        elem.addClass('editable');

        // hasForm
        if(hasForm) {
          if(eFormCtrl) {
            scope.$form = eFormCtrl;
            if(!scope.$form.$addEditable) {
              throw 'Form with editable elements should have `editable-form` attribute.';
            }
            scope.$form.$addEditable(eCtrl);
          } else {
            // future form (below): add editable controller to buffer and add to form later
            $rootScope.$$editableBuffer = $rootScope.$$editableBuffer || {};
            $rootScope.$$editableBuffer[attrs.eForm] = $rootScope.$$editableBuffer[attrs.eForm] || [];
            $rootScope.$$editableBuffer[attrs.eForm].push(eCtrl);
            scope.$form = null; //will be re-assigned later
          }
        // !hasForm
        } else {
          // create editableform controller
          scope.$form = editableFormController();
          // add self to editable controller
          scope.$form.$addEditable(eCtrl);

          // if `e-form` provided, publish local $form in scope
          if(attrs.eForm) {
            scope.$parent[attrs.eForm] = scope.$form;
          }

          // bind click - if no external form defined
          if(!attrs.eForm || attrs.eClickable) {
            elem.addClass('editable-click');
            elem.bind(editableOptions.activationEvent, function(e) {
              e.preventDefault();
              e.editable = eCtrl;
              scope.$apply(function(){
                scope.$form.$show();
              });
            });
          }
        }

      }
    };
  };
}]);
<|endoftext|>


<commit_before>/*======================================================
************   Material Text Inputs   ************
======================================================*/
app.initPageMaterialInputs = function (pageContainer) {
    pageContainer = $(pageContainer);
    var textareas = pageContainer.find('textarea.resizable');
    pageContainer.find('.item-input').each(function () {
        var itemInput = $(this);
        var notInputs = ['checkbox', 'button', 'submit', 'range', 'radio', 'image'];
        itemInput.find('input, select, textarea').each(function () {
            var input = $(this);
            if (notInputs.indexOf(input.attr('type')) < 0) {
                itemInput.addClass('item-input-field');
                if (input.val().trim() !== '') {
                    input.parents('.item-input, .input-field').add(input.parents('.item-inner')).addClass('not-empty-state');
                }
            }
        });
        if (itemInput.parents('.input-item, .inputs-list').length > 0) return;
        itemInput.parents('.list-block').eq(0).addClass('inputs-list');
    });
};
/*======================================================
************   Material Focus Inputs   ************
======================================================*/
app.initMaterialWatchInputs = function () {
    var notInputs = ['checkbox', 'button', 'submit', 'range', 'radio', 'image'];
    function addFocusState(e) {
        /*jshint validthis:true*/
        var i = $(this);
        var type = i.attr('type');
        if (notInputs.indexOf(type) >= 0) return;
        var els = i.add(i.parents('.item-input, .input-field')).add(i.parents('.item-inner').eq(0));
        els.addClass('focus-state');
    }
    function removeFocusState(e) {
        /*jshint validthis:true*/
        var i = $(this), value = i.val();
        var type = i.attr('type');
        if (notInputs.indexOf(type) >= 0) return;
        var els = i.add(i.parents('.item-input, .input-field')).add(i.parents('.item-inner').eq(0));
        els.removeClass('focus-state');
        if (value && value.trim() !== '') {
            els.addClass('not-empty-state');
        }
        else {
            els.removeClass('not-empty-state');
        }
    }
    function watchChangeState(e) {
        /*jshint validthis:true*/
        var i = $(this), value = i.val();
        var type = i.attr('type');
        if (notInputs.indexOf(type) >= 0) return;
        var els = i.add(i.parents('.item-input, .input-field')).add(i.parents('.item-inner').eq(0));
        if (value && value.trim() !== '') {
            els.addClass('not-empty-state');
        }
        else {
            els.removeClass('not-empty-state');
        }
    }
    $(document).on('change', '.item-input input, .item-input select, .item-input textarea, input, textarea, select', watchChangeState, true);
    $(document).on('focus', '.item-input input, .item-input select, .item-input textarea, input, textarea, select', addFocusState, true);
    $(document).on('blur', '.item-input input, .item-input select, .item-input textarea, input, textarea, select', removeFocusState, true);
};<commit_msg>Fix value check on array<commit_after>/*======================================================
************   Material Text Inputs   ************
======================================================*/
app.initPageMaterialInputs = function (pageContainer) {
    pageContainer = $(pageContainer);
    var textareas = pageContainer.find('textarea.resizable');
    pageContainer.find('.item-input').each(function () {
        var itemInput = $(this);
        var notInputs = ['checkbox', 'button', 'submit', 'range', 'radio', 'image'];
        itemInput.find('input, select, textarea').each(function () {
            var input = $(this);
            if (notInputs.indexOf(input.attr('type')) < 0) {
                itemInput.addClass('item-input-field');
                if (input.val().trim() !== '') {
                    input.parents('.item-input, .input-field').add(input.parents('.item-inner')).addClass('not-empty-state');
                }
            }
        });
        if (itemInput.parents('.input-item, .inputs-list').length > 0) return;
        itemInput.parents('.list-block').eq(0).addClass('inputs-list');
    });
};
/*======================================================
************   Material Focus Inputs   ************
======================================================*/
app.initMaterialWatchInputs = function () {
    var notInputs = ['checkbox', 'button', 'submit', 'range', 'radio', 'image'];
    function addFocusState(e) {
        /*jshint validthis:true*/
        var i = $(this);
        var type = i.attr('type');
        if (notInputs.indexOf(type) >= 0) return;
        var els = i.add(i.parents('.item-input, .input-field')).add(i.parents('.item-inner').eq(0));
        els.addClass('focus-state');
    }
    function removeFocusState(e) {
        /*jshint validthis:true*/
        var i = $(this), value = i.val();
        var type = i.attr('type');
        if (notInputs.indexOf(type) >= 0) return;
        var els = i.add(i.parents('.item-input, .input-field')).add(i.parents('.item-inner').eq(0));
        els.removeClass('focus-state');
        if (value && value.trim() !== '') {
            els.addClass('not-empty-state');
        }
        else {
            els.removeClass('not-empty-state');
        }
    }
    function watchChangeState(e) {
        /*jshint validthis:true*/
        var input = $(this),
            value = input.val();
        var type = input.attr('type');
        if (notInputs.indexOf(type) >= 0) return;
        var els = input.add(input.parents('.item-input, .input-field')).add(input.parents('.item-inner').eq(0));
        if (els.length === 0) return;
        if (value && (typeof value === 'string' && value.trim() !== '') || (Array.isArray(value) && value.length > 0)) {
            els.addClass('not-empty-state');
        }
        else {
            els.removeClass('not-empty-state');
        }
    }
    $(document).on('change', 'input, textarea, select', watchChangeState, true);
    $(document).on('focus', 'input, textarea, select', addFocusState, true);
    $(document).on('blur', 'input, textarea, select', removeFocusState, true);
};
<|endoftext|>


<commit_before>module( "main", { teardown: moduleTeardown } );

test( "success", function() {
	stop();
	expect( 1 );
	$.jsonp({
		url: "http://gdata.youtube.com/feeds/api/users/julianaubourg?callback=?",
		data: {
			alt: "json-in-script"
		},
		success: function() {
			ok( true, "Success" );
		},
		error: function() {
			ok( false, "Error" );
		},
		complete: function() {
			start();
		}
	});
});

test( "error (HTTP Code)", function() {
	stop();
	expect( 1 );
	$.jsonp({
		url: "http://gdata.youtube.com/feeds/api/users/hgfusyggbvbdbrfvurgbirhtiytjrhjsrhk66?callback=?",
		data: {
			alt: "json-in-script"
		},
		success: function() {
			ok( false, "Success" );
		},
		error: function() {
			ok( true, "Error" );
		},
		complete: function() {
			start();
		}
	});
});

test( "error (Syntax Error)", function() {
	stop();
	expect( 2 );
	var oldOnError = window.onerror;
	window.onerror = function() {
		ok( true, "Syntax Error Thrown" );
		return false;
	};
	$.jsonp({
		url: "data/syntax-error.js",
		cache: true,
		success: function() {
			ok( false, "Success" );
		},
		error: function() {
			ok( true, "Error" );
		},
		complete: function() {
			window.onerror = oldOnError;
			start();
		}
	});
});

test( "error (callback not called)", function() {
	stop();
	expect( 2 );
	$.jsonp({
		url: "data/no-callback.js",
		cache: true,
		success: function() {
			ok( false, "Success" );
		},
		error: function() {
			ok( true, "Error" );
		},
		complete: function() {
			strictEqual( window.bob, 33, "script was executed" );
			window.bob = false;
			start();
		}
	});
});

if ( $.Deferred ) {

	test( "promise - success", function() {
		stop();
		expect( 2 );
		$.jsonp({
			url: "http://gdata.youtube.com/feeds/api/users/julianaubourg?callback=?",
			data: {
				alt: "json-in-script"
			},
			success: function() {
				ok( true, "Success (options)" );
			},
			complete: function() {
				start();
			}
		}).done(function() {
			ok( true, "Success" );
		}).fail(function() {
			ok( false, "Error" );
		});
	});

	test( "promise - error (HTTP Code)", function() {
		stop();
		expect( 2 );
		$.jsonp({
			url: "http://gdata.youtube.com/feeds/api/users/hgfusyggbvbdbrfvurgbirhtiytjrhjsrhk66?callback=?",
			data: {
				alt: "json-in-script"
			},
			error: function() {
				ok( true, "Error (options)" );
			},
			complete: function() {
				start();
			}
		}).done(function() {
			ok( false, "Success" );
		}).fail(function() {
			ok( true, "Error" );
		});
	});

	test( "promise - error (Syntax Error)", function() {
		stop();
		expect( 3 );
		var oldOnError = window.onerror;
		window.onerror = function() {
			ok( true, "Syntax Error Thrown" );
			return false;
		};
		$.jsonp({
			url: "data/syntax-error.js",
			cache: true,
			error: function() {
				ok( true, "Error (options)" );
			},
			complete: function() {
				window.onerror = oldOnError;
				start();
			}
		}).done(function() {
			ok( false, "Success" );
		}).fail(function() {
			ok( true, "Error" );
		});
	});

	test( "promise - error (callback not called)", function() {
		stop();
		expect( 3 );
		$.jsonp({
			url: "data/no-callback.js",
			cache: true,
			error: function() {
				ok( true, "Error (options)" );
			},
			complete: function() {
				strictEqual( window.bob, 33, "script was executed" );
				window.bob = false;
				start();
			}
		}).done(function() {
			ok( false, "Success" );
		}).fail(function() {
			ok( true, "Error" );
		});
	});

}

test( "stress test", function() {

	var num = 20,
		count = num;

	expect( num );
	stop();

	for ( ; num ; num-- ) {
		$.jsonp({
			url: "http://gdata.youtube.com/feeds/api/users/julianaubourg?callback=?",
			success: function() {
				ok( true, "success" );
			},
			error: function() {
				ok( false, "error" );
			},
			complete: function() {
				if ( !( --count ) ) {
					start();
				}
			}
		});
	}
});
<commit_msg>There are two things I like dry: my code and my clothes. I'm a bald dev, that's why.<commit_after>module( "main", { teardown: moduleTeardown } );

var hasDeferred = $.Deferred ? 1 : 0;

function testJSONP( name, outcome, options ) {
	test( name, function() {
		stop();
		expect( ( options.expect || 0 ) + 1 + hasDeferred );
		var xOptions = $.jsonp( $.extend( {}, options, {
			success: function() {
				ok( outcome === "success", "Success" );
			},
			error: function() {
				ok( outcome === "error", "Error" );
			},
			complete: function() {
				if ( options.complete ) {
					options.complete.call( this );
				}
				start();
			}
		}) );
		if ( hasDeferred ) {
			xOptions.done(function() {
				ok( outcome === "success", "Done" );
			}).fail(function() {
				ok( outcome === "error", "Fail" );
			});
		}
	});
}

testJSONP( "success", "success", {
	url: "http://gdata.youtube.com/feeds/api/users/julianaubourg?callback=?",
	data: {
		alt: "json-in-script"
	}
});

testJSONP( "error (HTTP Code)", "error", {
	url: "http://gdata.youtube.com/feeds/api/users/hgfusyggbvbdbrfvurgbirhtiytjrhjsrhk66?callback=?",
	data: {
		alt: "json-in-script"
	}
});

testJSONP( "error (Syntax Error)", "error", {
	expect: 1,
	url: "data/syntax-error.js",
	cache: true,
	beforeSend: function() {
		this.oldOnError = window.onerror;
		window.onerror = function() {
			ok( true, "Syntax Error Thrown" );
		};
	},
	complete: function() {
		window.onerror = this.oldOnError;
	}
});

testJSONP( "error (callback not called)", "error", {
	expect: 1,
	url: "data/no-callback.js",
	cache: true,
	complete: function() {
		strictEqual( window.bob, 33, "script was executed" );
		window.bob = false;
	}
});

test( "stress test", function() {

	var num = 20,
		count = num;

	expect( num );
	stop();

	for ( ; num ; num-- ) {
		$.jsonp({
			url: "http://gdata.youtube.com/feeds/api/users/julianaubourg?callback=?",
			success: function() {
				ok( true, "success" );
			},
			error: function() {
				ok( false, "error" );
			},
			complete: function() {
				if ( !( --count ) ) {
					start();
				}
			}
		});
	}
});
<|endoftext|>


<commit_before>import test from 'ava';
import Keyv from '../';

test('Keyv is a function', t => {
	t.is(typeof Keyv, 'function');
});

test('Keyv cannot be invoked without \'new\'', t => {
	t.throws(() => Keyv()); // eslint-disable-line new-cap
	t.notThrows(() => new Keyv());
});

test('Keyv is an instance of Keyv', t => {
	t.true(new Keyv() instanceof Keyv);
});

test('.set(key, value) returns a Promise', t => {
	const store = new Keyv();
	t.true(store.set('foo', 'bar') instanceof Promise);
});

test('.set(key, value) resolves to value', async t => {
	const store = new Keyv();
	t.is(await store.set('foo', 'bar'), 'bar');
});
<commit_msg>Test .get(key) returns a Promise<commit_after>import test from 'ava';
import Keyv from '../';

test('Keyv is a function', t => {
	t.is(typeof Keyv, 'function');
});

test('Keyv cannot be invoked without \'new\'', t => {
	t.throws(() => Keyv()); // eslint-disable-line new-cap
	t.notThrows(() => new Keyv());
});

test('Keyv is an instance of Keyv', t => {
	t.true(new Keyv() instanceof Keyv);
});

test('.set(key, value) returns a Promise', t => {
	const store = new Keyv();
	t.true(store.set('foo', 'bar') instanceof Promise);
});

test('.set(key, value) resolves to value', async t => {
	const store = new Keyv();
	t.is(await store.set('foo', 'bar'), 'bar');
});

test('.get(key) returns a Promise', t => {
	const store = new Keyv();
	t.true(store.get('foo') instanceof Promise);
});
<|endoftext|>


<commit_before>var Set = require('../compare')
var tape = require('tape')
var u = require('../util')
var through = require('through')
var delay = require('delay-stream')

function clone () {
  return through(function (data) {
    return this.queue(JSON.parse(JSON.stringify(data)))
  })
}

//transform an array of keys into a object [key] = true
function toKeys (a) {
  var o = {}
  a.forEach(function (k) {
    o[k] = true
  })
  return o
}

function union (a, b) {
  a = toKeys(a); b = toKeys(b)
  var o = {}
  for(var k in a) {
    if (a[k] && b[k])
      o[k] = true
  }
  return Object.keys(o).sort()
}

//get keys in a that are not in b
function missing (a, b) {
  a = toKeys(a.sort()); b = toKeys(b.sort())
  var o = {}
  for(var k in a) {
    if (a[k] && !b[k])
      o[k] = true
  }
  return Object.keys(o).sort()
}

var DEBUG = process.env.DEBUG

var log = DEBUG ? console.log : function() {}

module.exports = function sets (o, n, m, sync) {
  return function (t) {
    var s = Set()
    var z = Set()
    for(var i = 0; i < o; i++)
      s.add(i), z.add(i)
    for(var i = 0; i < n; i++)
      s.add(o + (2 * i))
    for(var i = 0; i < m; i++)
      z.add(o + (2 * i) + 1)

    log(s.set, z.set)

    t.deepEqual(Object.keys(s.set).sort(), s.tree.leaves().sort())
    t.deepEqual(Object.keys(z.set).sort(), z.tree.leaves().sort())

    var missing_z = missing(s.tree.leaves().sort(), z.tree.leaves().sort())
    var missing_s = missing(z.tree.leaves().sort(), s.tree.leaves().sort())

    t.equal(missing_z.length, n)
    t.equal(missing_s.length, m)

    log('in s missing from z', missing_z)
    log('in z missing from s', missing_s)

    log('********************************', s.tree.leaves().length, z.tree.leaves().length)
    log(JSON.stringify(s.tree.toJSON(), null, 2))
    log(JSON.stringify(z.tree.toJSON(), null, 2))
    log('********************************')

    var ss = s.createStream()
    var zs = z.createStream()
    var us = false, uz = false, N = 2, sm = 0, zm = 0, sl = 0, zl = 0

    ss.on('union', function () {
    //  console.log('S UNION!')
      if(us) throw new Error('S, only union once')
      us = true
      next()
    })
    zs.on('union', function () {
  //    console.log('Z UNION!')
      if(uz) throw new Error('Z, only union once')
      uz = true
      next()
    })

    ss.on('data', log.bind(console, 'S>'))
    zs.on('data', log.bind(console, 'Z>'))
    ss.on('data', function (h) {
      sm ++; sl += JSON.stringify(h).length + 1
    })
    zs.on('data', function (h) {
      zm ++; zl += JSON.stringify(h).length + 1
    })

    ss
      .pipe(clone())
//      .pipe(delay(100))
      .pipe(zs)
      .pipe(clone())
  //    .pipe(delay(100))
      .pipe(ss)

    zs.resume()
    ss.resume()

    function check () {

      t.deepEqual(s.missing.sort(), missing_z)
      t.deepEqual(z.missing.sort(), missing_s)

      t.equal(s.expect, s.response)
      t.equal(z.expect, z.response)

      console.log('S maybe/expect', ss.maybe, ss.expect, ss.response)
      console.log('Z maybe/expect', zs.maybe, zs.expect, zs.response)
      console.log('Messages (s/z)', sm, zm)
      console.log('kilobytes(s/z)', sl/1000, zl/1000)
      console.log('small    (s/z)', ss.small, zs.small)
      console.log('Nodes    (s/z)', s.tree.count, z.tree.count)
      console.log('MISSING? (s/z)', missing_z.length, missing_s.length)
      console.log('Z maybe/expect', zs.maybe, zs.expect, zs.response)

  //      console.log(ss.maybes.map(function (e) {
  //        return e.digest()
  //      }), zs.otherMaybes)
  //      console.log(zs.maybes.map(function (e) {
  //        return e.digest()
  //      }), ss.otherMaybes)

  //    t.equal(ss.expect, 0, 'Union S')
  //    t.equal(zs.expect, 0, 'Union Z')

        console.log('********************')
        t.end()

    }

    if(sync) check()

    function next(){
      if(sync) return
      if(N < 0)
        throw new Error('too many unions')
      if(--N) return
      console.log('UNION')
      check()
    }
  }
}

<commit_msg>fix mode<commit_after>var Set = require('../compare')
var tape = require('tape')
var u = require('../util')
var through = require('through')
var delay = require('delay-stream')

function clone () {
  return through(function (data) {
    return this.queue(JSON.parse(JSON.stringify(data)))
  })
}

//transform an array of keys into a object [key] = true
function toKeys (a) {
  var o = {}
  a.forEach(function (k) {
    o[k] = true
  })
  return o
}

function union (a, b) {
  a = toKeys(a); b = toKeys(b)
  var o = {}
  for(var k in a) {
    if (a[k] && b[k])
      o[k] = true
  }
  return Object.keys(o).sort()
}

//get keys in a that are not in b
function missing (a, b) {
  a = toKeys(a.sort()); b = toKeys(b.sort())
  var o = {}
  for(var k in a) {
    if (a[k] && !b[k])
      o[k] = true
  }
  return Object.keys(o).sort()
}

var DEBUG = process.env.DEBUG

var log = DEBUG ? console.log : function() {}

module.exports = function sets (o, n, m, sync) {
  return function (t) {
    var s = Set()
    var z = Set()
    for(var i = 0; i < o; i++)
      s.add(i), z.add(i)
    for(var i = 0; i < n; i++)
      s.add(o + (2 * i))
    for(var i = 0; i < m; i++)
      z.add(o + (2 * i) + 1)

    log(s.set, z.set)

    t.deepEqual(Object.keys(s.set).sort(), s.tree.leaves().sort())
    t.deepEqual(Object.keys(z.set).sort(), z.tree.leaves().sort())

    var missing_z = missing(s.tree.leaves().sort(), z.tree.leaves().sort())
    var missing_s = missing(z.tree.leaves().sort(), s.tree.leaves().sort())

    t.equal(missing_z.length, n)
    t.equal(missing_s.length, m)

    log('in s missing from z', missing_z)
    log('in z missing from s', missing_s)

    log('********************************', s.tree.leaves().length, z.tree.leaves().length)
    log(JSON.stringify(s.tree.toJSON(), null, 2))
    log(JSON.stringify(z.tree.toJSON(), null, 2))
    log('********************************')

    var ss = s.createStream()
    var zs = z.createStream()
    var us = false, uz = false, N = 2, sm = 0, zm = 0, sl = 0, zl = 0

    ss.on('union', function () {
    //  console.log('S UNION!')
      if(us) throw new Error('S, only union once')
      us = true
      next()
    })
    zs.on('union', function () {
  //    console.log('Z UNION!')
      if(uz) throw new Error('Z, only union once')
      uz = true
      next()
    })

    ss.on('data', log.bind(console, 'S>'))
    zs.on('data', log.bind(console, 'Z>'))
    ss.on('data', function (h) {
      sm ++; sl += JSON.stringify(h).length + 1
    })
    zs.on('data', function (h) {
      zm ++; zl += JSON.stringify(h).length + 1
    })

    ss
      .pipe(clone())
//      .pipe(delay(100))
      .pipe(zs)
      .pipe(clone())
  //    .pipe(delay(100))
      .pipe(ss)

    zs.resume()
    ss.resume()

    function check () {

      t.deepEqual(s.missing.sort(), missing_z)
      t.deepEqual(z.missing.sort(), missing_s)

      t.equal(s.expect, s.response)
      t.equal(z.expect, z.response)

      console.log('S maybe/expect', ss.maybe, ss.expect, ss.response)
      console.log('Z maybe/expect', zs.maybe, zs.expect, zs.response)
      console.log('Messages (s/z)', sm, zm)
      console.log('kilobytes(s/z)', sl/1000, zl/1000)
      console.log('small    (s/z)', ss.small, zs.small)
      console.log('Nodes    (s/z)', s.tree.count, z.tree.count)
      console.log('MISSING? (s/z)', missing_z.length, missing_s.length)
      console.log('Z maybe/expect', zs.maybe, zs.expect, zs.response)

  //      console.log(ss.maybes.map(function (e) {
  //        return e.digest()
  //      }), zs.otherMaybes)
  //      console.log(zs.maybes.map(function (e) {
  //        return e.digest()
  //      }), ss.otherMaybes)

  //    t.equal(ss.expect, 0, 'Union S')
  //    t.equal(zs.expect, 0, 'Union Z')

        console.log('********************')
        t.end()

    }

    if(sync) check()

    function next(){
      if(sync) return
      if(N < 0)
        throw new Error('too many unions')
      if(--N) return
      console.log('UNION')
      check()
    }
  }
}

<|endoftext|>


<commit_before>const expect = require('chai').expect
const urls = require('../lib/urls')
const baseurl = urls._baseurl

describe('urls', function() {
    it('urls.index()', function() {
        expect(urls.index()).to.equal(baseurl)
    })

    it('urls.user.detail(uname)', function() {
        expect(urls.user.detail('test')).to
            .equal(baseurl + '/people/test/about')
    })

    it('urls.user.profile(uname)', function() {
        expect(urls.user.profile('test')).to
            .equal(baseurl + '/node/MemberProfileCardV2?params=%7B%22url_token%22%3A%22test%22%7D')
    })

    it('urls.user.followers()', function() {
        expect(urls.user.followers()).to
            .equal(baseurl + '/node/ProfileFollowersListV2')
    })

    it('urls.user.followees()', function() {
        expect(urls.user.followees()).to
            .equal(baseurl + '/node/ProfileFolloweesListV2')
    })

    it('urls.user.answers(uname, page)', function() {
        expect(urls.user.answers('test', 1)).to
            .equal(baseurl + '/people/test/answers?page=1')
    })

    it('urls.question.latest()', function() {
        expect(urls.question.latest()).to
            .equal(baseurl + '/log/questions')
    })

    it('urls.question.answersByVote()', function() {
        expect(urls.question.answersByVote()).to
            .equal(baseurl + '/node/QuestionAnswerListV2')
    })

    it('urls.question.answersByPage(questionId, page)', function() {
        expect(urls.question.answersByPage(41325553)).to
            .equal(baseurl + '/question/41325553?sort=created&page=1')

        expect(urls.question.answersByPage(41325553, 2)).to
            .equal(baseurl + '/question/41325553?sort=created&page=2')
    })

    it('urls.action.follow()', function() {
        expect(urls.action.follow()).to
            .equal(baseurl + '/node/MemberFollowBaseV2')
    })

    it('urls.action.unfollow()', function() {
        expect(urls.action.unfollow()).to
            .equal(baseurl + '/node/MemberFollowBaseV2')
    })
})
<commit_msg>add test cases<commit_after>const expect = require('chai').expect
const urls = require('../lib/urls')
const baseurl = urls._baseurl

describe('urls', function() {
    it('urls.index()', function() {
        expect(urls.index()).to.equal(baseurl)
    })

    it('urls.user.detail(uname)', function() {
        expect(urls.user.detail('test')).to
            .equal(baseurl + '/people/test/about')
    })

    it('urls.user.profile(uname)', function() {
        expect(urls.user.profile('test')).to
            .equal(baseurl + '/node/MemberProfileCardV2?params=%7B%22url_token%22%3A%22test%22%7D')
    })

    it('urls.user.followers()', function() {
        expect(urls.user.followers()).to
            .equal(baseurl + '/node/ProfileFollowersListV2')
    })

    it('urls.user.followees()', function() {
        expect(urls.user.followees()).to
            .equal(baseurl + '/node/ProfileFolloweesListV2')
    })

    it('urls.user.answers(uname, page)', function() {
        expect(urls.user.answers('test', 1)).to
            .equal(baseurl + '/people/test/answers?page=1')
    })

    it('urls.user.collections(uname, page)', function() {
        expect(urls.user.collections('test')).to
            .equal(baseurl + '/people/test/collections?page=1')
    })

    it('urls.user.columns(uname)', function() {
        expect(urls.user.columns('test')).to
            .equal(baseurl + '/people/test/posts')
    })

    it('urls.question.latest()', function() {
        expect(urls.question.latest()).to
            .equal(baseurl + '/log/questions')
    })

    it('urls.question.answersByVote()', function() {
        expect(urls.question.answersByVote()).to
            .equal(baseurl + '/node/QuestionAnswerListV2')
    })

    it('urls.question.answersByPage(questionId, page)', function() {
        expect(urls.question.answersByPage(41325553)).to
            .equal(baseurl + '/question/41325553?sort=created&page=1')

        expect(urls.question.answersByPage(41325553, 2)).to
            .equal(baseurl + '/question/41325553?sort=created&page=2')
    })

    it('urls.action.follow()', function() {
        expect(urls.action.follow()).to
            .equal(baseurl + '/node/MemberFollowBaseV2')
    })

    it('urls.action.unfollow()', function() {
        expect(urls.action.unfollow()).to
            .equal(baseurl + '/node/MemberFollowBaseV2')
    })
})
<|endoftext|>


<commit_before>'use strict';

var should = require('chai').should();
var Promise = require('bluebird');
var fs = require('hexo-fs');
var pathFn = require('path');
var util = require('../lib/util');

describe('util', function() {
	var Hexo = require('hexo');
	var baseDir = pathFn.join(__dirname, 'data_test');
	var hexo = new Hexo(baseDir);
	var processor = require('../node_modules/hexo/lib/plugins/processor/data');
	var process = Promise.method(processor.process).bind(hexo);
	var source = hexo.source;
	var File = source.File;
	var Data = hexo.model('Data');

	function newFile(options) {
		var path = options.path;
		options.params = {
			path: path
		};
		options.path = '_data/' + path;
		options.source = pathFn.join(source.base, options.path);
		return new File(options);
	}

	before(function() {
		hexo.locals.data = {};
	})

	before(function() {
		return fs.mkdirs(baseDir).then(function() {
			return hexo.init();
		});
	});

	after(function() {
		return fs.rmdir(baseDir);
	});

	it('config: simple - english - yaml', function() {
		var file = newFile({
			path: 'config_en.yml',
			type: 'create',
			content: new Buffer('description: English description')
		});
		return process(file).then(function() {
			hexo.locals.data.config_en = Data.findById('config_en').data;
			util._c('description', 'en', hexo.config, hexo.locals).should.eql('English description');
			return Data.findById('config_en').remove();
		});
	});

	it('config: simple - español - yaml', function() {
		var file = newFile({
			path: 'config_es.yml',
			type: 'create',
			content: new Buffer('description: Descripción en español')
		});
		return process(file).then(function() {
			hexo.locals.data.config_es = Data.findById('config_es').data;
			util._c('description', 'es', hexo.config, hexo.locals).should.eql('Descripción en español');
			return Data.findById('config_es').remove();
		});
	});
});
<commit_msg>Fix use of locals in tests<commit_after>'use strict';

var should = require('chai').should();
var Promise = require('bluebird');
var fs = require('hexo-fs');
var pathFn = require('path');
var util = require('../lib/util');

describe('util', function() {
	var Hexo = require('hexo');
	var baseDir = pathFn.join(__dirname, 'data_test');
	var hexo = new Hexo(baseDir);
	var processor = require('../node_modules/hexo/lib/plugins/processor/data');
	var process = Promise.method(processor.process).bind(hexo);
	var source = hexo.source;
	var File = source.File;
	var Data = hexo.model('Data');

	function newFile(options) {
		var path = options.path;
		options.params = {
			path: path
		};
		options.path = '_data/' + path;
		options.source = pathFn.join(source.base, options.path);
		return new File(options);
	}

	before(function() {
		return fs.mkdirs(baseDir).then(function() {
			hexo.init();
			process(newFile({
				path: 'config_en.yml',
				type: 'create',
				content: new Buffer('description: English description')
			}));
			process(newFile({
				path: 'config_es.yml',
				type: 'create',
				content: new Buffer('description: Descripción en español')
			}));
		});
	});

	after(function() {
		return fs.rmdir(baseDir);
	});

	it('config: simple - english - yaml', function() {
		util._c('description', 'en', hexo.config, hexo.locals.toObject()).should.eql('English description');
	});

	it('config: simple - español - yaml', function() {
		util._c('description', 'es', hexo.config, hexo.locals.toObject()).should.eql('Descripción en español');
	});
});
<|endoftext|>


<commit_before>$( document ).ready(function() {

  $.ajax({
    url: "http://snstrfreedom.tumblr.com/api/read/xml?num=10&&type=text",
    dataType: 'jsonp'
  }).done(function(data) {
    let posts = data.posts,
    blogsHtml = `

                  RSS Feed

`;
    for(let x in posts){
      blogsHtml +=
        `

${posts[x]["regular-title"]} ${posts[x]["date"]}

            ${posts[x]["regular-body"]}

`;
    }
    blogsHtml += `

        For more see the archives ...

`
    $('#blogDiv').html(blogsHtml)
    // blogDiv
    console.log(data)
  });

});
<commit_msg>updated url<commit_after>$( document ).ready(function() {

  $.ajax({
    url: "https://paulcaronnews.tumblr.com/api/read/xml?num=10&&type=text",
    dataType: 'jsonp'
  }).done(function(data) {
    let posts = data.posts,
    blogsHtml = `

                  RSS Feed

`;
    for(let x in posts){
      blogsHtml +=
        `

${posts[x]["regular-title"]} ${posts[x]["date"]}

            ${posts[x]["regular-body"]}

`;
    }
    blogsHtml += `

        For more see the archives ...

`
    $('#blogDiv').html(blogsHtml)
    // blogDiv
    console.log(data)
  });

});
<|endoftext|>


<commit_before>var github = {};
github.url = "https://api.github.com";

github.user = function(user, token) {
    this.username = user;
    this.token = token;
    return this;
};

github.api_token = function() {
    if (this.token) {
        return "?api_token=" + this.token;
    }
    return "";
}

github.getRepos = function(callback) {
    var url = this.url + '/users/' + this.username + '/repos' + this.api_token();
    $.ajax(url, {
        success: function(reply) {
            addon.port.emit('log', 'success');
            callback(reply);
        },
        error: function(jqXHR, error, errorThrown) {
            addon.port.emit('log', JSON.stringify(jqXHR));
            addon.port.emit('log', error);
            addon.port.emit('log', errorThrown);

        }
    });
};
<commit_msg>makes github.js work outside of being an addon<commit_after>var github = {};
github.log = function(message) {
    if (typeof(addon) === "undefined") {
        console.log(message);
    } else {
        addon.port.emit('log', message);
    }
}

github.url = "https://api.github.com";

github.user = function(user, token) {
    this.username = user;
    this.token = token;
    return this;
};

github.api_token = function() {
    if (this.token) {
        return "?api_token=" + this.token;
    }
    return "";
}

github.getRepos = function(callback) {
    var url = this.url + '/users/' + this.username + '/repos' + this.api_token();
    $.ajax(url, {
        success: function(reply) {
            github.log('success');
            callback(reply);
        },
        error: function(jqXHR, error, errorThrown) {
            github.log(JSON.stringify(jqXHR));
            github.log(error);
            github.log(errorThrown);

        }
    });
};
<|endoftext|>


<commit_before>
/**
 * Module dependencies
 */

var WPCOM = require('../');

try {
  var config = require('./config');
} catch (ex) {
  var config = {};
}

/**
 * Detect client/server side
 */

var is_client_side = 'undefined' !== typeof window;

/**
 * Config vars
 */

var token = process.env.TOKEN || config.token;
var site = process.env.SITE || config.site;

/**
 * Testing data
 */

var fixture = require('./fixture');

module.exports = {
  wpcom: wpcom,
  wpcom_public: function() { return WPCOM(); },
  site: function () { return config.site; }
};

function wpcom() {
  if (is_client_side) {
    var proxy = require('../node_modules/wpcom-proxy-request');
    var _wpcom = WPCOM(proxy);

    _wpcom.request({
      metaAPI: { accessAllUsersBlogs: true }
    }, function(err) {
      if (err) throw err;
      console.log('proxy now running in "access all user\'s blogs" mode');
    });

    return _wpcom;
  } else {
    return WPCOM(token);
  }
}
<commit_msg>test: fix util.site() method<commit_after>
/**
 * Module dependencies
 */

var WPCOM = require('../');

try {
  var config = require('./config');
} catch (ex) {
  var config = {};
}

/**
 * Detect client/server side
 */

var is_client_side = 'undefined' !== typeof window;

/**
 * Config vars
 */

var token = process.env.TOKEN || config.token;
var site = process.env.SITE || config.site;

/**
 * Testing data
 */

var fixture = require('./fixture');

module.exports = {
  wpcom: wpcom,
  wpcom_public: function() { return WPCOM(); },
  site: function () { return site; }
};

function wpcom() {
  if (is_client_side) {
    var proxy = require('../node_modules/wpcom-proxy-request');
    var _wpcom = WPCOM(proxy);

    _wpcom.request({
      metaAPI: { accessAllUsersBlogs: true }
    }, function(err) {
      if (err) throw err;
      console.log('proxy now running in "access all user\'s blogs" mode');
    });

    return _wpcom;
  } else {
    return WPCOM(token);
  }
}
<|endoftext|>


<commit_before>(function($) {
  bootTaskViews = function() {
    $( ".js-display-list" ).click(function(e) {
      e.preventDefault();
      $(this).parent().find(".js-view-package-list").toggle();
    });

     $(".list-group-item").each(function(){
      $(this).click(function(event){
        event.preventDefault();
        getView($(this).html());
        $(".highlight").removeClass("highlight");
        $(this).addClass("highlight");
        hideSlider();
      });
    });
    if($(".view")[0]){
      if(window.location.hash) {
        console.log("location "+window.location.hash.slice(1))
        getView(window.location.hash.slice(1));
      } else {
        var v = $('.list-group .list-group-item:first-child').text();
        console.log("v "+v)
        getView(v);
      }
    }
    window.makeSideBar();
    hideSlider();
    var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
    $('.list-group').css('height',h-80)
  };

  window.makeSideBar = function(){
    $(".sidebar-slider-icon").click(function(){
      var slider = $(".sidebar-slider-icon");
      if(slider.hasClass("fa-angle-right")){
        slideRight(slider);
      }else{
        slideLeft(slider);
      }
    });
  };

  slideLeft = function(slider){
    slider.removeClass("fa-angle-left");
    slider.addClass("fa-angle-right");
    $(".sliding-sidebar").animate({width:'toggle'},350,function(){
      $(".view").css("width","100%");
      $(".view").css("margin-left","20px");
      $(".footer--credits--title ").css("width","100%");
    $(".footer--credits--title ").css("margin-left","0px");
    });
  }

  slideRight = function(slider){
    slider.removeClass("fa-angle-right");
    slider.addClass("fa-angle-left")
    $(".view").css("width","calc(100% - 21em)");
    $(".view").css("margin-left","280px");
    $(".footer--credits--title ").css("width","calc(100% - 21em)");
    $(".footer--credits--title ").css("margin-left","280px");
    $(".sliding-sidebar").animate({width:'toggle'},350);
  }

  hideSlider = function(){
    if($(".view").width()<600){
      var slider = $(".sidebar-slider-icon");
      slideLeft(slider);
    }
  }

  window.getView = function(view){
    if(!(urlParam('viewer_pane')==='1')) location.hash = view;
    console.log("here "+location)
    $.ajax({
    	url: "/taskviews/"+view,
      cache: false
    }).done(function(response){
    	$(".view").html(response);
    	window.bindFilter();
      percentileTaskView();
      $(document).trigger('content-changed');
    });
  };

  window.sortTable = function(){
    $("table.taskviewtable").tablesorter({
            headers: {
              3: {
                  sorter:'rating'
              }
          },
          textExtraction: function (node){
            if($(node).find(".rating").length>0){
              return ($(node).find(".rating").data('rating'));
            }else if($(node).find(".percentile-task".length>0)){
              return $(node).find(".percentile-task").data('percentile');
            }
            return $(node).text();
          },
          sortList: [[2,1]]
      });
  };

  window.percentileTaskView = function(){
    requests =[];
    $('.taskviewtable .percentile-task').each(function(elem) {
      var $self = $(this);
      var url = $self.data('url');
      requests.push($.get(url, function(data){
        if(data.percentile !== null){
          $self.find(".percentile").text(''+ data.percentile + 'th');
          $self.data("percentile", data.percentile);
          $self.css({'visibility': 'visible'});
        } else{
          $self.css({'visibility': 'hidden'});
        }
      }));
    });

    $.when.apply(undefined,requests).then(function(){
      window.triggerIcon();
      sortTable();
    });
  };

})($jq);

<commit_msg>removed debug log<commit_after>(function($) {
  bootTaskViews = function() {
    $( ".js-display-list" ).click(function(e) {
      e.preventDefault();
      $(this).parent().find(".js-view-package-list").toggle();
    });

     $(".list-group-item").each(function(){
      $(this).click(function(event){
        event.preventDefault();
        getView($(this).html());
        $(".highlight").removeClass("highlight");
        $(this).addClass("highlight");
        hideSlider();
      });
    });
    if($(".view")[0]){
      if(window.location.hash) {
        getView(window.location.hash.slice(1));
      } else {
        var v = $('.list-group .list-group-item:first-child').text();
        getView(v);
      }
    }
    window.makeSideBar();
    hideSlider();
    var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
    $('.list-group').css('height',h-80)
  };

  window.makeSideBar = function(){
    $(".sidebar-slider-icon").click(function(){
      var slider = $(".sidebar-slider-icon");
      if(slider.hasClass("fa-angle-right")){
        slideRight(slider);
      }else{
        slideLeft(slider);
      }
    });
  };

  slideLeft = function(slider){
    slider.removeClass("fa-angle-left");
    slider.addClass("fa-angle-right");
    $(".sliding-sidebar").animate({width:'toggle'},350,function(){
      $(".view").css("width","100%");
      $(".view").css("margin-left","20px");
      $(".footer--credits--title ").css("width","100%");
    $(".footer--credits--title ").css("margin-left","0px");
    });
  }

  slideRight = function(slider){
    slider.removeClass("fa-angle-right");
    slider.addClass("fa-angle-left")
    $(".view").css("width","calc(100% - 21em)");
    $(".view").css("margin-left","280px");
    $(".footer--credits--title ").css("width","calc(100% - 21em)");
    $(".footer--credits--title ").css("margin-left","280px");
    $(".sliding-sidebar").animate({width:'toggle'},350);
  }

  hideSlider = function(){
    if($(".view").width()<600){
      var slider = $(".sidebar-slider-icon");
      slideLeft(slider);
    }
  }

  window.getView = function(view){
    if(!(urlParam('viewer_pane')==='1')) location.hash = view;
    $.ajax({
    	url: "/taskviews/"+view,
      cache: false
    }).done(function(response){
    	$(".view").html(response);
    	window.bindFilter();
      percentileTaskView();
      $(document).trigger('content-changed');
    });
  };

  window.sortTable = function(){
    $("table.taskviewtable").tablesorter({
            headers: {
              3: {
                  sorter:'rating'
              }
          },
          textExtraction: function (node){
            if($(node).find(".rating").length>0){
              return ($(node).find(".rating").data('rating'));
            }else if($(node).find(".percentile-task".length>0)){
              return $(node).find(".percentile-task").data('percentile');
            }
            return $(node).text();
          },
          sortList: [[2,1]]
      });
  };

  window.percentileTaskView = function(){
    requests =[];
    $('.taskviewtable .percentile-task').each(function(elem) {
      var $self = $(this);
      var url = $self.data('url');
      requests.push($.get(url, function(data){
        if(data.percentile !== null){
          $self.find(".percentile").text(''+ data.percentile + 'th');
          $self.data("percentile", data.percentile);
          $self.css({'visibility': 'visible'});
        } else{
          $self.css({'visibility': 'hidden'});
        }
      }));
    });

    $.when.apply(undefined,requests).then(function(){
      window.triggerIcon();
      sortTable();
    });
  };

})($jq);

<|endoftext|>


<commit_before>/* global describe it beforeEach */
'use strict'

const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const requireInject = require('require-inject')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')

chai.use(chaiAsPromised)
chai.use(sinonChai)

const expect = chai.expect

describe('exec', function () {
  let exec
  let stubs

  function requireModule () {
    return requireInject('../lib/util', stubs)
  }

  beforeEach(function () {
    exec = sinon.stub()
    stubs = {
      child_process: {
        exec
      }
    }
  })

  it('rejects if childProcess.exec fails', function () {
    exec.yields('some error')
    const util = requireModule()
    return expect(util.exec('command'))
      .to.be.eventually.rejectedWith('some error')
  })

  it('resolves if childProcess.exec succeeds', function () {
    exec.yields(null, 'stdout', 'stderr')
    const util = requireModule()
    return expect(util.exec('command')).to.eventually.deep.equal({
      command: 'command',
      stdout: 'stdout',
      stderr: 'stderr'
    })
  })
})

describe('exists', function () {
  let exists
  let stubs

  function requireModule () {
    return requireInject('../lib/util', stubs)
  }

  beforeEach(function () {
    exists = sinon.stub()
    stubs = {
      fs: {
        exists
      }
    }
  })

  it('rejects if fs.exists returns false', function () {
    exists.yields(false)
    const util = requireModule()
    return expect(util.exists('path')).to.be.eventually.rejected
  })

  it('resolves if fs.exists returns true', function () {
    exists.yields(true)
    const util = requireModule()
    return expect(util.exists('path')).to.be.eventually.fulfilled
  })
})
<commit_msg>Fix test cases<commit_after>/* global describe it beforeEach */
'use strict'

const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const requireInject = require('require-inject')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')

chai.use(chaiAsPromised)
chai.use(sinonChai)

const expect = chai.expect

describe('exec', function () {
  let exec
  let stubs

  function requireModule () {
    return requireInject('../lib/util', stubs)
  }

  beforeEach(function () {
    exec = sinon.stub()
    stubs = {
      child_process: {
        exec
      }
    }
  })

  it('rejects if childProcess.exec fails', function () {
    exec.yields('some error')
    const util = requireModule()
    return expect(util.exec('command'))
      .to.be.eventually.rejectedWith('some error')
  })

  it('resolves if childProcess.exec succeeds', function () {
    exec.yields(null, 'stdout', 'stderr')
    const util = requireModule()
    return expect(util.exec('command')).to.eventually.deep.equal({
      command: 'command',
      stdout: 'stdout',
      stderr: 'stderr'
    })
  })
})

describe('exists', function () {
  let exists
  let stubs

  function requireModule () {
    return requireInject('../lib/util', stubs)
  }

  beforeEach(function () {
    exists = sinon.stub()
    stubs = {
      fs: {
        exists,
        mkdir: sinon.stub(),
        readFile: sinon.stub()
      }
    }
  })

  it('rejects if fs.exists returns false', function () {
    exists.yields(false)
    const util = requireModule()
    return expect(util.exists('path')).to.be.eventually.rejected
  })

  it('resolves if fs.exists returns true', function () {
    exists.yields(true)
    const util = requireModule()
    return expect(util.exists('path')).to.be.eventually.fulfilled
  })
})
<|endoftext|>


<commit_before>/* global describe it */
'use strict'

const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const requireInject = require('require-inject')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
require('sinon-as-promised')

chai.use(chaiAsPromised)
chai.use(sinonChai)

const expect = chai.expect

describe('exec', function () {
  it('rejects if childProcess.exec fails', function () {
    const exec = sinon.stub().yields(['some error'])
    const stubs = {
      child_process: {
        exec
      }
    }
    const util = requireInject('../lib/util', stubs)
    return expect(util.exec()).to.be.eventually.rejectedWith('some error')
  })
})
<commit_msg>Yield string instead of array<commit_after>/* global describe it */
'use strict'

const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const requireInject = require('require-inject')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
require('sinon-as-promised')

chai.use(chaiAsPromised)
chai.use(sinonChai)

const expect = chai.expect

describe('exec', function () {
  it('rejects if childProcess.exec fails', function () {
    const exec = sinon.stub().yields('some error')
    const stubs = {
      child_process: {
        exec
      }
    }
    const util = requireInject('../lib/util', stubs)
    return expect(util.exec()).to.be.eventually.rejectedWith('some error')
  })
})
<|endoftext|>


<commit_before>(function() {

  // window.app must be created by now, since LocalDb must be imported before
  // this file.
  window.app.store = new window.app.LocalDb();

  // Create some default puzzles...
  if (window.app.store.getActivePuzzle() === null) {
    var addPuzzles = [7, 6, 5, 4, 2, 3];
    for (var i = 0, len = addPuzzles.length; i < len; ++i) {
      var x = addPuzzles[i];
      var puzzleName = x + 'x' + x + 'x' + x;
      var puzzle = {name: puzzleName, icon: '3x3x3', scrambler: '3x3x3',
        scrambleType: 'moves', scrambleLength: -1};
      window.app.store.addPuzzle(puzzle);
    }
  }

})();
<commit_msg>add default puzzles with their icons<commit_after>(function() {

  // window.app must be created by now, since LocalDb must be imported before
  // this file.
  window.app.store = new window.app.LocalDb();

  // Create some default puzzles...
  if (window.app.store.getActivePuzzle() === null) {
    var addPuzzles = [7, 6, 5, 4, 2, 3];
    for (var i = 0, len = addPuzzles.length; i < len; ++i) {
      var x = addPuzzles[i];
      var puzzleName = x + 'x' + x + 'x' + x;
      var puzzle = {name: puzzleName, icon: puzzleName, scrambler: '3x3x3',
        scrambleType: 'moves', scrambleLength: -1};
      window.app.store.addPuzzle(puzzle);
    }
  }

})();
<|endoftext|>


<commit_before>/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import { createGlobalStyle, ThemeContext } from 'styled-components';
import { useContext } from 'react';

/**
 * Internal dependencies
 */
import { DROPDOWN_TYPES } from './constants';

export const GlobalStyle = createGlobalStyle`
	*,
	*::after,
	*::before {
		box-sizing: border-box;
    }

  h1, h2, h3, h4, h5, h6, p, a {
    margin: 0;
  }
`;

export function useTheme() {
  return useContext(ThemeContext);
}

const themeFonts = {
  primary: "'Google Sans', sans-serif",
};

const colors = {
  gray900: '#1A1D1F',
  gray800: '#2C3033',
  gray700: '#3F454A',
  gray600: '#4F575F',
  gray500: '#606B74',
  gray400: '#6D7A85',
  gray300: '#848D96',
  gray200: '#9AA1A9',
  gray100: '#B8BCBF',
  gray75: '#D9DBDD',
  gray50: '#EEEEEE',
  // gray25: '#F7F7F7', gray25 is duplicated, it looks like F6F6 wins out in the docs, keeping this here for now for reference.
  gray25: '#F6F6F6',
  white: '#fff',
  bluePrimary: '#2979FF',
  bluePrimary600: '#1A73E8',
  blueLight: '#EAF2FF',
  // taken from edit-stories
  action: '#47A0F4',
  danger: '#FF0000',
  selection: '#44aaff',
  warning: '#FF9800',
  success: '#4CAF4F',
  // Updated design colors
  black: '#000',
  // todo
  placeholder: '#d9dbdd',
  storyPreviewBackground: '#202125',

  foreground: {
    gray24: '#A1A09B',
    gray16: '#D1D1CC',
    gray12: '#E8E8E8', // bonus shade added for side nav create story button
  },
};

const borders = {
  gray50: `1px solid ${colors.gray50}`,
  gray75: `1px solid ${colors.gray75}`,
  gray100: `1px solid ${colors.gray100}`,
  gray800: `1px solid ${colors.gray800}`,
  transparent: '1px solid transparent',
  bluePrimary: `1px solid ${colors.bluePrimary}`,
  action: `1px solid ${colors.action}`,
  danger: `1px solid ${colors.danger}`,
};

const theme = {
  colors,
  borders,
  button: {
    borderRadius: 100,
  },
  dropdown: {
    [DROPDOWN_TYPES.PANEL]: {
      background: 'transparent',
      activeBackground: colors.gray25,
      borderRadius: 40,
      border: borders.gray50,
      arrowColor: colors.bluePrimary,
    },
    [DROPDOWN_TYPES.COLOR_PANEL]: {
      background: 'transparent',
      activeBackground: colors.gray25,
      borderRadius: 40,
      border: borders.gray50,
      arrowColor: colors.bluePrimary,
    },
    [DROPDOWN_TYPES.MENU]: {
      background: 'transparent',
      activeBackground: 'transparent',
      borderRadius: 4,
      border: borders.transparent,
      arrowColor: colors.gray300,
    },
  },
  leftRail: {
    logoMargin: '75px auto 20px',
  },
  text: {
    shadow: '0px 1px 1px rgba(0, 0, 0, 1)',
  },
  chip: {
    shadow: '0px 1px 3px rgba(0, 0, 0, 0.2)',
  },
  typeahead: {
    borderRadius: 100,
  },
  formatContainer: {
    height: 44,
  },
  expandedTypeahead: {
    borderRadius: 8,
    boxShadow:
      '0px 0.181152px 2.29372px rgba(0, 0, 0, 0.031357), 0px 0.500862px 5.15978px rgba(0, 0, 0, 0.045),0px 1.20588px 8.99337px rgba(0, 0, 0, 0.058643), 0px 4px 17px rgba(0, 0, 0, 0.09)',
  },
  floatingTab: {
    shadow: '0px 2px 8px rgba(0, 0, 0, 0.17)',
  },
  storyPreview: {
    shadow: '1px 1px 5px hsla(0, 0%, 0%, 0.15)',
    borderRadius: 4,
  },
  tooltip: {
    background: colors.gray900,
    color: colors.white,
  },
  navBar: {
    height: 64,
  },
  subNavigationBar: {
    border: borders.gray50,
  },
  table: {
    headerCellPadding: 15,
    cellPadding: 15,
    headerContentSize: 20,
    border: borders.gray50,
  },
  cardItem: {
    previewOverlay:
      'linear-gradient(360deg, rgba(26, 29, 31, 0.8) 11.58%, rgba(26, 29, 31, 0) 124.43%)',
  },
  popoverPanel: {
    desktopWidth: 595,
    tabletWidth: 395,
  },
  typography: {
    family: { ...themeFonts },
    weight: {
      normal: '400',
      light: '300',
      bold: '500',
      bolder: '700',
    },
    presets: {
      xxl: {
        family: themeFonts.primary,
        size: 36,
        minSize: 18,
        lineHeight: 40,
        minLineHeight: 40,
        letterSpacing: -0.01,
        minLetterSpacing: -0.01,
      },
      xl: {
        family: themeFonts.primary,
        size: 28,
        lineHeight: 35,
        letterSpacing: -0.01,
      },
      l: {
        family: themeFonts.primary,
        size: 20,
        lineHeight: 28,
        letterSpacing: -0.01,
      },
      m: {
        family: themeFonts.primary,
        size: 16,
        lineHeight: 22,
        letterSpacing: 0.01,
        minSize: 12,
      },
      s: {
        family: themeFonts.primary,
        size: 14,
        lineHeight: 20,
        letterSpacing: 0.01,
      },
      xs: {
        family: themeFonts.primary,
        size: 12,
        minSize: 10,
        letterSpacing: 0.01,
      },
    },
  },
  detailViewContentGutter: {
    desktop: 80,
    tablet: 40,
    min: 10,
  },
  standardViewContentGutter: {
    desktop: 20,
    tablet: 20,
    largeDisplayPhone: 10,
    smallDisplayPhone: 10,
    min: 10,
  },
  grid: {
    columnGap: {
      desktop: 10,
      tablet: 10,
      largeDisplayPhone: 10,
      smallDisplayPhone: 10,
      min: 10,
    },
  },
  previewWidth: {
    desktop: 221,
    tablet: 189,
    largeDisplayPhone: 162,
    smallDisplayPhone: 185,
    min: 139,
    thumbnail: 33,
  },
  breakpoint: {
    desktop: 'screen and (max-width: 1280px)',
    tablet: 'screen and (max-width: 1120px)',
    largeDisplayPhone: 'screen and (max-width: 800px)',
    smallDisplayPhone: 'screen and (max-width: 684px)',
    min: 'screen and (max-width: 440px)',
    raw: {
      desktop: 1280,
      tablet: 1120,
      largeDisplayPhone: 800,
      smallDisplayPhone: 684,
      min: 440,
    },
  },
};

export default theme;
<commit_msg>gutter increase from 20px to 52px<commit_after>/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import { createGlobalStyle, ThemeContext } from 'styled-components';
import { useContext } from 'react';

/**
 * Internal dependencies
 */
import { DROPDOWN_TYPES } from './constants';

export const GlobalStyle = createGlobalStyle`
	*,
	*::after,
	*::before {
		box-sizing: border-box;
    }

  h1, h2, h3, h4, h5, h6, p, a {
    margin: 0;
  }
`;

export function useTheme() {
  return useContext(ThemeContext);
}

const themeFonts = {
  primary: "'Google Sans', sans-serif",
};

const colors = {
  gray900: '#1A1D1F',
  gray800: '#2C3033',
  gray700: '#3F454A',
  gray600: '#4F575F',
  gray500: '#606B74',
  gray400: '#6D7A85',
  gray300: '#848D96',
  gray200: '#9AA1A9',
  gray100: '#B8BCBF',
  gray75: '#D9DBDD',
  gray50: '#EEEEEE',
  // gray25: '#F7F7F7', gray25 is duplicated, it looks like F6F6 wins out in the docs, keeping this here for now for reference.
  gray25: '#F6F6F6',
  white: '#fff',
  bluePrimary: '#2979FF',
  bluePrimary600: '#1A73E8',
  blueLight: '#EAF2FF',
  // taken from edit-stories
  action: '#47A0F4',
  danger: '#FF0000',
  selection: '#44aaff',
  warning: '#FF9800',
  success: '#4CAF4F',
  // Updated design colors
  black: '#000',
  // todo
  placeholder: '#d9dbdd',
  storyPreviewBackground: '#202125',

  foreground: {
    gray24: '#A1A09B',
    gray16: '#D1D1CC',
    gray12: '#E8E8E8', // bonus shade added for side nav create story button
  },
};

const borders = {
  gray50: `1px solid ${colors.gray50}`,
  gray75: `1px solid ${colors.gray75}`,
  gray100: `1px solid ${colors.gray100}`,
  gray800: `1px solid ${colors.gray800}`,
  transparent: '1px solid transparent',
  bluePrimary: `1px solid ${colors.bluePrimary}`,
  action: `1px solid ${colors.action}`,
  danger: `1px solid ${colors.danger}`,
};

const theme = {
  colors,
  borders,
  button: {
    borderRadius: 100,
  },
  dropdown: {
    [DROPDOWN_TYPES.PANEL]: {
      background: 'transparent',
      activeBackground: colors.gray25,
      borderRadius: 40,
      border: borders.gray50,
      arrowColor: colors.bluePrimary,
    },
    [DROPDOWN_TYPES.COLOR_PANEL]: {
      background: 'transparent',
      activeBackground: colors.gray25,
      borderRadius: 40,
      border: borders.gray50,
      arrowColor: colors.bluePrimary,
    },
    [DROPDOWN_TYPES.MENU]: {
      background: 'transparent',
      activeBackground: 'transparent',
      borderRadius: 4,
      border: borders.transparent,
      arrowColor: colors.gray300,
    },
  },
  leftRail: {
    logoMargin: '75px auto 20px',
  },
  text: {
    shadow: '0px 1px 1px rgba(0, 0, 0, 1)',
  },
  chip: {
    shadow: '0px 1px 3px rgba(0, 0, 0, 0.2)',
  },
  typeahead: {
    borderRadius: 100,
  },
  formatContainer: {
    height: 44,
  },
  expandedTypeahead: {
    borderRadius: 8,
    boxShadow:
      '0px 0.181152px 2.29372px rgba(0, 0, 0, 0.031357), 0px 0.500862px 5.15978px rgba(0, 0, 0, 0.045),0px 1.20588px 8.99337px rgba(0, 0, 0, 0.058643), 0px 4px 17px rgba(0, 0, 0, 0.09)',
  },
  floatingTab: {
    shadow: '0px 2px 8px rgba(0, 0, 0, 0.17)',
  },
  storyPreview: {
    shadow: '1px 1px 5px hsla(0, 0%, 0%, 0.15)',
    borderRadius: 4,
  },
  tooltip: {
    background: colors.gray900,
    color: colors.white,
  },
  navBar: {
    height: 64,
  },
  subNavigationBar: {
    border: borders.gray50,
  },
  table: {
    headerCellPadding: 15,
    cellPadding: 15,
    headerContentSize: 20,
    border: borders.gray50,
  },
  cardItem: {
    previewOverlay:
      'linear-gradient(360deg, rgba(26, 29, 31, 0.8) 11.58%, rgba(26, 29, 31, 0) 124.43%)',
  },
  popoverPanel: {
    desktopWidth: 595,
    tabletWidth: 395,
  },
  typography: {
    family: { ...themeFonts },
    weight: {
      normal: '400',
      light: '300',
      bold: '500',
      bolder: '700',
    },
    presets: {
      xxl: {
        family: themeFonts.primary,
        size: 36,
        minSize: 18,
        lineHeight: 40,
        minLineHeight: 40,
        letterSpacing: -0.01,
        minLetterSpacing: -0.01,
      },
      xl: {
        family: themeFonts.primary,
        size: 28,
        lineHeight: 35,
        letterSpacing: -0.01,
      },
      l: {
        family: themeFonts.primary,
        size: 20,
        lineHeight: 28,
        letterSpacing: -0.01,
      },
      m: {
        family: themeFonts.primary,
        size: 16,
        lineHeight: 22,
        letterSpacing: 0.01,
        minSize: 12,
      },
      s: {
        family: themeFonts.primary,
        size: 14,
        lineHeight: 20,
        letterSpacing: 0.01,
      },
      xs: {
        family: themeFonts.primary,
        size: 12,
        minSize: 10,
        letterSpacing: 0.01,
      },
    },
  },
  detailViewContentGutter: {
    desktop: 80,
    tablet: 40,
    min: 10,
  },
  standardViewContentGutter: {
    desktop: 52,
    tablet: 52,
    largeDisplayPhone: 10,
    smallDisplayPhone: 10,
    min: 10,
  },
  grid: {
    columnGap: {
      desktop: 10,
      tablet: 10,
      largeDisplayPhone: 10,
      smallDisplayPhone: 10,
      min: 10,
    },
  },
  previewWidth: {
    desktop: 221,
    tablet: 189,
    largeDisplayPhone: 162,
    smallDisplayPhone: 185,
    min: 139,
    thumbnail: 33,
  },
  breakpoint: {
    desktop: 'screen and (max-width: 1280px)',
    tablet: 'screen and (max-width: 1120px)',
    largeDisplayPhone: 'screen and (max-width: 800px)',
    smallDisplayPhone: 'screen and (max-width: 684px)',
    min: 'screen and (max-width: 440px)',
    raw: {
      desktop: 1280,
      tablet: 1120,
      largeDisplayPhone: 800,
      smallDisplayPhone: 684,
      min: 440,
    },
  },
};

export default theme;
<|endoftext|>


<commit_before>function moveThings() {
    // video position is used as reference point
    // var vid = document.getElementById('video-frame');

    // desktop view involves moving around lots of things
    if(window.innerWidth > 960) {
        // var minimizeTrigger = document.getElementById('phoneme-explanation');
        // var videoLimitElement = document.getElementById('whats-next');
        // var videoLimit = findPosY(videoLimitElement) - 700;

        // // adjust top margin to TfCS header position (header stops being fixed at 1242px)
        // var marginTop;
        // if(window.innerWidth > 1242){
        //     marginTop = 125;
        // }else{
        //     marginTop = 75;
        // }

        // if(minimizeTriggerPosition<0)minimizeTriggerPosition=findPosY(minimizeTrigger);

        if(pageYOffset>window.minimizeTriggerPosition-300){
            jQuery('#video-navigation').addClass('minimized');
            jQuery('#video-frame').addClass('minimized');
            jQuery('#video').addClass('minimized');
            jQuery('.entry-content').addClass('shifted');
            window.vid.style.top=window.marginTop+'px';
            if(pageYOffset>window.videoLimit){
                window.vid.style.top=(window.marginTop-pageYOffset+window.videoLimit)+'px';
            }
        }else{
            jQuery('#video-navigation').removeClass('minimized');
            jQuery('#video-frame').removeClass('minimized');
            jQuery('#video').removeClass('minimized');
            jQuery('.entry-content').removeClass('shifted');
            window.vid.style.top=0;
        }
    }else{
        // mobile view is much simpler
        if(pageYOffset>window.exercisePosition && pageYOffset<window.phonemeGridPosition){
            jQuery('.video-navigation-mobile').addClass('minimized');
            jQuery('#video').addClass('minimized');
        }else{
            jQuery('.video-navigation-mobile').removeClass('minimized');
            jQuery('#video').removeClass('minimized');
        }

        // things need to be reset when window shrinks from desktop view to mobile view
        // jQuery('#video-navigation').removeClass('minimized');
        // jQuery('#video-frame').removeClass('minimized');
        // jQuery('#video').removeClass('minimized');
        // jQuery('.entry-content').removeClass('shifted');
        // vid.style.top=0;
    }
}

window.onscroll=function(){
    moveThings();
};

window.onresize=function(){
    moveThings();
};

function findPosY(obj) {
    var curtop = 0;
    if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
        curtop += obj.offsetTop;
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

/**
 * jQuery.browser.mobile (http://detectmobilebrowser.com/)
 *
 * jQuery.browser.mobile will be true if the browser is a mobile device
 *
 **/
(function(a){(jQuery.browser=jQuery.browser||{}).mobile=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

// add current page's title (which should be the phoneme) to navigation menu
jQuery(document).ready(function($) {
    $('.current-phoneme').html(document.title);
    $("div#video-phoneme-explanation").html($("div#phoneme-explanation").html())

    $('.trigger-hover').on('click mouseover', function() {
        $('button.recorder').css("background-color", "#ffc438");
        $('button.recorder').addClass("button-hover-effect");
        setTimeout(function() {
            $('button.recorder').removeClass("button-hover-effect");
            $('button.recorder').css("background-color", "#f0f0f0");
        }, 300);
    });

    // smooth scroll to inner links instead of jumps
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': ($target.offset().top)
        }, 500, 'swing', function () {
            window.location.hash = target;
        });
    });

    // calculate anchor positions
    // adapted from Jim W's code: http://stackoverflow.com/a/17494943
    // change layout based on amount of Y scroll
    window.minimizeTriggerPosition=-1;
    window.vid = document.getElementById('video-frame');
    window.minimizeTrigger = document.getElementById('phoneme-explanation');
    window.videoLimitElement = document.getElementById('whats-next');
    window.videoLimit = findPosY(window.videoLimitElement) - 700;

    // adjust top margin to TfCS header position (header stops being fixed at 1242px)
    window.marginTop;
    if(window.innerWidth > 1242){
        window.marginTop = 125;
    }else{
        window.marginTop = 75;
    }
    if(window.minimizeTriggerPosition<0)window.minimizeTriggerPosition=findPosY(window.minimizeTrigger);

    window.exercisePosition = document.getElementsByClassName("exercise")[0].offsetTop;
    window.phonemeGridPosition = document.getElementsByClassName("phoneme-grid")[0].offsetTop;

});

<commit_msg>fix video-frame height, so that elements stay in position when video is minimized<commit_after>function moveThings() {
    // video position is used as reference point
    // var vid = document.getElementById('video-frame');

    // desktop view involves moving around lots of things
    if(window.innerWidth > 960) {
        // var minimizeTrigger = document.getElementById('phoneme-explanation');
        // var videoLimitElement = document.getElementById('whats-next');
        // var videoLimit = findPosY(videoLimitElement) - 700;

        // // adjust top margin to TfCS header position (header stops being fixed at 1242px)
        // var marginTop;
        // if(window.innerWidth > 1242){
        //     marginTop = 125;
        // }else{
        //     marginTop = 75;
        // }

        // if(minimizeTriggerPosition<0)minimizeTriggerPosition=findPosY(minimizeTrigger);

        if(pageYOffset>window.minimizeTriggerPosition-300){
            jQuery('#video-navigation').addClass('minimized');
            jQuery('#video-frame').addClass('minimized');
            jQuery('#video').addClass('minimized');
            jQuery('.entry-content').addClass('shifted');
            window.vid.style.top=window.marginTop+'px';
            if(pageYOffset>window.videoLimit){
                window.vid.style.top=(window.marginTop-pageYOffset+window.videoLimit)+'px';
            }
        }else{
            jQuery('#video-navigation').removeClass('minimized');
            jQuery('#video-frame').removeClass('minimized');
            jQuery('#video').removeClass('minimized');
            jQuery('.entry-content').removeClass('shifted');
            window.vid.style.top=0;
        }
    }else{
        // mobile view is much simpler
        if(pageYOffset>window.exercisePosition && pageYOffset<window.phonemeGridPosition){
            jQuery('.video-navigation-mobile').addClass('minimized');
            jQuery('#video').addClass('minimized');
        }else{
            jQuery('.video-navigation-mobile').removeClass('minimized');
            jQuery('#video').removeClass('minimized');
        }

        // things need to be reset when window shrinks from desktop view to mobile view
        // jQuery('#video-navigation').removeClass('minimized');
        // jQuery('#video-frame').removeClass('minimized');
        // jQuery('#video').removeClass('minimized');
        // jQuery('.entry-content').removeClass('shifted');
        // vid.style.top=0;
    }
}

window.onscroll=function(){
    moveThings();
};

window.onresize=function(){
    moveThings();
};

function findPosY(obj) {
    var curtop = 0;
    if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
        curtop += obj.offsetTop;
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

/**
 * jQuery.browser.mobile (http://detectmobilebrowser.com/)
 *
 * jQuery.browser.mobile will be true if the browser is a mobile device
 *
 **/
(function(a){(jQuery.browser=jQuery.browser||{}).mobile=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

// add current page's title (which should be the phoneme) to navigation menu
jQuery(document).ready(function($) {
    $('.current-phoneme').html(document.title);
    $("div#video-phoneme-explanation").html($("div#phoneme-explanation").html())

    $('.trigger-hover').on('click mouseover', function() {
        $('button.recorder').css("background-color", "#ffc438");
        $('button.recorder').addClass("button-hover-effect");
        setTimeout(function() {
            $('button.recorder').removeClass("button-hover-effect");
            $('button.recorder').css("background-color", "#f0f0f0");
        }, 300);
    });

    // smooth scroll to inner links instead of jumps
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': ($target.offset().top)
        }, 500, 'swing', function () {
            window.location.hash = target;
        });
    });

    // calculate anchor positions
    // adapted from Jim W's code: http://stackoverflow.com/a/17494943
    // change layout based on amount of Y scroll
    window.minimizeTriggerPosition=-1;
    window.vid = document.getElementById('video-frame');
    window.minimizeTrigger = document.getElementById('phoneme-explanation');
    window.videoLimitElement = document.getElementById('whats-next');
    window.videoLimit = findPosY(window.videoLimitElement) - 700;

    // adjust top margin to TfCS header position (header stops being fixed at 1242px)
    window.marginTop;
    if(window.innerWidth > 1242){
        window.marginTop = 125;
    }else{
        window.marginTop = 75;
    }
    if(window.minimizeTriggerPosition<0)window.minimizeTriggerPosition=findPosY(window.minimizeTrigger);

    window.exercisePosition = document.getElementsByClassName("exercise")[0].offsetTop;
    window.phonemeGridPosition = document.getElementsByClassName("phoneme-grid")[0].offsetTop;

    // fix video-frame height, so that elements stay in position when video is minimized
    document.getElementById('video-frame').style.height = document.getElementById('video').offsetHeight;

});

<|endoftext|>


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

/*var socket = io("http://127.0.0.1:3001");

const wesh = console.log;

const exit = (code = 0) => process.exit(code);

socket.on("connect", () => {
  socket.emit("connectFront");
  wesh("I' am connected");
  socket.emit("createHub", {
    name: "test",
    properties: {
      hubName: "hub1",
      mapWidth: 8,
      mapHeight: 8,
      teams: ["ISSOU", "BITE"],
      clientsPerTeam: 1
    }
  });
});

socket.on("dead", () => {
  wesh("I' dead");
  exit();
});

socket.on("update", data => {
  wesh("I' m updated");
  wesh(prettyjson.render(data));
});

socket.on("disconnect", () => {
  wesh("I'm out");
  exit();
});*/

window.onload = () => {
  const WelcomeDiv = document.getElementById("welcome");
  const id = gup("id", window.location.href);
  WelcomeDiv.innerHTML = "Vous êtes sur la partie numéro " + id;

  const tileMapSize = 16;
  const size = 40;
  const windowSize = size * tileMapSize;

  Crafty.init(windowSize, windowSize, document.getElementById("game"));

  //Add audio for Gameplay
  //Crafty.audio.add("PokemonSounds", "/sounds/Bourvil.mp3");
  //Crafty.audio.play("PokemonSounds", 5, 1);

  //turn the sprite map into usable components
  Crafty.sprite(16, "/images/sprite.png", {
    grass1: [0, 0],
    grass2: [1, 0],
    grass3: [2, 0],
    grass4: [3, 0],
    flower: [0, 1],
  });

  Crafty.sprite(33, "/images/Pl.png" , {
      team1: [0, 2],
      team2: [3, 2]
  });

  //randomy generate map
  const generateWorld = () => {
    for (let i = 0; i < size; ++i) {
      for (let j = 0; j < size; ++j) {
        grassType = Math.floor(Math.random() * 4 + 1);
        Crafty.e(`2D, Canvas, grass${grassType}`).attr({
          x: i * tileMapSize,
          y: j * tileMapSize
        });
      }
    }
    for (let i = 0; i < size; ++i) {
      Crafty.e(
        "2D, Canvas, wall_top, bush" + Math.floor(Math.random() * 2 + 1)
      ).attr({ x: i * tileMapSize, y: 0, z: 2 });
      Crafty.e(
        "2D, DOM, wall_bottom, bush" + Math.floor(Math.random() * 2 + 1)
      ).attr({ x: i * tileMapSize, y: (size - 1) * tileMapSize, z: 2 });
    }
    //we need to start one more and one less to not overlap the previous bushes
    for (let i = 1; i < size; i++) {
      Crafty.e(
        "2D, DOM, wall_left, bush" + Math.floor(Math.random() * 2 + 1)
      ).attr({ x: 0, y: i * tileMapSize, z: 2 });
      Crafty.e(
        "2D, Canvas, wall_right, bush" + Math.floor(Math.random() * 2 + 1)
      ).attr({ x: (size - 1) * tileMapSize, y: i * tileMapSize, z: 2 });
    }
  };

  Crafty.scene("loading", () => {
    Crafty.scene("main");
  });

  Crafty.scene("main", () => {
    generateWorld();

    const team1 = Crafty.e(
      "2D, Canvas, team1, Controls, Collision, SpriteAnimation"
    )
      .attr({ x: 60, y: 60, w: tileMapSize, h: tileMapSize })
      .reel("walk_right", 100, [[0, 3], [1, 3], [2, 3]])
      .reel("walk_left", 100, [[0, 1], [1, 1], [2, 1]])
      .reel("walk_down", 100, [[0, 2], [1, 2], [2, 2]])
      .reel("walk_up", 100, [[0, 0], [1, 0], [2, 0]])
      .bind("KeyDown", function(e) {
        if (e.key === Crafty.keys.LEFT_ARROW) {
          this.animate("walk_left");
          this.x -= tileMapSize;
        } else if (e.key === Crafty.keys.RIGHT_ARROW) {
          this.animate("walk_right");
          this.x += tileMapSize;
        } else if (e.key === Crafty.keys.UP_ARROW) {
          this.animate("walk_up");
          this.y -= tileMapSize;
        } else if (e.key === Crafty.keys.DOWN_ARROW) {
          this.animate("walk_down");
          this.y += tileMapSize;
        }
      });

    const team2 = Crafty.e(
      "2D, Canvas, team2, Controls, Collision, SpriteAnimation"
    )
      .attr({ x: 100, y: 100, w: tileMapSize, h: tileMapSize })
      .reel("walk_right", 100, [[3, 3], [4, 3], [5, 3]])
      .reel("walk_left", 100, [[3, 1], [4, 1], [5, 1]])
      .reel("walk_down", 100, [[3, 2], [4, 2], [5, 2]])
      .reel("walk_up", 100, [[3, 0], [4, 0], [5, 0]])
      .bind("KeyDown", function(e) {
        if (e.key === Crafty.keys.LEFT_ARROW) {
          this.animate("walk_left");
          this.x -= tileMapSize;
        } else if (e.key === Crafty.keys.RIGHT_ARROW) {
          this.animate("walk_right");
          this.x += tileMapSize;
        } else if (e.key === Crafty.keys.UP_ARROW) {
          this.animate("walk_up");
          this.y -= tileMapSize;
        } else if (e.key === Crafty.keys.DOWN_ARROW) {
          this.animate("walk_down");
          this.y += tileMapSize;
        }
      });
  });

var zoom = Crafty.e("2D");
    zoom.onMouseDown = function(e) {
        Crafty.viewport.zoom(2, 100, 100, 500);
    };
Crafty.addEvent(zoom, Crafty.stage.elem, "mousedown", zoom.onMouseDown);

  Crafty.scene("loading");
};
<commit_msg>fix zoom<commit_after>function gup(name, url) {
  if (!url) url = location.href;
  name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(url);
  return results == null ? null : results[1];
}

/*var socket = io("http://127.0.0.1:3001");

const wesh = console.log;

const exit = (code = 0) => process.exit(code);

socket.on("connect", () => {
  socket.emit("connectFront");
  wesh("I' am connected");
  socket.emit("createHub", {
    name: "test",
    properties: {
      hubName: "hub1",
      mapWidth: 8,
      mapHeight: 8,
      teams: ["ISSOU", "BITE"],
      clientsPerTeam: 1
    }
  });
});

socket.on("dead", () => {
  wesh("I' dead");
  exit();
});

socket.on("update", data => {
  wesh("I' m updated");
  wesh(prettyjson.render(data));
});

socket.on("disconnect", () => {
  wesh("I'm out");
  exit();
});*/

window.onload = () => {
  const WelcomeDiv = document.getElementById("welcome");
  const id = gup("id", window.location.href);
  WelcomeDiv.innerHTML = "Vous êtes sur la partie numéro " + id;

  const tileMapSize = 16;
  const size = 40;
  const windowSize = size * tileMapSize;

  Crafty.init(windowSize, windowSize, document.getElementById("game"));

  //Add audio for Gameplay
  //Crafty.audio.add("PokemonSounds", "/sounds/Bourvil.mp3");
  //Crafty.audio.play("PokemonSounds", 5, 1);

  //turn the sprite map into usable components
  Crafty.sprite(16, "/images/sprite.png", {
    grass1: [0, 0],
    grass2: [1, 0],
    grass3: [2, 0],
    grass4: [3, 0],
    flower: [0, 1],
  });

  Crafty.sprite(33, "/images/Pl.png" , {
      team1: [0, 2],
      team2: [3, 2]
  });

  //randomy generate map
  const generateWorld = () => {
    for (let i = 0; i < size; ++i) {
      for (let j = 0; j < size; ++j) {
        grassType = Math.floor(Math.random() * 4 + 1);
        Crafty.e(`2D, Canvas, grass${grassType}`).attr({
          x: i * tileMapSize,
          y: j * tileMapSize
        });
      }
    }
    for (let i = 0; i < size; ++i) {
      Crafty.e(
        "2D, Canvas, wall_top, bush" + Math.floor(Math.random() * 2 + 1)
      ).attr({ x: i * tileMapSize, y: 0, z: 2 });
      Crafty.e(
        "2D, DOM, wall_bottom, bush" + Math.floor(Math.random() * 2 + 1)
      ).attr({ x: i * tileMapSize, y: (size - 1) * tileMapSize, z: 2 });
    }
    //we need to start one more and one less to not overlap the previous bushes
    for (let i = 1; i < size; i++) {
      Crafty.e(
        "2D, DOM, wall_left, bush" + Math.floor(Math.random() * 2 + 1)
      ).attr({ x: 0, y: i * tileMapSize, z: 2 });
      Crafty.e(
        "2D, Canvas, wall_right, bush" + Math.floor(Math.random() * 2 + 1)
      ).attr({ x: (size - 1) * tileMapSize, y: i * tileMapSize, z: 2 });
    }
  };

  Crafty.scene("loading", () => {
    Crafty.scene("main");
  });

  Crafty.scene("main", () => {
    generateWorld();

    const team1 = Crafty.e(
      "2D, Canvas, team1, Controls, Collision, SpriteAnimation"
    )
      .attr({ x: 60, y: 60, w: tileMapSize, h: tileMapSize })
      .reel("walk_right", 100, [[0, 3], [1, 3], [2, 3]])
      .reel("walk_left", 100, [[0, 1], [1, 1], [2, 1]])
      .reel("walk_down", 100, [[0, 2], [1, 2], [2, 2]])
      .reel("walk_up", 100, [[0, 0], [1, 0], [2, 0]])
      .bind("KeyDown", function(e) {
        if (e.key === Crafty.keys.LEFT_ARROW) {
          this.animate("walk_left");
          this.x -= tileMapSize;
        } else if (e.key === Crafty.keys.RIGHT_ARROW) {
          this.animate("walk_right");
          this.x += tileMapSize;
        } else if (e.key === Crafty.keys.UP_ARROW) {
          this.animate("walk_up");
          this.y -= tileMapSize;
        } else if (e.key === Crafty.keys.DOWN_ARROW) {
          this.animate("walk_down");
          this.y += tileMapSize;
        }
      });

    const team2 = Crafty.e(
      "2D, Canvas, team2, Controls, Collision, SpriteAnimation"
    )
      .attr({ x: 100, y: 100, w: tileMapSize, h: tileMapSize })
      .reel("walk_right", 100, [[3, 3], [4, 3], [5, 3]])
      .reel("walk_left", 100, [[3, 1], [4, 1], [5, 1]])
      .reel("walk_down", 100, [[3, 2], [4, 2], [5, 2]])
      .reel("walk_up", 100, [[3, 0], [4, 0], [5, 0]])
      .bind("KeyDown", function(e) {
        if (e.key === Crafty.keys.LEFT_ARROW) {
          this.animate("walk_left");
          this.x -= tileMapSize;
        } else if (e.key === Crafty.keys.RIGHT_ARROW) {
          this.animate("walk_right");
          this.x += tileMapSize;
        } else if (e.key === Crafty.keys.UP_ARROW) {
          this.animate("walk_up");
          this.y -= tileMapSize;
        } else if (e.key === Crafty.keys.DOWN_ARROW) {
          this.animate("walk_down");
          this.y += tileMapSize;
        }
      });
  });

const zoom = Crafty.e("2D")
zoom.onMouseDown = e => {
  if (e.buttons === 1) Crafty.viewport.zoom(2, e.clientX, e.clientY, 500)
}
Crafty.addEvent(zoom, Crafty.stage.elem, "mousedown", zoom.onMouseDown)

  Crafty.scene("loading");
}
<|endoftext|>