<commit_before>function Module() {
    this.sp = null;
    this.sensorTypes = {
        ALIVE: 0,
        DIGITAL: 1,
        ANALOG: 2,
        PWM: 3,
        SERVO_PIN: 4,
        TONE: 5,
        PULSEIN: 6,
        ULTRASONIC: 7,
        TIMER: 8,
        METRIX: 9,
        METRIXCLEAR: 11,
        METRIXROWCOLCLEAR: 12,
        METRIXDRAW: 13,
        NEOPIXEL: 14,
        NEOPIXELCLEAR: 15,
        NEOPIXELINIT : 16,
        NEOPIXELRAINBOW : 17,
    };

    this.actionTypes = {
        GET: 1,
        SET: 2,
        RESET: 3,
    };

    this.sensorValueSize = {
        FLOAT: 2,
        SHORT: 3,
    };

    this.digitalPortTimeList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

    this.sensorData = {
        ULTRASONIC: 0,
        DIGITAL: {
            '0': 0,
            '1': 0,
            '2': 0,
            '3': 0,
            '4': 0,
            '5': 0,
            '6': 0,
            '7': 0,
            '8': 0,
            '9': 0,
            '10': 0,
            '11': 0,
            '12': 0,
            '13': 0,
        },
        ANALOG: {
            '0': 0,
            '1': 0,
            '2': 0,
            '3': 0,
            '4': 0,
            '5': 0,
        },
        PULSEIN: {},
        TIMER: 0,
    };

    this.defaultOutput = {};

    this.recentCheckData = {};

    this.sendBuffers = [];

    this.lastTime = 0;
    this.lastSendTime = 0;
    this.isDraing = false;
}

var sensorIdx = 0;

Module.prototype.init = function(handler, config) {};

Module.prototype.setSerialPort = function(sp) {
    var self = this;
    this.sp = sp;
};

Module.prototype.requestInitialData = function() {
    return this.makeSensorReadBuffer(this.sensorTypes.ANALOG, 0);
};

Module.prototype.checkInitialData = function(data, config) {
    return true;
    // 이후에 체크 로직 개선되면 처리
    // var datas = this.getDataByBuffer(data);
    // var isValidData = datas.some(function (data) {
    //     return (data.length > 4 && data[0] === 255 && data[1] === 85);
    // });
    // return isValidData;
};

Module.prototype.afterConnect = function(that, cb) {
    that.connected = true;
    if (cb) {
        cb('connected');
    }
};

Module.prototype.validateLocalData = function(data) {
    return true;
};

Module.prototype.requestRemoteData = function(handler) {
    var self = this;
    if (!self.sensorData) {
        return;
    }
    Object.keys(this.sensorData).forEach(function(key) {
        if (self.sensorData[key] != undefined) {
            handler.write(key, self.sensorData[key]);
        }
    });
};

Module.prototype.handleRemoteData = function(handler) {
    var self = this;
    var getDatas = handler.read('GET');
    var setDatas = handler.read('SET') || this.defaultOutput;
    var time = handler.read('TIME');
    var buffer = new Buffer([]);

    if (getDatas) {
        var keys = Object.keys(getDatas);
        keys.forEach(function(key) {
            var isSend = false;
            var dataObj = getDatas[key];
            if (
                typeof dataObj.port === 'string' ||
                typeof dataObj.port === 'number'
            ) {
                var time = self.digitalPortTimeList[dataObj.port];
                if (dataObj.time > time) {
                    isSend = true;
                    self.digitalPortTimeList[dataObj.port] = dataObj.time;
                }
            } else if (Array.isArray(dataObj.port)) {
                isSend = dataObj.port.every(function(port) {
                    var time = self.digitalPortTimeList[port];
                    return dataObj.time > time;
                });

                if (isSend) {
                    dataObj.port.forEach(function(port) {
                        self.digitalPortTimeList[port] = dataObj.time;
                    });
                }
            }

            if (isSend) {
                if (!self.isRecentData(dataObj.port, key, dataObj.data)) {
                    self.recentCheckData[dataObj.port] = {
                        type: key,
                        data: dataObj.data,
                    };
                    buffer = Buffer.concat([
                        buffer,
                        self.makeSensorReadBuffer(
                            key,
                            dataObj.port,
                            dataObj.data
                        ),
                    ]);
                }
            }
        });
    }

    if (setDatas) {
        var setKeys = Object.keys(setDatas);
        setKeys.forEach(function(port) {
            var data = setDatas[port];
            if (data) {
                if (self.digitalPortTimeList[port] < data.time) {
                    self.digitalPortTimeList[port] = data.time;

                    if (!self.isRecentData(port, data.type, data.data)) {
                        self.recentCheckData[port] = {
                            type: data.type,
                            data: data.data,
                        };
                        buffer = Buffer.concat([
                            buffer,
                            self.makeOutputBuffer(data.type, port, data.data),
                        ]);
                    }
                }
            }
        });
    }

    if (buffer.length) {
        this.sendBuffers.push(buffer);
    }
};

Module.prototype.isRecentData = function(port, type, data) {
    var that = this;
    var isRecent = false;

    if(type == this.sensorTypes.ULTRASONIC) {
        var portString = port.toString();
        var isGarbageClear = false;
        Object.keys(this.recentCheckData).forEach(function (key) {
            var recent = that.recentCheckData[key];
            if(key === portString) {

            }
            if(key !== portString && recent.type == that.sensorTypes.ULTRASONIC) {
                delete that.recentCheckData[key];
                isGarbageClear = true;
            }
        });

        if((port in this.recentCheckData && isGarbageClear) || !(port in this.recentCheckData)) {
            isRecent = false;
        } else {
            isRecent = true;
        }

    } else if (port in this.recentCheckData && type != this.sensorTypes.TONE) {
        if (
            this.recentCheckData[port].type === type &&
            this.recentCheckData[port].data === data
        ) {
            isRecent = true;
        }
    }

    return isRecent;
};

Module.prototype.requestLocalData = function() {
    var self = this;

    if (!this.isDraing && this.sendBuffers.length > 0) {
        this.isDraing = true;
        this.sp.write(this.sendBuffers.shift(), function() {
            if (self.sp) {
                self.sp.drain(function() {
                    self.isDraing = false;
                });
            }
        });
    }

    return null;
};

/*
ff 55 idx size data a
*/
Module.prototype.handleLocalData = function(data) {
    var self = this;
    var datas = this.getDataByBuffer(data);

    datas.forEach(function(data) {
        if (data.length <= 4 || data[0] !== 255 || data[1] !== 85) {
            return;
        }
        var readData = data.subarray(2, data.length);
        var value;
        switch (readData[0]) {
            case self.sensorValueSize.FLOAT: {
                value = new Buffer(readData.subarray(1, 5)).readFloatLE();
                value = Math.round(value * 100) / 100;
                break;
            }
            case self.sensorValueSize.SHORT: {
                value = new Buffer(readData.subarray(1, 3)).readInt16LE();
                break;
            }
            default: {
                value = 0;
                break;
            }
        }

        var type = readData[readData.length - 1];
        var port = readData[readData.length - 2];

        switch (type) {
            case self.sensorTypes.DIGITAL: {
                self.sensorData.DIGITAL[port] = value;
                break;
            }
            case self.sensorTypes.ANALOG: {
                self.sensorData.ANALOG[port] = value;
                break;
            }
            case self.sensorTypes.PULSEIN: {
                self.sensorData.PULSEIN[port] = value;
                break;
            }
            case self.sensorTypes.ULTRASONIC: {
                self.sensorData.ULTRASONIC = value;
                break;
            }
            case self.sensorTypes.TIMER: {
                self.sensorData.TIMER = value;
                break;
            }
            default: {
                break;
            }
        }
    });
};

/*
ff 55 len idx action device port  slot  data a
0  1  2   3   4      5      6     7     8
*/

Module.prototype.makeSensorReadBuffer = function(device, port, data) {
    var buffer;
    var dummy = new Buffer([10]);
    if (device == this.sensorTypes.ULTRASONIC) {
        buffer = new Buffer([
            255,
            85,
            6,
            sensorIdx,
            this.actionTypes.GET,
            device,
            port[0],
            port[1],
            10,
        ]);
    } else if (!data) {
        buffer = new Buffer([
            255,
            85,
            5,
            sensorIdx,
            this.actionTypes.GET,
            device,
            port,
            10,
        ]);
    } else {
        value = new Buffer(2);
        value.writeInt16LE(data);
        buffer = new Buffer([
            255,
            85,
            7,
            sensorIdx,
            this.actionTypes.GET,
            device,
            port,
            10,
        ]);
        buffer = Buffer.concat([buffer, value, dummy]);
    }
    sensorIdx++;
    if (sensorIdx > 254) {
        sensorIdx = 0;
    }

    return buffer;
};

//0xff 0x55 0x6 0x0 0x1 0xa 0x9 0x0 0x0 0xa
Module.prototype.makeOutputBuffer = function(device, port, data) {
    var buffer;
    console.log('come');
    var value = new Buffer(2);
    var dummy = new Buffer([10]);

    console.log(device);

    switch (device) {
        case this.sensorTypes.SERVO_PIN:
        case this.sensorTypes.DIGITAL:
        case this.sensorTypes.PWM:
        case this.sensorTypes.METRIXCLEAR:
        case this.sensorTypes.METRIXDRAW:
        case this.sensorTypes.NEOPIXELCLEAR:
        case this.sensorTypes.NEOPIXELRAINBOW:
        {
            value.writeInt16LE(data);

            console.log(data);
            console.log(value);
            buffer = new Buffer([
                255,
                85,
                6,
                sensorIdx,
                this.actionTypes.SET,
                device,
                port,
            ]);
            buffer = Buffer.concat([buffer, value, dummy]);
            console.log(buffer);
            break;
        }
        case this.sensorTypes.METRIX:
        case this.sensorTypes.METRIXROWCOLCLEAR:
        {
            var value2 = new Buffer(2);
            if ($.isPlainObject(data)) {
                value.writeInt16LE(data.value1);
                value2.writeInt16LE(data.value2);
            } else {
                value.writeInt16LE(0);
                value2.writeInt16LE(0);
            }

            console.log(data);
            console.log(value);
            console.log(value2);
            buffer = new Buffer([
                255,
                85,
                8,
                sensorIdx,
                this.actionTypes.SET,
                device,
                port,
            ]);
            buffer = Buffer.concat([buffer, value, value2, dummy]);
            console.log(buffer);
            break;
        }
        case this.sensorTypes.NEOPIXELINIT:{
            var bright = new Buffer(2);
            var neo_count = new Buffer(2);

            if ($.isPlainObject(data)) {
                neo_count.writeInt16LE(data.value1);
                bright.writeInt16LE(data.value2);
            } else {
                neo_count.writeInt16LE(0);
                bright.writeInt16LE(0);
            }

            console.log(data);
            console.log(neo_count);
            console.log(bright);
            buffer = new Buffer([
                255,
                85,
                8,
                sensorIdx,
                this.actionTypes.SET,
                device,
                port,
            ]);
            buffer = Buffer.concat([buffer, neo_count, bright, dummy]);
            console.log(buffer);
            break;
        }
        case this.sensorTypes.NEOPIXEL:{
            //var count_value = new Buffer(2);
            var r_value = new Buffer(2);
            var g_value = new Buffer(2);
            var b_value = new Buffer(2);

            if ($.isPlainObject(data)) {
               // count_value.writeInt16LE(data.count);
                r_value.writeInt16LE(data.R_val);
                g_value.writeInt16LE(data.G_val);
                b_value.writeInt16LE(data.B_val);
            } else {
                //count_value.writeInt16LE(0);
                r_value.writeInt16LE(0);
                g_value.writeInt16LE(0);
                b_value.writeInt16LE(0);
            }

            console.log(data);
            buffer = new Buffer([
                255,
                85,
                10,
                sensorIdx,
                this.actionTypes.SET,
                device,
                port,
            ]);
            buffer = Buffer.concat([buffer, r_value, g_value, b_value, dummy]);
            console.log(buffer);
            break;
        }
        case this.sensorTypes.TONE: {
            var time = new Buffer(2);
            if ($.isPlainObject(data)) {
                value.writeInt16LE(data.value);
                time.writeInt16LE(data.duration);
            } else {
                value.writeInt16LE(0);
                time.writeInt16LE(0);
            }
            buffer = new Buffer([
                255,
                85,
                8,
                sensorIdx,
                this.actionTypes.SET,
                device,
                port,
            ]);
            buffer = Buffer.concat([buffer, value, time, dummy]);
            break;
        }
    }

    return buffer;
};

Module.prototype.getDataByBuffer = function(buffer) {
    var datas = [];
    var lastIndex = 0;
    buffer.forEach(function(value, idx) {
        if (value == 13 && buffer[idx + 1] == 10) {
            datas.push(buffer.subarray(lastIndex, idx));
            lastIndex = idx + 2;
        }
    });

    return datas;
};

Module.prototype.disconnect = function(connect) {
    var self = this;
    connect.close();
    if (self.sp) {
        delete self.sp;
    }
};

Module.prototype.reset = function() {
    this.lastTime = 0;
    this.lastSendTime = 0;

    this.sensorData.PULSEIN = {};
};

module.exports = new Module();
<commit_msg>런코딩 로그 정리<commit_after>function Module() {
    this.sp = null;
    this.sensorTypes = {
        ALIVE: 0,
        DIGITAL: 1,
        ANALOG: 2,
        PWM: 3,
        SERVO_PIN: 4,
        TONE: 5,
        PULSEIN: 6,
        ULTRASONIC: 7,
        TIMER: 8,
        METRIX: 9,
        METRIXCLEAR: 11,
        METRIXROWCOLCLEAR: 12,
        METRIXDRAW: 13,
        NEOPIXEL: 14,
        NEOPIXELCLEAR: 15,
        NEOPIXELINIT : 16,
        NEOPIXELRAINBOW : 17,
    };

    this.actionTypes = {
        GET: 1,
        SET: 2,
        RESET: 3,
    };

    this.sensorValueSize = {
        FLOAT: 2,
        SHORT: 3,
    };

    this.digitalPortTimeList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

    this.sensorData = {
        ULTRASONIC: 0,
        DIGITAL: {
            '0': 0,
            '1': 0,
            '2': 0,
            '3': 0,
            '4': 0,
            '5': 0,
            '6': 0,
            '7': 0,
            '8': 0,
            '9': 0,
            '10': 0,
            '11': 0,
            '12': 0,
            '13': 0,
        },
        ANALOG: {
            '0': 0,
            '1': 0,
            '2': 0,
            '3': 0,
            '4': 0,
            '5': 0,
        },
        PULSEIN: {},
        TIMER: 0,
    };

    this.defaultOutput = {};

    this.recentCheckData = {};

    this.sendBuffers = [];

    this.lastTime = 0;
    this.lastSendTime = 0;
    this.isDraing = false;
}

var sensorIdx = 0;

Module.prototype.init = function(handler, config) {};

Module.prototype.setSerialPort = function(sp) {
    var self = this;
    this.sp = sp;
};

Module.prototype.requestInitialData = function() {
    return this.makeSensorReadBuffer(this.sensorTypes.ANALOG, 0);
};

Module.prototype.checkInitialData = function(data, config) {
    return true;
    // 이후에 체크 로직 개선되면 처리
    // var datas = this.getDataByBuffer(data);
    // var isValidData = datas.some(function (data) {
    //     return (data.length > 4 && data[0] === 255 && data[1] === 85);
    // });
    // return isValidData;
};

Module.prototype.afterConnect = function(that, cb) {
    that.connected = true;
    if (cb) {
        cb('connected');
    }
};

Module.prototype.validateLocalData = function(data) {
    return true;
};

Module.prototype.requestRemoteData = function(handler) {
    var self = this;
    if (!self.sensorData) {
        return;
    }
    Object.keys(this.sensorData).forEach(function(key) {
        if (self.sensorData[key] != undefined) {
            handler.write(key, self.sensorData[key]);
        }
    });
};

Module.prototype.handleRemoteData = function(handler) {
    var self = this;
    var getDatas = handler.read('GET');
    var setDatas = handler.read('SET') || this.defaultOutput;
    var time = handler.read('TIME');
    var buffer = new Buffer([]);

    if (getDatas) {
        var keys = Object.keys(getDatas);
        keys.forEach(function(key) {
            var isSend = false;
            var dataObj = getDatas[key];
            if (
                typeof dataObj.port === 'string' ||
                typeof dataObj.port === 'number'
            ) {
                var time = self.digitalPortTimeList[dataObj.port];
                if (dataObj.time > time) {
                    isSend = true;
                    self.digitalPortTimeList[dataObj.port] = dataObj.time;
                }
            } else if (Array.isArray(dataObj.port)) {
                isSend = dataObj.port.every(function(port) {
                    var time = self.digitalPortTimeList[port];
                    return dataObj.time > time;
                });

                if (isSend) {
                    dataObj.port.forEach(function(port) {
                        self.digitalPortTimeList[port] = dataObj.time;
                    });
                }
            }

            if (isSend) {
                if (!self.isRecentData(dataObj.port, key, dataObj.data)) {
                    self.recentCheckData[dataObj.port] = {
                        type: key,
                        data: dataObj.data,
                    };
                    buffer = Buffer.concat([
                        buffer,
                        self.makeSensorReadBuffer(
                            key,
                            dataObj.port,
                            dataObj.data
                        ),
                    ]);
                }
            }
        });
    }

    if (setDatas) {
        var setKeys = Object.keys(setDatas);
        setKeys.forEach(function(port) {
            var data = setDatas[port];
            if (data) {
                if (self.digitalPortTimeList[port] < data.time) {
                    self.digitalPortTimeList[port] = data.time;

                    if (!self.isRecentData(port, data.type, data.data)) {
                        self.recentCheckData[port] = {
                            type: data.type,
                            data: data.data,
                        };
                        buffer = Buffer.concat([
                            buffer,
                            self.makeOutputBuffer(data.type, port, data.data),
                        ]);
                    }
                }
            }
        });
    }

    if (buffer.length) {
        this.sendBuffers.push(buffer);
    }
};

Module.prototype.isRecentData = function(port, type, data) {
    var that = this;
    var isRecent = false;

    if(type == this.sensorTypes.ULTRASONIC) {
        var portString = port.toString();
        var isGarbageClear = false;
        Object.keys(this.recentCheckData).forEach(function (key) {
            var recent = that.recentCheckData[key];
            if(key === portString) {

            }
            if(key !== portString && recent.type == that.sensorTypes.ULTRASONIC) {
                delete that.recentCheckData[key];
                isGarbageClear = true;
            }
        });

        if((port in this.recentCheckData && isGarbageClear) || !(port in this.recentCheckData)) {
            isRecent = false;
        } else {
            isRecent = true;
        }

    } else if (port in this.recentCheckData && type != this.sensorTypes.TONE) {
        if (
            this.recentCheckData[port].type === type &&
            this.recentCheckData[port].data === data
        ) {
            isRecent = true;
        }
    }

    return isRecent;
};

Module.prototype.requestLocalData = function() {
    var self = this;

    if (!this.isDraing && this.sendBuffers.length > 0) {
        this.isDraing = true;
        this.sp.write(this.sendBuffers.shift(), function() {
            if (self.sp) {
                self.sp.drain(function() {
                    self.isDraing = false;
                });
            }
        });
    }

    return null;
};

/*
ff 55 idx size data a
*/
Module.prototype.handleLocalData = function(data) {
    var self = this;
    var datas = this.getDataByBuffer(data);

    datas.forEach(function(data) {
        if (data.length <= 4 || data[0] !== 255 || data[1] !== 85) {
            return;
        }
        var readData = data.subarray(2, data.length);
        var value;
        switch (readData[0]) {
            case self.sensorValueSize.FLOAT: {
                value = new Buffer(readData.subarray(1, 5)).readFloatLE();
                value = Math.round(value * 100) / 100;
                break;
            }
            case self.sensorValueSize.SHORT: {
                value = new Buffer(readData.subarray(1, 3)).readInt16LE();
                break;
            }
            default: {
                value = 0;
                break;
            }
        }

        var type = readData[readData.length - 1];
        var port = readData[readData.length - 2];

        switch (type) {
            case self.sensorTypes.DIGITAL: {
                self.sensorData.DIGITAL[port] = value;
                break;
            }
            case self.sensorTypes.ANALOG: {
                self.sensorData.ANALOG[port] = value;
                break;
            }
            case self.sensorTypes.PULSEIN: {
                self.sensorData.PULSEIN[port] = value;
                break;
            }
            case self.sensorTypes.ULTRASONIC: {
                self.sensorData.ULTRASONIC = value;
                break;
            }
            case self.sensorTypes.TIMER: {
                self.sensorData.TIMER = value;
                break;
            }
            default: {
                break;
            }
        }
    });
};

/*
ff 55 len idx action device port  slot  data a
0  1  2   3   4      5      6     7     8
*/

Module.prototype.makeSensorReadBuffer = function(device, port, data) {
    var buffer;
    var dummy = new Buffer([10]);
    if (device == this.sensorTypes.ULTRASONIC) {
        buffer = new Buffer([
            255,
            85,
            6,
            sensorIdx,
            this.actionTypes.GET,
            device,
            port[0],
            port[1],
            10,
        ]);
    } else if (!data) {
        buffer = new Buffer([
            255,
            85,
            5,
            sensorIdx,
            this.actionTypes.GET,
            device,
            port,
            10,
        ]);
    } else {
        value = new Buffer(2);
        value.writeInt16LE(data);
        buffer = new Buffer([
            255,
            85,
            7,
            sensorIdx,
            this.actionTypes.GET,
            device,
            port,
            10,
        ]);
        buffer = Buffer.concat([buffer, value, dummy]);
    }
    sensorIdx++;
    if (sensorIdx > 254) {
        sensorIdx = 0;
    }

    return buffer;
};

//0xff 0x55 0x6 0x0 0x1 0xa 0x9 0x0 0x0 0xa
Module.prototype.makeOutputBuffer = function(device, port, data) {
    var buffer;
    var value = new Buffer(2);
    var dummy = new Buffer([10]);

    switch (device) {
        case this.sensorTypes.SERVO_PIN:
        case this.sensorTypes.DIGITAL:
        case this.sensorTypes.PWM:
        case this.sensorTypes.METRIXCLEAR:
        case this.sensorTypes.METRIXDRAW:
        case this.sensorTypes.NEOPIXELCLEAR:
        case this.sensorTypes.NEOPIXELRAINBOW:
        {
            value.writeInt16LE(data);

            buffer = new Buffer([
                255,
                85,
                6,
                sensorIdx,
                this.actionTypes.SET,
                device,
                port,
            ]);
            buffer = Buffer.concat([buffer, value, dummy]);
            break;
        }
        case this.sensorTypes.METRIX:
        case this.sensorTypes.METRIXROWCOLCLEAR:
        {
            var value2 = new Buffer(2);
            if ($.isPlainObject(data)) {
                value.writeInt16LE(data.value1);
                value2.writeInt16LE(data.value2);
            } else {
                value.writeInt16LE(0);
                value2.writeInt16LE(0);
            }

            buffer = new Buffer([
                255,
                85,
                8,
                sensorIdx,
                this.actionTypes.SET,
                device,
                port,
            ]);
            buffer = Buffer.concat([buffer, value, value2, dummy]);
            break;
        }
        case this.sensorTypes.NEOPIXELINIT:{
            var bright = new Buffer(2);
            var neo_count = new Buffer(2);

            if ($.isPlainObject(data)) {
                neo_count.writeInt16LE(data.value1);
                bright.writeInt16LE(data.value2);
            } else {
                neo_count.writeInt16LE(0);
                bright.writeInt16LE(0);
            }

            buffer = new Buffer([
                255,
                85,
                8,
                sensorIdx,
                this.actionTypes.SET,
                device,
                port,
            ]);
            buffer = Buffer.concat([buffer, neo_count, bright, dummy]);
            break;
        }
        case this.sensorTypes.NEOPIXEL:{
            //var count_value = new Buffer(2);
            var r_value = new Buffer(2);
            var g_value = new Buffer(2);
            var b_value = new Buffer(2);

            if ($.isPlainObject(data)) {
               // count_value.writeInt16LE(data.count);
                r_value.writeInt16LE(data.R_val);
                g_value.writeInt16LE(data.G_val);
                b_value.writeInt16LE(data.B_val);
            } else {
                //count_value.writeInt16LE(0);
                r_value.writeInt16LE(0);
                g_value.writeInt16LE(0);
                b_value.writeInt16LE(0);
            }

            buffer = new Buffer([
                255,
                85,
                10,
                sensorIdx,
                this.actionTypes.SET,
                device,
                port,
            ]);
            buffer = Buffer.concat([buffer, r_value, g_value, b_value, dummy]);
            break;
        }
        case this.sensorTypes.TONE: {
            var time = new Buffer(2);
            if ($.isPlainObject(data)) {
                value.writeInt16LE(data.value);
                time.writeInt16LE(data.duration);
            } else {
                value.writeInt16LE(0);
                time.writeInt16LE(0);
            }
            buffer = new Buffer([
                255,
                85,
                8,
                sensorIdx,
                this.actionTypes.SET,
                device,
                port,
            ]);
            buffer = Buffer.concat([buffer, value, time, dummy]);
            break;
        }
    }

    return buffer;
};

Module.prototype.getDataByBuffer = function(buffer) {
    var datas = [];
    var lastIndex = 0;
    buffer.forEach(function(value, idx) {
        if (value == 13 && buffer[idx + 1] == 10) {
            datas.push(buffer.subarray(lastIndex, idx));
            lastIndex = idx + 2;
        }
    });

    return datas;
};

Module.prototype.disconnect = function(connect) {
    var self = this;
    connect.close();
    if (self.sp) {
        delete self.sp;
    }
};

Module.prototype.reset = function() {
    this.lastTime = 0;
    this.lastSendTime = 0;

    this.sensorData.PULSEIN = {};
};

module.exports = new Module();
<|endoftext|>


<commit_before>/**
 * add two digits with carry
 * @author sarkiroka on 2017.07.02.
 */
var addTable = require('./add-table.json');
module.exports = function addDigits(a, b, carry) {
	var retValue = addTable[a + b];
	if (!retValue) {
		retValue = addTable[b + a];
	}
	if (!retValue) {
		retValue = null;
	} else {
		if (carry) {
			var previousCarry = retValue.carry;
			retValue = addDigits('1', retValue.result, false);
			retValue.carry |= previousCarry;
		}
	}
	return retValue;
};
<commit_msg>fractions<commit_after>/**
 * add two digits with carry
 * @author sarkiroka on 2017.07.02.
 */
var addTable = require('./add-table.json');
module.exports = function addDigits(a, b, carry) {
	var retValue = addTable[a + b];
	if (!retValue) {
		retValue = addTable[b + a];
	}
	if (!retValue) {
		if(a=='.' && b=='.'){
			retValue={result:'.',carry:carry};
		}else {
			retValue = null;
		}
	} else {
		if (carry) {
			var previousCarry = retValue.carry;
			retValue = addDigits('1', retValue.result, false);
			retValue.carry |= previousCarry;
		}
	}
	return retValue;
};
<|endoftext|>


<commit_before>core.service("AbstractRepo", function ($rootScope, $q, WsApi, ValidationStore) {

    return function AbstractRepo(modelName, model, mapping) {

        var abstractRepo = this;

        abstractRepo.mapping = mapping;

        var list = [];

        var defer = $q.defer();

        var listenCallbacks = [];

        var validations = ValidationStore.getValidations(modelName);

        $rootScope.$on("$locationChangeSuccess", function () {
            listenCallbacks.length = 0;
        });

        var build = function (data) {
            return $q(function (resolve) {
                list.length = 0;
                angular.forEach(data, function (modelJson) {
                    abstractRepo.add(modelJson);
                });
                resolve();
            });
        };

        var unwrap = function (res) {
            var repoObj = {};
            var payload = angular.fromJson(res.body).payload;
            var keys = Object.keys(payload);
            angular.forEach(keys, function (key) {
                angular.extend(repoObj, payload[key]);
            });
            return repoObj;
        };

        var fetch = function () {
            if (abstractRepo.mapping.all !== undefined) {
                WsApi.fetch(abstractRepo.mapping.all).then(function (res) {
                    build(unwrap(res)).then(function () {
                        defer.resolve(res);
                    });
                });
            }
        };

        WsApi.listen(abstractRepo.mapping.listen).then(null, null, function (res) {
            build(unwrap(res)).then(function () {
                angular.forEach(listenCallbacks, function (cb) {
                    cb(res);
                });
            });
        });

        if (!mapping.lazy) {
            fetch();
        }

        abstractRepo.ValidationResults = {};

        abstractRepo.add = function (modelJson) {
            list.push(new model(modelJson));
        };

        abstractRepo.addAll = function (modelJsons) {
            for (var i in modelJsons) {
                abstractRepo.add(modelJsons[i]);
            }
        };

        abstractRepo.remove = function (modelToRemove) {
            for (var i in list) {
                if (list[i].id === modelToRemove.id) {
                    list.splice(i, 1);
                    break;
                }
            }
        };

        abstractRepo.empty = function () {
            list.length = 0;
        };

        abstractRepo.getEntityName = function () {
            return modelName;
        };

        abstractRepo.getValidations = function () {
            return validations;
        };

        abstractRepo.count = function () {
            return list.length;
        };

        abstractRepo.getAll = function () {
            if (mapping.lazy) {
                fetch();
            }
            return abstractRepo.getContents();
        };

        abstractRepo.getContents = function () {
            return list;
        };

        abstractRepo.saveAll = function () {
            angular.forEach(list, function (model) {
                model.save();
            });
        };

        abstractRepo.ready = function () {
            return defer.promise;
        };

        abstractRepo.reset = function () {
            defer = $q.defer();
            fetch();
        };

        abstractRepo.findById = function (id) {
            for (var i in list) {
                if (list[i].id == id) {
                    return list[i];
                }
            }
        };

        abstractRepo.delete = function (model) {
            abstractRepo.clearValidationResults();
            var promise = model.delete();
            promise.then(function (res) {
                if (angular.fromJson(res.body).meta.type == "INVALID") {
                    angular.extend(abstractRepo, angular.fromJson(res.body).payload);
                }
            });
            return promise;
        };

        abstractRepo.deleteById = function (id) {
            abstractRepo.clearValidationResults();
            var promise = abstractRepo.findById(id).delete();
            promise.then(function (res) {
                if (angular.fromJson(res.body).meta.type == "INVALID") {
                    angular.extend(abstractRepo, angular.fromJson(res.body).payload);
                }
            });
            return promise;
        };

        abstractRepo.create = function (model) {
            abstractRepo.clearValidationResults();
            angular.extend(abstractRepo.mapping.create, {
                'data': model
            });
            var promise = WsApi.fetch(abstractRepo.mapping.create);
            promise.then(function (res) {
                if (angular.fromJson(res.body).meta.type == "INVALID") {
                    angular.extend(abstractRepo, angular.fromJson(res.body).payload);
                }
            });
            return promise;
        };

        // TODO: remove
        abstractRepo.update = function (model) {
            abstractRepo.clearValidationResults();
            var promise = model.save();
            promise.then(function (res) {
                if (angular.fromJson(res.body).meta.type == "INVALID") {
                    angular.extend(abstractRepo, angular.fromJson(res.body).payload);
                }
            });
            return promise;
        };

        abstractRepo.listen = function (cb) {
            listenCallbacks.push(cb);
        };

        // additiona core level repo methods and variables

        // these should be added through decoration
        abstractRepo.sort = function (facet) {
            abstractRepo.clearValidationResults();
            angular.extend(abstractRepo.mapping.sort, {
                'method': 'sort/' + facet
            });
            var promise = WsApi.fetch(abstractRepo.mapping.sort);
            promise.then(function (res) {
                if (angular.fromJson(res.body).meta.type == "INVALID") {
                    angular.extend(abstractRepo, angular.fromJson(res.body).payload);
                    console.log(abstractRepo);
                }
            });
            return promise;
        };

        abstractRepo.reorder = function (src, dest) {
            abstractRepo.clearValidationResults();
            angular.extend(abstractRepo.mapping.reorder, {
                'method': 'reorder/' + src + '/' + dest
            });
            var promise = WsApi.fetch(abstractRepo.mapping.reorder);
            promise.then(function (res) {
                if (angular.fromJson(res.body).meta.type == "INVALID") {
                    angular.extend(abstractRepo, angular.fromJson(res.body).payload);
                    console.log(abstractRepo);
                }
            });
            return promise;
        };

        abstractRepo.getValidationResults = function () {
            return abstractRepo.ValidationResults;
        };

        abstractRepo.clearValidationResults = function () {
            if (abstractRepo.ValidationResults.messages !== undefined) {
                delete abstractRepo.ValidationResults.messages;
            }
        };

        return abstractRepo;
    }

});
<commit_msg>Fixed more lint warnings. Repo check mappings whether to get validations.<commit_after>core.service("AbstractRepo", function ($rootScope, $q, WsApi, ValidationStore) {

    return function AbstractRepo(modelName, model, mapping) {

        var abstractRepo = this;

        abstractRepo.mapping = mapping;

        var list = [];

        var defer = $q.defer();

        var listenCallbacks = [];

        var validations = {};

        if (abstractRepo.mapping.validations) {
            validations = ValidationStore.getValidations(modelName);
        }

        $rootScope.$on("$locationChangeSuccess", function () {
            listenCallbacks.length = 0;
        });

        var build = function (data) {
            return $q(function (resolve) {
                list.length = 0;
                angular.forEach(data, function (modelJson) {
                    abstractRepo.add(modelJson);
                });
                resolve();
            });
        };

        var unwrap = function (res) {
            var repoObj = {};
            var payload = angular.fromJson(res.body).payload;
            var keys = Object.keys(payload);
            angular.forEach(keys, function (key) {
                angular.extend(repoObj, payload[key]);
            });
            return repoObj;
        };

        var fetch = function () {
            if (abstractRepo.mapping.all !== undefined) {
                WsApi.fetch(abstractRepo.mapping.all).then(function (res) {
                    build(unwrap(res)).then(function () {
                        defer.resolve(res);
                    });
                });
            }
        };

        WsApi.listen(abstractRepo.mapping.listen).then(null, null, function (res) {
            build(unwrap(res)).then(function () {
                angular.forEach(listenCallbacks, function (cb) {
                    cb(res);
                });
            });
        });

        if (!mapping.lazy) {
            fetch();
        }

        abstractRepo.ValidationResults = {};

        abstractRepo.add = function (modelJson) {
            list.push(new model(modelJson));
        };

        abstractRepo.addAll = function (modelJsons) {
            for (var i in modelJsons) {
                abstractRepo.add(modelJsons[i]);
            }
        };

        abstractRepo.remove = function (modelToRemove) {
            for (var i in list) {
                if (list[i].id === modelToRemove.id) {
                    list.splice(i, 1);
                    break;
                }
            }
        };

        abstractRepo.empty = function () {
            list.length = 0;
        };

        abstractRepo.getEntityName = function () {
            return modelName;
        };

        abstractRepo.getValidations = function () {
            return validations;
        };

        abstractRepo.count = function () {
            return list.length;
        };

        abstractRepo.getAll = function () {
            if (mapping.lazy) {
                fetch();
            }
            return abstractRepo.getContents();
        };

        abstractRepo.getContents = function () {
            return list;
        };

        abstractRepo.saveAll = function () {
            angular.forEach(list, function (model) {
                model.save();
            });
        };

        abstractRepo.ready = function () {
            return defer.promise;
        };

        abstractRepo.reset = function () {
            defer = $q.defer();
            fetch();
        };

        abstractRepo.findById = function (id) {
            for (var i in list) {
                if (list[i].id == id) {
                    return list[i];
                }
            }
        };

        abstractRepo.delete = function (model) {
            abstractRepo.clearValidationResults();
            var promise = model.delete();
            promise.then(function (res) {
                if (angular.fromJson(res.body).meta.type === "INVALID") {
                    angular.extend(abstractRepo, angular.fromJson(res.body).payload);
                }
            });
            return promise;
        };

        abstractRepo.deleteById = function (id) {
            abstractRepo.clearValidationResults();
            var promise = abstractRepo.findById(id).delete();
            promise.then(function (res) {
                if (angular.fromJson(res.body).meta.type === "INVALID") {
                    angular.extend(abstractRepo, angular.fromJson(res.body).payload);
                }
            });
            return promise;
        };

        abstractRepo.create = function (model) {
            abstractRepo.clearValidationResults();
            angular.extend(abstractRepo.mapping.create, {
                'data': model
            });
            var promise = WsApi.fetch(abstractRepo.mapping.create);
            promise.then(function (res) {
                if (angular.fromJson(res.body).meta.type === "INVALID") {
                    angular.extend(abstractRepo, angular.fromJson(res.body).payload);
                }
            });
            return promise;
        };

        // TODO: remove
        abstractRepo.update = function (model) {
            abstractRepo.clearValidationResults();
            var promise = model.save();
            promise.then(function (res) {
                if (angular.fromJson(res.body).meta.type === "INVALID") {
                    angular.extend(abstractRepo, angular.fromJson(res.body).payload);
                }
            });
            return promise;
        };

        abstractRepo.listen = function (cb) {
            listenCallbacks.push(cb);
        };

        // additiona core level repo methods and variables

        // these should be added through decoration
        abstractRepo.sort = function (facet) {
            abstractRepo.clearValidationResults();
            angular.extend(abstractRepo.mapping.sort, {
                'method': 'sort/' + facet
            });
            var promise = WsApi.fetch(abstractRepo.mapping.sort);
            promise.then(function (res) {
                if (angular.fromJson(res.body).meta.type === "INVALID") {
                    angular.extend(abstractRepo, angular.fromJson(res.body).payload);
                    console.log(abstractRepo);
                }
            });
            return promise;
        };

        abstractRepo.reorder = function (src, dest) {
            abstractRepo.clearValidationResults();
            angular.extend(abstractRepo.mapping.reorder, {
                'method': 'reorder/' + src + '/' + dest
            });
            var promise = WsApi.fetch(abstractRepo.mapping.reorder);
            promise.then(function (res) {
                if (angular.fromJson(res.body).meta.type === "INVALID") {
                    angular.extend(abstractRepo, angular.fromJson(res.body).payload);
                }
            });
            return promise;
        };

        abstractRepo.getValidationResults = function () {
            return abstractRepo.ValidationResults;
        };

        abstractRepo.clearValidationResults = function () {
            if (abstractRepo.ValidationResults.messages !== undefined) {
                delete abstractRepo.ValidationResults.messages;
            }
        };

        return abstractRepo;
    }

});
<|endoftext|>


<commit_before>var
	_ = require('underscore'),
	domain = require('domain'),
	d = domain.create(),
	express = require('express'),
	router = express.Router(),
	config = require('../../config/config'),
	Slack = require('slack-client'),
	slackConfigService = require('../services/slackConfigService');

d.on('error', function(err) {
	console.log("Unable to process actions.");
	console.log(err);
});

var connections = {};

module.exports = function (app) {
  app.use('/actions', router);
};

router.route('/')
	/* POST actions */
	.post(function (req, res) {
		d.run(function() {
			var actions = req.body;

			console.log("Received " + actions.length + " actions on REST API.");

			_.each(actions, function (action) {
				if (_.isUndefined(connections[action.instanceId])) {
					var slack = slackConfigService.get(action.instanceId).slack;

					console.log("Action: " + action.typeId);

					if (action.typeId === config.app.actionType) {
						var channelName = action.payload.channel;
						var message = action.payload.message;
						var channel = slack.getChannelByName(channelName);

						console.log("Sending " + message + " to " + channelName);
						if (channel !== undefined && message !== undefined && message !== "") {
							channel.send(message);
						}
					}
				}
			});

			res.status(204).send();
		});
	});<commit_msg>Fixed small issue with typeId vs. type<commit_after>var
	_ = require('underscore'),
	domain = require('domain'),
	d = domain.create(),
	express = require('express'),
	router = express.Router(),
	config = require('../../config/config'),
	Slack = require('slack-client'),
	slackConfigService = require('../services/slackConfigService');

d.on('error', function(err) {
	console.log("Unable to process actions.");
	console.log(err);
});

var connections = {};

module.exports = function (app) {
  app.use('/actions', router);
};

router.route('/')
	/* POST actions */
	.post(function (req, res) {
		d.run(function() {
			var actions = req.body;

			console.log("Received " + actions.length + " actions on REST API.");

			_.each(actions, function (action) {
				if (_.isUndefined(connections[action.instanceId])) {
					var slack = slackConfigService.get(action.instanceId).slack;

					console.log("Action: " + action.type);

					if (action.type === config.app.actionType) {
						var channelName = action.payload.channel;
						var message = action.payload.message;
						var channel = slack.getChannelByName(channelName);

						console.log("Sending " + message + " to " + channelName);
						if (channel !== undefined && message !== undefined && message !== "") {
							channel.send(message);
						}
					}
				}
			});

			res.status(204).send();
		});
	});<|endoftext|>


<commit_before>'use strict';

angular.module('repicbro.constants')
  .constant('constants', {
    'apiPrefix' : 'http://www.reddit.com/r/',
    'blacklist': [
      /imgur\.com\/gallery/,
      /imgur\.com\/a\//,
      /www\.reddit\.com/,
      /www\.flickr\.com/
    ],
    'subreddits': [
      'funny',
      'pics',
      'gifs',
      'aww',
      'earthporn',
      'adviceanimals',
      'minecraft'
    ]
  });
<commit_msg>Adds perfect loops to default subreddits<commit_after>'use strict';

angular.module('repicbro.constants')
  .constant('constants', {
    'apiPrefix' : 'http://www.reddit.com/r/',
    'blacklist': [
      /imgur\.com\/gallery/,
      /imgur\.com\/a\//,
      /www\.reddit\.com/,
      /www\.flickr\.com/
    ],
    'subreddits': [
      'funny',
      'pics',
      'gifs',
      'aww',
      'earthporn',
      'adviceanimals',
      'minecraft',
      'perfectloops'
    ]
  });
<|endoftext|>


<commit_before>google.setOnLoadCallback(drawChart);

function drawChart() {
	var flu_data = [];
	flu_data.month = ['August', 'September', 'September', 'September', 'September', 'October', 'October', 'October', 'October', 'October', 'November', 'November', 'November', 'November', 'December', 'December', 'December', 'December', 'February', 'February', 'February', 'February', 'February', 'March', 'March', 'March', 'March', 'April', 'April', 'April', 'April', 'May', 'May', 'May', 'May', 'May', 'March', 'March', 'March', 'March', 'June', 'June', 'June', 'June', 'July', 'July', 'July', 'July', 'July', 'August', 'August', 'August'];
	flu_data.week = [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34];

	// Will probably move this to a data.js or something
	/* Flu data taken from http://open.canada.ca/data/en/dataset/178f04f7-5a3a-40ad-991f-25be84b4868c */
	flu_data.hospital = [0, 0, 0, 0, 3, 2, 2, 1, 2, 5.5, 6.5, 6.5, 12.5, 31, 44, 66.5, 113, 163.5, 181, 129, 118.5, 109, 108.5, 102.5, 102.5, 121.5, 121.5, 149, 152, 121.5, 94.5, 60.5, 73.5, 42.5, 36, 32.5, 22.5, 18, 8, 3.5, 4, 1, 1, 0, 0, 1.5, 1.5, 0, 0, 0, 0, 1];
	flu_data.death = [0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0, 0.5, 0, 0.5, 1, 0.5, 2.5, 5.5, 8, 13, 11.5, 9.5, 14.5, 9, 7, 5.5, 4.5, 8.5, 8.5, 7.5, 8.5, 9, 4, 3, 2.5, 2.5, 2, 1, 1, 1.5, 0.5, 0, 0, 0, 0, 0, 0, 0, 0.5, 0, 0, 0, 0];

	thisWeek = getCurrentWeek();

	var splitData = [];
	splitData.push(['Week', 'Deaths so far', 'Deaths to come']);

	var i = 0, soFar = 0, left = 0;
	while (flu_data.week[i] != thisWeek) {
		soFar += flu_data.death[i];
		splitData.push([flu_data.month[i],flu_data.death[i],0]);
		i++;
	}
	for (var i;i<52;i++) {
		left += flu_data.death[i];
		splitData.push([flu_data.month[i],0,flu_data.death[i]]);
	}

	var data = google.visualization.arrayToDataTable(splitData);

	var options = {
		title: 'Deaths from influenza in 2010-2011 by today',
		hAxis: {title: 'Week',  titleTextStyle: {color: '#333'}},
		vAxis: {minValue: 0}
	};

	var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
	chart.draw(data, options);
}

function getCurrentDay(){
	var now = new Date();
	var start = new Date(now.getFullYear(), 0, 0);
	var diff = now - start;
	var oneDay = 1000 * 60 * 60 * 24;
	return Math.floor(diff / oneDay);
}

function getCurrentWeek(){
	return Math.min(Math.floor(getCurrentDay()/7)+1,52);
}
<commit_msg>Undoing matt's harm<commit_after>google.setOnLoadCallback(drawChart);

function drawChart() {
	var flu_data = [];
	flu_data.month = ['August', 'September', 'September', 'September', 'September', 'October', 'October', 'October', 'October', 'October', 'November', 'November', 'November', 'November', 'December', 'December', 'December', 'December', 'February', 'February', 'February', 'February', 'February', 'March', 'March', 'March', 'March', 'April', 'April', 'April', 'April', 'May', 'May', 'May', 'May', 'May', 'March', 'March', 'March', 'March', 'June', 'June', 'June', 'June', 'July', 'July', 'July', 'July', 'July', 'August', 'August', 'August'];
	flu_data.week = [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34];

	// Will probably move this to a data.js or something
	/* Flu data taken from http://open.canada.ca/data/en/dataset/178f04f7-5a3a-40ad-991f-25be84b4868c */
	flu_data.hospital = [0, 0, 0, 0, 3, 2, 2, 1, 2, 5.5, 6.5, 6.5, 12.5, 31, 44, 66.5, 113, 163.5, 181, 129, 118.5, 109, 108.5, 102.5, 102.5, 121.5, 121.5, 149, 152, 121.5, 94.5, 60.5, 73.5, 42.5, 36, 32.5, 22.5, 18, 8, 3.5, 4, 1, 1, 0, 0, 1.5, 1.5, 0, 0, 0, 0, 1];
	flu_data.death = [0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0, 0.5, 0, 0.5, 1, 0.5, 2.5, 5.5, 8, 13, 11.5, 9.5, 14.5, 9, 7, 5.5, 4.5, 8.5, 8.5, 7.5, 8.5, 9, 4, 3, 2.5, 2.5, 2, 1, 1, 1.5, 0.5, 0, 0, 0, 0, 0, 0, 0, 0.5, 0, 0, 0, 0];

	thisWeek = getCurrentWeek();

	var splitData = [];
	splitData.push(['Week', 'Deaths so far', 'Deaths to come']);

	var i = 0, soFar = 0, left = 0;
	while (flu_data.week[i] != thisWeek) {
		soFar += flu_data.death[i];
		splitData.push([flu_data.month[i],flu_data.death[i],0]);
		i++;
	}
	//Keep incrementing "i" with the next graph
	for (;i<52;i++) {
		left += flu_data.death[i];
		splitData.push([flu_data.month[i],0,flu_data.death[i]]);
	}

	var data = google.visualization.arrayToDataTable(splitData);

	var options = {
		title: 'Deaths from influenza in 2010-2011 by today',
		hAxis: {title: 'Week',  titleTextStyle: {color: '#333'}},
		vAxis: {minValue: 0}
	};

	var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
	chart.draw(data, options);
}

function getCurrentDay(){
	var now = new Date();
	var start = new Date(now.getFullYear(), 0, 0);
	var diff = now - start;
	var oneDay = 1000 * 60 * 60 * 24;
	return Math.floor(diff / oneDay);
}

function getCurrentWeek(){
	return Math.min(Math.floor(getCurrentDay()/7)+1,52);
}
<|endoftext|>


<commit_before>// var tessel = require('tessel');
var events = require('events');
var util = require('util');
var gpio = require("gpio");

// pin 38 GPIO 20 - for trigger
var trig = gpio.export(38, {
   direction: "out",
   ready: function() {
   }
});

// pin 37 GPIO 26 - for echo
var echo = gpio.export(37, {
   direction: "in",
   ready: function() {
   }
});

function Proximity(callback) {

  setImmediate(function ready() {
    this.emit('ready');
  }.bind(this));

  if (callback) {
    callback(null, this);
  }
  return this;
}

util.inherits(Proximity, events.EventEmitter);

Proximity.prototype.triggerRead = function() {
  this.trig.write(1);
  setTimeout(function off() {
    this.trig.write(0);
  }.bind(this), 10);
}

Proximity.prototype.getDistance = function(callback) {
  this.triggerRead(trig);
  this.echo.readPulse('high', 1000, function(err, duration) {

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

    var distance = ((duration * 1000)/2) / 29.1;

    setImmediate(function() {
      this.emit('data', distance);
    }.bind(this));

    if (callback) {
      callback(null, distance);
    }
  }.bind(this));
}

function use(callback) {
  return new Proximity(callback);
}

module.exports.getDistance;
module.exports.use = use;
module.exports.Proximity = Proximity;
<commit_msg>WIP motion.js 5<commit_after>// var tessel = require('tessel');
var events = require('events');
var util = require('util');
var gpio = require("gpio");

// pin 38 GPIO 20 - for trigger
var trig = gpio.export(38, {
   direction: "out",
   ready: function() {
   }
});

// pin 37 GPIO 26 - for echo
var echo = gpio.export(37, {
   direction: "in",
   ready: function() {
   }
});

function Proximity(callback) {
  setImmediate(function ready() {
    this.emit('ready');
  }.bind(this));

  if (callback) {
    callback(null, this);
  }
  return this;
}

util.inherits(Proximity, events.EventEmitter);

Proximity.prototype.trigger = function() {
  this.trig.set(1);
  setTimeout(function off() {
    this.trig.set(0);
  }.bind(this), 10);
}

Proximity.prototype.getDistance = function(callback) {

  var pulseStart = Date.now();
  var pulseEnd = Date.now();
  this.trigger(trig);
  while(this.echo.value == 0) {
    pulseStart = Date.now();
  }

  while(this.echo.value == 1) {
    pulseEnd = Date.now();
  }

  let duration = pulseEnd - pulseStart;
  let distance = duration * 17150;
  let centimeters = Math.round(distance * 100) / 100;
  console.log("centimeters: " + centimeters);
  var distance = ((duration * 1000)/2) / 29.1;
  if (callback) {
    callback(null, distance);
  }
}.bind(this));

function use(callback) {
  return new Proximity(callback);
}

module.exports.getDistance;
module.exports.use = use;
module.exports.Proximity = Proximity;
<|endoftext|>


<commit_before>const moment = require('moment');
const RSS = require('rss');
const ejs = require('ejs');

const config = require('config/config.js');

const Campaign = require('models/Campaign.js');
const Action = require('models/Action.js');

const getContext = (action) => {

  const useTodaysDate = action.ongoing || !moment(action.start_time).isValid();
  const dateToUse = useTodaysDate ? moment() : moment(action.start_time);
  const pubDate = dateToUse.toISOString();
  const prettyDate = dateToUse.format('dddd, MMMM Do YYYY, h:mm a');
  const hasLocation = action.city || action.state;

  return {
    action,
    prettyDate,
    hasLocation,
    pubDate,
  };
}

module.exports = async (app) => {

  app.get('/api/rss/campaign/:slug', async (req, res, next) => {

    try {
      const slug = req.params.slug;
      const campaign = await Campaign.findOne({ slug });

      const feed = new RSS({
        title: `${campaign.title} upcoming volunteer opportunities`,
        description: campaign.description,
        feed_url: `${config.urls.api}/api/rss/campaign/${slug}`,
        site_url: campaign.public_url,
        pubDate: moment().toISOString(),
      });

      const actions = campaign.actions.filter(action => {
        return moment(action.end_time).isAfter(moment()) || action.ongoing
      });

      await Promise.all(actions.map( async (action) => {
        Object.assign(action, await Action.details(action, true));
        action.campaign_title = campaign.title;

        const context = getContext(action);

        ejs.renderFile(config.paths.base + '/views/action-description-rss.ejs', context, function (err, textBody) {
          if (err) {
            throw new Error(err);
          } else {
            feed.item({
              title: action.title,
              author: campaign.title,
              guid: action.id,
              description: textBody,
              url: action.public_url,
              pubDate: context.pubDate,
            });
          }
        });
      }));

      return res.send(feed.xml());

    } catch (e) {
      next(e);
    }
  });

  app.get('/api/rss/:search', async (req, res, next) => {

    try {
      const search = req.params.search;
      const actionSearch = await Action.search({
        keywords: [search],
        dates: {
          startDate: moment().format(),
          ongoing: true,
        },
      });

      const actions = actionSearch.actions;

      const feed = new RSS({
        title: `UpRise volunteer opportunities`,
        description: `Opportunities matching keyword: ${search}`,
        feed_url: `${config.urls.api}/api/rss/${search}`,
        site_url: `${config.urls.client}/${search}`,
        pubDate: moment().format(),
      });

      await Promise.all(actions.map( async (action) => {
        Object.assign(action, await Action.details(action, false));

        const context = getContext(action);

        ejs.renderFile(config.paths.base + '/views/action-description-rss.ejs', context, function (err, textBody) {
          if (err) {
            throw new Error(err);
          } else {
            feed.item({
              title: action.title,
              author: action.campaign_title,
              guid: action.id,
              description: textBody,
              url: action.public_url,
              pubDate: context.pubDate,
            });
          }
        });

      }));

      return res.send(feed.xml());

    } catch (e) {
      next(e);
    }
  });

}

<commit_msg>Adding campaign title to rss feed action search results titles and image urls.<commit_after>const moment = require('moment');
const RSS = require('rss');
const ejs = require('ejs');

const config = require('config/config.js');

const Campaign = require('models/Campaign.js');
const Action = require('models/Action.js');

const getContext = (action) => {

  const useTodaysDate = action.ongoing || !moment(action.start_time).isValid();
  const dateToUse = useTodaysDate ? moment() : moment(action.start_time);
  const pubDate = dateToUse.toISOString();
  const prettyDate = dateToUse.format('dddd, MMMM Do YYYY, h:mm a');
  const hasLocation = action.city || action.state;

  return {
    action,
    prettyDate,
    hasLocation,
    pubDate,
  };
}

module.exports = async (app) => {

  app.get('/api/rss/campaign/:slug', async (req, res, next) => {

    try {
      const slug = req.params.slug;
      const campaign = await Campaign.findOne({ slug });

      console.log(campaign.profile_image_url);
      const feed = new RSS({
        title: `${campaign.title} upcoming volunteer opportunities`,
        description: campaign.description,
        feed_url: `${config.urls.api}/api/rss/campaign/${slug}`,
        site_url: campaign.public_url,
        image_url: campaign.profile_image_url,
        pubDate: moment().toISOString(),
      });

      const actions = campaign.actions.filter(action => {
        return moment(action.end_time).isAfter(moment()) || action.ongoing
      });

      await Promise.all(actions.map( async (action) => {
        Object.assign(action, await Action.details(action, true));
        action.campaign_title = campaign.title;

        const context = getContext(action);

        ejs.renderFile(config.paths.base + '/views/action-description-rss.ejs', context, function (err, textBody) {
          if (err) {
            throw new Error(err);
          } else {
            feed.item({
              title: action.title,
              author: campaign.title,
              guid: action.id,
              description: textBody,
              url: action.public_url,
              pubDate: context.pubDate,
            });
          }
        });
      }));

      return res.send(feed.xml());

    } catch (e) {
      next(e);
    }
  });

  app.get('/api/rss/:search', async (req, res, next) => {

    try {
      const search = req.params.search;
      const actionSearch = await Action.search({
        keywords: [search],
        dates: {
          startDate: moment().format(),
          ongoing: true,
        },
      });

      const actions = actionSearch.actions;

      const feed = new RSS({
        title: `UpRise Volunteer Opportunities`,
        description: `Opportunities matching keyword: ${search}`,
        feed_url: `${config.urls.api}/api/rss/${search}`,
        site_url: `${config.urls.client}/${search}`,
        // TODO: Replace this with a relative link to an image we are hosting!
        image_url: 'https://upriseweb.files.wordpress.com/2017/06/cropped-headerlogowspace.png',
        pubDate: moment().format(),
      });

      await Promise.all(actions.map( async (action) => {
        Object.assign(action, await Action.details(action, false));

        const context = getContext(action);

        ejs.renderFile(config.paths.base + '/views/action-description-rss.ejs', context, function (err, textBody) {
          if (err) {
            throw new Error(err);
          } else {
            feed.item({
              title: `${action.campaign_title} - ${action.title}`,
              author: action.campaign_title,
              guid: action.id,
              description: textBody,
              url: action.public_url,
              pubDate: context.pubDate,
            });
          }
        });

      }));

      return res.send(feed.xml());

    } catch (e) {
      next(e);
    }
  });

}

<|endoftext|>


<commit_before>import Service from '@ember/service';
import ENV from 'bracco/config/environment';
import environment from 'config/environment';
import fetch from 'fetch';

export default Service.extend({

  init() {
    this._super(...arguments);
    this.min = 50;
    this.msg_zero = "There are 0 prefixes available. Request new prefixes from CNRI.";
    this.msg_min = "There are fewer than 50 prefixes available. Contact CNRI and request more prefixes.";
  },

  get_n_available() {
    let promise = new Promise((resolve, reject) => {
      const url = ENV.API_URL + '/prefixes?page[number]=1&page[size]=0&state=unassigned';
      const headers = { 'Accept': 'application/json' };
      fetch(url, {
        headers,
      }).then((response) => {
        response.text().then((text) => {
          try {
            let json = JSON.parse(text);
            if (!response.ok) {
              response.responseJSON = json;
              reject(response);
            } else {
              // ENV.PREFIXES_AVAILABLE only for development/staging/testing.
              let total = json.meta.total;
              // let total = 0;
              //if (ENV.PREFIXES_AVAILABLE !== null) {
              //  total = ENV.PREFIXES_AVAILABLE;
              //}
              console.log("Prefixes available = " + total);
              resolve(total);
              // resolve(0);
            }
          } catch (SyntaxError) {
            response.responseText = text;
            reject(response);
          }
        });
      }).catch(reject);
    });

    return promise;
  },

  get_n_available_pp(provider_id = null) {
    let promise = new Promise((resolve, reject) => {
      const url = ENV.API_URL + '/provider-prefixes?provider-id=' + provider_id + '&page[number]=1&page[size]=0&state=without-repository';
      const headers = { 'Accept': 'application/json' };
      fetch(url, {
        headers,
      }).then((response) => {
        response.text().then((text) => {
          try {
            let json = JSON.parse(text);
            if (!response.ok) {
              response.responseJSON = json;
              reject(response);
            } else {
              // ENV.PREFIXES_AVAILABLE only for development/staging/testing.
              let total = json.meta.total;
              // let total = 0;
              //if (ENV.PREFIXES_AVAILABLE !== null) {
              //  total = ENV.PREFIXES_AVAILABLE;
              //}
              console.log("Provider prefixes available = " + total);
              resolve(total);
              // resolve(0);
            }
          } catch (SyntaxError) {
            response.responseText = text;
            reject(response);
          }
        });
      }).catch(reject);
    });

    return promise;
  },

  // Returns a promise.
  async available(provider_id = null) {
    let m = 0;

    if (provider_id) {
      m = await this.get_n_available_pp(provider_id);
      console.log("PREFIXES.AVAILABLE() - AWAITING M!! " + m);
      console.log("PREFIXES.AVAILABLE() - PROVIDER PREFIXES AVAILABLE FOR " + provider_id + ' = ' + m);
      console.log("PREFIXES.AVAILABLE() M = " + m);
    } else {
      console.log("PREFIXES.AVAILABLE() - NO PROVIDER ID PROVIDED!!")
    }

    let n = await this.get_n_available();
    console.log("N = " + n);
    console.log("PREFIXES.AVAILABLE() - PROVIDER_ID - AVAILABLE: " + provider_id);
    //return await this.get_n_available();
    let o = m + n;
    console.log('PREFIXES.AVAILABLE() - RETURNING M+N: ' + o);
    return m+n;
    //return 0;
  }
})
<commit_msg>Prefix workflow. (Remove console.logs.)<commit_after>import Service from '@ember/service';
import ENV from 'bracco/config/environment';
import environment from 'config/environment';
import fetch from 'fetch';

export default Service.extend({

  init() {
    this._super(...arguments);
    this.min = 50;
    this.msg_zero = "There are 0 prefixes available. Request new prefixes from CNRI.";
    this.msg_min = "There are fewer than 50 prefixes available. Contact CNRI and request more prefixes.";
  },

  get_n_available() {
    let promise = new Promise((resolve, reject) => {
      const url = ENV.API_URL + '/prefixes?page[number]=1&page[size]=0&state=unassigned';
      const headers = { 'Accept': 'application/json' };
      fetch(url, {
        headers,
      }).then((response) => {
        response.text().then((text) => {
          try {
            let json = JSON.parse(text);
            if (!response.ok) {
              response.responseJSON = json;
              reject(response);
            } else {
              resolve(json.meta.total);
            }
          } catch (SyntaxError) {
            response.responseText = text;
            reject(response);
          }
        });
      }).catch(reject);
    });

    return promise;
  },

  get_n_available_pp(provider_id = null) {
    let promise = new Promise((resolve, reject) => {
      const url = ENV.API_URL + '/provider-prefixes?provider-id=' + provider_id + '&page[number]=1&page[size]=0&state=without-repository';
      const headers = { 'Accept': 'application/json' };
      fetch(url, {
        headers,
      }).then((response) => {
        response.text().then((text) => {
          try {
            let json = JSON.parse(text);
            if (!response.ok) {
              response.responseJSON = json;
              reject(response);
            } else {
              resolve(json.meta.total);
            }
          } catch (SyntaxError) {
            response.responseText = text;
            reject(response);
          }
        });
      }).catch(reject);
    });

    return promise;
  },

  // Returns a promise.
  async available(provider_id = null) {
    let m = 0;
    if (provider_id) {
      m = await this.get_n_available_pp(provider_id);
    }

    let n = await this.get_n_available();

    return m+n;

    // FOR DEV/TESTING ONLY:
    // return 0;
  }
})
<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp').
factory('quizData', function(){
  var quizData = {};

  quizData.questions = [
    { question: 'I work well under pressure and get to the heart of a matter and take decisive action' },
    { question: 'Other people seem to have confidence in my ability to tell when something or someone is right or wrong' },
    { question: 'I would rather deal with someone having problems personally instead of sending them to someone else' },
    { question: 'I receive great satisfaction in sharing Christ freely and effectively with unbelieving persons' },
    { question: 'I have known God\'s will with certainty in a specific situation even when concrete evidence was missing' }
  ];
  quizData.currentQuestion = 0;

  return quizData;
});
<commit_msg>Adds gifts to data<commit_after>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp').
factory('quizData', function(){
  var quizData = {};

  quizData.currentQuestion = 0;

  quizData.questions = [
    {
      question: 'I work well under pressure and get to the heart of a matter and take decisive action',
      giftId: 0
    },
    {
      question: 'Other people seem to have confidence in my ability to tell when something or someone is right or wrong',
      giftId: 0
    },
    {
      question: 'I would rather deal with someone having problems personally instead of sending them to someone else',
      giftId: 0
    },
    {
      question: 'I receive great satisfaction in sharing Christ freely and effectively with unbelieving persons',
      giftId: 0
    },
    {
      question: 'I have known God\'s will with certainty in a specific situation even when concrete evidence was missing',
      giftId: 0
    }
  ];

  quizData.gifts = [
    {
      id: 1,
      name: 'Administration',
      description: ''
    },
    {
      id: 2,
      name: 'Discernment',
      description: ''
    },
    {
      id: 3,
      name: 'Encouragement',
      description: ''
    },
    {
      id: 4,
      name: 'Evangelism',
      description: ''
    },
    {
      id: 5,
      name: 'Faith',
      description: ''
    },
    {
      id: 6,
      name: 'Giving',
      description: ''
    },
    {
      id: 7,
      name: 'Helping',
      description: ''
    },
    {
      id: 8,
      name: 'Knowledge',
      description: ''
    },
    {
      id: 9,
      name: 'Leadership',
      description: ''
    },
    {
      id: 10,
      name: 'Mercy',
      description: ''
    },
    {
      id: 11,
      name: 'Prophecy',
      description: ''
    },
    {
      id: 12,
      name: 'Service',
      description: ''
    },
    {
      id: 13,
      name: 'Shepherding',
      description: ''
    },
    {
      id: 14,
      name: 'Teaching',
      description: ''
    },
    {
      id: 15,
      name: 'Wisdom',
      description: ''
    }
  ];

  return quizData;
});
<|endoftext|>


<commit_before>angular.module('cov-injector', []).factory('cov', function () {
    return cov;
});
angular.module('d3-injector', []).factory('d3', function () {
    return d3;
});
angular.module('egrid-injector', []).factory('egrid', function () {
    return egrid;
});
angular.module('jQuery-injector', []).factory('jQuery', function () {
    return jQuery;
});
angular.module('sem-injector', []).factory('sem', function () {
    return sem;
});
var isem;
(function (isem) {
    isem.appName = 'egrid-sem';
    isem.externalModules = [
        'egrid-injector',
        'sem-injector',
        'cov-injector',
        'd3-injector',
        'jQuery-injector'
    ];
})(isem || (isem = {}));
angular.module(isem.appName, isem.externalModules);
var isem;
(function (isem) {
    var SemController = (function () {
        /**
         * @constructor
         * @ngInject
         */
        function SemController(// @fm:off
            $scope, egrid, sem, cov, d3, jQuery) {
            this.$scope = $scope;
            this.egrid = egrid;
            this.sem = sem;
            this.cov = cov;
            this.d3 = d3;
            this.jQuery = jQuery;
            this.dag = this.egrid.sem();
            this.init();
            this.bindToScope();
        }
        /**
         * Initialize the controller.
         *
         * @returns {void}
         */
        SemController.prototype.init = function () {
            var _this = this;
            var nodes = [
                '総合評価',
                '使いたさ',
                '書きやすさ',
                '便利さ',
                '快適さ',
                '安心さ',
                '芯の太さ',
                '持ち運びやすさ',
                '持ちやすさ',
                '太さ',
                '重さ'
            ];
            var links = [
                { source: 1, target: 0 },
                { source: 2, target: 0 },
                { source: 3, target: 0 },
                { source: 4, target: 0 },
                { source: 5, target: 0 },
                { source: 6, target: 2 },
                { source: 8, target: 2 },
                { source: 10, target: 2 },
                { source: 7, target: 3 },
                { source: 8, target: 3 },
                { source: 8, target: 4 },
                { source: 8, target: 5 },
                { source: 10, target: 5 },
                { source: 9, target: 7 },
                { source: 10, target: 7 },
                { source: 9, target: 8 }
            ];
            var S = [
                [1.180487805, 0.939634146, 1.021341463, 0.646341463, 0.96402439, 0.322560976, 0.058536585, 0.117682927, 1.021341463, -0.231097561, -0.170731707],
                [0.939634146, 1.18902439, 0.915243902, 0.565243902, 0.895731707, 0.176829268, 0.106097561, 0.055487805, 0.915243902, -0.132926829, -0.02195122],
                [1.021341463, 0.915243902, 1.552439024, 0.427439024, 1.007317073, 0.018292683, 0.06097561, 0.154878049, 1.552439024, -0.179268293, -0.369512195],
                [0.646341463, 0.565243902, 0.427439024, 1.102439024, 0.482317073, -0.031707317, -0.13902439, 0.179878049, 0.427439024, -0.104268293, -0.219512195],
                [0.96402439, 0.895731707, 1.007317073, 0.482317073, 1.07195122, 0.179878049, 0.057926829, 0.114634146, 1.007317073, -0.237804878, -0.133536585],
                [0.322560976, 0.176829268, 0.018292683, -0.031707317, 0.179878049, 0.962195122, 0.157317073, -0.038414634, 0.018292683, 0.030487805, 0.128658537],
                [0.058536585, 0.106097561, 0.06097561, -0.13902439, 0.057926829, 0.157317073, 0.474390244, -0.15304878, 0.06097561, 0.093292683, -0.087804878],
                [0.117682927, 0.055487805, 0.154878049, 0.179878049, 0.114634146, -0.038414634, -0.15304878, 0.809756098, 0.154878049, -0.308536585, -0.58902439],
                [1.021341463, 0.915243902, 1.552439024, 0.427439024, 1.007317073, 0.018292683, 0.06097561, 0.154878049, 1.552439024, -0.179268293, -0.369512195],
                [-0.231097561, -0.132926829, -0.179268293, -0.104268293, -0.237804878, 0.030487805, 0.093292683, -0.308536585, -0.179268293, 1.051219512, 0.509146341],
                [-0.170731707, -0.02195122, -0.369512195, -0.219512195, -0.133536585, 0.128658537, -0.087804878, -0.58902439, -0.369512195, 0.509146341, 1.256097561]
            ]; // @fm:on
            this.dag.registerUiCallback(function () {
                _this.$scope.$apply();
                _this.calcPath();
            });
            this.loadData(nodes, links, S);
            var displayId = '#sem-analysis-display';
            var display = this.jQuery(displayId);
            var width = display.width();
            var height = display.height();
            this.d3.select([
                displayId,
                'svg'
            ].join(' ')).call(this.dag.display(width, height));
            this.$scope.gfiValue = 0;
        };
        /**
         * Bind function to $scope.
         */
        SemController.prototype.bindToScope = function () {
            this.$scope.removeNode = this.removeNode.bind(this);
            this.$scope.loadFile = this.loadFile.bind(this);
        };
        /**
         * @returns {void}
         */
        SemController.prototype.calcPath = function () {
            var _this = this;
            var nodes = this.dag.activeNodes();
            var links = this.dag.activeLinks();
            // nodesDict
            var nodesDict = {};
            nodes.forEach(function (node, i) {
                nodesDict[node.text] = i;
            });
            // sem() args
            var n = nodes.length;
            var alpha = links.map(function (link) {
                return [nodesDict[link.source.text], nodesDict[link.target.text]];
            });
            var sigma = nodes.map(function (_, i) {
                return [i, i];
            });
            var S = nodes.map(function (node1) {
                return nodes.map(function (node2) {
                    return _this.SDict[node1.text][node2.text];
                });
            });
            this.sem(n, alpha, sigma, S, (function (result) {
                var A = nodes.map(function (_) {
                    return nodes.map(function (_) {
                        return 0;
                    });
                });
                result.alpha.forEach(function (r) {
                    A[r[0]][r[1]] = r[2];
                });
                _this.$scope.gfiValue = result.GFI;
                _this.$scope.linkText = '結果,原因,係数\n';
                links.forEach(function (link) {
                    link.coef = A[nodesDict[link.source.text]][nodesDict[link.target.text]];
                    _this.$scope.linkText += link.source.text + ',' + link.target.text + ',' + link.coef + '\n';
                });
                _this.dag.draw().focusCenter();
                _this.$scope.$apply();
            }));
        };
        /**
         * @param {string[]} nodes
         * @param {{source: number, target: number}[]} links
         * @param {number[][]} S
         * @returns {void}
         */
        SemController.prototype.loadData = function (nodes, links, S) {
            var _this = this;
            this.SDict = {};
            nodes.forEach(function (node) {
                _this.SDict[node] = {};
            });
            nodes.forEach(function (node1, i) {
                nodes.forEach(function (node2, j) {
                    _this.SDict[node1][node2] = S[i][j];
                });
            });
            var egmNodes = nodes.map(function (d) {
                return new egrid.Node(d);
            });
            var egmLinks = links.map(function (d) {
                return new egrid.Link(egmNodes[d.target], egmNodes[d.source]);
            });
            this.dag.nodes(egmNodes).links(egmLinks);
            this.$scope.items = this.dag.nodes();
            var n = nodes.length;
            var alpha = links.map(function (d) {
                return [d.target, d.source];
            });
            var sigma = nodes.map(function (_, i) {
                return [i, i];
            });
            this.sem(n, alpha, sigma, S, (function (result) {
                var A = _this.dag.nodes().map(function (_) {
                    return _this.dag.nodes().map(function (_) {
                        return 0;
                    });
                });
                result.alpha.forEach(function (r) {
                    A[r[0]][r[1]] = r[2];
                });
                _this.$scope.gfiValue = result.GFI;
                _this.$scope.linkText = '結果,原因,係数\n';
                _this.dag.links().forEach(function (link) {
                    link.coef = A[link.source.index][link.target.index];
                    _this.$scope.linkText += link.source.text + ',' + link.target.text + ',' + link.coef + '\n';
                });
                _this.dag.draw().focusCenter();
                _this.$scope.$apply();
            }));
        };
        /**
         * @returns {void}
         */
        SemController.prototype.removeNode = function () {
            this.dag.draw().focusCenter();
            this.calcPath();
        };
        /**
         * @returns {void}
         */
        SemController.prototype.loadFile = function () {
            var _this = this;
            var reader = new FileReader();
            reader.onload = function (e) {
                var data = _this.d3.csv.parse(e.target.result);
                var attributes = [];
                var attr;
                for (attr in data[0]) {
                    attributes.push(attr);
                }
                var x = attributes.map(function (key) {
                    return data.map(function (d) {
                        return d[key];
                    });
                });
                _this.cov(x, function (cov) {
                    var S = cov.data;
                    _this.loadData(attributes, [], S);
                    _this.$scope.$apply();
                });
            };
            var file = document.getElementById('fileInput').files[0];
            var encoding = document.querySelectorAll('.encoding:checked')[0].value;
            reader.readAsText(file, encoding);
        };
        return SemController;
    })();
    isem.SemController = SemController;
})(isem || (isem = {}));
angular.module(isem.appName).controller('SemController', isem.SemController);
/// <reference path="../../../typings/angularjs/angular.d.ts" />
/// <reference path="../../../typings/d3/d3.d.ts" />
/// <reference path="for-egrid-sem.d.ts" />
/// <reference path="injector/cov.ts" />
/// <reference path="injector/d3.ts" />
/// <reference path="injector/egrid.ts" />
/// <reference path="injector/jquery.ts" />
/// <reference path="injector/sem.ts" />
/// <reference path="app.ts" />
/// <reference path="egrid-sem.ts" />
//# sourceMappingURL=index.js.map<commit_msg>resolve #15<commit_after>angular.module('cov-injector', []).factory('cov', function () {
    return cov;
});
angular.module('d3-injector', []).factory('d3', function () {
    return d3;
});
angular.module('egrid-injector', []).factory('egrid', function () {
    return egrid;
});
angular.module('jQuery-injector', []).factory('jQuery', function () {
    return jQuery;
});
angular.module('sem-injector', []).factory('sem', function () {
    return sem;
});
var isem;
(function (isem) {
    isem.appName = 'egrid-sem';
    isem.externalModules = [
        'egrid-injector',
        'sem-injector',
        'cov-injector',
        'd3-injector',
        'jQuery-injector'
    ];
})(isem || (isem = {}));
angular.module(isem.appName, isem.externalModules);
angular.module(isem.appName).factory('initializationData', function () {
    return {
        nodes: [
            '総合評価',
            '使いたさ',
            '書きやすさ',
            '便利さ',
            '快適さ',
            '安心さ',
            '芯の太さ',
            '持ち運びやすさ',
            '持ちやすさ',
            '太さ',
            '重さ'
        ],
        links: [
            { source: 1, target: 0 },
            { source: 2, target: 0 },
            { source: 3, target: 0 },
            { source: 4, target: 0 },
            { source: 5, target: 0 },
            { source: 6, target: 2 },
            { source: 8, target: 2 },
            { source: 10, target: 2 },
            { source: 7, target: 3 },
            { source: 8, target: 3 },
            { source: 8, target: 4 },
            { source: 8, target: 5 },
            { source: 10, target: 5 },
            { source: 9, target: 7 },
            { source: 10, target: 7 },
            { source: 9, target: 8 }
        ],
        S: [
            [1.180487805, 0.939634146, 1.021341463, 0.646341463, 0.96402439, 0.322560976, 0.058536585, 0.117682927, 1.021341463, -0.231097561, -0.170731707],
            [0.939634146, 1.18902439, 0.915243902, 0.565243902, 0.895731707, 0.176829268, 0.106097561, 0.055487805, 0.915243902, -0.132926829, -0.02195122],
            [1.021341463, 0.915243902, 1.552439024, 0.427439024, 1.007317073, 0.018292683, 0.06097561, 0.154878049, 1.552439024, -0.179268293, -0.369512195],
            [0.646341463, 0.565243902, 0.427439024, 1.102439024, 0.482317073, -0.031707317, -0.13902439, 0.179878049, 0.427439024, -0.104268293, -0.219512195],
            [0.96402439, 0.895731707, 1.007317073, 0.482317073, 1.07195122, 0.179878049, 0.057926829, 0.114634146, 1.007317073, -0.237804878, -0.133536585],
            [0.322560976, 0.176829268, 0.018292683, -0.031707317, 0.179878049, 0.962195122, 0.157317073, -0.038414634, 0.018292683, 0.030487805, 0.128658537],
            [0.058536585, 0.106097561, 0.06097561, -0.13902439, 0.057926829, 0.157317073, 0.474390244, -0.15304878, 0.06097561, 0.093292683, -0.087804878],
            [0.117682927, 0.055487805, 0.154878049, 0.179878049, 0.114634146, -0.038414634, -0.15304878, 0.809756098, 0.154878049, -0.308536585, -0.58902439],
            [1.021341463, 0.915243902, 1.552439024, 0.427439024, 1.007317073, 0.018292683, 0.06097561, 0.154878049, 1.552439024, -0.179268293, -0.369512195],
            [-0.231097561, -0.132926829, -0.179268293, -0.104268293, -0.237804878, 0.030487805, 0.093292683, -0.308536585, -0.179268293, 1.051219512, 0.509146341],
            [-0.170731707, -0.02195122, -0.369512195, -0.219512195, -0.133536585, 0.128658537, -0.087804878, -0.58902439, -0.369512195, 0.509146341, 1.256097561]
        ] // @fm:on
    };
});
var isem;
(function (isem) {
    var SemController = (function () {
        /**
         * @constructor
         * @ngInject
         */
        function SemController(// @fm:off
            $scope, egrid, sem, cov, d3, jQuery, initializationData) {
            this.$scope = $scope;
            this.egrid = egrid;
            this.sem = sem;
            this.cov = cov;
            this.d3 = d3;
            this.jQuery = jQuery;
            this.initializationData = initializationData;
            this.dag = this.egrid.sem();
            this.init();
            this.bindToScope();
        }
        /**
         * Initialize the controller.
         *
         * @returns {void}
         */
        SemController.prototype.init = function () {
            var _this = this;
            this.$scope.gfiValue = 0;
            this.dag.registerUiCallback(function () {
                _this.$scope.$apply();
                _this.calcPath();
            });
            this.loadData(this.initializationData.nodes, this.initializationData.links, this.initializationData.S);
            var displayId = '#sem-analysis-display';
            var display = this.jQuery(displayId);
            this.d3.select([displayId, 'svg'].join(' ')).call(this.dag.display(display.width(), display.height()));
        };
        /**
         * Bind function to $scope.
         */
        SemController.prototype.bindToScope = function () {
            this.$scope.removeNode = this.removeNode.bind(this);
            this.$scope.loadFile = this.loadFile.bind(this);
        };
        /**
         * @returns {void}
         */
        SemController.prototype.calcPath = function () {
            var _this = this;
            var nodes = this.dag.activeNodes();
            var links = this.dag.activeLinks();
            // nodesDict
            var nodesDict = {};
            nodes.forEach(function (node, i) {
                nodesDict[node.text] = i;
            });
            // sem() args
            var n = nodes.length;
            var alpha = links.map(function (link) {
                return [nodesDict[link.source.text], nodesDict[link.target.text]];
            });
            var sigma = nodes.map(function (_, i) {
                return [i, i];
            });
            var S = nodes.map(function (node1) {
                return nodes.map(function (node2) {
                    return _this.SDict[node1.text][node2.text];
                });
            });
            this.sem(n, alpha, sigma, S, (function (result) {
                var A = nodes.map(function (_) {
                    return nodes.map(function (_) {
                        return 0;
                    });
                });
                result.alpha.forEach(function (r) {
                    A[r[0]][r[1]] = r[2];
                });
                _this.$scope.gfiValue = result.GFI;
                _this.$scope.linkText = '結果,原因,係数\n';
                links.forEach(function (link) {
                    link.coef = A[nodesDict[link.source.text]][nodesDict[link.target.text]];
                    _this.$scope.linkText += link.source.text + ',' + link.target.text + ',' + link.coef + '\n';
                });
                _this.dag.draw().focusCenter();
                _this.$scope.$apply();
            }));
        };
        /**
         * @param {string[]} nodes
         * @param {{source: number, target: number}[]} links
         * @param {number[][]} S
         * @returns {void}
         */
        SemController.prototype.loadData = function (nodes, links, S) {
            var _this = this;
            this.SDict = {};
            nodes.forEach(function (node) {
                _this.SDict[node] = {};
            });
            nodes.forEach(function (node1, i) {
                nodes.forEach(function (node2, j) {
                    _this.SDict[node1][node2] = S[i][j];
                });
            });
            var egmNodes = nodes.map(function (d) {
                return new egrid.Node(d);
            });
            var egmLinks = links.map(function (d) {
                return new egrid.Link(egmNodes[d.target], egmNodes[d.source]);
            });
            this.dag.nodes(egmNodes).links(egmLinks);
            this.$scope.items = this.dag.nodes();
            var n = nodes.length;
            var alpha = links.map(function (d) {
                return [d.target, d.source];
            });
            var sigma = nodes.map(function (_, i) {
                return [i, i];
            });
            this.sem(n, alpha, sigma, S, (function (result) {
                var A = _this.dag.nodes().map(function (_) {
                    return _this.dag.nodes().map(function (_) {
                        return 0;
                    });
                });
                result.alpha.forEach(function (r) {
                    A[r[0]][r[1]] = r[2];
                });
                _this.$scope.gfiValue = result.GFI;
                _this.$scope.linkText = '結果,原因,係数\n';
                _this.dag.links().forEach(function (link) {
                    link.coef = A[link.source.index][link.target.index];
                    _this.$scope.linkText += link.source.text + ',' + link.target.text + ',' + link.coef + '\n';
                });
                _this.dag.draw().focusCenter();
                _this.$scope.$apply();
            }));
        };
        /**
         * @returns {void}
         */
        SemController.prototype.removeNode = function () {
            this.dag.draw().focusCenter();
            this.calcPath();
        };
        /**
         * @returns {void}
         */
        SemController.prototype.loadFile = function () {
            var _this = this;
            var reader = new FileReader();
            reader.onload = function (e) {
                var data = _this.d3.csv.parse(e.target.result);
                var attributes = [];
                var attr;
                for (attr in data[0]) {
                    attributes.push(attr);
                }
                var x = attributes.map(function (key) {
                    return data.map(function (d) {
                        return d[key];
                    });
                });
                _this.cov(x, function (cov) {
                    var S = cov.data;
                    _this.loadData(attributes, [], S);
                    _this.$scope.$apply();
                });
            };
            var file = document.getElementById('fileInput').files[0];
            var encoding = document.querySelectorAll('.encoding:checked')[0].value;
            reader.readAsText(file, encoding);
        };
        return SemController;
    })();
    isem.SemController = SemController;
})(isem || (isem = {}));
angular.module(isem.appName).controller('SemController', isem.SemController);
/// <reference path="../../../typings/angularjs/angular.d.ts" />
/// <reference path="../../../typings/d3/d3.d.ts" />
/// <reference path="for-egrid-sem.d.ts" />
/// <reference path="injector/cov.ts" />
/// <reference path="injector/d3.ts" />
/// <reference path="injector/egrid.ts" />
/// <reference path="injector/jquery.ts" />
/// <reference path="injector/sem.ts" />
/// <reference path="app.ts" />
/// <reference path="factory/initialization-data.ts" />
/// <reference path="egrid-sem.ts" />
//# sourceMappingURL=index.js.map<|endoftext|>