<commit_before>var typeOf = require('./typeOf.js'),
    servicesAdapter = require('misc/servicesAdapter.js');

var acceptedFunctions = [Number, String, Boolean, Date, Array, Object],
    acceptedFunctionsLiteral = ['Number', 'String', 'Boolean', 'Date', 'Array', 'Object'];

function noop() {}

function getFunctionName(func) {
    var name;

    if (func.name === undefined) {
        name = func.toString();
        name = name.substr('function '.length + 1);
        name = name.match(/^[^\(]*/)[0];
    } else {
        name = func.name;
    }

    return name;
}

var Extends = require('./EventEmitter.class.js');
var Class = {
    "init": function init(id) {
        this._id = id;
        this.Super();
    },
    "__init": function __init() {   // used by the init function and removeAll since they act similarly
        function Attributes() {}
        function Changed() {}

        Attributes.prototype = this._defaults;
        this._attributes = Changed.prototype = new Attributes();
        this._changed = new Changed();
    },
    "__keys": null,
    "_defaults": null,
    "_attributes": null,
    "_changed": null,
    "_casting": false,
    "_service": null,
    "_validators": null,
    "_id": null,
    "muted": false,
    "getId": function () {
        return this._id;
    },
    "_setDefaults": function (defaults) {
        var key;

        this.__keys = [];
        for (key in defaults) {
            if (typeof key === 'object'
                || (typeof key === 'function'
                    && acceptedFunctions.indexOf(key) === -1)
                ) {
                throw new TypeError('A model can only contain native types.'
                    + '\nIf you want to save a reference, you should store the ID');
            }
            this.__keys.push(key);
        }
        this._defaults = defaults;
        this.__init();
    },
    "set": function set(key, value) {
        var map,
            self = this;

        function doSet(key, value) {
            var castingFunc,
                defaultValue,
                expectedType,
                actualType;

            if (self.__keys.indexOf(key) === -1) {
                throw new Error('Unknown property ' + key);
            }
            if (value === null || value === undefined) {
                value = null;
            } else if (self._casting) {
                defaultValue = self.__defaults[key];
                if (defaultValue) {
                    expectedType = typeOf(defaultValue);
                    actualType = typeOf(value);
                    if (expectedType === 'Function') {
                        expectedType = getFunctionName(defaultValue);
                    }
                    if (actualType !== expectedType) {
                        castingFunc = acceptedFunctionsLiteral.indexOf(expectedType);
                        castingFunc = acceptedFunctions[castingFunc];
                        if (castingFunc === Date) {
                            value = new castingFunc(Number(value));
                        } else {
                            value = castingFunc(value);
                        }
                    }
                }
            }
            self.__changed[key] = value;
        }

        if (arguments.length === 1 && typeof key === 'object') {
            map = key;
            for (key in map) {if(map.hasOwnProperty(key)) {
                doSet(key, map[key]);
            }}
        } else {
            doSet(key, value);
        }

        if (!this.muted) {
            this.Super.emit('change');
        }
    },
    "get": function get(key) {
        var result,
            i, l;

        function checkSingleResult(result) {
            if (typeof result === 'function') { // IF TRUE: Its a constructor function, thus a default value
                result = null;
            }

            return result;
        }

        if (arguments.length === 0) {
            arguments = this.__keys;
        }
        if (arguments.length === 1) {
            result = this._changed[key];
            result = checkSingleResult(result);
        } else {
            result = {};
            for (i = 0, l = arguments.length; i < l; i++) {
                key = arguments[i];
                result[key] = checkSingleResult(this._changed[key]);
            }
        }

        return result;
    },
    "escape": function escape(key) {
        var result,
            i, l;

        function doEscape(value) {
            if (value === undefined || value === null) {
                return '';
            } else if (typeof value === 'function') { // IF TRUE: Its a constructor function, thus a default value
                return '';
            } else if (value instanceof Date) {
                return String(value.getTime());
            }

            value = String(value); // cast to string

            // These replace patterns are taken from the great Backbone.js
            // project. Please check out: http://documentcloud.github.com/backbone/
            return value.replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&')
                .replace(/</g, '<')
                .replace(/>/g, '>')
                .replace(/"/g, '"')
                .replace(/'/g, ''')
                .replace(/\//g,'/');
        }

        if (arguments.length === 0) {
            arguments = this.__keys;
        }
        if (arguments.length === 1) {
            result = doEscape(this._changed[key]);
        } else {
            result = {};
            for (i = 0, l = arguments.length; i < l; i++) {
                key = arguments[i];
                result[key] = doEscape(this._changed[key]);
            }
        }

        return result;
    },
    "remove": function remove(key) {
        var i, l;

        for (i = 0, l = arguments.length; i < l; i++) {
            key = arguments[i];
            delete this._changed[key];
            delete this._attributes[key];
        }
        if (!this.muted) {
            this.Super.emit('change');
        }
    },
    "removeAll": function removeAll() {
        this.__init();
        if (!this.muted) {
            this.Super.emit('change');
        }
    },
    "unset": function unset(key) {
        var i, l;

        for (i = 0, l = arguments.length; i < l; i++) {
            key = arguments[i];
            delete this._changed[key];
        }
        if (!this.muted) {
            this.Super.emit('change');
        }
    },
    "unsetAll": function unsetAll() {
        var key,
            changed = this._changed;

        for (key in changed) { if (changed.hasOwnProperty(key)) {
            delete changed[key];
        }}
        if (!this.muted) {
            this.Super.emit('change');
        }
    },
    "hasChanged": function hasChanged(key) {
        var result = false,
            strict = false,
            changed = this._changed,
            attributes = this._attributes,
            argsLength = arguments.length,
            arr,
            checkFunc,
            i, l;

        function doNormalCheck() {
            return changed[key] !== attributes[key];
        }

        function doStrictCheck() {
            return changed.hasOwnProperty(key);
        }

        if (argsLength === 0) {
            arr = this.__keys;
        } else if(argsLength === 1 && typeof key === 'boolean') {
            strict = true;
            arr = this.__keys;
        } else {
            if (typeof arguments[argsLength - 1] === 'boolean') {
                strict = arguments[argsLength - 1];
                arr = Array.prototype.slice.call(arguments, 0, -1);
            }
            arr = arguments;
        }
        if (strict) {
            checkFunc = doStrictCheck;
        } else {
            checkFunc = doNormalCheck;
        }
        for (i = 0, l = arr.length; i < l; i++) {
            key = arr[i];
            result = checkFunc();
            if (result) {
                break;
            }
        }

        return result;
    },
    "isDefault": function isDefault(key) {
        var result = false,
            strict = false,
            changed = this._changed,
            attributes = this._attributes,
            defaults = this._defaults,
            argsLength = arguments.length,
            arr,
            checkFunc,
            i, l;

        function doNormalCheck() {
            return changed[key] === defaults[key];
        }

        function doStrictCheck() {
            return !changed.hasOwnProperty(key)
                && !attributes.hasOwnProperty(key);
        }

        if (argsLength === 0) {
            arr = this.__keys;
        } else if(argsLength === 1 && typeof key === 'boolean') {
            strict = true;
            arr = this.__keys;
        } else {
            if (typeof arguments[argsLength - 1] === 'boolean') {
                strict = arguments[argsLength - 1];
                arr = Array.prototype.slice.call(arguments, 0, -1);
            }
            arr = arguments;
        }
        if (strict) {
            checkFunc = doStrictCheck;
        } else {
            checkFunc = doNormalCheck;
        }
        for (i = 0, l = arr.length; i < l; i++) {
            key = arr[i];
            result = checkFunc();
            if (!result) {
                break;
            }
        }

        return result;
    },
    "getDefaults": function getDefaults() {
        return this._defaults;
    },
    "toJSON": function toJSON() {
        var keys = this.__keys,
            key,
            result = {},
            i, l;

        function doEscape(value) {
            if (value === undefined || value === null) {
                return null;
            } else if (typeof value === 'function') { // IF TRUE: Its a constructor function, thus a default value
                return null;
            } else if (value instanceof Date) {
                return value.getTime();
            } else {
                return value;
            }
        }

        for (i = 0, l = keys.length; i < l; i++) {
            key = keys[i];
            result[key] = doEscape(this._changed[key]);
        }

        return result;
    },
    "validate": function validate(clientOnly, callback) {
        var validators = this._validators,
            type,
            i = 0,
            self = this,
            finalResult = {
                "result": false
            };

        function finish() {
            finalResult.result = finalResult.client.result;
            if (finalResult.result === true && !clientOnly) {
                finalResult.result = finalResult.server.result === true;
            }
            if (!self.muted) {
               self.Super.emit('validate', finalResult);
            }
            callback(finalResult);
        }

        function onValidationResult(result) {
            finalResult[type] = result;
            if (result.result === true) {
                doValidation();
            } else {
                finish();
            }
        }

        function doValidation() {
            if (i === 0) {
                type = 'client';
            } else if (i === 1 && !clientOnly) {
                type = 'server';
            } else {
                finish();

                return;
            }
            i++;
            validators[type].validate(self.id, self.toJSON(), onValidationResult);
        }

        if (!validators || (clientOnly && !validators.client) ||
                (!validators.client && !validators.server)) {
            throw new Error('Cannot validate: There is no validator available.');
        }
        if (typeof clientOnly === 'function') {
            callback = clientOnly;
            clientOnly = undefined;
        }
        if (clientOnly === undefined) {
            clientOnly = false;
        }
        if (callback === undefined) {
            callback = noop;
        }
        doValidation();
    },
    "fetch": function fetch(callback) {
        var service = this._service,
            id = this.id,
            self = this;

        function onServiceResult(code, response) {
            var err;

            response = servicesAdapter.GET(code, response);
            err = response[0];
            response = response[1];
            if (!err) {
                self.set(response);
            }
            callback(err);
        }

        if (!service) {
            console.error('Cannot fetch model: There is no service available.');

            return;
        }

        if (id === null && typeof console !== 'undefined') {
            console.error('Cannot fetch model: You havent specified an id.');

            return;
        }

        callback = callback || noop;
        service.GET(id, onServiceResult);
    },
    "save": function save(callback) {
        var service = this._service,
            self = this,
            id = this.id,
            method,
            model = this.toJSON();

        function onServiceResult(code, response) {
            var err;

            response = servicesAdapter[method](code, response);
            err = response[0];
            id = response[1];
            if (!err && id !== null) {
                self.id = id;
            }
            callback(err);
        }

        if (!service) {
            console.error('Cannot save model: There is no service available.');

            return;
        }
        callback = callback || noop;
        if (id === null) {
            method = 'POST';
            service.POST(model, onServiceResult);
        } else {
            method = 'PUT';
            service.PUT(id, model, onServiceResult);
        }
    },
    "destroy": function destroy(callback) {
        var service = this._service,
            id = this.id,
            self = this;

        function onServiceResult(code, response) {
            var err;

            err = servicesAdapter.DELETE(code, response);
            if (!err) {
                self.id = null;
            }
            callback(err);
        }

        if (!service) {
            console.error('Cannot destroy model: There is no service available.');

            return;
        }
        if (id === null && typeof console !== 'undefined') {
            console.error('Cannot destroy model: You can only destroy models that have an id.');
        }
        callback = callback || noop;
        service.DELETE(id, onServiceResult);
    },
    "_acceptCurrentState": function _acceptCurrentState() {
        var key,
            value,
            changed = this._changed,
            attributes = this._attributes;

        for (key in changed) { if(changed.hasOwnProperty(key)) {
            value = changed[key];
            attributes[key] = value;
            delete changed[key];
        }}
    }
};<commit_msg>changed visibility of defaults, attributes, changed back to private<commit_after>var typeOf = require('./typeOf.js'),
    servicesAdapter = require('misc/servicesAdapter.js');

var acceptedFunctions = [Number, String, Boolean, Date, Array, Object],
    acceptedFunctionsLiteral = ['Number', 'String', 'Boolean', 'Date', 'Array', 'Object'];

function noop() {}

function getFunctionName(func) {
    var name;

    if (func.name === undefined) {
        name = func.toString();
        name = name.substr('function '.length + 1);
        name = name.match(/^[^\(]*/)[0];
    } else {
        name = func.name;
    }

    return name;
}

var Extends = require('./EventEmitter.class.js');
var Class = {
    "init": function init(id) {
        this._id = id;
        this.Super();
    },
    "__init": function __init() {   // used by the init function and removeAll since they act similarly
        function Attributes() {}
        function Changed() {}

        Attributes.prototype = this.__defaults;
        this.__attributes = Changed.prototype = new Attributes();
        this.__changed = new Changed();
    },
    "__keys": null,
    "__defaults": null,
    "__attributes": null,
    "__changed": null,
    "_casting": false,
    "_service": null,
    "_validators": null,
    "_id": null,
    "muted": false,
    "getId": function () {
        return this._id;
    },
    "_setDefaults": function (defaults) {
        var key;

        this.__keys = [];
        for (key in defaults) {
            if (typeof key === 'object'
                || (typeof key === 'function'
                    && acceptedFunctions.indexOf(key) === -1)
                ) {
                throw new TypeError('A model can only contain native types.'
                    + '\nIf you want to save a reference, you should store the ID');
            }
            this.__keys.push(key);
        }
        this.__defaults = defaults;
        this.__init();
    },
    "set": function set(key, value) {
        var map,
            self = this;

        function doSet(key, value) {
            var castingFunc,
                defaultValue,
                expectedType,
                actualType;

            if (self.__keys.indexOf(key) === -1) {
                throw new Error('Unknown property ' + key);
            }
            if (value === null || value === undefined) {
                value = null;
            } else if (self._casting) {
                defaultValue = self.__defaults[key];
                if (defaultValue) {
                    expectedType = typeOf(defaultValue);
                    actualType = typeOf(value);
                    if (expectedType === 'Function') {
                        expectedType = getFunctionName(defaultValue);
                    }
                    if (actualType !== expectedType) {
                        castingFunc = acceptedFunctionsLiteral.indexOf(expectedType);
                        castingFunc = acceptedFunctions[castingFunc];
                        if (castingFunc === Date) {
                            value = new castingFunc(Number(value));
                        } else {
                            value = castingFunc(value);
                        }
                    }
                }
            }
            self.__changed[key] = value;
        }

        if (arguments.length === 1 && typeof key === 'object') {
            map = key;
            for (key in map) {if(map.hasOwnProperty(key)) {
                doSet(key, map[key]);
            }}
        } else {
            doSet(key, value);
        }

        if (!this.muted) {
            this.Super.emit('change');
        }
    },
    "get": function get(key) {
        var result,
            i, l;

        function checkSingleResult(result) {
            if (typeof result === 'function') { // IF TRUE: Its a constructor function, thus a default value
                result = null;
            }

            return result;
        }

        if (arguments.length === 0) {
            arguments = this.__keys;
        }
        if (arguments.length === 1) {
            result = this.__changed[key];
            result = checkSingleResult(result);
        } else {
            result = {};
            for (i = 0, l = arguments.length; i < l; i++) {
                key = arguments[i];
                result[key] = checkSingleResult(this.__changed[key]);
            }
        }

        return result;
    },
    "escape": function escape(key) {
        var result,
            i, l;

        function doEscape(value) {
            if (value === undefined || value === null) {
                return '';
            } else if (typeof value === 'function') { // IF TRUE: Its a constructor function, thus a default value
                return '';
            } else if (value instanceof Date) {
                return String(value.getTime());
            }

            value = String(value); // cast to string

            // These replace patterns are taken from the great Backbone.js
            // project. Please check out: http://documentcloud.github.com/backbone/
            return value.replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&')
                .replace(/</g, '<')
                .replace(/>/g, '>')
                .replace(/"/g, '"')
                .replace(/'/g, ''')
                .replace(/\//g,'/');
        }

        if (arguments.length === 0) {
            arguments = this.__keys;
        }
        if (arguments.length === 1) {
            result = doEscape(this.__changed[key]);
        } else {
            result = {};
            for (i = 0, l = arguments.length; i < l; i++) {
                key = arguments[i];
                result[key] = doEscape(this.__changed[key]);
            }
        }

        return result;
    },
    "remove": function remove(key) {
        var i, l;

        for (i = 0, l = arguments.length; i < l; i++) {
            key = arguments[i];
            delete this.__changed[key];
            delete this.__attributes[key];
        }
        if (!this.muted) {
            this.Super.emit('change');
        }
    },
    "removeAll": function removeAll() {
        this.__init();
        if (!this.muted) {
            this.Super.emit('change');
        }
    },
    "unset": function unset(key) {
        var i, l;

        for (i = 0, l = arguments.length; i < l; i++) {
            key = arguments[i];
            delete this.__changed[key];
        }
        if (!this.muted) {
            this.Super.emit('change');
        }
    },
    "unsetAll": function unsetAll() {
        var key,
            changed = this.__changed;

        for (key in changed) { if (changed.hasOwnProperty(key)) {
            delete changed[key];
        }}
        if (!this.muted) {
            this.Super.emit('change');
        }
    },
    "hasChanged": function hasChanged(key) {
        var result = false,
            strict = false,
            changed = this.__changed,
            attributes = this.__attributes,
            argsLength = arguments.length,
            arr,
            checkFunc,
            i, l;

        function doNormalCheck() {
            return changed[key] !== attributes[key];
        }

        function doStrictCheck() {
            return changed.hasOwnProperty(key);
        }

        if (argsLength === 0) {
            arr = this.__keys;
        } else if(argsLength === 1 && typeof key === 'boolean') {
            strict = true;
            arr = this.__keys;
        } else {
            if (typeof arguments[argsLength - 1] === 'boolean') {
                strict = arguments[argsLength - 1];
                arr = Array.prototype.slice.call(arguments, 0, -1);
            }
            arr = arguments;
        }
        if (strict) {
            checkFunc = doStrictCheck;
        } else {
            checkFunc = doNormalCheck;
        }
        for (i = 0, l = arr.length; i < l; i++) {
            key = arr[i];
            result = checkFunc();
            if (result) {
                break;
            }
        }

        return result;
    },
    "isDefault": function isDefault(key) {
        var result = false,
            strict = false,
            changed = this.__changed,
            attributes = this.__attributes,
            defaults = this.__defaults,
            argsLength = arguments.length,
            arr,
            checkFunc,
            i, l;

        function doNormalCheck() {
            return changed[key] === defaults[key];
        }

        function doStrictCheck() {
            return !changed.hasOwnProperty(key)
                && !attributes.hasOwnProperty(key);
        }

        if (argsLength === 0) {
            arr = this.__keys;
        } else if(argsLength === 1 && typeof key === 'boolean') {
            strict = true;
            arr = this.__keys;
        } else {
            if (typeof arguments[argsLength - 1] === 'boolean') {
                strict = arguments[argsLength - 1];
                arr = Array.prototype.slice.call(arguments, 0, -1);
            }
            arr = arguments;
        }
        if (strict) {
            checkFunc = doStrictCheck;
        } else {
            checkFunc = doNormalCheck;
        }
        for (i = 0, l = arr.length; i < l; i++) {
            key = arr[i];
            result = checkFunc();
            if (!result) {
                break;
            }
        }

        return result;
    },
    "getDefaults": function getDefaults() {
        return this.__defaults;
    },
    "toJSON": function toJSON() {
        var keys = this.__keys,
            key,
            result = {},
            i, l;

        function doEscape(value) {
            if (value === undefined || value === null) {
                return null;
            } else if (typeof value === 'function') { // IF TRUE: Its a constructor function, thus a default value
                return null;
            } else if (value instanceof Date) {
                return value.getTime();
            } else {
                return value;
            }
        }

        for (i = 0, l = keys.length; i < l; i++) {
            key = keys[i];
            result[key] = doEscape(this.__changed[key]);
        }

        return result;
    },
    "validate": function validate(clientOnly, callback) {
        var validators = this._validators,
            type,
            i = 0,
            self = this,
            finalResult = {
                "result": false
            };

        function finish() {
            finalResult.result = finalResult.client.result;
            if (finalResult.result === true && !clientOnly) {
                finalResult.result = finalResult.server.result === true;
            }
            if (!self.muted) {
               self.Super.emit('validate', finalResult);
            }
            callback(finalResult);
        }

        function onValidationResult(result) {
            finalResult[type] = result;
            if (result.result === true) {
                doValidation();
            } else {
                finish();
            }
        }

        function doValidation() {
            if (i === 0) {
                type = 'client';
            } else if (i === 1 && !clientOnly) {
                type = 'server';
            } else {
                finish();

                return;
            }
            i++;
            validators[type].validate(self.id, self.toJSON(), onValidationResult);
        }

        if (!validators || (clientOnly && !validators.client) ||
                (!validators.client && !validators.server)) {
            throw new Error('Cannot validate: There is no validator available.');
        }
        if (typeof clientOnly === 'function') {
            callback = clientOnly;
            clientOnly = undefined;
        }
        if (clientOnly === undefined) {
            clientOnly = false;
        }
        if (callback === undefined) {
            callback = noop;
        }
        doValidation();
    },
    "fetch": function fetch(callback) {
        var service = this._service,
            id = this.id,
            self = this;

        function onServiceResult(code, response) {
            var err;

            response = servicesAdapter.GET(code, response);
            err = response[0];
            response = response[1];
            if (!err) {
                self.set(response);
            }
            callback(err);
        }

        if (!service) {
            console.error('Cannot fetch model: There is no service available.');

            return;
        }

        if (id === null && typeof console !== 'undefined') {
            console.error('Cannot fetch model: You havent specified an id.');

            return;
        }

        callback = callback || noop;
        service.GET(id, onServiceResult);
    },
    "save": function save(callback) {
        var service = this._service,
            self = this,
            id = this.id,
            method,
            model = this.toJSON();

        function onServiceResult(code, response) {
            var err;

            response = servicesAdapter[method](code, response);
            err = response[0];
            id = response[1];
            if (!err && id !== null) {
                self.id = id;
            }
            callback(err);
        }

        if (!service) {
            console.error('Cannot save model: There is no service available.');

            return;
        }
        callback = callback || noop;
        if (id === null) {
            method = 'POST';
            service.POST(model, onServiceResult);
        } else {
            method = 'PUT';
            service.PUT(id, model, onServiceResult);
        }
    },
    "destroy": function destroy(callback) {
        var service = this._service,
            id = this.id,
            self = this;

        function onServiceResult(code, response) {
            var err;

            err = servicesAdapter.DELETE(code, response);
            if (!err) {
                self.id = null;
            }
            callback(err);
        }

        if (!service) {
            console.error('Cannot destroy model: There is no service available.');

            return;
        }
        if (id === null && typeof console !== 'undefined') {
            console.error('Cannot destroy model: You can only destroy models that have an id.');
        }
        callback = callback || noop;
        service.DELETE(id, onServiceResult);
    },
    "_acceptCurrentState": function _acceptCurrentState() {
        var key,
            value,
            changed = this.__changed,
            attributes = this.__attributes;

        for (key in changed) { if(changed.hasOwnProperty(key)) {
            value = changed[key];
            attributes[key] = value;
            delete changed[key];
        }}
    }
};<|endoftext|>


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

var RED = require("../../red/red");
var util = require("util");
var firmata = require("firmata");
var arduinoReady = false;
var thisboard = null;

// The Board Definition - this opens (and closes) the connection
function ArduinoNode(n) {
	RED.nodes.createNode(this,n);
	this.device = n.device;
	this.repeat = n.repeat||25;
	util.log("[firmata] Opening"+this.device);

//	var tou = setInterval(function() {
//		if (!arduinoReady) {
//			clearInterval(tou);

	arduinoReady = false;
	if (thisboard == null) {
		this.board = new firmata.Board(this.device, function(err) {
			if (err) {
				util.log("[firmata] "+err);
				return;
			}
			arduinoReady = true;
			util.log('[firmata] Arduino connected');
		});
		thisboard = this.board;
	}
	else {
		util.log("[firmata] Arduino already connected");
		this.board = thisboard;
		console.log(this.board._events);
		this.board.removeAllListeners();
		arduinoReady = true;
	}

//		} else { util.log("[firmata] Waiting for Firmata"); }
//	}, 1000); // wait for firmata to disconnect from arduino

	this._close = function() {
		//this.board.sp.close(function() { console.log("[firmata] Serial port closed"); arduinoReady = false; });
		util.log("[firmata] Stopped");
	}
}

RED.nodes.registerType("arduino-board",ArduinoNode);

ArduinoNode.prototype.close = function() {
	this._close();
}

// The Input Node
function DuinoNodeIn(n) {
	RED.nodes.createNode(this,n);
	this.buttonState = -1;
	this.pin = n.pin;
	this.state = n.state;
	this.arduino = n.arduino;
	this.serverConfig = RED.nodes.getNode(this.arduino);
	if (typeof this.serverConfig === "object") {
	this.board = this.serverConfig.board;
		this.repeat = this.serverConfig.repeat;
		var node = this;

		var tout = setInterval(function() {
			if (arduinoReady) {
				clearInterval(tout);
				console.log(node.state,node.pin,node.board.MODES[node.state]);
				node.board.pinMode(node.pin, node.board.MODES[node.state]);
				node.board.setSamplingInterval(node.repeat);
				var oldrdg = "";
				if (node.state == "ANALOG") {
					node.board.analogRead(node.pin, function(data) {
						var msg = {payload:data, topic:"A"+node.pin};
						if (data != oldrdg) {
							node.send(msg);
							oldrdg = data;
						}
					});
				}
				else {
					node.board.digitalRead(node.pin, function(data) {
						var msg = {payload:data, topic:node.pin};
						node.send(msg);
					});
				}
			}
			else { node.log("Waiting for Arduino"); }
		}, 2000); // loop to wait for firmata to connect to arduino

		this._close = function() {
			clearInterval(this._interval);
			util.log("[arduino] input eventlistener stopped");
		}
	}
	else {
		util.log("[arduino] Serial Port not Configured");
	}
}
RED.nodes.registerType("arduino in",DuinoNodeIn);

DuinoNodeIn.prototype.close = function() {
	this._close();
}

// The Output Node
function DuinoNodeOut(n) {
	RED.nodes.createNode(this,n);
	this.buttonState = -1;
	this.pin = n.pin;
	this.state = n.state;
	this.arduino = n.arduino;
	this.serverConfig = RED.nodes.getNode(this.arduino);
	if (typeof this.serverConfig === "object") {
		this.board = this.serverConfig.board;
		var node = this;

		this.on("input", function(msg) {
			//console.log(msg);
			if (arduinoReady) {
				if (node.state == "OUTPUT") {
					if ((msg.payload == true)||(msg.payload == 1)||(msg.payload.toString().toLowerCase() == "on")) {
						node.board.digitalWrite(node.pin, node.board.HIGH);
					}
					if ((msg.payload == false)||(msg.payload == 0)||(msg.payload.toString().toLowerCase() == "off")) {
						node.board.digitalWrite(node.pin, node.board.LOW);
					}
				}
				if (node.state == "PWM") {
					msg.payload = msg.payload * 1;
					if ((msg.payload >= 0) && (msg.payload <= 255)) {
						//console.log(msg.payload, node.pin);
						node.board.servoWrite(node.pin, msg.payload);
					}
				}
				if (node.state == "SERVO") {
					msg.payload = msg.payload * 1;
					if ((msg.payload >= 0) && (msg.payload <= 180)) {
						//console.log(msg.payload, node.pin);
						node.board.servoWrite(node.pin, msg.payload);
					}
				}
			}
			//else { console.log("Arduino not ready"); }
		});

		var touo = setInterval(function() {
			if (arduinoReady) {
				clearInterval(touo);
				//console.log(node.state,node.pin,node.board.MODES[node.state]);
				node.board.pinMode(node.pin, node.board.MODES[node.state]);
			}
		}, 5000); // loop to wait for firmata to connect to arduino
	}
	else {
		util.log("[arduino] Serial Port not Configured");
	}
}
RED.nodes.registerType("arduino out",DuinoNodeOut);
<commit_msg>added more debug / state checking to Arduino node<commit_after>/**
 * Copyright 2013 IBM Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

var RED = require("../../red/red");
var util = require("util");
var firmata = require("firmata");
var arduinoReady = false;
var thisboard = null;

// The Board Definition - this opens (and closes) the connection
function ArduinoNode(n) {
	RED.nodes.createNode(this,n);
	this.device = n.device;
	this.repeat = n.repeat||25;
	util.log("[firmata] Opening"+this.device);
	var node = this;

	node.toun = setInterval(function() {
		if (!arduinoReady) {
			arduinoReady = false;
			if (thisboard == null) {
				node.board = new firmata.Board(node.device, function(err) {
					if (err) {
						console.log("[firmata] error: ",err);
						return;
					}
					arduinoReady = true;
					thisboard = node.board;
					clearInterval(node.toun);
					util.log('[firmata] Arduino connected');
				});
			}
			else {
				util.log("[firmata] Arduino already connected");
				node.board = thisboard;
				console.log(node.board.sp);
				node.board.removeAllListeners();
				arduinoReady = true;
				clearInterval(node.toun);
			}
		} else { util.log("[firmata] Waiting for Firmata"); }
	}, 10000); // wait for firmata to connect to arduino

	this.on('close', function() {
		//this.board.sp.close(function() { console.log("[firmata] Serial port closed"); arduinoReady = false; });
		if (node.toun) {
			clearInterval(node.toun);
			util.log("[arduino] arduino wait loop stopped");
		}
		util.log("[firmata] Stopped");
	});
}
RED.nodes.registerType("arduino-board",ArduinoNode);

// The Input Node
function DuinoNodeIn(n) {
	RED.nodes.createNode(this,n);
	this.buttonState = -1;
	this.pin = n.pin;
	this.state = n.state;
	this.arduino = n.arduino;
	this.serverConfig = RED.nodes.getNode(this.arduino);
	if (typeof this.serverConfig === "object") {
	this.board = this.serverConfig.board;
		this.repeat = this.serverConfig.repeat;
		var node = this;

		node.toui = setInterval(function() {
			if (arduinoReady) {
				clearInterval(node.toui);
				console.log(node.state,node.pin,node.board.MODES[node.state]);
				node.board.pinMode(node.pin, node.board.MODES[node.state]);
				node.board.setSamplingInterval(node.repeat);
				var oldrdg = "";
				if (node.state == "ANALOG") {
					node.board.analogRead(node.pin, function(data) {
						var msg = {payload:data, topic:"A"+node.pin};
						if (data != oldrdg) {
							node.send(msg);
							oldrdg = data;
						}
					});
				}
				else {
					node.board.digitalRead(node.pin, function(data) {
						var msg = {payload:data, topic:node.pin};
						node.send(msg);
					});
				}
			}
			else { node.log("Waiting for Arduino"); }
		}, 5000); // loop to wait for firmata to connect to arduino

		this.on('close', function() {
			if (node.toui) {
				clearInterval(node.toui);
				util.log("[arduino] input wait loop stopped");
			}
		});
	}
	else {
		util.log("[arduino] Serial Port not Configured");
	}
}
RED.nodes.registerType("arduino in",DuinoNodeIn);

// The Output Node
function DuinoNodeOut(n) {
	RED.nodes.createNode(this,n);
	this.buttonState = -1;
	this.pin = n.pin;
	this.state = n.state;
	this.arduino = n.arduino;
	this.serverConfig = RED.nodes.getNode(this.arduino);
	if (typeof this.serverConfig === "object") {
		this.board = this.serverConfig.board;
		var node = this;

		this.on("input", function(msg) {
			//console.log(msg);
			if (arduinoReady) {
				if (node.state == "OUTPUT") {
					if ((msg.payload == true)||(msg.payload == 1)||(msg.payload.toString().toLowerCase() == "on")) {
						node.board.digitalWrite(node.pin, node.board.HIGH);
					}
					if ((msg.payload == false)||(msg.payload == 0)||(msg.payload.toString().toLowerCase() == "off")) {
						node.board.digitalWrite(node.pin, node.board.LOW);
					}
				}
				if (node.state == "PWM") {
					msg.payload = msg.payload * 1;
					if ((msg.payload >= 0) && (msg.payload <= 255)) {
						//console.log(msg.payload, node.pin);
						node.board.servoWrite(node.pin, msg.payload);
					}
				}
				if (node.state == "SERVO") {
					msg.payload = msg.payload * 1;
					if ((msg.payload >= 0) && (msg.payload <= 180)) {
						//console.log(msg.payload, node.pin);
						node.board.servoWrite(node.pin, msg.payload);
					}
				}
			}
			//else { console.log("Arduino not ready"); }
		});

		node.touo = setInterval(function() {
			if (arduinoReady) {
				clearInterval(node.touo);
				//console.log(node.state,node.pin,node.board.MODES[node.state]);
				node.board.pinMode(node.pin, node.board.MODES[node.state]);
			}
		}, 5000); // loop to wait for firmata to connect to arduino

		this.on('close', function() {
			if (node.touo) {
				clearInterval(node.touo);
				util.log("[arduino] output wait loop stopped");
			}
		});
	}
	else {
		util.log("[arduino] Serial Port not Configured");
	}
}
RED.nodes.registerType("arduino out",DuinoNodeOut);
<|endoftext|>


<commit_before>(function () {
  'use strict';

  angular
    .module('app.core')
    .factory('Specialization', Specialization);

  /** @ngInject */
  function Specialization(CacheFactory, Util) {
    const ini = 'SPC';

    const service = {
      all,
      get
    };

    return service;

    //////////

    async function all() {
      const snapshot = await firebase.database().ref(ini).once('value');

      return Util.many(snapshot);
    }

    async function get(id) {
      if (!id) {
        return null;
      }

      const snapshot = await firebase.database().ref(ini)
        .child(id)
        .once('value');

      return Util.one(snapshot);
    }
  }
})();
<commit_msg>feat: specialization cache<commit_after>(function () {
  'use strict';

  angular
    .module('app.core')
    .factory('Specialization', Specialization);

  /** @ngInject */
  function Specialization(CacheFactory, Util) {
    const ini = 'SPC';
    const cache = CacheFactory(ini);

    const service = {
      all,
      get
    };

    return service;

    //////////

    async function all() {
      const snapshot = await firebase.database().ref(ini).once('value');
      const list = Util.many(snapshot);

      return cache.put('all', list);
    }

    async function get(id) {
      if (!id) {
        return null;
      }

      const list = cache.get('all') || (await all());

      return _.find(list, ['_id', id]) || null;
    }
  }
})();
<|endoftext|>


<commit_before>function(args) {
/*
is_app(true)
control_type("VB")
display_name("3d control")
description("This will return the 3d container control")
base_component_id("threedee_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:     "text",
            name:   "Text",
            type:   "String"
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "hide_children",
            name:       "Hide Children?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
    ]
)//properties
logo_url("/driver_icons/threedee_control.png")
*/

    Vue.component("threedee_control",{
      props: ["args","design_mode", "refresh", "children","delete_component","select_component"]
      ,
      template:

`

        Detail editor

{{child_item.name}}

                <div    class='btn btn-danger'
                        v-bind:refresh='refresh'
                        v-if='child_item'
                        v-bind:style='"box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;padding:0px; z-index: 21474836;opacity:1;"  +
                        "width: 20px; height: 20px; line-height:20px;text-align: center;vertical-align: middle;margin-left: 20px;"'
                        v-on:click='$event.stopPropagation();delete_component(child_item.index_in_parent_array)'>

                        X

            <slot v-bind:refresh='refresh'>
            </slot>

`
         ,

        mounted: function() {
            if (!this.design_mode) {
                //var scene = document.querySelector('a-scene');
                //if (isValidObject(scene)) {
                    //scene.addEventListener('click', function () {

                        // Apply impulse;
                        //setTimeout(function () {
                            //var box = document.getElementById('left-box');
                            //var impulse = { x: 0, y: 10, z: 0 };
                            //var point = { x: 0.5, y: 0, z: 0 };
                            //box['physics-body'].applyImpulse(impulse, point);
                        //}, 25);
                    //});
                //}

            }
        }
      ,
      data: function() {
          return {
              msg: "Hello Yazz!",
              selected_index: null
          }
      }
    })
}
<commit_msg>Made the 3d container control larger by default<commit_after>function(args) {
/*
is_app(true)
control_type("VB")
display_name("3d control")
description("This will return the 3d container control")
base_component_id("threedee_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:     "text",
            name:   "Text",
            type:   "String"
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "hide_children",
            name:       "Hide Children?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    300,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    300,
            type:       "Number"
        }
    ]
)//properties
logo_url("/driver_icons/threedee_control.png")
*/

    Vue.component("threedee_control",{
      props: ["args","design_mode", "refresh", "children","delete_component","select_component"]
      ,
      template:

`

        Detail editor

{{child_item.name}}

                <div    class='btn btn-danger'
                        v-bind:refresh='refresh'
                        v-if='child_item'
                        v-bind:style='"box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;padding:0px; z-index: 21474836;opacity:1;"  +
                        "width: 20px; height: 20px; line-height:20px;text-align: center;vertical-align: middle;margin-left: 20px;"'
                        v-on:click='$event.stopPropagation();delete_component(child_item.index_in_parent_array)'>

                        X

            <slot v-bind:refresh='refresh'>
            </slot>

`
         ,

        mounted: function() {
            if (!this.design_mode) {
                //var scene = document.querySelector('a-scene');
                //if (isValidObject(scene)) {
                    //scene.addEventListener('click', function () {

                        // Apply impulse;
                        //setTimeout(function () {
                            //var box = document.getElementById('left-box');
                            //var impulse = { x: 0, y: 10, z: 0 };
                            //var point = { x: 0.5, y: 0, z: 0 };
                            //box['physics-body'].applyImpulse(impulse, point);
                        //}, 25);
                    //});
                //}

            }
        }
      ,
      data: function() {
          return {
              msg: "Hello Yazz!",
              selected_index: null
          }
      }
    })
}
<|endoftext|>


<commit_before>/** MIT License (c) copyright B Cavalier & J Hann */

/**
 * curl CommonJS Modules/1.1 loader
 *
 * Licensed under the MIT License at:
 * 		http://www.opensource.org/licenses/mit-license.php
 */

/**
 * @experimental
 */
(function (global, document, globalEval) {

define(/*=='curl/loader/cjsm11',==*/ function () {

	var head, insertBeforeEl /*, findRequiresRx, myId*/;

//	findRequiresRx = /require\s*\(\s*['"](\w+)['"]\s*\)/,

//	function nextId (index) {
//		var varname = '', part;
//		do {
//			part = index % 26;
//			varname += String.fromCharCode(part + 65);
//			index -= part;
//		}
//		while (index > 0);
//		return 'curl$' + varname;
//	}

//	/**
//	 * @description Finds the require() instances in the source text of a cjs
//	 * 	 module and collects them. If removeRequires is true, it also replaces
//	 * 	 them with a unique variable name. All unique require()'d module ids
//	 * 	 are assigned a unique variable name to be used in the define(deps)
//	 * 	 that will be constructed to wrap the cjs module.
//	 * @param source - source code of cjs module
//	 * @param moduleIds - hashMap (object) to receive pairs of moduleId /
//	 *   unique variable name
//	 * @param removeRequires - if truthy, replaces all require() instances with
//	 *   a unique variable
//	 * @return - source code of cjs module, possibly with require()s replaced
//	 */
//	function parseDepModuleIds (source, moduleIds, removeRequires) {
//		var index = 0;
//		// fast parse
//		source = source.replace(findRequiresRx, function (match, id) {
//			if (!moduleIds[id]) {
//				moduleIds[id] = nextId(index++);
//				moduleIds.push(id);
//			}
//			return removeRequires ? moduleIds[id] : match;
//		});
//		return source;
//	}

	head = document && (document['head'] || document.getElementsByTagName('head')[0]);
	// to keep IE from crying, we need to put scripts before any
	// <base> elements, but after any <meta>. this should do it:
	insertBeforeEl = head && head.getElementsByTagName('base')[0] || null;

	function wrapSource (source, resourceId, fullUrl) {
		var sourceUrl = fullUrl ? '////@ sourceURL=' + fullUrl.replace(/\s/g, '%20') + '.js' : '';
		return "define('" + resourceId + "'," +
			"['require','exports','module'],function(require,exports,module){" +
			source + "\n});\n" + sourceUrl + "\n";
	}

	var injectSource = function (el, source) {
		// got this from Stoyan Stefanov (http://www.phpied.com/dynamic-script-and-style-elements-in-ie/)
		injectSource = ('text' in el) ?
			function (el, source) { el.text = source; } :
			function (el, source) { el.appendChild(document.createTextNode(source)); };
		injectSource(el, source);
	};

	function injectScript (source) {
		var el = document.createElement('script');
		injectSource(el, source);
		el.charset = 'utf-8';
		head.insertBefore(el, insertBeforeEl);
	}

	return {
		'load': function (resourceId, require, callback, config) {
			// TODO: extract xhr from text! plugin and use that instead (after we upgrade to cram.js)
			require(['text!' + resourceId + '.js', 'curl/_privileged'], function (source, priv) {
				var moduleMap;

				// find (and replace?) dependencies
				moduleMap = priv['core'].extractCjsDeps(source);
				//source = parseDepModuleIds(source, moduleMap, config.replaceRequires);

				// get deps
				require(moduleMap, function () {

					// wrap source in a define
					source = wrapSource(source, resourceId, config['injectSourceUrl'] !== false && require.toUrl(resourceId));

					if (config['injectScript']) {
						injectScript(source);
					}
					else {
						//eval(source);
						globalEval(source);
					}

					// call callback now that the module is defined
					callback(require(resourceId));

				}, callback['error'] || function (ex) { throw ex; });

			});
		}
	};

});

}(this, this.document, function () { /* FB needs direct eval here */ eval(arguments[0]); }));
<commit_msg>protect //sourceURL from IE 6-8 when @cc_on<commit_after>/** MIT License (c) copyright B Cavalier & J Hann */

/**
 * curl CommonJS Modules/1.1 loader
 *
 * Licensed under the MIT License at:
 * 		http://www.opensource.org/licenses/mit-license.php
 */

/**
 * @experimental
 */
(function (global, document, globalEval) {

define(/*=='curl/loader/cjsm11',==*/ function () {

	var head, insertBeforeEl /*, findRequiresRx, myId*/;

//	findRequiresRx = /require\s*\(\s*['"](\w+)['"]\s*\)/,

//	function nextId (index) {
//		var varname = '', part;
//		do {
//			part = index % 26;
//			varname += String.fromCharCode(part + 65);
//			index -= part;
//		}
//		while (index > 0);
//		return 'curl$' + varname;
//	}

//	/**
//	 * @description Finds the require() instances in the source text of a cjs
//	 * 	 module and collects them. If removeRequires is true, it also replaces
//	 * 	 them with a unique variable name. All unique require()'d module ids
//	 * 	 are assigned a unique variable name to be used in the define(deps)
//	 * 	 that will be constructed to wrap the cjs module.
//	 * @param source - source code of cjs module
//	 * @param moduleIds - hashMap (object) to receive pairs of moduleId /
//	 *   unique variable name
//	 * @param removeRequires - if truthy, replaces all require() instances with
//	 *   a unique variable
//	 * @return - source code of cjs module, possibly with require()s replaced
//	 */
//	function parseDepModuleIds (source, moduleIds, removeRequires) {
//		var index = 0;
//		// fast parse
//		source = source.replace(findRequiresRx, function (match, id) {
//			if (!moduleIds[id]) {
//				moduleIds[id] = nextId(index++);
//				moduleIds.push(id);
//			}
//			return removeRequires ? moduleIds[id] : match;
//		});
//		return source;
//	}

	head = document && (document['head'] || document.getElementsByTagName('head')[0]);
	// to keep IE from crying, we need to put scripts before any
	// <base> elements, but after any <meta>. this should do it:
	insertBeforeEl = head && head.getElementsByTagName('base')[0] || null;

	function wrapSource (source, resourceId, fullUrl) {
		var sourceUrl = fullUrl ? '/*\n////@ sourceURL=' + fullUrl.replace(/\s/g, '%20') + '.js\n*/' : '';
		return "define('" + resourceId + "'," +
			"['require','exports','module'],function(require,exports,module){" +
			source + "\n});\n" + sourceUrl + "\n";
	}

	var injectSource = function (el, source) {
		// got this from Stoyan Stefanov (http://www.phpied.com/dynamic-script-and-style-elements-in-ie/)
		injectSource = ('text' in el) ?
			function (el, source) { el.text = source; } :
			function (el, source) { el.appendChild(document.createTextNode(source)); };
		injectSource(el, source);
	};

	function injectScript (source) {
		var el = document.createElement('script');
		injectSource(el, source);
		el.charset = 'utf-8';
		head.insertBefore(el, insertBeforeEl);
	}

	return {
		'load': function (resourceId, require, callback, config) {
			// TODO: extract xhr from text! plugin and use that instead (after we upgrade to cram.js)
			require(['text!' + resourceId + '.js', 'curl/_privileged'], function (source, priv) {
				var moduleMap;

				// find (and replace?) dependencies
				moduleMap = priv['core'].extractCjsDeps(source);
				//source = parseDepModuleIds(source, moduleMap, config.replaceRequires);

				// get deps
				require(moduleMap, function () {

					// wrap source in a define
					source = wrapSource(source, resourceId, config['injectSourceUrl'] !== false && require.toUrl(resourceId));

					if (config['injectScript']) {
						injectScript(source);
					}
					else {
						//eval(source);
						globalEval(source);
					}

					// call callback now that the module is defined
					callback(require(resourceId));

				}, callback['error'] || function (ex) { throw ex; });

			});
		}
	};

});

}(this, this.document, function () { /* FB needs direct eval here */ eval(arguments[0]); }));
<|endoftext|>


<commit_before>APP.controllers.sessions = (function() {

    function init() {

        APP.components.inputTextareaMovingLabel();

        $(document).ready(function() {
          // Set FB and Analytics Tracking for new registered Users
          var newRegConfUser = $("#flash .alert");
          if (newRegConfUser.exists()) {
            if( newRegConfUser.html().indexOf('Anmeldedaten') >= 0){
            //if( newRegConfUser.html().indexOf('Dein Account ist nun freigeschaltet') >= 0){
              var reggraetzl;
              reggraetzl = localStorage.getItem('Graetzl');
              // Analytics
              gtag('event', 'sign_up', {
                'event_category': 'Registration',
                'event_label': reggraetzl
              });
              // FB
              fbq('track', 'CompleteRegistration');
            }
          }
        });

    }

// ---------------------------------------------------------------------- Public

    return {
        init: init
    }

})();
<commit_msg>fixed registration event tracking<commit_after>APP.controllers.sessions = (function() {

    function init() {

        APP.components.inputTextareaMovingLabel();

        $(document).ready(function() {
          // Set FB and Analytics Tracking for new registered Users
          var newRegConfUser = $("#flash .alert");
          if (newRegConfUser.exists()) {
            //if( newRegConfUser.html().indexOf('Anmeldedaten') > 0){
            if( newRegConfUser.html().indexOf('Dein Account ist nun freigeschaltet') > 0){
              var reggraetzl;
              reggraetzl = localStorage.getItem('Graetzl');
              // Analytics
              gtag('event', 'sign_up', {
                'event_category': 'Registration',
                'event_label': reggraetzl
              });
              // FB
              fbq('track', 'CompleteRegistration');
              localStorage.removeItem('Graetzl');
            }
          }
        });

    }

// ---------------------------------------------------------------------- Public

    return {
        init: init
    }

})();
<|endoftext|>


<commit_before>// @flow

import React from 'react';
import classnames from 'classnames';
import {
  config as faConfig,
  library as faLibrary,
} from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  faCaretDown,
  faCaretUp,
  faArrowLeft,
  faArrowRight,
} from '@fortawesome/free-solid-svg-icons';
import { ThemeContext } from '../gral/themeContext';
import type { Theme } from '../gral/themeContext';

faConfig.autoAddCss = false;
faLibrary.add(faCaretDown, faCaretUp, faArrowLeft, faArrowRight);

const SPINNER_ICON = 'circle-notch';

// ==========================================
// Declaration
// ==========================================
// -- A wrapper for Font Awesome icons. Props:
// --
// -- START_DOCS
type PublicProps = {
  className?: string,
  id?: string,
  icon: string | [string, string], // e.g. `ambulance`, `cogs`...
  family?: string, // e.g. `fas`, `far`
  size?: 'lg' | '2x' | '3x' | '4x' | '5x',
  fixedWidth?: boolean,
  spin?: boolean,
  pulse?: boolean,
  onClick?: (ev: SyntheticMouseEvent<*>) => any,
  disabled?: boolean,
  skipTheme?: boolean,
  style?: Object, // use sparsely (CSS should cover you in most cases!)
};
// -- END_DOCS

type Props = {
  ...$Exact<PublicProps>,
  // Context
  theme: Theme,
};

// ==========================================
// Component
// ==========================================
class Icon extends React.PureComponent<Props> {
  refIcon: any = React.createRef();

  componentDidMount() {
    if (this.props.theme.id === 'mdl' && this.refIcon.current) {
      window.componentHandler.upgradeElement(this.refIcon.current);
    }
  }

  // ==========================================
  render() {
    const { icon, disabled } = this.props;
    if (!this.props.skipTheme && this.props.theme.id === 'mdl') {
      return icon === SPINNER_ICON ? this.renderMdlSpinner() : this.renderMdl();
    }
    const family = this.props.family || 'fa';
    return (
      <FontAwesomeIcon
        className={classnames(
          'giu-icon',
          {
            'giu-icon-disabled': disabled,
            'giu-icon-clickable': !disabled && this.props.onClick,
          },
          this.props.className
        )}
        id={this.props.id}
        icon={family ? [family, icon] : icon}
        size={this.props.size}
        onClick={disabled ? undefined : this.props.onClick}
        fixedWidth={this.props.fixedWidth}
        spin={icon === SPINNER_ICON || this.props.spin}
        pulse={this.props.pulse}
        style={this.props.style}
      />
    );
  }

  renderMdl() {
    const { icon, disabled, size } = this.props;
    return (
      <i
        className={classnames(
          'giu-icon',
          size ? `giu-icon-${size}` : undefined,
          'material-icons',
          {
            'giu-icon-disabled': disabled,
            'giu-icon-clickable': !disabled && this.props.onClick,
            'giu-icon-fixed-width': this.props.fixedWidth,
          },
          this.props.className
        )}
        id={this.props.id}
        onClick={disabled ? undefined : this.props.onClick}
        style={this.props.style}
      >
        {icon}
      </i>
    );
  }

  renderMdlSpinner() {
    const { size } = this.props;
    return (
      <div
        ref={this.refIcon}
        className={classnames(
          'giu-mdl-spinner mdl-spinner mdl-js-spinner is-active',
          size ? `giu-mdl-spinner-${size}` : undefined,
          this.props.className
        )}
        id={this.props.id}
        style={this.props.style}
      />
    );
  }
}

// ==========================================
const ThemedIcon = (props: PublicProps) => (
  <ThemeContext.Consumer>
    {theme => <Icon {...props} theme={theme} />}
  </ThemeContext.Consumer>
);

// ==========================================
// Public
// ==========================================
export default ThemedIcon;
export { SPINNER_ICON };
<commit_msg>Include additional icons in the predefined Font Awesome library<commit_after>// @flow

import React from 'react';
import classnames from 'classnames';
import {
  config as faConfig,
  library as faLibrary,
} from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  faBars,
  faCircleNotch,
  faTimes,
  faCaretDown,
  faCaretUp,
  faArrowLeft,
  faArrowRight,
} from '@fortawesome/free-solid-svg-icons';
import { ThemeContext } from '../gral/themeContext';
import type { Theme } from '../gral/themeContext';

faConfig.autoAddCss = false;
faLibrary.add(
  faBars,
  faCircleNotch,
  faTimes,
  faCaretDown,
  faCaretUp,
  faArrowLeft,
  faArrowRight
);

const SPINNER_ICON = 'circle-notch';

// ==========================================
// Declaration
// ==========================================
// -- A wrapper for Font Awesome icons. Props:
// --
// -- START_DOCS
type PublicProps = {
  className?: string,
  id?: string,
  icon: string | [string, string], // e.g. `ambulance`, `cogs`...
  family?: string, // e.g. `fas`, `far`
  size?: 'lg' | '2x' | '3x' | '4x' | '5x',
  fixedWidth?: boolean,
  spin?: boolean,
  pulse?: boolean,
  onClick?: (ev: SyntheticMouseEvent<*>) => any,
  disabled?: boolean,
  skipTheme?: boolean,
  style?: Object, // use sparsely (CSS should cover you in most cases!)
};
// -- END_DOCS

type Props = {
  ...$Exact<PublicProps>,
  // Context
  theme: Theme,
};

// ==========================================
// Component
// ==========================================
class Icon extends React.PureComponent<Props> {
  refIcon: any = React.createRef();

  componentDidMount() {
    if (this.props.theme.id === 'mdl' && this.refIcon.current) {
      window.componentHandler.upgradeElement(this.refIcon.current);
    }
  }

  // ==========================================
  render() {
    const { icon, disabled } = this.props;
    if (!this.props.skipTheme && this.props.theme.id === 'mdl') {
      return icon === SPINNER_ICON ? this.renderMdlSpinner() : this.renderMdl();
    }
    const family = this.props.family || 'fa';
    return (
      <FontAwesomeIcon
        className={classnames(
          'giu-icon',
          {
            'giu-icon-disabled': disabled,
            'giu-icon-clickable': !disabled && this.props.onClick,
          },
          this.props.className
        )}
        id={this.props.id}
        icon={family ? [family, icon] : icon}
        size={this.props.size}
        onClick={disabled ? undefined : this.props.onClick}
        fixedWidth={this.props.fixedWidth}
        spin={icon === SPINNER_ICON || this.props.spin}
        pulse={this.props.pulse}
        style={this.props.style}
      />
    );
  }

  renderMdl() {
    const { icon, disabled, size } = this.props;
    return (
      <i
        className={classnames(
          'giu-icon',
          size ? `giu-icon-${size}` : undefined,
          'material-icons',
          {
            'giu-icon-disabled': disabled,
            'giu-icon-clickable': !disabled && this.props.onClick,
            'giu-icon-fixed-width': this.props.fixedWidth,
          },
          this.props.className
        )}
        id={this.props.id}
        onClick={disabled ? undefined : this.props.onClick}
        style={this.props.style}
      >
        {icon}
      </i>
    );
  }

  renderMdlSpinner() {
    const { size } = this.props;
    return (
      <div
        ref={this.refIcon}
        className={classnames(
          'giu-mdl-spinner mdl-spinner mdl-js-spinner is-active',
          size ? `giu-mdl-spinner-${size}` : undefined,
          this.props.className
        )}
        id={this.props.id}
        style={this.props.style}
      />
    );
  }
}

// ==========================================
const ThemedIcon = (props: PublicProps) => (
  <ThemeContext.Consumer>
    {theme => <Icon {...props} theme={theme} />}
  </ThemeContext.Consumer>
);

// ==========================================
// Public
// ==========================================
export default ThemedIcon;
export { SPINNER_ICON };
<|endoftext|>


<commit_before>import { addDecorator, addParameters, addParameterEnhancer } from '@storybook/client-api';
import { logger } from '@storybook/client-logger';

const {
  decorators,
  parameters,
  parameterEnhancers,
  globalArgs,
  globalArgTypes,
  args,
  argTypes,
} = require('{{configFilename}}');

if (args || argTypes)
  logger.warn('Invalid args/argTypes in config, ignoring.', JSON.stringify({ args, argTypes }));
if (decorators) decorators.forEach((decorator) => addDecorator(decorator));
if (parameters || globalArgs || globalArgTypes)
  addParameters({ ...parameters, globalArgs, globalArgTypes });
if (parameterEnhancers) parameterEnhancers.forEach((enhancer) => addParameterEnhancer(enhancer));
<commit_msg>CLEANUP<commit_after>import { addDecorator, addParameters, addParameterEnhancer } from '@storybook/client-api';
import { logger } from '@storybook/client-logger';

const {
  decorators,
  parameters,
  parameterEnhancers,
  globalArgs,
  globalArgTypes,
  args,
  argTypes,
} = require('{{configFilename}}');

if (args || argTypes) {
  logger.warn('Invalid args/argTypes in config, ignoring.', JSON.stringify({ args, argTypes }));
}
if (decorators) {
  decorators.forEach((decorator) => addDecorator(decorator));
}
if (parameters || globalArgs || globalArgTypes) {
  addParameters({ ...parameters, globalArgs, globalArgTypes });
}
if (parameterEnhancers) {
  parameterEnhancers.forEach((enhancer) => addParameterEnhancer(enhancer));
}
<|endoftext|>


<commit_before>'use strict';

// Iron-node does not work with forked processes
// This cli command will run a single file in the current process.
// Intended to be used with iron-node for profiling purposes.

const path = require('path');
const EventEmitter = require('events');
const meow = require('meow');
const Promise = require('bluebird');
const pkgConf = require('pkg-conf');
const findCacheDir = require('find-cache-dir');
const uniqueTempDir = require('unique-temp-dir');
const arrify = require('arrify');
const resolveCwd = require('resolve-cwd');
const babelConfigHelper = require('./lib/babel-config');
const CachingPrecompiler = require('./lib/caching-precompiler');
const globals = require('./lib/globals');

function resolveModules(modules) {
	return arrify(modules).map(name => {
		const modulePath = resolveCwd.silent(name);

		if (modulePath === null) {
			throw new Error(`Could not resolve required module '${name}'`);
		}

		return modulePath;
	});
}

// Chrome gets upset when the `this` value is non-null for these functions
globals.setTimeout = setTimeout.bind(null);
globals.clearTimeout = clearTimeout.bind(null);

Promise.longStackTraces();

const conf = pkgConf.sync('ava', {
	defaults: {
		babel: 'default'
	}
});

// Define a minimal set of options from the main CLI
const cli = meow(`
	Usage
	  $ iron-node node_modules/ava/profile.js <test-file>

	Options
	  --fail-fast   Stop after first test failure
	  --serial, -s  Run tests serially

`, {
	string: [
		'_'
	],
	boolean: [
		'fail-fast',
		'verbose',
		'serial',
		'tap'
	],
	default: conf,
	alias: {
		s: 'serial'
	}
});

if (cli.input.length === 0) {
	throw new Error('Specify a test file');
}

const file = path.resolve(cli.input[0]);
const cacheDir = findCacheDir({
	name: 'ava',
	files: [file]
}) || uniqueTempDir();

babelConfigHelper.build(process.cwd(), cacheDir, conf.babel, true)
	.then(result => {
		const precompiler = new CachingPrecompiler({
			path: cacheDir,
			getBabelOptions: result.getOptions,
			babelCacheKeys: result.cacheKeys
		});

		const precompiled = {};
		precompiled[file] = precompiler.precompileFile(file);

		const opts = {
			file,
			failFast: cli.flags.failFast,
			serial: cli.flags.serial,
			tty: false,
			cacheDir,
			precompiled,
			require: resolveModules(conf.require)
		};

		const events = new EventEmitter();
		let uncaughtExceptionCount = 0;

		// Mock the behavior of a parent process
		process.channel = {ref() {}, unref() {}};
		process.send = data => {
			if (data && data.ava) {
				const name = data.name.replace(/^ava-/, '');

				if (events.listeners(name).length > 0) {
					events.emit(name, data.data);
				} else {
					console.log('UNHANDLED AVA EVENT:', name, data.data);
				}

				return;
			}

			console.log('NON AVA EVENT:', data);
		};

		events.on('test', data => {
			console.log('TEST:', data.title, data.error);
		});

		events.on('results', data => {
			if (console.profileEnd) {
				console.profileEnd();
			}

			console.log('RESULTS:', data.stats);

			if (process.exit) {
				process.exit(data.stats.failCount + uncaughtExceptionCount); // eslint-disable-line unicorn/no-process-exit
			}
		});

		events.on('stats', () => {
			setImmediate(() => {
				process.emit('ava-run', {});
			});
		});

		events.on('uncaughtException', data => {
			uncaughtExceptionCount++;
			let stack = data && data.exception && data.exception.stack;
			stack = stack || data;
			console.log(stack);
		});

		// `test-worker` will read process.argv[2] for options
		process.argv[2] = JSON.stringify(opts);
		process.argv.length = 3;

		if (console.profile) {
			console.profile('AVA test-worker process');
		}

		setImmediate(() => {
			require('./lib/test-worker'); // eslint-disable-line import/no-unassigned-import
		});
	});
<commit_msg>Modify profile.js (#10)<commit_after>'use strict';

// Iron-node does not work with forked processes
// This cli command will run a single file in the current process.
// Intended to be used with iron-node for profiling purposes.

const path = require('path');
const EventEmitter = require('events');
const meow = require('meow');
const Promise = require('bluebird');
const pkgConf = require('pkg-conf');
const findCacheDir = require('find-cache-dir');
const uniqueTempDir = require('unique-temp-dir');
const arrify = require('arrify');
const resolveCwd = require('resolve-cwd');
const babelConfigHelper = require('./lib/babel-config');
const CachingPrecompiler = require('./lib/caching-precompiler');
const globals = require('./lib/globals');

function resolveModules(modules) {
	return arrify(modules).map(name => {
		const modulePath = resolveCwd.silent(name);

		if (modulePath === null) {
			throw new Error(`Could not resolve required module '${name}'`);
		}

		return modulePath;
	});
}

// Chrome gets upset when the `this` value is non-null for these functions
globals.setTimeout = setTimeout.bind(null);
globals.clearTimeout = clearTimeout.bind(null);

Promise.longStackTraces();

const conf = pkgConf.sync('ava', {
	defaults: {
		babel: 'default'
	}
});

// Define a minimal set of options from the main CLI
const cli = meow(`
	Usage
	  $ iron-node node_modules/ava/profile.js <test-file>

	Options
	  --fail-fast   Stop after first test failure
	  --serial, -s  Run tests serially

`, {
	string: [
		'_'
	],
	boolean: [
		'fail-fast',
		'verbose',
		'serial',
		'tap'
	],
	default: conf,
	alias: {
		s: 'serial'
	}
});

if (cli.input.length === 0) {
	throw new Error('Specify a test file');
}

const file = path.resolve(cli.input[0]);
const cacheDir = findCacheDir({
	name: 'ava',
	files: [file]
}) || uniqueTempDir();

babelConfigHelper.build(process.cwd(), cacheDir, conf.babel, true)
	.then(result => {
		const precompiler = new CachingPrecompiler({
			path: cacheDir,
			getBabelOptions: result.getOptions,
			babelCacheKeys: result.cacheKeys
		});

		const precompiled = {};
		precompiled[file] = precompiler.precompileFile(file);

		const opts = {
			file,
			failFast: cli.flags.failFast,
			serial: cli.flags.serial,
			tty: false,
			cacheDir,
			precompiled,
			require: resolveModules(arrify(this.options.require).concat('ts-node/register'))
		};

		const events = new EventEmitter();
		let uncaughtExceptionCount = 0;

		// Mock the behavior of a parent process
		process.channel = {ref() {}, unref() {}};
		process.send = data => {
			if (data && data.ava) {
				const name = data.name.replace(/^ava-/, '');

				if (events.listeners(name).length > 0) {
					events.emit(name, data.data);
				} else {
					console.log('UNHANDLED AVA EVENT:', name, data.data);
				}

				return;
			}

			console.log('NON AVA EVENT:', data);
		};

		events.on('test', data => {
			console.log('TEST:', data.title, data.error);
		});

		events.on('results', data => {
			if (console.profileEnd) {
				console.profileEnd();
			}

			console.log('RESULTS:', data.stats);

			if (process.exit) {
				process.exit(data.stats.failCount + uncaughtExceptionCount); // eslint-disable-line unicorn/no-process-exit
			}
		});

		events.on('stats', () => {
			setImmediate(() => {
				process.emit('ava-run', {});
			});
		});

		events.on('uncaughtException', data => {
			uncaughtExceptionCount++;
			let stack = data && data.exception && data.exception.stack;
			stack = stack || data;
			console.log(stack);
		});

		// `test-worker` will read process.argv[2] for options
		process.argv[2] = JSON.stringify(opts);
		process.argv.length = 3;

		if (console.profile) {
			console.profile('AVA test-worker process');
		}

		setImmediate(() => {
			require('./lib/test-worker'); // eslint-disable-line import/no-unassigned-import
		});
	});
<|endoftext|>


<commit_before>if(!Draw.fill) {
  Draw.fill = function(r, g, b, a) {
    if(!Canvas.configured) {
      console.warn("KAPhy Warning - You must use Canvas.configure(); before you can draw!");
      return;
    }

    switch(arguments.length) {
      case 0: Canvas.context.fillStyle = "#FFFFFF"; break;
      case 1: Canvas.context.fillStyle = "rgb(" + arguments[0] + ", " + arguments[0] + ", " + arguments[0] + ")"; break;
      case 2: Canvas.context.fillStyle = "rgba(" + arguments[0] + ", " + arguments[0] + ", " + arguments[0] + ", " + arguments[1]/255 + ")"; break;
      case 3: Canvas.context.fillStyle = "rgb(" + arguments[0] + ", " + arguments[1] + ", " + arguments[2] + ")"; break;
      case 4: Canvas.context.fillStyle = "rgba(" + arguments[0] + ", " + arguments[1] + ", " + arguments[2] + ", " + arguments[3]/255 + ")";
    }
  };
}
<commit_msg>Update fill.js<commit_after>if(!Draw.fill) {
  Draw.fill = function(r, g, b, a) {
    if(!Canvas.configured) {
      console.warn("KAPhy Warning - You must use Canvas.configure(); before you can draw!");
      return;
    }

    switch(arguments.length) {
      case 0: Canvas.context.fillStyle = "rgba(255, 255, 255, 1)"; break;
      case 1: Canvas.context.fillStyle = "rgba(" + arguments[0] + ", " + arguments[0] + ", " + arguments[0] + ", 1.0)"; break;
      case 2: Canvas.context.fillStyle = "rgba(" + arguments[0] + ", " + arguments[0] + ", " + arguments[0] + ", " + arguments[1]/255 + ")"; break;
      case 3: Canvas.context.fillStyle = "rgba(" + arguments[0] + ", " + arguments[1] + ", " + arguments[2] + ", 1.0)"; break;
      case 4: Canvas.context.fillStyle = "rgba(" + arguments[0] + ", " + arguments[1] + ", " + arguments[2] + ", " + arguments[3]/255 + ")";
    }
  };
}
<|endoftext|>


<commit_before>//
//  unmuteZoneClient.js
//
//  Created by Robin Wilson on 2019-04-08
//  Copyright 2019 High Fidelity, Inc.
//
//  Distributed under the Apache License, Version 2.0.
//  See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html

(function() {

    function onMuteSettingChanged() {
        // if user mutes themselves in the zone,
        // do not apply the previous mute setting
        usePreviousMuteSetting = false;
    }

    function UnmuteZoneClient () {
        // blank
    }

    var previousMuteSetting = false,
        usePreviousMuteSetting = true,
        isMutedSignalConnected = false;
    UnmuteZoneClient.prototype = {
        preload: function(id) {
            // blank
        },
        enterEntity: function() {
            // if push to talk is enabled
            // exit
            if (Audio.pushToTalk) {
                return;
            }

            // save previous muted setting
            previousMuteSetting = Audio.muted;
            Audio.muted = false;
            usePreviousMuteSetting = true;

            Audio.mutedChanged.connect(onMuteSettingChanged);
            isMutedSignalConnected = true;
        },
        leaveEntity: function() {
            if (usePreviousMuteSetting) {
                // did not change muted status while inside the zone
                // apply previous setting
                Audio.muted = previousMuteSetting;
            }

            if (isMutedSignalConnected) {
                // only disconnect once
                Audio.mutedChanged.disconnect(onMuteSettingChanged);
                isMutedSignalConnected = false;
            }
        },
        unload: function() {
            if (isMutedSignalConnected) {
                // only disconnect once
                Audio.mutedChanged.disconnect(onMuteSettingChanged);
                isMutedSignalConnected = false;
            }
        }
    };

    return new UnmuteZoneClient();
});
<commit_msg>updated preload to check if the avatar is inside the zone<commit_after>//
//  unmuteZoneClient.js
//
//  Created by Robin Wilson on 2019-04-08
//  Copyright 2019 High Fidelity, Inc.
//
//  Distributed under the Apache License, Version 2.0.
//  See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html

(function() {

    function onMuteSettingChanged() {
        // if user mutes themselves in the zone,
        // do not apply the previous mute setting
        that.usePreviousMuteSetting = false;
    }

    // Returns true if my avatar is inside the zone, false otherwise.
    function positionIsInsideEntityBounds(entityID, targetPosition) {
        targetPosition = targetPosition || MyAvatar.position;

        var properties = Entities.getEntityProperties(entityID, ["position", "dimensions", "rotation"]);
        var entityPosition = properties.position;
        var entityDimensions = properties.dimensions;
        var entityRotation = properties.rotation;

        var worldOffset = Vec3.subtract(targetPosition, entityPosition);
        targetPosition = Vec3.multiplyQbyV(Quat.inverse(entityRotation), worldOffset);

        var minX = -entityDimensions.x * HALF;
        var maxX = entityDimensions.x * HALF;
        var minY = -entityDimensions.y * HALF;
        var maxY = entityDimensions.y * HALF;
        var minZ = -entityDimensions.z * HALF;
        var maxZ = entityDimensions.z * HALF;

        return (targetPosition.x >= minX && targetPosition.x <= maxX
            && targetPosition.y >= minY && targetPosition.y <= maxY
            && targetPosition.z >= minZ && targetPosition.z <= maxZ);
    }

    var that = null;
    function UnmuteZoneClient() {
        that = this;
        this.entityID = null;
        this.previousMuteSetting = false,
        this.usePreviousMuteSetting = true,
        this.isMutedSignalConnected = false;
    }

    UnmuteZoneClient.prototype = {
        preload: function(id) {
            that.entityID = id;
            if (positionIsInsideEntityBounds(that.entityID, MyAvatar.position)) {
                that.enterEntity();
            }
        },
        enterEntity: function() {
            // if push to talk is enabled
            // exit
            if (Audio.pushToTalk) {
                return;
            }

            // save previous muted setting
            that.previousMuteSetting = Audio.muted;
            Audio.muted = false;
            that.usePreviousMuteSetting = true;

            Audio.mutedChanged.connect(onMuteSettingChanged);
            that.isMutedSignalConnected = true;
        },
        leaveEntity: function() {
            if (that.usePreviousMuteSetting) {
                // did not change muted status while inside the zone
                // apply previous setting
                Audio.muted = that.previousMuteSetting;
            }

            if (that.isMutedSignalConnected) {
                // only disconnect once
                Audio.mutedChanged.disconnect(onMuteSettingChanged);
                that.isMutedSignalConnected = false;
            }
        },
        unload: function() {
            if (that.isMutedSignalConnected) {
                // only disconnect once
                Audio.mutedChanged.disconnect(onMuteSettingChanged);
                that.isMutedSignalConnected = false;
            }
        }
    };

    return new UnmuteZoneClient();
});
<|endoftext|>