text:
describe('Sweety', function (){
  var $ = Sweety();

  beforeEach(function (){
    var elem = document.createElement('div');
    elem.id = 'sweety_test';
    elem.className = 'sweety-test';
    document.body.appendChild(elem);
  });

  afterEach(function () {
    var elem = document.getElementById('sweety_test');
    elem.parentNode.removeChild(elem);
  });

  describe('$', function (){

    it('should be initialized', function (){
      expect($).to.be.ok;
    });

    it('should select by id', function () {
      expect($('#sweety_test').toArray().length).to.be(1);
    });

    it('should select by class', function () {
      expect($('.sweety-test').toArray().length).to.be(1);
    });

    it('should select by name', function () {
      var elem = document.createElement('a');
      elem.name = 'sweety_test_name';
      document.body.appendChild(elem);

      expect($('@sweety_test_name').toArray().length).to.be(1);
    });

    it('should select by tag', function () {
      expect($('div').toArray().length).to.not.be(0);
    });

    it('should create a DOM elements by html', function () {
      expect($('<div>').toArray().length).to.be(1);
    });

    it('should properly handle window', function () {
      expect($(window).toArray()[0].toString()).to.be(window.toString());
    });

    it('should properly handle document', function () {
      expect($(document).toArray()[0]).to.be(document);
    });

    it('should properly handle Array', function () {
      expect($([document]).toArray()[0]).to.be(document);
    });

    it('should properly handle SweetyElement', function () {
      expect($($(document)).toArray()[0]).to.be(document);
    });

    it('should select nothing by empty string', function () {
      expect($('').toArray().length).to.be(0);
    });

    it('should return empty collection without any params', function () {
      expect($().toArray().length).to.be(0);
    });

  });

  describe('.toArray', function () {

    it('should return an Array', function () {
      expect($('#sweety_test').toArray()).to.be.an('array');
    });

  });

  describe('.findChild', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.className = 'sweety-test-child';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return a child element by tag', function () {
      expect($('#sweety_test').findChild('div').toArray().length).to.be(1);
    });

    it('should return a child element by class', function () {
      expect($('#sweety_test').findChild('.sweety-test-child').toArray().length).to.be(1);
    });

    it('should return empty collection on empty collection', function () {
      expect($().findChild('.sweety-test-child').toArray().length).to.be(0);
    });

  });

  describe('.findParent', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return a parent element', function () {
      expect($('#sweety_test_child').findParent()
        .hasClass('sweety-test')).to.be(true);
    });

    it('should return a parent element by tag', function () {
      expect($('#sweety_test_child').findParent('div')
        .hasClass('sweety-test')).to.be(true);
    });

    it('should return a parent element by class', function () {
      expect($('#sweety_test_child').findParent('.sweety-test')
        .hasClass('sweety-test')).to.be(true);
    });

    it('should return empty collection on empty collection', function () {
      expect($().findParent('.sweety-test').toArray().length).to.be(0);
    });

  });

  describe('.parent', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return a parent element', function () {
      expect($('#sweety_test_child').parent().toArray().length).to.be(1);
    });

    it('should return empty collection on empty collection', function () {
      expect($().parent().toArray().length).to.be(0);
    });

  });

  describe('.getProp', function () {
    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return a value of given property', function () {
      var input = '<input id="sweety_test_input" type="text" value="test-value">';
      document.getElementById('sweety_test').innerHTML = input;
      expect($('#sweety_test_input').getProp('value')).to.be('test-value');
      expect($('#sweety_test_input').getProp('type')).to.be('text');
    });

    it('should return true if property checked exists', function () {
      var input = '<input id="sweety_test_input" type="checkbox" checked="">';
      document.getElementById('sweety_test').innerHTML = input;
      expect($('#sweety_test_input').getProp('checked')).to.be(true);
    });

    it('should return false if property checked does not exists', function () {
      var input = '<input id="sweety_test_input" type="checkbox">';
      document.getElementById('sweety_test').innerHTML = input;
      expect($('#sweety_test_input').getProp('checked')).to.be(false);
    });

    it('should return undefined if property does not exists', function () {
      var input = '<input id="sweety_test_input">';
      document.getElementById('sweety_test').innerHTML = input;
      expect($('#sweety_test_input').getProp('notexists') === undefined).to.be(true);
    });

    it('should return undefined if element does not exists', function () {
      expect($().getProp('notexists') === undefined).to.be(true);
    });
  });

  describe('.setProp', function () {
    beforeEach(function () {
      var input = '<input id="sweety_test_input">';
      document.getElementById('sweety_test').innerHTML = input;
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should set a given property and value from a pair', function () {
      $('#sweety_test_input')
        .setProp('value', 'test-value')
        .setProp('type', 'text');
      expect(document.getElementById('sweety_test_input').value).to.be('test-value');
      expect(document.getElementById('sweety_test_input').type).to.be('text');
    });

    it('should set a given property and value from an object', function () {
      $('#sweety_test_input')
        .setProp({
          'value': 'test-value',
          'type': 'text'
        });
      expect(document.getElementById('sweety_test_input').value).to.be('test-value');
      expect(document.getElementById('sweety_test_input').type).to.be('text');
    });

    it('should set a checked property', function () {
      $('#sweety_test_input')
        .setProp('type', 'checkbox')
        .setProp('checked', true);
      expect(document.getElementById('sweety_test_input').checked).to.be(true);
    });

    it('should not crash on empty collection', function () {
      $().setProp('type', 'checkbox');
    });
  });

  describe('.prop', function () {
    beforeEach(function () {
      var input = '<input id="sweety_test_input">';
      document.getElementById('sweety_test').innerHTML = input;
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return a value of given property', function () {
      document.getElementById('sweety_test_input').type = 'text';
      document.getElementById('sweety_test_input').value = 'test-value';
      expect($('#sweety_test_input').prop('value')).to.be('test-value');
      expect($('#sweety_test_input').prop('type')).to.be('text');
    });

    it('should set a given property and value from a pair', function () {
      $('#sweety_test_input')
        .prop('value', 'test-value')
        .prop('type', 'text');
      expect(document.getElementById('sweety_test_input').value).to.be('test-value');
      expect(document.getElementById('sweety_test_input').type).to.be('text');
    });

    it('should set a given property and value from an object', function () {
      $('#sweety_test_input')
        .prop({
          'value': 'test-value',
          'type': 'text'
        });
      expect(document.getElementById('sweety_test_input').value).to.be('test-value');
      expect(document.getElementById('sweety_test_input').type).to.be('text');
    });

    it('should not crash on empty collection', function () {
      $().prop('type', 'checkbox');
    });
  });

  describe('.getAttr', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      elem.setAttribute('test-attr', 'test-value');
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return a value of given attr', function () {
      expect($('#sweety_test_child').getAttr('test-attr')).to.be('test-value');
    });

    it('should return null if attr does not exists', function () {
      expect($('#sweety_test_child').getAttr('test-attr-2') === null).to.be(true);
    });

    it('should return null if element does not exist', function () {
      expect($().getAttr('test-attr') === null).to.be(true);
    });

  });

  describe('.setAttr', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should set a given attr and value from a pair of strings', function () {
      expect($('#sweety_test_child')
        .setAttr('test-attr', 'test-value')
        .getAttr('test-attr')).to.be('test-value');
    });

    it('should set a given attr and value from an object', function () {
      expect($('#sweety_test_child')
        .setAttr({
          'test-attr': 'test-value'
        })
        .getAttr('test-attr')).to.be('test-value');
    });

    it('should not crash on empty collection', function () {
      $().setAttr('test-attr', 'test-value');
      $().setAttr({
        'test-attr': 'test-value'
      });
    });

  });

  describe('.removeAttr', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      elem.setAttribute('test-attr', 'test-value');
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should remove a given attr by name from a string', function () {
      expect($('#sweety_test_child').removeAttr('test-attr').getAttr('test-attr') === null).to.be(true);
    });

    it('should remove a given attr by list of names from an array', function () {
      expect($('#sweety_test_child').removeAttr(['test-attr']).getAttr('test-attr') === null).to.be(true);
    });

    it('should not crash on empty collection', function () {
      $().removeAttr('test-attr');
      $().removeAttr(['test-attr']);
    });

  });

  describe('.hasAttr', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      elem.setAttribute('test-attr', 'test-value');
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return true if attr exists', function () {
      expect($('#sweety_test_child').hasAttr('test-attr')).to.be(true);
    });

    it('should return false if attr doesn\'t exist', function () {
      expect($('#sweety_test_child').hasAttr('not-exist')).to.be(false);
    });

    it('should return false if element does not exist', function () {
      expect($().hasAttr('test-attr')).to.be(false);
    });

  });

  describe('.attr', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      elem.setAttribute('test-attr', 'test-value');
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return a value with if only key is specified', function () {
      expect($('#sweety_test_child').attr('test-attr')).to.be('test-value');
    });

    it('should set a value if both key and value is specified', function () {
      expect($('#sweety_test_child')
        .attr('test-attr', 'new-test-value')
        .attr('test-attr')
        ).to.be('new-test-value');
    });

  });

  describe('.val with input element', function () {

    beforeEach(function () {
      var elem = document.createElement('input');
      elem.type = 'text';
      elem.id = 'sweety_test_child';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return a value if value set from property', function () {
      document.getElementById('sweety_test_child').value = 'test-value';
      expect($('#sweety_test_child').val()).to.be('test-value');
    });

    it('should return a value if value set from attribute', function () {
      document.getElementById('sweety_test_child').setAttribute('value', 'test-value');
      expect($('#sweety_test_child').val()).to.be('test-value');
    });

    it('should set a value if value is specified', function () {
      expect($('#sweety_test_child').val('new-test-value').val()
        ).to.be('new-test-value');
    });

  });

  describe('.val with select element', function () {

    beforeEach(function () {
      document.getElementById('sweety_test').innerHTML = '<select id="sweety_test_child"><option value="value-1" selected="">Value 1</option><option value="value-2">Value 2</option></select>';
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return selected value', function () {
      expect($('#sweety_test_child').val()).to.be('value-1');
    });

    it('should return value set using property', function () {
      document.getElementById('sweety_test_child').value = 'value-2';
      expect($('#sweety_test_child').val()).to.be('value-2');
    });

    it('should change and return value', function () {
      expect($('#sweety_test_child').val('value-2').val()).to.be('value-2');
    });

  });

  describe('.val with multiple select element', function () {

    beforeEach(function () {
      document.getElementById('sweety_test').innerHTML = '<select id="sweety_test_child" multiple=""><option value="value-1" selected="">Value 1</option><option value="value-2">Value 2</option><option value="value-3">Value 3</option></select>';
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return selected value', function () {
      expect($('#sweety_test_child').val()).to.eql(['value-1']);
    });

    it('should return value set using property', function () {
      document.getElementById('sweety_test_child').value = 'value-2';
      expect($('#sweety_test_child').val()).to.eql(['value-2']);
    });

    it('should change value on string', function () {
      expect($('#sweety_test_child').val('value-2 value-3').val()).to.eql(['value-2', 'value-3']);
    });

    it('should change value on array', function () {
      expect($('#sweety_test_child').val(['value-2', 'value-3']).val()).to.eql(['value-2', 'value-3']);
    });

    it('should deselect all on empty string', function () {
      expect($('#sweety_test_child').val('').val() === null).to.be(true);
    });

    it('should deselect all on empty array', function () {
      expect($('#sweety_test_child').val([]).val() === null).to.be(true);
    });

  });

  describe('.val with radio buttons', function () {
    beforeEach(function () {
      document.getElementById('sweety_test').innerHTML = '<input type="radio" name="sweety_radio_button" value="value-1" checked=""><input type="radio" name="sweety_radio_button" value="value-2"><input type="radio" name="sweety_radio_button" value="value-3">';
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return a value of checked radio', function () {
      expect($('@sweety_radio_button').val()).to.be('value-1');
    });

    it('should change value', function () {
      expect($('@sweety_radio_button').val('value-2').val()).to.be('value-2');
    });

    it('should uncheck all on empty string', function () {
      expect($('@sweety_radio_button').val('').val() === null).to.be(true);
    });
  });

  describe('.val with checkboxes', function () {
    beforeEach(function () {
      document.getElementById('sweety_test').innerHTML = '<input type="checkbox" name="sweety_checkbox" value="value-1" checked=""><input type="checkbox" name="sweety_checkbox" value="value-2"><input type="checkbox" name="sweety_checkbox" value="value-3">';
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return a value of checked checkbox', function () {
      expect($('@sweety_checkbox').val()).to.eql(['value-1']);
    });

    it('should change value on string', function () {
      expect($('@sweety_checkbox').val('value-2').val()).to.eql(['value-2']);
    });

    it('should change value on array', function () {
      expect($('@sweety_checkbox').val(['value-2', 'value-3']).val()
        ).to.eql(['value-2', 'value-3']);
    });

    it('should uncheck all on empty string', function () {
      expect($('@sweety_checkbox').val('').val() === null).to.be(true);
    });

    it('should uncheck all on empty array', function () {
      expect($('@sweety_checkbox').val([]).val() === null).to.be(true);
    });
  });

  describe('.val with div element', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return a value if value set from property', function () {
      document.getElementById('sweety_test_child').value = 'test-value';
      expect($('#sweety_test_child').val()).to.be('test-value');
    });

    it('should return a value if value set from attribute', function () {
      document.getElementById('sweety_test_child').setAttribute('value', 'test-value');
      expect($('#sweety_test_child').val()).to.be('test-value');
    });

    it('should set a value if value is specified', function () {
      expect($('#sweety_test_child').val('new-test-value').val()
        ).to.be('new-test-value');
    });

  });

  describe('fn.getClasses', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      elem.className = 'class-1 class-2 class-3';
      document.getElementById('sweety_test').appendChild(elem);
      var elem2 = document.createElement('div');
      elem2.id = 'sweety_test_child2';
      document.getElementById('sweety_test').appendChild(elem2);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return an array of classes', function () {
      expect($.fn.getClasses($('#sweety_test_child').toArray()[0])
        ).to.eql(['class-1', 'class-2', 'class-3']);
    });

    it('should return a blank array if no class is specified', function () {
      expect($.fn.getClasses($('#sweety_test_child2').toArray()[0])
        ).to.eql([]);
    });

  });

  describe('fn.saveClasses', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should set class from array', function () {
      $.fn.saveClasses($('#sweety_test_child').toArray()[0], ['class-1', 'class-2', 'class-3']);
      expect($('#sweety_test_child').attr('class')).to.be('class-1 class-2 class-3');
    });

    it('should set blank class from a blank array', function () {
      $.fn.saveClasses($('#sweety_test_child').toArray()[0], []);
      expect($('#sweety_test_child').attr('class')).to.be('');
    });

  });

  describe('.addClass', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      elem.className = 'class-1 class-2';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should add class from a string', function () {
      expect($.fn.getClasses($('#sweety_test_child').addClass('class-3').toArray()[0])
        ).to.eql(['class-1', 'class-2', 'class-3']);
    });

    it('should add multiple classes from a string', function () {
      expect($.fn.getClasses($('#sweety_test_child').addClass('class-3 class-4').toArray()[0])
        ).to.eql(['class-1', 'class-2', 'class-3', 'class-4']);
    });

    it('should add classes from a list', function () {
      expect($.fn.getClasses($('#sweety_test_child').addClass(['class-3', 'class-4']).toArray()[0])
        ).to.eql(['class-1', 'class-2', 'class-3', 'class-4']);
    });

    it('should not duplicate classes when adding', function () {
      expect($.fn.getClasses($('#sweety_test_child').addClass(['class-1', 'class-2']).toArray()[0])
        ).to.eql(['class-1', 'class-2']);
    });

    it('should not crash on empty collection', function () {
      $().addClass('class-1');
      $().addClass(['class-1']);
    });

  });

  describe('.removeClass', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      elem.className = 'class-1 class-2';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should remove class from a string', function () {
      expect($.fn.getClasses($('#sweety_test_child').removeClass('class-2').toArray()[0])
        ).to.eql(['class-1']);
    });

    it('should remove multiple classes from a string', function () {
      expect($.fn.getClasses($('#sweety_test_child').removeClass('class-1 class-2').toArray()[0])
        ).to.eql([]);
    });

    it('should remove classes from a list', function () {
      expect($.fn.getClasses($('#sweety_test_child').removeClass(['class-1', 'class-2']).toArray()[0])
        ).to.eql([]);
    });

    it('should not crash on empty collection', function () {
      $().removeClass('class-1');
      $().removeClass(['class-1']);
    });

  });

  describe('.hasClass', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      elem.className = 'class-1 class-2';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return true if first element has a given class', function () {
      expect($('#sweety_test_child').hasClass('class-2')).to.be(true);
    });

    it('should return false if first element doesn\'t have a given class', function () {
      expect($('#sweety_test_child').hasClass('no-such-class')).to.be(false);
    });

    it('should return false if element does not exist', function () {
      expect($().hasClass('class-2')).to.be(false);
    });

  });

  describe('.toggleClass', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should toggle a given class on element', function () {
      expect($('#sweety_test_child').toggleClass('new-class').hasClass('new-class')).to.be(true);
      expect($('#sweety_test_child').toggleClass('new-class').hasClass('new-class')).to.be(false);
    });

  });

  describe('fn.getStyles', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      elem.style.cssText = 'color: black;';
      document.getElementById('sweety_test').appendChild(elem);
      var elem2 = document.createElement('div');
      elem2.id = 'sweety_test_child2';
      document.getElementById('sweety_test').appendChild(elem2);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return an object of CSS styles', function () {
      expect($.fn.getStyles($('#sweety_test_child').toArray()[0])
        ).to.eql({ color: 'black' });
    });

    it('should return a blank object if no style is specified', function () {
      expect($.fn.getStyles($('#sweety_test_child2').toArray()[0])
        ).to.eql({});
    });

  });

  describe('fn.saveStyles', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should set styles from object', function () {
      $.fn.saveStyles($('#sweety_test_child').toArray()[0], { color: 'black' });
      expect(document.getElementById('sweety_test_child').style.color
        ).to.be('black');
    });

    it('should set blank styles from a blank object', function () {
      $.fn.saveStyles($('#sweety_test_child').toArray()[0], {});
      expect(document.getElementById('sweety_test_child').style.cssText
        ).to.be('');
    });

  });

  describe('.addStyle', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      elem.style.cssText = 'color:black';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should add styles from arguments', function () {
      $('#sweety_test_child').addStyle('text-align', 'right');
      expect(document.getElementById('sweety_test_child').style.textAlign
        ).to.be('right');
    });

    it('should add styles from an object', function () {
      $('#sweety_test_child').addStyle({
        'text-align': 'right',
        'text-decoration': 'none'
      });
      expect(document.getElementById('sweety_test_child').style.textAlign
        ).to.be('right');
      expect(document.getElementById('sweety_test_child').style.textDecoration
        ).to.be('none');
    });

    it('should not duplicate styles when adding', function () {
      var prevCssText = document.getElementById('sweety_test_child').style.cssText;
      $('#sweety_test_child').addStyle({
        color: 'black'
      });
      expect(document.getElementById('sweety_test_child').style.cssText
        ).to.be(prevCssText);
    });

    it('should not crash on empty collection', function () {
      $().addStyle('color', 'black');
      $().addStyle({
        color: 'black'
      });
    });

  });

  describe('.removeStyle', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      elem.style.cssText = 'color: black; text-align: right;';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should remove styles from arguments', function () {
      $('#sweety_test_child').removeStyle('color');
      expect(document.getElementById('sweety_test_child').style.color
        ).to.be('');
    });

    it('should remove styles from a list', function () {
      $('#sweety_test_child').removeStyle(['color', 'text-align']);
      expect(document.getElementById('sweety_test_child').style.cssText
        ).to.be('');
    });

    it('should not crash on empty collection', function () {
      $().removeStyle('color');
      $().removeStyle(['color']);
    });

  });

  describe('.css', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      elem.style.cssText = 'color:black';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should add styles from arguments', function () {
      $('#sweety_test_child').css('text-align', 'right');
      expect(document.getElementById('sweety_test_child').style.textAlign
        ).to.be('right');
    });

    it('should add styles from an object', function () {
      $('#sweety_test_child').css({
        'text-align': 'right',
        'text-decoration': 'none'
      });
      expect(document.getElementById('sweety_test_child').style.textAlign
        ).to.be('right');
      expect(document.getElementById('sweety_test_child').style.textDecoration
        ).to.be('none');
    });

    it('should not duplicate styles when adding', function () {
      var prevCssText = document.getElementById('sweety_test_child').style.cssText;
      $('#sweety_test_child').css({
        color: 'black'
      });
      expect(document.getElementById('sweety_test_child').style.cssText
        ).to.be(prevCssText);
    });

  });

  describe('.html', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should return inner HTML if no arguments are provided', function () {
      expect($('#sweety_test')
        .html()
        ).to.be('<div id="sweety_test_child"></div>');
    });

    it('should set inner HTML if string is provided', function () {
      expect($('#sweety_test')
        .html('<div id="sweety_test_child_2"></div>')
        .html()
        ).to.be('<div id="sweety_test_child_2"></div>');
    });

    it('setter should not crash on empty collection', function () {
      $().html('<div id="sweety_test_child_2"></div>');
    });

    it('getter should return undefined on empty collection', function () {
      expect($().html() === undefined).to.be(true);
    });

  });

  describe('.empty', function () {

    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should empty inner HTML', function () {
      expect($('#sweety_test')
        .empty()
        .html()
        ).to.be('');
    });

  });

  describe('.append', function () {

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should append elements', function () {
      $('#sweety_test').append($('<div id="sweety_test_child"></div>'));
      expect($('#sweety_test_child').toArray().length).to.be(1);
    });

    it('should not crash on empty collection', function () {
      $().append($('<div id="sweety_test_child"></div>'));
    });

    it('should not crash if passed an empty collection', function () {
      $('#sweety_test').append();
      $('#sweety_test').append($());
    });

  });

  describe('.remove', function () {
    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should remove elements', function () {
      $('#sweety_test_child').remove();
      expect($('#sweety_test_child').toArray().length).to.be(0);
    });

    it('should not crash on empty collection', function () {
      $().remove();
    });

  });

  describe('.on', function () {
    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should bind events by string', function (done) {
      $('#sweety_test_child').on('click', function (e) {
        expect(e).to.be.ok();
        done();
      });
      document.getElementById('sweety_test_child').click();
    });

    it('should bind events by array', function (done) {
      $('#sweety_test_child').on(['click'], function (e) {
        expect(e).to.be.ok();
        done();
      });
      document.getElementById('sweety_test_child').click();
    });

    it('should not crash on empty collection', function () {
      $().on('click', function () {});
    });

  });

  describe('.off', function () {
    beforeEach(function () {
      var elem = document.createElement('div');
      elem.id = 'sweety_test_child';
      document.getElementById('sweety_test').appendChild(elem);
    });

    afterEach(function () {
      document.getElementById('sweety_test').innerHTML = '';
    });

    it('should unbind events by string', function (done) {
      var testFunc = function (e) {
        done(new Error('testFunc is binded'));
      };
      $('#sweety_test_child').on('click', testFunc);
      $('#sweety_test_child').off('click', testFunc);
      $('#sweety_test_child').on('click',function (e) {
        expect(e).to.be.ok();
        done();
      });
      document.getElementById('sweety_test_child').click();
    });

    it('should unbind events by array', function (done) {
      var testFunc = function (e) {
        done(new Error('testFunc is binded'));
      };
      $('#sweety_test_child').on(['click'], testFunc);
      $('#sweety_test_child').off(['click'], testFunc);
      $('#sweety_test_child').on(['click'],function (e) {
        expect(e).to.be.ok();
        done();
      });
      document.getElementById('sweety_test_child').click();
    });

    it('should unbind all handlers by event string', function (done) {
      var testFunc = function (e) {
        done(new Error('testFunc is binded'));
      };
      $('#sweety_test_child').on('click', testFunc);
      $('#sweety_test_child').off('click');
      $('#sweety_test_child').on('click',function (e) {
        expect(e).to.be.ok();
        done();
      });
      document.getElementById('sweety_test_child').click();
    });

    it('should unbind all handlers by event array', function (done) {
      var testFunc = function (e) {
        done(new Error('testFunc is binded'));
      };
      $('#sweety_test_child').on(['click'], testFunc);
      $('#sweety_test_child').off(['click']);
      $('#sweety_test_child').on(['click'],function (e) {
        expect(e).to.be.ok();
        done();
      });
      document.getElementById('sweety_test_child').click();
    });

    it('should not crash on empty collection', function () {
      var testFunc = function () {};
      $().on('click', testFunc);
      $().off('click', testFunc);
    });

  });

  describe('.exists', function () {
    it('should return true if it does contain elements', function () {
      expect($('<div id="sweety_test_child"></div>').exists()).to.be(true);
    });

    it('should return false if it doesn\'t contain any elements', function () {
      expect($().exists()).to.be(false);
    });
  });

  describe('.toString', function () {
    it('should return [SweetyElement]', function () {
      expect($('<div id="sweety_test_child"></div>').toString()).to.be('[SweetyElement]');
    });
  });

});

describe('Extensions', function () {
  var $ = Sweety({
    testFunc: function () {
      return this.elements.length;
    }
  });

  it('testFunc should return collection length', function () {
    expect($().testFunc() === 0).to.be(true);
    expect($('<div></div>').testFunc() === 1).to.be(true);
  });
});


text:
@implementation FlyDrop

static const uint32_t waterDropCategory     =  0x1 << 0;
static const uint32_t flyDropCategory        =  0x1 << 1;

+(instancetype)spritewithDirectionAndLocation:(NSInteger)direction location:(CGPoint)location{
    FlyDrop *drop  = [FlyDrop spriteNodeWithImageNamed:@"drop_1"];
    drop.direction = direction;
    drop.position = location;
    [drop setupAction];
    drop.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:drop.size.width/2];
    drop.physicsBody.dynamic = YES;
    drop.physicsBody.categoryBitMask = flyDropCategory;
    drop.physicsBody.contactTestBitMask = waterDropCategory;
    drop.physicsBody.collisionBitMask = 0;
    //drop.physicsBody.usesPreciseCollisionDetection = YES;
    return drop;
}
-(void)setDirection:(NSInteger)direction{
    if (direction<1||direction>4) {
        self.direction = 1;
        return;
    }
    _direction = direction;
}
-(void)setupAction{
    SKAction *action;
    SKAction *moveAction;
    CGFloat angle;
    CGFloat actualDuration;
    switch (self.direction) {
        case DIRECTION_UP:
            actualDuration = (kWindowHeight - self.position.y)/kSpeed;
            angle = M_PI/2;
            moveAction = [SKAction moveToY:kWindowHeight  duration:actualDuration];
            break;
        case DIRECTION_DOWN:
            actualDuration = self.position.y / kSpeed;
            angle = -M_PI/2;
            moveAction = [SKAction moveToY:0  duration:actualDuration];
            break;
        case DIRECTION_LEFT:
            actualDuration = self.position.x / kSpeed;
            angle =  M_PI;
            moveAction = [SKAction moveToX:0 duration:actualDuration];
            break;
        case DIRECTION_RIGHT:
            actualDuration = (kWindowWidth- self.position.x) / kSpeed;
            angle = 0;
            moveAction = [SKAction moveToX:kWindowWidth duration:actualDuration];
            break;
        default:
            break;
    }
    action = [SKAction rotateByAngle:angle duration:0];
    [self runAction:action];
    action = [SKAction sequence:@[
                                  moveAction,
                                 [SKAction runBlock:^{
        GameScene *parent =  (GameScene*)self.parent;
        parent.flyDropsNum = parent.flyDropsNum - 1;
//        if (parent.isAI && parent.flyDropsNum == 0 && parent.AIStep<parent.AISolution.count) {
//            MyPoint *point = [parent.AISolution objectAtIndex:parent.AIStep];
//            MySprite *sprite = [parent childNodeWithName:[NSString stringWithFormat:@"%d%d",point.x,point.y]];
//            [sprite addDrop];
//            parent.AIStep ++;
//            CGFloat duration = 3;
//            SKAction *flashAction = [SKAction sequence:@[
//                                                         [SKAction fadeInWithDuration:duration/3.0],
//                                                         [SKAction waitForDuration:duration],
//                                                         [SKAction fadeOutWithDuration:duration/7.0]
//                                                         ]];
//            [parent.locationLabel runAction:flashAction completion:^{
//                [parent.locationLabel removeFromParent];
//                [sprite addDrop];
//            }];
//
//        }
    }],
                                  [SKAction runBlock:^{
        [self removeFromParent];}],
                                  ]];
    [self runAction:action];
    action = [SKAction animateWithTextures:DROP_ANIM_DROP timePerFrame:0.033];
    SKAction *actions = [SKAction repeatActionForever:action];
    [self runAction:actions];
}
@end

redpajama_set_name: RedPajamaGithub


text:
package com.frameworkset.common.poolman.management;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

import com.frameworkset.common.poolman.PoolManConstants;
import com.frameworkset.util.SimpleStringUtil;

/**
 * SAXParser used by Configurator to parse the
 * poolman.xml file. It returns Collections of
 * generic pool properties, JDBC pool properties,
 * and admin-agent properties.
 */
public class ConfigParser extends DefaultHandler{
	private static Logger log = Logger.getLogger(ConfigParser.class) ;
    private ArrayList dbProps;
    private ArrayList genericProps;
    private Properties adminProps;
    private boolean jmxManagement = PoolManConstants.DEFAULT_USE_JMX;
    private String currentSet;
    private String currentName;
    private StringBuffer currentValue = new StringBuffer();
    private String file;
    private String[] filterdbname = null;
    private String interceptor = "com.frameworkset.common.poolman.interceptor.DummyInterceptor";
    private String currentdbtype ;
    private String dbnamespace;

    /**
     * 用户自定义的适配器
     */
    private Map<String,String> adaptors = new HashMap<String,String>();
    public ConfigParser(String file,String dbnamespace,String[] filterdbname) {
        this.dbProps = new ArrayList();
        this.genericProps = new ArrayList();
        this.file = file;
        this.filterdbname = filterdbname;
        this.dbnamespace = dbnamespace;
    }

    public ArrayList getDataSourceProperties() {
    	if(this.filterdbname != null && filterdbname.length > 0)
    	{
    		this.dbProps.clear();
    		if(this.filterpros != null && this.filterpros.size() > 0)
    			this.dbProps.addAll(this.filterpros);
    	}
        return this.dbProps;
    }

    public ArrayList getGenericProperties() {
        return this.genericProps;
    }

    public Properties getAdminProps() {
        return this.adminProps;
    }

    public boolean isManagementJMX() {
        return this.jmxManagement;
    }

    public void startElement(String s1, String s2,String name,Attributes attributes) {

        currentValue.delete(0, currentValue.length());
        this.currentName = name;

        if (name.toLowerCase().equals("datasource")) {
            this.currentSet = "datasource";
            Properties properties = new Properties();
            String external = SimpleStringUtil.replaceNull(attributes.getValue("external"),"false");
            properties.put("external",external);
            dbProps.add(properties);
        }
        else if (name.toLowerCase().equals("objectpool")) {
            this.currentSet = "generic";
            genericProps.add(new Properties());
        }
        else if (name.toLowerCase().equals("admin-agent")) {
            this.currentSet = "admin-agent";
            this.adminProps = new Properties();
        }
        else if (name.toLowerCase().equals("management-mode")) {
            this.currentSet = "management-mode";
        }
        else if (name.equals("poolman") || name.equals("MLET")) {
            this.currentSet = "ignorable";
        }
        else if (name.toLowerCase().equals("jndi_principal")) {
            this.currentSet = "jndi_principal";
        }
        else if (name.equals("jndi_credentials") ) {
            this.currentSet = "jndi_credentials";
        }
        else if (name.toLowerCase().equals("adaptor")) {
            this.currentSet = "adaptor";
            this.currentdbtype = attributes.getValue("dbtype");
        }

        else if(!name.equals("dbname") && !name.equals("loadmetadata") &&
        		!name.equals("jndiName") &&
        		!name.equals("driver") &&
        		!name.equals("url") &&
        		!name.equals("username") &&
        		!name.equals("password") &&
        		!name.equals("txIsolationLevel") &&
        		!name.equals("nativeResults") &&
        		!name.equals("poolPreparedStatements") &&
        		!name.equals("initialConnections") &&
        		!name.equals("minimumSize") &&
        		!name.equals("maximumSize") &&
        		!name.equals("maximumSoft") &&
        		!name.equals("removeAbandoned") &&
        		!name.equals("userTimeout") &&
        		!name.equals("logAbandoned") &&
        		!name.equals("readOnly") &&
        		!name.equals("skimmerFrequency") &&
        		!name.equals("connectionTimeout") &&
        		!name.equals("shrinkBy") &&
        		!name.equals("testWhileidle") &&
        		!name.equals("keygenerate") &&
        		!name.equals("maxWait") &&
        		!name.equals("validationQuery")&&
        		!name.equals("autoprimarykey")&&
        		!name.equals("cachequerymetadata")&&
        		!name.equals("showsql") &&
        		!name.equals("externaljndiName")&&
        		!name.equals("enablejta") &&
        		!name.equals("usepool") &&
        		!name.equals("encryptdbinfo") &&
        		!name.equals("datasourceFile") )

        {
        	log.debug("解析文件时[" + this.file + "]遇到元素[" + name + "],忽略处理。");
        }

    }

    public void characters(char[] ch, int start, int length) {
        currentValue.append(ch, start, length);
    }

    private List<Properties> filterpros = null;
    private boolean contain(String newdbname)
    {
    	if(filterpros == null || filterpros.size() == 0)
    		return false;
    	for(Properties p:filterpros)
    	{
    		String dbname = (String)p.get("dbname");
    		if(dbname.equals(newdbname))
    			return true;
    	}
    	return false;

    }
    public void endElement(String s1,String s2,String name) {
        if (this.currentSet.equals("datasource")) {
            Properties p = (Properties) dbProps.get(dbProps.size() - 1);
            if(name.toLowerCase().equals("dbname"))
            {
            	String dbname = currentValue.toString().trim();
            	String temp = dbname;
            	if(this.dbnamespace != null && !this.dbnamespace.equals(""))
	   			 {
            		dbname = dbnamespace + ":" + currentValue.toString().trim();
	   			 }
            	p.put(name.toLowerCase(), dbname);

            	if(this.filterdbname !=null && this.filterdbname.length > 0)
            	{
	            	for(String _dbname:filterdbname)
	            	{
	            		if(temp.equals(_dbname) )
	            		{
	            			if(filterpros == null)
	            				filterpros = new ArrayList<Properties>();
	            			filterpros.add(p);
	            			break;
	            		}
	            	}
            	}

            }
            else
            {
            	p.put(name.toLowerCase(), currentValue.toString().trim());
            }
        }
        else if (this.currentSet.equals("generic")) {

            Properties p = (Properties) genericProps.get(genericProps.size() - 1);
            p.put(name.toLowerCase(), currentValue.toString().trim());

        }
        else if (this.currentSet.equals("admin-agent")) {
            adminProps.setProperty(name.toLowerCase(), currentValue.toString().trim());
        }
        else if (this.currentSet.equals("management-mode")) {
            if (currentValue.toString().toLowerCase().trim().equals("jmx"))
                this.jmxManagement = true;
        }
        else if (this.currentSet.equals("jndi_principal")) {
            if (currentValue.toString().trim().length() > 0)
            	PoolManConfiguration.jndi_principal = currentValue.toString();
        }
        else if (this.currentSet.equals("jndi_credentials")) {
        	if (currentValue.toString().trim().length() > 0)
            	PoolManConfiguration.jndi_credentials = currentValue.toString();
        }

        else if (this.currentSet.equals("adaptor")) {
        	if (currentValue.toString().trim().length() > 0)
        	{
        		if(currentdbtype == null || currentdbtype.equals(""))
        		{
        			System.out.println("ignoe adaptor["+currentValue+"],没有指定dbtype。");
        		}
        		else
        		{
        			this.adaptors.put(this.currentdbtype, currentValue.toString().trim());
        			currentdbtype = null;
        		}

        	}
        }

        this.currentValue.delete(0, this.currentValue.length());
    }

    class ConfigElement {

        String name;
        String value;
        String datatype;
        ConfigElement parent;
        ArrayList children;

        ConfigElement(String name, String value, String datatype) {
            this.name = name;
            this.value = value;
            this.datatype = datatype;
            this.parent = null;
            this.children = new ArrayList();
        }

        String getValue() {
            return this.value;
        }

        void setValue(String value) {
            this.value = value;
        }

        boolean hasChildren() {
            if (this.children.size() > 0)
                return true;
            return false;
        }

        ConfigElement getParent() {
            return this.parent;
        }

        ArrayList getChildren() {
            return this.children;
        }

        void addChild(ConfigElement child) {
            this.children.add(child);
        }

    }

	/**
	 * @return the adaptors
	 */
	public Map<String, String> getAdaptors() {
		return adaptors;
	}

	/**
	 * @param adaptors the adaptors to set
	 */
	public void setAdaptors(Map<String, String> adaptors) {
		this.adaptors = adaptors;
	}

	/**
	 * @return the interceptor
	 */
	public String getInterceptor() {
		return interceptor;
	}

	/**
	 * @param interceptor the interceptor to set
	 */
	public void setInterceptor(String interceptor) {
		this.interceptor = interceptor;
	}
}


text:
package com.braingumbo.examp.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class Zombie extends Monster implements ApplicationContextAware, BeanNameAware {
	private String speed = "";
	private boolean undead;
	private ApplicationContext applicationContext;
	private String springBeanName;
	public Zombie() {
		super("zombie", "undefined zombie", null, null);
		setSpeed("");
		this.undead = false;
	}
	public Zombie(String name, String speed, Tradition tradition, Location location, boolean undead) {
		super("zombie", name, tradition, location);
		setSpeed(speed);
		this.undead = undead;
	}

	public boolean isUndead() {
		return undead;
	}
	public void setUndead(boolean undead) {
		this.undead = undead;
	}
	public String getSpeed() {
		return speed;
	}
	public void setSpeed(String speed) {
		this.speed = speed;
	}

	@Override
	public void dump() {
		System.out.println("\n-------------------------------");
		System.out.println("name: " + getName());
		System.out.println("type: " + getType());
		System.out.println("speed: " + getSpeed());
		System.out.println("is undead?: " + undead);
		System.out.println("tradition: " + getTradition().getAuthor() + " - " + getTradition().getDescription());
		System.out.println("location: " + getLocation().getGeographicLocation() + " - " + getLocation().getPlanet());
		System.out.println("-------------------------------\n");
	}
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
		System.out.println("-> start Zombie:setApplicationContext()");
		System.out.println("applicationContext.getDisplayName(): " + this.applicationContext.getDisplayName());
		System.out.println("<- end Zombie:setApplicationContext()");
	}
	@Override
	public void setBeanName(String springBeanName) {
		this.springBeanName = springBeanName;
		System.out.println("-> start Zombie:setBeanName()");
		System.out.println("springBeanName : " + this.springBeanName);
		System.out.println("<- end Zombie:setBeanName()");
	}
}


text:
package com.karcompany.heybeach.views.adapters;

/**
 * Created by pvkarthik on 2017-02-22.
 *
 * Recycler view adapter which displays beach list data.
 */

import android.graphics.drawable.ColorDrawable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.karcompany.heybeach.R;
import com.karcompany.heybeach.cache.ImageFetcher;
import com.karcompany.heybeach.cache.ImageWorker;
import com.karcompany.heybeach.models.BeachMetaData;
import com.karcompany.heybeach.networking.ApiRepo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class BeachListAdapter extends RecyclerView.Adapter<BeachListItemViewHolder> {

	private Map<String, BeachMetaData> mBeachDataMap;
	private List<String> mBeachIdList;

	private boolean mIsDataLoadFinished;

	private int VIEW_TYPE_ITEM = 1;
	private int VIEW_TYPE_PROGRESS = 2;

	private ImageFetcher mImageFetcher;

	private int mColorIndex = 0;

	private List<Integer> mColourList;

	public BeachListAdapter(ImageFetcher imageFetcher) {
		mBeachDataMap = new LinkedHashMap<>();
		mBeachIdList = new ArrayList<>(4);
		mImageFetcher = imageFetcher;
		mColourList = new ArrayList<>(4);
		mColourList.add(R.color.accent_brand);
		mColourList.add(R.color.neutral_medium_soft_dark);
		mColourList.add(R.color.light_brand);
		mColourList.add(R.color.medium_brand);
	}

	@Override
	public BeachListItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
		View view;
		if(viewType == VIEW_TYPE_ITEM) {
			view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_beach_row_item, parent, false);
		} else {
			view = LayoutInflater.from(parent.getContext()).inflate(R.layout.loading_progress, parent, false);
		}
		return new BeachListItemViewHolder(view);
	}

	@Override
	public void onBindViewHolder(final BeachListItemViewHolder holder, int position) {
		if(getItemViewType(position) == VIEW_TYPE_ITEM) {
			holder.imageTitleTxtView.setText("");
			if (position < mBeachIdList.size()) {
				BeachMetaData beachItem = mBeachDataMap.get(mBeachIdList.get(position));
				if (beachItem != null) {
					if (!TextUtils.isEmpty(beachItem.getName())) {
						holder.imageTitleTxtView.setText(beachItem.getName());
					}
					if (!TextUtils.isEmpty(beachItem.getUrl())) {
						ViewCompat.setBackground(holder.imageImgView, new ColorDrawable(ContextCompat.getColor(holder.itemView.getContext(), getColorIndex())));
						// Finally load the image asynchronously into the ImageView, this also takes care of
						// setting a placeholder image while the background thread runs
						mImageFetcher.loadImage(ApiRepo.getBaseUrl(beachItem.getUrl()), holder.imageImgView, new ImageWorker.OnImageLoadedListener() {
							@Override
							public void onImageLoaded(boolean success) {
								ViewCompat.setBackground(holder.imageImgView, null);
							}
						});
					}
				}
			}
		} else {
			StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
			layoutParams.setFullSpan(true);
		}
	}

	@Override
	public void onViewRecycled(BeachListItemViewHolder holder) {
		if(holder.imageImgView != null) {

		}
		super.onViewRecycled(holder);
	}

	@Override
	public int getItemCount() {
		if(mIsDataLoadFinished) {
			return mBeachIdList.size();
		} else {
			return mBeachIdList.size() + 1;
		}
	}

	public void clearData() {
		mBeachIdList.clear();
		mBeachDataMap.clear();
	}

	@Override
	public int getItemViewType(int position) {
		if(mIsDataLoadFinished)
			return VIEW_TYPE_ITEM;
		if(position < mBeachIdList.size()){
			return VIEW_TYPE_ITEM;
		}
		return VIEW_TYPE_PROGRESS;
	}

	public boolean isLoadingPos(int position) {
		return getItemViewType(position) == VIEW_TYPE_PROGRESS;
	}

	public boolean isDataLoadFinished() {
		return mIsDataLoadFinished;
	}

	public void setDataFinished() {
		mIsDataLoadFinished = true;
		notifyItemRemoved(mBeachIdList.size());
	}

	public void addData(List<BeachMetaData> beachList) {
		if (beachList != null) {
			for (BeachMetaData beachItem : beachList) {
				mBeachDataMap.put(beachItem.getId(), beachItem);
			}
			int oldSize = mBeachIdList.size();
			mBeachIdList.clear();
			mBeachIdList.addAll(mBeachDataMap.keySet());
			int newSize = mBeachIdList.size();
			if (oldSize > 0) {
				notifyItemRangeInserted(oldSize, newSize - oldSize);
			} else {
				notifyDataSetChanged();
			}
		}
	}

	private synchronized int getColorIndex() {
		int colour = mColourList.get(mColorIndex);
		mColorIndex++;
		if (mColorIndex == mColourList.size()) mColorIndex = 0;
		return colour;
	}

	public ArrayList<BeachMetaData> getBeachList() {
		ArrayList<BeachMetaData> beachList = new ArrayList<>();
		Iterator<Map.Entry<String, BeachMetaData>> iterator = mBeachDataMap.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<String, BeachMetaData> entry = iterator.next();
			beachList.add(entry.getValue());
		}
		return beachList;
	}
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.wliu</groupId>
  <artifactId>org.wliu.hdfs_hdp210</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
  	<dependency>
  		<groupId>org.apache.hadoop</groupId>
  		<artifactId>hadoop-hdfs</artifactId>
  		<version>2.6.0</version>
  	</dependency>
  	<dependency>
  		<groupId>junit</groupId>
  		<artifactId>junit</artifactId>
  		<version>4.12</version>
  		<scope>test</scope>
  	</dependency>
  	<dependency>
  		<groupId>org.apache.hadoop</groupId>
  		<artifactId>hadoop-common</artifactId>
  		<version>2.6.0</version>
  	</dependency>
  </dependencies>
</project>


text:
@implementation UIColor (Addition)

-(UIColor*)lc_toColor:(UIColor*)color ratio:(CGFloat)ratio{
    if (ratio > 1)
        ratio = 1;
    if (ratio < 0)
        ratio = 0;

    const CGFloat* components1 =  CGColorGetComponents(color.CGColor);
    const CGFloat* components2 = CGColorGetComponents(self.CGColor);

    CGFloat r = components1[0] * ratio + components2[0]*(1 - ratio);
    CGFloat g = components1[1] * ratio + components2[1]*(1 - ratio);
    CGFloat b = components1[2] * ratio + components2[2]*(1 - ratio);

    return [UIColor colorWithRed:r green:g blue:b alpha:1];
}

+(UIColor*)lc_colorWithRGB:(NSString*)rgbStr alpha:(float) alpha{
    if (rgbStr && rgbStr.length == 6 && alpha >= 0) {
        long red = strtoul([[rgbStr substringWithRange:NSMakeRange(0, 2)] UTF8String], 0, 16);
        long green = strtoul([[rgbStr substringWithRange:NSMakeRange(2, 2)] UTF8String], 0, 16);
        long blue = strtoul([[rgbStr substringWithRange:NSMakeRange(4, 2)] UTF8String], 0, 16);
        [UIColor colorWithRed:red green:green blue:blue alpha:MIN(1, alpha)];
    }else if(rgbStr.length == 8){
        long red = strtoul([[rgbStr substringWithRange:NSMakeRange(2, 2)] UTF8String], 0, 16);
        long green = strtoul([[rgbStr substringWithRange:NSMakeRange(4, 2)] UTF8String], 0, 16);
        long blue = strtoul([[rgbStr substringWithRange:NSMakeRange(5, 2)] UTF8String], 0, 16);
        [UIColor colorWithRed:red green:green blue:blue alpha:MIN(1, alpha)];
    }
    return [UIColor clearColor];
}

+(UIColor*)lc_randomColor{
    return [UIColor colorWithRed:arc4random_uniform(256)/255.f green:arc4random_uniform(256)/255.f blue:arc4random_uniform(256)/255.f alpha:1];
}
@end


text:
@implementation SOZOJulianDateConverter

#pragma mark - Public Interface

+ (NSDate *)dateFromJulianYear:(int)year month:(int)month day:(int)day {
    [self checkForZeroYear:year];

    SOZOJulianDate *julian = [[SOZOJulianDate alloc] initWithYear:year month:month day:day];
    SOZOGregorianDate *gregorian = [SOZOGregorianDate dateFromFixed:[julian daysSinceEpoch]];

    NSDateComponents *components = [[NSDateComponents alloc] init];

    if (year < 0) {
        //Compensate for missing year 0.
        [components setYear:[gregorian year] + 1];
    } else  {
        [components setYear:[gregorian year]];
    }

    [components setDay:[gregorian day]];
    [components setMonth:[gregorian month]];
    [components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    [components setHour:12];
    [components setMinute:0];
    [components setSecond:0];

    NSCalendar *gregcal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *converted = [gregcal dateFromComponents:components];

    return converted;
}

+ (SOZOJulianDateComponents)componentsFromDate:(NSDate *)date {
    SOZOGregorianDate *gregorianDate = [[SOZOGregorianDate alloc] initWithDate:date];
    SOZOJulianDate *julianDate = [SOZOJulianDate dateFromFixed:gregorianDate.daysSinceEpoch];

    SOZOJulianDateComponents julianComponents;
    julianComponents.year = julianDate.year;
    julianComponents.month = julianDate.month;
    julianComponents.day = julianDate.day;
    return julianComponents;
}

#pragma mark - Internal Methods

+ (void)checkForZeroYear:(int)year {
    if (year == 0) {
        [NSException raise:@"SOZOJulianZeroYearException"
                    format:@"The Julian calendar does not have a year zero."];
    }
}

@end


text:
'''Virtual datasets: the 'Percival Frame Builder' use case.

https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf
'''
import h5py

in_key = 'data' # where is the data at the input?
dtype = h5py.File('raw_file_1.h5')['data'].dtype
outshape = (799,2000,2000)

# Virtual target is a representation of the output dataset
layout = h5py.VirtualLayout(shape=outshape, dtype=dtype)

# Sources represent the input datasets
vsource1 = h5py.VirtualSource('raw_file_1.h5', 'data', shape=(200, 2000, 2000))
vsource2 = h5py.VirtualSource('raw_file_2.h5', 'data', shape=(200, 2000, 2000))
vsource3 = h5py.VirtualSource('raw_file_3.h5', 'data', shape=(200, 2000, 2000))
vsource4 = h5py.VirtualSource('raw_file_4.h5', 'data', shape=(199, 2000, 2000))

# Map the inputs into the virtual dataset
layout[0:799:4, :, :] = vsource1
layout[1:799:4, :, :] = vsource2
layout[2:799:4, :, :] = vsource3
layout[3:799:4, :, :] = vsource4

# Create an output file
with h5py.File('full_time_series.h5', 'w', libver='latest') as f:
    f.create_virtual_dataset(in_key, layout, fillvalue=0x1)


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [WebAudio](./puppeteer.protocol.webaudio.md) > [BaseAudioContext](./puppeteer.protocol.webaudio.baseaudiocontext.md) > [contextId](./puppeteer.protocol.webaudio.baseaudiocontext.contextid.md)

## Protocol.WebAudio.BaseAudioContext.contextId property

<b>Signature:</b>

```typescript
contextId: GraphObjectId;
```


text:
oled_cli tool allows to use oled display, connected to raspberry pi, directly from command line.

## Compilation

compile oled_cli tool on your raspberry pi with the command
> make

## Running

example of running oled_cli tool for i2c display
> sudo modprobe i2c-dev<br>
> ./oled_cli i2c 1 0x3c ssd1306_128x64

now you're able to send commands to oled display from command line

> rect 10,10,20,30


text:
import Controls from './classes/Controls.js';
import Game     from './classes/Game';

let controls = new Controls();
let game     = new Game(controls);

let lastFrameTime = 0;

let frameCounter = 0;

/**
 * Main game loop
 * @param {number} currentFrameTime Time in seconds
 * @returns {void}
 */
function gameLoop(currentFrameTime) {
    requestAnimationFrame(gameLoop);
    let deltaT = currentFrameTime - lastFrameTime;
    lastFrameTime = currentFrameTime;

    if(controls.enabled) {
        controls.update();
        game.update(deltaT / 1000);
        game.draw();
    } else if(frameCounter % 10 == 0) {
        game.draw();
    }

    frameCounter++;
}

// eslint-disable-next-line no-console
console.log('⛵ Welcome to make-sail! 🌊');
gameLoop();


text:
<bill session="110" type="sr" number="361" updated="2009-01-09T20:43:00-05:00">
	<status><vote date="1193803200" datetime="2007-10-31" where="s" result="pass" how="by Unanimous Consent" roll=""/></status>

	<introduced date="1193803200" datetime="2007-10-31"/>
	<titles>
		<title type="official" as="introduced">A resolution to permit the collection of donations in Senate buildings to be sent to United States military personnel on active duty overseas participating in or in support of Operation Iraqi Freedom, Operation Enduring Freedom, and the war on terrorism.</title>
	</titles>
	<sponsor id="300072"/>
	<cosponsors>
		<cosponsor id="300082" joined="2007-10-31"/>
		<cosponsor id="300007" joined="2007-10-31"/>
	</cosponsors>
	<actions>
		<vote date="1193803200" how="by Unanimous Consent" datetime="2007-10-31" where="s" type="vote" result="pass" ><text>Submitted in the Senate, considered, and agreed to without amendment by Unanimous Consent.</text><reference label="consideration" ref="CR S13645"/><reference label="text as passed Senate" ref="CR S13645"/><reference label="text of measure as introduced" ref="CR S13641"/></vote>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	10/31/2007--Passed Senate without amendment. (This measure has not been amended since it was introduced. The summary of that version is repeated here.) Authorizes a Senator, officer, or employee of the Senate to: (1) collect from another such individual, within Senate buildings, nonmonetary donations to be sent to U.S. military personnel on active duty overseas participating in or in support of Operation Iraqi Freedom, Operation Enduring Freedom, and the war on terrorism; and (2) work with a nonprofit organization with respect to the delivery of such donations.<br/>
	</summary>
</bill>


text:
using Sprache;
using System;
using System.Collections.Generic;
using System.Linq;

namespace MMIO.Bvh
{
    public enum ChannelType
    {
        Xposition,
        Yposition,
        Zposition,
        Zrotation,
        Yrotation,
        Xrotation,
    }

    public class Node
    {
        public String Name { get; private set; }
        public Vector3 Offset { get; private set; }
        public ChannelType[] Channels { get; private set; }
        public List<Node> Children { get; private set; }

        public Node(String name, Vector3 offset, IEnumerable<ChannelType> channels = null, IEnumerable<Node> children = null)
        {
            Name = name;
            Offset = offset;
            Channels = channels != null ? channels.ToArray() : new ChannelType[] { };
            Children = children != null ? children.ToList() : new List<Node>();
        }

        public override string ToString()
        {
            return String.Format("{0}[{1}, {2}, {3}]{4}", Name, Offset.X, Offset.Y, Offset.Z, String.Join(", ", Channels));
        }

        public IEnumerable<T> Traverse<T>(Func<Node, int, T> pred, int level = 0)
        {
            yield return pred(this, level);

            foreach (var child in Children)
            {
                foreach(var x in child.Traverse(pred, level + 1))
                {
                    yield return x;
                }
            }
        }
    }

    public class BvhMotion
    {
        public Node Root { get; set; }
        public Dictionary<String, String> MotionProperties { get; set; }
        public Single[][] Frames { get; set; }

        public Single FrameTime
        {
            get
            {
                return Convert.ToSingle(MotionProperties["Frame Time"]);
            }
        }

        public Int32 Fps
        {
            get
            {
                return (Int32)(1.0f / FrameTime);
            }
        }
    }

    public static class BvhParse
    {
        public static Parser<String> Exponent = from _ in Parse.Char('E')
                                                from sign in Parse.Chars("+-")
                                                from num in Parse.Number
                                                select String.Format("E{0}{1}", sign, num);

        public static Parser<Single> FloatEx = from negative in Parse.Char('-').Optional().Select(x => x.IsDefined ? x.Get().ToString() : "")
                                               from num in Parse.Decimal
                                               from exponent in Exponent.Optional().Select(x => x.IsDefined ? x.Get() : "")
                                               select Convert.ToSingle(negative + num + exponent);

        public static Parser<Vector3> Offset = from _ in Parse.String("OFFSET").Token()
                                               from x in FloatEx.Token().Select(n => Convert.ToSingle(n))
                                               from y in FloatEx.Token().Select(n => Convert.ToSingle(n))
                                               from z in FloatEx.Token().Select(n => Convert.ToSingle(n))
                                               select new Vector3
                                               {
                                                   X = x,
                                                   Y = y,
                                                   Z = z
                                               };

        public static Parser<IEnumerable<ChannelType>> Channels = from _ in Parse.String("CHANNELS").Token()
                                                                  from n in Parse.Number.Select(x => Convert.ToInt32(x))
                                                                  from channels in Parse.String("Xposition").Token().Return(ChannelType.Xposition)
                                                                      .Or(Parse.String("Yposition").Token().Return(ChannelType.Yposition))
                                                                      .Or(Parse.String("Zposition").Token().Return(ChannelType.Zposition))
                                                                      .Or(Parse.String("Xrotation").Token().Return(ChannelType.Xrotation))
                                                                      .Or(Parse.String("Yrotation").Token().Return(ChannelType.Yrotation))
                                                                      .Or(Parse.String("Zrotation").Token().Return(ChannelType.Zrotation))
                                                                      .Repeat(n)
                                                                  select channels
                                                                    ;

        public static Parser<Node> EndSite = from _ in Parse.String("End Site").Token()
                                             from open in Parse.Char('{').Token()
                                             from offset in Offset
                                             from close in Parse.Char('}').Token()
                                             select new Node("EndSite", offset);

        public static Parser<Node> Node(String prefix)
        {
            return from _ in Parse.String(prefix).Token()
                   from name in Parse.LetterOrDigit.Many().Token().Text()
                   from open in Parse.Char('{').Token()
                   from offset in Offset
                   from channels in Channels
                   from children in Node("JOINT").AtLeastOnce().Or(EndSite
                        // 型をIEnumerable<Node>にそろえる
                        .Select(x => new Node[] { x }))
                   from close in Parse.Char('}').Token()
                   select new Node(name, offset, channels, children)
                                        ;
        }

        static Parser<String> Line =
            from line in Parse.AnyChar.Except(Parse.Char((char)0x0a)).Many().Text()
            from _ in Parse.Char((Char)0x0a)
            select line;

        /*
        static Tuple<String, String> ToKV(String src)
        {
            var splited = src.Split(new[] { ':' }, 2);
            return Tuple.Create(splited[0].Trim(), splited[1].Trim());
        }
        */

        static Parser<Tuple<String, String>> MotionProperty =
            from key in Parse.AnyChar.Except(Parse.Char(':')).Many().Text()
            from colon in Parse.Char(':')
            from value in Parse.AnyChar.Except(Parse.Char((char)0x0a)).Many().Text()
            from _ in Parse.Char((char)0x0a)
            select Tuple.Create(key.Trim(), value.Trim())
            ;

        static Parser<Single[]> Frame =
            from line in Line
            select line.Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(x => {
                return Convert.ToSingle(x);
            }).ToArray()
            ;

        public static Parser<BvhMotion> Parser = from hierarchy in Parse.String("HIERARCHY").Token()
                                                 from root in Node("ROOT")
                                                 from motion in Parse.String("MOTION").Token()
                                                 from motionProperties in MotionProperty.Many().Select(x => x.ToDictionary(y => y.Item1, y=> y.Item2))
                                                 from frames in Frame.Repeat(Convert.ToInt32(motionProperties["Frames"]))
                                                 select new BvhMotion
                                                 {
                                                     Root=root,
                                                     MotionProperties=motionProperties,
                                                     Frames=frames.ToArray(),
                                                 };

        public static BvhMotion Execute(String text, bool getFrames)
        {
            return Parser.Parse(text);
        }
    }
}


text:
Summary for Data Mining
=========
Data Mining @ ETH, HS2016


text:
<?php

namespace OSS\Tests;

use OSS\Core\OssException;
use OSS\OssClient;

require_once __DIR__ . DIRECTORY_SEPARATOR . 'TestOssClientBase.php';

class OssClientBucketTest extends TestOssClientBase
{
    public function testBucketWithInvalidName()
    {
        try {
            $this->ossClient->createBucket("s");
            $this->assertFalse(true);
        } catch (OssException $e) {
            $this->assertEquals('"s"bucket name is invalid', $e->getMessage());
        }
    }

    public function testBucketWithInvalidACL()
    {
        try {
            $this->ossClient->createBucket($this->bucket, "invalid");
            $this->assertFalse(true);
        } catch (OssException $e) {
            $this->assertEquals('invalid:acl is invalid(private,public-read,public-read-write)', $e->getMessage());
        }
    }

    public function testBucket()
    {
        $this->ossClient->createBucket($this->bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE);

        $bucketListInfo = $this->ossClient->listBuckets();
        $this->assertNotNull($bucketListInfo);
        $bucketList = $bucketListInfo->getBucketList();
        $this->assertTrue(is_array($bucketList));
        $this->assertGreaterThan(0, count($bucketList));
        $this->ossClient->putBucketAcl($this->bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE);
        Common::waitMetaSync();
        $this->assertEquals($this->ossClient->getBucketAcl($this->bucket), OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE);

        $this->assertTrue($this->ossClient->doesBucketExist($this->bucket));
        $this->assertFalse($this->ossClient->doesBucketExist($this->bucket . '-notexist'));
    }
}


text:
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2021 Realm Inc.
//
// 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
//
// http://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.
//
////////////////////////////////////////////////////////////////////////////
import Realm from "realm";
import { useContext } from "react";

/**
 * Generates a `useRealm` hook given a RealmContext.  This allows access to the {@link Realm}
 * instance anywhere within the RealmProvider.
 *
 * @param RealmContext - The context containing the {@link Realm} instance
 * @returns useRealm - Hook that is used to gain access to the {@link Realm} instance
 */
export const createUseRealm = (RealmContext: React.Context<Realm | null>) => {
  /**
   * Returns the instance of the {@link Realm} configured by `createRealmContext`
   *
   * @example
   * ```
   * const realm = useRealm();
   * ```
   *
   * @returns a realm instance
   */
  return function useRealm(): Realm {
    // This is the context setup by `createRealmContext`
    const context = useContext(RealmContext);
    if (context === null) {
      throw new Error("Realm context not found.  Did you call useRealm() within a <RealmProvider/>?");
    }
    return context;
  };
};


text:
package ru.contextguide.campaign.textCampaign;

public enum TextCampaignSettingsGetEnum {
    ADD_METRICA_TAG,
    ADD_OPENSTAT_TAG,
    ADD_TO_FAVORITES,
    DAILY_BUDGET_ALLOWED,
    ENABLE_AREA_OF_INTEREST_TARGETING,
    ENABLE_AUTOFOCUS,
    ENABLE_BEHAVIORAL_TARGETING,
    ENABLE_EXTENDED_AD_TITLE,
    ENABLE_RELATED_KEYWORDS,
    ENABLE_SITE_MONITORING,
    EXCLUDE_PAUSED_COMPETING_ADS,
    MAINTAIN_NETWORK_CPC,
    REQUIRE_SERVICING,
    SHARED_ACCOUNT_ENABLED
}


text:
.PHONY: default build rebuild start test shell clean

default: build test

build:
	@docker-compose build

rebuild:
	@docker-compose build --no-cache

start:
	@docker-compose up

test:
	@docker-compose run web npm test

shell:
	@docker-compose run web bash

clean:
	@docker-compose rm -v


text:
/* Shows the SEED functional category hierarchy as a
 * collapsable/expandable bar chart
 *
 * Found a collapsable hierarcy example from Mike Bostock to follow:
 * https://gist.github.com/mbostock/1093025
 *
 * will adapt this to work with the KBase SEED annotations
 */

define (
	[
		'kbwidget',
		'bootstrap',
		'jquery',
		'narrativeConfig',
		'd3'
	], function(
		KBWidget,
		bootstrap,
		$,
		Config,
		d3
	) {

    return KBWidget({
        name: "KBaseSEEDFunctions",
        parent : kbaseAuthenticatedWidget,
        version: "1.0.0",

        wsUrl: Config.url('workspace'),

        options: {
            objNameOrId: null,
            wsNameOrId: null,
            objVer: null,
            loadingImage: Config.get('loading_gif'),
            kbCache:null,
            width:900
        },

        SEEDTree:{ "name":"Functional Categories", "count": 0, "children":[], "size":0, "x0":0, "y0":0 },
        subsysToGeneMap:[],
        maxCount:0,

        margin:{top: 30, right: 20, bottom: 30, left: 20},
        width: 920,
        barHeight : 20,
        barWidth:400,
        stepSize:8,
        svg:null,

        i : 0,
        duration : 400,
        root:null,

        tree:null,

        objName:"",
        wsName:"",

        /**
         * Initialize the widget.
         */

        init: function(options) {
            this._super(options);
            //this.render();

            return this;
        },

        /*
          I need to load the SEED subsystem ontology. I am going to use
          the "subsys.txt" file I found at:
                ftp.theseed.org/subsystems/subsys.txt

          Note that this file is updated weekly, but not versioned. It's
          possible that errors will arise because the subsystems assigned
          in the genome object are out of date relative to the current
          subsys.txt file.

          file format is:
          Level 1 \t Level 2 \t Level 3 \t Level 4\t Optional GO id \t Optional GO desc \n

          ontologyDepth is set to 4 for SEED

          SEED is not a strict heirarchy, some nodes have multiple parents
          I'm going to keep track of a nodes parents to map things right.

          to scale the graph, I'm going to keep track of the max count in the Level 1 of the
          hierarchy.

          maxCount - count in the largest Level 1 category

          loadSEEDHierarchy() function will parse file and populate the SEEDTree data structure
        */
        loadSEEDHierarchy: function() {
            var self = this;
            var ontologyDepth = 4; //this should be moved up to the global variables
            var nodeMap = {};

            var SEEDTree = self.SEEDTree;
            var subsysToGeneMap = self.subsysToGeneMap;
            var Level1 = [];

            //d3.text("assets/data/subsys.txt", function(text) {
            //d3.text("/static/subsys.txt", function(text) {
            d3.text("/modules/plugins/dataview/resources/data/subsys.txt", function(text) {
                var data = d3.tsv.parseRows(text);
                var totalGenesWithFunctionalRoles = 0;

                for (i = 0; i < data.length; i++) {
                    var geneCount = 0;
                    var nodeHierarchy = "";
                    var parentHierarchy = "Functional Categories";

                    if (subsysToGeneMap[data[i][3]] === undefined) {
                        // if barchart needs to only show the subsystems that have genes in this genome,
                        // uncomment the continue statement.
                        //continue;
                    } else {
                        geneCount = subsysToGeneMap[data[i][3]].length;
                        totalGenesWithFunctionalRoles += subsysToGeneMap[data[i][3]].length;
                    }

                    for (j = 0; j < ontologyDepth; j++) {

                        // some node names are an empty string "". I'm going to set these to
                        // a modified version of their parent node name
                        data[i][j] = (data[i][j] === "") ? "--- " + data[i][j-1] + " ---" : data[i][j];
                        nodeHierarchy = parentHierarchy + ":" + data[i][j];

                        // create new node for top level of hierarchy if it's not already defined.
                        if (j === 0) {
                            if (nodeMap[nodeHierarchy] === undefined) {
                                var node = { "name" : data[i][j], size : 0, "children" : [] };
                                SEEDTree.children.push(node);
                                nodeMap[nodeHierarchy] = node;
                                Level1[data[i][j]] = 0;
                            }
                            Level1[data[i][j]] += geneCount;

                        } else {
                            if (nodeMap[nodeHierarchy] === undefined) {
                                var node = { "name" : data[i][j], size : 0, "children" : [] };
                                nodeMap[parentHierarchy].children.push(node);
                                nodeMap[nodeHierarchy] = node;

                                if ( j === ontologyDepth - 1 && subsysToGeneMap[data[i][j]] !== undefined) {
                                    subsysToGeneMap[data[i][j]].forEach( function(f){
                                        var gene = { "name" : f, "size" : "" };
                                        node.children.push( gene );
                                    });
                                }
                            }
                        }
                        nodeMap[nodeHierarchy].size += geneCount;
                        parentHierarchy = nodeHierarchy;
                    }
                }

                if (totalGenesWithFunctionalRoles < 100) {
                    //console.log("No Functional Categories assigned, you can added them using the Narrative");
                    self.$elem.find("#mainview").append("No Functional Categories assigned, you can added them using the Narrative");
                } else {
                    // Set maxCount to scale bars
                    for (k in Level1) {
                        self.maxCount = self.maxCount > Level1[k] ? self.maxCount : Level1[k];
                    }

                    $.when(
                        self.SEEDTree.children.forEach(function(d) {
                            self.collapse(d) })
                        )
                    .done(
                        self.update( self.root = self.SEEDTree )
                        );
                }

            });
        },

        update: function(source) {

            var self = this;

            var nodes = self.tree.nodes(self.SEEDTree);

            var scale = d3.scale.linear().domain([0,this.maxCount]).range([0,275]);
            var height = Math.max(500, nodes.length * self.barHeight + self.margin.top + self.margin.bottom);
            var i = self.i;

            d3.selectAll("#mainview").select("svg").transition()
                .duration(self.duration)
                .attr("height", height);

            d3.select(self.frameElement).transition()
                .duration(self.duration)
                .style("height", height + "px");

            // Compute the "layout".
            nodes.forEach(function(n, i) {
                n.x = i * self.barHeight;
            });

            // Update the nodes…
            var node = self.svg.selectAll("g.KBSnode")
                .data(nodes, function(d) { return d.id || (d.id = ++self.i); });

            var nodeEnter = node.enter().append("g")
                .attr("class", "KBSnode")
                .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
                .style("opacity", 1e-6)
                .on("mouseover", function(d) {
                    d3.select(this).selectAll('text, rect')
                    .style('font-weight', 'bold')
                    .style('font-size', '90%')
                    .style('stroke-width', '3px');
                })
                .on("mouseout", function(d) {
                    d3.select(this).selectAll('text, rect')
                    .style('font-weight', 'normal')
                    .style('font-size', '80%')
                    .style('stroke-width', '1.5px');
                });

            // Enter any new nodes at the parent's previous position.
            nodeEnter.append("rect")
                .attr("y", -self.barHeight / 2)
                .attr("x", 300)
                .attr("height", self.barHeight)
                .attr("width", self.barWidth)
                .style("fill", self.color)
                .on("click", $.proxy(function(d) {self.click(d)}, self));

            nodeEnter.append("text")
                .attr("dy", 3.5)
                .attr("dx", 300 + 5.5)
                .text(function(d) { return d.name; });

            nodeEnter.append("rect")
                .attr("y", -self.barHeight / 2)
                .attr("x", function (d) { return 0 + 275 - scale(d.size) - d.depth * self.stepSize;} )
                .attr("height", self.barHeight)
                .attr("width", function (d) { return scale(d.size); })
                .style("fill", self.color)
                .on("click", $.proxy(function(d) {self.click(d)}, self));

            nodeEnter.append("text")
                .attr("dy", 3.5)
                .attr("x", 278)
                .text(function(d) { return d.name === "Functional Categories" ? "" : d.size; });

            // Transition nodes to their new position.
            nodeEnter.transition()
                .duration(self.duration)
                .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
                .style("opacity", 1);

            node.transition()
                .duration(self.duration)
                .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
                .style("opacity", 1)
                .select("rect")
                .style("fill", self.color);

            // Transition exiting nodes to the parent's new position.
            node.exit().transition()
                .duration(self.duration)
                .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
                .style("opacity", 1e-6)
                .remove();

            // Stash the old positions for transition.
            nodes.forEach(function(d) {
                d.x0 = d.x;
                d.y0 = d.y;
            });

        },

        // Toggle children on click.
        click: function(d) {

        // open window with gene landing page
        if (d.children === undefined || (d._children === null && d.children === null)) {
        var winPop = window.open("/#dataview/" + this.options.wsNameOrId + "/" + this.options.objNameOrId + "?sub=Feature&subid=" + d.name);
        }

        // expand tree
            if (d.children) {
                d._children = d.children;
                d.children = null;
            } else {
                d.children = d._children;
                d._children = null;
            }

            this.update(d);
        },

        color: function(d) {
        //return d._children ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c";
            return d._children ? "#c6dbef" : d.children ? "#3399ff" : "#ffffff";
        },

        collapse: function(d) {
            var self = this;
            if (d.children) {
                d._children = d.children;
                d._children.forEach( function(n) {self.collapse(n)});
                d.children = null;
            }
        },

        getData: function() {
            return {title:"Functional Categories ",id:this.options.objNameOrId, workspace:this.options.wsNameOrId};
        },

        render: function() {
            var margin =  this.margin,
                width = this.width;

            this.tree = d3.layout.tree().nodeSize([0, this.stepSize]);

            var $mainview = $('<div id="mainview">').css({'overflow-x' : 'scroll'});
            this.$elem.append($mainview);

            this.svg = d3.select($mainview[0]).append("svg")
                    .attr("width", width + margin.left + margin.right)
                    .append("g")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

            var SEEDTree = this.SEEDTree;
            var subsysToGeneMap = this.subsysToGeneMap;

            var obj = {"ref" : this.options.wsNameOrId + "/" + this.options.objNameOrId };
            var prom;

            if (this.options.kbCache) {
                prom = this.options.kbCache.req('ws', 'get_objects', [obj]);
            } else {
                prom = this.wsClient.get_objects([obj]);
            }
            //var prom = this.options.kbCache.req('ws', 'get_objects', [obj]);

            $.when(prom).fail($.proxy(function(error) {
                //this.renderError(error); Need to define this function when I have time
                console.log(error);
            }, this));

            $.when(prom).done($.proxy(function(genome) {
                var genomeObj = genome[0].data;

                /*
                    First I am going to iterate over the Genome Typed Object and
                    create a mapping of the assigned functional roles (by SEED) to
                    an array of genes with those roles.

                    subsysToGeneMap [ SEED Role ] = Array of Gene Ids
                */

                genomeObj.features.forEach( function(f){

                    // Each function can have multiple genes, creating mapping of function to list of gene ids
                    if (subsysToGeneMap[f["function"]] === undefined) {subsysToGeneMap[f["function"]] = [];}
                    subsysToGeneMap[f["function"]].push(f["id"]);

                    // Not sure if this is necessary, but I'm going to keep track of the number of genes with
                    // SEED assigned functions in this count variable.
                    SEEDTree.count++;
                });

                this.loadSEEDHierarchy();

            }, this));

        },

        loggedInCallback: function(event, auth) {
            this.authToken = auth;
            this.wsClient = new Workspace(this.wsUrl, this.authToken);
            this.render();
            return this;
        },

        loggedOutCallback: function(event, auth) {
            this.authToken = null;
            this.wsClient = null;
            return this;
        }

    });
});


text:
namespace Microsoft.Azure.Management.HealthcareApis.Models
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Workspaces resource specific properties.
    /// </summary>
    public partial class WorkspaceProperties : IResource
    {
        /// <summary>
        /// Initializes a new instance of the WorkspaceProperties class.
        /// </summary>
        public WorkspaceProperties()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the WorkspaceProperties class.
        /// </summary>
        /// <param name="provisioningState">The provisioning state. Possible
        /// values include: 'Deleting', 'Succeeded', 'Creating', 'Accepted',
        /// 'Verifying', 'Updating', 'Failed', 'Canceled', 'Deprovisioned',
        /// 'Moving', 'Suspended', 'Warned', 'SystemMaintenance'</param>
        /// <param name="privateEndpointConnections">The list of private
        /// endpoint connections that are set up for this resource.</param>
        /// <param name="publicNetworkAccess">Control permission for data plane
        /// traffic coming from public networks while private endpoint is
        /// enabled. Possible values include: 'Enabled', 'Disabled'</param>
        public WorkspaceProperties(string provisioningState = default(string), IList<PrivateEndpointConnection> privateEndpointConnections = default(IList<PrivateEndpointConnection>), string publicNetworkAccess = default(string))
        {
            ProvisioningState = provisioningState;
            PrivateEndpointConnections = privateEndpointConnections;
            PublicNetworkAccess = publicNetworkAccess;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the provisioning state. Possible values include:
        /// 'Deleting', 'Succeeded', 'Creating', 'Accepted', 'Verifying',
        /// 'Updating', 'Failed', 'Canceled', 'Deprovisioned', 'Moving',
        /// 'Suspended', 'Warned', 'SystemMaintenance'
        /// </summary>
        [JsonProperty(PropertyName = "provisioningState")]
        public string ProvisioningState { get; set; }

        /// <summary>
        /// Gets the list of private endpoint connections that are set up for
        /// this resource.
        /// </summary>
        [JsonProperty(PropertyName = "privateEndpointConnections")]
        public IList<PrivateEndpointConnection> PrivateEndpointConnections { get; private set; }

        /// <summary>
        /// Gets or sets control permission for data plane traffic coming from
        /// public networks while private endpoint is enabled. Possible values
        /// include: 'Enabled', 'Disabled'
        /// </summary>
        [JsonProperty(PropertyName = "publicNetworkAccess")]
        public string PublicNetworkAccess { get; set; }

    }
}