<commit_before>Kwf.Form.ComboBox = Ext.extend(Ext.form.ComboBox,
{
    displayField: 'name',
    valueField: 'id',

    initComponent : function()
    {
        this.addEvents({
            changevalue : true
        });
        if(!this.store) {
            throw "no store set";
        }
        if (!(this.store instanceof Ext.data.Store)) {
            //store klonen (um nicht this.initalConfig.store zu ändern)
            var store = {};
            for (var i in this.store) {
                store[i] = this.store[i];
            }
            delete this.store;
            if (store.data) {
                store = Ext.applyIf(store, {
                    fields: ['id', 'name'],
                    id: 'id'
                });
                this.store = new Ext.data.SimpleStore(store);
                this.displayField = store.fields[1];
                this.mode = 'local';
            } else {
                if (store.reader) {
                    if (store.reader.type && Ext.data[store.reader.type]) {
                        var readerType = Ext.data[store.reader.type];
                        delete store.reader.type;
                    } else if (store.reader.type) {
                        try {
                            var readerType = eval(store.reader.type);
                        } catch(e) {
                            throw "invalid readerType: "+store.reader.type;
                        }
                        delete store.reader.type;
                    } else {
                        var readerType = Ext.data.JsonReader;
                    }
                    if (!store.reader.rows) throw "no rows defined, required if reader doesn't this through meta data";
                    var rows = store.reader.rows;
                    delete store.reader.rows;
                    var reader = new readerType(store.reader, rows);
                } else {
                    var reader = new Ext.data.JsonReader(); //reader thisuriert sich autom. durch meta-daten
                }
                if (store.proxy) {
                    if (store.proxy.type && Ext.data[store.proxy.type]) {
                        var proxyType = Ext.data[store.proxy.type];
                        delete store.proxy.type;
                    } else if (store.proxy.type) {
                        try {
                            var proxyType = eval(store.proxy.type);
                        } catch(e) {
                            throw "invalid proxyType: "+store.proxy.type;
                        }
                        delete store.proxy.type;
                    } else {
                        var proxyType = Ext.data.HttpProxy;
                    }
                    var proxy = new proxyType(store.proxy);
                } else if (store.data) {
                    var proxy = new Ext.data.MemoryProxy(store.data);
                } else {
                    var proxy = new Ext.data.HttpProxy(store);
                }
                var storeConfig = {
                    proxy: proxy,
                    reader: reader
                };
                Ext.apply(storeConfig, this.storeConfig);
                if (store.type && Ext.data[store.type]) {
                    this.store = new Ext.data[store.type](storeConfig);
                } else if (store.type) {
                    try {
                        var storeType = eval(store.type);
                    } catch(e) {
                        throw "invalid storeType: "+store.type;
                    }
                    this.store = new storeType(storeConfig);
                } else {
                    this.store = new Ext.data.Store(storeConfig);
                }
            }
        }
        if (this.baseParams) {
            this.store.baseParams = this.baseParams;
        }

        if (this.addDialog) {
            var d = Kwf.Auto.Form.Window;
            if (this.addDialog.type) {
                try {
                    d = eval(this.addDialog.type);
                } catch (e) {
                    throw new Error("Invalid addDialog \'"+this.addDialog.type+"': "+e);
                }
            }
            this.addDialog = new d(this.addDialog);
            this.addDialog.on('datachange', function(result) {
                if (result.data.addedId) {
                    //neuen Eintrag auswählen
                    this.setValue(result.data.addedId);
                }
            }, this);
        }

        if (this.showNoSelection) {
            if (!this.emptyText) {
                this.emptyText = '('+trlKwf('no selection')+')';
            }
        }
        this.store.on('load', function() {
            this.addNoSelection();
        }, this);
        if (this.store.recordType) {
            this.addNoSelection();
        }

        Kwf.Form.ComboBox.superclass.initComponent.call(this);
    },

    initList : function(){
        if (!this.listWidth) {
            //fixt bug wenn combobox in einem tab ist
            //ext verwendet this.wrap.getWidth() was ja eingentlich korrekt ist
            //das funktioniert aber im FF da nicht
            this.listWidth = this.el.getWidth()+this.trigger.getWidth();
        }
        Kwf.Form.ComboBox.superclass.initList.call(this);
    },

    addNoSelection : function() {
        if (this.showNoSelection && this.store.find('id', '') == -1) {
            var data = {};
            data[this.displayField] = this.emptyText;
            data[this.valueField] = null;
            for (var i = 0; i < this.store.fields.keys.length; i++) {
                if (this.store.fields.keys[i] != this.displayField
                    && this.store.fields.keys[i] != this.valueField
                ) {
                    data[this.store.fields.keys[i]] = null;
                }
            }
            this.store.insert(0, new this.store.recordType(data));
        }
    },

    setValue : function(v)
    {
        if (v === '') v = null;
        if (v == this.emptyText) v = null;
        if (v && this.store.proxy && this.valueField && this.mode == 'remote') {
            //wenn proxy vorhanden können daten nachgeladen werden
            //also loading anzeigen (siehe setValue)
            this.valueNotFoundText = this.loadingText;
        } else {
            this.valueNotFoundText = '';
        }
        Kwf.Form.ComboBox.superclass.setValue.apply(this, arguments);
        if (v && this.valueField
                && !this.findRecord(this.valueField, v) //record nicht gefunden
                && this.mode == 'remote'
                && this.store.proxy //proxy vorhanden (dh. daten können nachgeladen werden)
                ) {
            this.store.baseParams[this.queryParam] = this.valueField+':'+v;
            this.store.load({
                params: this.getParams(v),
                callback: function(r, options, success) {
                    if (success && this.findRecord(this.valueField, this.value)) {
                        this.setValue(this.value);
                    }
                },
                scope: this
            });
        }
        this.fireEvent('changevalue', this.value, this);
    },

    onRender : function(ct, position)
    {
        Kwf.Form.ComboBox.superclass.onRender.call(this, ct, position);
        if (this.addDialog) {
            var c = this.el.up('div.x-form-field-wrap').insertSibling({style: 'float: right'}, 'before');
            var button = new Ext.Button({
                renderTo: c,
                text: this.addDialog.text || trlKwf('add new entry'),
                handler: function() {
                    this.addDialog.showAdd();
                },
                scope: this
            });
        }
    },
    setFormBaseParams: function(params) {
        Ext.apply(this.store.baseParams, params);
    },

    /*
    Workaround für folgendes Problem:
    - ComboBox onBeforeLoad ersetzt den DataView html code durch einen eigenen Loading
    - this.view.all (da werden die gerenderten dom knoten gemerkt) wird aber nicht geleert
    - dadurch sind da elemente drinnen die in der luft hängen
    - wenn nun im onLoad this.select() aufgerufen wird, wird ein scrollChildIntoView für das Element
      das in der luft hängt aufgerufen
    - und das gibt einen JS-Error im IE
     */
    onBeforeLoad: function()
    {
        Kwf.Form.ComboBox.superclass.onBeforeLoad.call(this);
        if(!this.hasFocus){
            return;
        }
        this.view.all.clear();
    }

});
Ext.reg('combobox', Kwf.Form.ComboBox);
<commit_msg>set remoteSort for store when using httpProxy<commit_after>Kwf.Form.ComboBox = Ext.extend(Ext.form.ComboBox,
{
    displayField: 'name',
    valueField: 'id',

    initComponent : function()
    {
        this.addEvents({
            changevalue : true
        });
        if(!this.store) {
            throw "no store set";
        }
        if (!(this.store instanceof Ext.data.Store)) {
            //store klonen (um nicht this.initalConfig.store zu ändern)
            var store = {};
            for (var i in this.store) {
                store[i] = this.store[i];
            }
            delete this.store;
            if (store.data) {
                store = Ext.applyIf(store, {
                    fields: ['id', 'name'],
                    id: 'id'
                });
                this.store = new Ext.data.SimpleStore(store);
                this.displayField = store.fields[1];
                this.mode = 'local';
            } else {
                if (store.reader) {
                    if (store.reader.type && Ext.data[store.reader.type]) {
                        var readerType = Ext.data[store.reader.type];
                        delete store.reader.type;
                    } else if (store.reader.type) {
                        try {
                            var readerType = eval(store.reader.type);
                        } catch(e) {
                            throw "invalid readerType: "+store.reader.type;
                        }
                        delete store.reader.type;
                    } else {
                        var readerType = Ext.data.JsonReader;
                    }
                    if (!store.reader.rows) throw "no rows defined, required if reader doesn't this through meta data";
                    var rows = store.reader.rows;
                    delete store.reader.rows;
                    var reader = new readerType(store.reader, rows);
                } else {
                    var reader = new Ext.data.JsonReader(); //reader thisuriert sich autom. durch meta-daten
                }
                if (store.proxy) {
                    if (store.proxy.type && Ext.data[store.proxy.type]) {
                        var proxyType = Ext.data[store.proxy.type];
                        delete store.proxy.type;
                    } else if (store.proxy.type) {
                        try {
                            var proxyType = eval(store.proxy.type);
                        } catch(e) {
                            throw "invalid proxyType: "+store.proxy.type;
                        }
                        delete store.proxy.type;
                    } else {
                        var proxyType = Ext.data.HttpProxy;
                    }
                    var proxy = new proxyType(store.proxy);
                } else if (store.data) {
                    var proxy = new Ext.data.MemoryProxy(store.data);
                } else {
                    var proxy = new Ext.data.HttpProxy(store);
                }
                var storeConfig = {
                    proxy: proxy,
                    reader: reader
                };
                Ext.apply(storeConfig, this.storeConfig);
                if (typeof storeConfig.remoteSort == 'undefined') {
                    storeConfig.remoteSort = proxy instanceof Ext.data.HttpProxy;
                }
                if (store.type && Ext.data[store.type]) {
                    this.store = new Ext.data[store.type](storeConfig);
                } else if (store.type) {
                    try {
                        var storeType = eval(store.type);
                    } catch(e) {
                        throw "invalid storeType: "+store.type;
                    }
                    this.store = new storeType(storeConfig);
                } else {
                    this.store = new Ext.data.Store(storeConfig);
                }
            }
        }
        if (this.baseParams) {
            this.store.baseParams = this.baseParams;
        }

        if (this.addDialog) {
            var d = Kwf.Auto.Form.Window;
            if (this.addDialog.type) {
                try {
                    d = eval(this.addDialog.type);
                } catch (e) {
                    throw new Error("Invalid addDialog \'"+this.addDialog.type+"': "+e);
                }
            }
            this.addDialog = new d(this.addDialog);
            this.addDialog.on('datachange', function(result) {
                if (result.data.addedId) {
                    //neuen Eintrag auswählen
                    this.setValue(result.data.addedId);
                }
            }, this);
        }

        if (this.showNoSelection) {
            if (!this.emptyText) {
                this.emptyText = '('+trlKwf('no selection')+')';
            }
        }
        this.store.on('load', function() {
            this.addNoSelection();
        }, this);
        if (this.store.recordType) {
            this.addNoSelection();
        }

        Kwf.Form.ComboBox.superclass.initComponent.call(this);
    },

    initList : function(){
        if (!this.listWidth) {
            //fixt bug wenn combobox in einem tab ist
            //ext verwendet this.wrap.getWidth() was ja eingentlich korrekt ist
            //das funktioniert aber im FF da nicht
            this.listWidth = this.el.getWidth()+this.trigger.getWidth();
        }
        Kwf.Form.ComboBox.superclass.initList.call(this);
    },

    addNoSelection : function() {
        if (this.showNoSelection && this.store.find('id', '') == -1) {
            var data = {};
            data[this.displayField] = this.emptyText;
            data[this.valueField] = null;
            for (var i = 0; i < this.store.fields.keys.length; i++) {
                if (this.store.fields.keys[i] != this.displayField
                    && this.store.fields.keys[i] != this.valueField
                ) {
                    data[this.store.fields.keys[i]] = null;
                }
            }
            this.store.insert(0, new this.store.recordType(data));
        }
    },

    setValue : function(v)
    {
        if (v === '') v = null;
        if (v == this.emptyText) v = null;
        if (v && this.store.proxy && this.valueField && this.mode == 'remote') {
            //wenn proxy vorhanden können daten nachgeladen werden
            //also loading anzeigen (siehe setValue)
            this.valueNotFoundText = this.loadingText;
        } else {
            this.valueNotFoundText = '';
        }
        Kwf.Form.ComboBox.superclass.setValue.apply(this, arguments);
        if (v && this.valueField
                && !this.findRecord(this.valueField, v) //record nicht gefunden
                && this.mode == 'remote'
                && this.store.proxy //proxy vorhanden (dh. daten können nachgeladen werden)
                ) {
            this.store.baseParams[this.queryParam] = this.valueField+':'+v;
            this.store.load({
                params: this.getParams(v),
                callback: function(r, options, success) {
                    if (success && this.findRecord(this.valueField, this.value)) {
                        this.setValue(this.value);
                    }
                },
                scope: this
            });
        }
        this.fireEvent('changevalue', this.value, this);
    },

    onRender : function(ct, position)
    {
        Kwf.Form.ComboBox.superclass.onRender.call(this, ct, position);
        if (this.addDialog) {
            var c = this.el.up('div.x-form-field-wrap').insertSibling({style: 'float: right'}, 'before');
            var button = new Ext.Button({
                renderTo: c,
                text: this.addDialog.text || trlKwf('add new entry'),
                handler: function() {
                    this.addDialog.showAdd();
                },
                scope: this
            });
        }
    },
    setFormBaseParams: function(params) {
        Ext.apply(this.store.baseParams, params);
    },

    /*
    Workaround für folgendes Problem:
    - ComboBox onBeforeLoad ersetzt den DataView html code durch einen eigenen Loading
    - this.view.all (da werden die gerenderten dom knoten gemerkt) wird aber nicht geleert
    - dadurch sind da elemente drinnen die in der luft hängen
    - wenn nun im onLoad this.select() aufgerufen wird, wird ein scrollChildIntoView für das Element
      das in der luft hängt aufgerufen
    - und das gibt einen JS-Error im IE
     */
    onBeforeLoad: function()
    {
        Kwf.Form.ComboBox.superclass.onBeforeLoad.call(this);
        if(!this.hasFocus){
            return;
        }
        this.view.all.clear();
    }

});
Ext.reg('combobox', Kwf.Form.ComboBox);
<|endoftext|>


<commit_before>'use strict'

var os = require('os')
var zlib = require('zlib')
var util = require('util')
var test = require('tape')
var nock = require('nock')
var helpers = require('./_helpers')
var request = require('../lib/request')
var opbeat = require('../')

var options = {
  organizationId: 'some-org-id',
  appId: 'some-app-id',
  secretToken: 'secret',
  captureExceptions: false
}

var optionFixtures = [
  ['appId', 'APP_ID'],
  ['organizationId', 'ORGANIZATION_ID'],
  ['secretToken', 'SECRET_TOKEN'],
  ['clientLogLevel', 'CLIENT_LOG_LEVEL', 'info'],
  ['hostname', 'HOSTNAME', os.hostname()],
  ['stackTraceLimit', 'STACK_TRACE_LIMIT', Infinity],
  ['captureExceptions', 'CAPTURE_EXCEPTIONS', true],
  ['exceptionLogLevel', 'EXCEPTION_LOG_LEVEL', 'fatal'],
  ['filter'],
  ['_ff_captureFrame', 'FF_CAPTURE_FRAME', false]
]

var falsyValues = [false, 0, '', '0', 'false', 'no', 'off', 'disabled']
var truthyValues = [true, 1, '1', 'true', 'yes', 'on', 'enabled']

var skipBody = function () { return '*' }
var uncaughtExceptionListeners = process._events.uncaughtException

var setup = function () {
  clean()
  uncaughtExceptionListeners = process._events.uncaughtException
  process.removeAllListeners('uncaughtException')
  helpers.mockLogger()
}

var clean = function () {
  process._events.uncaughtException = uncaughtExceptionListeners
  helpers.restoreLogger()
}

optionFixtures.forEach(function (fixture) {
  if (fixture[1]) {
    test('should be configurable by envrionment variable OPBEAT_' + fixture[1], function (t) {
      setup()
      var bool = typeof fixture[2] === 'boolean'
      var value = bool ? (fixture[2] ? '0' : '1') : 'custom-value'
      process.env['OPBEAT_' + fixture[1]] = value
      var client = opbeat()
      t.equal(client[fixture[0]], bool ? value !== false : value)
      delete process.env['OPBEAT_' + fixture[1]]
      t.end()
    })

    test('should overwrite OPBEAT_' + fixture[1] + ' by option property ' + fixture[0], function (t) {
      setup()
      var options = {}
      var bool = typeof fixture[2] === 'boolean'
      var value1 = bool ? (fixture[2] ? '0' : '1') : 'overwriting-value'
      var value2 = bool ? (fixture[2] ? '1' : '0') : 'custom-value'
      options[fixture[0]] = value1
      process.env['OPBEAT_' + fixture[1]] = value2
      var client = opbeat(options)
      t.equal(client[fixture[0]], bool ? value1 !== false : value1)
      delete process.env['OPBEAT_' + fixture[1]]
      t.end()
    })
  }

  test('should default ' + fixture[0] + ' to ' + fixture[2], function (t) {
    setup()
    var client = opbeat()
    t.equal(client[fixture[0]], fixture[2])
    t.end()
  })
})

falsyValues.forEach(function (val) {
  test('should be disabled by envrionment variable OPBEAT_ACTIVE set to: ' + util.inspect(val), function (t) {
    setup()
    process.env.OPBEAT_ACTIVE = val
    var client = opbeat({ appId: 'foo', organizationId: 'bar', secretToken: 'baz' })
    t.equal(client.active, false)
    delete process.env.OPBEAT_ACTIVE
    t.end()
  })
})

truthyValues.forEach(function (val) {
  test('should be enabled by envrionment variable OPBEAT_ACTIVE set to: ' + util.inspect(val), function (t) {
    setup()
    process.env.OPBEAT_ACTIVE = val
    var client = opbeat({ appId: 'foo', organizationId: 'bar', secretToken: 'baz' })
    t.equal(client.active, true)
    delete process.env.OPBEAT_ACTIVE
    t.end()
  })
})

test('should overwrite OPBEAT_ACTIVE by option property active', function (t) {
  setup()
  var options = { appId: 'foo', organizationId: 'bar', secretToken: 'baz', active: false }
  process.env.OPBEAT_ACTIVE = '1'
  var client = opbeat(options)
  t.equal(client.active, false)
  delete process.env.OPBEAT_ACTIVE
  t.end()
})

test('should default active to true if required options have been specified', function (t) {
  setup()
  var client = opbeat({ appId: 'foo', organizationId: 'bar', secretToken: 'baz' })
  t.equal(client.active, true)
  t.end()
})

test('should default active to false if required options have not been specified', function (t) {
  setup()
  var client = opbeat()
  t.equal(client.active, false)
  t.end()
})

test('should force active to false if required options have not been specified', function (t) {
  setup()
  var client = opbeat({ active: true })
  t.equal(client.active, false)
  t.end()
})

test('#captureError()', function (t) {
  t.test('should send a plain text message to Opbeat server', function (t) {
    setup()
    var client = opbeat(options)
    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(skipBody)
      .defaultReplyHeaders({'Location': 'foo'})
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
      .reply(200)

    client.on('logged', function (result) {
      scope.done()
      t.equal(result, 'foo')
      t.end()
    })
    client.captureError('Hey!')
  })

  t.test('should emit error when request returns non 200', function (t) {
    setup()
    var client = opbeat(options)
    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(skipBody)
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
      .reply(500, { error: 'Oops!' })

    client.on('error', function () {
      scope.done()
      t.end()
    })
    client.captureError('Hey!')
  })

  t.test('shouldn\'t shit it\'s pants when error is emitted without a listener', function (t) {
    setup()
    var client = opbeat(options)
    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(skipBody)
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
      .reply(500, { error: 'Oops!' })

    client.captureError('Hey!')
    setTimeout(function () {
      scope.done()
      t.end()
    }, 25)
  })

  t.test('should attach an Error object when emitting error', function (t) {
    setup()
    var client = opbeat(options)
    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(skipBody)
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
      .reply(500, { error: 'Oops!' })

    client.on('error', function (err) {
      scope.done()
      t.equal(err.message, 'Opbeat error (500): {"error":"Oops!"}')
      t.end()
    })

    client.captureError('Hey!')
  })

  t.test('should use `param_message` as well as `message` if given an object as 1st argument', function (t) {
    setup()
    var client = opbeat(options)
    var oldErrorFn = request.error
    request.error = function (client, options, callback) {
      t.ok('message' in options)
      t.ok('param_message' in options)
      t.equal(options.message, 'Hello World')
      t.equal(options.param_message, 'Hello %s')
      request.error = oldErrorFn
      t.end()
    }
    client.captureError({ message: 'Hello %s', params: ['World'] })
  })

  t.test('should send an Error to Opbeat server', function (t) {
    setup()
    var client = opbeat(options)
    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(skipBody)
      .defaultReplyHeaders({'Location': 'foo'})
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
      .reply(200)

    client.on('logged', function (result) {
      scope.done()
      t.equal(result, 'foo')
      t.end()
    })
    client.captureError(new Error('wtf?'))
  })

  t.test('should use filter if provided', function (t) {
    setup()
    var called = false
    var options = {
      appId: 'foo',
      organizationId: 'bar',
      secretToken: 'baz',
      filter: function (err, options) {
        t.equal(options.foo, 'bar')
        t.ok(err instanceof Error)
        t.equal(err.message, 'foo')
        called = true
        return { owned: true }
      }
    }
    var client = opbeat(options)
    var oldErrorFn = request.error
    request.error = function (client, options, callback) {
      t.ok(called, 'called')
      t.deepEqual(options, { owned: true })
      request.error = oldErrorFn
      t.end()
    }
    client.captureError(new Error('foo'), { foo: 'bar' })
  })
})

test('#handleUncaughtExceptions()', function (t) {
  t.test('should add itself to the uncaughtException event list', function (t) {
    setup()
    t.equal(process._events.uncaughtException, undefined)
    var client = opbeat(options)
    client.handleUncaughtExceptions()
    t.equal(process._events.uncaughtException.length, 1)
    t.end()
  })

  t.test('should not add more than one listener for the uncaughtException event', function (t) {
    setup()
    var client = opbeat(options)
    client.handleUncaughtExceptions()
    var before = process._events.uncaughtException.length
    client.handleUncaughtExceptions()
    t.equal(process._events.uncaughtException.length, before)
    t.end()
  })

  t.test('should send an uncaughtException to Opbeat server', function (t) {
    setup()

    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(skipBody)
      .defaultReplyHeaders({'Location': 'foo'})
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
      .reply(200)

    var client = opbeat(options)
    client.handleUncaughtExceptions(function (err, url) {
      t.ok(util.isError(err))
      scope.done()
      t.equal(url, 'foo')
      t.end()
    })

    process.emit('uncaughtException', new Error('derp'))
  })
})

test('#trackRelease()', function (t) {
  t.test('should send release request to the Opbeat server with given rev', function (t) {
    setup()
    var client = opbeat(options)
    var buffer
    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(function (body) {
        buffer = new Buffer(body, 'hex')
        return '*'
      })
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/releases/', '*')
      .reply(200)

    client.trackRelease({ rev: 'foo' }, function () {
      scope.done()
      zlib.inflate(buffer, function (err, buffer) {
        t.error(err)
        var body = JSON.parse(buffer.toString())
        t.equal(Object.keys(body).length, 3)
        t.equal(body.status, 'completed')
        t.equal(body.rev, 'foo')
        t.ok('branch' in body)
        t.equal(typeof body.branch, 'string')
        t.ok(body.branch.length > 0)
        t.end()
      })
    })
  })

  t.test('should send release request to the Opbeat server with given rev and branch', function (t) {
    setup()
    var client = opbeat(options)
    var buffer
    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(function (body) {
        buffer = new Buffer(body, 'hex')
        return '*'
      })
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/releases/', '*')
      .reply(200)

    client.trackRelease({ rev: 'foo', branch: 'bar' }, function () {
      scope.done()
      zlib.inflate(buffer, function (err, buffer) {
        t.error(err)
        var body = JSON.parse(buffer.toString())
        t.equal(Object.keys(body).length, 3)
        t.equal(body.status, 'completed')
        t.equal(body.rev, 'foo')
        t.equal(body.branch, 'bar')
        t.end()
      })
    })
  })

  t.test('should send release request to the Opbeat server with given rev and branch automatically generated', function (t) {
    setup()
    var client = opbeat(options)
    var buffer
    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(function (body) {
        buffer = new Buffer(body, 'hex')
        return '*'
      })
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/releases/', '*')
      .reply(200)

    client.trackRelease(function () {
      scope.done()
      zlib.inflate(buffer, function (err, buffer) {
        t.error(err)
        var body = JSON.parse(buffer.toString())
        t.equal(Object.keys(body).length, 3)
        t.equal(body.status, 'completed')
        t.ok(/^[\da-f]{40}$/.test(body.rev))
        t.ok('branch' in body)
        t.equal(typeof body.branch, 'string')
        t.ok(body.branch.length > 0)
        t.end()
      })
    })
  })
})
<commit_msg>standard: fix strict equals error introduced in 01cd1a8<commit_after>'use strict'

var os = require('os')
var zlib = require('zlib')
var util = require('util')
var test = require('tape')
var nock = require('nock')
var helpers = require('./_helpers')
var request = require('../lib/request')
var opbeat = require('../')

var options = {
  organizationId: 'some-org-id',
  appId: 'some-app-id',
  secretToken: 'secret',
  captureExceptions: false
}

var optionFixtures = [
  ['appId', 'APP_ID'],
  ['organizationId', 'ORGANIZATION_ID'],
  ['secretToken', 'SECRET_TOKEN'],
  ['clientLogLevel', 'CLIENT_LOG_LEVEL', 'info'],
  ['hostname', 'HOSTNAME', os.hostname()],
  ['stackTraceLimit', 'STACK_TRACE_LIMIT', Infinity],
  ['captureExceptions', 'CAPTURE_EXCEPTIONS', true],
  ['exceptionLogLevel', 'EXCEPTION_LOG_LEVEL', 'fatal'],
  ['filter'],
  ['_ff_captureFrame', 'FF_CAPTURE_FRAME', false]
]

var falsyValues = [false, 0, '', '0', 'false', 'no', 'off', 'disabled']
var truthyValues = [true, 1, '1', 'true', 'yes', 'on', 'enabled']

var skipBody = function () { return '*' }
var uncaughtExceptionListeners = process._events.uncaughtException

var setup = function () {
  clean()
  uncaughtExceptionListeners = process._events.uncaughtException
  process.removeAllListeners('uncaughtException')
  helpers.mockLogger()
}

var clean = function () {
  process._events.uncaughtException = uncaughtExceptionListeners
  helpers.restoreLogger()
}

optionFixtures.forEach(function (fixture) {
  if (fixture[1]) {
    test('should be configurable by envrionment variable OPBEAT_' + fixture[1], function (t) {
      setup()
      var bool = typeof fixture[2] === 'boolean'
      var value = bool ? (fixture[2] ? '0' : '1') : 'custom-value'
      process.env['OPBEAT_' + fixture[1]] = value
      var client = opbeat()
      t.equal(client[fixture[0]], bool ? !fixture[2] : value)
      delete process.env['OPBEAT_' + fixture[1]]
      t.end()
    })

    test('should overwrite OPBEAT_' + fixture[1] + ' by option property ' + fixture[0], function (t) {
      setup()
      var options = {}
      var bool = typeof fixture[2] === 'boolean'
      var value1 = bool ? (fixture[2] ? '0' : '1') : 'overwriting-value'
      var value2 = bool ? (fixture[2] ? '1' : '0') : 'custom-value'
      options[fixture[0]] = value1
      process.env['OPBEAT_' + fixture[1]] = value2
      var client = opbeat(options)
      t.equal(client[fixture[0]], bool ? !fixture[2] : value1)
      delete process.env['OPBEAT_' + fixture[1]]
      t.end()
    })
  }

  test('should default ' + fixture[0] + ' to ' + fixture[2], function (t) {
    setup()
    var client = opbeat()
    t.equal(client[fixture[0]], fixture[2])
    t.end()
  })
})

falsyValues.forEach(function (val) {
  test('should be disabled by envrionment variable OPBEAT_ACTIVE set to: ' + util.inspect(val), function (t) {
    setup()
    process.env.OPBEAT_ACTIVE = val
    var client = opbeat({ appId: 'foo', organizationId: 'bar', secretToken: 'baz' })
    t.equal(client.active, false)
    delete process.env.OPBEAT_ACTIVE
    t.end()
  })
})

truthyValues.forEach(function (val) {
  test('should be enabled by envrionment variable OPBEAT_ACTIVE set to: ' + util.inspect(val), function (t) {
    setup()
    process.env.OPBEAT_ACTIVE = val
    var client = opbeat({ appId: 'foo', organizationId: 'bar', secretToken: 'baz' })
    t.equal(client.active, true)
    delete process.env.OPBEAT_ACTIVE
    t.end()
  })
})

test('should overwrite OPBEAT_ACTIVE by option property active', function (t) {
  setup()
  var options = { appId: 'foo', organizationId: 'bar', secretToken: 'baz', active: false }
  process.env.OPBEAT_ACTIVE = '1'
  var client = opbeat(options)
  t.equal(client.active, false)
  delete process.env.OPBEAT_ACTIVE
  t.end()
})

test('should default active to true if required options have been specified', function (t) {
  setup()
  var client = opbeat({ appId: 'foo', organizationId: 'bar', secretToken: 'baz' })
  t.equal(client.active, true)
  t.end()
})

test('should default active to false if required options have not been specified', function (t) {
  setup()
  var client = opbeat()
  t.equal(client.active, false)
  t.end()
})

test('should force active to false if required options have not been specified', function (t) {
  setup()
  var client = opbeat({ active: true })
  t.equal(client.active, false)
  t.end()
})

test('#captureError()', function (t) {
  t.test('should send a plain text message to Opbeat server', function (t) {
    setup()
    var client = opbeat(options)
    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(skipBody)
      .defaultReplyHeaders({'Location': 'foo'})
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
      .reply(200)

    client.on('logged', function (result) {
      scope.done()
      t.equal(result, 'foo')
      t.end()
    })
    client.captureError('Hey!')
  })

  t.test('should emit error when request returns non 200', function (t) {
    setup()
    var client = opbeat(options)
    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(skipBody)
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
      .reply(500, { error: 'Oops!' })

    client.on('error', function () {
      scope.done()
      t.end()
    })
    client.captureError('Hey!')
  })

  t.test('shouldn\'t shit it\'s pants when error is emitted without a listener', function (t) {
    setup()
    var client = opbeat(options)
    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(skipBody)
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
      .reply(500, { error: 'Oops!' })

    client.captureError('Hey!')
    setTimeout(function () {
      scope.done()
      t.end()
    }, 25)
  })

  t.test('should attach an Error object when emitting error', function (t) {
    setup()
    var client = opbeat(options)
    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(skipBody)
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
      .reply(500, { error: 'Oops!' })

    client.on('error', function (err) {
      scope.done()
      t.equal(err.message, 'Opbeat error (500): {"error":"Oops!"}')
      t.end()
    })

    client.captureError('Hey!')
  })

  t.test('should use `param_message` as well as `message` if given an object as 1st argument', function (t) {
    setup()
    var client = opbeat(options)
    var oldErrorFn = request.error
    request.error = function (client, options, callback) {
      t.ok('message' in options)
      t.ok('param_message' in options)
      t.equal(options.message, 'Hello World')
      t.equal(options.param_message, 'Hello %s')
      request.error = oldErrorFn
      t.end()
    }
    client.captureError({ message: 'Hello %s', params: ['World'] })
  })

  t.test('should send an Error to Opbeat server', function (t) {
    setup()
    var client = opbeat(options)
    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(skipBody)
      .defaultReplyHeaders({'Location': 'foo'})
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
      .reply(200)

    client.on('logged', function (result) {
      scope.done()
      t.equal(result, 'foo')
      t.end()
    })
    client.captureError(new Error('wtf?'))
  })

  t.test('should use filter if provided', function (t) {
    setup()
    var called = false
    var options = {
      appId: 'foo',
      organizationId: 'bar',
      secretToken: 'baz',
      filter: function (err, options) {
        t.equal(options.foo, 'bar')
        t.ok(err instanceof Error)
        t.equal(err.message, 'foo')
        called = true
        return { owned: true }
      }
    }
    var client = opbeat(options)
    var oldErrorFn = request.error
    request.error = function (client, options, callback) {
      t.ok(called, 'called')
      t.deepEqual(options, { owned: true })
      request.error = oldErrorFn
      t.end()
    }
    client.captureError(new Error('foo'), { foo: 'bar' })
  })
})

test('#handleUncaughtExceptions()', function (t) {
  t.test('should add itself to the uncaughtException event list', function (t) {
    setup()
    t.equal(process._events.uncaughtException, undefined)
    var client = opbeat(options)
    client.handleUncaughtExceptions()
    t.equal(process._events.uncaughtException.length, 1)
    t.end()
  })

  t.test('should not add more than one listener for the uncaughtException event', function (t) {
    setup()
    var client = opbeat(options)
    client.handleUncaughtExceptions()
    var before = process._events.uncaughtException.length
    client.handleUncaughtExceptions()
    t.equal(process._events.uncaughtException.length, before)
    t.end()
  })

  t.test('should send an uncaughtException to Opbeat server', function (t) {
    setup()

    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(skipBody)
      .defaultReplyHeaders({'Location': 'foo'})
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/errors/', '*')
      .reply(200)

    var client = opbeat(options)
    client.handleUncaughtExceptions(function (err, url) {
      t.ok(util.isError(err))
      scope.done()
      t.equal(url, 'foo')
      t.end()
    })

    process.emit('uncaughtException', new Error('derp'))
  })
})

test('#trackRelease()', function (t) {
  t.test('should send release request to the Opbeat server with given rev', function (t) {
    setup()
    var client = opbeat(options)
    var buffer
    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(function (body) {
        buffer = new Buffer(body, 'hex')
        return '*'
      })
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/releases/', '*')
      .reply(200)

    client.trackRelease({ rev: 'foo' }, function () {
      scope.done()
      zlib.inflate(buffer, function (err, buffer) {
        t.error(err)
        var body = JSON.parse(buffer.toString())
        t.equal(Object.keys(body).length, 3)
        t.equal(body.status, 'completed')
        t.equal(body.rev, 'foo')
        t.ok('branch' in body)
        t.equal(typeof body.branch, 'string')
        t.ok(body.branch.length > 0)
        t.end()
      })
    })
  })

  t.test('should send release request to the Opbeat server with given rev and branch', function (t) {
    setup()
    var client = opbeat(options)
    var buffer
    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(function (body) {
        buffer = new Buffer(body, 'hex')
        return '*'
      })
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/releases/', '*')
      .reply(200)

    client.trackRelease({ rev: 'foo', branch: 'bar' }, function () {
      scope.done()
      zlib.inflate(buffer, function (err, buffer) {
        t.error(err)
        var body = JSON.parse(buffer.toString())
        t.equal(Object.keys(body).length, 3)
        t.equal(body.status, 'completed')
        t.equal(body.rev, 'foo')
        t.equal(body.branch, 'bar')
        t.end()
      })
    })
  })

  t.test('should send release request to the Opbeat server with given rev and branch automatically generated', function (t) {
    setup()
    var client = opbeat(options)
    var buffer
    var scope = nock('https://intake.opbeat.com')
      .filteringRequestBody(function (body) {
        buffer = new Buffer(body, 'hex')
        return '*'
      })
      .post('/api/v1/organizations/some-org-id/apps/some-app-id/releases/', '*')
      .reply(200)

    client.trackRelease(function () {
      scope.done()
      zlib.inflate(buffer, function (err, buffer) {
        t.error(err)
        var body = JSON.parse(buffer.toString())
        t.equal(Object.keys(body).length, 3)
        t.equal(body.status, 'completed')
        t.ok(/^[\da-f]{40}$/.test(body.rev))
        t.ok('branch' in body)
        t.equal(typeof body.branch, 'string')
        t.ok(body.branch.length > 0)
        t.end()
      })
    })
  })
})
<|endoftext|>


<commit_before>// Copyright 2016 The Draco Authors.
//
// 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.
//
'use strict';

THREE.DRACOLoader = function(manager) {
    this.manager = (manager !== undefined) ? manager :
        THREE.DefaultLoadingManager;
    this.materials = null;
};

THREE.DRACOLoader.prototype = {

    constructor: THREE.DRACOLoader,

    load: function(url, onLoad, onProgress, onError) {
        const scope = this;
        const loader = new THREE.FileLoader(scope.manager);
        loader.setPath(this.path);
        loader.setResponseType('arraybuffer');
        loader.load(url, function(blob) {
            onLoad(scope.decodeDracoFile(blob));
        }, onProgress, onError);
    },

    setPath: function(value) {
        this.path = value;
    },

    decodeDracoFile: function(rawBuffer) {
        const scope = this;
        /*
         * Here is how to use Draco Javascript decoder and get the geometry.
         */
        const buffer = new DracoModule.DecoderBuffer();
        buffer.Init(new Int8Array(rawBuffer), rawBuffer.byteLength);
        const wrapper = new DracoModule.WebIDLWrapper();

        /*
         * Determine what type is this file, mesh or point cloud.
         */
        const geometryType = wrapper.GetEncodedGeometryType(buffer);
        if (geometryType == DracoModule.TRIANGULAR_MESH) {
          fileDisplayArea.innerText = "Loaded a mesh.\n";
        } else if (geometryType == DracoModule.POINT_CLOUD) {
          fileDisplayArea.innerText = "Loaded a point cloud.\n";
        } else {
          const errorMsg = "Error: Unknown geometry type.";
          fileDisplayArea.innerText = errorMsg;
          throw new Error(errorMsg);
        }
        return scope.convertDracoGeometryTo3JS(wrapper, geometryType, buffer);
    },

    convertDracoGeometryTo3JS: function(wrapper, geometryType, buffer) {
        let dracoGeometry;
        if (geometryType == DracoModule.TRIANGULAR_MESH) {
          dracoGeometry = wrapper.DecodeMeshFromBuffer(buffer);
        } else {
          dracoGeometry = wrapper.DecodePointCloudFromBuffer(buffer);
        }
        DracoModule.destroy(buffer);
        /*
         * Example on how to retrieve mesh and attributes.
         */
        let numFaces, numPoints, numVertexCoordinates, numAttributes;
        // For output basic geometry information.
        let geometryInfoStr;
        if (geometryType == DracoModule.TRIANGULAR_MESH) {
          numFaces = dracoGeometry.num_faces();
          geometryInfoStr += "Number of faces loaded: " + numFaces.toString()
              + ".\n";
        } else {
          numFaces = 0;
        }
        numPoints = dracoGeometry.num_points();
        numVertexCoordinates = numPoints * 3;
        numAttributes = dracoGeometry.num_attributes();
        geometryInfoStr = "Number of points loaded: " + numPoints.toString()
            + ".\n";
        geometryInfoStr += "Number of attributes loaded: " +
            numAttributes.toString() + ".\n";

        // Get position attribute. Must exists.
        const posAttId = wrapper.GetAttributeId(dracoGeometry,
                                                Module.POSITION);
        if (posAttId == -1) {
          const errorMsg = "No position attribute found in the mesh.";
          fileDisplayArea.innerText = errorMsg;
          DracoModule.destroy(wrapper);
          DracoModule.destroy(dracoGeometry);
          throw new Error(errorMsg);
        }
        const posAttribute = wrapper.GetAttribute(dracoGeometry, posAttId);
        const posAttributeData = new DracoModule.DracoFloat32Array();
        wrapper.GetAttributeFloatForAllPoints(
            dracoGeometry, posAttribute, posAttributeData);
        // Get color attributes if exists.
        const colorAttId = wrapper.GetAttributeId(dracoGeometry, Module.COLOR);
        let colAttributeData;
        if (colorAttId != -1) {
          geometryInfoStr += "\nLoaded color attribute.\n";
          const colAttribute = wrapper.GetAttribute(dracoGeometry, colorAttId);
          colAttributeData = new DracoModule.DracoFloat32Array();
          wrapper.GetAttributeFloatForAllPoints(dracoGeometry, colAttribute,
                                                colAttributeData);
        }

        // Get normal attributes if exists.
        const normalAttId =
            wrapper.GetAttributeId(dracoGeometry, Module.NORMAL);
        let norAttributeData;
        if (normalAttId != -1) {
          geometryInfoStr += "\nLoaded normal attribute.\n";
          const norAttribute = wrapper.GetAttribute(dracoGeometry, normalAttId);
          norAttributeData = new DracoModule.DracoFloat32Array();
          wrapper.GetAttributeFloatForAllPoints(dracoGeometry, norAttribute,
                                                norAttributeData);
        }

        // Structure for converting to THREEJS geometry later.
        const geometryBuffer = {
            indices: [],
            vertices: [],
            normals: [],
            uvs: [],
            colors: []
        };
        for (let i = 0; i < numVertexCoordinates; i += 3) {
            geometryBuffer.vertices.push(
                posAttributeData.GetValue(i),
                posAttributeData.GetValue(i + 1),
                posAttributeData.GetValue(i + 2));
            // Add color.
            if (colorAttId != -1) {
              geometryBuffer.colors.push(
                  colAttributeData.GetValue(i),
                  colAttributeData.GetValue(i + 1),
                  colAttributeData.GetValue(i + 2));
            } else {
              // Default is white.
              geometryBuffer.colors.push(1.0, 1.0, 1.0);
            }
            // Add normal.
            if (normalAttId != -1) {
              geometryBuffer.normals.push(
                  norAttributeData.GetValue(i),
                  norAttributeData.GetValue(i + 1),
                  norAttributeData.GetValue(i + 2));
            }
        }
        DracoModule.destroy(posAttributeData);
        if (colorAttId != -1)
          DracoModule.destroy(colAttributeData);
        if (normalAttId != -1)
          DracoModule.destroy(norAttributeData);

        // For mesh, we need to generate the faces.
        if (geometryType == DracoModule.TRIANGULAR_MESH) {
          const numIndices = numFaces * 3;
          const ia = new DracoInt32Array();
          for (let i = 0; i < numFaces; ++i) {
            wrapper.GetFaceFromMesh(dracoGeometry, i, ia);
            geometryBuffer.indices.push(
                ia.GetValue(0), ia.GetValue(1), ia.GetValue(2));
          }
          DracoModule.destroy(ia);
        }
        DracoModule.destroy(wrapper);
        DracoModule.destroy(dracoGeometry);

        fileDisplayArea.innerText += geometryInfoStr;

        // Import data to Three JS geometry.
        const geometry = new THREE.BufferGeometry();
        if (geometryType == DracoModule.TRIANGULAR_MESH) {
          geometry.setIndex(new(geometryBuffer.indices.length > 65535 ?
                THREE.Uint32BufferAttribute : THREE.Uint16BufferAttribute)
              (geometryBuffer.indices, 1));
        }
        geometry.addAttribute('position',
            new THREE.Float32BufferAttribute(geometryBuffer.vertices, 3));
        geometry.addAttribute('color',
            new THREE.Float32BufferAttribute(geometryBuffer.colors, 3));
        if (normalAttId != -1) {
          geometry.addAttribute('normal',
              new THREE.Float32BufferAttribute(geometryBuffer.normals, 3));
        }
        return geometry;
    }
};
<commit_msg>Javascript loader: load texture coordinates<commit_after>// Copyright 2016 The Draco Authors.
//
// 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.
//
'use strict';

THREE.DRACOLoader = function(manager) {
    this.manager = (manager !== undefined) ? manager :
        THREE.DefaultLoadingManager;
    this.materials = null;
};

THREE.DRACOLoader.prototype = {

    constructor: THREE.DRACOLoader,

    load: function(url, onLoad, onProgress, onError) {
        const scope = this;
        const loader = new THREE.FileLoader(scope.manager);
        loader.setPath(this.path);
        loader.setResponseType('arraybuffer');
        loader.load(url, function(blob) {
            onLoad(scope.decodeDracoFile(blob));
        }, onProgress, onError);
    },

    setPath: function(value) {
        this.path = value;
    },

    decodeDracoFile: function(rawBuffer) {
        const scope = this;
        /*
         * Here is how to use Draco Javascript decoder and get the geometry.
         */
        const buffer = new DracoModule.DecoderBuffer();
        buffer.Init(new Int8Array(rawBuffer), rawBuffer.byteLength);
        const wrapper = new DracoModule.WebIDLWrapper();

        /*
         * Determine what type is this file, mesh or point cloud.
         */
        const geometryType = wrapper.GetEncodedGeometryType(buffer);
        if (geometryType == DracoModule.TRIANGULAR_MESH) {
          fileDisplayArea.innerText = "Loaded a mesh.\n";
        } else if (geometryType == DracoModule.POINT_CLOUD) {
          fileDisplayArea.innerText = "Loaded a point cloud.\n";
        } else {
          const errorMsg = "Error: Unknown geometry type.";
          fileDisplayArea.innerText = errorMsg;
          throw new Error(errorMsg);
        }
        return scope.convertDracoGeometryTo3JS(wrapper, geometryType, buffer);
    },

    convertDracoGeometryTo3JS: function(wrapper, geometryType, buffer) {
        let dracoGeometry;
        if (geometryType == DracoModule.TRIANGULAR_MESH) {
          dracoGeometry = wrapper.DecodeMeshFromBuffer(buffer);
        } else {
          dracoGeometry = wrapper.DecodePointCloudFromBuffer(buffer);
        }
        DracoModule.destroy(buffer);
        /*
         * Example on how to retrieve mesh and attributes.
         */
        let numFaces, numPoints, numVertexCoordinates, numTextureCoordinates, numAttributes;
        // For output basic geometry information.
        let geometryInfoStr;
        if (geometryType == DracoModule.TRIANGULAR_MESH) {
          numFaces = dracoGeometry.num_faces();
          geometryInfoStr += "Number of faces loaded: " + numFaces.toString()
              + ".\n";
        } else {
          numFaces = 0;
        }
        numPoints = dracoGeometry.num_points();
        numVertexCoordinates = numPoints * 3;
        numTextureCoordinates = numPoints * 2;
        numAttributes = dracoGeometry.num_attributes();
        geometryInfoStr = "Number of points loaded: " + numPoints.toString()
            + ".\n";
        geometryInfoStr += "Number of attributes loaded: " +
            numAttributes.toString() + ".\n";

        // Get position attribute. Must exists.
        const posAttId = wrapper.GetAttributeId(dracoGeometry,
                                                Module.POSITION);
        if (posAttId == -1) {
          const errorMsg = "No position attribute found in the mesh.";
          fileDisplayArea.innerText = errorMsg;
          DracoModule.destroy(wrapper);
          DracoModule.destroy(dracoGeometry);
          throw new Error(errorMsg);
        }
        const posAttribute = wrapper.GetAttribute(dracoGeometry, posAttId);
        const posAttributeData = new DracoModule.DracoFloat32Array();
        wrapper.GetAttributeFloatForAllPoints(
            dracoGeometry, posAttribute, posAttributeData);
        // Get color attributes if exists.
        const colorAttId = wrapper.GetAttributeId(dracoGeometry, Module.COLOR);
        let colAttributeData;
        if (colorAttId != -1) {
          geometryInfoStr += "\nLoaded color attribute.\n";
          const colAttribute = wrapper.GetAttribute(dracoGeometry, colorAttId);
          colAttributeData = new DracoModule.DracoFloat32Array();
          wrapper.GetAttributeFloatForAllPoints(dracoGeometry, colAttribute,
                                                colAttributeData);
        }

        // Get normal attributes if exists.
        const normalAttId =
            wrapper.GetAttributeId(dracoGeometry, Module.NORMAL);
        let norAttributeData;
        if (normalAttId != -1) {
          geometryInfoStr += "\nLoaded normal attribute.\n";
          const norAttribute = wrapper.GetAttribute(dracoGeometry, normalAttId);
          norAttributeData = new DracoModule.DracoFloat32Array();
          wrapper.GetAttributeFloatForAllPoints(dracoGeometry, norAttribute,
                                                norAttributeData);
        }

        // Get texture coord attributes if exists.
        const texCoordAttId =
            wrapper.GetAttributeId(dracoGeometry, Module.TEX_COORD);
        let textCoordAttributeData;
        if (texCoordAttId != -1) {
          geometryInfoStr += "\nLoaded texture coordinate attribute.\n";
          const texCoordAttribute = wrapper.GetAttribute(dracoGeometry, texCoordAttId);
          textCoordAttributeData = new DracoModule.DracoFloat32Array();
          wrapper.GetAttributeFloatForAllPoints(dracoGeometry, texCoordAttribute,
                                                textCoordAttributeData);
        }

        // Structure for converting to THREEJS geometry later.
        const geometryBuffer = {
            indices: [],
            vertices: [],
            normals: [],
            uvs: [],
            colors: []
        };
        for (let i = 0; i < numVertexCoordinates; i += 3) {
            geometryBuffer.vertices.push(
                posAttributeData.GetValue(i),
                posAttributeData.GetValue(i + 1),
                posAttributeData.GetValue(i + 2));
            // Add color.
            if (colorAttId != -1) {
              geometryBuffer.colors.push(
                  colAttributeData.GetValue(i),
                  colAttributeData.GetValue(i + 1),
                  colAttributeData.GetValue(i + 2));
            } else {
              // Default is white.
              geometryBuffer.colors.push(1.0, 1.0, 1.0);
            }
            // Add normal.
            if (normalAttId != -1) {
              geometryBuffer.normals.push(
                  norAttributeData.GetValue(i),
                  norAttributeData.GetValue(i + 1),
                  norAttributeData.GetValue(i + 2));
            }
        }

        for (let i = 0; i < numTextureCoordinates; i += 2) {
            // Add texture coordinates.
            if (texCoordAttId != -1) {
              geometryBuffer.uvs.push(
                  textCoordAttributeData.GetValue(i),
                  textCoordAttributeData.GetValue(i + 1));
            }
          }

        DracoModule.destroy(posAttributeData);
        if (colorAttId != -1)
          DracoModule.destroy(colAttributeData);
        if (normalAttId != -1)
          DracoModule.destroy(norAttributeData);
        if (texCoordAttId != -1)
          DracoModule.destroy(textCoordAttributeData);

        // For mesh, we need to generate the faces.
        if (geometryType == DracoModule.TRIANGULAR_MESH) {
          const numIndices = numFaces * 3;
          const ia = new DracoInt32Array();
          for (let i = 0; i < numFaces; ++i) {
            wrapper.GetFaceFromMesh(dracoGeometry, i, ia);
            geometryBuffer.indices.push(
                ia.GetValue(0), ia.GetValue(1), ia.GetValue(2));
          }
          DracoModule.destroy(ia);
        }
        DracoModule.destroy(wrapper);
        DracoModule.destroy(dracoGeometry);

        fileDisplayArea.innerText += geometryInfoStr;

        // Import data to Three JS geometry.
        const geometry = new THREE.BufferGeometry();
        if (geometryType == DracoModule.TRIANGULAR_MESH) {
          geometry.setIndex(new(geometryBuffer.indices.length > 65535 ?
                THREE.Uint32BufferAttribute : THREE.Uint16BufferAttribute)
              (geometryBuffer.indices, 1));
        }
        geometry.addAttribute('position',
            new THREE.Float32BufferAttribute(geometryBuffer.vertices, 3));
        geometry.addAttribute('color',
            new THREE.Float32BufferAttribute(geometryBuffer.colors, 3));
        if (normalAttId != -1) {
          geometry.addAttribute('normal',
              new THREE.Float32BufferAttribute(geometryBuffer.normals, 3));
        }
        if (texCoordAttId != -1) {
          geometry.addAttribute('uv',
              new THREE.Float32BufferAttribute(geometryBuffer.uvs, 2));
        }
        return geometry;
    }
};
<|endoftext|>


<commit_before>const html = require('quantum-html')
const api = require('quantum-api')
const version = require('quantum-version')
const template = require('quantum-template')
const docs = require('quantum-docs')
const codeHighlight = require('quantum-code-highlight')

const entityTransforms = require('./transforms/transforms')
const versions = require('./content/versions.json')

const typeLinks = {
  'Array': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array',
  'Boolean': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean',
  'Function': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function',
  'Number': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number',
  'Object': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object',
  'String': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String',
  'Element': 'https://developer.mozilla.org/docs/Web/API/Element',
  'Node': 'https://developer.mozilla.org/docs/Web/API/Node',
  'AutoComplete': '/docs/autocomplete/#autocomplete',
  'EventEmitter': '/docs/event-emitter/#eventemitter',
  'Animation': '/docs/animate/#animation',
  'Morph': '/docs/animate/#morph'
}

//XXX: tidy and move this into quantum (with persistence)
function cachedTransforms (trans) {
  const store = {}

  function cached (transform) {
    return (selection, transforms) => {
      const h = JSON.stringify(selection.entity())
      if (!(h in store)) {
        store[h] = transform(selection, transforms)
      }
      return store[h]
    }
  }

  function processObj(obj) {
    const res = {}
    Object.keys(obj).forEach(k => {
      if (typeof obj[k] === 'function') {
        res[k] = cached(obj[k])
      } else {
        res[k] = processObj(obj[k])
      }
    })
    return res
  }

  return processObj(trans)
}

const apiOptions = {
  languages: [
    api.languages.javascript({
      typeLinks: typeLinks
    }),
    api.languages.css()
  ],
  reverseVisibleList: true,
  issueUrl: (id) => 'https://github.com/ocadotechnology/hexagonjs/issues/' + id
}

const htmlOptions = {
  embedAssets: false,
  baseUrl: '',
  entityTransforms: cachedTransforms({
    html: html.entityTransforms(),
    api: api.entityTransforms(apiOptions),
    docs: docs.entityTransforms(),
    codeHighlight: codeHighlight.entityTransforms(),
    hxs: entityTransforms
  })
}

function customizedTemplate (file) {
  const templateOptions = {
    variables: {
      version: file.meta.version,
      latestVersion: versions.latest
    }
  }

  return template.fileTransform(templateOptions)(file)
}

module.exports = {
  port: 9000,
  pipeline: [
    customizedTemplate,
    api.fileTransform(apiOptions),
    version.fileTransform(),
    docs.fileTransform(),
    html.fileTransform(htmlOptions)
  ],
  concurrency: 1,
  resolveRoot: 'content',
  dest: 'target',
  pages: [
    {
      files: 'content/**/index.um',
      base: 'content',
      watch: true
    }
  ],
  resources: [
    {
      files: [
        'node_modules/font-awesome/css/**',
        'node_modules/font-awesome/fonts/**'
      ],
      base: 'node_modules',
      dest: 'resources',
      watch: false
    },
    {
      files: 'resources/hexagon/**/*',
      base: '.',
      watch: false
    },
    {
      files: 'resources/fonts/**/*',
      base: '.',
      watch: false
    },
    {
      files: 'resources/*',
      base: '.',
      watch: true
    }
  ]
}
<commit_msg>fix(quantum): Run versioning before templating so we get file versions<commit_after>const html = require('quantum-html')
const api = require('quantum-api')
const version = require('quantum-version')
const template = require('quantum-template')
const docs = require('quantum-docs')
const codeHighlight = require('quantum-code-highlight')

const entityTransforms = require('./transforms/transforms')
const versions = require('./content/versions.json')

const typeLinks = {
  'Array': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array',
  'Boolean': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean',
  'Function': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function',
  'Number': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number',
  'Object': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object',
  'String': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String',
  'Element': 'https://developer.mozilla.org/docs/Web/API/Element',
  'Node': 'https://developer.mozilla.org/docs/Web/API/Node',
  'AutoComplete': '/docs/autocomplete/#autocomplete',
  'EventEmitter': '/docs/event-emitter/#eventemitter',
  'Animation': '/docs/animate/#animation',
  'Morph': '/docs/animate/#morph'
}

//XXX: tidy and move this into quantum (with persistence)
function cachedTransforms (trans) {
  const store = {}

  function cached (transform) {
    return (selection, transforms) => {
      const h = JSON.stringify(selection.entity())
      if (!(h in store)) {
        store[h] = transform(selection, transforms)
      }
      return store[h]
    }
  }

  function processObj(obj) {
    const res = {}
    Object.keys(obj).forEach(k => {
      if (typeof obj[k] === 'function') {
        res[k] = cached(obj[k])
      } else {
        res[k] = processObj(obj[k])
      }
    })
    return res
  }

  return processObj(trans)
}

const apiOptions = {
  languages: [
    api.languages.javascript({
      typeLinks: typeLinks
    }),
    api.languages.css()
  ],
  reverseVisibleList: true,
  issueUrl: (id) => 'https://github.com/ocadotechnology/hexagonjs/issues/' + id
}

const htmlOptions = {
  embedAssets: false,
  baseUrl: '',
  entityTransforms: cachedTransforms({
    html: html.entityTransforms(),
    api: api.entityTransforms(apiOptions),
    docs: docs.entityTransforms(),
    codeHighlight: codeHighlight.entityTransforms(),
    hxs: entityTransforms
  })
}

function customizedTemplate (file) {
  const templateOptions = {
    variables: {
      version: file.meta.version,
      latestVersion: versions.latest
    }
  }

  return template.fileTransform(templateOptions)(file)
}

module.exports = {
  port: 9000,
  pipeline: [
    version.fileTransform(),
    customizedTemplate,
    api.fileTransform(apiOptions),
    docs.fileTransform(),
    html.fileTransform(htmlOptions)
  ],
  concurrency: 1,
  resolveRoot: 'content',
  dest: 'target',
  pages: [
    {
      files: 'content/**/index.um',
      base: 'content',
      watch: true
    }
  ],
  resources: [
    {
      files: [
        'node_modules/font-awesome/css/**',
        'node_modules/font-awesome/fonts/**'
      ],
      base: 'node_modules',
      dest: 'resources',
      watch: false
    },
    {
      files: 'resources/hexagon/**/*',
      base: '.',
      watch: false
    },
    {
      files: 'resources/fonts/**/*',
      base: '.',
      watch: false
    },
    {
      files: 'resources/*',
      base: '.',
      watch: true
    }
  ]
}
<|endoftext|>


<commit_before>/*
#IFNDEF ALT_LICENSE
                           ThinWire(R) RIA Ajax Framework
                 Copyright (C) 2003-2007 Custom Credit Systems

  This library is free software; you can redistribute it and/or modify it under
  the terms of the GNU Lesser General Public License as published by the Free
  Software Foundation; either version 2.1 of the License, or (at your option) any
  later version.

  This library 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 Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public License along
  with this library; if not, write to the Free Software Foundation, Inc., 59
  Temple Place, Suite 330, Boston, MA 02111-1307 USA

  Users who would rather have a commercial license, warranty or support should
  contact the following company who invented, built and supports the technology:

                Custom Credit Systems, Richardson, TX 75081, USA.
                email: info@thinwire.com    ph: +1 (888) 644-6405
                            http://www.thinwire.com
#ENDIF
#IFDEF ALT_LICENSE
#LICENSE_HEADER#
#ENDIF
#VERSION_HEADER#
*/
//TODO: What does enabled and visible do on a Frame?
//TODO: X & Y do not currently work on a Frame.
//TODO: Focus does not fire on any container
var tw_Frame = tw_BaseContainer.extend({
    _resizeInProgress: false,
    _resizeTimerId: null,
    _menu: null,
    _standardButton: null,
    _modalLayer: null,
    _modalDialogIds: null,
    _focusBeforeDialog: null,

    construct: function(id, containerId, props) {
        arguments.callee.$.call(this, "frame", id, 0);
        this._fontBox = this._borderBox = null;

        var s = this._box.style;
        var cssText = "position:absolute;overflow:hidden;padding:0px;margin:0px;cursor:default;top:0px;left:0px;width:100%;height:100%;";
        tw_Component.setCSSText(cssText, this._box);

        tw_Frame.active = this;
        this._modalDialogIds = [];

        this._backgroundBox = this._container = this._scrollBox = document.createElement("div");
        this._container.className = "container";
        var s = this._container.style;
        cssText = "position:absolute;overflow:hidden;z-index:0;width:100%;bottom:0px;";
        tw_Component.setCSSText(cssText, this._container);
        this._box.appendChild(this._container);

        this._modalLayer = document.createElement("div");
        var s = this._modalLayer.style;
        cssText = "display:none;position:absolute;height:100%;width:100%;z-index:1;";
        tw_Component.setCSSText(cssText, this._modalLayer);
        tw_setLayerTransparent(this._modalLayer);

        tw_addEventListener(this._modalLayer, "mousedown", this._modalLayerMouseDownListener);
        document.body.appendChild(this._modalLayer);

        this._getFrameBounds = this._getFrameBounds.bind(this);
        tw_addEventListener(this._box, "mousedown", this._mouseDownListener.bind(this));
        tw_addEventListener(window, "resize", this._windowBoundsListener.bind(this));
        tw_addEventListener(this._box, ["click", "dblclick"], this._clickListener.bind(this));
        this.init(-1, props);

        var s = document.body.style;
        s.height = "100%";
        s.padding = "0px";
        s.margin = "0px";
        s.border = "0px";

        //NOTE: IE will fire this on load via the windowBoundListener
        if (!tw_isIE) this._getFrameBounds();
    },

    _getFrameBounds: function() {
        var innerWidth = document.body.clientWidth;
        var innerHeight = tw_getVisibleHeight();

        if (window.outerWidth) {
            var outerWidth = window.outerWidth;
            var outerHeight = window.outerHeight;
        } else {
            try {
                this._resizeTimerId = null;
                this._resizeInProgress = true;
                window.resizeTo(innerWidth, innerHeight);
                var outerWidth = innerWidth + (innerWidth - document.body.clientWidth);
                var outerHeight = innerHeight + (innerHeight - tw_getVisibleHeight());
                window.resizeTo(outerWidth, outerHeight);
                setTimeout(function() { this._resizeInProgress = false; }.bind(this), 250);
            } catch (e) {
                this._resizeInProgress = false;
                this._resizeTimerId = setTimeout(this._getFrameBounds, 100);
                return;
            }
        }

        this._width = innerWidth;
        this._height = innerHeight - (this._menu != null ? tw_Dialog.menuBarHeight : 0);
        this._container.style.height = this._height + "px";
        tw_em.sendViewStateChanged(this._id, "frameSize", innerWidth + "," + innerHeight + "," + outerWidth + "," + outerHeight);
    },

    _modalLayerMouseDownListener: function() {
        tw_Dialog.active.setActive(true, true);
    },

    _mouseDownListener: function(event) {
        var target = tw_getEventTarget(event);
        if (target == null || target.className == undefined) return;
        while (target != null && target.className != "dialog" && target.className != "frame" && target.className != "mainMenu") target = target.parentNode;

        if (target != null && target.className != "dialog" && target.parentNode.className != "dialog") {
            if (tw_Dialog.active != null) tw_Dialog.active.setActive(false);
            if (tw_Frame.active.getMenu() != null && target.className != "mainMenu") tw_Frame.active.getMenu().close();
        }
    },

    _windowBoundsListener: function(event) {
        if (this._resizeInProgress) return;
        if (this._resizeTimerId != null) clearTimeout(this._resizeTimerId);
        this._resizeTimerId = setTimeout(this._getFrameBounds, 0);
    },

    isModalLayerVisible: function() {
        return this._modalLayer.style.display != "none";
    },

    setModalLayerVisible: function(state, dialog) {
        if (state) {
            this._focusBeforeDialog = tw_Component.currentFocus;
            tw_Component.currentFocus = null;
            if (this._modalDialogIds.length == 0) this._modalLayer.style.display = "block";
            this._modalLayer.style.zIndex = ++tw_Component.zIndex;
            this._modalDialogIds.push(dialog);
        } else {
            for (var i = 0, cnt = this._modalDialogIds.length; i < cnt; i++) {
                if (this._modalDialogIds[i] === dialog) {
                    this._modalDialogIds.splice(i, 1);
                    break;
                }
            }

            if (this._modalDialogIds.length == 0) {
                this._modalLayer.style.display = "none";
            } else {
                this._modalDialogIds[this._modalDialogIds.length - 1].setActive(true);
            }

            //This would be the case if the component got destroyed while the dialog was visible.
            if (this._focusBeforeDialog != null && this._focusBeforeDialog._box != null) tw_Component.currentFocus = this._focusBeforeDialog;
            this._focusBeforeDialog = null;
        }
    },

    getOffsetY: function() {
        return arguments.callee.$.call(this) + (this.getMenu() != null ? tw_Dialog.menuBarHeight : 0);
    },

    setX: function() { },
    setY: function() { },
    setWidth: function() { },
    setHeight: function() { },

    keyPressNotify: tw_BaseContainer.keyPressNotifyCtrlEnterButton,

    setMenu: function(menu) {
        if (this._menu != null) {
            this._container.style.height = parseInt(this._container.style.height, 10) + tw_Dialog.menuBarHeight + "px";
            this._box.removeChild(this._menu._box);
        }

        this._menu = menu;

        if (menu instanceof tw_Menu) {
			document.body.appendChild(menu._box);
            this._container.style.height = parseInt(this._container.style.height, 10) - tw_Dialog.menuBarHeight + "px";
        }
    },

    getMenu: function() {
        return this._menu;
    },

    setTitle: function(title) {
        document.title = title.length > 0 ? title : "(Untitled ThinWire Application)";
    },

    getStandardButton: function() {
        return this._standardButton;
    },

    setStandardButton: function(standardButton) {
        this._standardButton = standardButton;
    },

    _clickListener: tw_Component.clickListener,

    destroy: function() {
        if (tw_Frame.active == this) tw_Frame.active = null;
        document.body.removeChild(this._modalLayer);
        document.body.removeChild(this._box);
        this._menu = this._standardButton = this._modalLayer = this._modalDialogIds = null;
        arguments.callee.$.call(this);
        tw_shutdownInstance("The application instance has shutdown. Press F5 to restart the application or close the browser to end your session.");
    }
});

tw_Frame.active = null;
<commit_msg>* Fixed an issue causing the text carrot cursor to appear when hovering over a   menu.<commit_after>/*
#IFNDEF ALT_LICENSE
                           ThinWire(R) RIA Ajax Framework
                 Copyright (C) 2003-2007 Custom Credit Systems

  This library is free software; you can redistribute it and/or modify it under
  the terms of the GNU Lesser General Public License as published by the Free
  Software Foundation; either version 2.1 of the License, or (at your option) any
  later version.

  This library 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 Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public License along
  with this library; if not, write to the Free Software Foundation, Inc., 59
  Temple Place, Suite 330, Boston, MA 02111-1307 USA

  Users who would rather have a commercial license, warranty or support should
  contact the following company who invented, built and supports the technology:

                Custom Credit Systems, Richardson, TX 75081, USA.
                email: info@thinwire.com    ph: +1 (888) 644-6405
                            http://www.thinwire.com
#ENDIF
#IFDEF ALT_LICENSE
#LICENSE_HEADER#
#ENDIF
#VERSION_HEADER#
*/
//TODO: What does enabled and visible do on a Frame?
//TODO: X & Y do not currently work on a Frame.
//TODO: Focus does not fire on any container
var tw_Frame = tw_BaseContainer.extend({
    _resizeInProgress: false,
    _resizeTimerId: null,
    _menu: null,
    _standardButton: null,
    _modalLayer: null,
    _modalDialogIds: null,
    _focusBeforeDialog: null,

    construct: function(id, containerId, props) {
        arguments.callee.$.call(this, "frame", id, 0);
        this._fontBox = this._borderBox = null;

        var s = this._box.style;
        var cssText = "position:absolute;overflow:hidden;padding:0px;margin:0px;cursor:default;top:0px;left:0px;width:100%;height:100%;";
        tw_Component.setCSSText(cssText, this._box);

        tw_Frame.active = this;
        this._modalDialogIds = [];

        this._backgroundBox = this._container = this._scrollBox = document.createElement("div");
        this._container.className = "container";
        var s = this._container.style;
        cssText = "position:absolute;overflow:hidden;z-index:0;width:100%;bottom:0px;";
        tw_Component.setCSSText(cssText, this._container);
        this._box.appendChild(this._container);

        this._modalLayer = document.createElement("div");
        var s = this._modalLayer.style;
        cssText = "display:none;position:absolute;height:100%;width:100%;z-index:1;";
        tw_Component.setCSSText(cssText, this._modalLayer);
        tw_setLayerTransparent(this._modalLayer);

        tw_addEventListener(this._modalLayer, "mousedown", this._modalLayerMouseDownListener);
        document.body.appendChild(this._modalLayer);

        this._getFrameBounds = this._getFrameBounds.bind(this);
        tw_addEventListener(this._box, "mousedown", this._mouseDownListener.bind(this));
        tw_addEventListener(window, "resize", this._windowBoundsListener.bind(this));
        tw_addEventListener(this._box, ["click", "dblclick"], this._clickListener.bind(this));
        this.init(-1, props);

        var s = document.body.style;
        s.height = "100%";
        s.padding = "0px";
        s.margin = "0px";
        s.border = "0px";

        //NOTE: IE will fire this on load via the windowBoundListener
        if (!tw_isIE) this._getFrameBounds();
    },

    _getFrameBounds: function() {
        var innerWidth = document.body.clientWidth;
        var innerHeight = tw_getVisibleHeight();

        if (window.outerWidth) {
            var outerWidth = window.outerWidth;
            var outerHeight = window.outerHeight;
        } else {
            try {
                this._resizeTimerId = null;
                this._resizeInProgress = true;
                window.resizeTo(innerWidth, innerHeight);
                var outerWidth = innerWidth + (innerWidth - document.body.clientWidth);
                var outerHeight = innerHeight + (innerHeight - tw_getVisibleHeight());
                window.resizeTo(outerWidth, outerHeight);
                setTimeout(function() { this._resizeInProgress = false; }.bind(this), 250);
            } catch (e) {
                this._resizeInProgress = false;
                this._resizeTimerId = setTimeout(this._getFrameBounds, 100);
                return;
            }
        }

        this._width = innerWidth;
        this._height = innerHeight - (this._menu != null ? tw_Dialog.menuBarHeight : 0);
        this._container.style.height = this._height + "px";
        tw_em.sendViewStateChanged(this._id, "frameSize", innerWidth + "," + innerHeight + "," + outerWidth + "," + outerHeight);
    },

    _modalLayerMouseDownListener: function() {
        tw_Dialog.active.setActive(true, true);
    },

    _mouseDownListener: function(event) {
        var target = tw_getEventTarget(event);
        if (target == null || target.className == undefined) return;
        while (target != null && target.className != "dialog" && target.className != "frame" && target.className != "mainMenu") target = target.parentNode;

        if (target != null && target.className != "dialog" && target.parentNode.className != "dialog") {
            if (tw_Dialog.active != null) tw_Dialog.active.setActive(false);
            if (tw_Frame.active.getMenu() != null && target.className != "mainMenu") tw_Frame.active.getMenu().close();
        }
    },

    _windowBoundsListener: function(event) {
        if (this._resizeInProgress) return;
        if (this._resizeTimerId != null) clearTimeout(this._resizeTimerId);
        this._resizeTimerId = setTimeout(this._getFrameBounds, 0);
    },

    isModalLayerVisible: function() {
        return this._modalLayer.style.display != "none";
    },

    setModalLayerVisible: function(state, dialog) {
        if (state) {
            this._focusBeforeDialog = tw_Component.currentFocus;
            tw_Component.currentFocus = null;
            if (this._modalDialogIds.length == 0) this._modalLayer.style.display = "block";
            this._modalLayer.style.zIndex = ++tw_Component.zIndex;
            this._modalDialogIds.push(dialog);
        } else {
            for (var i = 0, cnt = this._modalDialogIds.length; i < cnt; i++) {
                if (this._modalDialogIds[i] === dialog) {
                    this._modalDialogIds.splice(i, 1);
                    break;
                }
            }

            if (this._modalDialogIds.length == 0) {
                this._modalLayer.style.display = "none";
            } else {
                this._modalDialogIds[this._modalDialogIds.length - 1].setActive(true);
            }

            //This would be the case if the component got destroyed while the dialog was visible.
            if (this._focusBeforeDialog != null && this._focusBeforeDialog._box != null) tw_Component.currentFocus = this._focusBeforeDialog;
            this._focusBeforeDialog = null;
        }
    },

    getOffsetY: function() {
        return arguments.callee.$.call(this) + (this.getMenu() != null ? tw_Dialog.menuBarHeight : 0);
    },

    setX: function() { },
    setY: function() { },
    setWidth: function() { },
    setHeight: function() { },

    keyPressNotify: tw_BaseContainer.keyPressNotifyCtrlEnterButton,

    setMenu: function(menu) {
        if (this._menu != null) {
            this._container.style.height = parseInt(this._container.style.height, 10) + tw_Dialog.menuBarHeight + "px";
            this._box.removeChild(this._menu._box);
        }

        this._menu = menu;

        if (menu instanceof tw_Menu) {
			// All components inherit this style from the frame, but since the menu is not actually
			//  attached to the frame in the DOM, the style doesn't cascade down.
			menu._box.style.cursor = "default";
			document.body.appendChild(menu._box);
            this._container.style.height = parseInt(this._container.style.height, 10) - tw_Dialog.menuBarHeight + "px";
        }
    },

    getMenu: function() {
        return this._menu;
    },

    setTitle: function(title) {
        document.title = title.length > 0 ? title : "(Untitled ThinWire Application)";
    },

    getStandardButton: function() {
        return this._standardButton;
    },

    setStandardButton: function(standardButton) {
        this._standardButton = standardButton;
    },

    _clickListener: tw_Component.clickListener,

    destroy: function() {
        if (tw_Frame.active == this) tw_Frame.active = null;
        document.body.removeChild(this._modalLayer);
        document.body.removeChild(this._box);
        this._menu = this._standardButton = this._modalLayer = this._modalDialogIds = null;
        arguments.callee.$.call(this);
        tw_shutdownInstance("The application instance has shutdown. Press F5 to restart the application or close the browser to end your session.");
    }
});

tw_Frame.active = null;
<|endoftext|>


<commit_before>console.log (5+4)
alert("U start nu de log")
nameAsk();
datumAsk();
modemAsk();
klachtAsk();
function nameAsk() {
	var naam = prompt("Geef de naam");
	if (naam.length === 0){
		alert("Geen naam gegeven");
		nameAsk();
	}
	else {
		document.write('');
		document.write(naam);
		document.write("");
		document.write("
");
	}
}

function datumAsk() {
	var datum = prompt("Geef de datum (dd-mm-jjjj)");
	if (datum.length <= 9) {
		alert("Geef een geldige datum op");
		datumAsk();
	}
	else{
		document.write(datum);
		document.write("
");
	}
}

function modemAsk() {
	var modem = prompt("Wat voor type modem gebruikt de klant?");
	if (modem.length === 0){
		alert("Geef een geldige modem op");
		modemAsk();
	}
	else{
		document.write(modem);
		document.write("
");
	}
}

function klachtAsk() {
	var klachtCheck = confirm("Heeft de klant een klacht?");
	if (klachtCheck = true){
		var browsen = prompt("Kunt u browsen naar www.nu.nl?");
		if (klacht.length === 0){
			alert("Geef een geldige klacht op");
			klachtAsk();
		}
		else{
			document.write(browsen);
			document.write("
");
		}
	}
	else{
		document.write(naam + datum + modem + klachtCheck);
	}
}<commit_msg>did some removal and cleanup still messy<commit_after>console.log (5+4)
alert("U start nu de log")
nameAsk();
datumAsk();
modemAsk();
klachtAsk();
function nameAsk() {
	var naam = prompt("Geef de naam");
	if (naam.length === 0){
		alert("Geen naam gegeven");
		nameAsk();
	}
	else {
		document.write('');
		document.write(naam);
		document.write("");
		document.write("
");
	}
}

function datumAsk() {
	var datum = prompt("Geef de datum (dd-mm-jjjj)");
	if (datum.length <= 9) {
		alert("Geef een geldige datum op");
		datumAsk();
	}
	else{
		document.write(datum);
		document.write("
");
	}
}

function modemAsk() {
	var modem = prompt("Wat voor type modem gebruikt de klant?");
	if (modem.length === 0){
		alert("Geef een geldige modem op");
		modemAsk();
	}
	else{
		document.write(modem);
		document.write("
");
	}
}

function klachtAsk() {
	var klachtCheck = confirm("Heeft de klant een klacht?");
	if (klachtCheck = true){
		var browsen = prompt("Kunt u browsen naar www.nu.nl?");
		if (klacht.length === 0){
			alert("Geef een geldige klacht op");
			klachtAsk();
		}
		else{
			document.write(browsen);
			document.write("
");
		}
	}
	else{

	}
}<|endoftext|>


<commit_before>var margin = {
  top: 20,
  right: 80,
  bottom: 30,
  left: 50
}

var width = 960 - margin.left - margin.right;
var height = 500 - margin.top - margin.bottom;

var parseDate = d3.time.format('%Y%m%d').parse;

var x = d3.time.scale()
  .range([0, width]);

var y = d3.scale.linear()
  .range([height, 0]);

var color = d3.scale.category10();

var xAxis = d3.svg.axis()
  .scale(x)
  .orient('bottom')

var yAxis = d3.svg.axis()
  .scale(y)
  .orient('left')

var line = d3.svg.line()
  .interpolate('basis')
  .x(function(d) {
    return x(d.date);
  })
  .y(function(d) {
    return y(d.temperature);
  })

var svg = d3.select('body')
  .append('svg')
  .attr('height', height + margin.top + margin.bottom)
  .attr('width', width + margin.left + margin.right)
  .append('g')
  .attr('transform', 'translate(' + margin.left + ','
    + margin.right + ')')

d3.csv('temps.csv', function(error, data) {
  //color.domain(
   //console.log(data);
    color
      .domain(d3.keys(data[0])
          .filter(function(key) {
            return key !== 'date';
          }));

    data.forEach(function(d) {
      d.date = parseDate(d.date);
    });

    var cities = color.domain().map(function(name) {
      return {
        name: name,
        values: data.map(function(d) {
          return {
            date: d.date,
            temperature: +d[name]
          };
        })
      }
    });

    x.domain(d3.extent(function(d) {
      return d.date;
    }));

    y.domain([
      d3.min(cities, function(c) {
        return d3.min(c.values, function(v) {
          return v.temperature;
        })
      }),
      d3.max(cities, function(c) {
        return d3.max(c.values, function(v) {
          return v.temperature;
        })
      })]);

    svg.append('g')
      .attr('class', 'x axis')
      .attr('transform', 'translate(0,' + height + ')')
      .call(xAxis);

    svg.append('g')
      .attr('class', 'y axis')
      .call(yAxis)
      .append('text')
      .attr('transform', 'rotate(-90)')
      .attr('y', 6)
      .attr('dy', '.71em')
      .style('text-anchor', 'end')
      .text('Temperature (degrees F)')

    var city = svg.selectAll('.city')
      .data(cities)
}); // end d3.csv()
<commit_msg>completes another line chart warmup<commit_after>var margin = {top: 20, right: 80, bottom: 30, left: 50},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var parseDate = d3.time.format("%Y%m%d").parse;

var x = d3.time.scale()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height, 0]);

var color = d3.scale.category10();

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

var line = d3.svg.line()
    .interpolate("basis")
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.temperature); });

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.csv("temps.csv", function(error, data) {
  color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; }));

  data.forEach(function(d) {
    d.date = parseDate(d.date);
  });

  var cities = color.domain().map(function(name) {
    return {
      name: name,
      values: data.map(function(d) {
        return {date: d.date, temperature: +d[name]};
      })
    };
  });

  x.domain(d3.extent(data, function(d) { return d.date; }));

  y.domain([
    d3.min(cities, function(c) { return d3.min(c.values, function(v) { return v.temperature; }); }),
    d3.max(cities, function(c) { return d3.max(c.values, function(v) { return v.temperature; }); })
  ]);

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Temperature (ºF)");

  var city = svg.selectAll(".city")
      .data(cities)
    .enter().append("g")
      .attr("class", "city");

  city.append("path")
      .attr("class", "line")
      .attr("d", function(d) { return line(d.values); })
      .style("stroke", function(d) { return color(d.name); });

  city.append("text")
      .datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
      .attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.temperature) + ")"; })
      .attr("x", 3)
      .attr("dy", ".35em")
      .text(function(d) { return d.name; });
});

//var margin = {
//  top: 20,
//  right: 80,
//  bottom: 30,
//  left: 50
//}
//
//var width = 960 - margin.left - margin.right;
//var height = 500 - margin.top - margin.bottom;
//
//var parseDate = d3.time.format('%Y%m%d').parse;
//
//var x = d3.time.scale()
//  .range([0, width]);
//
//var y = d3.scale.linear()
//  .range([height, 0]);
//
//var color = d3.scale.category10();
//
//var xAxis = d3.svg.axis()
//  .scale(x)
//  .orient('bottom')
//
//var yAxis = d3.svg.axis()
//  .scale(y)
//  .orient('left')
//
//var line = d3.svg.line()
//  .interpolate('basis')
//  .x(function(d) {
//    return x(d.date);
//  })
//  .y(function(d) {
//    return y(d.temperature);
//  })
//
//var svg = d3.select('body')
//  .append('svg')
//  .attr('height', height + margin.top + margin.bottom)
//  .attr('width', width + margin.left + margin.right)
//  .append('g')
//  .attr('transform', 'translate(' + margin.left + ','
//    + margin.right + ')')
//
//d3.csv('temps.csv', function(error, data) {
//    color
//      .domain(d3.keys(data[0])
//          .filter(function(key) {
//            return key !== 'date';
//          }));
//
//    data.forEach(function(d) {
//      d.date = parseDate(d.date);
//    });
//
//    var cities = color.domain().map(function(name) {
//      return {
//        name: name,
//        values: data.map(function(d) {
//          return {
//            date: d.date,
//            temperature: +d[name]
//          };
//        })
//      }
//    });
//
//    x.domain(d3.extent(function(d) {
//      return d.date;
//    }));
//
//    y.domain([
//      d3.min(cities, function(c) {
//        return d3.min(c.values, function(v) {
//          return v.temperature;
//        });
//      }),
//      d3.max(cities, function(c) {
//        return d3.max(c.values, function(v) {
//          return v.temperature;
//        });
//      })]);
//
//    svg.append('g')
//      .attr('class', 'x axis')
//      .attr('transform', 'translate(0,' + height + ')')
//      .call(xAxis);
//
//    svg.append('g')
//      .attr('class', 'y axis')
//      .call(yAxis)
//      .append('text')
//      .attr('transform', 'rotate(-90)')
//      .attr('y', 6)
//      .attr('dy', '.71em')
//      .style('text-anchor', 'end')
//      .text('Temperature (degrees F)')
//
//    var city = svg.selectAll('.city')
//      .data(cities)
//      .enter()
//        .append('g')
//        .attr('class', 'city')
//
//    city.append('path')
//      .attr('class', 'path')
//      .attr('d', function(d) {
//        return line(d.values);
//      })
//      .style('stroke', function(d) {
//        return color(d.name)
//      })
//
//
//
//}); // end d3.csv()
<|endoftext|>


<commit_before>/* eslint-disable camelcase, strict */
'use strict';

require('babel-core/register');

module.exports = {
  src_folders: ['./test'],
  output_folder: './logs/nightwatch',
  custom_commands_path: './test/util/nightwatch-commands',
  live_output: true,
  parallel_process_delay: 10,
  disable_colors: process.env.BUILDTYPE === 'production',
  test_workers: false,
  globals_path: './config/nightwatch-globals-sauce.js',
  test_settings: {
    'default': {
      launch_url: 'http://ondemand.saucelabs.com:80',
      filter: './test/**/*.e2e.spec.js',
      selenium_host: 'ondemand.saucelabs.com',
      selenium_port: 80,
      username: 'vetsdotgov',
      access_key: process.env.SAUCE_ACCESS_KEY,
      use_ssl: false,
      silent: true,
      output: true,
      screenshots: {
        enabled: false
      },
      desiredCapabilities: {
        recordVideo: true,
        recordScreenshots: true,
        recordLogs: true,
        captureHtml: true,
        seleniumVersion: '3.4.0'
      }
    },
    chrome: {
      desiredCapabilities: {
        browserName: 'chrome',
        platform: 'macOS 10.12',
        version: '59.0'
      }
    },
    firefox: {
      desiredCapabilities: {
        browserName: 'firefox',
        platform: 'macOS 10.12',
        version: '54.0'
      }
    },
    ie: {
      desiredCapabilities: {
        browserName: 'internet explorer',
        platform: 'Windows 10',
        version: '11.103'
      }
    },
    edge: {
      desiredCapabilities: {
        browserName: 'MicrosoftEdge',
        platform: 'Windows 10',
        version: '15.15063'
      }
    },
    safari: {
      desiredCapabilities: {
        browserName: 'safari',
        platform: 'macOS 10.12',
        version: '10.0'
      }
    },
    ios: {
      desiredCapabilities: {
        appiumVersion: '1.6.5',
        deviceName: 'iPhone 7 Simulator',
        deviceOrientation: 'portrait',
        platformVersion: '10.3',
        platformName: 'iOS',
        browserName: 'Safari'
      }
    },
    android: {
      desiredCapabilities: {
        appiumVersion: '1.6.5',
        deviceName: 'Android Emulator',
        deviceOrientation: 'portrait',
        platformVersion: '6.0',
        platformName: 'Android',
        browserName: 'Chrome'
      }
    }
  }
};
<commit_msg>Add selenium port option (#6145)<commit_after>/* eslint-disable camelcase, strict */
'use strict';

require('babel-core/register');

module.exports = {
  src_folders: ['./test'],
  output_folder: './logs/nightwatch',
  custom_commands_path: './test/util/nightwatch-commands',
  live_output: true,
  parallel_process_delay: 10,
  disable_colors: process.env.BUILDTYPE === 'production',
  test_workers: false,
  globals_path: './config/nightwatch-globals-sauce.js',
  test_settings: {
    'default': {
      launch_url: 'http://ondemand.saucelabs.com:80',
      filter: './test/**/*.e2e.spec.js',
      selenium_host: 'ondemand.saucelabs.com',
      selenium_port: 80,
      username: 'vetsdotgov',
      access_key: process.env.SAUCE_ACCESS_KEY,
      use_ssl: false,
      silent: true,
      output: true,
      screenshots: {
        enabled: false
      },
      desiredCapabilities: {
        recordVideo: true,
        recordScreenshots: true,
        recordLogs: true,
        captureHtml: true,
        seleniumVersion: '3.4.0'
      },
      selenium: {
        port: process.env.SELENIUM_PORT || 4444
      }
    },
    chrome: {
      desiredCapabilities: {
        browserName: 'chrome',
        platform: 'macOS 10.12',
        version: '59.0'
      }
    },
    firefox: {
      desiredCapabilities: {
        browserName: 'firefox',
        platform: 'macOS 10.12',
        version: '54.0'
      }
    },
    ie: {
      desiredCapabilities: {
        browserName: 'internet explorer',
        platform: 'Windows 10',
        version: '11.103'
      }
    },
    edge: {
      desiredCapabilities: {
        browserName: 'MicrosoftEdge',
        platform: 'Windows 10',
        version: '15.15063'
      }
    },
    safari: {
      desiredCapabilities: {
        browserName: 'safari',
        platform: 'macOS 10.12',
        version: '10.0'
      }
    },
    ios: {
      desiredCapabilities: {
        appiumVersion: '1.6.5',
        deviceName: 'iPhone 7 Simulator',
        deviceOrientation: 'portrait',
        platformVersion: '10.3',
        platformName: 'iOS',
        browserName: 'Safari'
      }
    },
    android: {
      desiredCapabilities: {
        appiumVersion: '1.6.5',
        deviceName: 'Android Emulator',
        deviceOrientation: 'portrait',
        platformVersion: '6.0',
        platformName: 'Android',
        browserName: 'Chrome'
      }
    }
  }
};
<|endoftext|>