<commit_before>"use strict";
(function(window) {
    function Moon(opts) {
        var _el = opts.el;
        var _data = opts.data;
        var _methods = opts.methods;
        var directives = {};
        var self = this;
        this.$el = document.querySelector(_el);
        this.components = opts.components;
        this.dom = {type: this.$el.nodeName, children: [], node: this.$el};

        // Change state when $data is changed
        Object.defineProperty(this, '$data', {
            get: function() {
                return _data;
            },
            set: function(value) {
                _data = value;
                this.build(this.dom.children);
            }
        });

        /**
        * Converts attributes into key-value pairs
        * @param {Node} node
        * @return {Object} Key-Value pairs of Attributes
        */
        var extractAttrs = function(node) {
          var attrs = {};
          if(!node.attributes) return attrs;
          var rawAttrs = node.attributes;
          for(var i = 0; i < rawAttrs.length; i++) {
            attrs[rawAttrs[i].name] = rawAttrs[i].value
          }

          return attrs;
        }

        /**
        * Compiles a template with given data
        * @param {String} template
        * @param {Object} data
        * @return {String} Template with data rendered
        */
        var compileTemplate = function(template, data) {
          var code = template,
              re = /{{([A-Za-z0-9_.]+)}}/gi;
          code.replace(re, function(match, p) {
            code = code.replace(match, "` + data." + p + " + `");
          });
          var compile = new Function("data", "var out = `" + code + "`; return out");
          return compile(data);
        }

        /**
        * Creates an object to be used in a Virtual DOM
        * @param {String} type
        * @param {Array} children
        * @param {String} val
        * @param {Object} props
        * @param {Node} node
        * @return {Object} Object usable in Virtual DOM
        */
        this.createElement = function(type, children, val, props, node) {
          return {type: type, children: children, val: val, props: props, node: node};
        }

        /**
        * Create Elements Recursively For all Children
        * @param {Array} children
        * @return {Array} Array of elements usable in Virtual DOM
        */
        this.recursiveChildren = function(children) {
          var recursiveChildrenArr = [];
          for(var i = 0; i < children.length; i++) {
            var child = children[i];
            recursiveChildrenArr.push(this.createElement(child.nodeName, this.recursiveChildren(child.childNodes), child.textContent, extractAttrs(child), child));
          }
          return recursiveChildrenArr;
        }

        /**
        * Creates Virtual DOM
        * @param {Node} node
        */
        this.createVirtualDOM = function(node) {
          var vdom = this.createElement(node.nodeName, this.recursiveChildren(node.childNodes), node.textContent, extractAttrs(node), node);
          this.dom = vdom;
        }

        /**
        * Turns Custom Components into their Corresponding Templates
        */
        this.componentsToHTML = function() {
          for(var component in this.components) {
            var componentsFound = document.getElementsByTagName(component);
            for(var i = 0; i < componentsFound.length; i++) {
              var componentFound = componentsFound[i];
              var componentProps = extractAttrs(componentFound);
              var componentDummy = document.createElement('div');
              componentDummy.innerHTML = this.components[component].template;
              componentDummy = componentDummy.firstChild;

              for(var attr in componentProps) {
                componentDummy.setAttribute(attr, componentProps[attr]);
              }

              componentFound.outerHTML = componentDummy.outerHTML;
            }
          }
        }

        /**
        * Sets Value in Data
        * @param {String} key
        * @param {String} val
        */
        this.set = function(key, val) {
          this.$data[key] = val;
          this.build(this.dom.children);
        }

        /**
        * Gets Value in Data
        * @param {String} key
        * @return {String} Value of key in data
        */
        this.get = function(key) {
          return this.$data[key];
        }

        /**
        * Makes an AJAX Request
        * @param {String} method
        * @param {String} url
        * @param {Object} params
        * @param {Function} cb
        */
        this.ajax = function(method, url, params, cb) {
          var xmlHttp = new XMLHttpRequest();
          method = method.toUpperCase();
          if(typeof params === "function") {
            cb = params;
          }
          var urlParams = "?";
          if(method === "POST") {
            http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            for(var param in params) {
              urlParams += param + "=" + params[param] + "&";
            }
          }
          xmlHttp.onreadystatechange = function() {
          if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            cb(JSON.parse(xmlHttp.responseText));
          }
          xmlHttp.open(method, url, true);
          xmlHttp.send(method === "POST" ? urlParams : null);
        }

        /**
        * Calls a method
        * @param {String} method
        */
        this.method = function(method) {
          _methods[method]();
        }

        // Directive Initialization
        this.directive = function(name, action) {
          directives["m-" + name] = action;
        }

        // Default Directives
        directives["m-if"] = function(el, val, vdom) {
          var evaluated = new Function("return " + val);
          if(!evaluated()) {
            el.textContent = "";
          } else {
            el.textContent = compileTemplate(vdom.val, self.$data);
          }
        }

        directives["m-on"] = function(el, val, vdom) {
          var splitVal = val.split(":");
          var eventToCall = splitVal[0];
          var methodToCall = splitVal[1];
          el.addEventListener(eventToCall, function() {
            self.method(methodToCall);
          });
          el.removeAttribute("m-on");
          delete vdom.props["m-on"];
        }

        /**
        * Builds the DOM With Data
        * @param {Array} children
        */
        this.build = function(children) {
          for(var i = 0; i < children.length; i++) {
            var el = children[i];

            if(el.type === "#text") {
              el.node.textContent = compileTemplate(el.val, this.$data);
            } else if(el.props) {
              for(var prop in el.props) {
                var propVal = el.props[prop];
                var compiledProperty = compileTemplate(propVal, this.$data);
                var directive = directives[prop];
                if(directive) {
                  directive(el.node, compiledProperty, el);
                }

                el.node.setAttribute(prop, compiledProperty);
              }
            }

            this.build(el.children);
          }
        }

        // Initialize 🎉
        this.componentsToHTML();
        this.createVirtualDOM(this.$el);
        this.build(this.dom.children);
    }

    window.Moon = Moon;
    window.$ = function(el) {
      el = document.querySelectorAll(el);
      return el.length === 1 ? el[0] : el;
    }

})(window);
<commit_msg>new if statement<commit_after>"use strict";
(function(window) {
    function Moon(opts) {
        var _el = opts.el;
        var _data = opts.data;
        var _methods = opts.methods;
        var directives = {};
        var self = this;
        this.$el = document.querySelector(_el);
        this.components = opts.components;
        this.dom = {type: this.$el.nodeName, children: [], node: this.$el};

        // Change state when $data is changed
        Object.defineProperty(this, '$data', {
            get: function() {
                return _data;
            },
            set: function(value) {
                _data = value;
                this.build(this.dom.children);
            }
        });

        /**
        * Converts attributes into key-value pairs
        * @param {Node} node
        * @return {Object} Key-Value pairs of Attributes
        */
        var extractAttrs = function(node) {
          var attrs = {};
          if(!node.attributes) return attrs;
          var rawAttrs = node.attributes;
          for(var i = 0; i < rawAttrs.length; i++) {
            attrs[rawAttrs[i].name] = rawAttrs[i].value
          }

          return attrs;
        }

        /**
        * Compiles a template with given data
        * @param {String} template
        * @param {Object} data
        * @return {String} Template with data rendered
        */
        var compileTemplate = function(template, data) {
          var code = template,
              re = /{{([A-Za-z0-9_.]+)}}/gi;
          code.replace(re, function(match, p) {
            code = code.replace(match, "` + data." + p + " + `");
          });
          var compile = new Function("data", "var out = `" + code + "`; return out");
          return compile(data);
        }

        /**
        * Creates an object to be used in a Virtual DOM
        * @param {String} type
        * @param {Array} children
        * @param {String} val
        * @param {Object} props
        * @param {Node} node
        * @return {Object} Object usable in Virtual DOM
        */
        this.createElement = function(type, children, val, props, node) {
          return {type: type, children: children, val: val, props: props, node: node};
        }

        /**
        * Create Elements Recursively For all Children
        * @param {Array} children
        * @return {Array} Array of elements usable in Virtual DOM
        */
        this.recursiveChildren = function(children) {
          var recursiveChildrenArr = [];
          for(var i = 0; i < children.length; i++) {
            var child = children[i];
            recursiveChildrenArr.push(this.createElement(child.nodeName, this.recursiveChildren(child.childNodes), child.textContent, extractAttrs(child), child));
          }
          return recursiveChildrenArr;
        }

        /**
        * Creates Virtual DOM
        * @param {Node} node
        */
        this.createVirtualDOM = function(node) {
          var vdom = this.createElement(node.nodeName, this.recursiveChildren(node.childNodes), node.textContent, extractAttrs(node), node);
          this.dom = vdom;
        }

        /**
        * Turns Custom Components into their Corresponding Templates
        */
        this.componentsToHTML = function() {
          for(var component in this.components) {
            var componentsFound = document.getElementsByTagName(component);
            for(var i = 0; i < componentsFound.length; i++) {
              var componentFound = componentsFound[i];
              var componentProps = extractAttrs(componentFound);
              var componentDummy = document.createElement('div');
              componentDummy.innerHTML = this.components[component].template;
              componentDummy = componentDummy.firstChild;

              for(var attr in componentProps) {
                componentDummy.setAttribute(attr, componentProps[attr]);
              }

              componentFound.outerHTML = componentDummy.outerHTML;
            }
          }
        }

        /**
        * Sets Value in Data
        * @param {String} key
        * @param {String} val
        */
        this.set = function(key, val) {
          this.$data[key] = val;
          this.build(this.dom.children);
        }

        /**
        * Gets Value in Data
        * @param {String} key
        * @return {String} Value of key in data
        */
        this.get = function(key) {
          return this.$data[key];
        }

        /**
        * Makes an AJAX Request
        * @param {String} method
        * @param {String} url
        * @param {Object} params
        * @param {Function} cb
        */
        this.ajax = function(method, url, params, cb) {
          var xmlHttp = new XMLHttpRequest();
          method = method.toUpperCase();
          if(typeof params === "function") {
            cb = params;
          }
          var urlParams = "?";
          if(method === "POST") {
            http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            for(var param in params) {
              urlParams += param + "=" + params[param] + "&";
            }
          }
          xmlHttp.onreadystatechange = function() {
          if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            cb(JSON.parse(xmlHttp.responseText));
          }
          xmlHttp.open(method, url, true);
          xmlHttp.send(method === "POST" ? urlParams : null);
        }

        /**
        * Calls a method
        * @param {String} method
        */
        this.method = function(method) {
          _methods[method]();
        }

        // Directive Initialization
        this.directive = function(name, action) {
          directives["m-" + name] = action;
        }

        // Default Directives
        directives["m-if"] = function(el, val, vdom) {
          var evaluated = new Function("if()");
          if(!evaluated()) {
            el.textContent = "";
          } else {
            el.textContent = compileTemplate(vdom.val, self.$data);
          }
        }

        directives["m-on"] = function(el, val, vdom) {
          var splitVal = val.split(":");
          var eventToCall = splitVal[0];
          var methodToCall = splitVal[1];
          el.addEventListener(eventToCall, function() {
            self.method(methodToCall);
          });
          el.removeAttribute("m-on");
          delete vdom.props["m-on"];
        }

        /**
        * Builds the DOM With Data
        * @param {Array} children
        */
        this.build = function(children) {
          for(var i = 0; i < children.length; i++) {
            var el = children[i];

            if(el.type === "#text") {
              el.node.textContent = compileTemplate(el.val, this.$data);
            } else if(el.props) {
              for(var prop in el.props) {
                var propVal = el.props[prop];
                var compiledProperty = compileTemplate(propVal, this.$data);
                var directive = directives[prop];
                if(directive) {
                  directive(el.node, compiledProperty, el);
                }

                el.node.setAttribute(prop, compiledProperty);
              }
            }

            this.build(el.children);
          }
        }

        // Initialize 🎉
        this.componentsToHTML();
        this.createVirtualDOM(this.$el);
        this.build(this.dom.children);
    }

    window.Moon = Moon;
    window.$ = function(el) {
      el = document.querySelectorAll(el);
      return el.length === 1 ? el[0] : el;
    }

})(window);
<|endoftext|>


<commit_before>'use strict';
angular.module('Trendicity')

// Creating a constant for post type values.
// This adds readability to our code later.
.constant('POST_TYPE', {
    'TRENDING': 'TR',
    'NEARBY': 'NB',
    'USER_FEED': 'UF',
    'LIKED': 'LP'
})
.controller('HomeCtrl', function (
  POST_TYPE,
  $rootScope,
  $scope,
  $ionicPopover,
  $ionicLoading,
  $ionicScrollDelegate,
  InstagramService,
  PostsService,
  GeolocationService,
  $state,
  FavoritesService,
  $q
) {
  var homeCtrl = this;

  // Since the current location is needed for all views, populate it now

/*    $scope.model =  PostsService.getModel();
    $scope.search = { value: POST_TYPE.NEARBY};

    $scope.getPosts = function(value, clearCurrentFavorite) {
      if (value === POST_TYPE.TRENDING) {
        PostsService.findPopularPosts();
      } else if (value === POST_TYPE.NEARBY) {
        GeolocationService.getCurrentPosition().then(function (position) {
          PostsService.findNearbyPosts(position.coords);
        });
      } else if (value === POST_TYPE.USER_FEED) {
        PostsService.findUserFeedPosts();
      } else if (value === POST_TYPE.LIKED) {
        PostsService.findLikedPosts();
      }
    };

    this.updatePosts = function (searchValue, isUserAction) {
      $scope.getPosts(searchValue, isUserAction);
      $scope.closePopover();
      $ionicScrollDelegate.scrollTop();
    };

    $scope.$watch('search.value', function(newValue) {
        // Triggered when user changes search value
        homeCtrl.updatePosts(newValue, true);
    });

    $ionicPopover.fromTemplateUrl('templates/search.html', {
      scope: $scope,
    }).then(function(popover) {
      $scope.popover = popover;
    });

    $scope.openPopover = function($event) {
      $scope.popover.show($event);
    };

    $scope.closePopover = function() {
      if ($scope.popover && $scope.popover.isShown()) {
        $scope.popover.hide();
      }
    };

    // Cleanup the popover when we're done with it!
    $scope.$on('$destroy', function() {
      if ($scope.popover) {
        $scope.popover.remove();
      }
    });

    //*** Register some event handlers
    $scope.$on('event:auth-logoutComplete', function() {
      console.log('handling event:auth-logoutComplete...');
      if ($scope.search.value == POST_TYPE.USER_FEED || $scope.search.value == POST_TYPE.LIKED_POST) {
          homeCtrl.clearPosts();
      }
    });*/
  }
);
<commit_msg>uncommented code in home.js and did some cleanup<commit_after>'use strict';
angular.module('Trendicity')

// Creating a constant for post type values.
// This adds readability to our code later.
.constant('POST_TYPE', {
    'TRENDING': 'TR',
    'NEARBY': 'NB',
    'USER_FEED': 'UF',
    'LIKED': 'LP'
})
.controller('HomeCtrl', function (
  POST_TYPE,
  $rootScope,
  $scope,
  $ionicPopover,
  $ionicLoading,
  $ionicScrollDelegate,
  InstagramService,
  PostsService,
  GeolocationService
) {
    var homeCtrl = this;

    $scope.model =  PostsService.getModel();
    $scope.search = { value: POST_TYPE.NEARBY};

    $scope.getPosts = function(value) {
      if (value === POST_TYPE.TRENDING) {
        PostsService.findPopularPosts();
      } else if (value === POST_TYPE.NEARBY) {
        $ionicLoading.show();
        GeolocationService.getCurrentPosition().then(function (position) {
          PostsService.findNearbyPosts(position.coords);
          $ionicLoading.hide();
        });
      } else if (value === POST_TYPE.USER_FEED) {
        PostsService.findUserFeedPosts();
      } else if (value === POST_TYPE.LIKED) {
        PostsService.findLikedPosts();
      }
    };

    this.updatePosts = function (searchValue) {
      $scope.getPosts(searchValue);
      $scope.closePopover();
      $ionicScrollDelegate.scrollTop();
    };

    $scope.$watch('search.value', function(newValue) {
        // Triggered when user changes search value
        homeCtrl.updatePosts(newValue);
    });

    $ionicPopover.fromTemplateUrl('templates/search.html', {
      scope: $scope,
    }).then(function(popover) {
      $scope.popover = popover;
    });

    $scope.openPopover = function($event) {
      $scope.popover.show($event);
    };

    $scope.closePopover = function() {
      if ($scope.popover && $scope.popover.isShown()) {
        $scope.popover.hide();
      }
    };

    // Cleanup the popover when we're done with it!
    $scope.$on('$destroy', function() {
      if ($scope.popover) {
        $scope.popover.remove();
      }
    });

    //*** Register some event handlers
    $scope.$on('event:auth-logoutComplete', function() {
      console.log('handling event:auth-logoutComplete...');
      if ($scope.search.value == POST_TYPE.USER_FEED || $scope.search.value == POST_TYPE.LIKED_POST) {
          homeCtrl.clearPosts();
      }
    });
  }
);
<|endoftext|>


<commit_before>'use strict';

const expect               = require('chai').expect;
const Promise              = require('bluebird');
const fs                   = require('fs');

const CompanionAssetEditor = require('../lib/companion_asset_editor');

const unlink = Promise.promisify(fs.unlink);

describe('CompanionAssetEditor', function() {
  let companion_file_name;
  let asset_editor;

  beforeEach(function() {
    companion_file_name = 'tests/data/companion_eder.unity3d';
    asset_editor = new CompanionAssetEditor(companion_file_name);
  });

  describe('.constructor', function() {
    it('sets the file name', function() {
      expect(asset_editor.file_name).to.equal(companion_file_name);
    });

    it('initializes companion_data', function() {
      expect(asset_editor.companion_data).to.deep.equal({});
    });
  });

  describe('#parseHeader', function() {
    it('parses the header file', function() {
      return asset_editor.parseHeader()
        .catch(function (err) {
          expect(err).to.not.exist;
        })
        .then(function(header) {
          expect(header).to.deep.equal({
            signature:                 'UnityRaw',
            format_version:            3,
            unity_version:             '3.x.x',
            generator_version:         '4.7.0f1',
            file_size:                 816036,
            header_size:               60,
            file_count:                1,
            bundle_count:              1,
            uncompressed_bundle_size:  815976,
            bundle_size:               815976,
            compressed_file_size:      816036,
            asset_header_size:         52,
          });
        });
    });
  });

  describe('#parseAssetBundle', function() {
    let offset;

    beforeEach(function() {
      offset = 60;
    });

    it('resolves the asset bundle metadata', function() {
      return asset_editor.parseAssetBundle(offset)
        .catch(function(err) {
          expect(err).to.not.exist;
        })
        .then(function(asset) {
          expect(asset).to.deep.equal({
            number_of_children:  1,
            name:                'CAB-1e289d4e73b9aa94a91e38b848e98389',
            header_size:         52,
            size:                815924,
            data_offset:         112,
          });
        });
    });
  });

  describe('#loadAssetTypeTree', function() {
    let offset;
    let expected;

    beforeEach(function(done) {
      offset = 112;

      return fs.readFile('./tests/data/eder_asset_tree.json', (err, file_buffer) => {
        expect(err).to.not.exist;

        expected = JSON.parse(file_buffer.toString());

        return done();
      });
    });

    it('resolves the asset data', function() {
      return asset_editor.loadAssetTypeTree(offset)
        .catch(function(err) {
          expect(err).to.not.exist;
        })
        .then(function(asset_data) {
          expect(asset_data).to.deep.equal(expected);
        });
    });
  });

  describe('#loadObjectInfo', function() {
    let offset;
    let number_of_objects;
    let object_data_offset;
    let is_long_ids;

    let expected;

    beforeEach(function() {
      offset             = 223126;
      number_of_objects  = 440;
      is_long_ids        = false;
      object_data_offset = 232160;
    });

    beforeEach(function(done) {
      return fs.readFile('./tests/data/eder_object_metadata.json', (err, file_buffer) => {
        expect(err).to.not.exist;

        expected = JSON.parse(file_buffer.toString());

        return done();
      });
    });

    it('loads object info', function() {
      return asset_editor.loadObjectInfo(number_of_objects, offset, object_data_offset, is_long_ids)
        .catch(function(err) {
         expect(err).to.not.exist();
        })
        .then(function(object_metadata) {
          expect(object_metadata).to.deep.equal(expected);
        });
    });
  });

  describe('#findCharicterSheetType', function() {
    let asset_tree;
    let expected_sheet_type;
    let offset;

    beforeEach(function() {
      offset = 112;

      return asset_editor.loadAssetTypeTree(offset)
        .catch(function(err) {
          expect(err).to.not.exist;
        })
        .then(function(result) {
          asset_tree = result;
        });
    });

    beforeEach(function(done) {
      return fs.readFile('./tests/data/eder_sheet_type.json', (err, file_buffer) => {
        expect(err).to.not.exist;

        expected_sheet_type = JSON.parse(file_buffer.toString());

        return done();
      });
    });

    it('searches the asset type tree for the charicter sheet', function() {
      return asset_editor.findCharicterSheetType(offset)
        .catch(function(err) {
          expect(err).to.not.exist();
        })
        .then(function(charicter_sheet_type) {
          expect(charicter_sheet_type.type).to.deep.equal(expected_sheet_type);
          expect(charicter_sheet_type.type_id).to.deep.equal("-20");
        });
    });
  });

  describe('#findCharicterSheetObjectInfo', function() {
    let object_metadata;
    let type_id;

    beforeEach(function() {
      type_id = "-20"
    });

    beforeEach(function() {
      let number_of_objects  = 440;
      let offset             = 223126;
      let object_data_offset = 232160 ;
      let is_long_ids        = false;

      return asset_editor.loadObjectInfo(number_of_objects, offset, object_data_offset, is_long_ids)
        //.catch(function(err) {
        //  expect(err).to.not.exist();
        //})
        .then(function(results) {
          object_metadata = results;
        });
    });

    it('gets the charicter sheet object metadata', function() {
      let charicter_sheet_object = asset_editor.findCharicterSheetObjectInfo(type_id, object_metadata);

      expect(charicter_sheet_object).to.deep.equal({
        object_id:               415,
        offset:                  807504,
        individual_data_offset:  575344,
        size:                    696,
        type_id:                 -20,
        class_id:                114,
        is_destroyed:            0,
      });
    });

  });

  describe('#readObjectData', function() {
    let object_metadata;
    let type;
    let type_id;
    let expected_sheet_data;

    beforeEach(function() {
      let offset = 112;

      return asset_editor.findCharicterSheetType(offset)
        .catch(function(err) {
          expect(err).to.not.exist;
        })
        .then(function(charicter_sheet_type) {
          type    = charicter_sheet_type;
          type_id = charicter_sheet_type.type_id;
        })
        .then(function() {
          let number_of_objects  = 440;
          let offset             = 223126;
          let object_data_offset = 232160 + 112;
          let is_long_ids        = false;

          return asset_editor.loadObjectInfo(number_of_objects, offset, object_data_offset, is_long_ids)
        })
        .then(function(results) {
          object_metadata = asset_editor.findCharicterSheetObjectInfo(type_id, results);
        });
    });

    beforeEach(function(done) {
      return fs.readFile('./tests/data/eder_sheet_data.json', (err, file_buffer) => {
        expect(err).to.not.exist;

        expected_sheet_data = JSON.parse(file_buffer.toString());

        return done();
      });
    });

    it('reads the object data', function() {
      return asset_editor.readObject(object_metadata, type)
        .catch(function(err) {
          expect(err).to.not.exist();
        })
        .then(function(object_data) {
          expect(object_data).to.deep.equal(expected_sheet_data);
        });
    });
  });

  describe('#getCharicterSheet', function() {
    it('gets the current charicter sheet stats', function() {
      return asset_editor.getCharicterSheet()
        .catch(function(err) {
          expect(err).to.not.exist();
        })
        .then(function(sheet) {
          expect(sheet).to.deep.equal({
            values: {
              might:         15,
              constitution:  16,
              dexterity:     11,
              perception:    12,
              intellect:     10,
              resolve:       11,
            },
            offsets: {
              might:         124,
              constitution:  128,
              dexterity:     132,
              perception:    136,
              intellect:     140,
              resolve:       144,
            },
            stat_total: 75,
            base_offset: 807616,
          });
        });
    });
  });

  describe('.alterStats', function() {
    let new_stats;

    beforeEach(function() {
      new_stats = {
        values: {
          might:         16,
          constitution:  10,
          dexterity:     10,
          perception:    3,
          intellect:     18,
          resolve:       18,
        },
        offsets: {
          might:         124,
          constitution:  128,
          dexterity:     132,
          perception:    136,
          intellect:     140,
          resolve:       144,
        },
        stat_total:  75,
        base_offset: 807616,
      };
    });

    beforeEach(function() {
      return asset_editor.getCharicterSheet();
    });

    it('updates the buffer with the new stats', function() {
      return asset_editor.alterStats(new_stats)
        .then(function() {
          return asset_editor.getCharicterSheet();
        })
        .then(function(sheet) {
          expect(sheet).to.deep.equal(new_stats);
        });
    });
  });

  describe('.saveAs', function() {
    let new_filename = 'tests/data/companion_eder_new.unity3d';
    let new_stats;

    beforeEach(function() {
      return unlink(new_filename);
    });

    beforeEach(function() {
      return asset_editor.getCharicterSheet();
    });

    beforeEach(function() {
      new_stats = {
        values: {
          might:         16,
          constitution:  10,
          dexterity:     10,
          perception:    3,
          intellect:     18,
          resolve:       18,
        },
        offsets: {
          might:         124,
          constitution:  128,
          dexterity:     132,
          perception:    136,
          intellect:     140,
          resolve:       144,
        },
        stat_total:  75,
        base_offset: 807616,
      };

      return asset_editor.alterStats(new_stats);
    });

    afterEach(function() {
      return unlink(new_filename);
    });

    it('saves the current buffer', function() {
      return asset_editor.saveAs(new_filename)
        .then(function() {
          let new_asset_editor = new CompanionAssetEditor(new_filename);

          return new_asset_editor.getCharicterSheet();
        })
        .catch(function(err) {
          expect(err).to.not.exist;
        })
        .then(function(sheet) {
          expect(sheet).to.deep.equal(new_stats);
        });
    });
  });
});
<commit_msg>Dont throw errors when we do pre test cleanup<commit_after>'use strict';

const expect               = require('chai').expect;
const Promise              = require('bluebird');
const fs                   = require('fs');

const CompanionAssetEditor = require('../lib/companion_asset_editor');

const unlink = Promise.promisify(fs.unlink);

describe('CompanionAssetEditor', function() {
  let companion_file_name;
  let asset_editor;

  beforeEach(function() {
    companion_file_name = 'tests/data/companion_eder.unity3d';
    asset_editor = new CompanionAssetEditor(companion_file_name);
  });

  describe('.constructor', function() {
    it('sets the file name', function() {
      expect(asset_editor.file_name).to.equal(companion_file_name);
    });

    it('initializes companion_data', function() {
      expect(asset_editor.companion_data).to.deep.equal({});
    });
  });

  describe('#parseHeader', function() {
    it('parses the header file', function() {
      return asset_editor.parseHeader()
        .catch(function (err) {
          expect(err).to.not.exist;
        })
        .then(function(header) {
          expect(header).to.deep.equal({
            signature:                 'UnityRaw',
            format_version:            3,
            unity_version:             '3.x.x',
            generator_version:         '4.7.0f1',
            file_size:                 816036,
            header_size:               60,
            file_count:                1,
            bundle_count:              1,
            uncompressed_bundle_size:  815976,
            bundle_size:               815976,
            compressed_file_size:      816036,
            asset_header_size:         52,
          });
        });
    });
  });

  describe('#parseAssetBundle', function() {
    let offset;

    beforeEach(function() {
      offset = 60;
    });

    it('resolves the asset bundle metadata', function() {
      return asset_editor.parseAssetBundle(offset)
        .catch(function(err) {
          expect(err).to.not.exist;
        })
        .then(function(asset) {
          expect(asset).to.deep.equal({
            number_of_children:  1,
            name:                'CAB-1e289d4e73b9aa94a91e38b848e98389',
            header_size:         52,
            size:                815924,
            data_offset:         112,
          });
        });
    });
  });

  describe('#loadAssetTypeTree', function() {
    let offset;
    let expected;

    beforeEach(function(done) {
      offset = 112;

      return fs.readFile('./tests/data/eder_asset_tree.json', (err, file_buffer) => {
        expect(err).to.not.exist;

        expected = JSON.parse(file_buffer.toString());

        return done();
      });
    });

    it('resolves the asset data', function() {
      return asset_editor.loadAssetTypeTree(offset)
        .catch(function(err) {
          expect(err).to.not.exist;
        })
        .then(function(asset_data) {
          expect(asset_data).to.deep.equal(expected);
        });
    });
  });

  describe('#loadObjectInfo', function() {
    let offset;
    let number_of_objects;
    let object_data_offset;
    let is_long_ids;

    let expected;

    beforeEach(function() {
      offset             = 223126;
      number_of_objects  = 440;
      is_long_ids        = false;
      object_data_offset = 232160;
    });

    beforeEach(function(done) {
      return fs.readFile('./tests/data/eder_object_metadata.json', (err, file_buffer) => {
        expect(err).to.not.exist;

        expected = JSON.parse(file_buffer.toString());

        return done();
      });
    });

    it('loads object info', function() {
      return asset_editor.loadObjectInfo(number_of_objects, offset, object_data_offset, is_long_ids)
        .catch(function(err) {
         expect(err).to.not.exist();
        })
        .then(function(object_metadata) {
          expect(object_metadata).to.deep.equal(expected);
        });
    });
  });

  describe('#findCharicterSheetType', function() {
    let asset_tree;
    let expected_sheet_type;
    let offset;

    beforeEach(function() {
      offset = 112;

      return asset_editor.loadAssetTypeTree(offset)
        .catch(function(err) {
          expect(err).to.not.exist;
        })
        .then(function(result) {
          asset_tree = result;
        });
    });

    beforeEach(function(done) {
      return fs.readFile('./tests/data/eder_sheet_type.json', (err, file_buffer) => {
        expect(err).to.not.exist;

        expected_sheet_type = JSON.parse(file_buffer.toString());

        return done();
      });
    });

    it('searches the asset type tree for the charicter sheet', function() {
      return asset_editor.findCharicterSheetType(offset)
        .catch(function(err) {
          expect(err).to.not.exist();
        })
        .then(function(charicter_sheet_type) {
          expect(charicter_sheet_type.type).to.deep.equal(expected_sheet_type);
          expect(charicter_sheet_type.type_id).to.deep.equal("-20");
        });
    });
  });

  describe('#findCharicterSheetObjectInfo', function() {
    let object_metadata;
    let type_id;

    beforeEach(function() {
      type_id = "-20"
    });

    beforeEach(function() {
      let number_of_objects  = 440;
      let offset             = 223126;
      let object_data_offset = 232160 ;
      let is_long_ids        = false;

      return asset_editor.loadObjectInfo(number_of_objects, offset, object_data_offset, is_long_ids)
        //.catch(function(err) {
        //  expect(err).to.not.exist();
        //})
        .then(function(results) {
          object_metadata = results;
        });
    });

    it('gets the charicter sheet object metadata', function() {
      let charicter_sheet_object = asset_editor.findCharicterSheetObjectInfo(type_id, object_metadata);

      expect(charicter_sheet_object).to.deep.equal({
        object_id:               415,
        offset:                  807504,
        individual_data_offset:  575344,
        size:                    696,
        type_id:                 -20,
        class_id:                114,
        is_destroyed:            0,
      });
    });

  });

  describe('#readObjectData', function() {
    let object_metadata;
    let type;
    let type_id;
    let expected_sheet_data;

    beforeEach(function() {
      let offset = 112;

      return asset_editor.findCharicterSheetType(offset)
        .catch(function(err) {
          expect(err).to.not.exist;
        })
        .then(function(charicter_sheet_type) {
          type    = charicter_sheet_type;
          type_id = charicter_sheet_type.type_id;
        })
        .then(function() {
          let number_of_objects  = 440;
          let offset             = 223126;
          let object_data_offset = 232160 + 112;
          let is_long_ids        = false;

          return asset_editor.loadObjectInfo(number_of_objects, offset, object_data_offset, is_long_ids)
        })
        .then(function(results) {
          object_metadata = asset_editor.findCharicterSheetObjectInfo(type_id, results);
        });
    });

    beforeEach(function(done) {
      return fs.readFile('./tests/data/eder_sheet_data.json', (err, file_buffer) => {
        expect(err).to.not.exist;

        expected_sheet_data = JSON.parse(file_buffer.toString());

        return done();
      });
    });

    it('reads the object data', function() {
      return asset_editor.readObject(object_metadata, type)
        .catch(function(err) {
          expect(err).to.not.exist();
        })
        .then(function(object_data) {
          expect(object_data).to.deep.equal(expected_sheet_data);
        });
    });
  });

  describe('#getCharicterSheet', function() {
    it('gets the current charicter sheet stats', function() {
      return asset_editor.getCharicterSheet()
        .catch(function(err) {
          expect(err).to.not.exist();
        })
        .then(function(sheet) {
          expect(sheet).to.deep.equal({
            values: {
              might:         15,
              constitution:  16,
              dexterity:     11,
              perception:    12,
              intellect:     10,
              resolve:       11,
            },
            offsets: {
              might:         124,
              constitution:  128,
              dexterity:     132,
              perception:    136,
              intellect:     140,
              resolve:       144,
            },
            stat_total: 75,
            base_offset: 807616,
          });
        });
    });
  });

  describe('.alterStats', function() {
    let new_stats;

    beforeEach(function() {
      new_stats = {
        values: {
          might:         16,
          constitution:  10,
          dexterity:     10,
          perception:    3,
          intellect:     18,
          resolve:       18,
        },
        offsets: {
          might:         124,
          constitution:  128,
          dexterity:     132,
          perception:    136,
          intellect:     140,
          resolve:       144,
        },
        stat_total:  75,
        base_offset: 807616,
      };
    });

    beforeEach(function() {
      return asset_editor.getCharicterSheet();
    });

    it('updates the buffer with the new stats', function() {
      return asset_editor.alterStats(new_stats)
        .then(function() {
          return asset_editor.getCharicterSheet();
        })
        .then(function(sheet) {
          expect(sheet).to.deep.equal(new_stats);
        });
    });
  });

  describe('.saveAs', function() {
    let new_filename = 'tests/data/companion_eder_new.unity3d';
    let new_stats;

    beforeEach(function() {
      return unlink(new_filename)
        .catch(function(err) {
          if(!/ENOENT/.test(err.message)) {
            throw err;
          }
        });
    });

    beforeEach(function() {
      return asset_editor.getCharicterSheet();
    });

    beforeEach(function() {
      new_stats = {
        values: {
          might:         16,
          constitution:  10,
          dexterity:     10,
          perception:    3,
          intellect:     18,
          resolve:       18,
        },
        offsets: {
          might:         124,
          constitution:  128,
          dexterity:     132,
          perception:    136,
          intellect:     140,
          resolve:       144,
        },
        stat_total:  75,
        base_offset: 807616,
      };

      return asset_editor.alterStats(new_stats);
    });

    afterEach(function() {
      return unlink(new_filename);
    });

    it('saves the current buffer', function() {
      return asset_editor.saveAs(new_filename)
        .then(function() {
          let new_asset_editor = new CompanionAssetEditor(new_filename);

          return new_asset_editor.getCharicterSheet();
        })
        .catch(function(err) {
          expect(err).to.not.exist;
        })
        .then(function(sheet) {
          expect(sheet).to.deep.equal(new_stats);
        });
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

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

const ccxt = require ('ccxt');
const { ExchangeError } = require ('ccxt/js/base/errors');
const { ArrayCache, ArrayCacheByTimestamp } = require ('./base/Cache');

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

module.exports = class ascendex extends ccxt.ascendex {
    describe () {
        return this.deepExtend (super.describe (), {
            'has': {
                'ws': true,
                'watchOrderBook': true,
                'watchTicker': true,
                'watchTrades': true,
            },
            'urls': {
                'api': {
                    'ws': 'wss://ascendex.com/0/api/pro/v1/stream',
                },
            },
            'options': {
                'tradesLimit': 1000,
                'ordersLimit': 1000,
                'OHLCVLimit': 1000,
            },
        });
    }

    async watchPublic (channel, messageHash, symbol, method, params = {}) {
        const url = this.urls['api']['ws'];
        const id = this.nonce ();
        const request = {
            'id': id.toString (),
            'op': 'sub',
            'ch': channel,
        };
        const message = this.extend (request, params);
        const subscription = {
            'id': id,
            'symbol': symbol,
            'channel': channel,
            'messageHash': messageHash,
            'method': method,
        };
        return await this.watch (url, messageHash, message, messageHash, subscription);
    }

    async watchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        if ((limit === undefined) || (limit > 1440)) {
            limit = 100;
        }
        const interval = this.timeframes[timeframe];
        const channel = 'bar' + ':' + interval + ':' + market['id'];
        const messageHash = 'bar' + ':' + market['id'];
        const ohlcv = await this.watchPublic (channel, messageHash, symbol, this.handleOHLCV, limit, params);
        if (this.newUpdates) {
            limit = ohlcv.getLimit (symbol, limit);
        }
        return this.filterBySinceLimit (ohlcv, since, limit, 0, true);
    }

    handleOHLCV (client, message, subscription) {
        //
        // {
        //     "m": "bar",
        //     "s": "ASD/USDT",
        //     "data": {
        //         "i":  "1",
        //         "ts": 1575398940000,
        //         "o":  "0.04993",
        //         "c":  "0.04970",
        //         "h":  "0.04993",
        //         "l":  "0.04970",
        //         "v":  "8052"
        //     }
        // }
        //
        const data = this.safeValue (message, 'data', []);
        const channel = this.safeString (message, 'channel', '');
        const parts = channel.split ('_');
        const partsLength = parts.length;
        const interval = this.safeString (parts, partsLength - 1);
        const timeframe = this.findTimeframe (interval);
        const symbol = this.safeString (subscription, 'symbol');
        const market = this.market (symbol);
        for (let i = 0; i < data.length; i++) {
            const candle = data[i];
            const parsed = this.parseOHLCV (candle, market);
            this.ohlcvs[symbol] = this.safeValue (this.ohlcvs, symbol, {});
            let stored = this.safeValue (this.ohlcvs[symbol], timeframe);
            if (stored === undefined) {
                const limit = this.safeInteger (this.options, 'OHLCVLimit', 1000);
                stored = new ArrayCacheByTimestamp (limit);
                this.ohlcvs[symbol][timeframe] = stored;
            }
            stored.append (parsed);
            client.resolve (stored, channel);
        }
        return message;
    }

    async watchTicker (symbol, params = {}) {
        return await this.watchPublic ('ticker', symbol, this.handleTicker, params);
    }

    handleTicker (client, message, subscription) {
        //
        //     {
        //         date: '1624398991255',
        //         ticker: {
        //             high: '33298.38',
        //             vol: '56375.9469',
        //             last: '32396.95',
        //             low: '28808.19',
        //             buy: '32395.81',
        //             sell: '32409.3',
        //             turnover: '1771122527.0000',
        //             open: '31652.44',
        //             riseRate: '2.36'
        //         },
        //         dataType: 'ticker',
        //         channel: 'btcusdt_ticker'
        //     }
        //
        const symbol = this.safeString (subscription, 'symbol');
        const channel = this.safeString (message, 'channel');
        const market = this.market (symbol);
        const data = this.safeValue (message, 'ticker');
        data['date'] = this.safeValue (message, 'date');
        const ticker = this.parseTicker (data, market);
        ticker['symbol'] = symbol;
        this.tickers[symbol] = ticker;
        client.resolve (ticker, channel);
        return message;
    }

    async watchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        const trades = await this.watchPublic ('trades', symbol, this.handleTrades, params);
        if (this.newUpdates) {
            limit = trades.getLimit (symbol, limit);
        }
        return this.filterBySinceLimit (trades, since, limit, 'timestamp', true);
    }

    handleTrades (client, message, subscription) {
        //
        //     {
        //         data: [
        //             { date: 1624537147, amount: '0.0357', price: '34066.11', trade_type: 'bid', type: 'buy', tid: 1718857158 },
        //             { date: 1624537147, amount: '0.0255', price: '34071.04', trade_type: 'bid', type: 'buy', tid: 1718857159 },
        //             { date: 1624537147, amount: '0.0153', price: '34071.29', trade_type: 'bid', type: 'buy', tid: 1718857160 }
        //         ],
        //         dataType: 'trades',
        //         channel: 'btcusdt_trades'
        //     }
        //
        const channel = this.safeValue (message, 'channel');
        const symbol = this.safeString (subscription, 'symbol');
        const market = this.market (symbol);
        const data = this.safeValue (message, 'data');
        const trades = this.parseTrades (data, market);
        let array = this.safeValue (this.trades, symbol);
        if (array === undefined) {
            const limit = this.safeInteger (this.options, 'tradesLimit', 1000);
            array = new ArrayCache (limit);
        }
        for (let i = 0; i < trades.length; i++) {
            array.append (trades[i]);
        }
        this.trades[symbol] = array;
        client.resolve (array, channel);
    }

    async watchOrderBook (symbol, limit = undefined, params = {}) {
        if (limit !== undefined) {
            if ((limit !== 5) && (limit !== 10) && (limit !== 20)) {
                throw new ExchangeError (this.id + ' watchOrderBook limit argument must be undefined, 5, 10 or 20');
            }
        } else {
            limit = 5; // default
        }
        await this.loadMarkets ();
        const market = this.market (symbol);
        const name = 'quick_depth';
        const messageHash = market['baseId'] + market['quoteId'] + '_' + name;
        const url = this.urls['api']['ws'] + '/' + market['baseId'];
        const request = {
            'event': 'addChannel',
            'channel': messageHash,
            'length': limit,
        };
        const message = this.extend (request, params);
        const subscription = {
            'name': name,
            'symbol': symbol,
            'marketId': market['id'],
            'messageHash': messageHash,
            'method': this.handleOrderBook,
        };
        const orderbook = await this.watch (url, messageHash, message, messageHash, subscription);
        return orderbook.limit (limit);
    }

    handleOrderBook (client, message, subscription) {
        //
        //     {
        //         lastTime: 1624524640066,
        //         dataType: 'quickDepth',
        //         channel: 'btcusdt_quick_depth',
        //         currentPrice: 33183.79,
        //         listDown: [
        //             [ 33166.87, 0.2331 ],
        //             [ 33166.86, 0.15 ],
        //             [ 33166.76, 0.15 ],
        //             [ 33161.02, 0.212 ],
        //             [ 33146.35, 0.6066 ]
        //         ],
        //         market: 'btcusdt',
        //         listUp: [
        //             [ 33186.88, 0.15 ],
        //             [ 33190.1, 0.15 ],
        //             [ 33193.03, 0.2518 ],
        //             [ 33195.05, 0.2031 ],
        //             [ 33199.99, 0.6066 ]
        //         ],
        //         high: 34816.8,
        //         rate: '6.484',
        //         low: 32312.41,
        //         currentIsBuy: true,
        //         dayNumber: 26988.5536,
        //         totalBtc: 26988.5536,
        //         showMarket: 'btcusdt'
        //     }
        //
        const channel = this.safeString (message, 'channel');
        const limit = this.safeInteger (subscription, 'limit');
        const symbol = this.safeString (subscription, 'symbol');
        let orderbook = this.safeValue (this.orderbooks, symbol);
        if (orderbook === undefined) {
            orderbook = this.orderBook ({}, limit);
            this.orderbooks[symbol] = orderbook;
        }
        const timestamp = this.safeInteger (message, 'lastTime');
        const parsed = this.parseOrderBook (message, symbol, timestamp, 'listDown', 'listUp');
        orderbook.reset (parsed);
        orderbook['symbol'] = symbol;
        client.resolve (orderbook, channel);
    }

    handleMessage (client, message) {
        //
        //     { m: 'ping', hp: 3 }
        //
        //     { m: 'sub', ch: 'bar:BTC/USDT', code: 0 }
        //
        //     { m: 'connected', type: 'unauth' }
        //
        // ohlcv
        //  {
        //     m: 'bar',
        //     s: 'BTC/USDT',
        //     data: {
        //       i: '1',
        //       ts: 1647510060000,
        //       o: '40813.93',
        //       c: '40804.57',
        //       h: '40814.21',
        //       l: '40804.56',
        //       v: '0.01537'
        //     }
        //   }
        //
        //
        const m = this.safeString (message, 'm');
        if (m === 'ping') {
            this.handlePing (client, message);
            return;
        }
        const marketId = this.safeString (message, 's');
        const subject = this.safeString (message, 'm');
        if (marketId !== undefined) {
            const channel = subject + ':' + marketId;
            const subscription = this.safeValue (client.subscriptions, channel);
            if (subscription !== undefined) {
                const method = this.safeValue (subscription, 'method');
                if (method !== undefined) {
                    return method.call (this, client, message, subscription);
                }
            }
            return message;
        }
    }

    async pong (client, message) {
        //
        //     { m: 'ping', hp: 3 }
        //
        await client.send ({ 'op': 'pong', 'hp': this.safeInteger (message, 'hp') });
    }

    handlePing (client, message) {
        this.spawn (this.pong, client, message);
    }
};
<commit_msg>handleTrades<commit_after>'use strict';

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

const ccxt = require ('ccxt');
const { ExchangeError } = require ('ccxt/js/base/errors');
const { ArrayCache, ArrayCacheByTimestamp } = require ('./base/Cache');

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

module.exports = class ascendex extends ccxt.ascendex {
    describe () {
        return this.deepExtend (super.describe (), {
            'has': {
                'ws': true,
                'watchOrderBook': true,
                'watchTicker': true,
                'watchTrades': true,
            },
            'urls': {
                'api': {
                    'ws': 'wss://ascendex.com/0/api/pro/v1/stream',
                },
            },
            'options': {
                'tradesLimit': 1000,
                'ordersLimit': 1000,
                'OHLCVLimit': 1000,
            },
        });
    }

    async watchPublic (channel, messageHash, symbol, method, params = {}) {
        const url = this.urls['api']['ws'];
        const id = this.nonce ();
        const request = {
            'id': id.toString (),
            'op': 'sub',
            'ch': channel,
        };
        const message = this.extend (request, params);
        const subscription = {
            'id': id,
            'symbol': symbol,
            'channel': channel,
            'messageHash': messageHash,
            'method': method,
        };
        return await this.watch (url, messageHash, message, messageHash, subscription);
    }

    async watchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        if ((limit === undefined) || (limit > 1440)) {
            limit = 100;
        }
        const interval = this.timeframes[timeframe];
        const channel = 'bar' + ':' + interval + ':' + market['id'];
        const messageHash = 'bar' + ':' + market['id'];
        const ohlcv = await this.watchPublic (channel, messageHash, symbol, this.handleOHLCV, limit, params);
        if (this.newUpdates) {
            limit = ohlcv.getLimit (symbol, limit);
        }
        return this.filterBySinceLimit (ohlcv, since, limit, 0, true);
    }

    handleOHLCV (client, message, subscription) {
        //
        // {
        //     "m": "bar",
        //     "s": "ASD/USDT",
        //     "data": {
        //         "i":  "1",
        //         "ts": 1575398940000,
        //         "o":  "0.04993",
        //         "c":  "0.04970",
        //         "h":  "0.04993",
        //         "l":  "0.04970",
        //         "v":  "8052"
        //     }
        // }
        //
        const data = this.safeValue (message, 'data', {});
        const interval = this.safeString (data, 'i');
        const timeframe = this.findTimeframe (interval);
        const symbol = this.safeString (subscription, 'symbol');
        const market = this.market (symbol);
        const parsed = this.parseOHLCV (message, market);
        this.ohlcvs[symbol] = this.safeValue (this.ohlcvs, symbol, {});
        let stored = this.safeValue (this.ohlcvs[symbol], timeframe);
        if (stored === undefined) {
            const limit = this.safeInteger (this.options, 'OHLCVLimit', 1000);
            stored = new ArrayCacheByTimestamp (limit);
            this.ohlcvs[symbol][timeframe] = stored;
        }
        stored.append (parsed);
        const messageHash = this.safeString (subscription, 'messageHash');
        client.resolve (stored, messageHash);
        return message;
    }

    async watchTicker (symbol, params = {}) {
        return await this.watchPublic ('ticker', symbol, this.handleTicker, params);
    }

    handleTicker (client, message, subscription) {
        //
        //     {
        //         date: '1624398991255',
        //         ticker: {
        //             high: '33298.38',
        //             vol: '56375.9469',
        //             last: '32396.95',
        //             low: '28808.19',
        //             buy: '32395.81',
        //             sell: '32409.3',
        //             turnover: '1771122527.0000',
        //             open: '31652.44',
        //             riseRate: '2.36'
        //         },
        //         dataType: 'ticker',
        //         channel: 'btcusdt_ticker'
        //     }
        //
        const symbol = this.safeString (subscription, 'symbol');
        const channel = this.safeString (message, 'channel');
        const market = this.market (symbol);
        const data = this.safeValue (message, 'ticker');
        data['date'] = this.safeValue (message, 'date');
        const ticker = this.parseTicker (data, market);
        ticker['symbol'] = symbol;
        this.tickers[symbol] = ticker;
        client.resolve (ticker, channel);
        return message;
    }

    async watchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const channel = 'trades' + ':' + market['id'];
        const trades = await this.watchPublic (channel, channel, symbol, this.handleTrades, limit, params);
        if (this.newUpdates) {
            limit = trades.getLimit (symbol, limit);
        }
        return this.filterBySinceLimit (trades, since, limit, 'timestamp', true);
    }

    handleTrades (client, message, subscription) {
        //
        // {
        //     m: 'trades',
        //     symbol: 'BTC/USDT',
        //     data: [
        //       {
        //         p: '40744.28',
        //         q: '0.00150',
        //         ts: 1647514330758,
        //         bm: true,
        //         seqnum: 72057633465800320
        //       }
        //     ]
        // }
        //
        const symbol = this.safeString (subscription, 'symbol');
        const messageHash = this.safeString (subscription, 'messageHash');
        const market = this.market (symbol);
        const data = this.safeValue (message, 'data', []);
        const trades = this.parseTrades (data, market);
        let array = this.safeValue (this.trades, symbol);
        if (array === undefined) {
            const limit = this.safeInteger (this.options, 'tradesLimit', 1000);
            array = new ArrayCache (limit);
        }
        for (let i = 0; i < trades.length; i++) {
            array.append (trades[i]);
        }
        this.trades[symbol] = array;
        client.resolve (array, messageHash);
    }

    async watchOrderBook (symbol, limit = undefined, params = {}) {
        if (limit !== undefined) {
            if ((limit !== 5) && (limit !== 10) && (limit !== 20)) {
                throw new ExchangeError (this.id + ' watchOrderBook limit argument must be undefined, 5, 10 or 20');
            }
        } else {
            limit = 5; // default
        }
        await this.loadMarkets ();
        const market = this.market (symbol);
        const name = 'quick_depth';
        const messageHash = market['baseId'] + market['quoteId'] + '_' + name;
        const url = this.urls['api']['ws'] + '/' + market['baseId'];
        const request = {
            'event': 'addChannel',
            'channel': messageHash,
            'length': limit,
        };
        const message = this.extend (request, params);
        const subscription = {
            'name': name,
            'symbol': symbol,
            'marketId': market['id'],
            'messageHash': messageHash,
            'method': this.handleOrderBook,
        };
        const orderbook = await this.watch (url, messageHash, message, messageHash, subscription);
        return orderbook.limit (limit);
    }

    handleOrderBook (client, message, subscription) {
        //
        //     {
        //         lastTime: 1624524640066,
        //         dataType: 'quickDepth',
        //         channel: 'btcusdt_quick_depth',
        //         currentPrice: 33183.79,
        //         listDown: [
        //             [ 33166.87, 0.2331 ],
        //             [ 33166.86, 0.15 ],
        //             [ 33166.76, 0.15 ],
        //             [ 33161.02, 0.212 ],
        //             [ 33146.35, 0.6066 ]
        //         ],
        //         market: 'btcusdt',
        //         listUp: [
        //             [ 33186.88, 0.15 ],
        //             [ 33190.1, 0.15 ],
        //             [ 33193.03, 0.2518 ],
        //             [ 33195.05, 0.2031 ],
        //             [ 33199.99, 0.6066 ]
        //         ],
        //         high: 34816.8,
        //         rate: '6.484',
        //         low: 32312.41,
        //         currentIsBuy: true,
        //         dayNumber: 26988.5536,
        //         totalBtc: 26988.5536,
        //         showMarket: 'btcusdt'
        //     }
        //
        const channel = this.safeString (message, 'channel');
        const limit = this.safeInteger (subscription, 'limit');
        const symbol = this.safeString (subscription, 'symbol');
        let orderbook = this.safeValue (this.orderbooks, symbol);
        if (orderbook === undefined) {
            orderbook = this.orderBook ({}, limit);
            this.orderbooks[symbol] = orderbook;
        }
        const timestamp = this.safeInteger (message, 'lastTime');
        const parsed = this.parseOrderBook (message, symbol, timestamp, 'listDown', 'listUp');
        orderbook.reset (parsed);
        orderbook['symbol'] = symbol;
        client.resolve (orderbook, channel);
    }

    handleMessage (client, message) {
        //
        //     { m: 'ping', hp: 3 }
        //
        //     { m: 'sub', ch: 'bar:BTC/USDT', code: 0 }
        //
        //     { m: 'connected', type: 'unauth' }
        //
        // ohlcv
        //  {
        //     m: 'bar',
        //     s: 'BTC/USDT',
        //     data: {
        //       i: '1',
        //       ts: 1647510060000,
        //       o: '40813.93',
        //       c: '40804.57',
        //       h: '40814.21',
        //       l: '40804.56',
        //       v: '0.01537'
        //     }
        //   }
        //
        // trades
        //
        //    {
        //        m: 'trades',
        //        symbol: 'BTC/USDT',
        //        data: [
        //          {
        //            p: '40762.26',
        //            q: '0.01500',
        //            ts: 1647514306759,
        //            bm: true,
        //            seqnum: 72057633465795180
        //          }
        //        ]
        //    }
        //
        //
        const subject = this.safeString (message, 'm');
        if (subject === 'ping') {
            this.handlePing (client, message);
            return;
        }
        const marketId = this.safeString2 (message, 's', 'symbol');
        if (marketId !== undefined) {
            const channel = subject + ':' + marketId;
            const subscription = this.safeValue (client.subscriptions, channel);
            if (subscription !== undefined) {
                const method = this.safeValue (subscription, 'method');
                if (method !== undefined) {
                    return method.call (this, client, message, subscription);
                }
            }
            return message;
        }
    }

    async pong (client, message) {
        //
        //     { m: 'ping', hp: 3 }
        //
        await client.send ({ 'op': 'pong', 'hp': this.safeInteger (message, 'hp') });
    }

    handlePing (client, message) {
        this.spawn (this.pong, client, message);
    }
};
<|endoftext|>


<commit_before>var Nodes, Relationships;

var fileBufferCount = 0;

var nodeInfo = new Array();

var edgeNum = 0;
var nodeCount = 0;

var timer;
var  timerIsActive = false;

var ServerJSONBuffer = [];
var bufferCount = 0;

var FileJSONBuffer = [];

var finished=false;
var informationJSON;

var readingFromFile = 0;
var readingFromServer = 0;

function startTimer()
{
	timer = setInterval(addNodesAndEdgesFile, 100);
	timerIsActive = true;
}

function stopTimer()
{
	clearInterval(timer);
	timerIsActive = false;
}

function resumeTimer()
{
	if(!timerIsActive)
		timer = setInterval(flashText, 1000);
}

function getNodeFromServer()
{
	var xhttp = new XMLHttpRequest();

	if(finished)
	{
		alert("Scan finnished");
		return;
	}

	xhttp.onreadystatechange = function()
	{
		 if(finished)
		{
			alert("Scan finnished");
			return;
		}

		if (this.readyState == 4 && this.status == 200)
		{
			if(this.responseText=="null")
			{
				finished=true;
			}

			if(!finished)
			{

				var jsonIn = this.responseText;
				readInJSONFromServer(jsonIn);
				addNodesAndEdges() ;
				getNodeFromServer();

			}
		}
	}

	xhttp.open("GET", "http://localhost:8080/NotLikeThisRESTServer_war_exploded/services/getLatestTree", true);
	xhttp.send();
}

function addNodesAndEdges()
{
	if(ServerJSONBuffer.length > bufferCount)
	{
		for(var k = 0; k< ServerJSONBuffer[bufferCount].NodesArray.length; k++)
		{
			addNode(ServerJSONBuffer[bufferCount].NodesArray[k].UUID, ServerJSONBuffer[bufferCount].NodesArray[k].Name, ServerJSONBuffer[bufferCount].NodesArray[k].Level);

			if(ServerJSONBuffer[bufferCount].NodesArray[k].Relationships.length != 0)
			{
				for(j = 0; j < ServerJSONBuffer[bufferCount].NodesArray[k].Relationships.length; j++)
				{
					addEdge(edgeNum, ServerJSONBuffer[bufferCount].NodesArray[k].UUID, ServerJSONBuffer[bufferCount].NodesArray[k].Relationships[j].UUID, ServerJSONBuffer[bufferCount].NodesArray[k].Relationships[j].type);
					edgeNum = edgeNum + 1;
				}
			}
		}

					sleep(500);
					bufferCount=bufferCount+1;

	}
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

function addNodesAndEdgesFile()
{

	//for(var k = 0; k< FileJSONBuffer.length; k++)
	//{
		addNode(FileJSONBuffer[fileBufferCount].UUID, FileJSONBuffer[fileBufferCount].Name, FileJSONBuffer[fileBufferCount].Level);

		if(FileJSONBuffer[fileBufferCount].Relationships.length != 0)
		{
			for(j = 0; j < FileJSONBuffer[fileBufferCount].Relationships.length; j++)
			{
				addEdge(edgeNum, FileJSONBuffer[fileBufferCount].UUID, FileJSONBuffer[fileBufferCount].Relationships[j].UUID, FileJSONBuffer[fileBufferCount].Relationships[j].type);
				edgeNum = edgeNum + 1;
			}
		}

		fileBufferCount = fileBufferCount + 1;
	//}

}

function addNode(idIn, labelIn, levelIn)
{
	try
	{
		switch (levelIn)
		{
			case "1":
			Nodes.add(
			{
				id: idIn,
				label: labelIn,
				level: levelIn,
				image: 'Images/root.png'
			});
			break;
			case "2":
			Nodes.add(
			{
				id: idIn,
				label: labelIn,
				level: levelIn,
				image: 'Images/region.png'
			});
			break;
			case "3":
			Nodes.add(
			{
				id: idIn,
				label: labelIn,
				level: levelIn,
				image: 'Images/VPC.png'
			});
			break;
			case "4":
			Nodes.add(
			{
				id: idIn,
				label: labelIn,
				level: levelIn,
				image: 'Images/subnetwork.png'
			});
			break;
			case "5":
			Nodes.add(
			{
				id: idIn,
				label: labelIn,
				level: levelIn,
				image: 'Images/Instance.png'
			});
			break;
			default:
			Nodes.add(
			{
				id: idIn,
				label: labelIn,
				level: levelIn,
				shape: 'dot',
				color: {background:'white', border:'black',highlight:{background:'white',border:'black'}},
				font: {background: 'white'}
			});
		}
	}
	catch (err)
	{
		alert(err);
	}
}

function updateNode(idIn, labelIn)
{
	try
	{
		Nodes.update(
		{
			id: idIn,
			label: labelIn
		});
	}
	catch (err)
	{
		alert(err);
	}
}

function removeNode(idIn)
{
	try
	{
		Nodes.remove({id: idIn});
	}
	catch (err)
	{
		alert(err);
	}
}

function addEdge(idIn, fromIn, toIn, type)
{
		try
	{
		switch (type)
		{
			case 1:
			Relationships.add(
			{
				id: idIn,
				from: fromIn,
				to: toIn,
				color: 'red',
				dashes: true,
				label: "lable"
			});
			break;
			case 2:
			Relationships.add(
			{
				id: idIn,
				from: fromIn,
				to: toIn,
				color: 'red',
				dashes: true,
				label: "lable"
			});
			break;
			case 3:
			Relationships.add(
			{
				id: idIn,
				from: fromIn,
				to: toIn,
				color: 'red',
				dashes: true,
				label: "lable"
			});
			break;
			case 4:
			Relationships.add(
			{
				id: idIn,
				from: fromIn,
				to: toIn,
				color: 'red',
				dashes: true,
				label: "lable"
			});
			break;
			case 5:
			Relationships.add(
			{
				id: idIn,
				from: fromIn,
				to: toIn,
				color: 'red',
				dashes: true,
				label: "lable"
			});
			break;
			default:
			Relationships.add(
			{
				id: idIn,
				from: fromIn,
				to: toIn,
				color: 'black',
				dashes: false
			});
		}
	}
	catch (err)
	{
		alert(err);
	}
}

function updateEdge(idIn, fromIn, inTo)
{
	try
	{
		Relationships.update(
		{
			id: idIn,
			from: fromIn,
			to: inTo
		});
	}
	catch (err)
	{
		alert(err);
	}
}

function removeEdge(idIn)
{
	try
	{
		Relationships.remove({id: idIn});
	}
	catch (err)
	{
		alert(err);
	}
}

var openFile = function (event)
{
	var input = event.target;
	var reader = new FileReader();

	reader.onload = function ()
	{
		var text = reader.result;
		console.log(reader.result.substring(0, 200));
		readInJSONFromFile(text);
	};

	reader.readAsText(input.files[0]);
};

function readInJSONFromServer(jsonIn)
{
	var obj = JSON.parse(jsonIn);

	ServerJSONBuffer.push(obj);
}

function readInJSONFromFile(jsonIn)
{
	var obj = JSON.parse(jsonIn);
	var obj2;

	for(var k = 0; k< obj.NodesArray.length; k++)
	{
		obj2 = obj.NodesArray[k];
		FileJSONBuffer.push(obj2);
	}
	//readingFromFile = 1;
	//addNodesAndEdgesFile() ;
	startTimer();
}

function clearNodesAndEdges()
{
	var removedIds = Nodes.clear();
	removedIds = Relationships.clear();
	ServerJSONBuffer = [];
	FileJSONBuffer = [];
	fileBufferCount = 0;
	bufferCount = 0;

	draw();

}

function getBufferContents()
{
	return ServerJSONBuffer;
}

function draw()
{
	Nodes = new vis.DataSet();

	Relationships = new vis.DataSet();

	var options =
        {
		interaction:
		{
			navigationButtons: true,
			keyboard: true, hover: true,
			hideEdgesOnDrag: true
		},
                nodes:
		{
			shape: 'circularImage',
			borderWidth:1, size:40,
			shapeProperties:
			{
				useBorderWithImage:true
			},
			color:
			{
				background:'white',
				border:'black',
				highlight:
				{
					background:' #3498db ',
					border:' #black '
				}
			},
			font:
			{
				background: 'white',
				size: 14
			}

		},
                edges:
		{
			width: 2,
			smooth:
			{
				type:"dynamic",
				forceDirection: "none",
				roundness: 0.0
			}
		},
		physics:
		{
			enabled: false
		},
		layout:
		{
			improvedLayout:true,
			hierarchical:
			{
				enabled:true,
				levelSeparation: 200,
				nodeSpacing: 200,
				//treeSpacing: 300,
				blockShifting: true,
				edgeMinimization: true,
				parentCentralization: true,
				direction: 'UD',        // UD, DU, LR, RL
				sortMethod: 'directed'   // hubsize, directed
			}
		}
	};

	var data =
	{
                nodes: Nodes,
                edges: Relationships
	};

	var container = document.getElementById("hierarchyVisualizerDiv");

	networkHierarchy = new vis.Network(container, data, options);

	networkHierarchy.on( 'selectNode', function(properties)
	{
		var ids = properties.nodes;
		var xhttp = new XMLHttpRequest();

		xhttp.onreadystatechange = function()
		{

			if (this.readyState == 4 && this.status == 200)
			{
				if(this.responseText!="null")
				{
					document.getElementById("information").value =this.responseText ;
					document.getElementById("fromUUID").value =ids ;
				}

			}

		};
		xhttp.open("GET", "http://localhost:8080/NotLikeThisRESTServer_war_exploded/services/getInformation?uuid="+ids, true);
		xhttp.send();

	});
}<commit_msg>Revert "Revert "Added node and edge colours""<commit_after>var Nodes, Relationships;

var fileBufferCount = 0;

var nodeInfo = new Array();

var edgeNum = 0;
var nodeCount = 0;

var timer;
var  timerIsActive = false;

var ServerJSONBuffer = [];
var bufferCount = 0;

var FileJSONBuffer = [];

var finished=false;
var informationJSON;

var readingFromFile = 0;
var readingFromServer = 0;

function startTimer()
{
	timer = setInterval(addNodesAndEdgesFile, 100);
	timerIsActive = true;
}

function stopTimer()
{
	clearInterval(timer);
	timerIsActive = false;
}

function resumeTimer()
{
	if(!timerIsActive)
		timer = setInterval(flashText, 1000);
}

function getNodeFromServer()
{
	var xhttp = new XMLHttpRequest();

	if(finished)
	{
		alert("Scan finnished");
		return;
	}

	xhttp.onreadystatechange = function()
	{
		 if(finished)
		{
			alert("Scan finnished");
			return;
		}

		if (this.readyState == 4 && this.status == 200)
		{
			if(this.responseText=="null")
			{
				finished=true;
			}

			if(!finished)
			{

				var jsonIn = this.responseText;
				readInJSONFromServer(jsonIn);
				addNodesAndEdges() ;
				getNodeFromServer();

			}
		}
	}

	xhttp.open("GET", "http://localhost:8080/NotLikeThisRESTServer_war_exploded/services/getLatestTree", true);
	xhttp.send();
}

function addNodesAndEdges()
{
	if(ServerJSONBuffer.length > bufferCount)
	{
		for(var k = 0; k< ServerJSONBuffer[bufferCount].NodesArray.length; k++)
		{
			addNode(ServerJSONBuffer[bufferCount].NodesArray[k].UUID, ServerJSONBuffer[bufferCount].NodesArray[k].Name, ServerJSONBuffer[bufferCount].NodesArray[k].Level);

			if(ServerJSONBuffer[bufferCount].NodesArray[k].Relationships.length != 0)
			{
				for(j = 0; j < ServerJSONBuffer[bufferCount].NodesArray[k].Relationships.length; j++)
				{
					addEdge(edgeNum, ServerJSONBuffer[bufferCount].NodesArray[k].UUID, ServerJSONBuffer[bufferCount].NodesArray[k].Relationships[j].UUID, ServerJSONBuffer[bufferCount].NodesArray[k].Relationships[j].type, edgeNum, ServerJSONBuffer[bufferCount].NodesArray[k].Level);
					edgeNum = edgeNum + 1;
				}
			}
		}

					sleep(500);
					bufferCount=bufferCount+1;
	}
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

function addNodesAndEdgesFile()
{

	if(FileJSONBuffer.length > fileBufferCount)
	{
		addNode(FileJSONBuffer[fileBufferCount].UUID, FileJSONBuffer[fileBufferCount].Name, FileJSONBuffer[fileBufferCount].Level);

		if(FileJSONBuffer[fileBufferCount].Relationships.length != 0)
		{
			for(j = 0; j < FileJSONBuffer[fileBufferCount].Relationships.length; j++)
			{
				addEdge(edgeNum, FileJSONBuffer[fileBufferCount].UUID, FileJSONBuffer[fileBufferCount].Relationships[j].UUID, FileJSONBuffer[fileBufferCount].Relationships[j].type, FileJSONBuffer[fileBufferCount].Level);
				edgeNum = edgeNum + 1;
			}
		}

		fileBufferCount = fileBufferCount + 1;
	}

}

function addNode(idIn, labelIn, levelIn)
{
	try
	{
		switch (levelIn)
		{
			case "1":
			Nodes.add(
			{
				id: idIn,
				label: labelIn,
				level: levelIn,
				image: 'Images/root.png',
				color:
				{
					background:'white',
					border:'black',
					highlight:
					{
						background:'white',
						border: 'red '
					},
					hover:
					{
						border: 'red'
					}
				}
			});
			break;
			case "2":
			Nodes.add(
			{
				id: idIn,
				label: labelIn,
				level: levelIn,
				image: 'Images/region.png',
				color:
				{
					background:'white',
					border:'black',
					highlight:
					{
						background:'white',
						border: 'blue '
					},
					hover:
					{
						border: 'blue'
					}
				}
			});
			break;
			case "3":
			Nodes.add(
			{
				id: idIn,
				label: labelIn,
				level: levelIn,
				image: 'Images/VPC.png',
				color:
				{
					background:'white',
					border:'black',
					highlight:
					{
						background:'white',
						border: 'yellow '
					},
					hover:
					{
						border: 'yellow'
					}
				}
			});
			break;
			case "4":
			Nodes.add(
			{
				id: idIn,
				label: labelIn,
				level: levelIn,
				image: 'Images/subnetwork.png',
				color:
				{
					background:'white',
					border:'black',
					highlight:
					{
						background:'white',
						border: 'green '
					},
					hover:
					{
						border: 'green'
					}
				}
			});
			break;
			case "5":
			Nodes.add(
			{
				id: idIn,
				label: labelIn,
				level: levelIn,
				image: 'Images/Instance.png',
				color:
				{
					background:'white',
					border:'black',
					highlight:
					{
						background:'white',
						border: 'orange '
					},
					hover:
					{
						border: 'orange'
					}
				}
			});
			break;
			default:
			Nodes.add(
			{
				id: idIn,
				label: labelIn,
				level: levelIn,
				shape: 'dot',
				color: {background:'white', border:'black',highlight:{background:'white',border:'black'}},
				font: {background: 'white'}
			});
		}
	}
	catch (err)
	{
		alert(err);
	}
}

function updateNode(idIn, labelIn)
{
	try
	{
		Nodes.update(
		{
			id: idIn,
			label: labelIn
		});
	}
	catch (err)
	{
		alert(err);
	}
}

function removeNode(idIn)
{
	try
	{
		Nodes.remove({id: idIn});
	}
	catch (err)
	{
		alert(err);
	}
}

function addEdge(idIn, fromIn, toIn, type, level)
{
		try
	{
		switch (level)
		{
			case "1":
			Relationships.add(
			{
				id: idIn,
				from: fromIn,
				to: toIn,
				dashes: false,
				label: "lable",
				color:
				{
					color:'black',
					highlight:'red',
					hover: 'red'
				},

			});
			break;
			case "2":
			Relationships.add(
			{
				id: idIn,
				from: fromIn,
				to: toIn,
				color: 'red',
				dashes: false,
				label: "lable",
				color:
				{
					color:'black',
					highlight:'blue',
					hover: 'blue'
				},
			});
			break;
			case "3":
			Relationships.add(
			{
				id: idIn,
				from: fromIn,
				to: toIn,
				dashes: false,
				label: "lable",
				color:
				{
					color:'black',
					highlight:'yellow',
					hover: 'yellow'
				},
			});
			break;
			case "4":
			Relationships.add(
			{
				id: idIn,
				from: fromIn,
				to: toIn,
				dashes: false,
				label: "lable",
				color:
				{
					color:'black',
					highlight:'green',
					hover: 'green'
				},
			});
			break;
			case "5":
			Relationships.add(
			{
				id: idIn,
				from: fromIn,
				to: toIn,
				color: 'red',
				dashes: true,
				label: "lable"
			});
			break;
			default:
			Relationships.add(
			{
				id: idIn,
				from: fromIn,
				to: toIn,
				color: 'black'
			});
		}
	}
	catch (err)
	{
		alert(err);
	}
}

function updateEdge(idIn, fromIn, inTo)
{
	try
	{
		Relationships.update(
		{
			id: idIn,
			from: fromIn,
			to: inTo
		});
	}
	catch (err)
	{
		alert(err);
	}
}

function removeEdge(idIn)
{
	try
	{
		Relationships.remove({id: idIn});
	}
	catch (err)
	{
		alert(err);
	}
}

var openFile = function (event)
{
	var input = event.target;
	var reader = new FileReader();

	reader.onload = function ()
	{
		var text = reader.result;
		console.log(reader.result.substring(0, 200));
		readInJSONFromFile(text);
	};

	reader.readAsText(input.files[0]);
};

function readInJSONFromServer(jsonIn)
{
	var obj = JSON.parse(jsonIn);

	ServerJSONBuffer.push(obj);
}

function readInJSONFromFile(jsonIn)
{
	var obj = JSON.parse(jsonIn);
	var obj2;

	for(var k = 0; k< obj.NodesArray.length; k++)
	{
		obj2 = obj.NodesArray[k];
		FileJSONBuffer.push(obj2);
	}
	//readingFromFile = 1;
	//addNodesAndEdgesFile() ;
	startTimer();
}

function clearNodesAndEdges()
{
	var removedIds = Nodes.clear();
	removedIds = Relationships.clear();
	ServerJSONBuffer = [];
	FileJSONBuffer = [];
	fileBufferCount = 0;
	bufferCount = 0;

	draw();

}

function getBufferContents()
{
	return ServerJSONBuffer;
}

function draw()
{
	Nodes = new vis.DataSet();

	Relationships = new vis.DataSet();

	var options =
        {
		interaction:
		{
			navigationButtons: true,
			keyboard: true, hover: true,
			hideEdgesOnDrag: true
		},
                nodes:
		{
			shape: 'circularImage',
			borderWidth:3,
			size:40,
			shapeProperties:
			{
				useBorderWithImage:true
			},
			color:
			{
				background:'white',
				border:'black',
				highlight:
				{
					background:'white',
					border: 'black '
				},
				hover:
				{
					border: 'black'
				}

			},
			font:
			{
				background: 'white',
				size: 14
			}

		},
                edges:
		{
			width: 2,
			smooth:
			{
				type:"dynamic",
				forceDirection: "none",
				roundness: 0.0
			}
		},
		physics:
		{
			enabled: false
		},
		layout:
		{
			improvedLayout:true,
			hierarchical:
			{
				enabled:true,
				levelSeparation: 200,
				nodeSpacing: 200,
				//treeSpacing: 300,
				blockShifting: true,
				edgeMinimization: true,
				parentCentralization: true,
				direction: 'UD',        // UD, DU, LR, RL
				sortMethod: 'directed'   // hubsize, directed
			}
		}
	};

	var data =
	{
                nodes: Nodes,
                edges: Relationships
	};

	var container = document.getElementById("hierarchyVisualizerDiv");

	networkHierarchy = new vis.Network(container, data, options);

	networkHierarchy.on( 'selectNode', function(properties)
	{
		var ids = properties.nodes;
		var xhttp = new XMLHttpRequest();

		xhttp.onreadystatechange = function()
		{

			if (this.readyState == 4 && this.status == 200)
			{
				if(this.responseText!="null")
				{
					document.getElementById("information").value =this.responseText ;
					document.getElementById("fromUUID").value =ids ;
				}

			}

		};
		xhttp.open("GET", "http://localhost:8080/NotLikeThisRESTServer_war_exploded/services/getInformation?uuid="+ids, true);
		xhttp.send();

	});
}<|endoftext|>