<commit_before>'use strict'
var ObjectId = require("mongodb").ObjectId;
require('mongodb-toolkit');
var DLModels = require('dl-models');
var assert = require('assert');
var map = DLModels.map;

var UnitReceiptNote = DLModels.purchasing.UnitReceiptNote;
var BaseManager = require('../base-manager');

module.exports = class UnitReceiptNoteManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.purchasing.collection.UnitReceiptNote);
    }

    _validate(unitReceiptNote) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = unitReceiptNote;

            var getUnitReceiptNotePromise = this.collection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': new ObjectId(valid._id)
                    }
                }, {
                        "no": valid.no
                    }]
            });

            Promise.all([getUnitReceiptNotePromise])
                .then(results => {
                    var _module = results[0];
                    var now = new Date();

                    if (!valid.no || valid.no == '')
                        errors["no"] = "No. bon unit tidak boleh kosong";
                    else if (_module)
                        errors["no"] = "No. bon unit sudah terdaftar";

                    if (!valid.unitId)
                        errors["unit"] = "Unit tidak boleh kosong";
                    else if (valid.unit) {
                        if (!valid.unit._id)
                            errors["unit"] = "Unit tidak boleh kosong";
                    }
                    else if (!valid.unit)
                        errors["unit"] = "Nama supplier tidak boleh kosong";

                    if (!valid.supplierId)
                        errors["supplier"] = "Nama supplier tidak boleh kosong";
                    else if (valid.supplier) {
                        if (!valid.supplier._id)
                            errors["supplier"] = "Nama supplier tidak boleh kosong";
                    }
                    else if (!valid.supplier)
                        errors["supplier"] = "Nama supplier tidak boleh kosong";

                    if (!valid.deliveryOrderId)
                        errors["deliveryOrder"] = "No. surat jalan tidak boleh kosong";
                    else if (valid.deliveryOrder) {
                        if (!valid.deliveryOrder._id)
                            errors["deliveryOrder"] = "No. surat jalan tidak boleh kosong";
                    }
                    else if (!valid.deliveryOrder)
                        errors["deliveryOrder"] = "No. surat jalan tidak boleh kosong";

                    if (valid.items.length <= 0) {
                        errors["items"] = "Harus ada minimal 1 barang";
                    }
                    else {
                        var itemErrors = [];
                        for (var item of valid.items) {
                            var itemError = {};
                            if (item.deliveredQuantity < 0)
                                itemError["deliveredQuantity"] = "Jumlah barang tidak boleh kosong";
                            itemErrors.push(itemError);
                        }
                        for (var itemError of itemErrors) {
                            for (var prop in itemError) {
                                errors.items = itemErrors;
                                break;
                            }
                            if (errors.items)
                                break;
                        }
                    }

                    if (Object.getOwnPropertyNames(errors).length > 0) {
                        var ValidationError = require('../../validation-error');
                        reject(new ValidationError('data does not pass validation', errors));
                    }

                    if (!valid.stamp)
                        valid = new UnitReceiptNote(valid);

                    valid.stamp(this.user.username, 'manager');
                    resolve(valid);
                })
                .catch(e => {
                    reject(e);
                })

        });
    }

    _getQuery(paging) {
        var filter = {
            _deleted: false
        };

        var query = paging.keyword ? {
            '$and': [filter]
        } : filter;

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");

            var filterNo = {
                'no': {
                    '$regex': regex
                }
            };

            var filterSupplierName = {
                'supplier.name': {
                    '$regex': regex
                }
            };

            var filterUnitDivision = {
                "unit.division": {
                    '$regex': regex
                }
            };
            var filterUnitSubDivision = {
                "unit.subDivision": {
                    '$regex': regex
                }
            };

            var filterDeliveryOrder = {
                "deliveryOrder.no": {
                    '$regex': regex
                }
            };

            var $or = {
                '$or': [filterNo, filterSupplierName, filterUnitDivision, filterUnitSubDivision, filterDeliveryOrder]
            };

            query['$and'].push($or);
        }
        return query;
    }

    create(unitReceiptNote) {
        return new Promise((resolve, reject) => {
            var tasks = [];
            var tasksPoExternal = [];
            var getPurchaseOrderById = [];
            this._validate(unitReceiptNote)
                .then(validUnitReceiptNote => {
                    validUnitReceiptNote.unitId = new ObjectId(validUnitReceiptNote.unitId);
                    validUnitReceiptNote.supplierId = new ObjectId(validUnitReceiptNote.supplierId);
                    validUnitReceiptNote.deliveryOrderId = new ObjectId(validUnitReceiptNote.deliveryOrderId);
                    this.collection.insert(validUnitReceiptNote)
                        .then(id => {
                            resolve(id);
                            //update PO Internal
                            // for (var doItem of validUnitReceiptNoteItem.deliveryOrder.items) {
                            //     for (var fulfillment of doItem.fulfillments)
                            //         getPurchaseOrderById.push(this.purchaseOrderManager.getSingleById(fulfillment.purchaseOrder._id));
                            // }
                            // Promise.all(getPurchaseOrderById)
                            //     .then(results => {
                            //         for (var result of results) {
                            //             var purchaseOrder = result;
                            //             for (var poItem of purchaseOrder.items) {
                            //                 for (var unitReceiptNoteItem of validUnitReceiptNote.items) {
                            //                     if (validUnitReceiptNote.unitId.equals(purchaseOrder.unitId)) {
                            //                         if (unitReceiptNoteItem.product._id.equals(poItem.product._id)) {
                            //                             for (var fulfillment of poItem.fulfillments) {
                            //                                 if (fulfillment.no.equals(validUnitReceiptNoteItem.deliveryOrder.no)) {
                            //                                     fulfillment.unitReceiptNoteNo = validUnitReceiptNoteItem.no;
                            //                                     fulfillment.unitReceiptNoteDate = validUnitReceiptNoteItem.date;
                            //                                     fulfillment.unitReceiptNoteDeliveredQuantity = unitReceiptNoteItem.deliveredQuantity;
                            //                                     fulfillment.unitReceiptDeliveredUom = unitReceiptNoteItem.deliveredUom;
                            //                                 }
                            //                             }
                            //                         }
                            //                     }
                            //                 }
                            //             }
                            //             tasks.push(this.purchaseOrderManager.update(purchaseOrder));
                            //         }

                            //         Promise.all(tasks)
                            //             .then(results => {
                            //                 resolve(id);
                            //             })
                            //             .catch(e => {
                            //                 reject(e);
                            //             })

                            //     })
                            //     .catch(e => {
                            //         reject(e);
                            //     });
                            // for (var validUnitReceiptNoteItem of validUnitReceiptNote.items) {
                            //     for (var doItem of validUnitReceiptNoteItem.deliveryOrder.items) {
                            //         for (var fulfillment of doItem.fulfillments)
                            //             getPurchaseOrderById.push(this.purchaseOrderManager.getSingleById(fulfillment.purchaseOrder._id));
                            //     }
                            //     Promise.all(getPurchaseOrderById)
                            //         .then(results => {
                            //             for (var result of results) {
                            //                 var purchaseOrder = result;
                            //                 for (var poItem of purchaseOrder.items) {
                            //                     var doItems = validUnitReceiptNoteItem.fulfillments;
                            //                     for (var doItem of doItems) {
                            //                         if (purchaseOrder._id == doItem.purchaseOrder._id && poItem.product._id == doItem.product._id) {

                            //                             var fulfillmentObj = {
                            //                                 no: validUnitReceiptNote.no,
                            //                                 deliveredQuantity: doItem.deliveredQuantity,
                            //                                 date: validUnitReceiptNote.date,
                            //                                 supplierDoDate: validUnitReceiptNote.supplierDoDate
                            //                             };
                            //                             poItem.fulfillments.push(fulfillmentObj);

                            //                             var totalRealize = 0;
                            //                             for (var poItemFulfillment of poItem.fulfillments) {
                            //                                 totalRealize += poItemFulfillment.deliveredQuantity;
                            //                             }
                            //                             poItem.realizationQuantity = totalRealize;
                            //                             if (poItem.realizationQuantity == poItem.pricePerDealUnit)
                            //                                 poItem.isClosed = true;
                            //                             else
                            //                                 poItem.isClosed = false;
                            //                             break;
                            //                         }
                            //                     }
                            //                 }
                            //                 for (var poItem of purchaseOrder.items) {
                            //                     if (poItem.isClosed == true)
                            //                         purchaseOrder.isClosed = true;
                            //                     else {
                            //                         purchaseOrder.isClosed = false;
                            //                         break;
                            //                     }
                            //                 }
                            //                 tasks.push(this.purchaseOrderManager.update(purchaseOrder));
                            //             }

                            //             Promise.all(tasks)
                            //                 .then(results => {
                            //                     //update PO Eksternal
                            //                     for (var validDeliveryOrderItem of validUnitReceiptNote.items) {
                            //                         var purchaseOrderExternal = validDeliveryOrderItem.purchaseOrderExternal;
                            //                         var getPurchaseOrderById = [];
                            //                         for (var purchaseOrderExternalItem of purchaseOrderExternal.items) {
                            //                             // var indexPO = purchaseOrderExternal.items.indexOf(purchaseOrderExternalItem);
                            //                             getPurchaseOrderById.push(this.purchaseOrderManager.getSingleById(purchaseOrderExternalItem._id));
                            //                         }
                            //                         Promise.all(getPurchaseOrderById)
                            //                             .then(results => {
                            //                                 for (var result of results) {
                            //                                     if (result.isClosed == true)
                            //                                         purchaseOrderExternal.isClosed = true;
                            //                                     else {
                            //                                         purchaseOrderExternal.isClosed = false;
                            //                                         break;
                            //                                     }
                            //                                 }
                            //                                 purchaseOrderExternal.items = results;
                            //                                 tasksPoExternal.push(this.purchaseOrderExternalManager.update(purchaseOrderExternal));
                            //                             })
                            //                             .catch(e => {
                            //                                 reject(e);
                            //                             });

                            //                     }

                            //                     Promise.all(tasksPoExternal)
                            //                         .then(results => {
                            //                             resolve(id);
                            //                         })
                            //                         .catch(e => {
                            //                             reject(e);
                            //                         })
                            //                 })
                            //                 .catch(e => {
                            //                     reject(e);
                            //                 })

                            //         })
                            //         .catch(e => {
                            //             reject(e);
                            //         });
                            // }

                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

}<commit_msg>update function of create -> when create, update po internal insert fulfillment<commit_after>'use strict'
var ObjectId = require("mongodb").ObjectId;
require('mongodb-toolkit');
var DLModels = require('dl-models');
var assert = require('assert');
var map = DLModels.map;

var UnitReceiptNote = DLModels.purchasing.UnitReceiptNote;
var PurchaseOrderManager = require('./purchase-order-manager');
var BaseManager = require('../base-manager');

module.exports = class UnitReceiptNoteManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.purchasing.collection.UnitReceiptNote);
        this.purchaseOrderManager = new PurchaseOrderManager(db, user);
    }

    _validate(unitReceiptNote) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = unitReceiptNote;

            var getUnitReceiptNotePromise = this.collection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': new ObjectId(valid._id)
                    }
                }, {
                        "no": valid.no
                    }]
            });

            Promise.all([getUnitReceiptNotePromise])
                .then(results => {
                    var _module = results[0];
                    var now = new Date();

                    if (!valid.no || valid.no == '')
                        errors["no"] = "No. bon unit tidak boleh kosong";
                    else if (_module)
                        errors["no"] = "No. bon unit sudah terdaftar";

                    if (!valid.unitId)
                        errors["unit"] = "Unit tidak boleh kosong";
                    else if (valid.unit) {
                        if (!valid.unit._id)
                            errors["unit"] = "Unit tidak boleh kosong";
                    }
                    else if (!valid.unit)
                        errors["unit"] = "Nama supplier tidak boleh kosong";

                    if (!valid.supplierId)
                        errors["supplier"] = "Nama supplier tidak boleh kosong";
                    else if (valid.supplier) {
                        if (!valid.supplier._id)
                            errors["supplier"] = "Nama supplier tidak boleh kosong";
                    }
                    else if (!valid.supplier)
                        errors["supplier"] = "Nama supplier tidak boleh kosong";

                    if (!valid.deliveryOrderId)
                        errors["deliveryOrder"] = "No. surat jalan tidak boleh kosong";
                    else if (valid.deliveryOrder) {
                        if (!valid.deliveryOrder._id)
                            errors["deliveryOrder"] = "No. surat jalan tidak boleh kosong";
                    }
                    else if (!valid.deliveryOrder)
                        errors["deliveryOrder"] = "No. surat jalan tidak boleh kosong";

                    if (valid.items.length <= 0) {
                        errors["items"] = "Harus ada minimal 1 barang";
                    }
                    else {
                        var itemErrors = [];
                        for (var item of valid.items) {
                            var itemError = {};
                            if (item.deliveredQuantity < 0)
                                itemError["deliveredQuantity"] = "Jumlah barang tidak boleh kosong";
                            itemErrors.push(itemError);
                        }
                        for (var itemError of itemErrors) {
                            for (var prop in itemError) {
                                errors.items = itemErrors;
                                break;
                            }
                            if (errors.items)
                                break;
                        }
                    }

                    if (Object.getOwnPropertyNames(errors).length > 0) {
                        var ValidationError = require('../../validation-error');
                        reject(new ValidationError('data does not pass validation', errors));
                    }

                    if (!valid.stamp)
                        valid = new UnitReceiptNote(valid);

                    valid.stamp(this.user.username, 'manager');
                    resolve(valid);
                })
                .catch(e => {
                    reject(e);
                })

        });
    }

    _getQuery(paging) {
        var filter = {
            _deleted: false
        };

        var query = paging.keyword ? {
            '$and': [filter]
        } : filter;

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");

            var filterNo = {
                'no': {
                    '$regex': regex
                }
            };

            var filterSupplierName = {
                'supplier.name': {
                    '$regex': regex
                }
            };

            var filterUnitDivision = {
                "unit.division": {
                    '$regex': regex
                }
            };
            var filterUnitSubDivision = {
                "unit.subDivision": {
                    '$regex': regex
                }
            };

            var filterDeliveryOrder = {
                "deliveryOrder.no": {
                    '$regex': regex
                }
            };

            var $or = {
                '$or': [filterNo, filterSupplierName, filterUnitDivision, filterUnitSubDivision, filterDeliveryOrder]
            };

            query['$and'].push($or);
        }
        return query;
    }

    create(unitReceiptNote) {
        return new Promise((resolve, reject) => {
            var tasks = [];
            var tasksPoExternal = [];
            var getPurchaseOrderById = [];
            this._validate(unitReceiptNote)
                .then(validUnitReceiptNote => {
                    validUnitReceiptNote.unitId = new ObjectId(validUnitReceiptNote.unitId);
                    validUnitReceiptNote.supplierId = new ObjectId(validUnitReceiptNote.supplierId);
                    validUnitReceiptNote.deliveryOrderId = new ObjectId(validUnitReceiptNote.deliveryOrderId);
                    this.collection.insert(validUnitReceiptNote)
                        .then(id => {
                            //update PO Internal
                            for (var doItem of validUnitReceiptNote.deliveryOrder.items) {
                                for (var fulfillment of doItem.fulfillments)
                                    getPurchaseOrderById.push(this.purchaseOrderManager.getSingleById(fulfillment.purchaseOrder._id));
                            }
                            Promise.all(getPurchaseOrderById)
                                .then(results => {
                                    for (var result of results) {
                                        var purchaseOrder = result;
                                        for (var poItem of purchaseOrder.items) {
                                            for (var unitReceiptNoteItem of validUnitReceiptNote.items) {
                                                if (validUnitReceiptNote.unitId.equals(purchaseOrder.unitId)) {
                                                    if (unitReceiptNoteItem.product._id.equals(poItem.product._id)) {
                                                        for (var fulfillment of poItem.fulfillments) {
                                                            var fulfillmentNo = fulfillment.no || '';
                                                            var deliveryOrderNo = validUnitReceiptNote.deliveryOrder.no || '';
                                                            if (fulfillmentNo == deliveryOrderNo ) {
                                                                fulfillment.unitReceiptNoteNo = validUnitReceiptNote.no;
                                                                fulfillment.unitReceiptNoteDate = validUnitReceiptNote.date;
                                                                fulfillment.unitReceiptNoteDeliveredQuantity = unitReceiptNoteItem.deliveredQuantity;
                                                                fulfillment.unitReceiptDeliveredUom = unitReceiptNoteItem.deliveredUom;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        tasks.push(this.purchaseOrderManager.update(purchaseOrder));
                                    }

                                    Promise.all(tasks)
                                        .then(results => {
                                            resolve(id);
                                        })
                                        .catch(e => {
                                            reject(e);
                                        })

                                })
                                .catch(e => {
                                    reject(e);
                                });
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

}<|endoftext|>


<commit_before>import React from 'react'
import { connect } from 'react-redux'
import validator from 'validator'
import {
  closeModal, fetchCommunitySettings, updateTagInvitationEditor, sendCommunityTagInvitation,
  SEND_COMMUNITY_TAG_INVITATION
} from '../actions'
import A from '../components/A'
import { Modal } from '../components/Modal'
import { communityTagJoinUrl } from '../routes'
import { parseEmailString } from '../util/text'
import { get, isEmpty, some } from 'lodash'
import cx from 'classnames'
const { func, string, object, bool } = React.PropTypes

@connect(({ communities, tagInvitationEditor, pending }, { slug }) => ({
  community: communities[slug],
  tagInvitationEditor,
  pending: pending[SEND_COMMUNITY_TAG_INVITATION]

}))
export default class ShareTopicModal extends React.Component {
  static propTypes = {
    dispatch: func,
    onCancel: func,
    tagName: string,
    slug: string,
    community: object,
    tagInvitationEditor: object,
    pending: bool
  }

  componentDidMount () {
    let { dispatch, slug, community } = this.props
    if (get(community, 'beta_access_code')) return
    dispatch(fetchCommunitySettings(slug))
  }

  render () {
    let { onCancel, tagName, community, dispatch, pending,
      tagInvitationEditor: { recipients, error, success } } = this.props
    let loaded = get(community, 'beta_access_code')
    let joinUrl
    if (loaded) joinUrl = communityTagJoinUrl(community, tagName)

    let setError = text => dispatch(updateTagInvitationEditor('error', text))

    let update = (field) => event =>
      dispatch(updateTagInvitationEditor(field, event.target.value))

    let submit = () => {
      setError(null)

      let emails = parseEmailString(recipients)
      if (isEmpty(emails)) return setError('Enter at least one email address.')

      let badEmails = emails.filter(email => !validator.isEmail(email))
      if (some(badEmails)) return setError(`These emails are invalid: ${badEmails.join(', ')}`)

      dispatch(sendCommunityTagInvitation(community.id, tagName, {emails}))
    }

    return <Modal title='Invite to join conversation' id='share-topic' onCancel={onCancel}>

        Copy Link
        {loaded
        ? {joinUrl}
      : Loading...}

        People
        <input type='text'
          placeholder='Enter email addresses, separated by commas'
          value={recipients}
          onChange={update('recipients')}/>

      {error &&
{error}
}
      {success &&
{success}
}

        <button onClick={() => dispatch(closeModal())}>Done</button>
        <button onClick={submit} className={cx({ok: !pending})}>
          {pending ? 'Sending...' : 'Invite'}
        </button>

    </Modal>
  }
}
<commit_msg>cleanup<commit_after>import React from 'react'
import { connect } from 'react-redux'
import validator from 'validator'
import {
  closeModal, fetchCommunitySettings, updateTagInvitationEditor, sendCommunityTagInvitation,
  SEND_COMMUNITY_TAG_INVITATION
} from '../actions'
import A from '../components/A'
import { Modal } from '../components/Modal'
import { communityTagJoinUrl } from '../routes'
import { parseEmailString } from '../util/text'
import { get, isEmpty, some } from 'lodash'
import cx from 'classnames'
const { func, string, object, bool } = React.PropTypes

@connect(({ communities, tagInvitationEditor, pending }, { slug }) => ({
  community: communities[slug],
  tagInvitationEditor,
  pending: pending[SEND_COMMUNITY_TAG_INVITATION]

}))
export default class ShareTopicModal extends React.Component {
  static propTypes = {
    dispatch: func,
    onCancel: func,
    tagName: string,
    slug: string,
    community: object,
    tagInvitationEditor: object,
    pending: bool
  }

  componentDidMount () {
    let { dispatch, slug, community } = this.props
    if (get(community, 'beta_access_code')) return
    dispatch(fetchCommunitySettings(slug))
  }

  render () {
    const { onCancel, tagName, community, dispatch, pending,
      tagInvitationEditor: { recipients, error, success } } = this.props
    const joinUrl = get(community, 'beta_access_code')
      ? communityTagJoinUrl(community, tagName)
      : null

    const setError = text => dispatch(updateTagInvitationEditor('error', text))

    const update = (field) => event =>
      dispatch(updateTagInvitationEditor(field, event.target.value))

    const submit = () => {
      setError(null)

      let emails = parseEmailString(recipients)
      if (isEmpty(emails)) return setError('Enter at least one email address.')

      let badEmails = emails.filter(email => !validator.isEmail(email))
      if (some(badEmails)) return setError(`These emails are invalid: ${badEmails.join(', ')}`)

      dispatch(sendCommunityTagInvitation(community.id, tagName, {emails}))
    }

    return <Modal title='Invite to join conversation' id='share-topic' onCancel={onCancel}>

        Copy Link
        {joinUrl ? {joinUrl} : Loading...}

        People
        <input type='text'
          placeholder='Enter email addresses, separated by commas'
          value={recipients}
          onChange={update('recipients')}/>

      {error &&
{error}
}
      {success &&
{success}
}

        <button onClick={() => dispatch(closeModal())}>Done</button>
        <button onClick={submit} className={cx({ok: !pending})}>
          {pending ? 'Sending...' : 'Invite'}
        </button>

    </Modal>
  }
}
<|endoftext|>


<commit_before>/**
 * tbwdjs -- TestingBotWebDriverJS
 * @author tom@goochesa.de (Tom Regner)
 *
 * based on the example code formerly provided by the testingbot.com
 * website (end-replacement).
 */

'use strict';

var webdriverjs = require('webdriverjs');
var http = require('http');
var qs = require('querystring');
var assert = require('assert');
var util = require('util');

var TbApi = require('./api');

/**
 * allow ~/.testingbot usage
 */
function fixAuth(options) {
  if (!options.api_key || !options.api_secret) {
    var fs = require('fs');
    try {
      var data = fs.readFileSync(process.env.HOME + '/.testingbot');
      if (data !== null) {
        var arr = data.toString().split(':');
        options.api_key = arr[0];
        options.api_secret = arr[1];
      }
    } catch (e) {
      console.log('couldn\'t read $HOME/.testingbot');
      console.log(e);
    }
  }
  return options;
}

/**
 * create a testingbot api client
 */
exports.api = function(options) {
  options = fixAuth(options);
  var t = new TbApi(options);
  return t;
};

/**
 * create a testingbot webdriver client
 */
exports.remote = function(options) {
  if (!options.host) {
    options.host = 'hub.testingbot.com';
  }

  options.desiredCapabilities = fixAuth(options.desiredCapabilities);
  if (options.logLevel !== 'silent') {
    console.log('testingbot.com\n\n' +
            'Test startup might take up to 90 seconds.\n' +
            'We might need to fire up a pristine virtual machine for you.\n' +
            '(VM setup times do not deplete your testing minutes.)');
  }
  var client = webdriverjs.remote(options);

  if (options.withApi === true) {
    client.api = new TbApi(options.desiredCapabilities);
  }

  // replace the end function, so that the
  // testingbot session will be deleted
  var webjsEnd = client.end;
  client._errors = [];
  client.end = function(fn) {
    webjsEnd(function() {
      var name = options.name || 'unnamed';
      if (fn) { fn(); }
      if (!client.api) {
        client.api = new TbApi(options.desiredCapabilities);
      }
      client.api.updateTest({
        test: {
          success: client._errors.length === 0 ? 1 : 0,
          name: name
        }
      }, client.sessionId);
    });
  };

  /* additional protocol commands */
  client.addCommand('windowHandle', function(callback) {
    var commandOptions = {
      path: '/session/:sessionId/window_handle',
      method: 'GET'
    };

    var data = {};

    this.executeProtocolCommand(
        commandOptions,
        this.proxyResponse(callback),
        data
    );
  });

  /* commands that push to client._error */
  client.addCommand('titleEquals', function(expected, callback) {
    var self = this;
    self.direct.title(function(title) {
      try {
        assert.equal(title.value, expected);
      } catch (e) {
        self._errors.push(e);
      }
      self.showTest(title.value === expected,
                    title.value, expected,
                    'Title is "' + expected + '"'
      );
      if (typeof callback === 'function') {
        callback(title.value === expected);
      }
    });
  });
  client.addCommand('cssVisible', function(cssSelector, visible, callback) {
    var self = this;
    self.isVisible(cssSelector,
                   function(result) {
                     try {
                       assert.equal(result, visible);
                     } catch (e) {
                       self._errors.push(e);
                     }
                     self.showTest(result === visible, result, visible,
                                   cssSelector +
                                   (visible ? ' ' : ' not ') +
                                   'visible');
                     if (typeof callback === 'function') {
                       callback(result);
                     }
                   }
    );
  });
  client.addCommand('evaluate', function(fun, expected, message, callback) {
    var self = this;
    self.direct.execute(fun, function(result) {
      try {
        assert(result.value, expected);
      } catch (e) {
        self._errors.push(e);
      }
      self.showTest(result.value === expected, result.value, expected, message);
      if (typeof callback === 'function') {
        callback(result);
      }
    });
  });
  client.addCommand('waitForVar',
                    function(varname, expected, myTimeout, equality, callback) {
                      var self = this;
                      var startTime = new Date().getTime();
                      function checkValue(val) {
                        return equality ? val === expected : val !== expected;
                      }
                      function checkVariable() {
                        var now = new Date().getTime();
                        var code = 'var myResult = ' +
                           varname + '; return myResult;';
                        self.direct.execute(code, function(result) {
                          if (result.status === 0 && checkValue(result.value)) {
                            if (typeof callback === 'function') {
                              callback(result.value);
                            }
                          } else {
                            if (now - startTime < myTimeout) {
                              setTimeout(checkVariable, 500);
                            } else if (typeof callback === 'function') {
                              callback(result);
                            }
                          }
                        });
                      }
                      checkVariable();
                    }
                   );
  client.addCommand('waitForTextIn',
                    function(cssSelector, myTimeout, callback) {
                      var self = this;
                      var startTime = new Date().getTime();
                      function checkForText() {
                        var now = new Date().getTime();
                        self.direct.element('css selector', cssSelector,
                            function(result) {
                              if (result.status === 0) {
                                self.direct.elementIdText(result.value.ELEMENT,
                                    function(result2) {
                                      if (result2.status === 0 &&
                                          result2.value !== '') {
                                        if (typeof callback === 'function') {
                                          callback(result2.value);
                                        }
                                      } else {
                                        if (now - startTime < myTimeout) {
                                          setTimeout(checkForText, 500);
                                        } else {
                                          if (typeof callback === 'function') {
                                            callback(result2);
                                          }
                                        }
                                      }
                                    });
                              } else {
                                if (now - startTime < myTimeout) {
                                  setTimeout(checkForText, 500);
                                } else {
                                  if (typeof callback === 'function') {
                                    callback(result);
                                  }
                                }
                              }
                            });
                      }
                      checkForText();
                    }
                   );
  client.addCommand('waitForValueIn',
                    function(cssSelector, myTimeout, callback) {
                      var self = this;
                      var startTime = new Date().getTime();
                      function checkForText() {
                        var now = new Date().getTime();
                        self.direct.element('css selector', cssSelector,
                            function(result) {
                              if (result.status === 0) {
                                self.direct.elementIdValue(result.value.ELEMENT,
                                    function(result2) {
                                      if (result2.status === 0 &&
                                          result2.value !== '') {
                                        if (typeof callback === 'function') {
                                          callback(result2.value);
                                        }
                                      } else {
                                        if (now - startTime < myTimeout) {
                                          setTimeout(checkForText, 500);
                                        } else {
                                          if (typeof callback === 'function') {
                                            callback(result2);
                                          }
                                        }
                                      }
                                    });
                              } else {
                                if (now - startTime < myTimeout) {
                                  setTimeout(checkForText, 500);
                                } else {
                                  if (typeof callback === 'function') {
                                    callback(result);
                                  }
                                }
                              }
                            });
                      }
                      checkForText();
                    }
                   );
  client.addCommand('getVar',
                    function(varname, callback) {
                      var self = this;
                      var code = 'var myResult = ' +
                         varname + '; return myResult;';
                      self.direct.execute(code, function(result) {
                        if (result.status === 0) {
                          if (typeof callback === 'function') {
                            callback(result.value);
                          }
                        } else if (typeof callback === 'function') {
                          callback(result);
                        }
                      });
                    }
                   );
  client.addCommand('setValues',
                    function(valHash, callback) {
                      var keys = Object.keys(valHash);
                      var self = this;
                      var results = {};
                      var addResult = function(result) {
                           if (result && result.status === 0) {
                             results[keys[i]] = result.value;
                           } else {
                             results[keys[i]] = result;
                           }
                         };

                      for (var i = 0; i < keys.length; ++i) {
                        self.setValue(keys[i],
                                      valHash[keys[i]],
                                      addResult);
                      }
                      callback(results);
                    }
                   );

  return client;
};
<commit_msg>New test titleMatches().<commit_after>/**
 * tbwdjs -- TestingBotWebDriverJS
 * @author tom@goochesa.de (Tom Regner)
 *
 * based on the example code formerly provided by the testingbot.com
 * website (end-replacement).
 */

'use strict';

var webdriverjs = require('webdriverjs');
var http = require('http');
var qs = require('querystring');
var assert = require('assert');
var util = require('util');

var TbApi = require('./api');

/**
 * allow ~/.testingbot usage
 */
function fixAuth(options) {
  if (!options.api_key || !options.api_secret) {
    var fs = require('fs');
    try {
      var data = fs.readFileSync(process.env.HOME + '/.testingbot');
      if (data !== null) {
        var arr = data.toString().split(':');
        options.api_key = arr[0];
        options.api_secret = arr[1];
      }
    } catch (e) {
      console.log('couldn\'t read $HOME/.testingbot');
      console.log(e);
    }
  }
  return options;
}

/**
 * create a testingbot api client
 */
exports.api = function(options) {
  options = fixAuth(options);
  var t = new TbApi(options);
  return t;
};

/**
 * create a testingbot webdriver client
 */
exports.remote = function(options) {
  if (!options.host) {
    options.host = 'hub.testingbot.com';
  }

  options.desiredCapabilities = fixAuth(options.desiredCapabilities);
  if (options.logLevel !== 'silent') {
    console.log('testingbot.com\n\n' +
            'Test startup might take up to 90 seconds.\n' +
            'We might need to fire up a pristine virtual machine for you.\n' +
            '(VM setup times do not deplete your testing minutes.)');
  }
  var client = webdriverjs.remote(options);

  if (options.withApi === true) {
    client.api = new TbApi(options.desiredCapabilities);
  }

  // replace the end function, so that the
  // testingbot session will be deleted
  var webjsEnd = client.end;
  client._errors = [];
  client.end = function(fn) {
    webjsEnd(function() {
      var name = options.name || 'unnamed';
      if (fn) { fn(); }
      if (!client.api) {
        client.api = new TbApi(options.desiredCapabilities);
      }
      client.api.updateTest({
        test: {
          success: client._errors.length === 0 ? 1 : 0,
          name: name
        }
      }, client.sessionId);
    });
  };

  /* additional protocol commands */
  client.addCommand('windowHandle', function(callback) {
    var commandOptions = {
      path: '/session/:sessionId/window_handle',
      method: 'GET'
    };

    var data = {};

    this.executeProtocolCommand(
        commandOptions,
        this.proxyResponse(callback),
        data
    );
  });

  /* commands that push to client._error */
  client.addCommand('titleEquals', function(expected, callback) {
    var self = this;
    self.direct.title(function(title) {
      try {
        assert.equal(title.value, expected);
      } catch (e) {
        self._errors.push(e);
      }
      self.showTest(title.value === expected,
                    title.value, expected,
                    'Title is "' + expected + '"'
      );
      if (typeof callback === 'function') {
        callback(title.value === expected);
      }
    });
  });
  client.addCommand('titleMatches', function(pattern, callback) {
    var self = this;
    self.direct.title(function(title) {
      try {
        assert.equal(pattern.test(title.value), true);
      } catch (e) {
        self._errors.push(e);
      }
      self.showTest(pattern.test(title.value) === true,
                    title.value, pattern,
                    'Title matches "' + pattern + '"'
      );
      if (typeof callback === 'function') {
        callback(pattern.test(title.value));
      }
    });
  });
  client.addCommand('cssVisible', function(cssSelector, visible, callback) {
    var self = this;
    self.isVisible(cssSelector,
                   function(result) {
                     try {
                       assert.equal(result, visible);
                     } catch (e) {
                       self._errors.push(e);
                     }
                     self.showTest(result === visible, result, visible,
                                   cssSelector +
                                   (visible ? ' ' : ' not ') +
                                   'visible');
                     if (typeof callback === 'function') {
                       callback(result);
                     }
                   }
    );
  });
  client.addCommand('evaluate', function(fun, expected, message, callback) {
    var self = this;
    self.direct.execute(fun, function(result) {
      try {
        assert(result.value, expected);
      } catch (e) {
        self._errors.push(e);
      }
      self.showTest(result.value === expected, result.value, expected, message);
      if (typeof callback === 'function') {
        callback(result);
      }
    });
  });
  client.addCommand('waitForVar',
                    function(varname, expected, myTimeout, equality, callback) {
                      var self = this;
                      var startTime = new Date().getTime();
                      function checkValue(val) {
                        return equality ? val === expected : val !== expected;
                      }
                      function checkVariable() {
                        var now = new Date().getTime();
                        var code = 'var myResult = ' +
                           varname + '; return myResult;';
                        self.direct.execute(code, function(result) {
                          if (result.status === 0 && checkValue(result.value)) {
                            if (typeof callback === 'function') {
                              callback(result.value);
                            }
                          } else {
                            if (now - startTime < myTimeout) {
                              setTimeout(checkVariable, 500);
                            } else if (typeof callback === 'function') {
                              callback(result);
                            }
                          }
                        });
                      }
                      checkVariable();
                    }
                   );
  client.addCommand('waitForTextIn',
                    function(cssSelector, myTimeout, callback) {
                      var self = this;
                      var startTime = new Date().getTime();
                      function checkForText() {
                        var now = new Date().getTime();
                        self.direct.element('css selector', cssSelector,
                            function(result) {
                              if (result.status === 0) {
                                self.direct.elementIdText(result.value.ELEMENT,
                                    function(result2) {
                                      if (result2.status === 0 &&
                                          result2.value !== '') {
                                        if (typeof callback === 'function') {
                                          callback(result2.value);
                                        }
                                      } else {
                                        if (now - startTime < myTimeout) {
                                          setTimeout(checkForText, 500);
                                        } else {
                                          if (typeof callback === 'function') {
                                            callback(result2);
                                          }
                                        }
                                      }
                                    });
                              } else {
                                if (now - startTime < myTimeout) {
                                  setTimeout(checkForText, 500);
                                } else {
                                  if (typeof callback === 'function') {
                                    callback(result);
                                  }
                                }
                              }
                            });
                      }
                      checkForText();
                    }
                   );
  client.addCommand('waitForValueIn',
                    function(cssSelector, myTimeout, callback) {
                      var self = this;
                      var startTime = new Date().getTime();
                      function checkForText() {
                        var now = new Date().getTime();
                        self.direct.element('css selector', cssSelector,
                            function(result) {
                              if (result.status === 0) {
                                self.direct.elementIdValue(result.value.ELEMENT,
                                    function(result2) {
                                      if (result2.status === 0 &&
                                          result2.value !== '') {
                                        if (typeof callback === 'function') {
                                          callback(result2.value);
                                        }
                                      } else {
                                        if (now - startTime < myTimeout) {
                                          setTimeout(checkForText, 500);
                                        } else {
                                          if (typeof callback === 'function') {
                                            callback(result2);
                                          }
                                        }
                                      }
                                    });
                              } else {
                                if (now - startTime < myTimeout) {
                                  setTimeout(checkForText, 500);
                                } else {
                                  if (typeof callback === 'function') {
                                    callback(result);
                                  }
                                }
                              }
                            });
                      }
                      checkForText();
                    }
                   );
  client.addCommand('getVar',
                    function(varname, callback) {
                      var self = this;
                      var code = 'var myResult = ' +
                         varname + '; return myResult;';
                      self.direct.execute(code, function(result) {
                        if (result.status === 0) {
                          if (typeof callback === 'function') {
                            callback(result.value);
                          }
                        } else if (typeof callback === 'function') {
                          callback(result);
                        }
                      });
                    }
                   );
  client.addCommand('setValues',
                    function(valHash, callback) {
                      var keys = Object.keys(valHash);
                      var self = this;
                      var results = {};
                      var addResult = function(result) {
                           if (result && result.status === 0) {
                             results[keys[i]] = result.value;
                           } else {
                             results[keys[i]] = result;
                           }
                         };

                      for (var i = 0; i < keys.length; ++i) {
                        self.setValue(keys[i],
                                      valHash[keys[i]],
                                      addResult);
                      }
                      callback(results);
                    }
                   );

  return client;
};
<|endoftext|>


<commit_before>// ==========================================================================
//                      DG.MultipleLSRLsAdornmentl
//
//  Author:   William Finzer
//
//  Copyright (c) 2017 by The Concord Consortium, Inc. All rights reserved.
//
//  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.
// ==========================================================================

sc_require('components/graph/adornments/plot_adornment');

/** @class  Holds onto an array of LSRLAdornment.

 @extends DG.PlotAdornment
 */
DG.MultipleLSRLsAdornment = DG.PlotAdornment.extend(
    /** @scope DG.MultipleLSRLsAdornmentl.prototype */
    {
      /**
       My array of adornments
       @property { [{DG.LSRLAdornment}] }
       */
      lsrlAdornments: null,

      init: function () {
        sc_super();
        this.set('lsrlAdornments', []);
        this.updateToModel();
      },

      destroy: function () {
        this.lsrlAdornments.forEach(function (iAdorn) {
          iAdorn.destroy();
        });
        sc_super();
      },

      /**
       Concatenated array of ['PropertyName','ObserverMethod'] pairs used for indicating
       which observers to add/remove from the model.

       @property   {Array of [{String},{String}]}  Elements are ['PropertyName','ObserverMethod']
       */
      modelPropertiesToObserve: [['lsrls', 'updateToModel'],
        ['isInterceptLocked', 'updateToModel'], ['showSumSquares', 'updateToModel']],

      /**
       Pass this down to my lsrlAdornments.
       And then deal with showing counts and percents
       */
      updateToModel: function () {
        this.get('model').recomputeSlopeAndInterceptIfNeeded();
        var tAdornments = this.get('lsrlAdornments');

        var adjustNumberOfAdornments = function () {
              var tLSRLs = this.getPath('model.lsrls');
              tAdornments.forEach( function( iAdornment, iIndex) {
                if( iIndex < tLSRLs.length) {
                  iAdornment.set('model', tLSRLs[iIndex]);
                }
              })
              while (tLSRLs.length > tAdornments.length) {
                var tNewAdorn = DG.LSRLAdornment.create({
                  parentView: this.get('parentView'),
                  model: tLSRLs[ tAdornments.length], paperSource: this.get('paperSource'),
                  layerName: DG.LayerNames.kAdornments });
                tNewAdorn.createElements();
                tAdornments.push(tNewAdorn);
              }
              while (tLSRLs.length < tAdornments.length) {
                var tIndex = tAdornments.findIndex(function (iAdorn) {
                  return SC.none(iAdorn.get('model'));
                });
                if (tIndex >= 0) {
                  var tAdorn = tAdornments[tIndex];
                  tAdornments.splice(tIndex, 1);
                  tAdorn.destroy();
                }
              }
            }.bind(this);

        // begin updateToModel
        adjustNumberOfAdornments();
        tAdornments.forEach(function (iAdornment) {
          iAdornment.updateToModel();
        });
      }

    });

<commit_msg>Lint kvetch<commit_after>// ==========================================================================
//                      DG.MultipleLSRLsAdornmentl
//
//  Author:   William Finzer
//
//  Copyright (c) 2017 by The Concord Consortium, Inc. All rights reserved.
//
//  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.
// ==========================================================================

sc_require('components/graph/adornments/plot_adornment');

/** @class  Holds onto an array of LSRLAdornment.

 @extends DG.PlotAdornment
 */
DG.MultipleLSRLsAdornment = DG.PlotAdornment.extend(
    /** @scope DG.MultipleLSRLsAdornmentl.prototype */
    {
      /**
       My array of adornments
       @property { [{DG.LSRLAdornment}] }
       */
      lsrlAdornments: null,

      init: function () {
        sc_super();
        this.set('lsrlAdornments', []);
        this.updateToModel();
      },

      destroy: function () {
        this.lsrlAdornments.forEach(function (iAdorn) {
          iAdorn.destroy();
        });
        sc_super();
      },

      /**
       Concatenated array of ['PropertyName','ObserverMethod'] pairs used for indicating
       which observers to add/remove from the model.

       @property   {Array of [{String},{String}]}  Elements are ['PropertyName','ObserverMethod']
       */
      modelPropertiesToObserve: [['lsrls', 'updateToModel'],
        ['isInterceptLocked', 'updateToModel'], ['showSumSquares', 'updateToModel']],

      /**
       Pass this down to my lsrlAdornments.
       And then deal with showing counts and percents
       */
      updateToModel: function () {
        this.get('model').recomputeSlopeAndInterceptIfNeeded();
        var tAdornments = this.get('lsrlAdornments');

        var adjustNumberOfAdornments = function () {
              var tLSRLs = this.getPath('model.lsrls');
              tAdornments.forEach( function( iAdornment, iIndex) {
                if( iIndex < tLSRLs.length) {
                  iAdornment.set('model', tLSRLs[iIndex]);
                }
              });
              while (tLSRLs.length > tAdornments.length) {
                var tNewAdorn = DG.LSRLAdornment.create({
                  parentView: this.get('parentView'),
                  model: tLSRLs[ tAdornments.length], paperSource: this.get('paperSource'),
                  layerName: DG.LayerNames.kAdornments });
                tNewAdorn.createElements();
                tAdornments.push(tNewAdorn);
              }
              while (tLSRLs.length < tAdornments.length) {
                var tIndex = tAdornments.findIndex(function (iAdorn) {
                  return SC.none(iAdorn.get('model'));
                });
                if (tIndex >= 0) {
                  var tAdorn = tAdornments[tIndex];
                  tAdornments.splice(tIndex, 1);
                  tAdorn.destroy();
                }
              }
            }.bind(this);

        // begin updateToModel
        adjustNumberOfAdornments();
        tAdornments.forEach(function (iAdornment) {
          iAdornment.updateToModel();
        });
      }

    });

<|endoftext|>


<commit_before>var app = app || {};
app = {
	i: 0,
	xRotation: 0.0,
	yRotation: 0.0,
	zTranslation:0.0,
}

/**
* Initialize the scene
*/
app.initializeScene = function() {
  	console.log("hellllooooooo! ")
  	// reset view
  	app.xRotation=0.0;
  	app.yRotation=0.0;
  	app.zRotation=0.0;

	app.channelCount = app.dataset_list[app.i].channels;
	// const xrange = 512;
	// const yrange = 512;
	app.zrange = app.dataset_list[app.i].resolution[2]||1;
	app.trange = app.dataset_list[app.i].timesteps||1;
	console.log(app.trange)
	// const imageCountX = xrange*trange;
	app.imageCount = app.zrange*app.trange;

	// Texture and flag for current texture filter
	app.textureArray = {};
	app.channelLoaded = [];
	app.manager = [];

	for (ch = 0; ch < app.channelCount; ++ch) {
		app.channelLoaded[ch] = false;
		app.manager.push(new THREE.LoadingManager());
		app.manager[ch].ch = ch;
		app.manager[ch].onLoad = function() {
			app.channelLoaded[this.ch] = true;
			if (this.ch == 0) {
				app.selectTexture(0, 0);
			}
		};
	}
	// Check whether the browser supports WebGL. If so, instantiate the hardware accelerated
	// WebGL renderer. For antialiasing, we have to enable it. The canvas renderer uses
	// antialiasing by default.
	// The approach of multiple renderers is quite nice, because your scene can also be
	// viewed in browsers, which don't support WebGL. The limitations of the canvas renderer
	// in contrast to the WebGL renderer will be explained in the tutorials, when there is a
	// difference.
	webGLAvailable = false;
	if (Detector.webgl) {
		app.renderer = new THREE.WebGLRenderer({antialias:true});
		webGLAvailable = true;
	} else {
		app.renderer = new THREE.CanvasRenderer();
	}

	// Set the background color
	app.renderer.setClearColor(0xc262626);//(0xc8c8c8);

	// Get the size of the inner window (content area) to create a full size renderer
	canvasWidth = window.innerWidth;
	canvasHeight = window.innerHeight;

	// Set the renderers size to the content areas size
	app.renderer.setSize(canvasWidth, canvasHeight);

	// Get the DIV element from the HTML document by its ID and append the renderers DOM
	// object to it
	// document.getElementById("WebGLCanvas").removeChild();
	var children =  document.getElementById("WebGLCanvas").childElementCount;
	if (children == 0){
		document.getElementById("WebGLCanvas").appendChild(app.renderer.domElement);
	} else {
		console.log(11);
		while (document.getElementById("WebGLCanvas").firstChild) {
		document.getElementById("WebGLCanvas").removeChild(document.getElementById("WebGLCanvas").firstChild)
		}
		console.log(22);
		document.getElementById("WebGLCanvas").appendChild(app.renderer.domElement);
		console.log(33);
	}
  // ^^ it's this line that appends new ones below

	// Create the scene, in which all objects are stored
	app.scene = new THREE.Scene();

	app.camera = new THREE.PerspectiveCamera(45, canvasWidth / canvasHeight, 1, 100);
	app.camera.position.set(0, 0, 1.5);
	app.camera.lookAt(app.scene.position);
	app.scene.add(app.camera);

	if (app.zrange>1) {
		for (ch = 0; ch < app.channelCount; ++ch) {
			var textureLoader = new THREE.TextureLoader(app.manager[ch]);
			for (tstep = 0; tstep < app.trange; ++tstep) {
				for (zval = 0; zval < app.zrange; ++zval) {
					app.textureArray[ch * app.imageCount + tstep*app.zrange + zval] = textureLoader.load(app.dataset_list[app.i].path[ch].concat("t_", tstep+1,"_z_",zval+1,".png"));
				}
			}
		}
		// Set the controls for camera
		app.orbitControls();
	}else{
		for (ch = 0; ch < app.channelCount; ++ch) {
			var textureLoader = new THREE.TextureLoader(app.manager[ch]);
			for (tstep = 0; tstep < app.trange; ++tstep) {
					app.textureArray[ch * app.imageCount + tstep] = textureLoader.load(app.dataset_list[app.i].path[ch].concat(tstep+1,".png"));
					console.log(app.dataset_list[app.i].path[ch].concat(tstep+1,".png"))
			}
		}
	}

	app.group = [];

	if (app.zrange>1) {
		for (ch = 0; ch < app.channelCount; ++ch) {
			for (tstep = 0; tstep < app.trange; ++tstep) {

				app.group[ch * app.imageCount +tstep] = new THREE.Object3D();
				 for (var zval = 0; zval<app.zrange; zval++) {
				 	mesh = new THREE.Mesh(new THREE.PlaneGeometry(1, app.dataset_list[app.i].resolution[1]/app.dataset_list[app.i].resolution[0]), new THREE.MeshBasicMaterial({map:app.textureArray[ch * app.imageCount + tstep*app.zrange + zval],
				 		side:THREE.DoubleSide, opacity:0.25, transparent:true, depthWrite:false, blending:THREE.AdditiveBlending}));
				 	mesh.position.z = 0.05*(1-2*zval/app.zrange);
				 	app.group[ch * app.imageCount +tstep].add(mesh);
				 	app.group[ch * app.imageCount +tstep].name = tstep;

				 }
			}
		}
	}else{
		for (ch = 0; ch < app.channelCount; ++ch) {
			for (tstep = 0; tstep < app.trange; ++tstep) {
				app.group[ch * app.imageCount +tstep] = new THREE.Object3D();
				mesh = new THREE.Mesh(new THREE.PlaneGeometry(1,app.dataset_list[app.i].resolution[1]/app.dataset_list[app.i].resolution[0]), new THREE.MeshBasicMaterial({map:app.textureArray[ch * app.imageCount + tstep],
					side:THREE.DoubleSide, transparent:true, depthWrite:false, blending:THREE.AdditiveBlending}));
				app.group[ch * app.imageCount +tstep].add(mesh);
				app.group[ch * app.imageCount +tstep].name = tstep;
			}
		}
		console.log("2D")

	}
	app.tcurrent = 0;
	app.chcurrent = 0;
	app.scene.add(app.group[app.chcurrent * app.imageCount +app.tcurrent]);

// Add a listener for 'keydown' events. By this listener, all key events will be
// passed to the function 'onDocumentKeyDown'. There's another event type 'keypress'.
// It will report only the visible characters like 'a', but not the function keys
// like 'cursor up'.
document.addEventListener("keydown", app.onDocumentKeyDown, false);

document.addEventListener("input", app.onSlide, false);

document.addEventListener('dblclick', app.onDblClick, false);

}

/**
* Select current texture to display in loaded texture arrays
*/
app.selectTexture = function( channel, tstep) {
	if ((app.tcurrent !== tstep)||(app.chcurrent !== channel)) {
		app.scene.remove(app.scene.getObjectByName(app.group[app.chcurrent * app.imageCount + app.tcurrent].name));
		app.scene.add(app.group[channel * app.imageCount +tstep]);
		app.tcurrent = tstep;
		app.chcurrent = channel;
	}
}

window.onkeydown = function(e) {
  return !(e.keyCode == 32);
}

/**
* This function is called, when a key is pushed down.
*/
app.onDocumentKeyDown = function(event) {
	this.currentTStep = this.currentTStep || 0;
	this.currentChannel = this.currentChannel || 0;

  // Get the key code of the pressed key
  var keyCode = event.which;
  if (keyCode == enums.keyboard.KEY_C) {	// SWITCH CHANNEL
	  if (this.currentChannel < app.channelCount - 1 && app.channelLoaded[this.currentChannel+1]) {
		  ++this.currentChannel;
	  } else {
		  this.currentChannel = 0;
	  }

	} else if(keyCode == enums.keyboard.KEY_W) {	// ROTATE UP
	  app.xRotation -= 0.1;
	} else if(keyCode == enums.keyboard.KEY_S) {	// ROTATE DOWN
	  app.xRotation += 0.1;
	} else if(keyCode == enums.keyboard.KEY_A) {	// ROTATE LEFT
	  app.yRotation -= 0.1;
	} else if(keyCode == enums.keyboard.KEY_D) {	// ROTATE RIGHT
	  app.yRotation += 0.1;
	} else if(keyCode == enums.keyboard.LEFT_ARROW) {	// NEXT IMAGE
		if (this.currentTStep > 0) {
			--this.currentTStep;
		} else {
			this.currentTStep = app.trange - 1;
		}

	} else if(keyCode == enums.keyboard.RIGHT_ARROW) {	// PREVIOUS IMAGE
		if (this.currentTStep < app.trange - 1) {
			++this.currentTStep;
		} else {
			this.currentTStep = 0;
		}
	  // Page up
	} else if(keyCode == enums.keyboard.UP_ARROW) {	// ZOOM IN
		app.zTranslation += 0.2;
	  // Page down
	} else if(keyCode == enums.keyboard.DOWN_ARROW) {	// ZOOM OUT
		app.zTranslation -= 0.2;
	}
		  // Page up
	} else if(keyCode == enums.keyboard.KEY_R) {	// ZOOM IN
		app.zTranslation += 0.2;
	  // Page down
	} else if(keyCode == enums.keyboard.KEY_F) {	// ZOOM OUT
		app.zTranslation -= 0.2;
	}
	else if(keyCode == enums.keyboard.KEY_R) {	// RESET VIEW
	  app.xRotation = 0.0;
	  app.yRotation = 0.0;
	  app.zTranslation = 0;
	  // planeHoriz.position.x = 0;
	  // planeHoriz.position.y = 0;
	  // planeHoriz.position.z = 0;
	  // planeVert.position.x = 0;
	  // planeVert.position.y = 0;
	  // planeVert.position.z = 0;
  }
  app.selectTexture(this.currentChannel, this.currentTStep);
}

app.onSlide = function(event){
	this.currentTStep = this.currentTStep || 0;
	this.currentChannel = this.currentChannel || 0;
	this.currentTStep = parseInt(document.getElementById("myRange").value);
	app.selectTexture(this.currentChannel, this.currentTStep);
}

app.onDblClick = function(event) {
	this.currentTStep = this.currentTStep || 0;
	this.currentChannel = this.currentChannel || 0;
	if (this.currentChannel < channelCount - 1 && channelLoaded[this.currentChannel+1]) {
		++this.currentChannel;
	} else {
		this.currentChannel = 0;
	}
	app.selectTexture(this.currentChannel, this.currentTStep);
}

app.orbitControls = function(event) {
  // add the controls
  app.controls = new THREE.OrbitControls( app.camera, app.renderer.domElement );
  console.log("setting orbit controls")
}

/**
* Animate the scene and call rendering.
*/
app.animateScene = function() {
//directionalLight.position = camera.position;
if (app.channelLoaded[0]) {
	// Map the 3D scene down to the 2D screen (render the frame)
	app.group[app.chcurrent * app.imageCount + app.tcurrent].rotation.set(app.xRotation, 0.0, app.yRotation, 'XYZ' );
	app.group[app.chcurrent * app.imageCount + app.tcurrent].position.z = app.zTranslation;
	app.renderScene();
}
// else{

// 	document.getElementById("WebGLCanvas").innerHTML = '
\
//
\
//
loading...
\
//
\
//
'
//   }

// Define the function, which is called by the browser supported timer loop. If the
// browser tab is not visible, the animation is paused. So 'animateScene()' is called
// in a browser controlled loop.
requestAnimationFrame(app.animateScene);
if (app.controls != null && typeof app.controls != 'undefined') {
	app.controls.update();
}
}

/**
* Render the scene. Map the 3D world to the 2D screen.
*/
app.renderScene = function() {
	app.renderer.render(app.scene, app.camera);
}
<commit_msg>added keys R and F for zoom in and out to avoid conflict zoom in and out<commit_after>var app = app || {};
app = {
	i: 0,
	xRotation: 0.0,
	yRotation: 0.0,
	zTranslation:0.0,
}

/**
* Initialize the scene
*/
app.initializeScene = function() {
  	console.log("hellllooooooo! ")
  	// reset view
  	app.xRotation=0.0;
  	app.yRotation=0.0;
  	app.zRotation=0.0;

	app.channelCount = app.dataset_list[app.i].channels;
	// const xrange = 512;
	// const yrange = 512;
	app.zrange = app.dataset_list[app.i].resolution[2]||1;
	app.trange = app.dataset_list[app.i].timesteps||1;
	console.log(app.trange)
	// const imageCountX = xrange*trange;
	app.imageCount = app.zrange*app.trange;

	// Texture and flag for current texture filter
	app.textureArray = {};
	app.channelLoaded = [];
	app.manager = [];

	for (ch = 0; ch < app.channelCount; ++ch) {
		app.channelLoaded[ch] = false;
		app.manager.push(new THREE.LoadingManager());
		app.manager[ch].ch = ch;
		app.manager[ch].onLoad = function() {
			app.channelLoaded[this.ch] = true;
			if (this.ch == 0) {
				app.selectTexture(0, 0);
			}
		};
	}
	// Check whether the browser supports WebGL. If so, instantiate the hardware accelerated
	// WebGL renderer. For antialiasing, we have to enable it. The canvas renderer uses
	// antialiasing by default.
	// The approach of multiple renderers is quite nice, because your scene can also be
	// viewed in browsers, which don't support WebGL. The limitations of the canvas renderer
	// in contrast to the WebGL renderer will be explained in the tutorials, when there is a
	// difference.
	webGLAvailable = false;
	if (Detector.webgl) {
		app.renderer = new THREE.WebGLRenderer({antialias:true});
		webGLAvailable = true;
	} else {
		app.renderer = new THREE.CanvasRenderer();
	}

	// Set the background color
	app.renderer.setClearColor(0xc262626);//(0xc8c8c8);

	// Get the size of the inner window (content area) to create a full size renderer
	canvasWidth = window.innerWidth;
	canvasHeight = window.innerHeight;

	// Set the renderers size to the content areas size
	app.renderer.setSize(canvasWidth, canvasHeight);

	// Get the DIV element from the HTML document by its ID and append the renderers DOM
	// object to it
	// document.getElementById("WebGLCanvas").removeChild();
	var children =  document.getElementById("WebGLCanvas").childElementCount;
	if (children == 0){
		document.getElementById("WebGLCanvas").appendChild(app.renderer.domElement);
	} else {
		console.log(11);
		while (document.getElementById("WebGLCanvas").firstChild) {
		document.getElementById("WebGLCanvas").removeChild(document.getElementById("WebGLCanvas").firstChild)
		}
		console.log(22);
		document.getElementById("WebGLCanvas").appendChild(app.renderer.domElement);
		console.log(33);
	}
  // ^^ it's this line that appends new ones below

	// Create the scene, in which all objects are stored
	app.scene = new THREE.Scene();

	app.camera = new THREE.PerspectiveCamera(45, canvasWidth / canvasHeight, 1, 100);
	app.camera.position.set(0, 0, 1.5);
	app.camera.lookAt(app.scene.position);
	app.scene.add(app.camera);

	if (app.zrange>1) {
		for (ch = 0; ch < app.channelCount; ++ch) {
			var textureLoader = new THREE.TextureLoader(app.manager[ch]);
			for (tstep = 0; tstep < app.trange; ++tstep) {
				for (zval = 0; zval < app.zrange; ++zval) {
					app.textureArray[ch * app.imageCount + tstep*app.zrange + zval] = textureLoader.load(app.dataset_list[app.i].path[ch].concat("t_", tstep+1,"_z_",zval+1,".png"));
				}
			}
		}
		// Set the controls for camera
		app.orbitControls();
	}else{
		for (ch = 0; ch < app.channelCount; ++ch) {
			var textureLoader = new THREE.TextureLoader(app.manager[ch]);
			for (tstep = 0; tstep < app.trange; ++tstep) {
					app.textureArray[ch * app.imageCount + tstep] = textureLoader.load(app.dataset_list[app.i].path[ch].concat(tstep+1,".png"));
					console.log(app.dataset_list[app.i].path[ch].concat(tstep+1,".png"))
			}
		}
	}

	app.group = [];

	if (app.zrange>1) {
		for (ch = 0; ch < app.channelCount; ++ch) {
			for (tstep = 0; tstep < app.trange; ++tstep) {

				app.group[ch * app.imageCount +tstep] = new THREE.Object3D();
				 for (var zval = 0; zval<app.zrange; zval++) {
				 	mesh = new THREE.Mesh(new THREE.PlaneGeometry(1, app.dataset_list[app.i].resolution[1]/app.dataset_list[app.i].resolution[0]), new THREE.MeshBasicMaterial({map:app.textureArray[ch * app.imageCount + tstep*app.zrange + zval],
				 		side:THREE.DoubleSide, opacity:0.25, transparent:true, depthWrite:false, blending:THREE.AdditiveBlending}));
				 	mesh.position.z = 0.05*(1-2*zval/app.zrange);
				 	app.group[ch * app.imageCount +tstep].add(mesh);
				 	app.group[ch * app.imageCount +tstep].name = tstep;

				 }
			}
		}
	}else{
		for (ch = 0; ch < app.channelCount; ++ch) {
			for (tstep = 0; tstep < app.trange; ++tstep) {
				app.group[ch * app.imageCount +tstep] = new THREE.Object3D();
				mesh = new THREE.Mesh(new THREE.PlaneGeometry(1,app.dataset_list[app.i].resolution[1]/app.dataset_list[app.i].resolution[0]), new THREE.MeshBasicMaterial({map:app.textureArray[ch * app.imageCount + tstep],
					side:THREE.DoubleSide, transparent:true, depthWrite:false, blending:THREE.AdditiveBlending}));
				app.group[ch * app.imageCount +tstep].add(mesh);
				app.group[ch * app.imageCount +tstep].name = tstep;
			}
		}
		console.log("2D")

	}
	app.tcurrent = 0;
	app.chcurrent = 0;
	app.scene.add(app.group[app.chcurrent * app.imageCount +app.tcurrent]);

// Add a listener for 'keydown' events. By this listener, all key events will be
// passed to the function 'onDocumentKeyDown'. There's another event type 'keypress'.
// It will report only the visible characters like 'a', but not the function keys
// like 'cursor up'.
document.addEventListener("keydown", app.onDocumentKeyDown, false);

document.addEventListener("input", app.onSlide, false);

document.addEventListener('dblclick', app.onDblClick, false);

}

/**
* Select current texture to display in loaded texture arrays
*/
app.selectTexture = function( channel, tstep) {
	if ((app.tcurrent !== tstep)||(app.chcurrent !== channel)) {
		app.scene.remove(app.scene.getObjectByName(app.group[app.chcurrent * app.imageCount + app.tcurrent].name));
		app.scene.add(app.group[channel * app.imageCount +tstep]);
		app.tcurrent = tstep;
		app.chcurrent = channel;
	}
}

window.onkeydown = function(e) {
  return !(e.keyCode == 32);
}

/**
* This function is called, when a key is pushed down.
*/
app.onDocumentKeyDown = function(event) {
	this.currentTStep = this.currentTStep || 0;
	this.currentChannel = this.currentChannel || 0;

  // Get the key code of the pressed key
  var keyCode = event.which;
  if (keyCode == enums.keyboard.KEY_C) {	// SWITCH CHANNEL
	  if (this.currentChannel < app.channelCount - 1 && app.channelLoaded[this.currentChannel+1]) {
		  ++this.currentChannel;
	  } else {
		  this.currentChannel = 0;
	  }

	} else if(keyCode == enums.keyboard.KEY_W) {	// ROTATE UP
	  app.xRotation -= 0.1;
	} else if(keyCode == enums.keyboard.KEY_S) {	// ROTATE DOWN
	  app.xRotation += 0.1;
	} else if(keyCode == enums.keyboard.KEY_A) {	// ROTATE LEFT
	  app.yRotation -= 0.1;
	} else if(keyCode == enums.keyboard.KEY_D) {	// ROTATE RIGHT
	  app.yRotation += 0.1;
	} else if(keyCode == enums.keyboard.LEFT_ARROW) {	// NEXT IMAGE
		if (this.currentTStep > 0) {
			--this.currentTStep;
		} else {
			this.currentTStep = app.trange - 1;
		}

	} else if(keyCode == enums.keyboard.RIGHT_ARROW) {	// PREVIOUS IMAGE
		if (this.currentTStep < app.trange - 1) {
			++this.currentTStep;
		} else {
			this.currentTStep = 0;
		}
	  // Page up
	} else if(keyCode == enums.keyboard.UP_ARROW) {	// ZOOM IN
		app.zTranslation += 0.2;
	  // Page down
	} else if(keyCode == enums.keyboard.DOWN_ARROW) {	// ZOOM OUT
		app.zTranslation -= 0.2;
		  // Page up
	} else if(keyCode == enums.keyboard.KEY_R) {	// ZOOM IN
		app.zTranslation += 0.2;
	  // Page down
	} else if(keyCode == enums.keyboard.KEY_F) {	// ZOOM OUT
		app.zTranslation -= 0.2;
	}
	else if(keyCode == enums.keyboard.KEY_R) {	// RESET VIEW
	  app.xRotation = 0.0;
	  app.yRotation = 0.0;
	  app.zTranslation = 0;
	  // planeHoriz.position.x = 0;
	  // planeHoriz.position.y = 0;
	  // planeHoriz.position.z = 0;
	  // planeVert.position.x = 0;
	  // planeVert.position.y = 0;
	  // planeVert.position.z = 0;
  }
  app.selectTexture(this.currentChannel, this.currentTStep);
}

app.onSlide = function(event){
	this.currentTStep = this.currentTStep || 0;
	this.currentChannel = this.currentChannel || 0;
	this.currentTStep = parseInt(document.getElementById("myRange").value);
	app.selectTexture(this.currentChannel, this.currentTStep);
}

app.onDblClick = function(event) {
	this.currentTStep = this.currentTStep || 0;
	this.currentChannel = this.currentChannel || 0;
	if (this.currentChannel < channelCount - 1 && channelLoaded[this.currentChannel+1]) {
		++this.currentChannel;
	} else {
		this.currentChannel = 0;
	}
	app.selectTexture(this.currentChannel, this.currentTStep);
}

app.orbitControls = function(event) {
  // add the controls
  app.controls = new THREE.OrbitControls( app.camera, app.renderer.domElement );
  console.log("setting orbit controls")
}

/**
* Animate the scene and call rendering.
*/
app.animateScene = function() {
//directionalLight.position = camera.position;
if (app.channelLoaded[0]) {
	// Map the 3D scene down to the 2D screen (render the frame)
	app.group[app.chcurrent * app.imageCount + app.tcurrent].rotation.set(app.xRotation, 0.0, app.yRotation, 'XYZ' );
	app.group[app.chcurrent * app.imageCount + app.tcurrent].position.z = app.zTranslation;
	app.renderScene();
}
// else{

// 	document.getElementById("WebGLCanvas").innerHTML = '
\
//
\
//
loading...
\
//
\
//
'
//   }

// Define the function, which is called by the browser supported timer loop. If the
// browser tab is not visible, the animation is paused. So 'animateScene()' is called
// in a browser controlled loop.
requestAnimationFrame(app.animateScene);
if (app.controls != null && typeof app.controls != 'undefined') {
	app.controls.update();
}
}

/**
* Render the scene. Map the 3D world to the 2D screen.
*/
app.renderScene = function() {
	app.renderer.render(app.scene, app.camera);
}
<|endoftext|>