<commit_before>var playField = (function () {

    const PUZZLE_HOVER_TINT = '#009900';

    var _stage,_canvas;

    var _img,
        _pieces,
        _puzzleWidth,
        _puzzleHeight,
        _pieceWidth,
        _pieceHeight,
        _currentPiece,
        _currentDropPiece,
        _mouse,
        _puzzle_difficulty;

    var mouse = (function () {
        var mouse = {
            init: function (x,y) {
                this.x = x;
                this.y = y;
                return this;
            }
        };
        Object.defineProperty(mouse, 'x', {
            get: function () {
                return this._x;
            },
            set: function (value) {
                this._x = value;
            }
        });
        Object.defineProperty(mouse, 'y', {
            get: function () {
                return this._y;
            },
            set: function (value) {
                this._y = value;
            }
        });

        return mouse;
    }());

    var puzzlePiece = (function () {
        var piece = {
            init: function (startX,startY) {
                this.startX = startX;
                this.startY = startY;
                this.currentX = startX;
                this.currentY = startY;
                return this;
            }
        };

        Object.defineProperty(piece, 'startX', {
            get: function () {
                return this._startX;
            },
            set: function (value) {
                this._startX = value;
            }
        });

        Object.defineProperty(piece, 'startY', {
            get: function () {
                return this._startY;
            },
            set: function (value) {
                this._startY = value;
            }
        });
        Object.defineProperty(piece, 'currentX', {
            get: function () {
                return this._currentX;
            },
            set: function (value) {
                this._currentX = value;
            }
        });
        Object.defineProperty(piece, 'currentY', {
            get: function () {
                return this._currentY;
            },
            set: function (value) {
                this._currentY = value;
            }
        });

        return piece;
    }());

    var playField = {
        init:function (imageSrc,difficulty){
            _img = new Image();
            _img.addEventListener('load',playField.onImage,false);
            _img.src = imageSrc;
            _puzzle_difficulty = difficulty;
            return playField;
        },
        onImage:function(e){
            _pieceWidth = Math.floor(_img.width / _puzzle_difficulty)
            _pieceHeight = Math.floor(_img.height / _puzzle_difficulty)
            _puzzleWidth = _pieceWidth * _puzzle_difficulty;
            _puzzleHeight = _pieceHeight * _puzzle_difficulty;
            playField.setCanvas();
            playField.initPuzzle();
        },
        setCanvas:function(){
            _canvas = document.getElementById('canvas');
            _stage = _canvas.getContext('2d');
            _canvas.width = _puzzleWidth;
            _canvas.height = _puzzleHeight;
            _canvas.style.border = "1px solid black";
        },
        initPuzzle:function(){
            _pieces = [];
            _mouse = Object.create(mouse).init(0,0);
            _currentPiece = null;
            _currentDropPiece = null;
            _stage.drawImage(_img, 0, 0, _puzzleWidth, _puzzleHeight, 0, 0, _puzzleWidth, _puzzleHeight);
            playField.createTitle("Click to Start Puzzle");
            playField.buildPieces();
        },
        createTitle:function(msg){
            _stage.fillStyle = "#000000";
            _stage.globalAlpha = .4;
            _stage.fillRect(100,_puzzleHeight - 40,_puzzleWidth - 200,40);
            _stage.fillStyle = "#FFFFFF";
            _stage.globalAlpha = 1;
            _stage.textAlign = "center";
            _stage.textBaseline = "middle";
            _stage.font = "20px Arial";
            _stage.fillText(msg,_puzzleWidth / 2,_puzzleHeight - 20);
        },
        buildPieces:function(){
            var i;
            var piece ;
            var xPos = 0;
            var yPos = 0;
            for(i = 0;i < _puzzle_difficulty * _puzzle_difficulty;i++){
                piece = Object.create(puzzlePiece).init(xPos,yPos);
                _pieces.push(piece);
                xPos += _pieceWidth;
                if(xPos >= _puzzleWidth){
                    xPos = 0;
                    yPos += _pieceHeight;
                }
            }
            document.onmousedown = playField.shufflePuzzle;
        },
        shufflePuzzle:function(){
            _pieces = playField.shuffleArray(_pieces);
            _stage.clearRect(0,0,_puzzleWidth,_puzzleHeight);
            var i;
            var piece;
            var xPos = 0;
            var yPos = 0;
            for(i = 0;i < _pieces.length;i++){
                piece = _pieces[i];
                piece.currentX = xPos;
                piece.currentY = yPos;
                _stage.drawImage(_img, piece.startX, piece.startY, _pieceWidth, _pieceHeight, xPos, yPos, _pieceWidth, _pieceHeight);
                _stage.strokeRect(xPos, yPos, _pieceWidth,_pieceHeight);
                xPos += _pieceWidth;
                if(xPos >= _puzzleWidth){
                    xPos = 0;
                    yPos += _pieceHeight;
                }
            }
            document.onmousedown = playField.onPuzzleClick;
        },
        onPuzzleClick:function(e){
            if(e.layerX || e.layerX == 0){
                _mouse.x = e.layerX - _canvas.offsetLeft;
                _mouse.y = e.layerY - _canvas.offsetTop;
            }
            else if(e.offsetX || e.offsetX == 0){
                _mouse.x = e.offsetX - _canvas.offsetLeft;
                _mouse.y = e.offsetY - _canvas.offsetTop;
            }
            _currentPiece = playField.checkPieceClicked();
            if(_currentPiece != null){
                _stage.clearRect(_currentPiece.currentX,_currentPiece.currentY,_pieceWidth,_pieceHeight);
                _stage.save();
                _stage.globalAlpha = .9;
                _stage.drawImage(_img, _currentPiece.startX, _currentPiece.startY, _pieceWidth, _pieceHeight, _mouse.x - (_pieceWidth / 2), _mouse.y - (_pieceHeight / 2), _pieceWidth, _pieceHeight);
                _stage.restore();
                document.onmousemove = playField.updatePuzzle;
                document.onmouseup = playField.pieceDropped;
            }
        },
        checkPieceClicked:function(){
            var i;
            var piece;
            for(i = 0;i < _pieces.length;i++){
                piece = _pieces[i];
                if(_mouse.x < piece.currentX || _mouse.x > (piece.currentX + _pieceWidth) || _mouse.y < piece.currentY || _mouse.y > (piece.currentY + _pieceHeight)){
                    //PIECE NOT HIT
                }
                else{
                    return piece;
                }
            }
            return null;
        },
        updatePuzzle:function(e){
            _currentDropPiece = null;
            if(e.layerX || e.layerX == 0){
                _mouse.x = e.layerX - _canvas.offsetLeft;
                _mouse.y = e.layerY - _canvas.offsetTop;
            }
            else if(e.offsetX || e.offsetX == 0){
                _mouse.x = e.offsetX - _canvas.offsetLeft;
                _mouse.y = e.offsetY - _canvas.offsetTop;
            }
            _stage.clearRect(0,0,_puzzleWidth,_puzzleHeight);
            var i;
            var piece;
            for(i = 0;i < _pieces.length;i++){
                piece = _pieces[i];
                if(piece == _currentPiece){
                    continue;
                }
                _stage.drawImage(_img, piece.startX, piece.startY, _pieceWidth, _pieceHeight, piece.currentX, piece.currentY, _pieceWidth, _pieceHeight);
                _stage.strokeRect(piece.currentX, piece.currentY, _pieceWidth,_pieceHeight);
                if(_currentDropPiece == null){
                    if(_mouse.x < piece.currentX || _mouse.x > (piece.currentX + _pieceWidth) || _mouse.y < piece.currentY || _mouse.y > (piece.currentY + _pieceHeight)){
                        //NOT OVER
                    }
                    else{
                        _currentDropPiece = piece;
                        _stage.save();
                        _stage.globalAlpha = .4;
                        _stage.fillStyle = PUZZLE_HOVER_TINT;
                        _stage.fillRect(_currentDropPiece.currentX,_currentDropPiece.currentY,_pieceWidth, _pieceHeight);
                        _stage.restore();
                    }
                }
            }
            _stage.save();
            _stage.globalAlpha = .6;
            _stage.drawImage(_img, _currentPiece.startX, _currentPiece.startY, _pieceWidth, _pieceHeight, _mouse.x - (_pieceWidth / 2), _mouse.y - (_pieceHeight / 2), _pieceWidth, _pieceHeight);
            _stage.restore();
            _stage.strokeRect( _mouse.x - (_pieceWidth / 2), _mouse.y - (_pieceHeight / 2), _pieceWidth,_pieceHeight);
        },
        pieceDropped:function(e){
            document.onmousemove = null;
            document.onmouseup = null;
            if(_currentDropPiece != null){
                var tmp = {xPos:_currentPiece.currentX,yPos:_currentPiece.currentY};
                _currentPiece.currentX = _currentDropPiece.currentX;
                _currentPiece.currentY = _currentDropPiece.currentY;
                _currentDropPiece.currentX = tmp.xPos;
                _currentDropPiece.currentY = tmp.yPos;
            }
            playField.resetPuzzleAndCheckWin();
        },
        resetPuzzleAndCheckWin:function(){
            _stage.clearRect(0,0,_puzzleWidth,_puzzleHeight);
            var gameWin = true;
            var i;
            var piece;
            for(i = 0;i < _pieces.length;i++){
                piece = _pieces[i];
                _stage.drawImage(_img, piece.startX, piece.startY, _pieceWidth, _pieceHeight, piece.currentX, piece.currentY, _pieceWidth, _pieceHeight);
                _stage.strokeRect(piece.currentX, piece.currentY, _pieceWidth,_pieceHeight);
                if(piece.currentX != piece.startX || piece.currentY != piece.startY){
                    gameWin = false;
                }
            }
            if(gameWin){
                setTimeout(playField.gameOver,500);
            }
        },
        gameOver:function(){
            document.onmousedown = null;
            document.onmousemove = null;
            document.onmouseup = null;
            playField.initPuzzle();
        },
        shuffleArray:function(o) {
            for (var j, x, i = o.length-1; i>0;i--){
                j = parseInt(Math.random() * i);
                x = o[i];
                o[i] = o[j];
                o[j] = x;
            }
            return o;
        }
    };

    return playField;
}());

function createPlayField(imageSrc,difficulty){
    var plr = Object.create(playField).init(imageSrc,difficulty);
}<commit_msg>A few formatting changes<commit_after>var playField = (function () {

    const PUZZLE_HOVER_TINT = '#009900';

    var _stage, _canvas;

    var _img,
        _pieces,
        _puzzleWidth,
        _puzzleHeight,
        _pieceWidth,
        _pieceHeight,
        _currentPiece,
        _currentDropPiece,
        _mouse,
        _puzzle_difficulty;

    var mouse = (function () {
        var mouse = {
            init: function (x, y) {
                this.x = x;
                this.y = y;
                return this;
            }
        };
        Object.defineProperty(mouse, 'x', {
            get: function () {
                return this._x;
            },
            set: function (value) {
                this._x = value;
            }
        });
        Object.defineProperty(mouse, 'y', {
            get: function () {
                return this._y;
            },
            set: function (value) {
                this._y = value;
            }
        });

        return mouse;
    }());

    var puzzlePiece = (function () {
        var piece = {
            init: function (startX, startY) {
                this.startX = startX;
                this.startY = startY;
                this.currentX = startX;
                this.currentY = startY;
                return this;
            }
        };

        Object.defineProperty(piece, 'startX', {
            get: function () {
                return this._startX;
            },
            set: function (value) {
                this._startX = value;
            }
        });

        Object.defineProperty(piece, 'startY', {
            get: function () {
                return this._startY;
            },
            set: function (value) {
                this._startY = value;
            }
        });
        Object.defineProperty(piece, 'currentX', {
            get: function () {
                return this._currentX;
            },
            set: function (value) {
                this._currentX = value;
            }
        });
        Object.defineProperty(piece, 'currentY', {
            get: function () {
                return this._currentY;
            },
            set: function (value) {
                this._currentY = value;
            }
        });

        return piece;
    }());

    var playField = {
        init: function (imageSrc, difficulty) {
            _img = new Image();
            _img.addEventListener('load', playField.onImage, false);
            _img.src = imageSrc;
            _puzzle_difficulty = difficulty;
            return playField;
        },
        onImage: function (e) {
            _pieceWidth = Math.floor(_img.width / _puzzle_difficulty);
            _pieceHeight = Math.floor(_img.height / _puzzle_difficulty);
            _puzzleWidth = _pieceWidth * _puzzle_difficulty;
            _puzzleHeight = _pieceHeight * _puzzle_difficulty;
            playField.setCanvas();
            playField.initPuzzle();
        },
        setCanvas: function () {
            _canvas = document.getElementById('canvas');
            _stage = _canvas.getContext('2d');
            _canvas.width = _puzzleWidth;
            _canvas.height = _puzzleHeight;
            _canvas.style.border = "1px solid black";
        },
        initPuzzle: function () {
            _pieces = [];
            _mouse = Object.create(mouse).init(0, 0);
            _currentPiece = null;
            _currentDropPiece = null;
            _stage.drawImage(_img, 0, 0, _puzzleWidth, _puzzleHeight, 0, 0, _puzzleWidth, _puzzleHeight);
            playField.createTitle("Click to Start Puzzle");
            playField.buildPieces();
        },
        createTitle: function (msg) {
            _stage.fillStyle = "#000000";
            _stage.globalAlpha = .4;
            _stage.fillRect(100, _puzzleHeight - 40, _puzzleWidth - 200, 40);
            _stage.fillStyle = "#FFFFFF";
            _stage.globalAlpha = 1;
            _stage.textAlign = "center";
            _stage.textBaseline = "middle";
            _stage.font = "20px Arial";
            _stage.fillText(msg, _puzzleWidth / 2, _puzzleHeight - 20);
        },
        buildPieces: function () {
            var i;
            var piece;
            var xPos = 0;
            var yPos = 0;
            for (i = 0; i < _puzzle_difficulty * _puzzle_difficulty; i++) {
                piece = Object.create(puzzlePiece).init(xPos, yPos);
                _pieces.push(piece);
                xPos += _pieceWidth;
                if (xPos >= _puzzleWidth) {
                    xPos = 0;
                    yPos += _pieceHeight;
                }
            }
            document.onmousedown = playField.shufflePuzzle;
        },
        shufflePuzzle: function () {
            _pieces = playField.shuffleArray(_pieces);
            _stage.clearRect(0, 0, _puzzleWidth, _puzzleHeight);
            var i;
            var piece;
            var xPos = 0;
            var yPos = 0;
            for (i = 0; i < _pieces.length; i++) {
                piece = _pieces[i];
                piece.currentX = xPos;
                piece.currentY = yPos;
                _stage.drawImage(_img, piece.startX, piece.startY, _pieceWidth, _pieceHeight, xPos, yPos, _pieceWidth, _pieceHeight);
                _stage.strokeRect(xPos, yPos, _pieceWidth, _pieceHeight);
                xPos += _pieceWidth;
                if (xPos >= _puzzleWidth) {
                    xPos = 0;
                    yPos += _pieceHeight;
                }
            }
            document.onmousedown = playField.onPuzzleClick;
        },
        onPuzzleClick: function (e) {
            if (e.layerX || e.layerX == 0) {
                _mouse.x = e.layerX - _canvas.offsetLeft;
                _mouse.y = e.layerY - _canvas.offsetTop;
            }
            else if (e.offsetX || e.offsetX == 0) {
                _mouse.x = e.offsetX - _canvas.offsetLeft;
                _mouse.y = e.offsetY - _canvas.offsetTop;
            }
            _currentPiece = playField.checkPieceClicked();
            if (_currentPiece != null) {
                _stage.clearRect(_currentPiece.currentX, _currentPiece.currentY, _pieceWidth, _pieceHeight);
                _stage.save();
                _stage.globalAlpha = .9;
                _stage.drawImage(_img, _currentPiece.startX, _currentPiece.startY, _pieceWidth, _pieceHeight, _mouse.x - (_pieceWidth / 2), _mouse.y - (_pieceHeight / 2), _pieceWidth, _pieceHeight);
                _stage.restore();
                document.onmousemove = playField.updatePuzzle;
                document.onmouseup = playField.pieceDropped;
            }
        },
        checkPieceClicked: function () {
            var i;
            var piece;
            for (i = 0; i < _pieces.length; i++) {
                piece = _pieces[i];
                if (_mouse.x < piece.currentX || _mouse.x > (piece.currentX + _pieceWidth) || _mouse.y < piece.currentY || _mouse.y > (piece.currentY + _pieceHeight)) {
                    //PIECE NOT HIT
                }
                else {
                    return piece;
                }
            }
            return null;
        },
        updatePuzzle: function (e) {
            _currentDropPiece = null;
            if (e.layerX || e.layerX == 0) {
                _mouse.x = e.layerX - _canvas.offsetLeft;
                _mouse.y = e.layerY - _canvas.offsetTop;
            }
            else if (e.offsetX || e.offsetX == 0) {
                _mouse.x = e.offsetX - _canvas.offsetLeft;
                _mouse.y = e.offsetY - _canvas.offsetTop;
            }
            _stage.clearRect(0, 0, _puzzleWidth, _puzzleHeight);
            var i;
            var piece;
            for (i = 0; i < _pieces.length; i++) {
                piece = _pieces[i];
                if (piece == _currentPiece) {
                    continue;
                }
                _stage.drawImage(_img, piece.startX, piece.startY, _pieceWidth, _pieceHeight, piece.currentX, piece.currentY, _pieceWidth, _pieceHeight);
                _stage.strokeRect(piece.currentX, piece.currentY, _pieceWidth, _pieceHeight);
                if (_currentDropPiece == null) {
                    if (_mouse.x < piece.currentX || _mouse.x > (piece.currentX + _pieceWidth) || _mouse.y < piece.currentY || _mouse.y > (piece.currentY + _pieceHeight)) {
                        //NOT OVER
                    }
                    else {
                        _currentDropPiece = piece;
                        _stage.save();
                        _stage.globalAlpha = .4;
                        _stage.fillStyle = PUZZLE_HOVER_TINT;
                        _stage.fillRect(_currentDropPiece.currentX, _currentDropPiece.currentY, _pieceWidth, _pieceHeight);
                        _stage.restore();
                    }
                }
            }
            _stage.save();
            _stage.globalAlpha = .6;
            _stage.drawImage(_img, _currentPiece.startX, _currentPiece.startY, _pieceWidth, _pieceHeight, _mouse.x - (_pieceWidth / 2), _mouse.y - (_pieceHeight / 2), _pieceWidth, _pieceHeight);
            _stage.restore();
            _stage.strokeRect(_mouse.x - (_pieceWidth / 2), _mouse.y - (_pieceHeight / 2), _pieceWidth, _pieceHeight);
        },
        pieceDropped: function (e) {
            document.onmousemove = null;
            document.onmouseup = null;
            if (_currentDropPiece != null) {
                var tmp = {xPos: _currentPiece.currentX, yPos: _currentPiece.currentY};
                _currentPiece.currentX = _currentDropPiece.currentX;
                _currentPiece.currentY = _currentDropPiece.currentY;
                _currentDropPiece.currentX = tmp.xPos;
                _currentDropPiece.currentY = tmp.yPos;
            }
            playField.resetPuzzleAndCheckWin();
        },
        resetPuzzleAndCheckWin: function () {
            _stage.clearRect(0, 0, _puzzleWidth, _puzzleHeight);
            var gameWin = true;
            var i;
            var piece;
            for (i = 0; i < _pieces.length; i++) {
                piece = _pieces[i];
                _stage.drawImage(_img, piece.startX, piece.startY, _pieceWidth, _pieceHeight, piece.currentX, piece.currentY, _pieceWidth, _pieceHeight);
                _stage.strokeRect(piece.currentX, piece.currentY, _pieceWidth, _pieceHeight);
                if (piece.currentX != piece.startX || piece.currentY != piece.startY) {
                    gameWin = false;
                }
            }
            if (gameWin) {
                setTimeout(playField.gameOver, 500);
            }
        },
        gameOver: function () {
            document.onmousedown = null;
            document.onmousemove = null;
            document.onmouseup = null;
            playField.initPuzzle();
        },
        shuffleArray: function (o) {
            for (var j, x, i = o.length - 1; i > 0; i--) {
                j = parseInt(Math.random() * i);
                x = o[i];
                o[i] = o[j];
                o[j] = x;
            }
            return o;
        }
    };

    return playField;
}());

function createPlayField(imageSrc, difficulty) {
    var plr = Object.create(playField).init(imageSrc, difficulty);
}<|endoftext|>


<commit_before>import React from 'react';
import { movePiece, holdPiece, releasePiece, showPromoteModal, enhanceMovablePoint, captureBlackPiece, captureWhitePiece } from '../actions';
import { connect } from 'react-redux';
import store from '../stores/index';
import pieceComponent from '../components/piece';

const mapStateToProps = (state) => {
  return {
    board: state.board,
    turn: state.turn
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    onPieceClick: (board, piece) => {
      if (piece.isBlackPromotePlace() || piece.isWhitePromotePlace()) {
        dispatch(showPromoteModal(piece));
      }

      const state = store.getState();

      if (state.shogi.holdingPiece) {
        if (piece.equals(state.shogi.holdingPiece)) {
          dispatch(releasePiece(piece));
        } else {
          dispatch(movePiece(board, piece));

          const capturedPiece = store.getState().shogi.board.takedPiece;

          switch (capturedPiece) {
          case undefined:
            break;
          default:
            switch (capturedPiece.team()) {
            case 'black':
              dispatch(captureBlackPiece(capturedPiece));
            case 'white':
              dispatch(captureWhitePiece(capturedPiece));
            default:
              break;
            }
          }
        }
      } else {
        dispatch(holdPiece(piece));
        dispatch(enhanceMovablePoint(board, piece));
      }
    }
  };
};

const Piece = connect(
  mapStateToProps,
  mapDispatchToProps
)(pieceComponent);

export default Piece;
<commit_msg>if capturedPiece is black, dispatch `captureWhitePiece` action.<commit_after>import React from 'react';
import { movePiece, holdPiece, releasePiece, showPromoteModal, enhanceMovablePoint, captureBlackPiece, captureWhitePiece } from '../actions';
import { connect } from 'react-redux';
import store from '../stores/index';
import pieceComponent from '../components/piece';

const mapStateToProps = (state) => {
  return {
    board: state.board,
    turn: state.turn
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    onPieceClick: (board, piece) => {
      if (piece.isBlackPromotePlace() || piece.isWhitePromotePlace()) {
        dispatch(showPromoteModal(piece));
      }

      const state = store.getState();

      if (state.shogi.holdingPiece) {
        if (piece.equals(state.shogi.holdingPiece)) {
          dispatch(releasePiece(piece));
        } else {
          dispatch(movePiece(board, piece));

          const capturedPiece = store.getState().shogi.board.takedPiece;

          switch (capturedPiece) {
          case undefined:
            break;
          default:
            switch (capturedPiece.team()) {
            case 'black':
              dispatch(captureWhitePiece(capturedPiece));
            case 'white':
              dispatch(captureBlackPiece(capturedPiece));
            default:
              break;
            }
          }
        }
      } else {
        dispatch(holdPiece(piece));
        dispatch(enhanceMovablePoint(board, piece));
      }
    }
  };
};

const Piece = connect(
  mapStateToProps,
  mapDispatchToProps
)(pieceComponent);

export default Piece;
<|endoftext|>


<commit_before>/*jslint indent: 2, nomen: true, maxlen: 100, vars: true, white: true, plusplus: true, stupid: true*/
/*global require, exports, Backbone, activeUser, window, ArangoQuery, $, data, _ */
(function() {
  "use strict";

  window.ArangoQueries = Backbone.Collection.extend({

    initialize: function(models, options) {
      if (options.activeUser) {
        this.activeUser = options.activeUser;
      }
      else {
        this.activeUser = "root";
      }
    },

    url: '/_api/user/',

    model: ArangoQuery,

    activeUser: 0,

    currentExtra: {},

    parse: function(response) {
      var self = this, toReturn;

      _.each(response.result, function(val) {
        if (val.user === self.activeUser) {
          self.currentExtra = val.extra;
          try {
            if (val.extra.queries) {
              toReturn = val.extra.queries;
            }
          }
          catch (e) {
          }
        }
      });
      return toReturn;
    },

    saveCollectionQueries: function() {
      if (this.activeUser === 0) {
        return false;
      }

      var queries = [],
      returnValue1 = false,
      returnValue2 = false,
      returnValue3 = false,
      extraBackup = null,
      self = this;

      this.each(function(query) {
        queries.push({
          value: query.attributes.value,
          name: query.attributes.name
        });
      });

      extraBackup = self.currentExtra;
      extraBackup.queries = [];

      $.ajax({
        cache: false,
        type: "PUT",
        async: false,
        url: "/_api/user/" + this.activeUser,
        data: JSON.stringify({
          extra: extraBackup
        }),
        contentType: "application/json",
        processData: false,
        success: function() {
          returnValue1 = true;
        },
        error: function() {
          returnValue1 = false;
        }
      });

      //save current collection
      $.ajax({
        cache: false,
        type: "PATCH",
        async: false,
        url: "/_api/user/" + this.activeUser,
        data: JSON.stringify({
          extra: {
           queries: queries
          }
        }),
        contentType: "application/json",
        processData: false,
        success: function() {
          returnValue2 = true;
        },
        error: function() {
          returnValue2 = false;
        }
      });

      if (returnValue1 === true && returnValue2 === true) {
        returnValue3 = true;
      }
      else {
        returnValue3 = false;
      }
      return returnValue3;
    },

    saveImportQueries: function(file) {

      if (this.activeUser === 0) {
        return false;
      }

      var queries = [];
      this.each(function(query) {
        queries.push({
          value: query.attributes.value,
          name: query.attributes.name
        });
      });

      var self = this,
      returnValue1 = false,
      returnValue2 = false,
      returnValue3 = false;

      var oldQueries = this.currentExtra;

      $.ajax({
        cache: false,
        type: "PATCH",
        async: false,
        url: "/_api/user/" + this.activeUser,
        data: file,
        contentType: "application/json",
        processData: false,
        success: function() {
          returnValue1 = true;
        },
        error: function() {
          returnValue1 = false;
        }
      });

      this.fetch({
        async: false,
        success: function() {
      }});

      var newQueries = self.currentExtra;

      var nameTaken = false;

      _.each(oldQueries.queries, function(query) {

        _.each(newQueries.queries, function(newQuery) {
          if (newQuery.name === query.name) {
            nameTaken = true;
          }
        });

        if (nameTaken === false) {
          newQueries.queries.push({
            name: query.name,
            value: query.value
          });
        }
      });

      $.ajax({
        cache: false,
        type: "PATCH",
        async: false,
        url: "/_api/user/" + this.activeUser,
        data: JSON.stringify({
          extra: newQueries
        }),
        contentType: "application/json",
        processData: false,
        success: function() {
          returnValue2 = true;
        },
        error: function() {
          returnValue2 = false;
        }
      });

      this.fetch({
        async: false
      });

      if (returnValue1 === true && returnValue2 === true) {
        returnValue3 = true;
      }
      else {
        returnValue3 = false;
      }
      return returnValue3;
    }

  });
}());
<commit_msg>js/collections/arangoQueries.js<commit_after>/*jslint indent: 2, nomen: true, maxlen: 100, vars: true, white: true, plusplus: true, stupid: true*/
/*global require, exports, Backbone, activeUser, window, ArangoQuery, $, data, _ */
(function() {
  "use strict";

  window.ArangoQueries = Backbone.Collection.extend({

    initialize: function(models, options) {
      var result;
      $.ajax("whoAmI", {async:false}).done(
        function(data) {
        result = data.name;
      }
      );
      this.activeUser = result;

      if (this.activeUser === 0 || this.activeUser === undefined || this.activeUser === null) {
        this.activeUser = "root";
      }

    },

    url: '/_api/user/',

    model: ArangoQuery,

    activeUser: 0,

    currentExtra: {},

    parse: function(response) {
      var self = this, toReturn;

      _.each(response.result, function(val) {
        if (val.user === self.activeUser) {
          self.currentExtra = val.extra;
          try {
            if (val.extra.queries) {
              toReturn = val.extra.queries;
            }
          }
          catch (e) {
          }
        }
      });
      return toReturn;
    },

    saveCollectionQueries: function() {
      if (this.activeUser === 0) {
        return false;
      }

      var queries = [],
      returnValue1 = false,
      returnValue2 = false,
      returnValue3 = false,
      extraBackup = null,
      self = this;

      this.each(function(query) {
        queries.push({
          value: query.attributes.value,
          name: query.attributes.name
        });
      });

      extraBackup = self.currentExtra;
      extraBackup.queries = [];

      $.ajax({
        cache: false,
        type: "PUT",
        async: false,
        url: "/_api/user/" + this.activeUser,
        data: JSON.stringify({
          extra: extraBackup
        }),
        contentType: "application/json",
        processData: false,
        success: function() {
          returnValue1 = true;
        },
        error: function() {
          returnValue1 = false;
        }
      });

      //save current collection
      $.ajax({
        cache: false,
        type: "PATCH",
        async: false,
        url: "/_api/user/" + this.activeUser,
        data: JSON.stringify({
          extra: {
           queries: queries
          }
        }),
        contentType: "application/json",
        processData: false,
        success: function() {
          returnValue2 = true;
        },
        error: function() {
          returnValue2 = false;
        }
      });

      if (returnValue1 === true && returnValue2 === true) {
        returnValue3 = true;
      }
      else {
        returnValue3 = false;
      }
      return returnValue3;
    },

    saveImportQueries: function(file) {

      if (this.activeUser === 0) {
        return false;
      }

      var queries = [];
      this.each(function(query) {
        queries.push({
          value: query.attributes.value,
          name: query.attributes.name
        });
      });

      var self = this,
      returnValue1 = false,
      returnValue2 = false,
      returnValue3 = false;

      var oldQueries = this.currentExtra;

      $.ajax({
        cache: false,
        type: "PATCH",
        async: false,
        url: "/_api/user/" + this.activeUser,
        data: file,
        contentType: "application/json",
        processData: false,
        success: function() {
          returnValue1 = true;
        },
        error: function() {
          returnValue1 = false;
        }
      });

      this.fetch({
        async: false,
        success: function() {
      }});

      var newQueries = self.currentExtra;

      var nameTaken = false;

      _.each(oldQueries.queries, function(query) {

        _.each(newQueries.queries, function(newQuery) {
          if (newQuery.name === query.name) {
            nameTaken = true;
          }
        });

        if (nameTaken === false) {
          newQueries.queries.push({
            name: query.name,
            value: query.value
          });
        }
      });

      $.ajax({
        cache: false,
        type: "PATCH",
        async: false,
        url: "/_api/user/" + this.activeUser,
        data: JSON.stringify({
          extra: newQueries
        }),
        contentType: "application/json",
        processData: false,
        success: function() {
          returnValue2 = true;
        },
        error: function() {
          returnValue2 = false;
        }
      });

      this.fetch({
        async: false
      });

      if (returnValue1 === true && returnValue2 === true) {
        returnValue3 = true;
      }
      else {
        returnValue3 = false;
      }
      return returnValue3;
    }

  });
}());
<|endoftext|>


<commit_before>$( document ).ready(function() {
	// create the audio context (chrome only for now)
    if (! window.AudioContext) {
        if (! window.webkitAudioContext) {
            alert('no audiocontext found');
        }
        window.AudioContext = window.webkitAudioContext;
    }

	//audio context variables
	var context = new AudioContext();
    var audioBuffer;
    var sourceNode;
    var splitter;
    var analyser, analyser2;
    var javascriptNode;

	var averageVolume = averageVolume2 = 0;

	var ctx;
	var WIDTH;
	var HEIGHT;
	var intervalId = 0;
	var frame = 0;

	var increment = 1;

	var volumeCenter = 87;

	var catBody = new Image();
	catBody.src = 'img/body.png';
	var bx = bx0 = 245;
	var by = by0 = 750-543;
	var bw;
	var bh;
	//set natural width and natural height once the image is loaded
	if (catBody.addEventListener){
		catBody.addEventListener('load', function(){
			bw = catBody.naturalWidth;
			bh = catBody.naturalHeight;
		}, false);
	} else if (catBody.attachEvent){
		catBody.attachEvent('onload', function(){
			bw = catBody.naturalWidth;
			bh = catBody.naturalHeight;
		});
	}

	var catHead = new Image();
	catHead.src = 'img/head.png';
	var hx = 486;
	var hy = 750-524;
	var hw;
	var hh;
	var hw0;
	var hh0;
	//set natural width and natural height once the image is loaded
	if (catHead.addEventListener){
		catHead.addEventListener('load', function(){
			hw = hw0 = catHead.naturalWidth;
			hh = hh0 = catHead.naturalHeight;
		}, false);
	} else if (catHead.attachEvent){
		catHead.attachEvent('onload', function(){
			hw = hw0 = catHead.naturalWidth;
			hh = hh0 = catHead.naturalHeight;
		});
	}

	var catTail = new Image();
	catTail.src = 'img/tail.png';
	var tx = tx0 = 320;
	var ty = ty0 = 750-642;
	var tw;
	var th;
	//set natural width and natural height once the image is loaded
	if (catTail.addEventListener){
		catTail.addEventListener('load', function(){
			tw = catTail.naturalWidth;
			th = catTail.naturalHeight;
		}, false);
	} else if (catTail.attachEvent){
		catTail.attachEvent('onload', function(){
			tw = catTail.naturalWidth;
			th = catTail.naturalHeight;
		});
	}

	function init(){

		//set canvas context
		var canvas = (typeof(G_vmlCanvasManager) != 'undefined') ? G_vmlCanvasManager.initElement($("canvas#card")[0]) : $("canvas#card")[0];
		ctx = canvas.getContext('2d');
	    ctx.font = "20.0px Arial, Helvetica, sans-serif";
		WIDTH = $("canvas#card").width();
		HEIGHT = $("canvas#card").height();
	}

	function startDrawing(){
		$('button#play').hide();
		intervalId = setInterval(draw, 10);

		//load the wav only if we need it, otherwise load the mp3
		if (typeof window.waapisimContexts != 'undefined'){
			loadSound("audio/bird.wav");
		} else {
			loadSound("audio/bird.mp3");
		}
	}

	function draw(){
		frame ++;
		clear();

		// waves/Path
	      ctx.save();
	      ctx.beginPath();
	      ctx.moveTo(170.0, 510.0);
	      ctx.bezierCurveTo(150.0, 530.0, 170.0, 550.0, 200.0, 550.0);
	      ctx.bezierCurveTo(230.0, 550.0, 230.0, 510.0, 270.0, 510.0);
	      ctx.bezierCurveTo(250.0, 530.0, 270.0, 550.0, 300.0, 550.0);
	      ctx.bezierCurveTo(330.0, 550.0, 330.0, 510.0, 370.0, 510.0);
	      ctx.bezierCurveTo(350.0, 530.0, 370.0, 550.0, 400.0, 550.0);
	      ctx.bezierCurveTo(430.0, 550.0, 430.0, 510.0, 470.0, 510.0);
	      ctx.bezierCurveTo(450.0, 530.0, 470.0, 550.0, 500.0, 550.0);
	      ctx.bezierCurveTo(530.0, 550.0, 530.0, 510.0, 570.0, 510.0);
	      ctx.bezierCurveTo(550.0, 530.0, 570.0, 550.0, 600.0, 550.0);
	      ctx.bezierCurveTo(630.0, 550.0, 630.0, 510.0, 670.0, 510.0);
	      ctx.bezierCurveTo(650.0, 530.0, 670.0, 550.0, 700.0, 550.0);
	      ctx.bezierCurveTo(730.0, 550.0, 730.0, 510.0, 770.0, 510.0);
	      ctx.bezierCurveTo(750.0, 530.0, 770.0, 550.0, 800.0, 550.0);
	      ctx.bezierCurveTo(830.0, 550.0, 830.0, 510.0, 870.0, 510.0);
	      ctx.bezierCurveTo(850.0, 530.0, 870.0, 550.0, 900.0, 550.0);
	      ctx.bezierCurveTo(930.0, 550.0, 930.0, 510.0, 970.0, 510.0);
	      ctx.bezierCurveTo(950.0, 530.0, 970.0, 550.0, 1000.0, 550.0);
	      ctx.bezierCurveTo(1030.0, 550.0, 1030.0, 510.0, 1070.0, 510.0);
	      ctx.bezierCurveTo(1050.0, 530.0, 1070.0, 550.0, 1100.0, 550.0);
	      ctx.bezierCurveTo(1130.0, 550.0, 1130.0, 510.0, 1170.0, 510.0);
	      ctx.bezierCurveTo(1150.0, 530.0, 1170.0, 550.0, 1200.0, 550.0);
	      ctx.bezierCurveTo(1230.0, 550.0, 1230.0, 510.0, 1270.0, 510.0);
	      ctx.bezierCurveTo(1250.0, 530.0, 1270.0, 550.0, 1300.0, 550.0);
	      ctx.bezierCurveTo(1300.0, 570.0, 1300.0, 820.0, 1300.0, 820.0);
	      ctx.lineTo(0.0, 820.0);
	      ctx.lineTo(0.0, 550.0);
	      ctx.bezierCurveTo(30.0, 550.0, 30.0, 510.0, 70.0, 510.0);
	      ctx.bezierCurveTo(50.0, 530.0, 70.0, 550.0, 100.0, 550.0);
	      ctx.bezierCurveTo(130.0, 550.0, 130.0, 510.0, 170.0, 510.0);
	      ctx.closePath();
	      ctx.fillStyle = "rgb(30, 193, 249)";
	      ctx.fill();
	      ctx.restore();

		//draw tail
		if(averageVolume > 0){
			ctx.save();
			ctx.translate(tx, (ty+th));
			ctx.rotate((averageVolume - volumeCenter)*Math.PI/180);
			ctx.translate(0, -th);
			drawCharacter(catTail, 0, 0, tw, th);
			ctx.restore();
		} else {
			drawCharacter(catTail, tx, ty, tw, th);
		}

		//draw head
		if(averageVolume - volumeCenter > 0){
			//increase head width based on volume
			hw = hw0 + (averageVolume - volumeCenter);
			//set head height proportionally to head width
			hh = (hw * (hh0 / hw0) );

			/*
			var headRatio = (hh0 / hw0);
			console.log('headRatio = '+headRatio);
			console.log('hw = '+hw);
			console.log('hh = '+hh);
			*/

			//pulse head size
			ctx.save();
			ctx.translate( hx, hy );
			drawCharacter(catHead, 0, -(hh-hh0), hw, hh);
			ctx.restore();
		} else {
			//reset width and height to natural size
			hw = hw0;
			hh = hh0;
			drawCharacter(catHead, hx, hy, hw, hh);
		}

		//draw body
		drawCharacter(catBody, bx, by, bw, bh);

		// create the meters
        /*
		ctx.fillRect(0,130-averageVolume,25,130);
        ctx.fillRect(30,130-averageVolume2,25,130);
		*/

		//show audio levels
		/*
		console.log(averageVolume);
		console.log(averageVolume2);
		*/

		/*
		//create a new random emflake
		emflakew = getRandomInt(50, ew);
		emflakeh = (emflakew * eh / ew);
		emflakex = getRandomInt(0 - (emflakew/2), WIDTH - (emflakew/2));

		//move all emflakes

		if (value.thisy <= HEIGHT){
			drawCharacter(emflake, value.thisx, value.thisy, value.thisw, value.thish);
			value.thisy += value.increment;
		}
		else {
			//remove the emflake from the array if it is off screen
			emflakes.splice(index, 1);
			return false;
		}
		*/

	} //end draw

	function drawCharacter(name, x, y, w, h){
		ctx.drawImage(name, x, y, w, h);
	}

	function clear() {
	  ctx.clearRect(0, 0, WIDTH, HEIGHT);
	}

	function getRandomInt (min, max) {
	    return Math.floor(Math.random() * (max - min + 1)) + min;
	}

	function setupAudioNodes() {

        // setup a javascript node
        javascriptNode = context.createScriptProcessor(2048, 1, 1);
        // connect to destination, else it isn't called
        javascriptNode.connect(context.destination);

        // setup a analyzer
        analyser = context.createAnalyser();
        analyser.smoothingTimeConstant = 0.3;
        analyser.fftSize = 1024;

        analyser2 = context.createAnalyser();
        analyser2.smoothingTimeConstant = 0.0;
        analyser2.fftSize = 1024;

        // create a buffer source node
        sourceNode = context.createBufferSource();
        splitter = context.createChannelSplitter();

        // connect the source to the analyser and the splitter
        sourceNode.connect(splitter);

        // connect one of the outputs from the splitter to
        // the analyser
        splitter.connect(analyser,0,0);
        splitter.connect(analyser2,1,0);

        // connect the splitter to the javascriptnode
        // we use the javascript node to draw at a
        // specific interval.
        analyser.connect(javascriptNode);

//        splitter.connect(context.destination,0,0);
//        splitter.connect(context.destination,0,1);

        // and connect to destination
        sourceNode.connect(context.destination);
    }

    // load the specified sound
    function loadSound(url) {
        var request = new XMLHttpRequest();
        request.open('GET', url, true);
        request.responseType = 'arraybuffer';

        // When loaded decode the data
        request.onload = function() {

            // decode the data
            context.decodeAudioData(request.response, function(buffer) {
                // when the audio is decoded play the sound
                playSound(buffer);
            }, onError);
        }
        request.send();
    }

    function playSound(buffer) {
        sourceNode.buffer = buffer;
        sourceNode.start(0);
    }

	// log if an error occurs
    function onError(e) {
        console.log(e);
    }

	init();

    setupAudioNodes();

	// when the javascript node is called
    // we use information from the analyzer node
    // to draw the volume
    javascriptNode.onaudioprocess = function() {

        // get the average for the first channel
        var array =  new Uint8Array(analyser.frequencyBinCount);
        analyser.getByteFrequencyData(array);
        averageVolume = getAverageVolume(array);

        // get the average for the second channel
        var array2 =  new Uint8Array(analyser2.frequencyBinCount);
        analyser2.getByteFrequencyData(array2);
        averageVolume2 = getAverageVolume(array2);

        // clear the current state
        //ctx.clearRect(0, 0, 60, 130);
    }

    function getAverageVolume(array) {
        var values = 0;
        var average;

        var length = array.length;

        // get all the frequency amplitudes
        for (var i = 0; i < length; i++) {
            values += array[i];
        }

        average = values / length;
        return average;
    }

	$('button#play').on('click', startDrawing );
//end document ready
});<commit_msg>waves moving, gap at the left<commit_after>$( document ).ready(function() {
	// create the audio context (chrome only for now)
    if (! window.AudioContext) {
        if (! window.webkitAudioContext) {
            alert('no audiocontext found');
        }
        window.AudioContext = window.webkitAudioContext;
    }

	//audio context variables
	var context = new AudioContext();
    var audioBuffer;
    var sourceNode;
    var splitter;
    var analyser, analyser2;
    var javascriptNode;

	var averageVolume = averageVolume2 = 0;

	var ctx;
	var WIDTH;
	var HEIGHT;
	var intervalId = 0;
	var frame = 0;

	var increment = 1;

	var volumeCenter = 87;

	//wave variables

		//amount to move waves
		var waveOffset = 0;

		//pixels between peaks of waves
		var waveInterval = 100;

	var catBody = new Image();
	catBody.src = 'img/body.png';
	var bx = bx0 = 245;
	var by = by0 = 750-543;
	var bw;
	var bh;
	//set natural width and natural height once the image is loaded
	if (catBody.addEventListener){
		catBody.addEventListener('load', function(){
			bw = catBody.naturalWidth;
			bh = catBody.naturalHeight;
		}, false);
	} else if (catBody.attachEvent){
		catBody.attachEvent('onload', function(){
			bw = catBody.naturalWidth;
			bh = catBody.naturalHeight;
		});
	}

	var catHead = new Image();
	catHead.src = 'img/head.png';
	var hx = 486;
	var hy = 750-524;
	var hw;
	var hh;
	var hw0;
	var hh0;
	//set natural width and natural height once the image is loaded
	if (catHead.addEventListener){
		catHead.addEventListener('load', function(){
			hw = hw0 = catHead.naturalWidth;
			hh = hh0 = catHead.naturalHeight;
		}, false);
	} else if (catHead.attachEvent){
		catHead.attachEvent('onload', function(){
			hw = hw0 = catHead.naturalWidth;
			hh = hh0 = catHead.naturalHeight;
		});
	}

	var catTail = new Image();
	catTail.src = 'img/tail.png';
	var tx = tx0 = 320;
	var ty = ty0 = 750-642;
	var tw;
	var th;
	//set natural width and natural height once the image is loaded
	if (catTail.addEventListener){
		catTail.addEventListener('load', function(){
			tw = catTail.naturalWidth;
			th = catTail.naturalHeight;
		}, false);
	} else if (catTail.attachEvent){
		catTail.attachEvent('onload', function(){
			tw = catTail.naturalWidth;
			th = catTail.naturalHeight;
		});
	}

	function init(){

		//set canvas context
		var canvas = (typeof(G_vmlCanvasManager) != 'undefined') ? G_vmlCanvasManager.initElement($("canvas#card")[0]) : $("canvas#card")[0];
		ctx = canvas.getContext('2d');
	    ctx.font = "20.0px Arial, Helvetica, sans-serif";
		WIDTH = $("canvas#card").width();
		HEIGHT = $("canvas#card").height();
	}

	function startDrawing(){
		$('button#play').hide();
		intervalId = setInterval(draw, 10);

		//load the wav only if we need it, otherwise load the mp3
		if (typeof window.waapisimContexts != 'undefined'){
			loadSound("audio/bird.wav");
		} else {
			loadSound("audio/bird.mp3");
		}
	}

	function draw(){
		frame ++;
		clear();

		if (waveOffset == 100) waveOffset = 0;

		// waves/Path
	      ctx.save();
	      ctx.beginPath();
	      ctx.moveTo(170.0 + waveOffset, 510.0);
	      ctx.bezierCurveTo(150.0 + waveOffset, 530.0, 170.0 + waveOffset, 550.0, 200.0 + waveOffset, 550.0);
	      ctx.bezierCurveTo(230.0 + waveOffset, 550.0, 230.0 + waveOffset, 510.0, 270.0 + waveOffset, 510.0);
	      ctx.bezierCurveTo(250.0 + waveOffset, 530.0, 270.0 + waveOffset, 550.0, 300.0 + waveOffset, 550.0);
	      ctx.bezierCurveTo(330.0 + waveOffset, 550.0, 330.0 + waveOffset, 510.0, 370.0 + waveOffset, 510.0);
	      ctx.bezierCurveTo(350.0 + waveOffset, 530.0, 370.0 + waveOffset, 550.0, 400.0 + waveOffset, 550.0);
	      ctx.bezierCurveTo(430.0 + waveOffset, 550.0, 430.0 + waveOffset, 510.0, 470.0 + waveOffset, 510.0);
	      ctx.bezierCurveTo(450.0 + waveOffset, 530.0, 470.0 + waveOffset, 550.0, 500.0 + waveOffset, 550.0);
	      ctx.bezierCurveTo(530.0 + waveOffset, 550.0, 530.0 + waveOffset, 510.0, 570.0 + waveOffset, 510.0);
	      ctx.bezierCurveTo(550.0 + waveOffset, 530.0, 570.0 + waveOffset, 550.0, 600.0 + waveOffset, 550.0);
	      ctx.bezierCurveTo(630.0 + waveOffset, 550.0, 630.0 + waveOffset, 510.0, 670.0 + waveOffset, 510.0);
	      ctx.bezierCurveTo(650.0 + waveOffset, 530.0, 670.0 + waveOffset, 550.0, 700.0 + waveOffset, 550.0);
	      ctx.bezierCurveTo(730.0 + waveOffset, 550.0, 730.0 + waveOffset, 510.0, 770.0 + waveOffset, 510.0);
	      ctx.bezierCurveTo(750.0 + waveOffset, 530.0, 770.0 + waveOffset, 550.0, 800.0 + waveOffset, 550.0);
	      ctx.bezierCurveTo(830.0 + waveOffset, 550.0, 830.0 + waveOffset, 510.0, 870.0 + waveOffset, 510.0);
	      ctx.bezierCurveTo(850.0 + waveOffset, 530.0, 870.0 + waveOffset, 550.0, 900.0 + waveOffset, 550.0);
	      ctx.bezierCurveTo(930.0 + waveOffset, 550.0, 930.0 + waveOffset, 510.0, 970.0 + waveOffset, 510.0);
	      ctx.bezierCurveTo(950.0 + waveOffset, 530.0, 970.0 + waveOffset, 550.0, 1000.0 + waveOffset, 550.0);
	      ctx.bezierCurveTo(1030.0 + waveOffset, 550.0, 1030.0 + waveOffset, 510.0, 1070.0 + waveOffset, 510.0);
	      ctx.bezierCurveTo(1050.0 + waveOffset, 530.0, 1070.0 + waveOffset, 550.0, 1100.0 + waveOffset, 550.0);
	      ctx.bezierCurveTo(1130.0 + waveOffset, 550.0, 1130.0 + waveOffset, 510.0, 1170.0 + waveOffset, 510.0);
	      ctx.bezierCurveTo(1150.0 + waveOffset, 530.0, 1170.0 + waveOffset, 550.0, 1200.0 + waveOffset, 550.0);
	      ctx.bezierCurveTo(1230.0 + waveOffset, 550.0, 1230.0 + waveOffset, 510.0, 1270.0 + waveOffset, 510.0);
	      ctx.bezierCurveTo(1250.0 + waveOffset, 530.0, 1270.0 + waveOffset, 550.0, 1300.0 + waveOffset, 550.0);
	      ctx.bezierCurveTo(1300.0 + waveOffset, 570.0, 1300.0 + waveOffset, 820.0, 1300.0 + waveOffset, 820.0);
	      ctx.lineTo(0.0 + waveOffset, 820.0);
	      ctx.lineTo(0.0 + waveOffset, 550.0);
	      ctx.bezierCurveTo(30.0 + waveOffset, 550.0, 30.0 + waveOffset, 510.0, 70.0 + waveOffset, 510.0);
	      ctx.bezierCurveTo(50.0 + waveOffset, 530.0, 70.0 + waveOffset, 550.0, 100.0 + waveOffset, 550.0);
	      ctx.bezierCurveTo(130.0 + waveOffset, 550.0, 130.0 + waveOffset, 510.0, 170.0 + waveOffset, 510.0);
	      ctx.closePath();
	      ctx.fillStyle = "rgb(30, 193, 249)";
	      ctx.fill();
	      ctx.restore();

		waveOffset ++;

		//draw tail
		if(averageVolume > 0){
			ctx.save();
			ctx.translate(tx, (ty+th));
			ctx.rotate((averageVolume - volumeCenter)*Math.PI/180);
			ctx.translate(0, -th);
			drawCharacter(catTail, 0, 0, tw, th);
			ctx.restore();
		} else {
			drawCharacter(catTail, tx, ty, tw, th);
		}

		//draw head
		if(averageVolume - volumeCenter > 0){
			//increase head width based on volume
			hw = hw0 + (averageVolume - volumeCenter);
			//set head height proportionally to head width
			hh = (hw * (hh0 / hw0) );

			/*
			var headRatio = (hh0 / hw0);
			console.log('headRatio = '+headRatio);
			console.log('hw = '+hw);
			console.log('hh = '+hh);
			*/

			//pulse head size
			ctx.save();
			ctx.translate( hx, hy );
			drawCharacter(catHead, 0, -(hh-hh0), hw, hh);
			ctx.restore();
		} else {
			//reset width and height to natural size
			hw = hw0;
			hh = hh0;
			drawCharacter(catHead, hx, hy, hw, hh);
		}

		//draw body
		drawCharacter(catBody, bx, by, bw, bh);

		// create the meters
        /*
		ctx.fillRect(0,130-averageVolume,25,130);
        ctx.fillRect(30,130-averageVolume2,25,130);
		*/

		//show audio levels
		/*
		console.log(averageVolume);
		console.log(averageVolume2);
		*/

		/*
		//create a new random emflake
		emflakew = getRandomInt(50, ew);
		emflakeh = (emflakew * eh / ew);
		emflakex = getRandomInt(0 - (emflakew/2), WIDTH - (emflakew/2));

		//move all emflakes

		if (value.thisy <= HEIGHT){
			drawCharacter(emflake, value.thisx, value.thisy, value.thisw, value.thish);
			value.thisy += value.increment;
		}
		else {
			//remove the emflake from the array if it is off screen
			emflakes.splice(index, 1);
			return false;
		}
		*/

	} //end draw

	function drawCharacter(name, x, y, w, h){
		ctx.drawImage(name, x, y, w, h);
	}

	function clear() {
	  ctx.clearRect(0, 0, WIDTH, HEIGHT);
	}

	function getRandomInt (min, max) {
	    return Math.floor(Math.random() * (max - min + 1)) + min;
	}

	function setupAudioNodes() {

        // setup a javascript node
        javascriptNode = context.createScriptProcessor(2048, 1, 1);
        // connect to destination, else it isn't called
        javascriptNode.connect(context.destination);

        // setup a analyzer
        analyser = context.createAnalyser();
        analyser.smoothingTimeConstant = 0.3;
        analyser.fftSize = 1024;

        analyser2 = context.createAnalyser();
        analyser2.smoothingTimeConstant = 0.0;
        analyser2.fftSize = 1024;

        // create a buffer source node
        sourceNode = context.createBufferSource();
        splitter = context.createChannelSplitter();

        // connect the source to the analyser and the splitter
        sourceNode.connect(splitter);

        // connect one of the outputs from the splitter to
        // the analyser
        splitter.connect(analyser,0,0);
        splitter.connect(analyser2,1,0);

        // connect the splitter to the javascriptnode
        // we use the javascript node to draw at a
        // specific interval.
        analyser.connect(javascriptNode);

//        splitter.connect(context.destination,0,0);
//        splitter.connect(context.destination,0,1);

        // and connect to destination
        sourceNode.connect(context.destination);
    }

    // load the specified sound
    function loadSound(url) {
        var request = new XMLHttpRequest();
        request.open('GET', url, true);
        request.responseType = 'arraybuffer';

        // When loaded decode the data
        request.onload = function() {

            // decode the data
            context.decodeAudioData(request.response, function(buffer) {
                // when the audio is decoded play the sound
                playSound(buffer);
            }, onError);
        }
        request.send();
    }

    function playSound(buffer) {
        sourceNode.buffer = buffer;
        sourceNode.start(0);
    }

	// log if an error occurs
    function onError(e) {
        console.log(e);
    }

	init();

    setupAudioNodes();

	// when the javascript node is called
    // we use information from the analyzer node
    // to draw the volume
    javascriptNode.onaudioprocess = function() {

        // get the average for the first channel
        var array =  new Uint8Array(analyser.frequencyBinCount);
        analyser.getByteFrequencyData(array);
        averageVolume = getAverageVolume(array);

        // get the average for the second channel
        var array2 =  new Uint8Array(analyser2.frequencyBinCount);
        analyser2.getByteFrequencyData(array2);
        averageVolume2 = getAverageVolume(array2);

        // clear the current state
        //ctx.clearRect(0, 0, 60, 130);
    }

    function getAverageVolume(array) {
        var values = 0;
        var average;

        var length = array.length;

        // get all the frequency amplitudes
        for (var i = 0; i < length; i++) {
            values += array[i];
        }

        average = values / length;
        return average;
    }

	$('button#play').on('click', startDrawing );
//end document ready
});<|endoftext|>


<commit_before>import { BackSide, NoBlending } from '../constants.js';
import { Scene } from '../scenes/Scene.js';
import { Mesh } from '../objects/Mesh.js';
import { BoxBufferGeometry } from '../geometries/BoxGeometry.js';
import { ShaderMaterial } from '../materials/ShaderMaterial.js';
import { cloneUniforms } from './shaders/UniformsUtils.js';
import { WebGLRenderTarget } from './WebGLRenderTarget.js';
import { CubeCamera } from '../cameras/CubeCamera.js';

/**
 * @author alteredq / http://alteredqualia.com
 * @author WestLangley / http://github.com/WestLangley
 */

function WebGLCubeRenderTarget( size, options, dummy ) {

	if ( Number.isInteger( options ) ) {

		console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );

		options = dummy;

	}

	WebGLRenderTarget.call( this, size, size, options );

}

WebGLCubeRenderTarget.prototype = Object.create( WebGLRenderTarget.prototype );
WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;

WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;

WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function ( renderer, texture ) {

	this.texture.type = texture.type;
	this.texture.format = texture.format;
	this.texture.encoding = texture.encoding;

	this.texture.generateMipmaps = texture.generateMipmaps;
	this.texture.minFilter = texture.minFilter;
	this.texture.magFilter = texture.magFilter;

	const scene = new Scene();

	const shader = {

		uniforms: {
			tEquirect: { value: null },
		},

		vertexShader: /* glsl */`

			varying vec3 vWorldDirection;

			vec3 transformDirection( in vec3 dir, in mat4 matrix ) {

				return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );

			}

			void main() {

				vWorldDirection = transformDirection( position, modelMatrix );

				#include <begin_vertex>
				#include <project_vertex>

			}
		`,

		fragmentShader: /* glsl */`

			uniform sampler2D tEquirect;

			varying vec3 vWorldDirection;

			#include <common>

			void main() {

				vec3 direction = normalize( vWorldDirection );

				vec2 sampleUV = equirectUv( direction );

				gl_FragColor = texture2D( tEquirect, sampleUV );

			}
		`
	};

	const material = new ShaderMaterial( {

		name: 'CubemapFromEquirect',

		uniforms: cloneUniforms( shader.uniforms ),
		vertexShader: shader.vertexShader,
		fragmentShader: shader.fragmentShader,
		side: BackSide,
		blending: NoBlending

	} );

	material.uniforms.tEquirect.value = texture;

	const mesh = new Mesh( new BoxBufferGeometry( 5, 5, 5 ), material );

	scene.add( mesh );

	const camera = new CubeCamera( 1, 10, this );
	camera.update( renderer, scene );

	mesh.geometry.dispose();
	mesh.material.dispose();

	return this;

};

export { WebGLCubeRenderTarget };
<commit_msg>default to RGBA format<commit_after>import { BackSide, NoBlending, RGBAFormat } from '../constants.js';
import { Scene } from '../scenes/Scene.js';
import { Mesh } from '../objects/Mesh.js';
import { BoxBufferGeometry } from '../geometries/BoxGeometry.js';
import { ShaderMaterial } from '../materials/ShaderMaterial.js';
import { cloneUniforms } from './shaders/UniformsUtils.js';
import { WebGLRenderTarget } from './WebGLRenderTarget.js';
import { CubeCamera } from '../cameras/CubeCamera.js';

/**
 * @author alteredq / http://alteredqualia.com
 * @author WestLangley / http://github.com/WestLangley
 */

function WebGLCubeRenderTarget( size, options, dummy ) {

	if ( Number.isInteger( options ) ) {

		console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );

		options = dummy;

	}

	WebGLRenderTarget.call( this, size, size, options );

}

WebGLCubeRenderTarget.prototype = Object.create( WebGLRenderTarget.prototype );
WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;

WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;

WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function ( renderer, texture ) {

	this.texture.type = texture.type;
	this.texture.format = RGBAFormat; // see #18859
	this.texture.encoding = texture.encoding;

	this.texture.generateMipmaps = texture.generateMipmaps;
	this.texture.minFilter = texture.minFilter;
	this.texture.magFilter = texture.magFilter;

	const scene = new Scene();

	const shader = {

		uniforms: {
			tEquirect: { value: null },
		},

		vertexShader: /* glsl */`

			varying vec3 vWorldDirection;

			vec3 transformDirection( in vec3 dir, in mat4 matrix ) {

				return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );

			}

			void main() {

				vWorldDirection = transformDirection( position, modelMatrix );

				#include <begin_vertex>
				#include <project_vertex>

			}
		`,

		fragmentShader: /* glsl */`

			uniform sampler2D tEquirect;

			varying vec3 vWorldDirection;

			#include <common>

			void main() {

				vec3 direction = normalize( vWorldDirection );

				vec2 sampleUV = equirectUv( direction );

				gl_FragColor = texture2D( tEquirect, sampleUV );

			}
		`
	};

	const material = new ShaderMaterial( {

		name: 'CubemapFromEquirect',

		uniforms: cloneUniforms( shader.uniforms ),
		vertexShader: shader.vertexShader,
		fragmentShader: shader.fragmentShader,
		side: BackSide,
		blending: NoBlending

	} );

	material.uniforms.tEquirect.value = texture;

	const mesh = new Mesh( new BoxBufferGeometry( 5, 5, 5 ), material );

	scene.add( mesh );

	const camera = new CubeCamera( 1, 10, this );
	camera.update( renderer, scene );

	mesh.geometry.dispose();
	mesh.material.dispose();

	return this;

};

export { WebGLCubeRenderTarget };
<|endoftext|>


<commit_before>import Proto from 'uberproto';
import makeDebug from 'debug';
import filter from 'feathers-query-filters';
import * as utils from './utils';

const debug = makeDebug('feathers-couchdb-nano');

const FILE_EXISTS = 'file_exists';

class Service {
  constructor (options) {
    if (!options) {
      throw new Error('CouchDB options have to be provided')
    }

    // if (!options.nano || !options.nano.use) {
    //   throw new Error('You must provide a Apache CouchDB Nano database');
    // }

    if (!options.db || !options.db.insert) {
      throw new Error('You must provide a Apache CouchDB Nano database');
    }

    if (!options.Model) {
      throw new Error('You must provide a CouchDB Model name')
    }

    this.id = options.id || '_id';
    this.events = options.events || [];
    this.paginate = options.paginate || {};
    this.Model = options.Model.toString().toLowerCase();
    this.nano = options.nano;
    this.db = options.db;

    // this.db = this._getOrCreateDb();
  }

  extend (obj) {
    return Proto.extend(obj, this);
  }

  /**
   * Get or create a database.
   *
   * NOTE: Currently not used.
   */
  _getOrCreateDb () {
    const nano = this.nano;
    const db = this.Model;

    return new Promise((resolve, reject) => {
      nano.db.create(db, function(err, body, header) {

        // Reject all errors except existing database.
        if (err && err.error !== FILE_EXISTS) {
          return reject(err);
        }

        resolve(nano.use(db));
      });
    });
  }

  _find (params, getFilter = filter) {
    const db = this.db;
    const { filters, query } = getFilter(params.query || {});
    const options = {
      limit: filters.$limit || paginate.default || 100,
      skip: filters.$skip || 0
    };

    return new Promise((resolve, reject) => {
      return db.view('patients', 'all', options, (err, body) => {
        const rows = body.rows;
        const n = rows.length;
        let data = [];

        if (err) {
          return reject(err);
        }

        for (let i = 0; i < n; i++) {
          const item = rows[i].key;
          const select = filters.$select;
          const m = select && Array.isArray(select) && select.length;

          data[i] = item;
          data[i].id = item._id;

          delete data[i]._id;
          delete data[i]._rev;

          if (m && m.length > 0) {
            let tmp = {};

            for (let j = 0; j < m; j++) {
              tmp[select[j]] = rows[i][select[j]];
            }

            data[i] = tmp;
          }
        }

        resolve({
          /* jshint camelcase: false */
          total: body.total_rows,
          skip: body.offset,
          limit: options.limit,
          data: data
        });
      });
    });
  }

  // Boilerplate
  find (params) {
    const db = this.db;
    const paginate = params && typeof params.paginate !== 'undefined' ? params.paginate : this.paginate;
    const result = this._find(params, where => filter(where, paginate));

    return result.then(result => {
      return {
        total: result.total,
        limit: result.limit,
        skip: result.skip,
        data: result.data
      };
    }).catch(utils.errorHandler);
  }

  get(id, params) {}
  create(data, params) {}
  update(id, data, params) {}
  patch(id, data, params) {}
  remove(id, params) {}
  setup(app, path) {}
}

export default function init (options) {
  return new Service(options);
}

init.Service = Service;
<commit_msg>Remove database get or create functionality.<commit_after>import Proto from 'uberproto';
import makeDebug from 'debug';
import filter from 'feathers-query-filters';
import * as utils from './utils';

const debug = makeDebug('feathers-couchdb-nano');

const FILE_EXISTS = 'file_exists';

class Service {
  constructor (options) {
    if (!options) {
      throw new Error('CouchDB options have to be provided')
    }

    if (!options.db || !options.db.insert) {
      throw new Error('You must provide a Apache CouchDB Nano database');
    }

    if (!options.Model) {
      throw new Error('You must provide a CouchDB Model name')
    }

    this.id = options.id || '_id';
    this.events = options.events || [];
    this.paginate = options.paginate || {};
    this.Model = options.Model.toString().toLowerCase();
    this.nano = options.nano;
    this.db = options.db;
  }

  extend (obj) {
    return Proto.extend(obj, this);
  }

  _find (params, getFilter = filter) {
    const db = this.db;
    const { filters, query } = getFilter(params.query || {});

    const options = {
      limit: filters.$limit || paginate.default || 100,
      skip: filters.$skip || 0
    };

    return new Promise((resolve, reject) => {
      return db.view('patients', 'all', options, (err, body) => {
        const rows = body.rows;
        const n = rows.length;
        let data = [];

        if (err) {
          return reject(err);
        }

        for (let i = 0; i < n; i++) {
          const item = rows[i].key;
          const select = filters.$select;
          const m = select && Array.isArray(select) && select.length;

          data[i] = item;
          data[i].id = item._id;

          delete data[i]._id;
          delete data[i]._rev;

          if (m && m.length > 0) {
            let tmp = {};

            for (let j = 0; j < m; j++) {
              tmp[select[j]] = rows[i][select[j]];
            }

            data[i] = tmp;
          }
        }

        resolve({
          /* jshint camelcase: false */
          total: body.total_rows,
          skip: body.offset,
          limit: options.limit,
          data: data
        });
      });
    });
  }

  // Boilerplate
  find (params) {
    const db = this.db;
    const paginate = params && typeof params.paginate !== 'undefined' ? params.paginate : this.paginate;
    const result = this._find(params, where => filter(where, paginate));

    return result.then(result => {
      return {
        total: result.total,
        limit: result.limit,
        skip: result.skip,
        data: result.data
      };
    }).catch(utils.errorHandler);
  }

  get(id, params) {}
  create(data, params) {}
  update(id, data, params) {}
  patch(id, data, params) {}
  remove(id, params) {}
  setup(app, path) {}
}

export default function init (options) {
  return new Service(options);
}

init.Service = Service;
<|endoftext|>


<commit_before>export { init, testCorrectness, disposeResources };

import * as Pool from "../util/Pool.js";
import * as Recyclable from "../util/Recyclable.js";
import * as ValueDesc from "../Unpacker/ValueDesc.js";
import * as Weights from "../Unpacker/Weights.js";
//import * as ActivationEscaping from "../Conv/ActivationEscaping.js";
import * as BoundsArraySet from "../Conv/BoundsArraySet.js";
import * as NeuralNet from "../Conv/NeuralNet.js";
import * as NeuralNet_Reference from "./Ref/NeuralNet_Reference.js";
import * as NeuralNet_TestParams from "./Ref/NeuralNet_TestParams.js";
import * as ImageSourceBag from "./Ref/ImageSourceBag.js";
import * as NumberImage from "./Ref/NumberImage.js";
import * as BatchIdCalculator from "./BatchIdCalculator.js";

/**
 * Test CNN NeuralNet.
 *
 * @see {@link https://www.measurethat.net/Benchmarks/Show/20203/54/colorfulcakechen-cnn-neuralnet-4d36f0e2ffd053a25457d9b6}
 */

/**
 *
 */
class PerformanceTestCase {

  constructor( testCaseId, testCaseName, neuralNetTestParams ) {
    this.testCaseId = testCaseId;
    this.testCaseName = testCaseName;
    this.neuralNetTestParams = neuralNetTestParams;
    this.neuralNet = undefined;
    //this.inputTensor3d = undefined;
  }

  /**
   * Create .neuralNet
   */
  prepare() {
    try {

//!!! (2022/08/16 Remarked) Use canvas instead.
//       // Pre-create performance test case's input image.
//       let inputImage = this.testPerformance_imageSourceBag.getImage_by(
//         neuralNetTestParams.out.input_height,
//         neuralNetTestParams.out.input_width,
//         neuralNetTestParams.out.input_channelCount );
//
//       // Pre-create performance test case's input tensor.
//       let inputTensor3d = this.testPerformance_imageSourceBag.getTensor3d_by(
//         neuralNetTestParams.out.input_height,
//         neuralNetTestParams.out.input_width,
//         neuralNetTestParams.out.input_channelCount );

      this.neuralNet = NeuralNet_Reference.Base.NeuralNet_create( this.neuralNetTestParams );

      console.log( `NeuralNet.${this.testCaseName}: tensorWeightCount = { `
        + `Extracted: ${this.neuralNet.tensorWeightCountExtracted}, `
        + `Total: ${this.neuralNet.tensorWeightCountTotal} }` );

    } catch ( e ) {
      debugger;
      throw e;
    }
  }

}

/**
 * A test set.
 */
class HeightWidthDepth {

  /**
   * @param {number} height            image height
   * @param {number} width             image width
   * @param {number} depth             image channel count
   */
  constructor( height, width, depth ) {

    this.disposeResources();

    this.height = height;
    this.width = width;
    this.depth = depth;

    this.valueCount = height * width * depth;
  }

  disposeResources() {
    this.neuralNet_PerformanceTest_release();
    this.testCanvas = null;
  }

  /**
   *
   */
  neuralNet_PerformanceTest_addCase( testCaseName, neuralNetTestParams ) {
    let aPerformanceTestCase = new PerformanceTestCase(
      neuralNetTestParams.id, testCaseName, neuralNetTestParams );

    this.testCaseMap.set( testCaseName, aPerformanceTestCase );
  }

  neuralNet_PerformanceTest_init() {

    // Release dataTensor3d too. Because perofrmance testing uses larger different input image from correctness testing.
    this.disposeResources();

    // Larger input image for performance testing.
    this.testPerformance_imageSourceBag = ImageSourceBag.Base.Pool.get_or_create_by( "int32" );

    {
      let largerHeight = this.height * 10;
      let largerWidth = this.width * 10;
      let inputChannelCount = this.depth; // Must be 4;

      this.testCanvas = document.createElement( "canvas" );
      this.testCanvas.height = largerHeight;
      this.testCanvas.width = largerWidth;

      let inputImage = this.testPerformance_imageSourceBag.getImage_by(
        largerHeight, largerWidth, inputChannelCount );

      let ctx = this.testCanvas.getContext( "2d" );
      let imageData = ctx.createImageData( largerHeight, largerWidth );
      for ( let i = 0; i < imageData.data.length; ++i ) {
        imageData.data[ i ] = inputImage.dataArray[ i ];
      }

      ctx.putImageData( imageData, 0 , 0 );
    }

    this.testPerformance_imageSourceBag.clear(); // Reduce memory.

    if ( this.testCaseMap )
      this.testCaseMap.clear();
    else
      this.testCaseMap = new Map();

    let vocabularyChannelCount = 4;
    let vocabularyCountPerInputChannel = 256;
    let stageCountRequested = 7; //5;
    let blockCountRequested = 10; //5;

    // The neuralNet performance testing should not keep-input-tensor. The reason input
    // image is created from canvas in real time.
    let bKeepInputTensor = false;

    // input_height, input_width, input_channelCount,
    // vocabularyChannelCount, vocabularyCountPerInputChannel,
    // nConvStageTypeId,
    // stageCountRequested, blockCountRequested, bKeepInputTensor
    //

    // Test Case 0: (MobileNetV1)
    this.neuralNet_PerformanceTest_addCase( "MobileNetV1",
      ( new NeuralNet_TestParams.Base( 0 ) ).set_byParamsScattered(
        this.height, this.width, this.depth,
        vocabularyChannelCount, vocabularyCountPerInputChannel,
        ValueDesc.ConvStageType.Singleton.Ids.MOBILE_NET_V1,
        stageCountRequested, blockCountRequested, bKeepInputTensor
      ) );

    // Test Case 1: (MobileNetV1_padValid)
    this.neuralNet_PerformanceTest_addCase( "MobileNetV1_padValid",
      ( new NeuralNet_TestParams.Base( 1 ) ).set_byParamsScattered(
        this.height, this.width, this.depth,
        vocabularyChannelCount, vocabularyCountPerInputChannel,
        ValueDesc.ConvStageType.Singleton.Ids.MOBILE_NET_V1_PAD_VALID,
        stageCountRequested, blockCountRequested, bKeepInputTensor
      ) );

    // Test Case 2: (MobileNetV2_Thin)
    this.neuralNet_PerformanceTest_addCase( "MobileNetV2_Thin",
      ( new NeuralNet_TestParams.Base( 2 ) ).set_byParamsScattered(
        this.height, this.width, this.depth,
        vocabularyChannelCount, vocabularyCountPerInputChannel,
        ValueDesc.ConvStageType.Singleton.Ids.MOBILE_NET_V2_THIN,
        stageCountRequested, blockCountRequested, bKeepInputTensor
      ) );

    // Test Case 3: (MobileNetV2)
    this.neuralNet_PerformanceTest_addCase( "MobileNetV2",
      ( new NeuralNet_TestParams.Base( 3 ) ).set_byParamsScattered(
        this.height, this.width, this.depth,
        vocabularyChannelCount, vocabularyCountPerInputChannel,
        ValueDesc.ConvStageType.Singleton.Ids.MOBILE_NET_V2,
        stageCountRequested, blockCountRequested, bKeepInputTensor
      ) );

    // Test Case 4: (ShuffleNetV2))
    this.neuralNet_PerformanceTest_addCase( "ShuffleNetV2",
      ( new NeuralNet_TestParams.Base( 4 ) ).set_byParamsScattered(
        this.height, this.width, this.depth,
        vocabularyChannelCount, vocabularyCountPerInputChannel,
        ValueDesc.ConvStageType.Singleton.Ids.SHUFFLE_NET_V2,
        stageCountRequested, blockCountRequested, bKeepInputTensor
      ) );

    // Test Case 5: (ShuffleNetV2_byPointwise21)
    this.neuralNet_PerformanceTest_addCase( "ShuffleNetV2_byPointwise21",
      ( new NeuralNet_TestParams.Base( 5 ) ).set_byParamsScattered(
        this.height, this.width, this.depth,
        vocabularyChannelCount, vocabularyCountPerInputChannel,
        ValueDesc.ConvStageType.Singleton.Ids.SHUFFLE_NET_V2_BY_POINTWISE21,
        stageCountRequested, blockCountRequested, bKeepInputTensor
      ) );

    // Test Case 6: (ShuffleNetV2_byMobileNetV1)
    this.neuralNet_PerformanceTest_addCase( "ShuffleNetV2_byMobileNetV1",
      ( new NeuralNet_TestParams.Base( 6 ) ).set_byParamsScattered(
        this.height, this.width, this.depth,
        vocabularyChannelCount, vocabularyCountPerInputChannel,
        ValueDesc.ConvStageType.Singleton.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1,
        stageCountRequested, blockCountRequested, bKeepInputTensor
      ) );

    // Test Case 7: (ShuffleNetV2_byMobileNetV1_padValid)
    this.neuralNet_PerformanceTest_addCase( "ShuffleNetV2_byMobileNetV1_padValid",
      ( new NeuralNet_TestParams.Base( 7 ) ).set_byParamsScattered(
        this.height, this.width, this.depth,
        vocabularyChannelCount, vocabularyCountPerInputChannel,
        ValueDesc.ConvStageType.Singleton.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1_PAD_VALID,
        stageCountRequested, blockCountRequested, bKeepInputTensor
      ) );
  }

  /** Release testCase.neuralNet, but keep testCase. */
  neuralNet_PerformanceTest_release_neuralNet() {
    if ( this.testCaseMap ) {
//!!! (2022/08/16 Remarked) Use values() instead.
//       for ( let name_testCase of this.testCaseMap.entries() ) {
//         let name = name_testCase[ 0 ];
//         let testCase = name_testCase[ 1 ];
      for ( let testCase of this.testCaseMap.values() ) {
        if ( testCase.neuralNet ) {
          testCase.neuralNet.disposeResources_and_recycleToPool();
          testCase.neuralNet = null;
        }
      }
    }
  }

  neuralNet_PerformanceTest_release() {
    if ( this.testCaseMap ) {
      this.neuralNet_PerformanceTest_release_neuralNet();
      this.testCaseMap.clear();
    }

    if ( this.testPerformance_imageSourceBag ) {
      this.testPerformance_imageSourceBag.disposeResources_and_recycleToPool();
      this.testPerformance_imageSourceBag = null;
    }
  }

  /** Test apply by Xxx */
  testNeuralNet_ByName( testCaseName ) {
    let testCase = this.testCaseMap.get( testCaseName );

    // First time test this case. Release all other neural network (so that there will
    // be enough memory). Create the specified neural network.
    if ( !testCase.neuralNet ) {
      this.neuralNet_PerformanceTest_release_neuralNet();
      testCase.prepare();
    }

    let neuralNet = testCase.neuralNet;

    let inputTensor3d = neuralNet.create_ScaledSourceTensor_from_PixelData(
      this.testCanvas );

    let outputTensor3d = neuralNet.apply( inputTensor3d );
    tf.dispose( outputTensor3d );
  }

  /** Testing whether the results of different implementation are the same. */
  * testCorrectness() {

    //!!! (2022/08/16 Temp Skipped) For speed up into performance testing.
    if ( 0 )
    {
      let pool_all_issuedCount_before = Pool.All.issuedCount;

      //Pool.Asserter.assert_Pool_issuedCount_same_after_as_before( "jsPerf_NeuralNet.HeightWidthDepth.testCorrectness()", () => {
      //}, this );

      yield;

      {
        let memoryInfo_testCorrectness_before = tf.memory(); // Test memory leakage of imageSourceBag.

        {
          // Note: imageSourceBag should not be created outside tidy() because tidy() will dispose tensors
          //       dynamically created in them.
          let imageSourceBag = ImageSourceBag.Base.Pool.get_or_create_by( "int32" );

          let testParams = NeuralNet_TestParams.Base.Pool.get_or_create_by();
          let testParamsGenerator = testParams.ParamsGenerator();
          let testReference = NeuralNet_Reference.Base.Pool.get_or_create_by();

          let batchIdCalculator = new BatchIdCalculator.Base( 100 * 1000 );

          try {
            for ( testParams of testParamsGenerator ) {
              let bDisplayed = batchIdCalculator.checkAndDisplay( testParams.id );
              if ( bDisplayed )
                yield; // Since just entering a new batch section, take a break so that memory garbage collector could be activated to work.

              testReference.testCorrectness( imageSourceBag, testParams );
            }

          } catch ( e ) {
            let backendName = tf.getBackend();
            let msg = `jsPerf_NeuralNet.js: testCorrectness(): backendName=${backendName}, `
              + `NeuralNet, (yieldCount == ${testParams.yieldCount}), testParams.id == ${testParams.id}`;

            console.log( msg );
            alert( `${msg}\n${e}` );

            //debugger;
            throw e;
          }

          batchIdCalculator.checkAndDisplay( testParams.id );

          testReference.disposeResources_and_recycleToPool(); testReference = null;
          testParams.disposeResources_and_recycleToPool(); testParams = null;
          imageSourceBag.disposeResources_and_recycleToPool(); imageSourceBag = null;
        }

        let memoryInfo_testCorrectness_after = tf.memory();

        if ( memoryInfo_testCorrectness_after.numTensors != memoryInfo_testCorrectness_before.numTensors )
          throw Error( `testCorrectness() memory leak. `
            + `result tensor count (${memoryInfo_testCorrectness_after.numTensors}) `
            + `should be (${memoryInfo_testCorrectness_before.numTensors} `
          );
      }

      Pool.Asserter.assert_Pool_issuedCount( "jsPerf_Block.HeightWidthDepth.testCorrectness()", pool_all_issuedCount_before );
      yield;
    }

    try {
      // After correctness testing done, create all NeuralNet for performance testing.
      this.neuralNet_PerformanceTest_init();
    } catch ( e ) {
      debugger;
      throw e;
    }
  }

}

function init() {
  //console.log("jsPerf_NeuralNet.js, init()");

  disposeResources();

  let depth = 4;

  // Using mobile phone's resolution ( 1080 * 2160 ) will crash the computer.
  // Using ( 1 / 10 ) of computer screen ( 1080 * 1920 ).
  globalThis.testSet_108x192x4 = new HeightWidthDepth( 108, 192, depth ); // height, width, depth

  globalThis.testSet_All = [
    globalThis.testSet_108x192x4
  ];
}

function* testCorrectness() {
  for ( let i = 0; i < globalThis.testSet_All.length; ++i ) {
    let testSet = globalThis.testSet_All[ i ];
    yield* testSet.testCorrectness();
  }
}

function disposeResources() {
  if ( globalThis.testSet_All ) {
    for ( let i = 0; i < globalThis.testSet_All.length; ++i ) {
      let testSet = globalThis.testSet_All[ i ];
      if ( testSet )
        testSet.disposeResources();
    }

    globalThis.testSet_All = null;
  }

  globalThis.testSet_108x192x4
    = null;
}
<commit_msg>blockCountRequested<commit_after>export { init, testCorrectness, disposeResources };

import * as Pool from "../util/Pool.js";
import * as Recyclable from "../util/Recyclable.js";
import * as ValueDesc from "../Unpacker/ValueDesc.js";
import * as Weights from "../Unpacker/Weights.js";
//import * as ActivationEscaping from "../Conv/ActivationEscaping.js";
import * as BoundsArraySet from "../Conv/BoundsArraySet.js";
import * as NeuralNet from "../Conv/NeuralNet.js";
import * as NeuralNet_Reference from "./Ref/NeuralNet_Reference.js";
import * as NeuralNet_TestParams from "./Ref/NeuralNet_TestParams.js";
import * as ImageSourceBag from "./Ref/ImageSourceBag.js";
import * as NumberImage from "./Ref/NumberImage.js";
import * as BatchIdCalculator from "./BatchIdCalculator.js";

/**
 * Test CNN NeuralNet.
 *
 * @see {@link https://www.measurethat.net/Benchmarks/Show/20203/54/colorfulcakechen-cnn-neuralnet-4d36f0e2ffd053a25457d9b6}
 */

/**
 *
 */
class PerformanceTestCase {

  constructor( testCaseId, testCaseName, neuralNetTestParams ) {
    this.testCaseId = testCaseId;
    this.testCaseName = testCaseName;
    this.neuralNetTestParams = neuralNetTestParams;
    this.neuralNet = undefined;
    //this.inputTensor3d = undefined;
  }

  /**
   * Create .neuralNet
   */
  prepare() {
    try {

//!!! (2022/08/16 Remarked) Use canvas instead.
//       // Pre-create performance test case's input image.
//       let inputImage = this.testPerformance_imageSourceBag.getImage_by(
//         neuralNetTestParams.out.input_height,
//         neuralNetTestParams.out.input_width,
//         neuralNetTestParams.out.input_channelCount );
//
//       // Pre-create performance test case's input tensor.
//       let inputTensor3d = this.testPerformance_imageSourceBag.getTensor3d_by(
//         neuralNetTestParams.out.input_height,
//         neuralNetTestParams.out.input_width,
//         neuralNetTestParams.out.input_channelCount );

      this.neuralNet = NeuralNet_Reference.Base.NeuralNet_create( this.neuralNetTestParams );

      console.log( `NeuralNet.${this.testCaseName}: tensorWeightCount = { `
        + `Extracted: ${this.neuralNet.tensorWeightCountExtracted}, `
        + `Total: ${this.neuralNet.tensorWeightCountTotal} }` );

    } catch ( e ) {
      debugger;
      throw e;
    }
  }

}

/**
 * A test set.
 */
class HeightWidthDepth {

  /**
   * @param {number} height            image height
   * @param {number} width             image width
   * @param {number} depth             image channel count
   */
  constructor( height, width, depth ) {

    this.disposeResources();

    this.height = height;
    this.width = width;
    this.depth = depth;

    this.valueCount = height * width * depth;
  }

  disposeResources() {
    this.neuralNet_PerformanceTest_release();
    this.testCanvas = null;
  }

  /**
   *
   */
  neuralNet_PerformanceTest_addCase( testCaseName, neuralNetTestParams ) {
    let aPerformanceTestCase = new PerformanceTestCase(
      neuralNetTestParams.id, testCaseName, neuralNetTestParams );

    this.testCaseMap.set( testCaseName, aPerformanceTestCase );
  }

  neuralNet_PerformanceTest_init() {

    // Release dataTensor3d too. Because perofrmance testing uses larger different input image from correctness testing.
    this.disposeResources();

    // Larger input image for performance testing.
    this.testPerformance_imageSourceBag = ImageSourceBag.Base.Pool.get_or_create_by( "int32" );

    {
      let largerHeight = this.height * 10;
      let largerWidth = this.width * 10;
      let inputChannelCount = this.depth; // Must be 4;

      this.testCanvas = document.createElement( "canvas" );
      this.testCanvas.height = largerHeight;
      this.testCanvas.width = largerWidth;

      let inputImage = this.testPerformance_imageSourceBag.getImage_by(
        largerHeight, largerWidth, inputChannelCount );

      let ctx = this.testCanvas.getContext( "2d" );
      let imageData = ctx.createImageData( largerHeight, largerWidth );
      for ( let i = 0; i < imageData.data.length; ++i ) {
        imageData.data[ i ] = inputImage.dataArray[ i ];
      }

      ctx.putImageData( imageData, 0 , 0 );
    }

    this.testPerformance_imageSourceBag.clear(); // Reduce memory.

    if ( this.testCaseMap )
      this.testCaseMap.clear();
    else
      this.testCaseMap = new Map();

    let vocabularyChannelCount = 4;
    let vocabularyCountPerInputChannel = 256;
    let stageCountRequested = 7; //5;
    let blockCountRequested = 8; //5;

    // The neuralNet performance testing should not keep-input-tensor. The reason input
    // image is created from canvas in real time.
    let bKeepInputTensor = false;

    // input_height, input_width, input_channelCount,
    // vocabularyChannelCount, vocabularyCountPerInputChannel,
    // nConvStageTypeId,
    // stageCountRequested, blockCountRequested, bKeepInputTensor
    //

    // Test Case 0: (MobileNetV1)
    this.neuralNet_PerformanceTest_addCase( "MobileNetV1",
      ( new NeuralNet_TestParams.Base( 0 ) ).set_byParamsScattered(
        this.height, this.width, this.depth,
        vocabularyChannelCount, vocabularyCountPerInputChannel,
        ValueDesc.ConvStageType.Singleton.Ids.MOBILE_NET_V1,
        stageCountRequested, blockCountRequested, bKeepInputTensor
      ) );

    // Test Case 1: (MobileNetV1_padValid)
    this.neuralNet_PerformanceTest_addCase( "MobileNetV1_padValid",
      ( new NeuralNet_TestParams.Base( 1 ) ).set_byParamsScattered(
        this.height, this.width, this.depth,
        vocabularyChannelCount, vocabularyCountPerInputChannel,
        ValueDesc.ConvStageType.Singleton.Ids.MOBILE_NET_V1_PAD_VALID,
        stageCountRequested, blockCountRequested, bKeepInputTensor
      ) );

    // Test Case 2: (MobileNetV2_Thin)
    this.neuralNet_PerformanceTest_addCase( "MobileNetV2_Thin",
      ( new NeuralNet_TestParams.Base( 2 ) ).set_byParamsScattered(
        this.height, this.width, this.depth,
        vocabularyChannelCount, vocabularyCountPerInputChannel,
        ValueDesc.ConvStageType.Singleton.Ids.MOBILE_NET_V2_THIN,
        stageCountRequested, blockCountRequested, bKeepInputTensor
      ) );

    // Test Case 3: (MobileNetV2)
    this.neuralNet_PerformanceTest_addCase( "MobileNetV2",
      ( new NeuralNet_TestParams.Base( 3 ) ).set_byParamsScattered(
        this.height, this.width, this.depth,
        vocabularyChannelCount, vocabularyCountPerInputChannel,
        ValueDesc.ConvStageType.Singleton.Ids.MOBILE_NET_V2,
        stageCountRequested, blockCountRequested, bKeepInputTensor
      ) );

    // Test Case 4: (ShuffleNetV2))
    this.neuralNet_PerformanceTest_addCase( "ShuffleNetV2",
      ( new NeuralNet_TestParams.Base( 4 ) ).set_byParamsScattered(
        this.height, this.width, this.depth,
        vocabularyChannelCount, vocabularyCountPerInputChannel,
        ValueDesc.ConvStageType.Singleton.Ids.SHUFFLE_NET_V2,
        stageCountRequested, blockCountRequested, bKeepInputTensor
      ) );

    // Test Case 5: (ShuffleNetV2_byPointwise21)
    this.neuralNet_PerformanceTest_addCase( "ShuffleNetV2_byPointwise21",
      ( new NeuralNet_TestParams.Base( 5 ) ).set_byParamsScattered(
        this.height, this.width, this.depth,
        vocabularyChannelCount, vocabularyCountPerInputChannel,
        ValueDesc.ConvStageType.Singleton.Ids.SHUFFLE_NET_V2_BY_POINTWISE21,
        stageCountRequested, blockCountRequested, bKeepInputTensor
      ) );

    // Test Case 6: (ShuffleNetV2_byMobileNetV1)
    this.neuralNet_PerformanceTest_addCase( "ShuffleNetV2_byMobileNetV1",
      ( new NeuralNet_TestParams.Base( 6 ) ).set_byParamsScattered(
        this.height, this.width, this.depth,
        vocabularyChannelCount, vocabularyCountPerInputChannel,
        ValueDesc.ConvStageType.Singleton.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1,
        stageCountRequested, blockCountRequested, bKeepInputTensor
      ) );

    // Test Case 7: (ShuffleNetV2_byMobileNetV1_padValid)
    this.neuralNet_PerformanceTest_addCase( "ShuffleNetV2_byMobileNetV1_padValid",
      ( new NeuralNet_TestParams.Base( 7 ) ).set_byParamsScattered(
        this.height, this.width, this.depth,
        vocabularyChannelCount, vocabularyCountPerInputChannel,
        ValueDesc.ConvStageType.Singleton.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1_PAD_VALID,
        stageCountRequested, blockCountRequested, bKeepInputTensor
      ) );
  }

  /** Release testCase.neuralNet, but keep testCase. */
  neuralNet_PerformanceTest_release_neuralNet() {
    if ( this.testCaseMap ) {
//!!! (2022/08/16 Remarked) Use values() instead.
//       for ( let name_testCase of this.testCaseMap.entries() ) {
//         let name = name_testCase[ 0 ];
//         let testCase = name_testCase[ 1 ];
      for ( let testCase of this.testCaseMap.values() ) {
        if ( testCase.neuralNet ) {
          testCase.neuralNet.disposeResources_and_recycleToPool();
          testCase.neuralNet = null;
        }
      }
    }
  }

  neuralNet_PerformanceTest_release() {
    if ( this.testCaseMap ) {
      this.neuralNet_PerformanceTest_release_neuralNet();
      this.testCaseMap.clear();
    }

    if ( this.testPerformance_imageSourceBag ) {
      this.testPerformance_imageSourceBag.disposeResources_and_recycleToPool();
      this.testPerformance_imageSourceBag = null;
    }
  }

  /** Test apply by Xxx */
  testNeuralNet_ByName( testCaseName ) {
    let testCase = this.testCaseMap.get( testCaseName );

    // First time test this case. Release all other neural network (so that there will
    // be enough memory). Create the specified neural network.
    if ( !testCase.neuralNet ) {
      this.neuralNet_PerformanceTest_release_neuralNet();
      testCase.prepare();
    }

    let neuralNet = testCase.neuralNet;

    let inputTensor3d = neuralNet.create_ScaledSourceTensor_from_PixelData(
      this.testCanvas );

    let outputTensor3d = neuralNet.apply( inputTensor3d );
    tf.dispose( outputTensor3d );
  }

  /** Testing whether the results of different implementation are the same. */
  * testCorrectness() {

    //!!! (2022/08/16 Temp Skipped) For speed up into performance testing.
    if ( 0 )
    {
      let pool_all_issuedCount_before = Pool.All.issuedCount;

      //Pool.Asserter.assert_Pool_issuedCount_same_after_as_before( "jsPerf_NeuralNet.HeightWidthDepth.testCorrectness()", () => {
      //}, this );

      yield;

      {
        let memoryInfo_testCorrectness_before = tf.memory(); // Test memory leakage of imageSourceBag.

        {
          // Note: imageSourceBag should not be created outside tidy() because tidy() will dispose tensors
          //       dynamically created in them.
          let imageSourceBag = ImageSourceBag.Base.Pool.get_or_create_by( "int32" );

          let testParams = NeuralNet_TestParams.Base.Pool.get_or_create_by();
          let testParamsGenerator = testParams.ParamsGenerator();
          let testReference = NeuralNet_Reference.Base.Pool.get_or_create_by();

          let batchIdCalculator = new BatchIdCalculator.Base( 100 * 1000 );

          try {
            for ( testParams of testParamsGenerator ) {
              let bDisplayed = batchIdCalculator.checkAndDisplay( testParams.id );
              if ( bDisplayed )
                yield; // Since just entering a new batch section, take a break so that memory garbage collector could be activated to work.

              testReference.testCorrectness( imageSourceBag, testParams );
            }

          } catch ( e ) {
            let backendName = tf.getBackend();
            let msg = `jsPerf_NeuralNet.js: testCorrectness(): backendName=${backendName}, `
              + `NeuralNet, (yieldCount == ${testParams.yieldCount}), testParams.id == ${testParams.id}`;

            console.log( msg );
            alert( `${msg}\n${e}` );

            //debugger;
            throw e;
          }

          batchIdCalculator.checkAndDisplay( testParams.id );

          testReference.disposeResources_and_recycleToPool(); testReference = null;
          testParams.disposeResources_and_recycleToPool(); testParams = null;
          imageSourceBag.disposeResources_and_recycleToPool(); imageSourceBag = null;
        }

        let memoryInfo_testCorrectness_after = tf.memory();

        if ( memoryInfo_testCorrectness_after.numTensors != memoryInfo_testCorrectness_before.numTensors )
          throw Error( `testCorrectness() memory leak. `
            + `result tensor count (${memoryInfo_testCorrectness_after.numTensors}) `
            + `should be (${memoryInfo_testCorrectness_before.numTensors} `
          );
      }

      Pool.Asserter.assert_Pool_issuedCount( "jsPerf_Block.HeightWidthDepth.testCorrectness()", pool_all_issuedCount_before );
      yield;
    }

    try {
      // After correctness testing done, create all NeuralNet for performance testing.
      this.neuralNet_PerformanceTest_init();
    } catch ( e ) {
      debugger;
      throw e;
    }
  }

}

function init() {
  //console.log("jsPerf_NeuralNet.js, init()");

  disposeResources();

  let depth = 4;

  // Using mobile phone's resolution ( 1080 * 2160 ) will crash the computer.
  // Using ( 1 / 10 ) of computer screen ( 1080 * 1920 ).
  globalThis.testSet_108x192x4 = new HeightWidthDepth( 108, 192, depth ); // height, width, depth

  globalThis.testSet_All = [
    globalThis.testSet_108x192x4
  ];
}

function* testCorrectness() {
  for ( let i = 0; i < globalThis.testSet_All.length; ++i ) {
    let testSet = globalThis.testSet_All[ i ];
    yield* testSet.testCorrectness();
  }
}

function disposeResources() {
  if ( globalThis.testSet_All ) {
    for ( let i = 0; i < globalThis.testSet_All.length; ++i ) {
      let testSet = globalThis.testSet_All[ i ];
      if ( testSet )
        testSet.disposeResources();
    }

    globalThis.testSet_All = null;
  }

  globalThis.testSet_108x192x4
    = null;
}
<|endoftext|>


<commit_before>const parse = require('./parse')
const eq = require('./eq')

const diff = (version1, version2) => {
  if (eq(version1, version2)) {
    return null
  } else {
    const v1 = parse(version1)
    const v2 = parse(version2)
    let prefix = ''
    let defaultResult
    if (v1.prerelease.length || v2.prerelease.length) {
      prefix = 'pre'
      defaultResult = 'prerelease'
    }
    for (const key in v1) {
      if (key === 'major' || key === 'minor' || key === 'patch') {
        if (v1[key] !== v2[key]) {
          return prefix + key
        }
      }
    }
    return defaultResult // may be undefined
  }
}
module.exports = diff
<commit_msg>prefer const over let<commit_after>const parse = require('./parse')
const eq = require('./eq')

const diff = (version1, version2) => {
  if (eq(version1, version2)) {
    return null
  } else {
    const v1 = parse(version1)
    const v2 = parse(version2)
    const hasPre = v1.prerelease.length || v2.prerelease.length
    const prefix = hasPre ? 'pre' : ''
    const defaultResult = hasPre ? 'prerelease' : ''
    for (const key in v1) {
      if (key === 'major' || key === 'minor' || key === 'patch') {
        if (v1[key] !== v2[key]) {
          return prefix + key
        }
      }
    }
    return defaultResult // may be undefined
  }
}
module.exports = diff
<|endoftext|>