<commit_before>/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.net/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/

/**********************************************************\
 *                                                        *
 * HproseWriter.js                                        *
 *                                                        *
 * HproseWriter for Node.js.                              *
 *                                                        *
 * LastModified: Mar 25, 2014                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

/*jshint node:true, eqeqeq:true */
/*jshint unused:false */
'use strict';

require('../common/HarmonyMaps.js');
var util = require('util');
var HproseTags = require('./HproseTags.js');
var HproseClassManager = require('./HproseClassManager.js');

function isNegZero(value) {
    return (value === 0 && 1/value === -Infinity);
}

function isDigit(value) {
    switch (value) {
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    case 7:
    case 8:
    case 9:
        return true;
    }
    return false;
}

function isInt32(value) {
    return (value >= -2147483648) &&
           (value <= 2147483647) &&
           (Math.floor(value) === value);
}

function getClassName(obj) {
    var cls = obj.constructor;
    var classname = HproseClassManager.getClassAlias(cls);
    if (classname) return classname;
    if (cls.name) {
        classname = cls.name;
    }
    else {
        var ctor = cls.toString();
        classname = ctor.substr(0, ctor.indexOf('(')).replace(/(^\s*function\s*)|(\s*$)/ig, '');
        if (classname === '' || classname === 'Object') {
            return (typeof(obj.getClassName) === 'function') ? obj.getClassName() : 'Object';
        }
    }
    if (classname !== 'Object') {
        HproseClassManager.register(cls, classname);
    }
    return classname;
}

var fakeWriterRefer = {
    set: function (val) {},
    write: function (stream, val) { return false; },
    reset: function () {}
};

var realWriterRefer = function () {
    var ref = new Map();
    var refcount = 0;
    return {
        set: function (val) {
            ref.set(val, refcount++);
        },
        write: function (stream, val) {
            var index = ref.get(val);
            if (index !== undefined) {
                stream.write(HproseTags.TagRef);
                stream.write(index.toString());
                stream.write(HproseTags.TagSemicolon);
                return true;
            }
        },
        reset: function () {
            ref = new Map();
            refcount = 0;
        }
    };
};

function HproseWriter(stream, simple) {
    var classref = Object.create(null);
    var fieldsref = [];
    var refer = (simple ? fakeWriterRefer : realWriterRefer());
    function serialize(variable) {
        if (variable === undefined ||
            variable === null ||
            typeof(variable) === 'function') {
            writeNull();
            return;
        }
        if (variable === '') {
            writeEmpty();
            return;
        }
        switch (typeof(variable)) {
        case 'boolean':
            writeBoolean(variable);
            break;
        case 'number':
            writeNumber(variable);
            break;
        case 'string':
            if (variable.length === 1) {
                writeUTF8Char(variable);
            }
            else {
                writeStringWithRef(variable);
            }
            break;
        default:
            if (util.isDate(variable)) {
                writeDateWithRef(variable);
            }
            else if (util.isArray(variable)) {
                writeListWithRef(variable);
            }
            else if (Buffer.isBuffer(variable)) {
                writeBytesWithRef(variable);
            }
            else {
                var classname = getClassName(variable);
                if (classname === 'Object') {
                    writeMapWithRef(variable);
                }
                else if (classname === 'Map') {
                    writeHarmonyMapWithRef(variable);
                }
                else {
                    writeObjectWithRef(variable);
                }
            }
            break;
        }
    }
    function writeNumber(n) {
        if (isNegZero(n)) {
            stream.write(HproseTags.TagInteger);
            stream.write('-0');
            stream.write(HproseTags.TagSemicolon);
        }
        else if (isDigit(n)) {
            stream.write(n + 0x30);
        }
        else if (isInt32(n)) {
            writeInteger(n);
        }
        else {
            writeDouble(n);
        }
    }
    function writeInteger(i) {
        stream.write(HproseTags.TagInteger);
        stream.write(i.toString());
        stream.write(HproseTags.TagSemicolon);
    }
    function writeLong(l) {
        stream.write(HproseTags.TagLong);
        stream.write(l.toString());
        stream.write(HproseTags.TagSemicolon);
    }
    function writeDouble(d) {
        if (isNaN(d)) {
            writeNaN();
        }
        else if (isFinite(d)) {
            stream.write(HproseTags.TagDouble);
            stream.write(d.toString());
            stream.write(HproseTags.TagSemicolon);
        }
        else {
            writeInfinity(d > 0);
        }
    }
    function writeNaN() {
        stream.write(HproseTags.TagNaN);
    }
    function writeInfinity(positive) {
        stream.write(HproseTags.TagInfinity);
        stream.write(positive ? HproseTags.TagPos : HproseTags.TagNeg);
    }
    function writeNull() {
        stream.write(HproseTags.TagNull);
    }
    function writeEmpty() {
        stream.write(HproseTags.TagEmpty);
    }
    function writeBoolean(b) {
        stream.write(b ? HproseTags.TagTrue : HproseTags.TagFalse);
    }
    function writeUTCDate(date) {
        refer.set(date);
        var year = ('0000' + date.getUTCFullYear()).slice(-4);
        var month = ('00' + (date.getUTCMonth() + 1)).slice(-2);
        var day = ('00' + date.getUTCDate()).slice(-2);
        var hour = ('00' + date.getUTCHours()).slice(-2);
        var minute = ('00' + date.getUTCMinutes()).slice(-2);
        var second = ('00' + date.getUTCSeconds()).slice(-2);
        var millisecond = ('000' + date.getUTCMilliseconds()).slice(-3);
        stream.write(HproseTags.TagDate);
        stream.write(year + month + day);
        stream.write(HproseTags.TagTime);
        stream.write(hour + minute + second);
        if (millisecond !== '000') {
            stream.write(HproseTags.TagPoint);
            stream.write(millisecond);
        }
        stream.write(HproseTags.TagUTC);
    }
    function writeUTCDateWithRef(date) {
        if (!refer.write(stream, date)) writeUTCDate(date);
    }
    function writeDate(date) {
        refer.set(date);
        var year = ('0000' + date.getFullYear()).slice(-4);
        var month = ('00' + (date.getMonth() + 1)).slice(-2);
        var day = ('00' + date.getDate()).slice(-2);
        var hour = ('00' + date.getHours()).slice(-2);
        var minute = ('00' + date.getMinutes()).slice(-2);
        var second = ('00' + date.getSeconds()).slice(-2);
        var millisecond = ('000' + date.getMilliseconds()).slice(-3);
        if ((hour === '00') && (minute === '00') &&
            (second === '00') && (millisecond === '000')) {
            stream.write(HproseTags.TagDate);
            stream.write(year + month + day);
        }
        else if ((year === '1970') && (month === '01') && (day === '01')) {
            stream.write(HproseTags.TagTime);
            stream.write(hour + minute + second);
            if (millisecond !== '000') {
                stream.write(HproseTags.TagPoint);
                stream.write(millisecond);
            }
        }
        else {
            stream.write(HproseTags.TagDate);
            stream.write(year + month + day);
            stream.write(HproseTags.TagTime);
            stream.write(hour + minute + second);
            if (millisecond !== '000') {
                stream.write(HproseTags.TagPoint);
                stream.write(millisecond);
            }
        }
        stream.write(HproseTags.TagSemicolon);
    }
    function writeDateWithRef(date) {
        if (!refer.write(stream, date)) writeDate(date);
    }
    function writeTime(time) {
        refer.set(time);
        var hour = ('00' + time.getHours()).slice(-2);
        var minute = ('00' + time.getMinutes()).slice(-2);
        var second = ('00' + time.getSeconds()).slice(-2);
        var millisecond = ('000' + time.getMilliseconds()).slice(-3);
        stream.write(HproseTags.TagTime);
        stream.write(hour + minute + second);
        if (millisecond !== '000') {
            stream.write(HproseTags.TagPoint);
            stream.write(millisecond);
        }
        stream.write(HproseTags.TagSemicolon);
    }
    function writeTimeWithRef(time) {
        if (!refer.write(stream, time)) writeTime(time);
    }
    function writeBytes(bytes) {
        refer.set(bytes);
        stream.write(HproseTags.TagBytes);
        if (bytes.length > 0) stream.write(bytes.length.toString());
        stream.write(HproseTags.TagQuote);
        if (bytes.length > 0) stream.write(bytes);
        stream.write(HproseTags.TagQuote);
    }
    function writeBytesWithRef(bytes) {
        if (!refer.write(stream, bytes)) writeBytes(bytes);
    }
    function writeUTF8Char(c) {
        stream.write(HproseTags.TagUTF8Char);
        stream.write(c);
    }
    function writeString(str) {
        refer.set(str);
        var length = str.length;
        stream.write(HproseTags.TagString);
        if (length > 0) stream.write(length.toString());
        stream.write(HproseTags.TagQuote);
        if (length > 0) stream.write(str);
        stream.write(HproseTags.TagQuote);
    }
    function writeStringWithRef(str) {
        if (!refer.write(stream, str)) writeString(str);
    }
    function writeList(list) {
        refer.set(list);
        var count = list.length;
        stream.write(HproseTags.TagList);
        if (count > 0) stream.write(count.toString());
        stream.write(HproseTags.TagOpenbrace);
        for (var i = 0; i < count; i++) {
            serialize(list[i]);
        }
        stream.write(HproseTags.TagClosebrace);
    }
    function writeListWithRef(list) {
        if (!refer.write(stream, list)) writeList(list);
    }
    function writeMap(map) {
        refer.set(map);
        var fields = [];
        for (var key in map) {
            if (map.hasOwnProperty(key) &&
                typeof(map[key]) !== 'function') {
                fields[fields.length] = key;
            }
        }
        var count = fields.length;
        stream.write(HproseTags.TagMap);
        if (count > 0) stream.write(count.toString());
        stream.write(HproseTags.TagOpenbrace);
        for (var i = 0; i < count; i++) {
            serialize(fields[i]);
            serialize(map[fields[i]]);
        }
        stream.write(HproseTags.TagClosebrace);
    }
    function writeMapWithRef(map) {
        if (!refer.write(stream, map)) writeMap(map);
    }
    function writeHarmonyMap(map) {
        refer.set(map);
        var count = map.size;
        stream.write(HproseTags.TagMap);
        if (count > 0) stream.write(count.toString());
        stream.write(HproseTags.TagOpenbrace);
        map.forEach(function(value, key, m) {
            serialize(key);
            serialize(value);
        });
        stream.write(HproseTags.TagClosebrace);
    }
    function writeHarmonyMapWithRef(map) {
        if (!refer.write(stream, map)) writeHarmonyMap(map);
    }
    function writeObject(obj) {
        var classname = getClassName(obj);
        var fields;
        var index = classref[classname];
        if (index >= 0) {
            fields = fieldsref[index];
        }
        else {
            fields = [];
            for (var key in obj) {
                if (obj.hasOwnProperty(key) &&
                    typeof(obj[key]) !== 'function') {
                    fields[fields.length] = key.toString();
                }
            }
            index = writeClass(classname, fields);
        }
        stream.write(HproseTags.TagObject);
        stream.write(index.toString());
        stream.write(HproseTags.TagOpenbrace);
        refer.set(obj);
        var count = fields.length;
        for (var i = 0; i < count; i++) {
            serialize(obj[fields[i]]);
        }
        stream.write(HproseTags.TagClosebrace);
    }
    function writeObjectWithRef(obj) {
        if (!refer.write(stream, obj)) writeObject(obj);
    }
    function writeClass(classname, fields) {
        var count = fields.length;
        stream.write(HproseTags.TagClass);
        stream.write(classname.length.toString());
        stream.write(HproseTags.TagQuote);
        stream.write(classname);
        stream.write(HproseTags.TagQuote);
        if (count > 0) stream.write(count.toString());
        stream.write(HproseTags.TagOpenbrace);
        for (var i = 0; i < count; i++) {
            writeString(fields[i]);
        }
        stream.write(HproseTags.TagClosebrace);
        var index = fieldsref.length;
        classref[classname] = index;
        fieldsref[index] = fields;
        return index;
    }
    function reset() {
        classref = Object.create(null);
        fieldsref.length = 0;
        refer.reset();
    }
    this.stream = stream;
    this.serialize = serialize;
    this.writeInteger = writeInteger;
    this.writeLong = writeLong;
    this.writeDouble = writeDouble;
    this.writeNaN = writeNaN;
    this.writeInfinity = writeInfinity;
    this.writeNull = writeNull;
    this.writeEmpty = writeEmpty;
    this.writeBoolean = writeBoolean;
    this.writeUTCDate = writeUTCDate;
    this.writeUTCDateWithRef = writeUTCDateWithRef;
    this.writeDate = writeDate;
    this.writeDateWithRef = writeDateWithRef;
    this.writeTime = writeTime;
    this.writeTimeWithRef = writeTimeWithRef;
    this.writeBytes = writeBytes;
    this.writeBytesWithRef = writeBytesWithRef;
    this.writeUTF8Char = writeUTF8Char;
    this.writeString = writeString;
    this.writeStringWithRef = writeStringWithRef;
    this.writeList = writeList;
    this.writeListWithRef = writeListWithRef;
    this.writeMap = writeMap;
    this.writeMapWithRef = writeMapWithRef;
    this.writeHarmonyMap = writeHarmonyMap;
    this.writeHarmonyMapWithRef = writeHarmonyMapWithRef;
    this.writeObject = writeObject;
    this.writeObjectWithRef = writeObjectWithRef;
    this.reset = reset;
}

module.exports = HproseWriter;<commit_msg>Update Hprose for nodejs<commit_after>/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.net/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/

/**********************************************************\
 *                                                        *
 * HproseWriter.js                                        *
 *                                                        *
 * HproseWriter for Node.js.                              *
 *                                                        *
 * LastModified: Mar 28, 2014                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

/*jshint node:true, eqeqeq:true */
/*jshint unused:false */
'use strict';

require('../common/HarmonyMaps.js');
var util = require('util');
var HproseTags = require('./HproseTags.js');
var HproseClassManager = require('./HproseClassManager.js');

function isNegZero(value) {
    return (value === 0 && 1/value === -Infinity);
}

function getClassName(obj) {
    var cls = obj.constructor;
    var classname = HproseClassManager.getClassAlias(cls);
    if (classname) return classname;
    if (cls.name) {
        classname = cls.name;
    }
    else {
        var ctor = cls.toString();
        classname = ctor.substr(0, ctor.indexOf('(')).replace(/(^\s*function\s*)|(\s*$)/ig, '');
        if (classname === '' || classname === 'Object') {
            return (typeof(obj.getClassName) === 'function') ? obj.getClassName() : 'Object';
        }
    }
    if (classname !== 'Object') {
        HproseClassManager.register(cls, classname);
    }
    return classname;
}

var fakeWriterRefer = {
    set: function () {},
    write: function () { return false; },
    reset: function () {}
};

var realWriterRefer = function (stream) {
    var ref = new Map();
    var refcount = 0;
    return {
        set: function (val) {
            ref.set(val, refcount++);
        },
        write: function (val) {
            var index = ref.get(val);
            if (index !== undefined) {
                stream.write(HproseTags.TagRef);
                stream.write(index.toString());
                stream.write(HproseTags.TagSemicolon);
                return true;
            }
        },
        reset: function () {
            ref = new Map();
            refcount = 0;
        }
    };
};

function HproseWriter(stream, simple) {
    var classref = Object.create(null);
    var fieldsref = [];
    var refer = simple ? fakeWriterRefer : realWriterRefer(stream);
    function serialize(value) {
        if (value === undefined || value === null) {
            stream.write(HproseTags.TagNull);
            return;
        }
        switch (value.constructor) {
        case Function:
            stream.write(HproseTags.TagNull);
            return;
        case Number:
            writeNumber(value);
            return;
        case Boolean:
            writeBoolean(value);
            return;
        case String:
            switch (value.length) {
            case 0:
                stream.write(HproseTags.TagEmpty);
                return;
            case 1:
                stream.write(HproseTags.TagUTF8Char);
                stream.write(value);
                return;
            }
            writeStringWithRef(value);
            return;
        case Map:
            writeHarmonyMapWithRef(value);
            return;
        default:
            if (util.isDate(value)) {
                writeDateWithRef(value);
            }
            else if (util.isArray(value)) {
                writeListWithRef(value);
            }
            else if (Buffer.isBuffer(value)) {
                writeBytesWithRef(value);
            }
            else {
                var classname = getClassName(value);
                if (classname === 'Object') {
                    writeMapWithRef(value);
                }
                else {
                    writeObjectWithRef(value);
                }
            }
            break;
        }
    }
    function writeNumber(n) {
        if (isNegZero(n)) {
            stream.write(HproseTags.TagInteger);
            stream.write(HproseTags.TagNeg);
            stream.write(0x30); // 0
            stream.write(HproseTags.TagSemicolon);
        }
        else if (n === (n | 0)) {
            writeInteger(n);
        }
        else {
            writeDouble(n);
        }
    }
    function writeInteger(i) {
        if (0 <= i && i <= 9) {
            stream.write(i + 0x30);
        }
        else {
            if (i < -2147483648 || i > 2147483647) {
                stream.write(HproseTags.TagLong);
            }
            else {
                stream.write(HproseTags.TagInteger);
            }
            stream.write('' + i);
            stream.write(HproseTags.TagSemicolon);
        }
    }
    function writeDouble(d) {
        if (isNaN(d)) {
            stream.write(HproseTags.TagNaN);
        }
        else if (isFinite(d)) {
            stream.write(HproseTags.TagDouble);
            if (isNegZero(d)) {
                stream.write(HproseTags.TagNeg);
                stream.write(0x30); // 0
            }
            else {
                stream.write('' + d);
            }
            stream.write(HproseTags.TagSemicolon);
        }
        else {
            stream.write(HproseTags.TagInfinity);
            stream.write((d > 0) ? HproseTags.TagPos : HproseTags.TagNeg);
        }
    }
    function writeBoolean(b) {
        stream.write(b ? HproseTags.TagTrue : HproseTags.TagFalse);
    }
    function writeUTCDate(date) {
        refer.set(date);
        var year = ('0000' + date.getUTCFullYear()).slice(-4);
        var month = ('00' + (date.getUTCMonth() + 1)).slice(-2);
        var day = ('00' + date.getUTCDate()).slice(-2);
        var hour = ('00' + date.getUTCHours()).slice(-2);
        var minute = ('00' + date.getUTCMinutes()).slice(-2);
        var second = ('00' + date.getUTCSeconds()).slice(-2);
        var millisecond = ('000' + date.getUTCMilliseconds()).slice(-3);
        stream.write(HproseTags.TagDate);
        stream.write(year + month + day);
        stream.write(HproseTags.TagTime);
        stream.write(hour + minute + second);
        if (millisecond !== '000') {
            stream.write(HproseTags.TagPoint);
            stream.write(millisecond);
        }
        stream.write(HproseTags.TagUTC);
    }
    function writeUTCDateWithRef(date) {
        if (!refer.write(date)) writeUTCDate(date);
    }
    function writeDate(date) {
        refer.set(date);
        var year = ('0000' + date.getFullYear()).slice(-4);
        var month = ('00' + (date.getMonth() + 1)).slice(-2);
        var day = ('00' + date.getDate()).slice(-2);
        var hour = ('00' + date.getHours()).slice(-2);
        var minute = ('00' + date.getMinutes()).slice(-2);
        var second = ('00' + date.getSeconds()).slice(-2);
        var millisecond = ('000' + date.getMilliseconds()).slice(-3);
        if ((hour === '00') && (minute === '00') &&
            (second === '00') && (millisecond === '000')) {
            stream.write(HproseTags.TagDate);
            stream.write(year + month + day);
        }
        else if ((year === '1970') && (month === '01') && (day === '01')) {
            stream.write(HproseTags.TagTime);
            stream.write(hour + minute + second);
            if (millisecond !== '000') {
                stream.write(HproseTags.TagPoint);
                stream.write(millisecond);
            }
        }
        else {
            stream.write(HproseTags.TagDate);
            stream.write(year + month + day);
            stream.write(HproseTags.TagTime);
            stream.write(hour + minute + second);
            if (millisecond !== '000') {
                stream.write(HproseTags.TagPoint);
                stream.write(millisecond);
            }
        }
        stream.write(HproseTags.TagSemicolon);
    }
    function writeDateWithRef(date) {
        if (!refer.write(date)) writeDate(date);
    }
    function writeTime(time) {
        refer.set(time);
        var hour = ('00' + time.getHours()).slice(-2);
        var minute = ('00' + time.getMinutes()).slice(-2);
        var second = ('00' + time.getSeconds()).slice(-2);
        var millisecond = ('000' + time.getMilliseconds()).slice(-3);
        stream.write(HproseTags.TagTime);
        stream.write(hour + minute + second);
        if (millisecond !== '000') {
            stream.write(HproseTags.TagPoint);
            stream.write(millisecond);
        }
        stream.write(HproseTags.TagSemicolon);
    }
    function writeTimeWithRef(time) {
        if (!refer.write(time)) writeTime(time);
    }
    function writeBytes(bytes) {
        refer.set(bytes);
        stream.write(HproseTags.TagBytes);
        if (bytes.length > 0) stream.write(bytes.length.toString());
        stream.write(HproseTags.TagQuote);
        if (bytes.length > 0) stream.write(bytes);
        stream.write(HproseTags.TagQuote);
    }
    function writeBytesWithRef(bytes) {
        if (!refer.write(bytes)) writeBytes(bytes);
    }
    function writeUTF8Char(c) {
        stream.write(HproseTags.TagUTF8Char);
        stream.write(c);
    }
    function writeString(str) {
        refer.set(str);
        var length = str.length;
        stream.write(HproseTags.TagString);
        if (length > 0) stream.write(length.toString());
        stream.write(HproseTags.TagQuote);
        if (length > 0) stream.write(str);
        stream.write(HproseTags.TagQuote);
    }
    function writeStringWithRef(str) {
        if (!refer.write(str)) writeString(str);
    }
    function writeList(list) {
        refer.set(list);
        var count = list.length;
        stream.write(HproseTags.TagList);
        if (count > 0) stream.write(count.toString());
        stream.write(HproseTags.TagOpenbrace);
        for (var i = 0; i < count; i++) {
            serialize(list[i]);
        }
        stream.write(HproseTags.TagClosebrace);
    }
    function writeListWithRef(list) {
        if (!refer.write(list)) writeList(list);
    }
    function writeMap(map) {
        refer.set(map);
        var fields = [];
        for (var key in map) {
            if (map.hasOwnProperty(key) &&
                typeof(map[key]) !== 'function') {
                fields[fields.length] = key;
            }
        }
        var count = fields.length;
        stream.write(HproseTags.TagMap);
        if (count > 0) stream.write(count.toString());
        stream.write(HproseTags.TagOpenbrace);
        for (var i = 0; i < count; i++) {
            serialize(fields[i]);
            serialize(map[fields[i]]);
        }
        stream.write(HproseTags.TagClosebrace);
    }
    function writeMapWithRef(map) {
        if (!refer.write(map)) writeMap(map);
    }
    function writeHarmonyMap(map) {
        refer.set(map);
        var count = map.size;
        stream.write(HproseTags.TagMap);
        if (count > 0) stream.write(count.toString());
        stream.write(HproseTags.TagOpenbrace);
        map.forEach(function(value, key, m) {
            serialize(key);
            serialize(value);
        });
        stream.write(HproseTags.TagClosebrace);
    }
    function writeHarmonyMapWithRef(map) {
        if (!refer.write(map)) writeHarmonyMap(map);
    }
    function writeObject(obj) {
        var classname = getClassName(obj);
        var fields;
        var index = classref[classname];
        if (index >= 0) {
            fields = fieldsref[index];
        }
        else {
            fields = [];
            for (var key in obj) {
                if (obj.hasOwnProperty(key) &&
                    typeof(obj[key]) !== 'function') {
                    fields[fields.length] = key.toString();
                }
            }
            index = writeClass(classname, fields);
        }
        stream.write(HproseTags.TagObject);
        stream.write(index.toString());
        stream.write(HproseTags.TagOpenbrace);
        refer.set(obj);
        var count = fields.length;
        for (var i = 0; i < count; i++) {
            serialize(obj[fields[i]]);
        }
        stream.write(HproseTags.TagClosebrace);
    }
    function writeObjectWithRef(obj) {
        if (!refer.write(obj)) writeObject(obj);
    }
    function writeClass(classname, fields) {
        var count = fields.length;
        stream.write(HproseTags.TagClass);
        stream.write(classname.length.toString());
        stream.write(HproseTags.TagQuote);
        stream.write(classname);
        stream.write(HproseTags.TagQuote);
        if (count > 0) stream.write(count.toString());
        stream.write(HproseTags.TagOpenbrace);
        for (var i = 0; i < count; i++) {
            writeString(fields[i]);
        }
        stream.write(HproseTags.TagClosebrace);
        var index = fieldsref.length;
        classref[classname] = index;
        fieldsref[index] = fields;
        return index;
    }
    function reset() {
        classref = Object.create(null);
        fieldsref.length = 0;
        refer.reset();
    }
    this.stream = stream;
    this.serialize = serialize;
    this.writeInteger = writeInteger;
    this.writeDouble = writeDouble;
    this.writeBoolean = writeBoolean;
    this.writeUTCDate = writeUTCDate;
    this.writeUTCDateWithRef = writeUTCDateWithRef;
    this.writeDate = writeDate;
    this.writeDateWithRef = writeDateWithRef;
    this.writeTime = writeTime;
    this.writeTimeWithRef = writeTimeWithRef;
    this.writeBytes = writeBytes;
    this.writeBytesWithRef = writeBytesWithRef;
    this.writeUTF8Char = writeUTF8Char;
    this.writeString = writeString;
    this.writeStringWithRef = writeStringWithRef;
    this.writeList = writeList;
    this.writeListWithRef = writeListWithRef;
    this.writeMap = writeMap;
    this.writeMapWithRef = writeMapWithRef;
    this.writeHarmonyMap = writeHarmonyMap;
    this.writeHarmonyMapWithRef = writeHarmonyMapWithRef;
    this.writeObject = writeObject;
    this.writeObjectWithRef = writeObjectWithRef;
    this.reset = reset;
}

module.exports = HproseWriter;<|endoftext|>


<commit_before>const config = require("./data/SiteConfig");
const urljoin = require("url-join");

const regexExcludeRobots = /^(?!\/(dev-404-page|404|offline-plugin-app-shell-fallback|tags|categories)).*$/;

module.exports = {
  pathPrefix: config.pathPrefix,
  siteMetadata: {
    siteUrl: urljoin(config.siteUrl, config.pathPrefix),
    rssMetadata: {
      site_url: urljoin(config.siteUrl, config.pathPrefix),
      feed_url: urljoin(config.siteUrl, config.pathPrefix, config.siteRss),
      title: config.siteTitle,
      description: config.siteDescription,
      image_url: `${urljoin(
        config.siteUrl,
        config.pathPrefix
      )}/logos/logo-512.png`,
      author: config.userName,
      copyright: config.copyright
    }
  },
  plugins: [
    "gatsby-plugin-react-helmet",
    "gatsby-plugin-lodash",
    "gatsby-plugin-sass",
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "assets",
        path: `${__dirname}/static/assets/`
      }
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "posts",
        path: `${__dirname}/content`
      }
    },
    {
      resolve: "gatsby-transformer-remark",
      options: {
        plugins: [
          {
            resolve: "gatsby-remark-relative-images"
          },
          {
            resolve: "gatsby-remark-images",
            options: {
              maxWidth: 672
            }
          },
          {
            resolve: "gatsby-remark-responsive-iframe"
          },
          "gatsby-remark-prismjs",
          "gatsby-remark-copy-linked-files",
          "gatsby-remark-autolink-headers"
        ]
      }
    },
    {
      resolve: "gatsby-plugin-google-analytics",
      options: {
        trackingId: config.siteGATrackingID
      }
    },
    {
      resolve: "gatsby-plugin-nprogress",
      options: {
        color: "#c62828"
      }
    },
    "gatsby-transformer-sharp",
    "gatsby-plugin-sharp",
    "gatsby-plugin-catch-links",
    "gatsby-plugin-netlify-cms",
    "gatsby-plugin-twitter",
    {
      resolve: "gatsby-plugin-sitemap",
      options: {
        output: "/sitemap.xml",
        query: `
          {
            site {
              siteMetadata {
                siteUrl
              }
            }

            allSitePage(
              filter: {
                path: {
                  regex: "${regexExcludeRobots}"
                }
              }
            ) {
              edges {
                node {
                  path
                }
              }
            }
        }`
      }
    },
    {
      resolve: "gatsby-plugin-manifest",
      options: {
        name: config.siteTitle,
        short_name: config.siteTitleShort,
        description: config.siteDescription,
        start_url: config.pathPrefix,
        background_color: "#e0e0e0",
        theme_color: "#c62828",
        display: "minimal-ui",
        icons: [
          {
            src: "/logos/logo-192.png",
            sizes: "192x192",
            type: "image/png"
          },
          {
            src: "/logos/logo-512.png",
            sizes: "512x512",
            type: "image/png"
          }
        ]
      }
    },
    "gatsby-plugin-offline",
    {
      resolve: "gatsby-plugin-feed",
      options: {
        setup(ref) {
          const ret = ref.query.site.siteMetadata.rssMetadata;
          ret.allMarkdownRemark = ref.query.allMarkdownRemark;
          ret.generator = "GatsbyJS Material Starter";
          return ret;
        },
        query: `
        {
          site {
            siteMetadata {
              rssMetadata {
                site_url
                feed_url
                title
                description
                image_url
                author
                copyright
              }
            }
          }
        }
      `,
        feeds: [
          {
            serialize(ctx) {
              const { rssMetadata } = ctx.query.site.siteMetadata;
              return ctx.query.allMarkdownRemark.edges.map(edge => ({
                categories: edge.node.frontmatter.tags,
                date: edge.node.frontmatter.date,
                title: edge.node.frontmatter.title,
                description: edge.node.excerpt,
                author: rssMetadata.author,
                url: rssMetadata.site_url + edge.node.fields.slug,
                guid: rssMetadata.site_url + edge.node.fields.slug,
                custom_elements: [{ "content:encoded": edge.node.html }]
              }));
            },
            query: `
            {
              allMarkdownRemark(
                limit: 1000,
                sort: { order: DESC, fields: [frontmatter___date] },
              ) {
                edges {
                  node {
                    excerpt
                    html
                    timeToRead
                    fields { slug }
                    frontmatter {
                      title
                      cover
                      date
                      category
                      tags
                    }
                  }
                }
              }
            }
          `,
            output: config.siteRss
          }
        ]
      }
    }
  ]
};
<commit_msg>Make empty config.pathPrefix an acceptable option.<commit_after>const urljoin = require("url-join");
const config = require("./data/SiteConfig");

const regexExcludeRobots = /^(?!\/(dev-404-page|404|offline-plugin-app-shell-fallback|tags|categories)).*$/;

module.exports = {
  pathPrefix: config.pathPrefix === "" ? "/" : config.pathPrefix,
  siteMetadata: {
    siteUrl: urljoin(config.siteUrl, config.pathPrefix),
    rssMetadata: {
      site_url: urljoin(config.siteUrl, config.pathPrefix),
      feed_url: urljoin(config.siteUrl, config.pathPrefix, config.siteRss),
      title: config.siteTitle,
      description: config.siteDescription,
      image_url: `${urljoin(
        config.siteUrl,
        config.pathPrefix
      )}/logos/logo-512.png`,
      author: config.userName,
      copyright: config.copyright
    }
  },
  plugins: [
    "gatsby-plugin-react-helmet",
    "gatsby-plugin-lodash",
    "gatsby-plugin-sass",
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "assets",
        path: `${__dirname}/static/assets/`
      }
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "posts",
        path: `${__dirname}/content`
      }
    },
    {
      resolve: "gatsby-transformer-remark",
      options: {
        plugins: [
          {
            resolve: "gatsby-remark-relative-images"
          },
          {
            resolve: "gatsby-remark-images",
            options: {
              maxWidth: 672
            }
          },
          {
            resolve: "gatsby-remark-responsive-iframe"
          },
          "gatsby-remark-prismjs",
          "gatsby-remark-copy-linked-files",
          "gatsby-remark-autolink-headers"
        ]
      }
    },
    {
      resolve: "gatsby-plugin-google-analytics",
      options: {
        trackingId: config.siteGATrackingID
      }
    },
    {
      resolve: "gatsby-plugin-nprogress",
      options: {
        color: "#c62828"
      }
    },
    "gatsby-transformer-sharp",
    "gatsby-plugin-sharp",
    "gatsby-plugin-catch-links",
    "gatsby-plugin-netlify-cms",
    "gatsby-plugin-twitter",
    {
      resolve: "gatsby-plugin-sitemap",
      options: {
        output: "/sitemap.xml",
        query: `
          {
            site {
              siteMetadata {
                siteUrl
              }
            }

            allSitePage(
              filter: {
                path: {
                  regex: "${regexExcludeRobots}"
                }
              }
            ) {
              edges {
                node {
                  path
                }
              }
            }
        }`
      }
    },
    {
      resolve: "gatsby-plugin-manifest",
      options: {
        name: config.siteTitle,
        short_name: config.siteTitleShort,
        description: config.siteDescription,
        start_url: config.pathPrefix,
        background_color: "#e0e0e0",
        theme_color: "#c62828",
        display: "minimal-ui",
        icons: [
          {
            src: "/logos/logo-192.png",
            sizes: "192x192",
            type: "image/png"
          },
          {
            src: "/logos/logo-512.png",
            sizes: "512x512",
            type: "image/png"
          }
        ]
      }
    },
    "gatsby-plugin-offline",
    {
      resolve: "gatsby-plugin-feed",
      options: {
        setup(ref) {
          const ret = ref.query.site.siteMetadata.rssMetadata;
          ret.allMarkdownRemark = ref.query.allMarkdownRemark;
          ret.generator = "GatsbyJS Material Starter";
          return ret;
        },
        query: `
        {
          site {
            siteMetadata {
              rssMetadata {
                site_url
                feed_url
                title
                description
                image_url
                author
                copyright
              }
            }
          }
        }
      `,
        feeds: [
          {
            serialize(ctx) {
              const { rssMetadata } = ctx.query.site.siteMetadata;
              return ctx.query.allMarkdownRemark.edges.map(edge => ({
                categories: edge.node.frontmatter.tags,
                date: edge.node.frontmatter.date,
                title: edge.node.frontmatter.title,
                description: edge.node.excerpt,
                author: rssMetadata.author,
                url: rssMetadata.site_url + edge.node.fields.slug,
                guid: rssMetadata.site_url + edge.node.fields.slug,
                custom_elements: [{ "content:encoded": edge.node.html }]
              }));
            },
            query: `
            {
              allMarkdownRemark(
                limit: 1000,
                sort: { order: DESC, fields: [frontmatter___date] },
              ) {
                edges {
                  node {
                    excerpt
                    html
                    timeToRead
                    fields { slug }
                    frontmatter {
                      title
                      cover
                      date
                      category
                      tags
                    }
                  }
                }
              }
            }
          `,
            output: config.siteRss
          }
        ]
      }
    }
  ]
};
<|endoftext|>


<commit_before>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";

  function init() {
    user = document.getElementById("loginInfo").user.value;
    pass = document.getElementById("loginInfo").pass.value;
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      document.getElementById("loginInfo").user.value = "INVALID INPUT";
      return;
    }
    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

socket.onmessage = function(message) {
  if (message.data.indexOf("pos") == 0){
  userData = message.data.split(":")[1].split(",");

} else if (message.data.indexOf("dat") == 0){
  enemies = message.data.split(":")[1].split(",");
}
};

socket.onclose = function() {
  window.location.reload(false);
};

socket.onerror = function() {
};

document.body.innerHTML = "";
for (i = 0; i < 256; i++){
  isKeyDown[i] = false;
}
$('body').append('<canvas id="GameCanvas">');
var $canvas = $('#GameCanvas');
$canvas.select().focus();
$canvas.attr('width', $(window).innerWidth());
$canvas.attr('height', $(window).innerHeight());
var canvas = $canvas[0];
window.addEventListener( "keydown", keyPress, false);
window.addEventListener( "keyup", keyRelease, false);
context = canvas.getContext('2d');
gameLoop();
}

function gameLoop() {
  var keyData = "";
  for (i = 0; i < 256; i++){
    keyData += isKeyDown[i] ? 1 : 0;
  }
  try {
    socket.send("keys:" + keyData);
  } catch (err) {
  }
  context.clearRect(0, 0, document.body.clientWidth, document.body.clientHeight);
  context.fillStyle = userData[2];
  context.fillRect(userData[0], userData[1], 30, 50);
  context.font = "15px Arial";
  context.fillText(user,(userData[3] - (context.measureText(user).width / 2)) + 15,userData[1] - 5);
  for (i = 0; i < enemies.length; i += 4){
  context.fillStyle = enemies[i+2];
  context.fillRect(enemies[i], enemies[i+1], 30, 50);
  context.fillText(enemies[i+3],(enemies[i] - (context.measureText(enemies[i+3]).width / 2)) + 15,enemies[i+1] - 5);
  }
  setTimeout(gameLoop, frameLength);
}

function keyPress(e){
  isKeyDown[e.keyCode] = true;
}
function keyRelease(e){
  isKeyDown[e.keyCode] = false;
}
function isKeyPressed(c){
  return isKeyDown[c.charCodeAt(0)];
}

return {
  init: init
};
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(event){
    event.preventDefault();
    JS_GAME.game.init();
    $("#user").blur();
    $("#pass").blur();
    this.remove();
    return false;
  });
});
<commit_msg>Mrrrrrr<commit_after>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";

  function init() {
    user = document.getElementById("loginInfo").user.value;
    pass = document.getElementById("loginInfo").pass.value;
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      document.getElementById("loginInfo").user.value = "INVALID INPUT";
      return;
    }
    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

socket.onmessage = function(message) {
  if (message.data.indexOf("pos") == 0){
  userData = message.data.split(":")[1].split(",");

} else if (message.data.indexOf("dat") == 0){
  enemies = message.data.split(":")[1].split(",");
}
};

socket.onclose = function() {
  window.location.reload(false);
};

socket.onerror = function() {
};

document.body.innerHTML = "";
for (i = 0; i < 256; i++){
  isKeyDown[i] = false;
}
$('body').append('<canvas id="GameCanvas">');
var $canvas = $('#GameCanvas');
$canvas.select().focus().click();
$canvas.attr('width', $(window).innerWidth());
$canvas.attr('height', $(window).innerHeight());
var canvas = $canvas[0];
window.addEventListener( "keydown", keyPress, false);
window.addEventListener( "keyup", keyRelease, false);
context = canvas.getContext('2d');
gameLoop();
}

function gameLoop() {
  var keyData = "";
  for (i = 0; i < 256; i++){
    keyData += isKeyDown[i] ? 1 : 0;
  }
  try {
    socket.send("keys:" + keyData);
  } catch (err) {
  }
  context.clearRect(0, 0, document.body.clientWidth, document.body.clientHeight);
  context.fillStyle = userData[2];
  context.fillRect(userData[0], userData[1], 30, 50);
  context.font = "15px Arial";
  context.fillText(user,(userData[3] - (context.measureText(user).width / 2)) + 15,userData[1] - 5);
  for (i = 0; i < enemies.length; i += 4){
  context.fillStyle = enemies[i+2];
  context.fillRect(enemies[i], enemies[i+1], 30, 50);
  context.fillText(enemies[i+3],(enemies[i] - (context.measureText(enemies[i+3]).width / 2)) + 15,enemies[i+1] - 5);
  }
  setTimeout(gameLoop, frameLength);
}

function keyPress(e){
  isKeyDown[e.keyCode] = true;
}
function keyRelease(e){
  isKeyDown[e.keyCode] = false;
}
function isKeyPressed(c){
  return isKeyDown[c.charCodeAt(0)];
}

return {
  init: init
};
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(event){
    event.preventDefault();
    JS_GAME.game.init();
    $("#user").blur();
    $("#pass").blur();
    this.remove();
    return false;
  });
});
<|endoftext|>


<commit_before>/*
 * Copyright 2016 EPAM Systems
 *
 *
 * This file is part of EPAM Report Portal.
 * https://github.com/epam/ReportPortal
 *
 * Report Portal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Report Portal is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Report Portal.  If not, see <http://www.gnu.org/licenses/>.
 */

define(function (require, exports, module) {
    "use strict";
    var $ = require('jquery');
    var Backbone = require('backbone');
    var Util = require('util');

    // Main modules
    var Dashboard = require('dashboard');
    var Favorites = require('favorites');
    var Launch = require('launch');
    var LaunchPage = require('launches/LaunchPage');
    var Project = require('project');
    var ProjectInfo = require('projectinfo');
    var Member = require('member');
    var Profile = require('userProfile/UserProfilePage');

    // Administrate modules
    var Projects = require('projects');
    var Users = require('users');
    var Settings = require('settings');

    var Content = Backbone.View.extend({

        initialize: function (options) {
            this.isAdminPage = options.isAdminPage;
            this.$el = options.el;
            if (this.isAdminPage) {
                this.queryString = options.queryString;
            }
        },

        tpl: 'tpl-container',

        events: {
            'click #btt': 'scrollTop'
        },

        render: function (options) {
            this.$el.html(Util.templates(this.tpl));
            if (this.isAdminPage) {
                this.$container = $("#dynamic-content", this.$el);
            }

            this.setupPageView(options);
            return this;
        },

        update: function (options) {
            if(this.page !== options.contextName || this.action !== options.action) {
                this.pageView.destroy();
                if (this.isAdminPage) {
                    this.page = options.page;
                    this.action = options.action;
                }
                this.setupPageView(options);
            } else {
                if (this.isAdminPage) {
                    this.page = options.page;
                    this.action = options.action;
                }
                this.pageView.update(options);
            }
        },

        setupPageView: function (options) {
            if (this.isAdminPage) {
                this.page = options.page;
                var PageView = this.getViewForAdministratePage(options);
                options['el'] = this.$container;
                options['header'] = $('#contentHeader', this.$el);
                this.pageView = new PageView(options).render();
            } else {
                this.page = options.contextName;
                var PageView = this.getViewForPage(options.contextName);
                this.$header = $('#contentHeader', this.$el);
                this.$body = $('#dynamic-content', this.$el);
                var self = this;

                this.pageView = new PageView.ContentView({
                    contextName: options.contextName,
                    context: this.getAppProp(self),
                    subContext: options.subContext,
                    queryString: options.queryString
                });
                this.pageView.render();
            }
        },

        getAppProp: function (context) {
            var mainView = context;
            return {
                getMainView: function () {
                    return mainView;
                }
            }
        },

        getViewForPage: function (name) {
            switch (name) {
                case "dashboard":
                    return Dashboard;
                    break;
                case "filters":
                    return Favorites;
                    break;
                case "launches":
                case "userdebug":
                    return Launch;
                    break;
                case "newlaunches":
                    return LaunchPage;
                    break;
                case "members":
                    return Member;
                    break;
                case "settings":
                    return Project;
                    break;
                case "user-profile":
                    return Profile;
                    break;
                case "info":
                    return ProjectInfo;
                    break;
                default:
                    break;
            }
        },

        getViewForAdministratePage: function (options) {
            if (options.page === 'users') {
                return Users.ContentView;
            } else if (options.page === 'project-details') {
                return Projects.ProjectDetails;
            } else if (options.page === 'settings') {
                return Settings.ContentView;
            } else {
                var key = options.page + '-' + options.action;
                switch (key) {
                    case "projects-add":
                    case "projects-settings":
                    case "projects-members":
                        return Projects.Project;
                        break;
                    default:
                        return Projects.List;
                        break;
                }
            }
        },

        scrollTop: function () {
            $('body,html').animate({
                scrollTop: 0
            }, 100);
            return false;
        },

        destroy: function () {
            this.pageView.destroy();
            this.$el.off().empty();
            this.undelegateEvents();
            this.stopListening();
        }
    });

    return Content;
});<commit_msg>minor fix<commit_after>/*
 * Copyright 2016 EPAM Systems
 *
 *
 * This file is part of EPAM Report Portal.
 * https://github.com/epam/ReportPortal
 *
 * Report Portal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Report Portal is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Report Portal.  If not, see <http://www.gnu.org/licenses/>.
 */

define(function (require, exports, module) {
    "use strict";
    var $ = require('jquery');
    var Backbone = require('backbone');
    var Util = require('util');

    // Main modules
    var Dashboard = require('dashboard');
    var Favorites = require('favorites');
    var Launch = require('launch');
    var LaunchPage = require('launches/LaunchPage');
    var Project = require('project');
    var ProjectInfo = require('projectinfo');
    var Member = require('member');
    var Profile = require('userProfile/UserProfilePage');

    // Administrate modules
    var Projects = require('projects');
    var Users = require('users');
    var Settings = require('settings');

    var Content = Backbone.View.extend({

        initialize: function (options) {
            this.isAdminPage = options.isAdminPage;
            this.$el = options.el;
            if (this.isAdminPage) {
                this.queryString = options.queryString;
            }
        },

        tpl: 'tpl-container',

        events: {
            'click #btt': 'scrollTop'
        },

        render: function (options) {
            this.$el.html(Util.templates(this.tpl));
            if (this.isAdminPage) {
                this.$container = $("#dynamic-content", this.$el);
            }

            this.setupPageView(options);
            return this;
        },

        update: function (options) {
            if(this.page !== options.contextName || this.action !== options.action) {
                this.pageView.destroy();
                if (this.isAdminPage) {
                    this.page = options.page;
                    this.action = options.action;
                }
                this.setupPageView(options);
            } else {
                this.pageView.update(options);
            }
        },

        setupPageView: function (options) {
            if (this.isAdminPage) {
                this.page = options.page;
                var PageView = this.getViewForAdministratePage(options);
                options['el'] = this.$container;
                options['header'] = $('#contentHeader', this.$el);
                this.pageView = new PageView(options).render();
            } else {
                this.page = options.contextName;
                var PageView = this.getViewForPage(options.contextName);
                this.$header = $('#contentHeader', this.$el);
                this.$body = $('#dynamic-content', this.$el);
                var self = this;

                this.pageView = new PageView.ContentView({
                    contextName: options.contextName,
                    context: this.getAppProp(self),
                    subContext: options.subContext,
                    queryString: options.queryString
                });
                this.pageView.render();
            }
        },

        getAppProp: function (context) {
            var mainView = context;
            return {
                getMainView: function () {
                    return mainView;
                }
            }
        },

        getViewForPage: function (name) {
            switch (name) {
                case "dashboard":
                    return Dashboard;
                    break;
                case "filters":
                    return Favorites;
                    break;
                case "launches":
                case "userdebug":
                    return Launch;
                    break;
                case "newlaunches":
                    return LaunchPage;
                    break;
                case "members":
                    return Member;
                    break;
                case "settings":
                    return Project;
                    break;
                case "user-profile":
                    return Profile;
                    break;
                case "info":
                    return ProjectInfo;
                    break;
                default:
                    break;
            }
        },

        getViewForAdministratePage: function (options) {
            if (options.page === 'users') {
                return Users.ContentView;
            } else if (options.page === 'project-details') {
                return Projects.ProjectDetails;
            } else if (options.page === 'settings') {
                return Settings.ContentView;
            } else {
                var key = options.page + '-' + options.action;
                switch (key) {
                    case "projects-add":
                    case "projects-settings":
                    case "projects-members":
                        return Projects.Project;
                        break;
                    default:
                        return Projects.List;
                        break;
                }
            }
        },

        scrollTop: function () {
            $('body,html').animate({
                scrollTop: 0
            }, 100);
            return false;
        },

        destroy: function () {
            this.pageView.destroy();
            this.$el.off().empty();
            this.undelegateEvents();
            this.stopListening();
        }
    });

    return Content;
});<|endoftext|>


<commit_before>'use strict';

const Promise = require('bluebird');
const _ = require('lodash');
const parseError = require('error_parser');
const messagingFn = require('./services/messaging');

module.exports = function module(context) {
    const events = context.apis.foundation.getSystemEvents();
    const cluster = context.cluster;
    const config = context.sysconfig.teraslice;
    const exId = process.env.ex_id;
    const jobId = process.env.job_id;
    const ID = `${context.sysconfig.teraslice.hostname}__${cluster.worker.id}`;
    const jobRunner = require('./runners/job')(context);
    const recycleWorkerRandomFactor = _.random(75, 100);

    let isDone = true;
    let isShuttingDown = false;
    let analyticsStore;
    let stateStore;
    let queue;
    let maxRetries;
    let job;
    let recycle;

    // this will be used to keep track of the previously sent message just in case of a disconnect
    let sentMessage = false;

    // this will store errors and the number of retries
    const errorLog = {};

    const logger = context.apis.foundation.makeLogger({
        ex_id: exId,
        job_id: jobId,
        module: 'worker',
        worker_id: ID
    });
    // need ipc channels open before job construction
    const messaging = messagingFn(context, logger);

    // if worker cannot make client, job needs to shutdown, needs to be setup before jobRunner
    events.on('getClient:config_error', terminalShutdown);

    const host = messaging.getHostUrl();

    logger.info(`worker ${ID} is online, communicating with host: ${host}`);

    messaging.register({
        event: 'assets:loaded',
        callback: ipcMessage => events.emit('worker:assets_loaded', ipcMessage)
    });

    // set up listener
    messaging.register({
        event: 'slicer:slice:new',
        callback: (msg) => {
            isDone = false;
            // getting a slice means the previous message was handled
            sentMessage = false;
            logger.info(`received slice: ${msg.payload.slice_id}`);
            const sliceLogger = context.apis.foundation.makeLogger({
                ex_id: exId,
                job_id: jobId,
                module: 'slice',
                worker_id: ID,
                slice_id: msg.payload.slice_id
            });

            runSlice(msg.payload, sliceLogger);
        }
    });

    messaging.register({
        event: 'slicer:slice:recorded',
        callback: () => {
        // the sent message has been processed, so set it to false;
            logger.debug('slice has been marked as completed by slicer');
            sentMessage = false;
        }
    });

    messaging.register({
        event: 'network:error',
        callback: (err) => {
            events.emit('network:error');
            logger.error('Error in worker socket: ', err);
        }
    });

    messaging.register({
        event: 'network:disconnect',
        callback: (event) => {
            events.emit('network:disconnect');
            if (!isShuttingDown) {
                logger.error(`worker ${ID} has disconnected from slicer ex_id ${exId}`, event);
            }
        }
    });

    messaging.register({
        event: 'network:connect',
        callback: () => {
            if (sentMessage) {
                logger.warn('reconnecting to slicer, previous slice: ', sentMessage);
                sentMessage.retry = true;
                messaging.send({ to: 'slicer', message: 'worker:slice:complete', worker_id: ID, payload: sentMessage });
            } else {
                logger.debug(`a worker has made the initial connection to slicer ex_id: ${exId}`);
                messaging.send({ to: 'slicer', message: 'worker:ready', worker_id: ID, payload: { worker_id: ID } });
            }
        }
    });

    const finalShutdown = _.once(shutdown);

    messaging.register({ event: 'worker:shutdown', callback: finalShutdown });

    // to catch signal propagation, but cleanup through msg sent from master
    function noOP() {
    }

    messaging.register({ event: 'process:SIGTERM', callback: noOP });
    messaging.register({ event: 'process:SIGINT', callback: noOP });

    Promise.resolve(require('./storage/assets')(context))
        .then(() =>
            // assets store is loaded so it can register under context.apis
            jobRunner.initialize(events, logger)
        )
        .then((_job) => {
            job = _job;
            queue = _job.queue;
            maxRetries = _job.maxRetries;
            recycle = recycleFn(job);
            return require('./storage/state')(context);
        })
        .then((store) => {
            stateStore = store;
            return require('./storage/analytics')(context);
        })
        .then((store) => {
            analyticsStore = store;
            logger.info(`connecting to host: ${host}`);
            messaging.initialize();
        })
        .catch((err) => {
            const errMsg = `worker: ${ID} could not instantiate for execution: ${exId}, error: ${parseError(err)}`;
            logger.error(errMsg);
            messaging.send({
                to: 'cluster_master',
                message: 'execution:error:terminal',
                ex_id: exId,
                error: errMsg
            })
                .then(() => logger.flush())
                .then(() => process.exit())
                .catch((flushErr) => {
                    const flushErrMsg = parseError(flushErr);
                    logger.error(flushErrMsg);
                    process.exit();
                });
        });

    function isReady(res, slice, msg, specData, sliceLogger) {
        // res may return null if no data was received
        return stateStore.updateState(slice, 'completed', slice.index)
            .then(() => {
                events.emit('slice:success', slice);
                sentMessage = { worker_id: ID, slice, analytics: specData };
                sliceLogger.info('completed slice: ', slice);
                if (isShuttingDown) {
                    sentMessage.isShuttingDown = true;
                }

                if (specData) {
                    if (job.reporter) {
                        job.reporter(context, job.jobConfig, specData);
                        logMessage(sliceLogger, msg);
                    } else {
                        logMessage(sliceLogger, msg, specData);
                        return analyticsStore.log(job, slice, specData)
                            .catch((err) => {
                                const errMsg = parseError(err);
                                logger.error(`Failure when storing analytics: ${errMsg}`);
                            });
                    }
                }
                return true;
            })
            .finally(() => {
                events.emit('slice:finalize');
                isDone = true;
                recycle();
            });
    }

    function runSlice(slice, sliceLogger) {
        function sliceFailed(err) {
            const errMsg = parseError(err);
            sentMessage = { worker_id: ID, slice, error: errMsg };
            events.emit('slice:failure', sentMessage);
            return stateStore.updateState(slice, 'error', errMsg)
                .then(() => sliceLogger.error(`failed to process ${JSON.stringify(sentMessage)}, slice state has been marked as error`))
                .catch((updateError) => {
                    const updateErrorMsg = parseError(updateError);
                    sliceLogger.error(`An error has occurred while marking slice as failed: ${updateErrorMsg} , message: `, slice);
                });
        }

        const msg = slice.request;
        const sliceID = slice.slice_id;

        let finalQueue = queue;
        let specData;

        if (job.analytics) {
            specData = { time: [], size: [], memory: [] };

            finalQueue = queue.map(fn => fn.bind(null, specData));
        }

        Promise.reduce(finalQueue, (prev, fn) => Promise.resolve(prev)
            .then(data => fn(data, sliceLogger, msg)
            ), msg)
            .then(res => isReady(res, slice, msg, specData, sliceLogger))
            .catch((err) => {
                const errMsg = parseError(err);
                sliceLogger.error(`An error has occurred: ${errMsg}, message: `, slice);
                if (maxRetries) {
                    // checking if error has occurred before
                    if (errorLog[sliceID]) {
                        errorLog[sliceID] += 1;

                        if (errorLog[sliceID] >= maxRetries) {
                            sliceLogger.error('Max retires has been reached for: ', slice);

                            sliceFailed(err)
                                .finally(() => {
                                    events.emit('slice:finalize');
                                    isDone = true;
                                    recycle();
                                });
                        } else {
                            events.emit('slice:retry');
                            runSlice(slice, sliceLogger);
                        }
                    } else {
                        events.emit('slice:retry');
                        errorLog[sliceID] = 1;
                        runSlice(slice, sliceLogger);
                    }
                } else {
                    // no retries, proceed to next slice
                    sliceFailed(err)
                        .finally(() => {
                            events.emit('slice:finalize');
                            isDone = true;
                            recycle();
                        });
                }
            });
    }

    function shutdown() {
        let counter = config.shutdown_timeout;
        isShuttingDown = true;
        events.emit('worker:shutdown');
        const shutDownInterval = setInterval(() => {
            logger.trace(`is done with current slice: ${isDone}, shutdown counter: ${counter}`);
            if (isDone || counter <= 0) {
                logger.info('shutting down');
                clearInterval(shutDownInterval);
                const shutdownSequence = [];
                if (analyticsStore !== undefined) {
                    shutdownSequence.push(analyticsStore.shutdown);
                }
                if (stateStore !== undefined) {
                    shutdownSequence.push(stateStore.shutdown);
                }

                shutdownSequence.push(logger.flush);

                Promise.reduce(shutdownSequence, (prev, curr) => Promise.resolve(prev)
                    .then(() => curr())
                    .catch((err) => {
                        const errMsg = parseError(err);
                        logger.error(`Error shutting down store ${prev.name}`, errMsg);
                        return curr();
                    }))
                    .then(() => {
                        process.exit();
                    })
                    .catch((err) => {
                        const errMsg = parseError(err);
                        logger.error(errMsg);
                        // TODO: the log might never be called to stdout with process.exit here
                        process.exit();
                    });
            } else {
                if (counter % 6000 === 0) {
                    logger.info(`shutdown sequence initiated, but is still processing. Will force shutdown in ${counter / 1000} seconds`);
                }

                counter -= 1000;
            }
        }, 1000);
    }

    function terminalShutdown(errEV) {
        logger.error(`Terminal error, shutting down job ${exId}`);
        events.emit('worker:shutdown');
        messaging.respond({ message: 'execution:error:terminal', error: errEV.err, ex_id: exId });
    }

    function recycleFn(jobSpec) {
        let sliceCount = 0;
        const recycleWorker = jobSpec.jobConfig.recycle_worker;
        return function () {
            if (recycleWorker) {
                sliceCount += 1;
                // recycle worker between 75% and 100% of job.jobConfig.recycle_worker
                const recycleCount = Math.trunc((recycleWorkerRandomFactor / 100) * recycleWorker);
                if (sliceCount >= recycleCount && !isShuttingDown) {
                    logger.info(`worker: ${ID} recycled after processing ${sliceCount} slices`);
                    // still need to signal that slice completed and not be enqueued
                    sentMessage.isShuttingDown = true;
                    messaging.send({ to: 'slicer', message: 'worker:slice:complete', worker_id: ID, payload: sentMessage });
                    setTimeout(() => {
                        process.exit(42);
                    }, 100);
                } else {
                    messaging.send({ to: 'slicer', message: 'worker:slice:complete', worker_id: ID, payload: sentMessage });
                }
            } else {
                messaging.send({ to: 'slicer', message: 'worker:slice:complete', worker_id: ID, payload: sentMessage });
            }
        };
    }

    function logMessage(sliceLogger, msg, specData) {
        const str = 'analytics for slice ';
        let dataStr = '';

        if (typeof msg === 'string') {
            dataStr = `${msg}, `;
        } else {
            _.forOwn(msg, (value, key) => {
                dataStr += `${key} : ${value} `;
            });
        }
        _.forOwn(specData, (value, key) => {
            dataStr += `${key} : ${value} `;
        });

        sliceLogger.info(str + dataStr);
    }
};
<commit_msg>Fixing the refactor error that breaks retries<commit_after>'use strict';

const Promise = require('bluebird');
const _ = require('lodash');
const parseError = require('error_parser');
const messagingFn = require('./services/messaging');

module.exports = function module(context) {
    const events = context.apis.foundation.getSystemEvents();
    const cluster = context.cluster;
    const config = context.sysconfig.teraslice;
    const exId = process.env.ex_id;
    const jobId = process.env.job_id;
    const ID = `${context.sysconfig.teraslice.hostname}__${cluster.worker.id}`;
    const jobRunner = require('./runners/job')(context);
    const recycleWorkerRandomFactor = _.random(75, 100);

    let isDone = true;
    let isShuttingDown = false;
    let analyticsStore;
    let stateStore;
    let queue;
    let maxRetries;
    let job;
    let recycle;

    // this will be used to keep track of the previously sent message just in case of a disconnect
    let sentMessage = false;

    // this will store errors and the number of retries
    const errorLog = {};

    const logger = context.apis.foundation.makeLogger({
        ex_id: exId,
        job_id: jobId,
        module: 'worker',
        worker_id: ID
    });
    // need ipc channels open before job construction
    const messaging = messagingFn(context, logger);

    // if worker cannot make client, job needs to shutdown, needs to be setup before jobRunner
    events.on('getClient:config_error', terminalShutdown);

    const host = messaging.getHostUrl();

    logger.info(`worker ${ID} is online, communicating with host: ${host}`);

    messaging.register({
        event: 'assets:loaded',
        callback: ipcMessage => events.emit('worker:assets_loaded', ipcMessage)
    });

    // set up listener
    messaging.register({
        event: 'slicer:slice:new',
        callback: (msg) => {
            isDone = false;
            // getting a slice means the previous message was handled
            sentMessage = false;
            logger.info(`received slice: ${msg.payload.slice_id}`);
            const sliceLogger = context.apis.foundation.makeLogger({
                ex_id: exId,
                job_id: jobId,
                module: 'slice',
                worker_id: ID,
                slice_id: msg.payload.slice_id
            });

            runSlice(msg.payload, sliceLogger);
        }
    });

    messaging.register({
        event: 'slicer:slice:recorded',
        callback: () => {
        // the sent message has been processed, so set it to false;
            logger.debug('slice has been marked as completed by slicer');
            sentMessage = false;
        }
    });

    messaging.register({
        event: 'network:error',
        callback: (err) => {
            events.emit('network:error');
            logger.error('Error in worker socket: ', err);
        }
    });

    messaging.register({
        event: 'network:disconnect',
        callback: (event) => {
            events.emit('network:disconnect');
            if (!isShuttingDown) {
                logger.error(`worker ${ID} has disconnected from slicer ex_id ${exId}`, event);
            }
        }
    });

    messaging.register({
        event: 'network:connect',
        callback: () => {
            if (sentMessage) {
                logger.warn('reconnecting to slicer, previous slice: ', sentMessage);
                sentMessage.retry = true;
                messaging.send({ to: 'slicer', message: 'worker:slice:complete', worker_id: ID, payload: sentMessage });
            } else {
                logger.debug(`a worker has made the initial connection to slicer ex_id: ${exId}`);
                messaging.send({ to: 'slicer', message: 'worker:ready', worker_id: ID, payload: { worker_id: ID } });
            }
        }
    });

    const finalShutdown = _.once(shutdown);

    messaging.register({ event: 'worker:shutdown', callback: finalShutdown });

    // to catch signal propagation, but cleanup through msg sent from master
    function noOP() {
    }

    messaging.register({ event: 'process:SIGTERM', callback: noOP });
    messaging.register({ event: 'process:SIGINT', callback: noOP });

    Promise.resolve(require('./storage/assets')(context))
        .then(() =>
            // assets store is loaded so it can register under context.apis
            jobRunner.initialize(events, logger)
        )
        .then((_job) => {
            job = _job;
            queue = _job.queue;
            maxRetries = _job.max_retries;
            recycle = recycleFn(job);
            return require('./storage/state')(context);
        })
        .then((store) => {
            stateStore = store;
            return require('./storage/analytics')(context);
        })
        .then((store) => {
            analyticsStore = store;
            logger.info(`connecting to host: ${host}`);
            messaging.initialize();
        })
        .catch((err) => {
            const errMsg = `worker: ${ID} could not instantiate for execution: ${exId}, error: ${parseError(err)}`;
            logger.error(errMsg);
            messaging.send({
                to: 'cluster_master',
                message: 'execution:error:terminal',
                ex_id: exId,
                error: errMsg
            })
                .then(() => logger.flush())
                .then(() => process.exit())
                .catch((flushErr) => {
                    const flushErrMsg = parseError(flushErr);
                    logger.error(flushErrMsg);
                    process.exit();
                });
        });

    function isReady(res, slice, msg, specData, sliceLogger) {
        // res may return null if no data was received
        return stateStore.updateState(slice, 'completed', slice.index)
            .then(() => {
                events.emit('slice:success', slice);
                sentMessage = { worker_id: ID, slice, analytics: specData };
                sliceLogger.info('completed slice: ', slice);
                if (isShuttingDown) {
                    sentMessage.isShuttingDown = true;
                }

                if (specData) {
                    if (job.reporter) {
                        job.reporter(context, job.jobConfig, specData);
                        logMessage(sliceLogger, msg);
                    } else {
                        logMessage(sliceLogger, msg, specData);
                        return analyticsStore.log(job, slice, specData)
                            .catch((err) => {
                                const errMsg = parseError(err);
                                logger.error(`Failure when storing analytics: ${errMsg}`);
                            });
                    }
                }
                return true;
            })
            .finally(() => {
                events.emit('slice:finalize');
                isDone = true;
                recycle();
            });
    }

    function runSlice(slice, sliceLogger) {
        function sliceFailed(err) {
            const errMsg = parseError(err);
            sentMessage = { worker_id: ID, slice, error: errMsg };
            events.emit('slice:failure', sentMessage);
            return stateStore.updateState(slice, 'error', errMsg)
                .then(() => sliceLogger.error(`failed to process ${JSON.stringify(sentMessage)}, slice state has been marked as error`))
                .catch((updateError) => {
                    const updateErrorMsg = parseError(updateError);
                    sliceLogger.error(`An error has occurred while marking slice as failed: ${updateErrorMsg} , message: `, slice);
                });
        }

        const msg = slice.request;
        const sliceID = slice.slice_id;

        let finalQueue = queue;
        let specData;

        if (job.analytics) {
            specData = { time: [], size: [], memory: [] };

            finalQueue = queue.map(fn => fn.bind(null, specData));
        }

        Promise.reduce(finalQueue, (prev, fn) => Promise.resolve(prev)
            .then(data => fn(data, sliceLogger, msg)
            ), msg)
            .then(res => isReady(res, slice, msg, specData, sliceLogger))
            .catch((err) => {
                const errMsg = parseError(err);
                sliceLogger.error(`An error has occurred: ${errMsg}, message: `, slice);
                if (maxRetries) {
                    // checking if error has occurred before
                    if (errorLog[sliceID]) {
                        errorLog[sliceID] += 1;

                        if (errorLog[sliceID] >= maxRetries) {
                            sliceLogger.error('Max retires has been reached for: ', slice);

                            sliceFailed(err)
                                .finally(() => {
                                    events.emit('slice:finalize');
                                    isDone = true;
                                    recycle();
                                });
                        } else {
                            events.emit('slice:retry');
                            runSlice(slice, sliceLogger);
                        }
                    } else {
                        events.emit('slice:retry');
                        errorLog[sliceID] = 1;
                        runSlice(slice, sliceLogger);
                    }
                } else {
                    // no retries, proceed to next slice
                    sliceFailed(err)
                        .finally(() => {
                            events.emit('slice:finalize');
                            isDone = true;
                            recycle();
                        });
                }
            });
    }

    function shutdown() {
        let counter = config.shutdown_timeout;
        isShuttingDown = true;
        events.emit('worker:shutdown');
        const shutDownInterval = setInterval(() => {
            logger.trace(`is done with current slice: ${isDone}, shutdown counter: ${counter}`);
            if (isDone || counter <= 0) {
                logger.info('shutting down');
                clearInterval(shutDownInterval);
                const shutdownSequence = [];
                if (analyticsStore !== undefined) {
                    shutdownSequence.push(analyticsStore.shutdown);
                }
                if (stateStore !== undefined) {
                    shutdownSequence.push(stateStore.shutdown);
                }

                shutdownSequence.push(logger.flush);

                Promise.reduce(shutdownSequence, (prev, curr) => Promise.resolve(prev)
                    .then(() => curr())
                    .catch((err) => {
                        const errMsg = parseError(err);
                        logger.error(`Error shutting down store ${prev.name}`, errMsg);
                        return curr();
                    }))
                    .then(() => {
                        process.exit();
                    })
                    .catch((err) => {
                        const errMsg = parseError(err);
                        logger.error(errMsg);
                        // TODO: the log might never be called to stdout with process.exit here
                        process.exit();
                    });
            } else {
                if (counter % 6000 === 0) {
                    logger.info(`shutdown sequence initiated, but is still processing. Will force shutdown in ${counter / 1000} seconds`);
                }

                counter -= 1000;
            }
        }, 1000);
    }

    function terminalShutdown(errEV) {
        logger.error(`Terminal error, shutting down job ${exId}`);
        events.emit('worker:shutdown');
        messaging.respond({ message: 'execution:error:terminal', error: errEV.err, ex_id: exId });
    }

    function recycleFn(jobSpec) {
        let sliceCount = 0;
        const recycleWorker = jobSpec.jobConfig.recycle_worker;
        return function () {
            if (recycleWorker) {
                sliceCount += 1;
                // recycle worker between 75% and 100% of job.jobConfig.recycle_worker
                const recycleCount = Math.trunc((recycleWorkerRandomFactor / 100) * recycleWorker);
                if (sliceCount >= recycleCount && !isShuttingDown) {
                    logger.info(`worker: ${ID} recycled after processing ${sliceCount} slices`);
                    // still need to signal that slice completed and not be enqueued
                    sentMessage.isShuttingDown = true;
                    messaging.send({ to: 'slicer', message: 'worker:slice:complete', worker_id: ID, payload: sentMessage });
                    setTimeout(() => {
                        process.exit(42);
                    }, 100);
                } else {
                    messaging.send({ to: 'slicer', message: 'worker:slice:complete', worker_id: ID, payload: sentMessage });
                }
            } else {
                messaging.send({ to: 'slicer', message: 'worker:slice:complete', worker_id: ID, payload: sentMessage });
            }
        };
    }

    function logMessage(sliceLogger, msg, specData) {
        const str = 'analytics for slice ';
        let dataStr = '';

        if (typeof msg === 'string') {
            dataStr = `${msg}, `;
        } else {
            _.forOwn(msg, (value, key) => {
                dataStr += `${key} : ${value} `;
            });
        }
        _.forOwn(specData, (value, key) => {
            dataStr += `${key} : ${value} `;
        });

        sliceLogger.info(str + dataStr);
    }
};
<|endoftext|>


<commit_before>$(document).ready(function() {

    $('#calendar').fullCalendar({
        header: {
        left: 'prevYear,nextYear, prev,next, today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay',
		},
		weekends:false,
		businessHours: true,
		editable: true,
		events:'/seances' /*[
        {
            title: 'My Event',
            start: '2015-11-12',
        },{
        title: 'AHAHAH',
        start: '2015-11-28',
        }
    ]*/,
    /*eventDataTransform: function (rawEventData) {
                       return {
                           id: rawEventData.id,
                           title: rawEventData.nom,
                           start: rawEventData.dateDebut,
                           end: rawEventData.dateFin,
                        //   url: rawEventData.url
                       };
                   }*/
		eventClick: function(calEvent, jsEvent, view) {
		document.getElementById('nomSeance').placeholder=calEvent.title;
        document.getElementById('LienSeance').click();

        // change the border color just for fun
        //$(this).css('border-color', 'red');

    }

  });

$.ajax({url: "/matiere", success: function(result){ // putting "admin" need to be the pseudo log
 	// document.cookie ="username="+result[0].userName;
 	 // alert(result.toJSON());
//console.log(result.fulfillmentValue[0].nom);
              for (i = 0; i< result.length; i++){
           document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].innerHTML +=
	"<option>"+result[i].nom+"</option>";
			document.getElementById('SupprimerMatiere').getElementsByTagName('select')[0].innerHTML +=
			  "<option>"+result[i].nom+"</option>";
			  document.getElementById('ConsulterMatiere').getElementsByTagName('select')[0].innerHTML +=
			  "<option>"+result[i].nom+"</option>";
              }

        }});

$.ajax({url: "/filiere", success: function(result){ // putting "admin" need to be the pseudo log
 	// document.cookie ="username="+result[0].userName;
 	 // alert(result.toJSON());
//console.log(result.fulfillmentValue[0].nom);
              for (j = 0; j< result.length; j++){
           document.getElementById('CreerMatiere').getElementsByTagName('select')[0].innerHTML +=
	"<option>"+result[j].nom+"</option>";
			document.getElementById('SupprimerFiliere').getElementsByTagName('select')[0].innerHTML +=
			"<option>"+result[j].nom+"</option>";
			document.getElementById('ConsulterFiliere').getElementsByTagName('select')[0].innerHTML +=
			"<option>"+result[j].nom+"</option>";
              }

        }});

$.ajax({url: "/enseignement", success: function(result){ // putting "admin" need to be the pseudo log
 	// document.cookie ="username="+result[0].userName;
 	 // alert(result.toJSON());
//console.log(result.fulfillmentValue[0].nom);
              for (x = 0; x< result.length; x++){
			document.getElementById('SupprimerEnseignement').getElementsByTagName('select')[0].innerHTML +=
			  "<option>"+result[x].nom+"</option>";
			  document.getElementById('ConsulterEnseignement').getElementsByTagName('select')[0].innerHTML +=
			  "<option>"+result[x].nom+"</option>";
              }

        }});

});

// function creerfiliere(){
	// $.post("/creerFiliere",
	// {
		// nom: document.getElementById("creerFiliere").getElementsByTagName("input")[0].value,
	// },
		// function(data, status){
			// console.log(data,"succés");
		// }
	// );
// }

function creerMatiere(){
	$.post("/creerMatiere",
	{
		filiere: document.getElementById("creerMatiere").getElementsByTagName("input")[0].value,
		nom: document.getElementById("creerMatiere").getElementsByTagName("input")[1].value,
	},
		function(data, status){
			console.log(data,"succés");
		}
	);
}

function supprimerMatiere(){
	var nom = document.getElementsByName('matiere')[1].value;
	$.ajax({url: "/matiere/" + nom, type:"DELETE", success: function(result){alert('Vous avez bien supprimé la matière ' + nom);}});
}

function supprimerFiliere(){
	var nom = document.getElementsByName('filiere')[1].value;
	$.ajax({url: "/filiere/" + nom, type:"DELETE", success: function(result){alert('Vous avez bien supprimé la filière ' + nom);}});
}

function supprimerEnseignement(){
	var nom = document.getElementsByName('enseignement')[1].value;
	$.ajax({url: "/enseignement/" + nom, type:"DELETE", success: function(result){alert('Vous avez bien supprimé l\'enseignement ' + nom);}});
}

function consulterEnseignement(){
	$.ajax({url: "/seancesByEnseignement", type:"GET", success: function(result){$('#calendar').fullCalendar( 'removeEvents'); $('#calendar').fullCalendar('addEventSource', result );}});
}

function consulterMatiere(){
	$.ajax({url: "/seancesByMatiere", type:"GET", success: function(result){$('#calendar').fullCalendar( 'removeEvents'); $('#calendar').fullCalendar('addEventSource', result );}});
}

function consulterFiliere(){
	$.ajax({url: "/seancesByFiliere", type:"GET", success: function(result){$('#calendar').fullCalendar( 'removeEvents'); $('#calendar').fullCalendar('addEventSource', result );}});
}

function NomEnseignementExam(){
	if(document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value != ""){
			document.getElementById('nom_enseignement').value= document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value + " - Examen";
	}
}

function NomEnseignementCM(){
	if(document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value != ""){
		document.getElementById('nom_enseignement').value= document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value + " - CM";
	}
}

function NomEnseignementTD(){
	if(document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value != ""){
		document.getElementById('nom_enseignement').value= document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value + " - TD";
	}
}

function NomEnseignementSelect(){
	if(document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value != "" && document.getElementById('CM').checked==true ){
		document.getElementById('nom_enseignement').value= document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value + " - CM";
	}
	if(document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value != "" && document.getElementById('TD').checked==true ){
		document.getElementById('nom_enseignement').value= document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value + " - TD";
	}
	if(document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value != "" && document.getElementById('Exam').checked==true ){
		document.getElementById('nom_enseignement').value= document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value + " - Examen";
	}
}
<commit_msg>Bug FullCalendar<commit_after>$(document).ready(function() {

    $('#calendar').fullCalendar({
        header: {
        left: 'prevYear,nextYear, prev,next, today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay',
		},
		businessHours: true,
		editable: true,
		events:'/seances' /*[
        {
            title: 'My Event',
            start: '2015-11-12',
        },{
        title: 'AHAHAH',
        start: '2015-11-28',
        }
    ]*/,
    /*eventDataTransform: function (rawEventData) {
                       return {
                           id: rawEventData.id,
                           title: rawEventData.nom,
                           start: rawEventData.dateDebut,
                           end: rawEventData.dateFin,
                        //   url: rawEventData.url
                       };
                   }*/
		eventClick: function(calEvent, jsEvent, view) {
		document.getElementById('nomSeance').placeholder=calEvent.title;
        document.getElementById('LienSeance').click();

        // change the border color just for fun
        //$(this).css('border-color', 'red');

    }

  });

$.ajax({url: "/matiere", success: function(result){ // putting "admin" need to be the pseudo log
 	// document.cookie ="username="+result[0].userName;
 	 // alert(result.toJSON());
//console.log(result.fulfillmentValue[0].nom);
              for (i = 0; i< result.length; i++){
           document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].innerHTML +=
	"<option>"+result[i].nom+"</option>";
			document.getElementById('SupprimerMatiere').getElementsByTagName('select')[0].innerHTML +=
			  "<option>"+result[i].nom+"</option>";
			  document.getElementById('ConsulterMatiere').getElementsByTagName('select')[0].innerHTML +=
			  "<option>"+result[i].nom+"</option>";
              }

        }});

$.ajax({url: "/filiere", success: function(result){ // putting "admin" need to be the pseudo log
 	// document.cookie ="username="+result[0].userName;
 	 // alert(result.toJSON());
//console.log(result.fulfillmentValue[0].nom);
              for (j = 0; j< result.length; j++){
           document.getElementById('CreerMatiere').getElementsByTagName('select')[0].innerHTML +=
	"<option>"+result[j].nom+"</option>";
			document.getElementById('SupprimerFiliere').getElementsByTagName('select')[0].innerHTML +=
			"<option>"+result[j].nom+"</option>";
			document.getElementById('ConsulterFiliere').getElementsByTagName('select')[0].innerHTML +=
			"<option>"+result[j].nom+"</option>";
              }

        }});

$.ajax({url: "/enseignement", success: function(result){ // putting "admin" need to be the pseudo log
 	// document.cookie ="username="+result[0].userName;
 	 // alert(result.toJSON());
//console.log(result.fulfillmentValue[0].nom);
              for (x = 0; x< result.length; x++){
			document.getElementById('SupprimerEnseignement').getElementsByTagName('select')[0].innerHTML +=
			  "<option>"+result[x].nom+"</option>";
			  document.getElementById('ConsulterEnseignement').getElementsByTagName('select')[0].innerHTML +=
			  "<option>"+result[x].nom+"</option>";
              }

        }});

});

// function creerfiliere(){
	// $.post("/creerFiliere",
	// {
		// nom: document.getElementById("creerFiliere").getElementsByTagName("input")[0].value,
	// },
		// function(data, status){
			// console.log(data,"succés");
		// }
	// );
// }

function creerMatiere(){
	$.post("/creerMatiere",
	{
		filiere: document.getElementById("creerMatiere").getElementsByTagName("input")[0].value,
		nom: document.getElementById("creerMatiere").getElementsByTagName("input")[1].value,
	},
		function(data, status){
			console.log(data,"succés");
		}
	);
}

function supprimerMatiere(){
	var nom = document.getElementsByName('matiere')[1].value;
	$.ajax({url: "/matiere/" + nom, type:"DELETE", success: function(result){alert('Vous avez bien supprimé la matière ' + nom);}});
}

function supprimerFiliere(){
	var nom = document.getElementsByName('filiere')[1].value;
	$.ajax({url: "/filiere/" + nom, type:"DELETE", success: function(result){alert('Vous avez bien supprimé la filière ' + nom);}});
}

function supprimerEnseignement(){
	var nom = document.getElementsByName('enseignement')[1].value;
	$.ajax({url: "/enseignement/" + nom, type:"DELETE", success: function(result){alert('Vous avez bien supprimé l\'enseignement ' + nom);}});
}

function consulterEnseignement(){
	$.ajax({url: "/seancesByEnseignement", type:"GET", success: function(result){$('#calendar').fullCalendar( 'removeEvents'); $('#calendar').fullCalendar('addEventSource', result );}});
}

function consulterMatiere(){
	$.ajax({url: "/seancesByMatiere", type:"GET", success: function(result){$('#calendar').fullCalendar( 'removeEvents'); $('#calendar').fullCalendar('addEventSource', result );}});
}

function consulterFiliere(){
	$.ajax({url: "/seancesByFiliere", type:"GET", success: function(result){$('#calendar').fullCalendar( 'removeEvents'); $('#calendar').fullCalendar('addEventSource', result );}});
}

function NomEnseignementExam(){
	if(document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value != ""){
			document.getElementById('nom_enseignement').value= document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value + " - Examen";
	}
}

function NomEnseignementCM(){
	if(document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value != ""){
		document.getElementById('nom_enseignement').value= document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value + " - CM";
	}
}

function NomEnseignementTD(){
	if(document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value != ""){
		document.getElementById('nom_enseignement').value= document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value + " - TD";
	}
}

function NomEnseignementSelect(){
	if(document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value != "" && document.getElementById('CM').checked==true ){
		document.getElementById('nom_enseignement').value= document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value + " - CM";
	}
	if(document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value != "" && document.getElementById('TD').checked==true ){
		document.getElementById('nom_enseignement').value= document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value + " - TD";
	}
	if(document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value != "" && document.getElementById('Exam').checked==true ){
		document.getElementById('nom_enseignement').value= document.getElementById('CreerEnseignement').getElementsByTagName('select')[0].value + " - Examen";
	}
}
<|endoftext|>