<commit_before>.import QtQuick.LocalStorage 2.0 as Sql

/*

  new QMDatabase('myApp', '1.0')
  define : returns an object with functions create/filter/delete
  create: returns an object with the properties
  */

function QMDatabase(appName, version) {

    //Tables to handle version control
    this.conn = Sql.LocalStorage.openDatabaseSync(appName + '_db', "1.0", appName, 100000,
        function(db) { console.log("*** DATABASE DOESNT EXIST ****"); }
    );
    var AppVersion = this.define('__AppVersion__', {
        appName: this.String('App Name', {accept_null:false}),
        version: this.String('Version', {accept_null:false})
    });

    var appVersion = AppVersion.filter({appName: appName}).get();
    this.migrate = false;
    if (appVersion) {
        if (appVersion.version !== version) {
            appVersion.version = version;
            appVersion.save();
            this.migrate = true
        }
    } else {
        appVersion = AppVersion.create({appName: appName, version: version});
        this.migrate = false;
    }
}

QMDatabase.prototype = {
    constructor: QMDatabase,

    String: function(label, params) {
        return new QMField('TEXT', label, params);
    },
    Integer: function(label, params) {
        return new QMField('INTEGER', label, params);
    },
    Float: function(label, params) {
        return new QMField('FLOAT', label, params);
    },
    Real: function(label, params) {
        return new QMField('REAL', label, params);
    },
    Date: function(label, params) {
        return new QMField('DATE', label, params);
    },
    DateTime: function(label, params) {
        return new QMField('DATETIME', label, params);
    },
    PK: function(label, params) {
        return new QMField('INTEGER PRIMARY KEY', label, params);
    },
    FK: function(label, params) {
        return new QMField('FK', label, params);
    },
    _defineField: function(column, data) {
        var sql;
        var items = [];
        var fk = [];

        //If is a foreign key
        if (data.type === 'FK') {
            items.push(column)
            items.push('INTEGER')
            fk.push('FOREIGN KEY(' + column + ')')
        }
        else if (data.type === 'PK') {
            items.push(column);
            items.push('INTEGER PRIMARY KEY');
        }
        else {
            items.push(column);
            items.push(data.type);
        }

        for (var param in data.params) {
            switch(param) {
                case 'accept_null':
                    if (!data.params[param]) {
                        items.push('NOT NULL');
                    }
                    break;
                case 'unique':
                    if (unique) {
                        items.push('UNIQUE');
                    }
                    break;
                case 'references':
                    fk.push('REFERENCES ' + data.params[param] + '(id) ON DELETE CASCADE');
                    break;
                case 'default':
                    items.push('DEFAULT ' + data.params[param]);
                    break;

            }
        }

        return {field: items.join(' '), fk: fk.join(' ')};
    },
    retrieveFields: function(name) {
        var rs;
        var sql = "PRAGMA table_info(" + name + ")";
        this.conn.transaction(
            function(tx) {
                console.log("Run SQL: " + sql);
                rs = tx.executeSql(sql);
            }
        )

        var fields = {};
        for (var idx=0; idx < rs.rows.length; idx++) {
            fields[rs.rows[idx].name] = null;
        }

        return fields;
    },
    define: function(name, data) {
        var sql_create = "CREATE TABLE IF NOT EXISTS " + name + " (";
        var idx = 0;
        this.properties = {};
        this.tableName = name;

        var field_pk = this._defineField('id', {type: 'PK'});
        sql_create += field_pk['field'];
        this.properties['id'] = null;

        var foreign_keys = [];
        for (var column in data) {
            if (column === 'id') continue;
            var definitions = data[column];
            var field_data = this._defineField(column, data[column]);
            sql_create += ", " + field_data['field'];

            if (field_data['fk'].length > 0) {
                foreign_keys.push(field_data['fk']);
            }

            this.properties[column] = null;
            idx++;
        }

        //Create foreign key references
        for (var ifk=0; ifk < foreign_keys.length; ifk++) {
            sql_create += ", " + foreign_keys[ifk];
        }

        sql_create += ")";
        var model = new QMModel(this, name, this.properties);

        var oldObjs = [];
        if (this.migrate) {
            var oldFields = this.retrieveFields(name);
            var oldModel = new QMModel(this, name, oldFields);

            oldObjs = oldModel.all();
            this._runSQL("DROP TABLE " + name);
        }

        //Run create table
        this._runSQL(sql_create);

        if (this.migrate) {
            for (var i=0; i< oldObjs.length; i++) {
                for (var field in oldObjs[i]) {
                    if (!(field in this.properties) && field !== '_meta' && field !== 'save') {
                        delete oldObjs[i][field];
                    }
                }

                oldObjs[i].save(true);
            }
        }

        return model;
    },
    _runSQL: function(sql) {
        this.conn.transaction(
            function(tx) {
                console.log("Run SQL: " + sql);
                tx.executeSql(sql);
            }
        )
    }
};

/*******************************
  QMModel
  Define a class referencing a database table
  *****************************/

function QMModel(db, tableName, fields) {
    this.filterConditions = {};
    this.sorters = [];
    this.limiters = null;

    this._meta = {
        db: db,
        tableName: tableName,
        fields: fields,
    };
}

QMModel.prototype = {
    create: function(data) {
        var obj = this._makeObject(data);
        var insertId = this.insert(obj);

        var objs = this.filter({id:insertId}).all();
        if (objs.length > 0) {
            return objs[0];
        }

        return null;
    },
    filter: function(conditions) {
        this.filterConditions = conditions;
        return this;
    },
    order: function(sorters) {
        if (typeof sorters === 'string') {
            if (!this.sorters) {
                this.sorters = [];
            }
            this.sorters.push(sorters);
        }
        else if (Array.isArray(sorters)) {
            this.sorters = sorters;
        }
        return this;
    },
    limit: function(limiter) {
        this.limiter = limiter;
        return this;
    },
    get: function() {
        var objs = this.limit(1).all();
        if (objs.length > 0)
            return objs[0];

        return null;
    },
    all: function() {
        var sql = "SELECT ";
        var fields = [];
        for (var field in this._meta.fields) {
            fields.push(field);
        }

        sql += fields.join(',');
        sql += " FROM " + this._meta.tableName;
        sql += this._defineWhereClause();

        if (this.sorters && this.sorters.constructor === String) {
            this.sorters = [this.sorters];
        }

        if (this.sorters && this.sorters.length > 0) {
            sql += " ORDER BY ";
            for (var idxOrder=0; idxOrder < this.sorters.length; idxOrder++) {
                if (idxOrder > 0) sql += ", ";
                var ord = this.sorters[idxOrder];
                if (ord[0] === '-') {
                    sql += ord.substring(1) + " DESC ";
                }
                else {
                    sql += ord;
                }
            }
        }

        if (this.limiter) {
            sql += " LIMIT " + this.limiter;
        }

        var rs = [];

        this._meta.db.conn.transaction(
            function(tx) {
                console.log("Run SQL: " + sql);
                rs = tx.executeSql(sql)

                //console.log("RESULT SET: " + rs);
            }
        )

        var objs = [];
        for (var i=0; i < rs.rows.length; i++) {
            var item = rs.rows.item(i);
            var obj = this._makeObject(item);
            objs.push(obj);
        }

        this.filterConditions = {};
        this.limiter = null;
        this.sorters = null;

        return objs;
    },
    update: function(newValues) {
        var sql = "UPDATE " + this._meta.tableName + " SET ";
        var idx = 0;
        for (var field in newValues) {
            if (field === 'id') continue;

            if (idx > 0) sql += ",";
            sql += field + " = '" + newValues[field] + "'";
            idx++;
        };
        sql += this._defineWhereClause(this.filterConditions);

        this._meta.db._runSQL(sql);
        this.filterConditions = {};
    },
    insert: function(obj) {
        var sql = "INSERT INTO " + this._meta.tableName + "(";
        var fields = [];
        var values = [];
        for (var field in obj) {
            if (field === 'id' || field === '_meta' || field === 'save')
                continue;
            fields.push(field);
            if (obj[field]) {
                values.push("'" + obj[field] + "'");
            }
            else {
                values.push('NULL');
            }
        }
        sql += fields.join(',');
        sql += ") VALUES (" + values.join(',') + ")";

        var rs;
        this._meta.db.conn.transaction(
            function(tx) {
                console.log("Run SQL: " + sql);
                rs = tx.executeSql(sql);
            }
        )

        return rs.insertId;
    },
    remove: function() {
        var sql = "DELETE FROM " + this._meta.tableName;
        sql += this._defineWhereClause();
        this._meta.db._runSQL(sql);
        this.filterConditions = {};
    },
    _defineWhereClause: function() {
        var sql = '';
        var idx = 0;

        for (var cond in this.filterConditions) {
            if (idx > 0) sql += " AND ";
            var operator;
            var newOperator = '=';
            var field = cond;
            var position;
            if (cond.indexOf('__') > -1) {
                var operands = cond.split('__');
                field = operands[0];
                operator = operands[1];

                switch(operator) {
                case 'gt':
                    newOperator = '>'; break;
                case 'ge':
                    newOperator = '>='; break;
                case 'lt':
                    newOperator = '<'; break;
                case 'le':
                    newOperator = '<='; break;
                case 'null':
                    if (this.filterConditions[cond])
                        newOperator = 'IS NULL';
                    else
                        newOperator = 'IS NOT NULL';
                    break;
                case 'like':
                    newOperator = 'LIKE';
                    position = 'BEGINEND';
                    break;
                case 'startswith':
                    newOperator = 'LIKE';
                    position = 'END';
                    break;
                case 'endswith':
                    newOperator = 'LIKE';
                    position = 'BEGIN';
                    break;
                }
            }
            else if (this.filterConditions[cond].constructor === Array) {
                newOperator = 'IN';
            }

            sql += field + " " + newOperator + " ";
            if (newOperator === 'LIKE') {
                sql += "'";
                if (position.indexOf('BEGIN') > -1) {
                    sql += "%";
                }
                sql += this.filterConditions[cond];
                if (position.indexOf('END') > -1) {
                    sql += "%";
                }
                sql += "'";
            } else if (operator !== 'null') {
                if (this.filterConditions[cond].constructor === String) {
                    sql += "'" + this.filterConditions[cond] + "'";
                } else if (newOperator === 'IN') {
                    sql += "('" + this.filterConditions[cond].join("','") + "')";
                }
                else {
                    sql += this.filterConditions[cond];
                }
            }
            idx++;
        }

        if (sql.length > 0) {
            sql = " WHERE " + sql;
        }

        return sql;
    },
    _makeObject: function(values) {
        var obj = new QMObject(this);
        for (var key in values) {
            obj[key] = values[key];
        }
        return obj;
    }
};

/**************************************
  QMObject
  reference a single instance of a object in the database
  *************************************/
function QMObject(model) {
    this._meta = {
        model: model,
    };

    this.id = null;
    //Functions for single object
    //save
    this.save = function(forceInsert) {
       if (typeof forceInsert === 'undefined') { forceInsert = false; }
       var updateFields = {};
       for (var newValue in this) {
           if (newValue !== 'save' && newValue !== '_meta') {
               updateFields[newValue] = this[newValue];
           }
       }

       if (this.id && !forceInsert) {
           model.filter({id: this.id}).update(updateFields);
       } else {
           model.insert(updateFields);
       }
    }

}

/*******************************************
  QMField
  Define a database field with attributes
  ******************************************/

function QMField(type, label, params) {
    this.items = [];
    var fieldName;
    this.type = type;
    this.params = params;
}

//TODO: Migrations!
//TODO: Replace concatenations with binds '?'
<commit_msg>Removed version from quickmodel<commit_after>.import QtQuick.LocalStorage 2.0 as Sql

/*

  new QMDatabase('myApp', '1.0')
  define : returns an object with functions create/filter/delete
  create: returns an object with the properties
  */

function QMDatabase(appName, version) {

    //Tables to handle version control
    this.conn = Sql.LocalStorage.openDatabaseSync(appName + '_db', "", appName, 100000,
        function(db) { console.log("*** DATABASE DOESNT EXIST ****"); }
    );
    var AppVersion = this.define('__AppVersion__', {
        appName: this.String('App Name', {accept_null:false}),
        version: this.String('Version', {accept_null:false})
    });

    var appVersion = AppVersion.filter({appName: appName}).get();
    this.migrate = false;
    if (appVersion) {
        if (appVersion.version !== version) {
            appVersion.version = version;
            appVersion.save();
            this.migrate = true
        }
    } else {
        appVersion = AppVersion.create({appName: appName, version: version});
        this.migrate = false;
    }
}

QMDatabase.prototype = {
    constructor: QMDatabase,

    String: function(label, params) {
        return new QMField('TEXT', label, params);
    },
    Integer: function(label, params) {
        return new QMField('INTEGER', label, params);
    },
    Float: function(label, params) {
        return new QMField('FLOAT', label, params);
    },
    Real: function(label, params) {
        return new QMField('REAL', label, params);
    },
    Date: function(label, params) {
        return new QMField('DATE', label, params);
    },
    DateTime: function(label, params) {
        return new QMField('DATETIME', label, params);
    },
    PK: function(label, params) {
        return new QMField('INTEGER PRIMARY KEY', label, params);
    },
    FK: function(label, params) {
        return new QMField('FK', label, params);
    },
    _defineField: function(column, data) {
        var sql;
        var items = [];
        var fk = [];

        //If is a foreign key
        if (data.type === 'FK') {
            items.push(column)
            items.push('INTEGER')
            fk.push('FOREIGN KEY(' + column + ')')
        }
        else if (data.type === 'PK') {
            items.push(column);
            items.push('INTEGER PRIMARY KEY');
        }
        else {
            items.push(column);
            items.push(data.type);
        }

        for (var param in data.params) {
            switch(param) {
                case 'accept_null':
                    if (!data.params[param]) {
                        items.push('NOT NULL');
                    }
                    break;
                case 'unique':
                    if (unique) {
                        items.push('UNIQUE');
                    }
                    break;
                case 'references':
                    fk.push('REFERENCES ' + data.params[param] + '(id) ON DELETE CASCADE');
                    break;
                case 'default':
                    items.push('DEFAULT ' + data.params[param]);
                    break;

            }
        }

        return {field: items.join(' '), fk: fk.join(' ')};
    },
    retrieveFields: function(name) {
        var rs;
        var sql = "PRAGMA table_info(" + name + ")";
        this.conn.transaction(
            function(tx) {
                console.log("Run SQL: " + sql);
                rs = tx.executeSql(sql);
            }
        )

        var fields = {};
        for (var idx=0; idx < rs.rows.length; idx++) {
            fields[rs.rows[idx].name] = null;
        }

        return fields;
    },
    define: function(name, data) {
        var sql_create = "CREATE TABLE IF NOT EXISTS " + name + " (";
        var idx = 0;
        this.properties = {};
        this.tableName = name;

        var field_pk = this._defineField('id', {type: 'PK'});
        sql_create += field_pk['field'];
        this.properties['id'] = null;

        var foreign_keys = [];
        for (var column in data) {
            if (column === 'id') continue;
            var definitions = data[column];
            var field_data = this._defineField(column, data[column]);
            sql_create += ", " + field_data['field'];

            if (field_data['fk'].length > 0) {
                foreign_keys.push(field_data['fk']);
            }

            this.properties[column] = null;
            idx++;
        }

        //Create foreign key references
        for (var ifk=0; ifk < foreign_keys.length; ifk++) {
            sql_create += ", " + foreign_keys[ifk];
        }

        sql_create += ")";
        var model = new QMModel(this, name, this.properties);

        var oldObjs = [];
        if (this.migrate) {
            var oldFields = this.retrieveFields(name);
            var oldModel = new QMModel(this, name, oldFields);

            oldObjs = oldModel.all();
            this._runSQL("DROP TABLE " + name);
        }

        //Run create table
        this._runSQL(sql_create);

        if (this.migrate) {
            for (var i=0; i< oldObjs.length; i++) {
                for (var field in oldObjs[i]) {
                    if (!(field in this.properties) && field !== '_meta' && field !== 'save') {
                        delete oldObjs[i][field];
                    }
                }

                oldObjs[i].save(true);
            }
        }

        return model;
    },
    _runSQL: function(sql) {
        this.conn.transaction(
            function(tx) {
                console.log("Run SQL: " + sql);
                tx.executeSql(sql);
            }
        )
    }
};

/*******************************
  QMModel
  Define a class referencing a database table
  *****************************/

function QMModel(db, tableName, fields) {
    this.filterConditions = {};
    this.sorters = [];
    this.limiters = null;

    this._meta = {
        db: db,
        tableName: tableName,
        fields: fields,
    };
}

QMModel.prototype = {
    create: function(data) {
        var obj = this._makeObject(data);
        var insertId = this.insert(obj);

        var objs = this.filter({id:insertId}).all();
        if (objs.length > 0) {
            return objs[0];
        }

        return null;
    },
    filter: function(conditions) {
        this.filterConditions = conditions;
        return this;
    },
    order: function(sorters) {
        if (typeof sorters === 'string') {
            if (!this.sorters) {
                this.sorters = [];
            }
            this.sorters.push(sorters);
        }
        else if (Array.isArray(sorters)) {
            this.sorters = sorters;
        }
        return this;
    },
    limit: function(limiter) {
        this.limiter = limiter;
        return this;
    },
    get: function() {
        var objs = this.limit(1).all();
        if (objs.length > 0)
            return objs[0];

        return null;
    },
    all: function() {
        var sql = "SELECT ";
        var fields = [];
        for (var field in this._meta.fields) {
            fields.push(field);
        }

        sql += fields.join(',');
        sql += " FROM " + this._meta.tableName;
        sql += this._defineWhereClause();

        if (this.sorters && this.sorters.constructor === String) {
            this.sorters = [this.sorters];
        }

        if (this.sorters && this.sorters.length > 0) {
            sql += " ORDER BY ";
            for (var idxOrder=0; idxOrder < this.sorters.length; idxOrder++) {
                if (idxOrder > 0) sql += ", ";
                var ord = this.sorters[idxOrder];
                if (ord[0] === '-') {
                    sql += ord.substring(1) + " DESC ";
                }
                else {
                    sql += ord;
                }
            }
        }

        if (this.limiter) {
            sql += " LIMIT " + this.limiter;
        }

        var rs = [];

        this._meta.db.conn.transaction(
            function(tx) {
                console.log("Run SQL: " + sql);
                rs = tx.executeSql(sql)

                //console.log("RESULT SET: " + rs);
            }
        )

        var objs = [];
        for (var i=0; i < rs.rows.length; i++) {
            var item = rs.rows.item(i);
            var obj = this._makeObject(item);
            objs.push(obj);
        }

        this.filterConditions = {};
        this.limiter = null;
        this.sorters = null;

        return objs;
    },
    update: function(newValues) {
        var sql = "UPDATE " + this._meta.tableName + " SET ";
        var idx = 0;
        for (var field in newValues) {
            if (field === 'id') continue;

            if (idx > 0) sql += ",";
            sql += field + " = '" + newValues[field] + "'";
            idx++;
        };
        sql += this._defineWhereClause(this.filterConditions);

        this._meta.db._runSQL(sql);
        this.filterConditions = {};
    },
    insert: function(obj) {
        var sql = "INSERT INTO " + this._meta.tableName + "(";
        var fields = [];
        var values = [];
        for (var field in obj) {
            if (field === 'id' || field === '_meta' || field === 'save')
                continue;
            fields.push(field);
            if (obj[field]) {
                values.push("'" + obj[field] + "'");
            }
            else {
                values.push('NULL');
            }
        }
        sql += fields.join(',');
        sql += ") VALUES (" + values.join(',') + ")";

        var rs;
        this._meta.db.conn.transaction(
            function(tx) {
                console.log("Run SQL: " + sql);
                rs = tx.executeSql(sql);
            }
        )

        return rs.insertId;
    },
    remove: function() {
        var sql = "DELETE FROM " + this._meta.tableName;
        sql += this._defineWhereClause();
        this._meta.db._runSQL(sql);
        this.filterConditions = {};
    },
    _defineWhereClause: function() {
        var sql = '';
        var idx = 0;

        for (var cond in this.filterConditions) {
            if (idx > 0) sql += " AND ";
            var operator;
            var newOperator = '=';
            var field = cond;
            var position;
            if (cond.indexOf('__') > -1) {
                var operands = cond.split('__');
                field = operands[0];
                operator = operands[1];

                switch(operator) {
                case 'gt':
                    newOperator = '>'; break;
                case 'ge':
                    newOperator = '>='; break;
                case 'lt':
                    newOperator = '<'; break;
                case 'le':
                    newOperator = '<='; break;
                case 'null':
                    if (this.filterConditions[cond])
                        newOperator = 'IS NULL';
                    else
                        newOperator = 'IS NOT NULL';
                    break;
                case 'like':
                    newOperator = 'LIKE';
                    position = 'BEGINEND';
                    break;
                case 'startswith':
                    newOperator = 'LIKE';
                    position = 'END';
                    break;
                case 'endswith':
                    newOperator = 'LIKE';
                    position = 'BEGIN';
                    break;
                }
            }
            else if (this.filterConditions[cond].constructor === Array) {
                newOperator = 'IN';
            }

            sql += field + " " + newOperator + " ";
            if (newOperator === 'LIKE') {
                sql += "'";
                if (position.indexOf('BEGIN') > -1) {
                    sql += "%";
                }
                sql += this.filterConditions[cond];
                if (position.indexOf('END') > -1) {
                    sql += "%";
                }
                sql += "'";
            } else if (operator !== 'null') {
                if (this.filterConditions[cond].constructor === String) {
                    sql += "'" + this.filterConditions[cond] + "'";
                } else if (newOperator === 'IN') {
                    sql += "('" + this.filterConditions[cond].join("','") + "')";
                }
                else {
                    sql += this.filterConditions[cond];
                }
            }
            idx++;
        }

        if (sql.length > 0) {
            sql = " WHERE " + sql;
        }

        return sql;
    },
    _makeObject: function(values) {
        var obj = new QMObject(this);
        for (var key in values) {
            obj[key] = values[key];
        }
        return obj;
    }
};

/**************************************
  QMObject
  reference a single instance of a object in the database
  *************************************/
function QMObject(model) {
    this._meta = {
        model: model,
    };

    this.id = null;
    //Functions for single object
    //save
    this.save = function(forceInsert) {
       if (typeof forceInsert === 'undefined') { forceInsert = false; }
       var updateFields = {};
       for (var newValue in this) {
           if (newValue !== 'save' && newValue !== '_meta') {
               updateFields[newValue] = this[newValue];
           }
       }

       if (this.id && !forceInsert) {
           model.filter({id: this.id}).update(updateFields);
       } else {
           model.insert(updateFields);
       }
    }

}

/*******************************************
  QMField
  Define a database field with attributes
  ******************************************/

function QMField(type, label, params) {
    this.items = [];
    var fieldName;
    this.type = type;
    this.params = params;
}

//TODO: Migrations!
//TODO: Replace concatenations with binds '?'
<|endoftext|>


<commit_before>const {
  invokeCallbackHandler: invoke
} = UniServiceJSBridge

const callbackIds = []

function changeHandler () {
  const {
    networkType
  } = getNetworkType()
  callbackIds.forEach(callbackId => {
    invoke(callbackId, {
      errMsg: 'onNetworkStatusChange:ok',
      isConnected: networkType !== 'none',
      networkType
    })
  })
}

export function onNetworkStatusChange (callbackId) {
  const connection = navigator.connection || navigator.webkitConnection
  callbackIds.push(callbackId)
  if (connection) {
    connection.addEventListener('change', changeHandler)
  } else {
    window.addEventListener('offline', changeHandler)
    window.addEventListener('online', changeHandler)
  }
}

export function getNetworkType () {
  const connection = navigator.connection || navigator.webkitConnection
  let networkType = 'unknown'
  if (connection) {
    networkType = connection.type
    if (networkType === 'cellular') {
      networkType = connection.effectiveType.replace('slow-', '')
    } else if (!['none', 'wifi'].includes(networkType)) {
      networkType = 'unknown'
    }
  } else if (navigator.onLine === false) {
    networkType = 'none'
  }
  return {
    errMsg: 'getNetworkType:ok',
    networkType
  }
}
<commit_msg>fix:#983,add effectiveType的判断<commit_after>const {
  invokeCallbackHandler: invoke
} = UniServiceJSBridge

const callbackIds = []

function changeHandler () {
  const {
    networkType
  } = getNetworkType()
  callbackIds.forEach(callbackId => {
    invoke(callbackId, {
      errMsg: 'onNetworkStatusChange:ok',
      isConnected: networkType !== 'none',
      networkType
    })
  })
}

export function onNetworkStatusChange (callbackId) {
  const connection = navigator.connection || navigator.webkitConnection
  callbackIds.push(callbackId)
  if (connection) {
    connection.addEventListener('change', changeHandler)
  } else {
    window.addEventListener('offline', changeHandler)
    window.addEventListener('online', changeHandler)
  }
}

export function getNetworkType () {
  const connection = navigator.connection || navigator.webkitConnection
  let networkType = 'unknown'
  if (connection) {
    networkType = connection.type
    if (networkType === 'cellular') {
      networkType = connection.effectiveType && connection.effectiveType.replace('slow-', '')
    } else if (!['none', 'wifi'].includes(networkType)) {
      networkType = 'unknown'
    }
  } else if (navigator.onLine === false) {
    networkType = 'none'
  }
  return {
    errMsg: 'getNetworkType:ok',
    networkType
  }
}
<|endoftext|>


<commit_before>//idea.route

var express = require('express');
var mongoose = require('mongoose');
var Idea = require('../models/idea.model.js');
var router = express.Router();
var ideaControler = require('../controllers/ideaControler');
var dateFormat = require('dateformat');
var Comment = require('../models/comment.model.js');
var User = require('../models/users.model.js');

router.get('/getAllIeas', function (req, res, next) {

    console.log("getAllIdeas triggerd");
	Idea.aggregate({
		   $lookup:
		     {
		       from: "users",
		       localField: "author",
		       foreignField: "_id",
		       as: "author"
		     }}, function(err, ideas) {
	// Idea.find([{}], function(err, ideas) {

		if (err) {
			console.log(err);
			res.status(400);
			res.json(err);
		} else {
			var ideasList = new Array;

			ideas.forEach(function(idea) {
				ideasList.push({"_id": idea._id,
								"livetime": idea.livetime,
								"description": idea.description,
								"abstract": idea.abstract,
								"title": idea.title,
								"author": {
									"_id": idea.author[0]._id,
									"profileImg": idea.author[0].profileImg,
									"url": idea.author[0].url,
									"title": idea.author[0].title,
									"firstname": idea.author[0].firstname,
									"email": idea.author[0].email,
									"name": idea.author[0].name,
									"contacs": idea.author[0].contacs,
									"followedpersons": idea.author[0].followedpersons,
									"followedideas": idea.author[0].followedideas,
									"created": dateFormat(idea.author[0].created, "dd/mm/yyyy")
								},
								"img": idea.img,
								"scribbles": idea.scribbles,
								"tags": idea.tags,
								"milestones": idea.milestones,
								"likes": idea.likes,
								"privacyType": idea.privacyType,
								"contributors": idea.contributors,
								"lastchanged": dateFormat(idea.lastchanged, "MM:hh dd/mm/yyyy"),
								"created": dateFormat(idea.created, "dd/mm/yyyy")
							});
				});

			res.status(200);
			res.json(ideasList);
		}
	})
});

// router.get('/getIdea/:id', function (req, res, next) {

// 	console.log("getIdea triggerd");
// 	// Idea.findOne({ _id: req.params.id }, function(err, idea) {
// 	Idea.aggregate({
// 	   $lookup:
// 	     {
// 	       from: "users",
// 	       localField: "author",
// 	       foreignField: "_id",
// 	       as: "author"
// 	     }}, function(err, ideas) {

// 		if (err) {
// 			console.log(err);
// 			res.status(400);
// 			res.json(err);
// 		} else {

// 			res.status(200);
// 			res.json({"_id": idea._id,
// 						"livetime": idea.livetime,
// 						"description": idea.description,
// 						"abstract": idea.abstract,
// 						"title": idea.title,
// 						"author": idea.author[0],
// 						"img": idea.img,
// 						"scribble": idea.scribble,
// 						"tags": idea.tags,
// 						"milestones": idea.milestones,
// 						"likes": idea.likes,
// 						"contributors": idea.contributors,
// 						"comments": idea.comments,
// 						"privacyType": idea.privacyType,
// 						"lastchanged": dateFormat(idea.lastchanged, "dd/mm/yyyy"),
// 						"created": dateFormat(idea.created, "dd/mm/yyyy")
// 					});
// 		}

// 	});

// });

router.get('/getIdea/:id', function (req, res, next) {

	console.log("getIdea triggerd");
	Idea.findOne({ _id: req.params.id }, function(err, idea) {
		if (err) {
			console.log(err);
			res.status(400);
			res.json(err);
		} else {

				var author = new Array;
				User.findOne({ _id: idea.author }, function(err, doc) {
				if (err) {
					console.log(err);
					res.status(400);
					res.json(err);
				} else {

					res.status(200);
					var author = {
						"_id": doc._id,
						"profileImg": doc.profileImg,
						"url": doc.url,
						"title": doc.title,
						"firstname": doc.firstname,
						"email": doc.email,
						"name": doc.name,
						"tags": doc.tags,
						"contacs": doc.contacs,
						"followedpersons": doc.followedpersons,
						"followedideas": doc.followedideas,
						"created": dateFormat(doc.created, "dd/mm/yyyy")};

						console.log(typeof idea.contributors);
						User.find({ _id: { $in: idea.contributors }}, function(err, contributorList) {
							if (err) {
								console.log(err);
								res.status(400);
								res.json(err);
							} else {

								var contributors = new Array;

								contributorList.forEach(function(cont) {
									contributors.push({
										"_id": cont._id,
										"profileImg": cont.profileImg,
										"url": cont.url,
										"title": cont.title,
										"firstname": cont.firstname,
										"email": cont.email,
										"name": cont.name,
										"contacs": cont.contacs,
										"followedpersons": cont.followedpersons,
										"followedideas": cont.followedideas,
										"created": dateFormat(cont.created, "dd/mm/yyyy")
									});
								});

								Comment.find({ idea: idea._id }, function(err, commentsList) {
									if (err) {
										console.log(err);
										res.status(400);
										res.json(err);
									} else {
										comments = commentsList;

										res.status(200);
										console.log(idea.scribble);
										res.json({"_id": idea._id,
													"livetime": idea.livetime,
													"description": idea.description,
													"abstract": idea.abstract,
													"title": idea.title,
													"author": author,
													"img": idea.img,
													"scribble": idea.scribble,
													"tags": idea.tags,
													"milestones": idea.milestones,
													"likes": idea.likes,
													"contributors": contributors,
													"comments": comments,
													"privacyType": idea.privacyType,
													"lastchanged": dateFormat(idea.lastchanged, "MM:hh dd/mm/yyyy"),
													"created": dateFormat(idea.created, "dd/mm/yyyy")
												});
									}
							})
						}
					})
				}
			})
		}
	});

});

//not tested
router.get('/getAllIdeasSorted/date', function (req, res, next) {

	console.log("getAllIdeas Sorting Date");
		Idea.aggregate({
		   $lookup:
		     {
		       from: "users",
		       localField: "author",
		       foreignField: "_id",
		       as: "author"
		     }},
		      { $sort : { created : 1} } ,
		      function(err, ideas) {
	// Idea.find([{}], function(err, ideas) {

		if (err) {
			console.log(err);
			res.status(400);
			res.json(err);
		} else {
			var ideasList = new Array;

			ideas.forEach(function(idea) {
				ideasList.push({"_id": idea._id,
								"livetime": idea.livetime,
								"description": idea.description,
								"abstract": idea.abstract,
								"title": idea.title,
								"author": {
									"_id": idea.author[0]._id,
									"profileImg": idea.author[0].profileImg,
									"url": idea.author[0].url,
									"title": idea.author[0].title,
									"firstname": idea.author[0].firstname,
									"email": idea.author[0].email,
									"name": idea.author[0].name,
									"contacs": idea.author[0].contacs,
									"followedpersons": idea.author[0].followedpersons,
									"followedideas": idea.author[0].followedideas,
									"created": dateFormat(idea.author[0].created, "dd/mm/yyyy")
								},
								"img": idea.img,
								"scribbles": idea.scribbles,
								"tags": idea.tags,
								"milestones": idea.milestones,
								"likes": idea.likes,
								"contributors": idea.contributors,
								"lastchanged": dateFormat(idea.lastchanged, "MM:hh dd/mm/yyyy"),
								"created": dateFormat(idea.created, "dd/mm/yyyy")
							});
				});

			res.status(200);
			res.json(ideasList);
		}
	})
});

router.get('/searchIdeas/:term', function (req, res, next) {

	console.log("getAllIdeas Sorting Date");
		Idea.aggregate([
			{
			   $lookup:
			     {
			       from: "users",
			       localField: "author",
			       foreignField: "_id",
			       as: "author"
			     }},
			      { $match: { tags : { $in: req.params.term }} } , function(err, ideas) {
	// Idea.find([{}], function(err, ideas) {

		if (err) {
			console.log(err);
			res.status(400);
			res.json(err);
		} else {
			var ideasList = new Array;

			ideas.forEach(function(idea) {
				ideasList.push({"_id": idea._id,
								"livetime": idea.livetime,
								"description": idea.description,
								"abstract": idea.abstract,
								"title": idea.title,
								"author": {
									"_id": idea.author[0]._id,
									"profileImg": idea.author[0].profileImg,
									"url": idea.author[0].url,
									"title": idea.author[0].title,
									"firstname": idea.author[0].firstname,
									"email": idea.author[0].email,
									"name": idea.author[0].name,
									"contacs": idea.author[0].contacs,
									"followedpersons": idea.author[0].followedpersons,
									"followedideas": idea.author[0].followedideas,
									"created": dateFormat(idea.author[0].created, "dd/mm/yyyy")
								},
								"img": idea.img,
								"scribbles": idea.scribbles,
								"tags": idea.tags,
								"milestones": idea.milestones,
								"likes": idea.likes,
								"contributors": idea.contributors,
								"lastchanged": dateFormat(idea.lastchanged, "MM:hh dd/mm/yyyy"),
								"created": dateFormat(idea.created, "dd/mm/yyyy")
							});
				});

			res.status(200);
			res.json(ideasList);
		}
	}])

});

router.post('/saveNewIdea', ideaControler.saveNewIdea);
router.post('/updateIdea', ideaControler.updateIdea);
router.post('/writeComment', ideaControler.writeComment);
router.post('/followIdea', ideaControler.followIdea);
router.post('/likeIdea', ideaControler.likeIdea);
router.post('/unFollowIdea', ideaControler.followIdea);
router.post('/dislikeIdea', ideaControler.likeIdea);

module.exports = router;<commit_msg>sorting of comments and date is global dd/mm/yyyy hh:MM<commit_after>//idea.route

var express = require('express');
var mongoose = require('mongoose');
var Idea = require('../models/idea.model.js');
var router = express.Router();
var ideaControler = require('../controllers/ideaControler');
var dateFormat = require('dateformat');
var Comment = require('../models/comment.model.js');
var User = require('../models/users.model.js');

router.get('/getAllIeas', function (req, res, next) {

    console.log("getAllIdeas triggerd");
	Idea.aggregate({
		   $lookup:
		     {
		       from: "users",
		       localField: "author",
		       foreignField: "_id",
		       as: "author"
		     }}, function(err, ideas) {
	// Idea.find([{}], function(err, ideas) {

		if (err) {
			console.log(err);
			res.status(400);
			res.json(err);
		} else {
			var ideasList = new Array;

			ideas.forEach(function(idea) {
				ideasList.push({"_id": idea._id,
								"livetime": idea.livetime,
								"description": idea.description,
								"abstract": idea.abstract,
								"title": idea.title,
								"author": {
									"_id": idea.author[0]._id,
									"profileImg": idea.author[0].profileImg,
									"url": idea.author[0].url,
									"title": idea.author[0].title,
									"firstname": idea.author[0].firstname,
									"email": idea.author[0].email,
									"name": idea.author[0].name,
									"contacs": idea.author[0].contacs,
									"followedpersons": idea.author[0].followedpersons,
									"followedideas": idea.author[0].followedideas,
									"created": dateFormat(idea.author[0].created, "dd/mm/yyyy hh:MM")
								},
								"img": idea.img,
								"scribbles": idea.scribbles,
								"tags": idea.tags,
								"milestones": idea.milestones,
								"likes": idea.likes,
								"privacyType": idea.privacyType,
								"contributors": idea.contributors,
								"lastchanged": dateFormat(idea.lastchanged, "dd/mm/yyyy hh:MM"),
								"created": dateFormat(idea.created, "dd/mm/yyyy hh:MM")
							});
				});

			res.status(200);
			res.json(ideasList);
		}
	})
});

// router.get('/getIdea/:id', function (req, res, next) {

// 	console.log("getIdea triggerd");
// 	// Idea.findOne({ _id: req.params.id }, function(err, idea) {
// 	Idea.aggregate({
// 	   $lookup:
// 	     {
// 	       from: "users",
// 	       localField: "author",
// 	       foreignField: "_id",
// 	       as: "author"
// 	     }}, function(err, ideas) {

// 		if (err) {
// 			console.log(err);
// 			res.status(400);
// 			res.json(err);
// 		} else {

// 			res.status(200);
// 			res.json({"_id": idea._id,
// 						"livetime": idea.livetime,
// 						"description": idea.description,
// 						"abstract": idea.abstract,
// 						"title": idea.title,
// 						"author": idea.author[0],
// 						"img": idea.img,
// 						"scribble": idea.scribble,
// 						"tags": idea.tags,
// 						"milestones": idea.milestones,
// 						"likes": idea.likes,
// 						"contributors": idea.contributors,
// 						"comments": idea.comments,
// 						"privacyType": idea.privacyType,
// 						"lastchanged": dateFormat(idea.lastchanged, "dd/mm/yyyy"),
// 						"created": dateFormat(idea.created, "dd/mm/yyyy")
// 					});
// 		}

// 	});

// });

router.get('/getIdea/:id', function (req, res, next) {

	console.log("getIdea triggerd");
	Idea.findOne({ _id: req.params.id }, function(err, idea) {
		if (err) {
			console.log(err);
			res.status(400);
			res.json(err);
		} else {

				var author = new Array;
				User.findOne({ _id: idea.author }, function(err, doc) {
				if (err) {
					console.log(err);
					res.status(400);
					res.json(err);
				} else {

					res.status(200);
					var author = {
						"_id": doc._id,
						"profileImg": doc.profileImg,
						"url": doc.url,
						"title": doc.title,
						"firstname": doc.firstname,
						"email": doc.email,
						"name": doc.name,
						"tags": doc.tags,
						"contacs": doc.contacs,
						"followedpersons": doc.followedpersons,
						"followedideas": doc.followedideas,
						"created": dateFormat(doc.created, "dd/mm/yyyy hh:MM")};

						console.log(typeof idea.contributors);
						User.find({ _id: { $in: idea.contributors }}, function(err, contributorList) {
							if (err) {
								console.log(err);
								res.status(400);
								res.json(err);
							} else {

								var contributors = new Array;

								contributorList.forEach(function(cont) {
									contributors.push({
										"_id": cont._id,
										"profileImg": cont.profileImg,
										"url": cont.url,
										"title": cont.title,
										"firstname": cont.firstname,
										"email": cont.email,
										"name": cont.name,
										"contacs": cont.contacs,
										"followedpersons": cont.followedpersons,
										"followedideas": cont.followedideas,
										"created": dateFormat(cont.created, "dd/mm/yyyy hh:MM")
									});
								});

								Comment.find({ $query: { idea: idea._id }, $orderby: { created : -1 } }, function(err, commentsList) {
									if (err) {
										console.log(err);
										res.status(400);
										res.json(err);
									} else {
										comments = commentsList;

										res.status(200);
										console.log(idea.scribble);
										res.json({"_id": idea._id,
													"livetime": idea.livetime,
													"description": idea.description,
													"abstract": idea.abstract,
													"title": idea.title,
													"author": author,
													"img": idea.img,
													"scribble": idea.scribble,
													"tags": idea.tags,
													"milestones": idea.milestones,
													"likes": idea.likes,
													"contributors": contributors,
													"comments": comments,
													"privacyType": idea.privacyType,
													"lastchanged": dateFormat(idea.lastchanged, "dd/mm/yyyy hh:MM"),
													"created": dateFormat(idea.created, "dd/mm/yyyy hh:MM")
												});
									}
							})
						}
					})
				}
			})
		}
	});

});

//not tested
router.get('/getAllIdeasSorted/date', function (req, res, next) {

	console.log("getAllIdeas Sorting Date");
		Idea.aggregate({
		   $lookup:
		     {
		       from: "users",
		       localField: "author",
		       foreignField: "_id",
		       as: "author"
		     }},
		      { $sort : { created : 1} } ,
		      function(err, ideas) {
	// Idea.find([{}], function(err, ideas) {

		if (err) {
			console.log(err);
			res.status(400);
			res.json(err);
		} else {
			var ideasList = new Array;

			ideas.forEach(function(idea) {
				ideasList.push({"_id": idea._id,
								"livetime": idea.livetime,
								"description": idea.description,
								"abstract": idea.abstract,
								"title": idea.title,
								"author": {
									"_id": idea.author[0]._id,
									"profileImg": idea.author[0].profileImg,
									"url": idea.author[0].url,
									"title": idea.author[0].title,
									"firstname": idea.author[0].firstname,
									"email": idea.author[0].email,
									"name": idea.author[0].name,
									"contacs": idea.author[0].contacs,
									"followedpersons": idea.author[0].followedpersons,
									"followedideas": idea.author[0].followedideas,
									"created": dateFormat(idea.author[0].created, "dd/mm/yyyy hh:MM")
								},
								"img": idea.img,
								"scribbles": idea.scribbles,
								"tags": idea.tags,
								"milestones": idea.milestones,
								"likes": idea.likes,
								"contributors": idea.contributors,
								"lastchanged": dateFormat(idea.lastchanged, "dd/mm/yyyy hh:MM"),
								"created": dateFormat(idea.created, "dd/mm/yyyy hh:MM")
							});
				});

			res.status(200);
			res.json(ideasList);
		}
	})
});

router.get('/searchIdeas/:term', function (req, res, next) {

	console.log("getAllIdeas Sorting Date");
		Idea.aggregate([
			{
			   $lookup:
			     {
			       from: "users",
			       localField: "author",
			       foreignField: "_id",
			       as: "author"
			     }},
			      { $match: { tags : { $in: req.params.term }} } , function(err, ideas) {
	// Idea.find([{}], function(err, ideas) {

		if (err) {
			console.log(err);
			res.status(400);
			res.json(err);
		} else {
			var ideasList = new Array;

			ideas.forEach(function(idea) {
				ideasList.push({"_id": idea._id,
								"livetime": idea.livetime,
								"description": idea.description,
								"abstract": idea.abstract,
								"title": idea.title,
								"author": {
									"_id": idea.author[0]._id,
									"profileImg": idea.author[0].profileImg,
									"url": idea.author[0].url,
									"title": idea.author[0].title,
									"firstname": idea.author[0].firstname,
									"email": idea.author[0].email,
									"name": idea.author[0].name,
									"contacs": idea.author[0].contacs,
									"followedpersons": idea.author[0].followedpersons,
									"followedideas": idea.author[0].followedideas,
									"created": dateFormat(idea.author[0].created, "dd/mm/yyyy hh:MM")
								},
								"img": idea.img,
								"scribbles": idea.scribbles,
								"tags": idea.tags,
								"milestones": idea.milestones,
								"likes": idea.likes,
								"contributors": idea.contributors,
								"lastchanged": dateFormat(idea.lastchanged, "dd/mm/yyyy hh:MM"),
								"created": dateFormat(idea.created, "dd/mm/yyyy hh:MM")
							});
				});

			res.status(200);
			res.json(ideasList);
		}
	}])

});

router.post('/saveNewIdea', ideaControler.saveNewIdea);
router.post('/updateIdea', ideaControler.updateIdea);
router.post('/writeComment', ideaControler.writeComment);
router.post('/followIdea', ideaControler.followIdea);
router.post('/likeIdea', ideaControler.likeIdea);
router.post('/unFollowIdea', ideaControler.followIdea);
router.post('/dislikeIdea', ideaControler.likeIdea);

module.exports = router;<|endoftext|>


<commit_before>var roleHealer = require('role.healer');

var roleBuilder = {

	/** @param {Creep} creep **/
	run: function(creep, target) {

		if (creep.memory.harvesting) {
			var sources = creep.room.find(FIND_SOURCES);
			var spawns = creep.room.find(FIND_STRUCTURES, {
				filter: (structure) => {
					return (
								 (structure.structureType == STRUCTURE_CONTAINER) &&
								 (structure.store[RESOURCE_ENERGY] > creep.carryCapacity));
				}
			});

			// if (sources.length) {
			if (spawns.length > 0) {
				var target = creep.pos.findClosestByRange(spawns);

				if (!(creep.pos.isNearTo(target))) {
					creep.moveTo(target);
				}
				else {
					creep.harvest(target, RESOURCE_ENERGY,
												(creep.carryCapacity - _.sum(creep.carry)));
				}
			}
			if (creep.carry.energy == creep.carryCapacity) {
					creep.say('Building');
			    creep.memory.harvesting = false;
			}
		}
		else {
		  var targets = creep.room.find(FIND_CONSTRUCTION_SITES);

			if (targets.length) {
				var target = creep.pos.findClosestByRange(targets);
				if (creep.build(target) == ERR_NOT_IN_RANGE) {
					creep.moveTo(target);
				}
				else {
					roleHealer.run(creep);
				}
				if (creep.carry.energy == 0) {
					creep.say('Harvesting');
					creep.memory.harvesting = true;
				}
			}
		}

	} // function

}; // roleBuilder

module.exports = roleBuilder;<commit_msg>Adjust changes<commit_after>var roleHealer = require('role.healer');

var roleBuilder = {

	/** @param {Creep} creep **/
	run: function(creep, target) {

		if (creep.memory.harvesting) {
			var sources = creep.room.find(FIND_SOURCES);
			var spawns = creep.room.find(FIND_STRUCTURES, {
				filter: (structure) => {
					return (
								 (structure.structureType == STRUCTURE_SPAWN) &&
								 (structure.store[RESOURCE_ENERGY] > creep.carryCapacity));
				}
			});

			// if (sources.length) {
			if (spawns.length > 0) {
				var target = creep.pos.findClosestByRange(spawns);

				if (!(creep.pos.isNearTo(target))) {
					creep.moveTo(target);
				}
				else {
					creep.harvest(target, RESOURCE_ENERGY,
												(creep.carryCapacity - _.sum(creep.carry)));
				}
			}
			if (creep.carry.energy == creep.carryCapacity) {
					creep.say('Building');
			    creep.memory.harvesting = false;
			}
		}
		else {
		  var targets = creep.room.find(FIND_CONSTRUCTION_SITES, {
		  	filter: (structure) => {
		  		return (!(structure.structureType == STRUCTURE_CONTAINER));
		  	}
		  });

			if (targets.length) {
				var target = creep.pos.findClosestByRange(targets);
				if (creep.build(target) == ERR_NOT_IN_RANGE) {
					creep.moveTo(target);
				}
				else {
					roleHealer.run(creep);
				}
				if (creep.carry.energy == 0) {
					creep.say('Harvesting');
					creep.memory.harvesting = true;
				}
			}
		}

	} // function

}; // roleBuilder

module.exports = roleBuilder;<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Route.extend({
  service: Ember.inject.service('cardstack-routing'),

  model({ type }) {
    let branch = this.modelFor('cardstack').branch;
    return this.store.createRecord(this.get('service').modelType(type, branch));
  }
});
<commit_msg>allow prefilled routingId in new-content route<commit_after>import Ember from 'ember';

export default Ember.Route.extend({
  service: Ember.inject.service('cardstack-routing'),
  queryParams: {
    // optionally prefill the routingId for the new record
    routingId: {
      refreshModel: true
    }
  },

  model({ type }, transition) {
    let { routingId } = transition.queryParams;
    let branch = this.modelFor('cardstack').branch;
    let modelType = this.get('service').modelType(type, branch);

    if (routingId == null) {
      return this.store.createRecord(modelType);
    }

    let initialProperties = Object.create(null);
    let modelClass = Ember.getOwner(this).resolveRegistration(`model:${modelType}`);
    if (!modelClass) {
      throw new Error(`@cardstack/routing tried to use model ${modelType} but it does not exist`);
    }
    if (modelClass.routingField) {
      initialProperties[modelClass.routingField] = routingId;
    } else {
      initialProperties.id = routingId;
    }
    return this.store.createRecord(modelType, initialProperties);
  }
});
<|endoftext|>


<commit_before>module.exports = {
  NODE_ENV: '"production"',
  API_URL: '"/"',
  ANALYTICS_KEY: '"clé de prod settée par prod.env.js UA-110218257-1"',
};
<commit_msg>fix(REC-98) : add real analytics key<commit_after>module.exports = {
  NODE_ENV: '"production"',
  API_URL: '"/"',
  ANALYTICS_KEY: '"UA-110218257-1"',
};
<|endoftext|>


<commit_before>module.exports.alias = [
	'hide'
];

module.exports.command = (message, content, bot) => {
  if (!message.member.hasPermission('ADMINISTRATOR')) return;
	let chan = bot.server.server.channels.get(content);
  if (chan) {
		bot.server.hideChannel(content);
		message.channel.send(`channel ID: ${chan.name} is hidden now.`)
	}
};
<commit_msg>hide message<commit_after>module.exports.alias = [
	'hide'
];

module.exports.command = (message, content, bot) => {
  if (!message.member.hasPermission('ADMINISTRATOR')) return;
	let chan = bot.server.server.channels.get(content);
  if (chan) {
		if (bot.server.ignoredChannels.includes(content)) {
			message.channel.send(`#${chan.name} is already hidden.`);
			return;
		}
		bot.server.hideChannel(content);
		message.channel.send(`#${chan.name} is hidden now.`)
	}
};
<|endoftext|>


<commit_before>// Extract docs into main chunk
import '../../components'
import '../../directives'

// Disable vue global error handler
import Vue from 'vue'

export default function () {
    Vue.config.errorHandler = console.error
}<commit_msg>chore(docs): Import layout and renference into docs.js<commit_after>// Extract docs into main chunk
import '../../components'
import '../../directives'
import '../../reference'
import '../../layout'

// Disable vue global error handler
import Vue from 'vue'

export default function () {
    Vue.config.errorHandler = console.error
}
<|endoftext|>


<commit_before>var auth = function(uid) {
  var firebaseSite = 'https://incandescent-heat-8083.firebaseio.com/people/';
  var firebaseSiteUser = firebaseSite + uid;
  var userData = new Firebase(firebaseSiteUser);

  var dataObj = {};

  userData.on('value', function(snapshot) {
    dataObj = snapshot.val();
    var data = snapshot.val();
    $.trigger('display', data);
  });

  var getConnections = function(callback) {
  };

  var postTransaction = function(obj, user, callback) {
    if(arguments.length < 3){
      var callback = user;
      dataObj["transactions"].push(obj);
      userData.set(dataObj);
      return true;
    }else{
      obj["to"] = uid;
      var otherUser = new Firebase(firebaseSite + user + "/transactions");
      var pushTransaction = otherUser.push();
      pushTransaction.set(obj);
      return true;
    }
    callback();
  };

  var getName = function(user, callback) {

  };

  var postTransaction = function(obj, user, callback) {
    if (arguments.length === 2) {
      callback = user;
    } else {

    }
    appData.set();
  };

  var createUser = function() {

  };

  var getName = function(user, callback) {

  };

  window.API = {
    getConnections: getConnections,
    postTransaction: postTransaction,
    createUser: createUser,
    getName: getName
  };

  return true;
};<commit_msg>Removed duplicate postTransaction function and set up getConnections function<commit_after>var auth = function(uid) {
  var firebaseSite = 'https://incandescent-heat-8083.firebaseio.com/people/';
  var firebaseSiteUser = firebaseSite + uid;
  var userData = new Firebase(firebaseSiteUser);

  var dataObj = {};

  userData.on('value', function(snapshot) {
    dataObj = snapshot.val();
    var data = snapshot.val();
    $.trigger('display', data);
  });

  var getConnections = function(callback) {
    return dataObj.connections;
  };

  var postTransaction = function(obj, user, callback) {
    if(arguments.length < 3){
      var callback = user;
      dataObj["transactions"].push(obj);
      userData.set(dataObj);
      return true;
    }else{
      obj["to"] = uid;
      var otherUser = new Firebase(firebaseSite + user + "/transactions");
      var pushTransaction = otherUser.push();
      pushTransaction.set(obj);
      return true;
    }
    callback();
  };

  var getName = function(user, callback) {

  };

  var createUser = function() {

  };

  var getName = function(user, callback) {

  };

  window.API = {
    getConnections: getConnections,
    postTransaction: postTransaction,
    createUser: createUser,
    getName: getName
  };

  return true;
};<|endoftext|>


<commit_before>/********
 * Numero
 * original: Number
 ********/

module.exports = {
  // propiedades
  AntiNumero: 'NaN',
  ENTERO_SEGURO_MAXIMO: 'MAX_SAFE_INTEGER',
  ENTERO_SEGURO_MINIMO: 'MIN_SAFE_INTEGER',
  EPSILON: 'EPSILON',
  INFINITO_NEGATIVO: 'NEGATIVE_INFINITY',
  INFINITO_POSITIVO: 'POSITIVE_INFINITY',
  VALOR_MAXIMO: 'MAX_VALUE',
  VALOR_MINIMO: 'MIN_VALUE',

  // metodos
  aExponencial: 'toExponential',
  aFraccionario: 'toFixed',
  conPrecision: 'toPrecision',
  deTextoAEntero: 'parseInt',
  deTextoAFraccionario: 'parseFloat',
  esAntiNumero: 'isNaN',
  esEntero: 'isInteger',
  esEnteroSeguro: 'isSafeInteger',
  esFinite: 'isFinite',
};
<commit_msg>Hay un typo en la última definición<commit_after>/********
 * Numero
 * original: Number
 ********/

module.exports = {
  // propiedades
  AntiNumero: 'NaN',
  ENTERO_SEGURO_MAXIMO: 'MAX_SAFE_INTEGER',
  ENTERO_SEGURO_MINIMO: 'MIN_SAFE_INTEGER',
  EPSILON: 'EPSILON',
  INFINITO_NEGATIVO: 'NEGATIVE_INFINITY',
  INFINITO_POSITIVO: 'POSITIVE_INFINITY',
  VALOR_MAXIMO: 'MAX_VALUE',
  VALOR_MINIMO: 'MIN_VALUE',

  // metodos
  aExponencial: 'toExponential',
  aFraccionario: 'toFixed',
  conPrecision: 'toPrecision',
  deTextoAEntero: 'parseInt',
  deTextoAFraccionario: 'parseFloat',
  esAntiNumero: 'isNaN',
  esEntero: 'isInteger',
  esEnteroSeguro: 'isSafeInteger',
  esFinito: 'isFinite',
};
<|endoftext|>


<commit_before>'use strict';

var $ = require('jquery'),
TimePickerComponent = require('./TimePickerComponent');

require('pikaday'),
require('pikaday/plugins/pikaday.jquery');
require('spectrum-colorpicker');
require('select2')();

function PulsarFormComponent(html) {
    this.$html = html;
    this.timePickerComponent = new TimePickerComponent();
}

PulsarFormComponent.prototype.init = function () {
    var component = this;

    // Colour picker
    component.initColourpickers();

    // Date picker
    component.initDatePickers();

    // Choice block
    component.initSelectionButtons();

    // Select2
    component.initSelect2(component.$html.find('.js-select2:not([data-init="false"])'));

    // Time picker
    component.initTimePickers();

    // reinitialise select2 items in a tab when the tab is focused to fix widths
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        var $target = $($(e.target).attr('href')),
            $select2 = $target.find('.js-select2:not([data-init="false"])');

        $.each($select2, function() {
            component.initSelect2($(this));
        });
    });

    // reinitialise select2 items when opening a modal to fix widths
    $('[data-toggle="modal"]').on('click', function (e) {
        var $target = $($(e.target).attr('href')),
            $select2 = $target.find('.js-select2:not([data-init="false"])');

        $target.on('shown.bs.modal', function() {
            $.each($select2, function() {
                component.initSelect2($(this));
            });
        });
    });
}

/**
 * Re-initialise the Form Component Services
 * I've intentionally left out Select2 here, as programmatic
 * control often requires more custom behaviour than simply re-init'ing
 */
PulsarFormComponent.prototype.refresh = function () {
    // Colour picker
    this.initColourpickers();

    // Date picker
    this.initDatePickers();

    // Choice block
    this.initSelectionButtons();

    // Time picker
    this.initTimePickers();
}

/**
 * Initiate a time picker on data-timepicker fields
 */
PulsarFormComponent.prototype.initTimePickers = function () {
    this.timePickerComponent.init(this.$html.find('[data-timepicker=true]'));
}

/**
 * Initiate a date picker on data-datepicker fields using pickaday
 */
PulsarFormComponent.prototype.initDatePickers = function () {
    const datepickers = this.$html.find('[data-datepicker="true"]');
    let defaultDateFormat = 'DD/MM/YYYY';

    datepickers.each((index, element) => {
        let dateFormat = element.getAttribute('data-format');

        // Check if data-format attribute exists and lowercase it
        // to eliminate different styles of writing issues
        if (dateFormat !== null) {
            dateFormat = dateFormat.toLowerCase();
        }

        switch (dateFormat) {
            case 'us':
                defaultDateFormat = 'MM/DD/YYYY';
                break;
            case 'reverse':
                defaultDateFormat = 'YYYY/MM/DD';
                break;
            default:
                defaultDateFormat = 'DD/MM/YYYY';
        }

        // Initialize pikaday with the correct date format
        $(element).pikaday({
            format: defaultDateFormat
        });

        // Initialize placeholder attribute based on the date format
        $(element).attr('placeholder', defaultDateFormat.toLowerCase());

        // Switch off autocomplete to avoid it overlapping the date picker
        $(element).attr('autocomplete', 'off');
    });
}

/**
 * Initiate colour pickers
 */
PulsarFormComponent.prototype.initColourpickers = function () {
    var component = this,
        pickers = component.$html.find('.js-colorpicker');

    pickers.each(function() {

        var $this = $(this),
            $input = $this.find('.form__control'),
            $pickerInput = $('<input type="hidden" data-colour-picker-input>'),
            disabledAttr = $input.attr('disabled'),
            isDisabled = false,
            existingPicker = $input.next('[data-colour-picker-input]');

        if (typeof disabledAttr !== typeof undefined && disabledAttr !== false) {
            isDisabled = true;
        }

        if (existingPicker.length) {
            // Remove existing colour picker elements,
            // frustratingly invoking the spectrum 'destroy'
            // method does not remove the sp-replacer
            $pickerInput.spectrum('destroy');
            existingPicker.remove();
            $input.siblings('.sp-replacer').remove();
        }

        $pickerInput.insertAfter($input);

        // changing the picker should update the input
        $pickerInput.spectrum({
            color: '#' + $input.val(),
            disabled: isDisabled,
            showInput: false,
            preferredFormat: 'hex',
            replacerClassName: 'btn',
            change: function (color) {
                if (!$input.attr('disabled')) {
                    $input.val(('' + color).substring(1));
                    $input.trigger('change');
                }
            }
        });

        // changing the input should update the picker
        $input.on('change', function () {
            $pickerInput.spectrum('set', '#' + $input.val());
        });
    });
}

/**
 * Update colour pickers within a scope
 * @param $root
 */
PulsarFormComponent.prototype.updateColourPicker = function ($root) {
    const $input = $root.find('.js-colorpicker .form__control');

    $input.each((index, element) => {
        const $input = $(element);
        const $picker = $input.next();

        $picker.spectrum('set', `#${$input.val()}`);
    });
}

/**
 * Initiate Selection Buttons
 */
PulsarFormComponent.prototype.initSelectionButtons = function () {
    const choiceblock = this.$html.find('.choice--block');

    choiceblock
        .find('input[type="checkbox"]:checked, input[type="radio"]:checked')
        .closest('.control__label')
        .addClass('is-selected');

    choiceblock
        .on('change', '.controls input[type="checkbox"], .controls input[type="radio"]', this.selectionButtons);
}

/**
 * Selection Button className logic
 */
PulsarFormComponent.prototype.selectionButtons = function () {
    var $target = $(this),
        $controls = $target.closest('.controls');

    $controls.find('input[type="checkbox"]:not(:checked), input[type="radio"]:not(:checked)')
        .closest('.control__label')
        .removeClass('is-selected');

    if ($target.is(':checked')) {
        $target.closest('.control__label').addClass('is-selected');
    } else {
        $target.closest('.control__label').removeClass('is-selected');
    }
}

/**
 * Initiate Select2
 * @param target
 */
PulsarFormComponent.prototype.initSelect2 = function (target) {
    var $target = target;

    $target.each(function() {
        var $this = $(this),
            config = {};

        function formatOption(data) {
            return $('' + data.text + '');
        }

        if ($this.data('html')) {
            config.templateResult = formatOption;
            config.templateSelection = formatOption;
        }

        $this.select2(config);
        $this.parent().find('.select2-container').removeAttr('style');
    });
}

module.exports = PulsarFormComponent;
<commit_msg>Tabbing fix<commit_after>'use strict';

var $ = require('jquery'),
    TimePickerComponent = require('./TimePickerComponent');

require('pikaday'),
require('pikaday/plugins/pikaday.jquery');
require('spectrum-colorpicker');
require('select2')();

function PulsarFormComponent(html) {
    this.$html = html;
    this.timePickerComponent = new TimePickerComponent();
}

PulsarFormComponent.prototype.init = function () {
    var component = this;

    // Colour picker
    component.initColourpickers();

    // Date picker
    component.initDatePickers();

    // Choice block
    component.initSelectionButtons();

    // Select2
    component.initSelect2(component.$html.find('.js-select2:not([data-init="false"])'));

    // Time picker
    component.initTimePickers();

    // reinitialise select2 items in a tab when the tab is focused to fix widths
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        var $target = $($(e.target).attr('href')),
            $select2 = $target.find('.js-select2:not([data-init="false"])');

        $.each($select2, function() {
            component.initSelect2($(this));
        });
    });

    // reinitialise select2 items when opening a modal to fix widths
    $('[data-toggle="modal"]').on('click', function (e) {
        var $target = $($(e.target).attr('href')),
            $select2 = $target.find('.js-select2:not([data-init="false"])');

        $target.on('shown.bs.modal', function() {
            $.each($select2, function() {
                component.initSelect2($(this));
            });
        });
    });
}

/**
 * Re-initialise the Form Component Services
 * I've intentionally left out Select2 here, as programmatic
 * control often requires more custom behaviour than simply re-init'ing
 */
PulsarFormComponent.prototype.refresh = function () {
    // Colour picker
    this.initColourpickers();

    // Date picker
    this.initDatePickers();

    // Choice block
    this.initSelectionButtons();

    // Time picker
    this.initTimePickers();
}

/**
 * Initiate a time picker on data-timepicker fields
 */
PulsarFormComponent.prototype.initTimePickers = function () {
    this.timePickerComponent.init(this.$html.find('[data-timepicker=true]'));
}

/**
 * Initiate a date picker on data-datepicker fields using pickaday
 */
PulsarFormComponent.prototype.initDatePickers = function () {
    const datepickers = this.$html.find('[data-datepicker="true"]');
    let defaultDateFormat = 'DD/MM/YYYY';

    datepickers.each((index, element) => {
        let dateFormat = element.getAttribute('data-format');

        // Check if data-format attribute exists and lowercase it
        // to eliminate different styles of writing issues
        if (dateFormat !== null) {
            dateFormat = dateFormat.toLowerCase();
        }

        switch (dateFormat) {
            case 'us':
                defaultDateFormat = 'MM/DD/YYYY';
                break;
            case 'reverse':
                defaultDateFormat = 'YYYY/MM/DD';
                break;
            default:
                defaultDateFormat = 'DD/MM/YYYY';
        }

        // Initialize pikaday with the correct date format
        $(element).pikaday({
            format: defaultDateFormat
        });

        // Initialize placeholder attribute based on the date format
        $(element).attr('placeholder', defaultDateFormat.toLowerCase());

        // Switch off autocomplete to avoid it overlapping the date picker
        $(element).attr('autocomplete', 'off');
    });
}

/**
 * Initiate colour pickers
 */
PulsarFormComponent.prototype.initColourpickers = function () {
    var component = this,
        pickers = component.$html.find('.js-colorpicker');

    pickers.each(function() {

        var $this = $(this),
            $input = $this.find('.form__control'),
            $pickerInput = $('<input type="hidden" data-colour-picker-input>'),
            disabledAttr = $input.attr('disabled'),
            isDisabled = false,
            existingPicker = $input.next('[data-colour-picker-input]');

        if (typeof disabledAttr !== typeof undefined && disabledAttr !== false) {
            isDisabled = true;
        }

        if (existingPicker.length) {
            // Remove existing colour picker elements,
            // frustratingly invoking the spectrum 'destroy'
            // method does not remove the sp-replacer
            $pickerInput.spectrum('destroy');
            existingPicker.remove();
            $input.siblings('.sp-replacer').remove();
        }

        $pickerInput.insertAfter($input);

        // changing the picker should update the input
        $pickerInput.spectrum({
            color: '#' + $input.val(),
            disabled: isDisabled,
            showInput: false,
            preferredFormat: 'hex',
            replacerClassName: 'btn',
            change: function (color) {
                if (!$input.attr('disabled')) {
                    $input.val(('' + color).substring(1));
                    $input.trigger('change');
                }
            }
        });

        // changing the input should update the picker
        $input.on('change', function () {
            $pickerInput.spectrum('set', '#' + $input.val());
        });
    });
}

/**
 * Update colour pickers within a scope
 * @param $root
 */
PulsarFormComponent.prototype.updateColourPicker = function ($root) {
    const $input = $root.find('.js-colorpicker .form__control');

    $input.each((index, element) => {
        const $input = $(element);
        const $picker = $input.next();

        $picker.spectrum('set', `#${$input.val()}`);
    });
}

/**
 * Initiate Selection Buttons
 */
PulsarFormComponent.prototype.initSelectionButtons = function () {
    const choiceblock = this.$html.find('.choice--block');

    choiceblock
        .find('input[type="checkbox"]:checked, input[type="radio"]:checked')
        .closest('.control__label')
        .addClass('is-selected');

    choiceblock
        .on('change', '.controls input[type="checkbox"], .controls input[type="radio"]', this.selectionButtons);
}

/**
 * Selection Button className logic
 */
PulsarFormComponent.prototype.selectionButtons = function () {
    var $target = $(this),
        $controls = $target.closest('.controls');

    $controls.find('input[type="checkbox"]:not(:checked), input[type="radio"]:not(:checked)')
        .closest('.control__label')
        .removeClass('is-selected');

    if ($target.is(':checked')) {
        $target.closest('.control__label').addClass('is-selected');
    } else {
        $target.closest('.control__label').removeClass('is-selected');
    }
}

/**
 * Initiate Select2
 * @param target
 */
PulsarFormComponent.prototype.initSelect2 = function (target) {
    var $target = target;

    $target.each(function() {
        var $this = $(this),
            config = {};

        function formatOption(data) {
            return $('' + data.text + '');
        }

        if ($this.data('html')) {
            config.templateResult = formatOption;
            config.templateSelection = formatOption;
        }

        $this.select2(config);
        $this.parent().find('.select2-container').removeAttr('style');
    });
}

module.exports = PulsarFormComponent;
<|endoftext|>


<commit_before>"use strict";

var speedy = require ("../lib");

speedy.run ({
	Number: function (){
		Number ("1.1");
	},
	"+": function (){
		+"1.1";
	},
	parseFloat: function (){
		//It's not the same as Number but shares some similarities
		parseFloat ("1.1");
	},
	json: function (){
		JSON.parse ("1.1");
	}
});

/*
File: parse-number.js

Node v0.10.20
V8 v3.14.5.9
Speedy v0.1.0

Tests: 4
Timeout: 1000ms (1s 0ms)
Samples: 3
Total time per test: ~3000ms (3s 0ms)
Total time: ~12000ms (12s 0ms)

Higher is better (ops/sec)

Number
  13,078,063 ± 0.1%
+
  10,982,975 ± 0.0%
parseFloat
  16,901,142 ± 0.0%
json
  10,823,115 ± 0.0%

Elapsed time: 12293ms (12s 293ms)
*/<commit_msg>updated parse-number<commit_after>"use strict";

var speedy = require ("../lib");

speedy.run ({
	Number: function (){
		Number ("1.1");
	},
	"+": function (){
		+"1.1";
	},
	"~~": function (){
		//It's the same as "+" but it also crops the decimal part, so if you need
		//to sanitize a number, instead of doing "parseInt + decimal removal", it's
		//faster using the tildes "~~"
		~~"1.1";
	},
	parseFloat: function (){
		//It's not the same as Number but shares some similarities
		parseFloat ("1.1");
	},
	json: function (){
		JSON.parse ("1.1");
	}
});

/*
File: parse-number.js

Node v0.10.21
V8 v3.14.5.9
Speedy v0.1.1

Tests: 5
Timeout: 1000ms (1s 0ms)
Samples: 3
Total time per test: ~3000ms (3s 0ms)
Total time: ~15000ms (15s 0ms)

Higher is better (ops/sec)

Number
  13,014,401 ± 0.1%
+
  11,078,243 ± 0.0%
~~
  11,337,886 ± 0.0%
parseFloat
  16,981,702 ± 0.0%
json
  10,712,992 ± 0.2%

Elapsed time: 15366ms (15s 366ms)
*/<|endoftext|>