<commit_before>import BlendingState from "../BlendingState.js";
import Buffer from "../../Renderer/Buffer.js";
import BufferUsage from "../../Renderer/BufferUsage.js";
import clone from "../../Core/clone.js";
import defined from "../../Core/defined.js";
import DrawCommand from "../../Renderer/DrawCommand.js";
import IndexDatatype from "../../Core/IndexDatatype.js";
import ModelExperimentalFS from "../../Shaders/ModelExperimental/ModelExperimentalFS.js";
import ModelExperimentalVS from "../../Shaders/ModelExperimental/ModelExperimentalVS.js";
import Pass from "../../Renderer/Pass.js";
import PrimitiveType from "../../Core/PrimitiveType.js";
import RenderState from "../../Renderer/RenderState.js";
import RuntimeError from "../../Core/RuntimeError.js";
import StencilConstants from "../StencilConstants.js";
import StyleCommandsNeeded from "./StyleCommandsNeeded.js";
import VertexArray from "../../Renderer/VertexArray.js";
import WireframeIndexGenerator from "../../Core/WireframeIndexGenerator.js";
import BoundingSphere from "../../Core/BoundingSphere.js";
import Matrix4 from "../../Core/Matrix4.js";
import ShadowMode from "../ShadowMode.js";

/**
 * Builds the DrawCommands for a {@link ModelExperimentalPrimitive} using its render resources.
 *
 * @param {PrimitiveRenderResources} primitiveRenderResources The render resources for a primitive.
 * @param {FrameState} frameState The frame state for creating GPU resources.
 *
 * @returns {DrawCommand[]} The generated DrawCommands.
 *
 * @private
 */
export default function buildDrawCommands(
  primitiveRenderResources,
  frameState
) {
  const shaderBuilder = primitiveRenderResources.shaderBuilder;
  shaderBuilder.addVertexLines([ModelExperimentalVS]);
  shaderBuilder.addFragmentLines([ModelExperimentalFS]);

  const model = primitiveRenderResources.model;
  let primitiveType = primitiveRenderResources.primitiveType;
  const debugWireframe =
    model.debugWireframe && PrimitiveType.isTriangles(primitiveType);

  const indexBuffer = getIndexBuffer(
    primitiveRenderResources,
    debugWireframe,
    frameState
  );

  const vertexArray = new VertexArray({
    context: frameState.context,
    indexBuffer: indexBuffer,
    attributes: primitiveRenderResources.attributes,
  });

  model._resources.push(vertexArray);

  let renderState = primitiveRenderResources.renderStateOptions;

  if (model.opaquePass === Pass.CESIUM_3D_TILE) {
    // Set stencil values for classification on 3D Tiles
    renderState = clone(renderState, true);
    renderState.stencilTest = StencilConstants.setCesium3DTileBit();
    renderState.stencilMask = StencilConstants.CESIUM_3D_TILE_MASK;
  }

  renderState = RenderState.fromCache(renderState);

  const shaderProgram = shaderBuilder.buildShaderProgram(frameState.context);
  model._resources.push(shaderProgram);

  const pass = primitiveRenderResources.alphaOptions.pass;

  const sceneGraph = model.sceneGraph;

  const modelMatrix = Matrix4.multiply(
    sceneGraph.computedModelMatrix,
    primitiveRenderResources.runtimeNode.computedTransform,
    new Matrix4()
  );

  primitiveRenderResources.boundingSphere = BoundingSphere.transform(
    primitiveRenderResources.boundingSphere,
    modelMatrix,
    primitiveRenderResources.boundingSphere
  );

  let count = primitiveRenderResources.count;
  if (debugWireframe) {
    count = WireframeIndexGenerator.getWireframeIndicesCount(
      primitiveType,
      count
    );
    primitiveType = PrimitiveType.LINES;
  }

  const command = new DrawCommand({
    boundingVolume: primitiveRenderResources.boundingSphere,
    modelMatrix: modelMatrix,
    uniformMap: primitiveRenderResources.uniformMap,
    renderState: renderState,
    vertexArray: vertexArray,
    shaderProgram: shaderProgram,
    cull: model.cull,
    pass: pass,
    count: count,
    pickId: primitiveRenderResources.pickId,
    instanceCount: primitiveRenderResources.instanceCount,
    primitiveType: primitiveType,
    debugShowBoundingVolume: model.debugShowBoundingVolume,
    castShadows: ShadowMode.castShadows(model.shadows),
    receiveShadows: ShadowMode.receiveShadows(model.shadows),
  });

  const styleCommandsNeeded = primitiveRenderResources.styleCommandsNeeded;

  const commandList = [];

  if (defined(styleCommandsNeeded)) {
    const derivedCommands = createDerivedCommands(command);

    if (pass !== Pass.TRANSLUCENT) {
      switch (styleCommandsNeeded) {
        case StyleCommandsNeeded.ALL_OPAQUE:
          commandList.push(command);
          break;
        case StyleCommandsNeeded.ALL_TRANSLUCENT:
          commandList.push(derivedCommands.translucent);
          break;
        case StyleCommandsNeeded.OPAQUE_AND_TRANSLUCENT:
          // Push both opaque and translucent commands. The rendering of features based on opacity is handled in the shaders.
          commandList.push(command, derivedCommands.translucent);
          break;
        //>>includeStart('debug', pragmas.debug);
        default:
          throw new RuntimeError("styleCommandsNeeded is not a valid value.");
        //>>includeEnd('debug');
      }
    } else {
      // Command was originally translucent so no need to derive new commands;
      // as of now, a style can't change an originally translucent feature to
      // opaque since the style's alpha is modulated, not a replacement.  When
      // this changes, we need to derive new opaque commands here.
      commandList.push(command);
    }
  } else {
    commandList.push(command);
  }

  return commandList;
}

/**
 * @private
 */
function createDerivedCommands(command) {
  const derivedCommands = {};
  derivedCommands.translucent = deriveTranslucentCommand(command);
  return derivedCommands;
}

/**
 * @private
 */
function deriveTranslucentCommand(command) {
  const derivedCommand = DrawCommand.shallowClone(command);
  derivedCommand.pass = Pass.TRANSLUCENT;
  const rs = clone(command.renderState, true);
  rs.cull.enabled = false;
  rs.depthTest.enabled = true;
  rs.depthMask = false;
  rs.blending = BlendingState.ALPHA_BLEND;
  derivedCommand.renderState = RenderState.fromCache(rs);
  return derivedCommand;
}

function getIndexBuffer(primitiveRenderResources, debugWireframe, frameState) {
  if (debugWireframe) {
    return createWireframeIndexBuffer(primitiveRenderResources, frameState);
  }

  const indices = primitiveRenderResources.indices;
  if (!defined(indices)) {
    return undefined;
  }

  if (defined(indices.buffer)) {
    return indices.buffer;
  }

  const typedArray = indices.typedArray;
  const indexDatatype = IndexDatatype.fromSizeInBytes(
    typedArray.BYTES_PER_ELEMENT
  );

  return Buffer.createIndexBuffer({
    context: frameState.context,
    typedArray: typedArray,
    usage: BufferUsage.STATIC_DRAW,
    indexDatatype: indexDatatype,
  });
}

/**
 * @private
 */
function createWireframeIndexBuffer(primitiveRenderResources, frameState) {
  let positionAttribute;
  const attributes = primitiveRenderResources.attributes;
  const length = attributes.length;
  for (let i = 0; i < length; i++) {
    if (attributes[i].index === 0) {
      positionAttribute = attributes[i];
      break;
    }
  }

  const vertexCount = positionAttribute.count;
  const indices = primitiveRenderResources.indices;
  const context = frameState.context;

  let originalIndices;
  if (defined(indices)) {
    const indicesBuffer = indices.buffer;
    const indicesCount = indices.count;
    const useWebgl2 = context.webgl2;

    if (useWebgl2 && defined(indicesBuffer)) {
      originalIndices = IndexDatatype.createTypedArray(
        vertexCount,
        indicesCount
      );
      indicesBuffer.getBufferData(originalIndices);
    } else {
      originalIndices = indices.typedArray;
    }
  }

  const primitiveType = primitiveRenderResources.primitiveType;
  const wireframeIndices = WireframeIndexGenerator.createWireframeIndices(
    primitiveType,
    vertexCount,
    originalIndices
  );

  const indexDatatype = IndexDatatype.fromSizeInBytes(
    wireframeIndices.BYTES_PER_ELEMENT
  );

  return Buffer.createIndexBuffer({
    context: context,
    typedArray: wireframeIndices,
    usage: BufferUsage.STATIC_DRAW,
    indexDatatype: indexDatatype,
  });
}
<commit_msg>Remove extraneous whitespace [skip ci]<commit_after>import BlendingState from "../BlendingState.js";
import Buffer from "../../Renderer/Buffer.js";
import BufferUsage from "../../Renderer/BufferUsage.js";
import clone from "../../Core/clone.js";
import defined from "../../Core/defined.js";
import DrawCommand from "../../Renderer/DrawCommand.js";
import IndexDatatype from "../../Core/IndexDatatype.js";
import ModelExperimentalFS from "../../Shaders/ModelExperimental/ModelExperimentalFS.js";
import ModelExperimentalVS from "../../Shaders/ModelExperimental/ModelExperimentalVS.js";
import Pass from "../../Renderer/Pass.js";
import PrimitiveType from "../../Core/PrimitiveType.js";
import RenderState from "../../Renderer/RenderState.js";
import RuntimeError from "../../Core/RuntimeError.js";
import StencilConstants from "../StencilConstants.js";
import StyleCommandsNeeded from "./StyleCommandsNeeded.js";
import VertexArray from "../../Renderer/VertexArray.js";
import WireframeIndexGenerator from "../../Core/WireframeIndexGenerator.js";
import BoundingSphere from "../../Core/BoundingSphere.js";
import Matrix4 from "../../Core/Matrix4.js";
import ShadowMode from "../ShadowMode.js";

/**
 * Builds the DrawCommands for a {@link ModelExperimentalPrimitive} using its render resources.
 *
 * @param {PrimitiveRenderResources} primitiveRenderResources The render resources for a primitive.
 * @param {FrameState} frameState The frame state for creating GPU resources.
 *
 * @returns {DrawCommand[]} The generated DrawCommands.
 *
 * @private
 */
export default function buildDrawCommands(
  primitiveRenderResources,
  frameState
) {
  const shaderBuilder = primitiveRenderResources.shaderBuilder;
  shaderBuilder.addVertexLines([ModelExperimentalVS]);
  shaderBuilder.addFragmentLines([ModelExperimentalFS]);

  const model = primitiveRenderResources.model;
  let primitiveType = primitiveRenderResources.primitiveType;
  const debugWireframe =
    model.debugWireframe && PrimitiveType.isTriangles(primitiveType);

  const indexBuffer = getIndexBuffer(
    primitiveRenderResources,
    debugWireframe,
    frameState
  );

  const vertexArray = new VertexArray({
    context: frameState.context,
    indexBuffer: indexBuffer,
    attributes: primitiveRenderResources.attributes,
  });

  model._resources.push(vertexArray);

  let renderState = primitiveRenderResources.renderStateOptions;

  if (model.opaquePass === Pass.CESIUM_3D_TILE) {
    // Set stencil values for classification on 3D Tiles
    renderState = clone(renderState, true);
    renderState.stencilTest = StencilConstants.setCesium3DTileBit();
    renderState.stencilMask = StencilConstants.CESIUM_3D_TILE_MASK;
  }

  renderState = RenderState.fromCache(renderState);

  const shaderProgram = shaderBuilder.buildShaderProgram(frameState.context);
  model._resources.push(shaderProgram);

  const pass = primitiveRenderResources.alphaOptions.pass;

  const sceneGraph = model.sceneGraph;

  const modelMatrix = Matrix4.multiply(
    sceneGraph.computedModelMatrix,
    primitiveRenderResources.runtimeNode.computedTransform,
    new Matrix4()
  );

  primitiveRenderResources.boundingSphere = BoundingSphere.transform(
    primitiveRenderResources.boundingSphere,
    modelMatrix,
    primitiveRenderResources.boundingSphere
  );

  let count = primitiveRenderResources.count;
  if (debugWireframe) {
    count = WireframeIndexGenerator.getWireframeIndicesCount(
      primitiveType,
      count
    );
    primitiveType = PrimitiveType.LINES;
  }

  const command = new DrawCommand({
    boundingVolume: primitiveRenderResources.boundingSphere,
    modelMatrix: modelMatrix,
    uniformMap: primitiveRenderResources.uniformMap,
    renderState: renderState,
    vertexArray: vertexArray,
    shaderProgram: shaderProgram,
    cull: model.cull,
    pass: pass,
    count: count,
    pickId: primitiveRenderResources.pickId,
    instanceCount: primitiveRenderResources.instanceCount,
    primitiveType: primitiveType,
    debugShowBoundingVolume: model.debugShowBoundingVolume,
    castShadows: ShadowMode.castShadows(model.shadows),
    receiveShadows: ShadowMode.receiveShadows(model.shadows),
  });

  const styleCommandsNeeded = primitiveRenderResources.styleCommandsNeeded;

  const commandList = [];

  if (defined(styleCommandsNeeded)) {
    const derivedCommands = createDerivedCommands(command);

    if (pass !== Pass.TRANSLUCENT) {
      switch (styleCommandsNeeded) {
        case StyleCommandsNeeded.ALL_OPAQUE:
          commandList.push(command);
          break;
        case StyleCommandsNeeded.ALL_TRANSLUCENT:
          commandList.push(derivedCommands.translucent);
          break;
        case StyleCommandsNeeded.OPAQUE_AND_TRANSLUCENT:
          // Push both opaque and translucent commands. The rendering of features based on opacity is handled in the shaders.
          commandList.push(command, derivedCommands.translucent);
          break;
        //>>includeStart('debug', pragmas.debug);
        default:
          throw new RuntimeError("styleCommandsNeeded is not a valid value.");
        //>>includeEnd('debug');
      }
    } else {
      // Command was originally translucent so no need to derive new commands;
      // as of now, a style can't change an originally translucent feature to
      // opaque since the style's alpha is modulated, not a replacement.  When
      // this changes, we need to derive new opaque commands here.
      commandList.push(command);
    }
  } else {
    commandList.push(command);
  }

  return commandList;
}

/**
 * @private
 */
function createDerivedCommands(command) {
  const derivedCommands = {};
  derivedCommands.translucent = deriveTranslucentCommand(command);
  return derivedCommands;
}

/**
 * @private
 */
function deriveTranslucentCommand(command) {
  const derivedCommand = DrawCommand.shallowClone(command);
  derivedCommand.pass = Pass.TRANSLUCENT;
  const rs = clone(command.renderState, true);
  rs.cull.enabled = false;
  rs.depthTest.enabled = true;
  rs.depthMask = false;
  rs.blending = BlendingState.ALPHA_BLEND;
  derivedCommand.renderState = RenderState.fromCache(rs);
  return derivedCommand;
}

function getIndexBuffer(primitiveRenderResources, debugWireframe, frameState) {
  if (debugWireframe) {
    return createWireframeIndexBuffer(primitiveRenderResources, frameState);
  }

  const indices = primitiveRenderResources.indices;
  if (!defined(indices)) {
    return undefined;
  }

  if (defined(indices.buffer)) {
    return indices.buffer;
  }

  const typedArray = indices.typedArray;
  const indexDatatype = IndexDatatype.fromSizeInBytes(
    typedArray.BYTES_PER_ELEMENT
  );

  return Buffer.createIndexBuffer({
    context: frameState.context,
    typedArray: typedArray,
    usage: BufferUsage.STATIC_DRAW,
    indexDatatype: indexDatatype,
  });
}

/**
 * @private
 */
function createWireframeIndexBuffer(primitiveRenderResources, frameState) {
  let positionAttribute;
  const attributes = primitiveRenderResources.attributes;
  const length = attributes.length;
  for (let i = 0; i < length; i++) {
    if (attributes[i].index === 0) {
      positionAttribute = attributes[i];
      break;
    }
  }

  const vertexCount = positionAttribute.count;
  const indices = primitiveRenderResources.indices;
  const context = frameState.context;
  let originalIndices;
  if (defined(indices)) {
    const indicesBuffer = indices.buffer;
    const indicesCount = indices.count;
    const useWebgl2 = context.webgl2;
    if (useWebgl2 && defined(indicesBuffer)) {
      originalIndices = IndexDatatype.createTypedArray(
        vertexCount,
        indicesCount
      );
      indicesBuffer.getBufferData(originalIndices);
    } else {
      originalIndices = indices.typedArray;
    }
  }

  const primitiveType = primitiveRenderResources.primitiveType;
  const wireframeIndices = WireframeIndexGenerator.createWireframeIndices(
    primitiveType,
    vertexCount,
    originalIndices
  );
  const indexDatatype = IndexDatatype.fromSizeInBytes(
    wireframeIndices.BYTES_PER_ELEMENT
  );

  return Buffer.createIndexBuffer({
    context: context,
    typedArray: wireframeIndices,
    usage: BufferUsage.STATIC_DRAW,
    indexDatatype: indexDatatype,
  });
}
<|endoftext|>


<commit_before>var Brick = function() {
  var x2 = game.rnd.integerInRange(0, game.width);
  var y2 = game.rnd.integerInRange(0, game.height);
  this.brick = game.add.sprite(x2, y2, 'brick');
  this.brick.anchor.setTo(0.5, 0.5);

  game.physics.p2.enable(this.brick, debug);
  //this.brick.body.data.gravityScale = 0.05;
  //this.brick.body.static = true;
  this.brick.scale.setTo(.5,.5);

  SpaceGame._bricks.add(this.brick);

  this.brick.body.onBeginContact.add(function (body1, shapeA, shapeB) {
    if (body1 && body1.sprite != null && body1.sprite.key=='spaceship') {
      // do not kill pickable items, only tower can pickup.
      // @todo: enemy can pickup?
      this.brick.kill();
      body1.sprite.countBricks+=10;
      updateScoreText();
    }
  }, this);
  this.brick.events.onKilled.add(function (brick) {
    game.time.events.add(Phaser.Timer.SECOND, Brick.prototype.generateBrick, this);
  });
};

Brick.prototype = {
  generateBrick: function () {
    new Brick();
  }
};<commit_msg>Brick fixes<commit_after>var Brick = function () {
  var x2 = game.rnd.integerInRange(0, game.width);
  var y2 = game.rnd.integerInRange(0, game.height);
  this.brick = game.add.sprite(x2, y2, 'brick');
  this.brick.anchor.setTo(0.5, 0.5);

  game.physics.p2.enable(this.brick, debug);
  //this.brick.body.data.gravityScale = 0.05;
  //this.brick.body.static = true;
  this.brick.scale.setTo(.5, .5);

  SpaceGame._bricks.add(this.brick);

  this.brick.body.onBeginContact.add(function (body1, shapeA, shapeB) {
    if (body1 && body1.sprite != null && body1.sprite.key == 'spaceship') {
      // do not kill pickable items, only tower can pickup.
      // @todo: enemy can pickup?
      this.brick.kill();
      body1.sprite.countBricks += 1;
      updateScoreText();
    }
  }, this);
  this.brick.events.onKilled.add(function (brick) {
    game.time.events.add(Phaser.Timer.SECOND, Brick.prototype.generateBrick, this);
  });
};

Brick.prototype = {
  generateBrick: function () {
    new Brick();
  }
};<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 Expression organization is undefined on line 4, column 61 in Templates/Licenses/license-gpl30.txt.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Slider
 * Controls the opacity of the layers. Used by the TransparencySlider component.
 * @author Meine Toonen
 */

Ext.define("viewer.components.Slider",{
    extend: "viewer.components.Component",
    slider: null,
    layers : null,
    config:{
        selectedLayers: [],
        name : "",
        initialTransparency: 75
    },
    constructor : function (conf){
        viewer.components.Slider.superclass.constructor.call(this, conf);
        this.initConfig(conf);
        this.slider = Ext.create('Ext.slider.Single', {
            width: 200,
            value: this.initialTransparency,
            increment: 1,
            fieldLabel: this.name,
            labelAlign: "top",
            minValue: 0,
            maxValue: 100,
            renderTo: this.div,
            listeners:{
                change: {
                    fn: this.sliderChanged,
                    scope: this
                }
            }
        });
        var selectedLayers = this.selectedLayers;
        if(this.layers == null){
            this.layers = new Array();
        }
        for( var i = 0 ; i < selectedLayers.length;i++){
            this.layers.push(this.viewerController.getLayerByLayerId(this.selectedLayers[i]));
        }
        return this;
    },
    sliderChanged: function (slider,value){
        for(var i = 0 ; i< this.layers.length ;i++){
            var layer = this.layers[i];
            layer.setAlpha(value);
        }
    }
});<commit_msg>fix null dereference<commit_after>/*
 * Copyright (C) 2012 Expression organization is undefined on line 4, column 61 in Templates/Licenses/license-gpl30.txt.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Slider
 * Controls the opacity of the layers. Used by the TransparencySlider component.
 * @author Meine Toonen
 */

Ext.define("viewer.components.Slider",{
    extend: "viewer.components.Component",
    slider: null,
    layers : null,
    config:{
        selectedLayers: [],
        name : "",
        initialTransparency: 75
    },
    constructor : function (conf){
        viewer.components.Slider.superclass.constructor.call(this, conf);
        this.initConfig(conf);
        this.slider = Ext.create('Ext.slider.Single', {
            width: 200,
            value: this.initialTransparency,
            increment: 1,
            fieldLabel: this.name,
            labelAlign: "top",
            minValue: 0,
            maxValue: 100,
            renderTo: this.div,
            listeners:{
                change: {
                    fn: this.sliderChanged,
                    scope: this
                }
            }
        });
        var selectedLayers = this.selectedLayers;
        if(this.layers == null){
            this.layers = new Array();
        }
        for( var i = 0 ; i < selectedLayers.length;i++){
            var layer = this.viewerController.getLayerByLayerId(this.selectedLayers[i]);
            if(layer) {
                this.layers.push();
            }
        }
        return this;
    },
    sliderChanged: function (slider,value){
        for(var i = 0 ; i< this.layers.length ;i++){
            var layer = this.layers[i];
            layer.setAlpha(value);
        }
    }
});<|endoftext|>


<commit_before>module.exports = {
  "extends": "airbnb-base",
  "rules": {
    "semi": [2, "never"],
    "indent": ["error", 2],
    "max-len": ["error", 100]
  }
}
<commit_msg>Modify linting rules.<commit_after>module.exports = {
  "extends": "airbnb-base",
  "rules": {
    "semi": [2, "never"],
    "indent": ["error", 2],
    "max-len": ["error", 100],
    "arrow-body-style": ["error", "as-needed", { requireReturnForObjectLiteral: true }]
  }
}
<|endoftext|>


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

// Enable us to simply require('websocket') from within the examples directory
require.paths.unshift(__dirname + '/../../lib/');

var WebSocketServer = require('websocket').server;
var express = require('express');

var app = express.createServer();

app.configure(function() {
    app.use(express.static(__dirname + "/public"));
    app.set('views', __dirname);
    app.set('view engine', 'ejs');
});
app.get('/', function(req, res) {
    res.render('index', { layout: false });
});
app.listen(8080);

var wsServer = new WebSocketServer({
    httpServer: app,

    // Firefox 7 alpha has a bug that drops the
    // connection on large fragmented messages
    fragmentOutgoingMessages: false
});

var connections = [];
var canvasCommands = [];

wsServer.on('request', function(request) {
    var connection = request.accept('whiteboard-example', request.origin);
    connections.push(connection);

    console.log(connection.remoteAddress + " connected - Protocol Version " + connection.websocketVersion);

    // Send all the existing canvas commands to the new client
    connection.sendUTF(JSON.stringify({
        msg: "initCommands",
        data: canvasCommands
    }));

    // Handle closed connections
    connection.on('close', function() {
        console.log(connection.remoteAddress + " disconnected");

        var index = connections.indexOf(connection);
        if (index !== -1) {
            // remove the connection from the pool
            connections.splice(index, 1);
        }
    });

    // Handle incoming messages
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            try {
                var command = JSON.parse(message.utf8Data);

                if (command.msg === 'clear') {
                    canvasCommands = [];
                }
                else {
                    canvasCommands.push(command);
                }

                // rebroadcast command to all clients
                connections.forEach(function(destination) {
                    destination.sendUTF(message.utf8Data);
                });
            }
            catch(e) {
                // do nothing if there's an error.
            }
        }
    });
});

console.log("Whiteboard test app ready");
<commit_msg>Fixing whiteboard.js example to work under Node 0.6.x<commit_after>#!/usr/bin/env node
/************************************************************************
 *  Copyright 2010-2011 Worlize Inc.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 ***********************************************************************/

var WebSocketServer = require('../../lib/websocket').server;
var express = require('express');

var app = express.createServer();

app.configure(function() {
    app.use(express.static(__dirname + "/public"));
    app.set('views', __dirname);
    app.set('view engine', 'ejs');
});
app.get('/', function(req, res) {
    res.render('index', { layout: false });
});
app.listen(8080);

var wsServer = new WebSocketServer({
    httpServer: app,

    // Firefox 7 alpha has a bug that drops the
    // connection on large fragmented messages
    fragmentOutgoingMessages: false
});

var connections = [];
var canvasCommands = [];

wsServer.on('request', function(request) {
    var connection = request.accept('whiteboard-example', request.origin);
    connections.push(connection);

    console.log(connection.remoteAddress + " connected - Protocol Version " + connection.websocketVersion);

    // Send all the existing canvas commands to the new client
    connection.sendUTF(JSON.stringify({
        msg: "initCommands",
        data: canvasCommands
    }));

    // Handle closed connections
    connection.on('close', function() {
        console.log(connection.remoteAddress + " disconnected");

        var index = connections.indexOf(connection);
        if (index !== -1) {
            // remove the connection from the pool
            connections.splice(index, 1);
        }
    });

    // Handle incoming messages
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            try {
                var command = JSON.parse(message.utf8Data);

                if (command.msg === 'clear') {
                    canvasCommands = [];
                }
                else {
                    canvasCommands.push(command);
                }

                // rebroadcast command to all clients
                connections.forEach(function(destination) {
                    destination.sendUTF(message.utf8Data);
                });
            }
            catch(e) {
                // do nothing if there's an error.
            }
        }
    });
});

console.log("Whiteboard test app ready");
<|endoftext|>


<commit_before>export { MobileNetV1 };

import * as ValueDesc from "../../../Unpacker/ValueDesc.js";
import { Params } from "../Block_Param.js";
import { Base } from "./Base.js";

/**
 * Provide parameters for MobileNetV1 (i.e. no-add-inut-to-output, pointwise1 is same size of pointwise21).
 *
 * Although this the simplest pointwise1-depthwise-pointwise2 architecture, it may be the most efficient neural network if
 * using CLIP_BY_VALUE_N3_P3 (instead of RELU) as activation function.
 *
 * The reasons are:
 *
 *   - Better than MobileNetV2: According to experience of ShuffleNetV2_ByMobileNetV1, the CLIP_BY_VALUE_N3_P3 activation
 *     function could achieve skipping connection (i.e. residual connection) without add-input-to-output (i.e MobileNetV2).
 *
 *   - Better than ShuffleNetV2_ByMobileNetV1: All block's every step's pointwise21 needs not bias. Only the last block's
 *     stepLast's pointwise21 needs bias.
 *
 *
 *
 */
class MobileNetV1 extends Base {

  /** @override */
  configTo_beforeStep0() {
    super.configTo_beforeStep0(); // step0's inputHeight0, inputWidth0, bias, activation.

    let blockParams = this.blockParams;

    this.channelCount0_pointwise1Before = blockParams.sourceChannelCount; // Step0 uses the original input channel count (as input0).

    // In MobileNetV1, all steps (include step0) do not use input1.
    this.channelCount1_pointwise1Before = ValueDesc.channelCount1_pointwise1Before.Singleton.Ids.ONE_INPUT;

    If ( blockParams.bPointwise1 == false ) {
      this.pointwise1ChannelCount = 0;                                  // NoPointwise1.
      this.depthwise_AvgMax_Or_ChannelMultiplier = 2;                   // Double of input0. (Same as pointwise21.)

    } else {
      this.pointwise1ChannelCount = blockParams.sourceChannelCount * 2; // Double of input0. (Same as pointwise21.)
      this.depthwise_AvgMax_Or_ChannelMultiplier = 1;
    }

    this.depthwiseFilterHeight = this.depthwiseFilterHeight_Default; // All steps uses default depthwise filter size.
    this.depthwiseFilterWidth = this.depthwiseFilterWidth_Default;

    // Step0 uses depthwise ( strides = 2, pad = "same" ) to halve ( height, width ).
    this.depthwiseStridesPad = ValueDesc.StridesPad.Singleton.Ids.STRIDES_2_PAD_SAME;

    // In MobileNetV2, all steps' output0 is double depth of source input0.
    //
    // Note: In MobileNetV2's original design, it is not always "twice". We choose "twice" just for comparing with ShuffleNetV2.
    //
    this.pointwise21ChannelCount = blockParams.sourceChannelCount * 2;

    this.bOutput1Requested = false; // In MobileNetV2, all steps do not have output1.

    this.bKeepInputTensor = blockParams.bKeepInputTensor; // Step0 may or may not keep input tensor according to caller's necessary.

    this.outChannels0 = this.pointwise21ChannelCount;
    this.outChannels1 = 0;
  }

  /** @override */
  configTo_afterStep0() {
    super.configTo_afterStep0(); // step1, 2, 3, ...'s inputHeight0, inputWidth0.

    // The input0 of all steps (except step0) have the same depth as previous (also step0's) step's output0.
    this.channelCount0_pointwise1Before = this.outChannels0;

    // In MobileNetV1, all steps (include step0) do not use input1.
    this.channelCount1_pointwise1Before = ValueDesc.channelCount1_pointwise1Before.Singleton.Ids.ONE_INPUT;

    this.depthwise_AvgMax_Or_ChannelMultiplier = 1; // Because step0 has already double output channel count.

    // All steps (except step0) uses depthwise ( strides = 1, pad = "same" ) to keep ( height, width ).
    this.depthwiseStridesPad = ValueDesc.StridesPad.Singleton.Ids.STRIDES_1_PAD_SAME;

    this.bKeepInputTensor = false; // No matter bKeepInputTensor, all steps (except step0) should not keep input tensor.
  }

  /** @override */
  configTo_beforeStepLast() {
    super.configTo_beforeStepLast(); // stepLast's pointwise21 bias.
  }

}

<commit_msg>Update MobileNetV1.js<commit_after>export { MobileNetV1 };

import * as ValueDesc from "../../../Unpacker/ValueDesc.js";
import { Params } from "../Block_Param.js";
import { Base } from "./Base.js";

/**
 * Provide parameters for MobileNetV1 (i.e. no-add-inut-to-output, pointwise1 is same size of pointwise21).
 *
 * Although this the simplest pointwise1-depthwise-pointwise2 architecture, it may be the most efficient neural network if
 * using CLIP_BY_VALUE_N3_P3 (instead of RELU) as activation function.
 *
 * The reasons are:
 *
 *   - Better than MobileNetV2: According to experience of ShuffleNetV2_ByMobileNetV1, the CLIP_BY_VALUE_N3_P3 activation
 *     function could achieve skipping connection (i.e. residual connection) without add-input-to-output (i.e MobileNetV2).
 *
 *   - Better than ShuffleNetV2_ByMobileNetV1: All block's every step's pointwise21 needs not bias. Only the last block's
 *     stepLast's pointwise21 needs bias.
 *
 *
 *
 */
class MobileNetV1 extends Base {

  /** @override */
  configTo_beforeStep0() {
    super.configTo_beforeStep0(); // step0's inputHeight0, inputWidth0, bias, activation.

    let blockParams = this.blockParams;

    this.channelCount0_pointwise1Before = blockParams.sourceChannelCount; // Step0 uses the original input channel count (as input0).

    // In MobileNetV1, all steps (include step0) do not use input1.
    this.channelCount1_pointwise1Before = ValueDesc.channelCount1_pointwise1Before.Singleton.Ids.ONE_INPUT;

    If ( blockParams.bPointwise1 == false ) {
      this.pointwise1ChannelCount = 0;                                  // NoPointwise1.
      this.depthwise_AvgMax_Or_ChannelMultiplier = 2;                   // Double of input0. (Same as pointwise21.)

    } else {
      this.pointwise1ChannelCount = blockParams.sourceChannelCount * 2; // Double of input0. (Same as pointwise21.)
      this.depthwise_AvgMax_Or_ChannelMultiplier = 1;
    }

    this.bOutput1Requested = false; // In MobileNet, all steps do not have output1.

    this.outChannels0 = this.pointwise21ChannelCount;
    this.outChannels1 = 0;
  }

  /** @override */
  configTo_afterStep0() {
    super.configTo_afterStep0(); // step1, 2, 3, ...'s inputHeight0, inputWidth0.

    // The input0 of all steps (except step0) have the same depth as previous (also step0's) step's output0.
    this.channelCount0_pointwise1Before = this.outChannels0;

    // In MobileNetV1, all steps (include step0) do not use input1.
    this.channelCount1_pointwise1Before = ValueDesc.channelCount1_pointwise1Before.Singleton.Ids.ONE_INPUT;
  }

  /** @override */
  configTo_beforeStepLast() {
    super.configTo_beforeStepLast(); // stepLast's pointwise21 bias.
  }

}

<|endoftext|>


<commit_before>/**
 * @author amakaseev / https://github.com/amakaseev
 *
 * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
 * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
 *
 * ported from https://github.com/BabylonJS/Babylon.js/blob/master/src/Tools/babylon.khronosTextureContainer.ts
 */

THREE.KTXLoader = function ( manager ) {

	THREE.CompressedTextureLoader.call( this, manager );

	this._parser = THREE.KTXLoader.parse;

};

THREE.KTXLoader.prototype = Object.create( THREE.CompressedTextureLoader.prototype );
THREE.KTXLoader.prototype.constructor = THREE.KTXLoader;

THREE.KTXLoader.parse = function ( buffer, loadMipmaps ) {

	var ktx = new KhronosTextureContainer( buffer, 1 );

	return {
		mipmaps: ktx.mipmaps( loadMipmaps ),
		width: ktx.pixelWidth,
		height: ktx.pixelHeight,
		format: ktx.glInternalFormat,
		isCubemap: ktx.numberOfFaces === 6,
		mipmapCount: ktx.numberOfMipmapLevels
	};

};

var KhronosTextureContainer = ( function () {

	/**
	 * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
	 * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
	 * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
	 * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
	 */
	function KhronosTextureContainer( arrayBuffer, facesExpected, threeDExpected, textureArrayExpected ) {

		this.arrayBuffer = arrayBuffer;

		// Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
		// '´', 'K', 'T', 'X', ' ', '1', '1', 'ª', '\r', '\n', '\x1A', '\n'
		// 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
		var identifier = new Uint8Array( this.arrayBuffer, 0, 12 );
		if ( identifier[ 0 ] !== 0xAB ||
			identifier[ 1 ] !== 0x4B ||
			identifier[ 2 ] !== 0x54 ||
			identifier[ 3 ] !== 0x58 ||
			identifier[ 4 ] !== 0x20 ||
			identifier[ 5 ] !== 0x31 ||
			identifier[ 6 ] !== 0x31 ||
			identifier[ 7 ] !== 0xBB ||
			identifier[ 8 ] !== 0x0D ||
			identifier[ 9 ] !== 0x0A ||
			identifier[ 10 ] !== 0x1A ||
			identifier[ 11 ] !== 0x0A ) {

			console.error( 'texture missing KTX identifier' );
			return;

		}

		// load the reset of the header in native 32 bit uint
		var dataSize = Uint32Array.BYTES_PER_ELEMENT;
		var headerDataView = new DataView( this.arrayBuffer, 12, 13 * dataSize );
		var endianness = headerDataView.getUint32( 0, true );
		var littleEndian = endianness === 0x04030201;

		this.glType = headerDataView.getUint32( 1 * dataSize, littleEndian ); // must be 0 for compressed textures
		this.glTypeSize = headerDataView.getUint32( 2 * dataSize, littleEndian ); // must be 1 for compressed textures
		this.glFormat = headerDataView.getUint32( 3 * dataSize, littleEndian ); // must be 0 for compressed textures
		this.glInternalFormat = headerDataView.getUint32( 4 * dataSize, littleEndian ); // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
		this.glBaseInternalFormat = headerDataView.getUint32( 5 * dataSize, littleEndian ); // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
		this.pixelWidth = headerDataView.getUint32( 6 * dataSize, littleEndian ); // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
		this.pixelHeight = headerDataView.getUint32( 7 * dataSize, littleEndian ); // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
		this.pixelDepth = headerDataView.getUint32( 8 * dataSize, littleEndian ); // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
		this.numberOfArrayElements = headerDataView.getUint32( 9 * dataSize, littleEndian ); // used for texture arrays
		this.numberOfFaces = headerDataView.getUint32( 10 * dataSize, littleEndian ); // used for cubemap textures, should either be 1 or 6
		this.numberOfMipmapLevels = headerDataView.getUint32( 11 * dataSize, littleEndian ); // number of levels; disregard possibility of 0 for compressed textures
		this.bytesOfKeyValueData = headerDataView.getUint32( 12 * dataSize, littleEndian ); // the amount of space after the header for meta-data

		// Make sure we have a compressed type.  Not only reduces work, but probably better to let dev know they are not compressing.
		if ( this.glType !== 0 ) {

			console.warn( 'only compressed formats currently supported' );
			return;

		} else {

			// value of zero is an indication to generate mipmaps @ runtime.  Not usually allowed for compressed, so disregard.
			this.numberOfMipmapLevels = Math.max( 1, this.numberOfMipmapLevels );

		}
		if ( this.pixelHeight === 0 || this.pixelDepth !== 0 ) {

			console.warn( 'only 2D textures currently supported' );
			return;

		}
		if ( this.numberOfArrayElements !== 0 ) {

			console.warn( 'texture arrays not currently supported' );
			return;

		}
		if ( this.numberOfFaces !== facesExpected ) {

			console.warn( 'number of faces expected' + facesExpected + ', but found ' + this.numberOfFaces );
			return;

		}
		// we now have a completely validated file, so could use existence of loadType as success
		// would need to make this more elaborate & adjust checks above to support more than one load type
		this.loadType = KhronosTextureContainer.COMPRESSED_2D;

	}

	// return mipmaps for THREE.js
	KhronosTextureContainer.prototype.mipmaps = function ( loadMipmaps ) {

		var mipmaps = [];

		// initialize width & height for level 1
		var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
		var width = this.pixelWidth;
		var height = this.pixelHeight;
		var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;

		for ( var level = 0; level < mipmapCount; level ++ ) {

			var imageSize = new Int32Array( this.arrayBuffer, dataOffset, 1 )[ 0 ]; // size per face, since not supporting array cubemaps
			dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field

			for ( var face = 0; face < this.numberOfFaces; face ++ ) {

				var byteArray = new Uint8Array( this.arrayBuffer, dataOffset + 4, imageSize );

				mipmaps.push( { "data": byteArray, "width": width, "height": height } );

				dataOffset += 3 - ( ( imageSize + 3 ) % 4 ); // add padding for odd sized image

			}
			width = Math.max( 1.0, width * 0.5 );
			height = Math.max( 1.0, height * 0.5 );

		}

		return mipmaps;

	};

	KhronosTextureContainer.HEADER_LEN = 12 + ( 13 * 4 ); // identifier + header elements (not including key value meta-data pairs)
	// load types
	KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
	KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
	KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
	KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()

	return KhronosTextureContainer;

}() );
<commit_msg>Fixed bug with indexing<commit_after>/**
 * @author amakaseev / https://github.com/amakaseev
 *
 * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
 * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
 *
 * ported from https://github.com/BabylonJS/Babylon.js/blob/master/src/Tools/babylon.khronosTextureContainer.ts
 */

THREE.KTXLoader = function ( manager ) {

	THREE.CompressedTextureLoader.call( this, manager );

	this._parser = THREE.KTXLoader.parse;

};

THREE.KTXLoader.prototype = Object.create( THREE.CompressedTextureLoader.prototype );
THREE.KTXLoader.prototype.constructor = THREE.KTXLoader;

THREE.KTXLoader.parse = function ( buffer, loadMipmaps ) {

	var ktx = new KhronosTextureContainer( buffer, 1 );

	return {
		mipmaps: ktx.mipmaps( loadMipmaps ),
		width: ktx.pixelWidth,
		height: ktx.pixelHeight,
		format: ktx.glInternalFormat,
		isCubemap: ktx.numberOfFaces === 6,
		mipmapCount: ktx.numberOfMipmapLevels
	};

};

var KhronosTextureContainer = ( function () {

	/**
	 * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
	 * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
	 * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
	 * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
	 */
	function KhronosTextureContainer( arrayBuffer, facesExpected, threeDExpected, textureArrayExpected ) {

		this.arrayBuffer = arrayBuffer;

		// Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
		// '´', 'K', 'T', 'X', ' ', '1', '1', 'ª', '\r', '\n', '\x1A', '\n'
		// 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
		var identifier = new Uint8Array( this.arrayBuffer, 0, 12 );
		if ( identifier[ 0 ] !== 0xAB ||
			identifier[ 1 ] !== 0x4B ||
			identifier[ 2 ] !== 0x54 ||
			identifier[ 3 ] !== 0x58 ||
			identifier[ 4 ] !== 0x20 ||
			identifier[ 5 ] !== 0x31 ||
			identifier[ 6 ] !== 0x31 ||
			identifier[ 7 ] !== 0xBB ||
			identifier[ 8 ] !== 0x0D ||
			identifier[ 9 ] !== 0x0A ||
			identifier[ 10 ] !== 0x1A ||
			identifier[ 11 ] !== 0x0A ) {

			console.error( 'texture missing KTX identifier' );
			return;

		}

		// load the reset of the header in native 32 bit uint
		var dataSize = Uint32Array.BYTES_PER_ELEMENT;
		var headerDataView = new DataView( this.arrayBuffer, 12, 13 * dataSize );
		var endianness = headerDataView.getUint32( 0, true );
		var littleEndian = endianness === 0x04030201;

		this.glType = headerDataView.getUint32( 1 * dataSize, littleEndian ); // must be 0 for compressed textures
		this.glTypeSize = headerDataView.getUint32( 2 * dataSize, littleEndian ); // must be 1 for compressed textures
		this.glFormat = headerDataView.getUint32( 3 * dataSize, littleEndian ); // must be 0 for compressed textures
		this.glInternalFormat = headerDataView.getUint32( 4 * dataSize, littleEndian ); // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
		this.glBaseInternalFormat = headerDataView.getUint32( 5 * dataSize, littleEndian ); // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
		this.pixelWidth = headerDataView.getUint32( 6 * dataSize, littleEndian ); // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
		this.pixelHeight = headerDataView.getUint32( 7 * dataSize, littleEndian ); // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
		this.pixelDepth = headerDataView.getUint32( 8 * dataSize, littleEndian ); // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
		this.numberOfArrayElements = headerDataView.getUint32( 9 * dataSize, littleEndian ); // used for texture arrays
		this.numberOfFaces = headerDataView.getUint32( 10 * dataSize, littleEndian ); // used for cubemap textures, should either be 1 or 6
		this.numberOfMipmapLevels = headerDataView.getUint32( 11 * dataSize, littleEndian ); // number of levels; disregard possibility of 0 for compressed textures
		this.bytesOfKeyValueData = headerDataView.getUint32( 12 * dataSize, littleEndian ); // the amount of space after the header for meta-data

		// Make sure we have a compressed type.  Not only reduces work, but probably better to let dev know they are not compressing.
		if ( this.glType !== 0 ) {

			console.warn( 'only compressed formats currently supported' );
			return;

		} else {

			// value of zero is an indication to generate mipmaps @ runtime.  Not usually allowed for compressed, so disregard.
			this.numberOfMipmapLevels = Math.max( 1, this.numberOfMipmapLevels );

		}
		if ( this.pixelHeight === 0 || this.pixelDepth !== 0 ) {

			console.warn( 'only 2D textures currently supported' );
			return;

		}
		if ( this.numberOfArrayElements !== 0 ) {

			console.warn( 'texture arrays not currently supported' );
			return;

		}
		if ( this.numberOfFaces !== facesExpected ) {

			console.warn( 'number of faces expected' + facesExpected + ', but found ' + this.numberOfFaces );
			return;

		}
		// we now have a completely validated file, so could use existence of loadType as success
		// would need to make this more elaborate & adjust checks above to support more than one load type
		this.loadType = KhronosTextureContainer.COMPRESSED_2D;

	}

	// return mipmaps for THREE.js
	KhronosTextureContainer.prototype.mipmaps = function ( loadMipmaps ) {

		var mipmaps = [];

		// initialize width & height for level 1
		var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
		var width = this.pixelWidth;
		var height = this.pixelHeight;
		var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;

		for ( var level = 0; level < mipmapCount; level ++ ) {

			var imageSize = new Int32Array( this.arrayBuffer, dataOffset, 1 )[ 0 ]; // size per face, since not supporting array cubemaps
			dataOffset += 4; // size of the image + 4 for the imageSize field

			for ( var face = 0; face < this.numberOfFaces; face ++ ) {

				var byteArray = new Uint8Array( this.arrayBuffer, dataOffset, imageSize );

				mipmaps.push( { "data": byteArray, "width": width, "height": height } );

				dataOffset += imageSize;
				dataOffset += 3 - ( ( imageSize + 3 ) % 4 ); // add padding for odd sized image

			}
			width = Math.max( 1.0, width * 0.5 );
			height = Math.max( 1.0, height * 0.5 );

		}

		return mipmaps;

	};

	KhronosTextureContainer.HEADER_LEN = 12 + ( 13 * 4 ); // identifier + header elements (not including key value meta-data pairs)
	// load types
	KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
	KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
	KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
	KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()

	return KhronosTextureContainer;

}() );
<|endoftext|>


<commit_before>// a random number generator
var generator = fc.data.random.walk()
    .steps(11);

// some formatters
var dateFormatter = d3.time.format('%b');

// randomly generated sales data
var data = generator(1).map(function(d, i) {
    return {
        month: dateFormatter(new Date(0, i + 1, 0)),
        sales: d + i / 2
    };
});

//START
var yExtent = fc.util.extent()
    .include(0)
    .pad([0, 0.5])
    .fields(['sales']);

var chart = fc.chart.cartesian(
        d3.scale.ordinal(),
        d3.scale.linear())
    .xDomain(data.map(function(d) { return d.month; }))
    .yDomain(yExtent(data));
//END

var series = fc.series.bar()
    .xValue(function(d) { return d.month; })
    .yValue(function(d) { return d.sales; });

chart.plotArea(series);

d3.select('#cartesian-extent')
    .datum(data)
    .call(chart);
<commit_msg>docs: fix cartesian chart extent example (#982)<commit_after>// a random number generator
var generator = fc.data.random.walk()
    .steps(11);

// some formatters
var dateFormatter = d3.time.format('%b');

// randomly generated sales data
var data = generator(1).map(function(d, i) {
    return {
        month: dateFormatter(new Date(0, i + 1, 0)),
        sales: d + i / 2
    };
});

//START
var yExtent = fc.util.extent()
    .include([0])
    .pad([0, 0.5])
    .fields(['sales']);

var chart = fc.chart.cartesian(
        d3.scale.ordinal(),
        d3.scale.linear())
    .xDomain(data.map(function(d) { return d.month; }))
    .yDomain(yExtent(data));
//END

var series = fc.series.bar()
    .xValue(function(d) { return d.month; })
    .yValue(function(d) { return d.sales; });

chart.plotArea(series);

d3.select('#cartesian-extent')
    .datum(data)
    .call(chart);
<|endoftext|>


<commit_before>import { inject } from 'aurelia-framework';
import { json } from 'aurelia-fetch-client';
import { ValidationControllerFactory, ValidationRules, Validator, validateTrigger } from 'aurelia-validation';
import { App } from '../app';
import { FormValidator } from '../classes/FormValidator';
import { fixDates, formatDate, markPast, showCheckboxes } from '../commons/utils';

@inject(App, ValidationControllerFactory, Validator)
export class VolunteerOpps {
  controller = null;
  validator = null;
  constructor(app, controllerFactory, validator) {
    // this.validationRules = ValidationRules;
    this.app = app;
    this.selectedTalents = [];
    this.selectedWorks = [];
    this.newEvent = true;
    this.showCheckboxes = showCheckboxes;
    this.validator2 = new FormValidator(validator, results => this.updateCanSubmit2(results));
    this.controller2 = controllerFactory.createForCurrentScope(this.validator2);
    this.controller2.validateTrigger = validateTrigger.changeOrBlur;
    this.canSubmit2 = false;
    this.newAddress = false;
    this.charity = {};
    this.voOpp = {};
    this.showVolunteers = false;
    this.events = [];
  }
  async activate() {
    this.counter = 1;
    this.canSubmit2 = false;
    this.showVolunteers = false;
    this.uid = this.app.auth.getTokenPayload().sub;
    this.user = await this.app.appState.getUser(this.uid);
    this.app.role = this.user.userType;
    const currentUrl = (window.location.href);
    this.charityID = currentUrl.substring(currentUrl.indexOf('vol-ops/') + 8);
    const res = await this.app.httpClient.fetch(`/volopp/${this.charityID}`);
    this.events = await res.json();
    await this.makeDataTable();
  }

  makeDataTable() {
    if (this.events.length > 0) {
      this.events = fixDates(this.events);
      this.app.buildPTag(this.events, 'voWorkTypes', 'voWorkTypeOther ', 'workHtml');
      this.app.buildPTag(this.events, 'voTalentTypes', 'voTalentTypeOther', 'talentHtml');
      this.checkScheduled();
      markPast(this.events, formatDate);
    }
    this.findCharity();
    this.talents = ['music', 'athletics', 'childcare', 'mechanics', 'construction', 'computers', 'communication', 'chess playing', 'listening'];
    this.works = ['hashbrown slinging', 'nail hammering', 'leaf removal', 'floor mopping', 'counseling', 'visitation'];
    this.talents.sort();
    this.talents.push('other');
    this.works.sort();
    this.works.push('other');
    this.today = new Date().toISOString().split('T')[0];
    this.minEndDate = this.today;
    this.maxStartDate = '';
  }

  async checkScheduled() {
    for (const i of this.events) {
      i.voNumPeopleScheduled = 0;
      for (const j of i.voPeopleScheduled) {
        try {
          this.app.httpClient.fetch(`/user/${j}`);
        } catch (err) {
          // user does not exist, remove it from voPeopleScheduled and update this event, then run make data makeDataTable
          console.log('user does not exist');
          i.voPeopleScheduled = i.voPeopleScheduled.filter(e => e !== j);
          this.app.updateById('/volopp/', i._id, i);
          return this.makeDataTable();
        }
      }
      i.voNumPeopleScheduled = i.voPeopleScheduled.length;
    }
    return null;
  }

  async viewPeople(thisevent) {
    this.showVolunteers = true;
    let res, person;
    this.allPeople = [];
    for (let i = 0; i < thisevent.voPeopleScheduled.length; i += 1) {
      res = this.app.httpClient.fetch(`/user/${thisevent.voPeopleScheduled[i]}`);
      person = res.json();
      this.allPeople.push(person);
    }
    this.eventTitle = thisevent.voName;
    const display = document.getElementById('showvolunteers');
    display.scrollIntoView();
  }

  selectDate(dtype) {
    if (dtype === 'start-date') {
      this.minEndDate = this.voOpp.voStartDate;
    } else {
      this.maxStartDate = this.voOpp.voEndDate;
    }
  }

  async findCharity() {
    const res2 = await this.app.httpClient.fetch(`/charity/find/${this.charityID}`);
    this.charity = await res2.json();
    this.voOpp.voCharityName = this.charity.charityName;
    this.voOpp.voStreet = this.charity.charityStreet;
    this.voOpp.voCity = this.charity.charityCity;
    this.voOpp.voState = this.charity.charityState;
    this.voOpp.voZipCode = this.charity.charityZipCode;
    this.voOpp.voCharityTypes = this.charity.charityTypes;
    /* istanbul ignore else */
    if (this.charity.charityTypeOther !== '') {
      const index = this.voOpp.voCharityTypes.indexOf('other');
      /* istanbul ignore else */
      if (index > -1) {
        this.voOpp.voCharityTypes.splice(index, 1);
      }
      this.voOpp.voCharityTypes.push(this.charity.charityTypeOther);
    }
  }

  scheduleEvent() {
    this.voOpp.voStatus = 'new';
    this.app.httpClient.fetch('/volopp/create', { method: 'post', body: json(this.voOpp) })
      .then(() => {
        this.voOpp = {};
        document.getElementById('eventHeader').scrollIntoView();
        this.activate();
      });
  }

  showUpdateEvent(thisEvent, type) {
    if (type === 'update') {
      this.newEvent = false;
      this.canSubmit2 = false;
      document.getElementById('topSection').style.display = 'none';
      this.voOpp = thisEvent;
    }
    this.app.selectPickedChange(this.voOpp, this, 'voTalentTypes', 'voTalentTypeOther', 'talentOther');
    this.app.selectPickedChange(this.voOpp, this, 'voWorkTypes', 'voWorkTypeOther', 'workOther');
    // this.updateCanSubmit2([{result: {valid: false}}]);
    const nub = document.getElementById('updateScheduleEvent');
    if (nub !== null) {
      nub.style.display = 'none';
    }
    this.setupValidation2();
    this.controller2.validate();
  }

  showNewEvent() {
    this.voOpp = {
      voName: '',
      voCharityId: this.charityID,
      voNumPeopleNeeded: 1,
      voDescription: '',
      voWorkTypes: [],
      voTalentTypes: [],
      voWorkTypeOther: '',
      voTalentTypeOther: '',
      voStartDate: null,
      voStartTime: '',
      voEndDate: null,
      voEndTime: '',
      voContactName: this.user.name,
      voContactEmail: this.user.email,
      voContactPhone: this.user.userPhone
    };
    this.voOpp.voCharityName = this.charity.charityName;
    this.voOpp.voStreet = this.charity.charityStreet;
    this.voOpp.voCity = this.charity.charityCity;
    this.voOpp.voState = this.charity.charityState;
    this.voOpp.voZipCode = this.charity.charityZipCode;
    this.newEvent = true;
    const topSection = document.getElementById('topSection');
    topSection.style.display = 'block';
    topSection.scrollIntoView();
    this.showUpdateEvent(null, 'new');
  }

  cancelEvent(theEvent) {
    this.voOpp = theEvent;
    this.updateEvent('cancel');
    if (this.voOpp.voDescription !== undefined) {
      this.voOpp.voDescription = this.voOpp.voDescription.replace('
The Charity Has Reactivated This Event' +
        '
', '');
      this.voOpp.voDescription = this.voOpp.voDescription.replace('
The Charity Has Updated Details About' +
        ' This Event
', '');
      this.voOpp.voDescription = `
The Charity Has Cancelled This Event

${this.voOpp.voDescription}`;
    }
  }

  reactivateEvent(theEvent) {
    this.voOpp = theEvent;
    if (this.voOpp.voDescription !== undefined) {
      this.voOpp.voDescription = this.voOpp.voDescription.replace('
' +
        'The Charity Has Updated Details About This Event
', '');
      this.voOpp.voDescription = this.voOpp.voDescription.replace('
The Charity Has Cancelled This ' +
        'Event
', '
The Charity Has Reactivated This Event
');
    }
    this.updateEvent('reactivate');
  }

  async updateEvent(updateType) {
    this.voOpp.voStatus = updateType;
    if (updateType === 'update') {
      this.voOpp.voDescription = this.voOpp.voDescription.replace('
' +
        'The Charity Has Updated Details About This Event
', '');
      this.voOpp.voDescription = this.voOpp.voDescription.replace('
' +
        'The Charity Has Updated Details About This Event
', '');
      this.voOpp.voDescription = this.voOpp.voDescription.replace('
' +
        'The Charity Has Reactivated This Event
', '');
      this.voOpp.voDescription = `
The Charity Has Updated Details About This Event

${this.voOpp.voDescription}`;
    }
    await this.app.updateById('/volopp/', this.voOpp._id, this.voOpp);
    if (process.env.NODE_ENV !== 'test') {
      window.location.reload();
    }
    // this.activate();
  }

  async deleteEvent(thisEventId) {
    await fetch;
    this.app.httpClient.fetch(`/volopp/${thisEventId}`, { method: 'delete' })
      .then(() => {
        this.activate();
      });
  }

  updateCanSubmit2(validationResults) {
    let valid = true;
    const nub = document.getElementsByClassName('updateButton')[0];
    if (nub !== undefined) {
      nub.style.display = 'none';
    }
    for (const result of validationResults) {
      if (result.valid === false) {
        valid = false;
        break;
      }
    }
    this.canSubmit2 = valid;
    if (this.canSubmit2) {
      if (this.counter !== 1 || !this.updateEvent) {
        nub.style.display = 'block';
      }
      this.counter += 1;
    }
    return this.canSubmit2;
  }

  validate2() {
    return this.validator2.validateObject(this.voOpp);
  }
  /* istanbul ignore next */
  setupValidation2() {
    ValidationRules
      .ensure('voContactPhone').matches(/\b[2-9]\d{9}\b/).withMessage('10 digits only')
      .ensure('voContactEmail')
      .email()
      .ensure('voName')
      .required()
      .withMessage('Event Name is required')
      .maxLength(40)
      .ensure('voNumPeopleNeeded')
      .required()
      .withMessage('How Many Volunteers please')
      .ensure('voStartTime')
      .required()
      .withMessage('Event Start time is required')
      .ensure('voEndTime')
      .required()
      .withMessage('Event End time is required')
      .ensure('voStartDate')
      .required()
      .withMessage('Event Start Date is required')
      .ensure('voEndDate')
      .required()
      .withMessage('Event End Date is required')
      .ensure('voZipCode')
      .required()
      .withMessage('5-digit Zipcode is required')
      .matches(/\b\d{5}\b/)
      .ensure('voCity')
      .required()
      .withMessage('Event City is required')
      .matches(/[^0-9]+/)
      .maxLength(30)
      .ensure('voStreet')
      .required()
      .withMessage('Event Street Address is required')
      .maxLength(40)
      .ensure('voState')
      .required()
      .withMessage('Event State is required')
      .on(this.voOpp);
  }

  onlyPositive() {
    if (this.voOpp.voNumPeopleNeeded < 1) {
      this.voOpp.voNumPeopleNeeded = 1;
    }
  }

  selectPickChange(type) {
    this.selectedTalents = this.voOpp.voTalentTypes;
    this.selectedWorks = this.voOpp.voWorkTypes;
    if (type === 'work') {
      this.app.selectPickedChange(this.user, this, 'selectedWorks', 'volWorkOther', 'workOther', true, 'volWorkPrefs');
    }
    if (type === 'talents') {
      this.app.selectPickedChange(this.user, this, 'selectedTalents', 'volTalentOther', 'talentOther', true, 'volTalents');
    }
  }

  attached() {
    this.showNewEvent();
    this.setupValidation2();
  }
}
<commit_msg>testing a test failure<commit_after>import { inject } from 'aurelia-framework';
import { json } from 'aurelia-fetch-client';
import { ValidationControllerFactory, ValidationRules, Validator, validateTrigger } from 'aurelia-validation';
import { App } from '../app';
import { FormValidator } from '../classes/FormValidator';
import { fixDates, formatDate, markPast, showCheckboxes } from '../commons/utils';

@inject(App, ValidationControllerFactory, Validator)
export class VolunteerOpps {
  controller = null;
  validator = null;
  constructor(app, controllerFactory, validator) {
    // this.validationRules = ValidationRules;
    this.app = app;
    this.selectedTalents = [];
    this.selectedWorks = [];
    this.newEvent = true;
    this.showCheckboxes = showCheckboxes;
    this.validator2 = new FormValidator(validator, results => this.updateCanSubmit2(results));
    this.controller2 = controllerFactory.createForCurrentScope(this.validator2);
    this.controller2.validateTrigger = validateTrigger.changeOrBlur;
    this.canSubmit2 = false;
    this.newAddress = false;
    this.charity = {};
    this.voOpp = {};
    this.showVolunteers = false;
    this.events = [];
  }
  async activate() {
    this.counter = 1;
    this.canSubmit2 = false;
    this.showVolunteers = false;
    this.uid = this.app.auth.getTokenPayload().sub;
    this.user = await this.app.appState.getUser(this.uid);
    this.app.role = this.user.userType;
    const currentUrl = (window.location.href);
    this.charityID = currentUrl.substring(currentUrl.indexOf('vol-ops/') + 8);
    const res = await this.app.httpClient.fetch(`/volopp/${this.charityID}`);
    this.events = await res.json();
    await this.makeDataTable();
  }

  makeDataTable() {
    if (this.events.length > 0) {
      this.events = fixDates(this.events);
      this.app.buildPTag(this.events, 'voWorkTypes', 'voWorkTypeOther ', 'workHtml');
      this.app.buildPTag(this.events, 'voTalentTypes', 'voTalentTypeOther', 'talentHtml');
      this.checkScheduled();
      markPast(this.events, formatDate);
    }
    this.findCharity();
    this.talents = ['music', 'athletics', 'childcare', 'mechanics', 'construction', 'computers', 'communication', 'chess playing', 'listening'];
    this.works = ['hashbrown slinging', 'nail hammering', 'leaf removal', 'floor mopping', 'counseling', 'visitation'];
    this.talents.sort();
    this.talents.push('other');
    this.works.sort();
    this.works.push('other');
    this.today = new Date().toISOString().split('T')[0];
    this.minEndDate = this.today;
    this.maxStartDate = '';
  }

  async checkScheduled() {
    for (const i of this.events) {
      i.voNumPeopleScheduled = 0;
      for (const j of i.voPeopleScheduled) {
        try {
          this.app.httpClient.fetch(`/user/${j}`);
        } catch (err) {
          // user does not exist, remove it from voPeopleScheduled and update this event, then run make data makeDataTable
          console.log('user does not exist');
          i.voPeopleScheduled = i.voPeopleScheduled.filter(e => e !== j);
          this.app.updateById('/volopp/', i._id, i);
          return this.makeDataTable();
        }
      }
      i.voNumPeopleScheduled = i.voPeopleScheduled.length;
    }
    return null;
  }

  async viewPeople(thisevent) {
    this.showVolunteers = true;
    let res, person;
    this.allPeople = [];
    for (let i = 0; i < thisevent.voPeopleScheduled.length; i += 1) {
      res = this.app.httpClient.fetch(`/user/${thisevent.voPeopleScheduled[i]}`);
      console.log(res);
      person = res.json();
      this.allPeople.push(person);
    }
    this.eventTitle = thisevent.voName;
    const display = document.getElementById('showvolunteers');
    display.scrollIntoView();
  }

  selectDate(dtype) {
    if (dtype === 'start-date') {
      this.minEndDate = this.voOpp.voStartDate;
    } else {
      this.maxStartDate = this.voOpp.voEndDate;
    }
  }

  async findCharity() {
    const res2 = await this.app.httpClient.fetch(`/charity/find/${this.charityID}`);
    this.charity = await res2.json();
    this.voOpp.voCharityName = this.charity.charityName;
    this.voOpp.voStreet = this.charity.charityStreet;
    this.voOpp.voCity = this.charity.charityCity;
    this.voOpp.voState = this.charity.charityState;
    this.voOpp.voZipCode = this.charity.charityZipCode;
    this.voOpp.voCharityTypes = this.charity.charityTypes;
    /* istanbul ignore else */
    if (this.charity.charityTypeOther !== '') {
      const index = this.voOpp.voCharityTypes.indexOf('other');
      /* istanbul ignore else */
      if (index > -1) {
        this.voOpp.voCharityTypes.splice(index, 1);
      }
      this.voOpp.voCharityTypes.push(this.charity.charityTypeOther);
    }
  }

  scheduleEvent() {
    this.voOpp.voStatus = 'new';
    this.app.httpClient.fetch('/volopp/create', { method: 'post', body: json(this.voOpp) })
      .then(() => {
        this.voOpp = {};
        document.getElementById('eventHeader').scrollIntoView();
        this.activate();
      });
  }

  showUpdateEvent(thisEvent, type) {
    if (type === 'update') {
      this.newEvent = false;
      this.canSubmit2 = false;
      document.getElementById('topSection').style.display = 'none';
      this.voOpp = thisEvent;
    }
    this.app.selectPickedChange(this.voOpp, this, 'voTalentTypes', 'voTalentTypeOther', 'talentOther');
    this.app.selectPickedChange(this.voOpp, this, 'voWorkTypes', 'voWorkTypeOther', 'workOther');
    // this.updateCanSubmit2([{result: {valid: false}}]);
    const nub = document.getElementById('updateScheduleEvent');
    if (nub !== null) {
      nub.style.display = 'none';
    }
    this.setupValidation2();
    this.controller2.validate();
  }

  showNewEvent() {
    this.voOpp = {
      voName: '',
      voCharityId: this.charityID,
      voNumPeopleNeeded: 1,
      voDescription: '',
      voWorkTypes: [],
      voTalentTypes: [],
      voWorkTypeOther: '',
      voTalentTypeOther: '',
      voStartDate: null,
      voStartTime: '',
      voEndDate: null,
      voEndTime: '',
      voContactName: this.user.name,
      voContactEmail: this.user.email,
      voContactPhone: this.user.userPhone
    };
    this.voOpp.voCharityName = this.charity.charityName;
    this.voOpp.voStreet = this.charity.charityStreet;
    this.voOpp.voCity = this.charity.charityCity;
    this.voOpp.voState = this.charity.charityState;
    this.voOpp.voZipCode = this.charity.charityZipCode;
    this.newEvent = true;
    const topSection = document.getElementById('topSection');
    topSection.style.display = 'block';
    topSection.scrollIntoView();
    this.showUpdateEvent(null, 'new');
  }

  cancelEvent(theEvent) {
    this.voOpp = theEvent;
    this.updateEvent('cancel');
    if (this.voOpp.voDescription !== undefined) {
      this.voOpp.voDescription = this.voOpp.voDescription.replace('
The Charity Has Reactivated This Event' +
        '
', '');
      this.voOpp.voDescription = this.voOpp.voDescription.replace('
The Charity Has Updated Details About' +
        ' This Event
', '');
      this.voOpp.voDescription = `
The Charity Has Cancelled This Event

${this.voOpp.voDescription}`;
    }
  }

  reactivateEvent(theEvent) {
    this.voOpp = theEvent;
    if (this.voOpp.voDescription !== undefined) {
      this.voOpp.voDescription = this.voOpp.voDescription.replace('
' +
        'The Charity Has Updated Details About This Event
', '');
      this.voOpp.voDescription = this.voOpp.voDescription.replace('
The Charity Has Cancelled This ' +
        'Event
', '
The Charity Has Reactivated This Event
');
    }
    this.updateEvent('reactivate');
  }

  async updateEvent(updateType) {
    this.voOpp.voStatus = updateType;
    if (updateType === 'update') {
      this.voOpp.voDescription = this.voOpp.voDescription.replace('
' +
        'The Charity Has Updated Details About This Event
', '');
      this.voOpp.voDescription = this.voOpp.voDescription.replace('
' +
        'The Charity Has Updated Details About This Event
', '');
      this.voOpp.voDescription = this.voOpp.voDescription.replace('
' +
        'The Charity Has Reactivated This Event
', '');
      this.voOpp.voDescription = `
The Charity Has Updated Details About This Event

${this.voOpp.voDescription}`;
    }
    await this.app.updateById('/volopp/', this.voOpp._id, this.voOpp);
    if (process.env.NODE_ENV !== 'test') {
      window.location.reload();
    }
    // this.activate();
  }

  async deleteEvent(thisEventId) {
    await fetch;
    this.app.httpClient.fetch(`/volopp/${thisEventId}`, { method: 'delete' })
      .then(() => {
        this.activate();
      });
  }

  updateCanSubmit2(validationResults) {
    let valid = true;
    const nub = document.getElementsByClassName('updateButton')[0];
    if (nub !== undefined) {
      nub.style.display = 'none';
    }
    for (const result of validationResults) {
      if (result.valid === false) {
        valid = false;
        break;
      }
    }
    this.canSubmit2 = valid;
    if (this.canSubmit2) {
      if (this.counter !== 1 || !this.updateEvent) {
        nub.style.display = 'block';
      }
      this.counter += 1;
    }
    return this.canSubmit2;
  }

  validate2() {
    return this.validator2.validateObject(this.voOpp);
  }
  /* istanbul ignore next */
  setupValidation2() {
    ValidationRules
      .ensure('voContactPhone').matches(/\b[2-9]\d{9}\b/).withMessage('10 digits only')
      .ensure('voContactEmail')
      .email()
      .ensure('voName')
      .required()
      .withMessage('Event Name is required')
      .maxLength(40)
      .ensure('voNumPeopleNeeded')
      .required()
      .withMessage('How Many Volunteers please')
      .ensure('voStartTime')
      .required()
      .withMessage('Event Start time is required')
      .ensure('voEndTime')
      .required()
      .withMessage('Event End time is required')
      .ensure('voStartDate')
      .required()
      .withMessage('Event Start Date is required')
      .ensure('voEndDate')
      .required()
      .withMessage('Event End Date is required')
      .ensure('voZipCode')
      .required()
      .withMessage('5-digit Zipcode is required')
      .matches(/\b\d{5}\b/)
      .ensure('voCity')
      .required()
      .withMessage('Event City is required')
      .matches(/[^0-9]+/)
      .maxLength(30)
      .ensure('voStreet')
      .required()
      .withMessage('Event Street Address is required')
      .maxLength(40)
      .ensure('voState')
      .required()
      .withMessage('Event State is required')
      .on(this.voOpp);
  }

  onlyPositive() {
    if (this.voOpp.voNumPeopleNeeded < 1) {
      this.voOpp.voNumPeopleNeeded = 1;
    }
  }

  selectPickChange(type) {
    this.selectedTalents = this.voOpp.voTalentTypes;
    this.selectedWorks = this.voOpp.voWorkTypes;
    if (type === 'work') {
      this.app.selectPickedChange(this.user, this, 'selectedWorks', 'volWorkOther', 'workOther', true, 'volWorkPrefs');
    }
    if (type === 'talents') {
      this.app.selectPickedChange(this.user, this, 'selectedTalents', 'volTalentOther', 'talentOther', true, 'volTalents');
    }
  }

  attached() {
    this.showNewEvent();
    this.setupValidation2();
  }
}
<|endoftext|>


<commit_before>import xs from 'xstream';
import {div, nav, a} from '@cycle/dom';
import {merge, prop} from 'ramda';
import BMI from '../../examples/bmi';
import Hello from '../../examples/hello-world';
import Reference from '../Reference';

export default function Router(sources) {
	const {router} = sources;

	const match$ = router.define({
		'/bmi': BMI,
		'/hello': Hello,
		'/ref': Reference
	});

	const page$ = match$.map(({path, value}) => value(merge(sources, {
		path: router.path(path)
	})));

	const makeLink = (path, label) => a({props: {href: path}, style: {padding: '1em'}}, label);

	const nav$ = xs.of(nav({style: {marginBottom: '1em'}}, [
		makeLink('/ref', 'Reference')
	]));

	const view$ = page$.map(prop('DOM')).flatten();

	const vdom$ = xs.combine(nav$, view$).map(([navDom, viewDom]) => div([navDom, viewDom]));

	return {
		DOM: vdom$,
		router: xs.of('/ref')
	}
}
<commit_msg>Removes examples from router and comments-out nav link.<commit_after>import xs from 'xstream';
import {div, nav, a} from '@cycle/dom';
import {merge, prop} from 'ramda';
import BMI from '../../examples/bmi';
import Hello from '../../examples/hello-world';
import Reference from '../Reference';

export default function Router(sources) {
	const {router} = sources;

	const match$ = router.define({
		'/ref': Reference
	});

	const page$ = match$.map(({path, value}) => value(merge(sources, {
		path: router.path(path)
	})));

	const makeLink = (path, label) => a({props: {href: path}, style: {padding: '1em'}}, label);

	const nav$ = xs.of(nav({style: {marginBottom: '1em'}}, [
		// makeLink('/ref', 'Reference')
	]));

	const view$ = page$.map(prop('DOM')).flatten();

	const vdom$ = xs.combine(nav$, view$).map(([navDom, viewDom]) => div([navDom, viewDom]));

	return {
		DOM: vdom$,
		router: xs.of('/ref')
	}
}
<|endoftext|>


<commit_before>export { PadInfoCalculator };

import * as ValueDesc from "../../Unpacker/ValueDesc.js";

/**
 * According to input image size and depthwise convolution parameters, calculate the padding information of the depthwise convolution.
 *
 * @member {number} inputHeight           Input image height.
 * @member {number} inputWidth            Input image width.
 * @member {number} inputDepth            Input image channel count.
 * @member {number} AvgMax_Or_ChannelMultiplier   Depthwise operation. (ValueDesc.AvgMax_Or_ChannelMultiplier)
 * @member {number} filterHeight          The height of the depthwise convolution's filter.
 * @member {number} filterWidth           The width of the depthwise convolution's filter.
 * @member {number} stridesPad            The strides and padding of depthwise convolution. (PointDepthPoint.Params.depthwiseStridesPad)
 *
 * @member {number} channelMultiplier     The channel multiplier of the depthwise operation (according to AvgMax_Or_ChannelMultiplier).
 *
 * @member {number} dilationHeight        The depthwise filters's dilation across height dimension.
 * @member {number} dilationWidth         The depthwise filters's dilation across width dimension.
 *
 * @member {number} effectFilterHeight    The effect height of the depthwise convolution's filter including the dilationHeight.
 * @member {number} effectFilterWidth     The effect width of the depthwise convolution's filter including the dilationWidth.
 * @member {number} effectFilterSize      The effect size of the depthwise convolution's filter. (= effectFilterHeight * effectFilterWidth)
 *
 * @member {number} strides               The strides along the image's height and width dimension (according to stridesPad).
 * @member {number} stridesHeight         The strides along the image's height dimension (according to stridesPad).
 * @member {number} stridesWidth          The strides along the image's width dimension (according to stridesPad).

 * @member {number} pad                   The padding along the image's height and width dimension (according to stridesPad).
 * @member {number} padHeight             The padding along the input image's height dimension.
 * @member {number} padHeightTop          The padding along the input image's height dimension at the top.
 * @member {number} padHeightBottom       The padding along the input image's height dimension at the bottom.
 * @member {number} padWidth              The padding along the input image's width dimension.
 * @member {number} padWidthLeft          The padding along the input image's width dimension at the left.
 * @member {number} padWidthRight         The padding along the input image's width dimension at the right.
 *
 * @member {number} outputHeight          Output image height.
 * @member {number} outputWidth           Output image width.
 * @member {number} outputDepth           Output image channel count.
 * @member {number} outputElementCount    Output image elements count (= ( outputHeight * outputWidth * outputDepth ) ).
 */
let PadInfoCalculator = ( Base = Object ) => class extends Base {

  constructor( inputHeight, inputWidth, inputDepth, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad ) {
    super();
    this.inputHeight = inputHeight;
    this.inputWidth = inputWidth;
    this.inputDepth = inputDepth;
    this.AvgMax_Or_ChannelMultiplier = AvgMax_Or_ChannelMultiplier;
    this.filterHeight = filterHeight;
    this.filterWidth = filterWidth;
    this.stridesPad = stridesPad;

//!!! ...unfinished... (2021/03/17) What about ( filterHeight <= 0 ) or ( filterWidth <= 0 )?

    this.channelMultiplier = AvgMax_Or_ChannelMultiplier;
    if (   ( ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.AVG === AvgMax_Or_ChannelMultiplier )
        || ( ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.MAX === AvgMax_Or_ChannelMultiplier ) ) {
      this.channelMultiplier = 1;
    }

    // Strides and Padding.
    switch ( stridesPad ) {
      case 0:  this.strides = 1; this.pad = "valid"; break;
      default:
      case 1:  this.strides = 1; this.pad = "same";  break;
      case 2:  this.strides = 2; this.pad = "same";  break;
    }

    // Assume strides width equals strides height.
    this.stridesHeight = this.strides;
    this.stridesWidth = this.strides;

    // Currently, we can only handle dilation = 1.
    this.dilationHeight = 1;
    this.dilationWidth = 1;

    // Effect filter size (includes dilation).
    this.effectFilterHeight = this.dilationHeight * ( this.filterHeight - 1 ) + 1;
    this.effectFilterWidth =  this.dilationWidth  * ( this.filterWidth  - 1 ) + 1;
    this.effectFilterSize = this.effectFilterHeight * this.effectFilterWidth;

    // (The following codes for output image height and width and padding calculation are copied from
    // https://github.com/tensorflow/tfjs/blob/tfjs-v3.8.0/tfjs-core/src/ops/conv_util.ts)
    {
      // Determine output image height and width without padding.
      if ( this.pad == "valid" ) {
        this.outputHeight = Math.ceil( ( inputHeight - this.effectFilterHeight + 1 ) / this.stridesHeight );
        this.outputWidth =  Math.ceil( ( inputWidth  - this.effectFilterWidth  + 1 ) / this.stridesWidth  );

        this.padHeight = this.padHeightTop = this.padHeightBottom = this.padWidth = this.padWidthLeft = this.padWidthRight = 0;

      // Determine output image height and width with padding around the input image height and width.
      } else if ( this.pad == "same" ) {
        this.outputHeight = Math.ceil( inputHeight / this.stridesHeight );
        this.outputWidth =  Math.ceil( inputWidth  / this.stridesWidth  );

        this.padHeight = Math.max( 0, ( this.outputHeight - 1 ) * this.stridesHeight + this.effectFilterHeight - inputHeight );
        this.padWidth =  Math.max( 0, ( this.outputWidth  - 1 ) * this.stridesWidth  + this.effectFilterWidth  - inputWidth  );

        this.padHeightTop =    Math.floor( this.padHeight / 2 );
        this.padHeightBottom = this.padHeight - this.padHeightTop;
        this.padWidthLeft =    Math.floor( this.padWidth /  2 );
        this.padWidthRight =   this.padWidth  - this.padWidthLeft;
      }
    }

    this.outputDepth = inputDepth * this.channelMultiplier;
    this.outputElementCount = ( this.outputHeight * this.outputWidth * this.outputDepth );
  }

  /**
   * @param {number} filterValue
   *   The (non-zero) value used in the pass-through depthwise convolution filter. Default is 1.
   *
   * @return {number[]}
   *   Return the depthwise convolution filters which could pass the input to output unchangely.
   */
  generate_PassThrough_FiltersArray( filterValue = 1 ) {

    if (   ( ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.AVG === this.AvgMax_Or_ChannelMultiplier )
        || ( ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.MAX === this.AvgMax_Or_ChannelMultiplier ) ) {
      return null; // The depthwise filter of AVG pooling and MAX pooling can not be manipulated.
    }

    // Make up a depthwise convolution filter.
    let depthwiseFiltersArray = new Array( this.filterHeight * this.filterWidth * this.inputDepth * this.channelMultiplier );

    // There is only one position (inside the effect depthwise filter) with value one. All other positions of the filter should be zero.
    let oneEffectFilterY = this.padHeightTop;
    let oneEffectFilterX = this.padWidthLeft;

    // Note: Unfortunately, this does not work for ( dilation > 1 ). So, only ( dilation == 1 ) is supported.
    for ( let inChannel = 0; inChannel < this.inputDepth; ++inChannel ) {

      for ( let outChannelSub = 0; outChannelSub < this.channelMultiplier; ++outChannelSub ) {

        for ( let filterY = 0, effectFilterY = 0; filterY < this.filterHeight; ++filterY ) {
          for ( let dilationFilterY = 0; dilationFilterY < this.dilationHeight; ++dilationFilterY, ++effectFilterY ) {
            let filterIndexBaseX = ( filterY * this.filterWidth );

            for ( let filterX = 0, effectFilterX = 0; filterX < this.filterWidth; ++filterX ) {
              for ( let dilationFilterX = 0; dilationFilterX < this.dilationWidth; ++dilationFilterX, ++effectFilterX ) {

                // The filter's dilation part can not be manipulated. (They are always zero.)
                if ( ( 0 != dilationFilterY ) || ( 0 != dilationFilterX ) )
                  continue;

                let filterIndexBaseC = ( ( filterIndexBaseX + filterX ) * this.outputDepth );
                let filterIndexBaseSubC = filterIndexBaseC + ( inChannel * this.channelMultiplier );

                let filterIndex = filterIndexBaseSubC + outChannelSub;

                if ( ( effectFilterY == oneEffectFilterY ) && ( effectFilterX == oneEffectFilterX ) ) {
//!!! (2021/12/07 Remarked)
//                  depthwiseFiltersArray[ filterIndex ] = 1; // The only one position with value one.
                  depthwiseFiltersArray[ filterIndex ] = filterValue; // The only one position with value non-zero.
                  filterValue
                } else {
                  depthwiseFiltersArray[ filterIndex ] = 0; // All other positions of the filter are value zero.
                }
              }
            }
          }
        }
      }
    }

    return depthwiseFiltersArray;
  }

}

<commit_msg>Update Depthwise_PadInfoCalculator.js<commit_after>export { PadInfoCalculator };

import * as ValueDesc from "../../Unpacker/ValueDesc.js";

/**
 * According to input image size and depthwise convolution parameters, calculate the padding information of the depthwise convolution.
 *
 * @member {number} inputHeight           Input image height.
 * @member {number} inputWidth            Input image width.
 * @member {number} inputDepth            Input image channel count.
 * @member {number} AvgMax_Or_ChannelMultiplier   Depthwise operation. (ValueDesc.AvgMax_Or_ChannelMultiplier)
 * @member {number} filterHeight          The height of the depthwise convolution's filter.
 * @member {number} filterWidth           The width of the depthwise convolution's filter.
 * @member {number} stridesPad            The strides and padding of depthwise convolution. (PointDepthPoint.Params.depthwiseStridesPad)
 *
 * @member {number} channelMultiplier     The channel multiplier of the depthwise operation (according to AvgMax_Or_ChannelMultiplier).
 *
 * @member {number} dilationHeight        The depthwise filters's dilation across height dimension.
 * @member {number} dilationWidth         The depthwise filters's dilation across width dimension.
 *
 * @member {number} effectFilterHeight    The effect height of the depthwise convolution's filter including the dilationHeight.
 * @member {number} effectFilterWidth     The effect width of the depthwise convolution's filter including the dilationWidth.
 * @member {number} effectFilterSize      The effect size of the depthwise convolution's filter. (= effectFilterHeight * effectFilterWidth)
 *
 * @member {number} strides               The strides along the image's height and width dimension (according to stridesPad).
 * @member {number} stridesHeight         The strides along the image's height dimension (according to stridesPad).
 * @member {number} stridesWidth          The strides along the image's width dimension (according to stridesPad).

 * @member {number} pad                   The padding along the image's height and width dimension (according to stridesPad).
 * @member {number} padHeight             The padding along the input image's height dimension.
 * @member {number} padHeightTop          The padding along the input image's height dimension at the top.
 * @member {number} padHeightBottom       The padding along the input image's height dimension at the bottom.
 * @member {number} padWidth              The padding along the input image's width dimension.
 * @member {number} padWidthLeft          The padding along the input image's width dimension at the left.
 * @member {number} padWidthRight         The padding along the input image's width dimension at the right.
 *
 * @member {number} outputHeight          Output image height.
 * @member {number} outputWidth           Output image width.
 * @member {number} outputDepth           Output image channel count.
 * @member {number} outputElementCount    Output image elements count (= ( outputHeight * outputWidth * outputDepth ) ).
 */
let PadInfoCalculator = ( Base = Object ) => class extends Base {

  constructor( inputHeight, inputWidth, inputDepth, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad ) {
    super();
    this.inputHeight = inputHeight;
    this.inputWidth = inputWidth;
    this.inputDepth = inputDepth;
    this.AvgMax_Or_ChannelMultiplier = AvgMax_Or_ChannelMultiplier;
    this.filterHeight = filterHeight;
    this.filterWidth = filterWidth;
    this.stridesPad = stridesPad;

//!!! ...unfinished... (2021/03/17) What about ( filterHeight <= 0 ) or ( filterWidth <= 0 )?

    this.channelMultiplier = AvgMax_Or_ChannelMultiplier;
    if (   ( ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.AVG === AvgMax_Or_ChannelMultiplier )
        || ( ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.MAX === AvgMax_Or_ChannelMultiplier ) ) {
      this.channelMultiplier = 1;
    }

    // Strides and Padding.
    switch ( stridesPad ) {
      case 0:  this.strides = 1; this.pad = "valid"; break;
      default:
      case 1:  this.strides = 1; this.pad = "same";  break;
      case 2:  this.strides = 2; this.pad = "same";  break;
    }

    // Assume strides width equals strides height.
    this.stridesHeight = this.strides;
    this.stridesWidth = this.strides;

    // Currently, we can only handle dilation = 1.
    this.dilationHeight = 1;
    this.dilationWidth = 1;

    // Effect filter size (includes dilation).
    this.effectFilterHeight = this.dilationHeight * ( this.filterHeight - 1 ) + 1;
    this.effectFilterWidth =  this.dilationWidth  * ( this.filterWidth  - 1 ) + 1;
    this.effectFilterSize = this.effectFilterHeight * this.effectFilterWidth;

    // (The following codes for output image height and width and padding calculation are copied from
    // https://github.com/tensorflow/tfjs/blob/tfjs-v3.8.0/tfjs-core/src/ops/conv_util.ts)
    {
      // Determine output image height and width without padding.
      if ( this.pad == "valid" ) {
        this.outputHeight = Math.ceil( ( inputHeight - this.effectFilterHeight + 1 ) / this.stridesHeight );
        this.outputWidth =  Math.ceil( ( inputWidth  - this.effectFilterWidth  + 1 ) / this.stridesWidth  );

        this.padHeight = this.padHeightTop = this.padHeightBottom = this.padWidth = this.padWidthLeft = this.padWidthRight = 0;

      // Determine output image height and width with padding around the input image height and width.
      } else if ( this.pad == "same" ) {
        this.outputHeight = Math.ceil( inputHeight / this.stridesHeight );
        this.outputWidth =  Math.ceil( inputWidth  / this.stridesWidth  );

        this.padHeight = Math.max( 0, ( this.outputHeight - 1 ) * this.stridesHeight + this.effectFilterHeight - inputHeight );
        this.padWidth =  Math.max( 0, ( this.outputWidth  - 1 ) * this.stridesWidth  + this.effectFilterWidth  - inputWidth  );

        this.padHeightTop =    Math.floor( this.padHeight / 2 );
        this.padHeightBottom = this.padHeight - this.padHeightTop;
        this.padWidthLeft =    Math.floor( this.padWidth /  2 );
        this.padWidthRight =   this.padWidth  - this.padWidthLeft;
      }
    }

    this.outputDepth = inputDepth * this.channelMultiplier;
    this.outputElementCount = ( this.outputHeight * this.outputWidth * this.outputDepth );
  }

  /**
   * @param {number} filterValue
   *   The (non-zero) value used in the pass-through depthwise convolution filter. Default is 1.
   *
   * @return {number[]}
   *   Return the depthwise convolution filters which could pass the input to output unchangely.
   */
  generate_PassThrough_FiltersArray( filterValue = 1 ) {

    if (   ( ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.AVG === this.AvgMax_Or_ChannelMultiplier )
        || ( ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.MAX === this.AvgMax_Or_ChannelMultiplier ) ) {
      return null; // The depthwise filter of AVG pooling and MAX pooling can not be manipulated.
    }

    // Make up a depthwise convolution filter.
    let depthwiseFiltersArray = new Array( this.filterHeight * this.filterWidth * this.inputDepth * this.channelMultiplier );

    // There is only one position (inside the effect depthwise filter) with value one. All other positions of the filter should be zero.
    let oneEffectFilterY = this.padHeightTop;
    let oneEffectFilterX = this.padWidthLeft;

    // Note: Unfortunately, this does not work for ( dilation > 1 ). So, only ( dilation == 1 ) is supported.
    for ( let inChannel = 0; inChannel < this.inputDepth; ++inChannel ) {

      for ( let outChannelSub = 0; outChannelSub < this.channelMultiplier; ++outChannelSub ) {

        for ( let filterY = 0, effectFilterY = 0; filterY < this.filterHeight; ++filterY ) {
          for ( let dilationFilterY = 0; dilationFilterY < this.dilationHeight; ++dilationFilterY, ++effectFilterY ) {
            let filterIndexBaseX = ( filterY * this.filterWidth );

            for ( let filterX = 0, effectFilterX = 0; filterX < this.filterWidth; ++filterX ) {
              for ( let dilationFilterX = 0; dilationFilterX < this.dilationWidth; ++dilationFilterX, ++effectFilterX ) {

                // The filter's dilation part can not be manipulated. (They are always zero.)
                if ( ( 0 != dilationFilterY ) || ( 0 != dilationFilterX ) )
                  continue;

                let filterIndexBaseC = ( ( filterIndexBaseX + filterX ) * this.outputDepth );
                let filterIndexBaseSubC = filterIndexBaseC + ( inChannel * this.channelMultiplier );

                let filterIndex = filterIndexBaseSubC + outChannelSub;

                if ( ( effectFilterY == oneEffectFilterY ) && ( effectFilterX == oneEffectFilterX ) ) {
                  depthwiseFiltersArray[ filterIndex ] = filterValue; // The only one position with value non-zero.
                  filterValue
                } else {
                  depthwiseFiltersArray[ filterIndex ] = 0; // All other positions of the filter are value zero.
                }
              }
            }
          }
        }
      }
    }

    return depthwiseFiltersArray;
  }

}

<|endoftext|>


<commit_before>module.exports = {

  'env': {
    'browser': true
  },

  'globals': {
    'define': 'readonly',
    'Promise': 'readonly',
    'module': 'readonly'
  },

  'extends': 'eslint:recommended',

  'rules': {
    'indent': ['error', 2, { 'VariableDeclarator': 'first' }],
    'linebreak-style': ['error', 'unix'],
    'quotes': ['error', 'single', {'avoidEscape':  true, 'allowTemplateLiterals': true}],
    'no-console': ['error', { 'allow': ['warn', 'error'] }],
    'no-multi-spaces': ['error', { 'ignoreEOLComments': true }],
    'no-trailing-spaces': ['error', { 'skipBlankLines': true, 'ignoreComments': true }],
    'no-underscore-dangle': 'off'
  }

};<commit_msg>Aligned eslint config with prettier (mostly)<commit_after>module.exports = {

  'env': {
    'browser': true
  },

  'globals': {
    'define': 'readonly',
    'Promise': 'readonly',
    'module': 'readonly'
  },

  'extends': ['eslint:recommended', 'prettier'],

  'rules': {
    'indent': ['error', 2],
    'linebreak-style': ['error', 'unix'],
    'quotes': ['error', 'double', {'avoidEscape':  true, 'allowTemplateLiterals': true}],
    'no-console': ['error', { 'allow': ['info', 'warn', 'error'] }],
    'no-multi-spaces': ['error', { 'ignoreEOLComments': true }],
    'no-trailing-spaces': ['error', { 'skipBlankLines': true, 'ignoreComments': true }],
    'no-underscore-dangle': 'off',
    'quote-props': ["error", "as-needed"]
  }

};<|endoftext|>