Executable.prototype.invoke = function() { var args = Array.prototype.slice.call(arguments); var next = args.pop(); var opts = {}; var params = []; if (!_.isFunction(next)) { throw "Function or Script Execution expects a next function as the last argument"; } if (!_.isArray(_.last(args)) && _.isObject(_.last(args))) { opts = args.pop(); } if (_.isArray(args[0])) { // backwards compatible -- db.function([...], ?opts, callback) params = args[0]; } else { params = args; } // console.log("invoke next: ", next); // console.log("invoke opts: ", opts); // console.log("invoke params: ", params); if (opts.stream) { this.db.stream(this.sql, params, null, next); } else { this.db.query(this.sql, params, null, next); } };
Info.pack = function(info, mapping){ var data = _.clone(info); var reply = data.reply; //log('packing reply: ', reply); // 具备图文消息的特征 if (_.isObject(reply) && !_.isArray(reply) && !reply.type) { reply = data.reply = [reply]; } if (_.isArray(reply)) { if (_.isFunction(mapping)) { reply = reply.map(function(item, i) { return mapping.call(reply, item, i, info); }); } else if (mapping) { reply.forEach(function(item, index){ item['title'] = item[ mapping['title'] || 'title']; item['description'] = item[ mapping['description'] || 'description']; item['pic'] = item[ mapping['picUrl'] || 'picUrl'] || item[ mapping['pic'] || 'pic']; item['url'] = item[ mapping['url'] || 'url']; }); } } data.reply = reply; var xml = _.template(Info.TEMPLATE_REPLY)(data); return xml; };
exports.fetch = function (o, p, owner) { var i , keys = [] , value; // convert p or list of p to Array for iteration if (_.isArray(p)) { keys = p; } else { for (i=1; i<arguments.length;i+=1) { keys.push(arguments[i]); } } if (o) { if (_.isArray(o)) { return find(o, p); } for (i=0; i<keys.length; i += 1) { value = exports.pfetch(o, keys[i]); if (typeof value !== 'undefined' && owner === true) { return value; } if (typeof value !== 'undefined') { return ((value && _.isObject(value) && value['#text']) || value) ; } } } };
Executable.prototype.invoke = function(params, opts, next) { if (_.isFunction(params)) { // invoked as db.function(callback) next = params; params = []; opts = {}; } else if (_.isFunction(opts)) { // invoked as db.function(something, callback) next = opts; // figure out if we were given params or opts as the first argument // lucky for us it's mutually exclusive: opts can only be an object, params can be a primitive or an array if (_.isObject(params) && !_.isArray(params)) { // it's an options object, we have no params opts = params; params = []; } else { // it's a parameter primitive or array, we have no opts opts = {}; } } if (!_.isArray(params)) { params = [params]; } if (opts.stream) { this.db.stream(this.sql, params, null, next); } else { this.db.query(this.sql, params, null, next); } };
exports.predicate = function (result, condition, value) { if (value === null) { //interpolate nulls directly with is/is not condition.operator = condition.operator === '=' ? 'IS' : 'IS NOT'; } else if (condition.mutator || !_.isArray(value)) { //parameterize any non-array or mutatey values if (condition.mutator) { value = condition.mutator(value); } result.params.push(value); value = util.format("$%s", result.params.length + result.offset); } else if (_.isArray(value)) { var arrayConditions = []; //loop the array _.each(value, function(v) { result.params.push(v); arrayConditions.push(util.format("$%s", result.params.length + result.offset)); }); condition.operator = condition.operator === '=' ? 'IN' : 'NOT IN'; value = util.format('(%s)', arrayConditions.join(', ')); } result.predicates.push(util.format('%s %s %s', condition.quotedField, condition.operator, value)); return result; };
exports.sexp = function(obj) { if (_.isNull(obj) || _.isUndefined(obj)) { return 'nil'; } else if (obj.toSexp) { return obj.toSexp(); } else if (obj.lispType) { switch (obj.lispType) { case 'string': return exports.string(obj); case 'symbol': return exports.symbol(obj); case 'keyword': return exports.keyword(obj); case 'list': return exports.list(obj); case 'vector': return exports.vector(obj); } throw new Error("Unrecognized lispType: " + util.inspect(obj.lispType)); } else if (_.isString(obj)) { return exports.string(obj); } else if (_.isArray(obj)) { return exports.list(obj); } else if (_.isBoolean(obj)) { return exports.bool(obj); } else if (_.isNumber(obj)) { return exports.number(obj); } else { return exports.alist(obj); } };
exports.searchDoc = function(){ var args = ArgTypes.searchArgs(arguments, this); assert(args.fields.keys && args.fields.term, "Need the keys to use and the term string"); var params = [args.fields.term]; //yuck full repetition here... fix me... if(!_.isArray(args.fields.keys)){ args.fields.keys = [args.fields.keys]; } var tsv; if(args.fields.keys.length === 1){ tsv = util.format("(body ->> '%s')", args.fields.keys[0]); }else{ var formattedKeys = []; _.each(args.fields.keys, function(key){ formattedKeys.push(util.format("(body ->> '%s')", key)); }); tsv= util.format("concat(%s)", formattedKeys.join(", ' ',")); } var whereString; if(args.fields.where){ var where = this.getWhereForDoc(args.fields.where, 1, ' AND '); whereString = where.where; params = params.concat(where.params); } var sql = "select * from " + this.fullname + " where " + util.format("to_tsvector(%s)", tsv); sql+= " @@ to_tsquery($1)" + (whereString || '') + args.options.queryOptions(); this.executeDocQuery(sql, params, args.options, args.next); };
validate: function(attrs, options) { // klass should be Artist if(!_.isString(attrs.klass) || attrs.klass != "Artist") return "klass property must be 'Artist'."; // needs to have either _id or mbid if(_.isUndefined(attrs._id) && _.isUndefined(attrs.mbid)) return "must define either _id or mbid"; // should have a string _id if(!_.isUndefined(attrs._id) && (!_.isString(attrs._id) || attrs._id == "")) return "_id property must be a non-empty string."; // can have a string mbid that follows rules of _id if(!_.isUndefined(attrs.mbid) && (!_.isString(attrs.mbid) || attrs.mbid == "")) return "mbid property must be a non-empty string."; // should have a string name if(_.isUndefined(attrs.name) || !_.isString(attrs.name)) return "must define name property that is a string."; // should have a string url if(_.isUndefined(attrs.url) || !_.isString(attrs.url)) return "must define url property that is a string."; // should have images array if(_.isUndefined(attrs.images) || !_.isArray(attrs.images)) return "must define images property that is an array."; // images should have valid objects if(!_.reduce(attrs.images, function(build, img) { return build && _.has(img, "url") && _.has(img, "size") && _.isString(img.url) && _.isString(img.size); }, true)) return "all images must have url and size properties that are strings."; },
server.post('/mails', function(request, response) { response.status = 200; response.headers['Content-Type'] = 'application/json'; // Fetch mails and make sure it's an array. var mails = JSON.parse(request.body); mails = _.isArray(mails) ? mails : [mails]; // Update each mail. var mail, obj; for (var i=0; i < mails.length; i++) { mail = mails[i]; // We're only going to ever update the 'read' field of mails. // The reset of the fields should never change. obj = { read: mail.read }; schemas.Mail.update({ _id: mail._id }, obj, function (err) { if (err) { console.error('Failed saving mail on POST /mails: ' + err); } }); } response.end(); });
classes = classes.map(function(label) { if (_.isArray(label)) label[0] = this.labelLookupTable.numberToFeature(label[0]); else label = this.labelLookupTable.numberToFeature(label); return label; }, this);
Connection.prototype.destroy = function(type, ids, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options = options || {}; var self = this; var isArray = _.isArray(ids); ids = isArray ? ids : [ ids ]; if (ids.length > self.maxRequest) { return Promise.reject(new Error("Exceeded max limit of concurrent call")).thenCall(callback); } return Promise.all( _.map(ids, function(id) { var url = [ self._baseUrl(), "sobjects", type, id ].join('/'); return self.request({ method : 'DELETE', url : url, headers: options.headers || null }, { noContentResponse: { id : id, success : true, errors : [] } }); }) ).then(function(results) { return !isArray && _.isArray(results) ? results[0] : results; }).thenCall(callback); };
function addError(error) { if (_.isArray(error)) errors.push.apply(errors, error); else if (_.isObject(error)) errors.push(error); }
find: function(id, callback) { if (_.isArray(id)) { this.find_by_ids(id, callback); } else { this.find_by_id(id, callback); } },
/** * @class Action * * 动作规则 * * 执行流程: pattern -> handler -> register reply action * * @constructor 动作规则 * @param {Mixed} cfg Action的配置 * @param {String} [prex] 动作名的前缀 */ function Action(cfg, prex){ if(_.isString(cfg)){ //为字符串时,pattern为通过匹配,handler为直接返回该值 this.name = prex + '_' + cfg; this.description = '发送任意字符,直接返回:' + cfg; this.handler = cfg; }else if(_.isFunction(cfg)){ //为函数时,pattern为通过匹配,handler为该函数 this.name = prex + '_' + cfg.name; this.description = cfg.description || '发送任意字符,直接执行函数并返回'; this.handler = cfg; }else if(_.isArray(cfg)){ throw new Error('no support cfg type: Array') }else if(_.isObject(cfg)){ /** * 匹配这种格式: * { * name: 'say_hi', * description: 'pattern可以用正则表达式匹配,试着发送「hi」', * pattern: /^Hi/i, * handler: function(info) { * //回复的另一种方式 * return '你也好哈'; * } * @ignore */ _.extend(this,cfg) this.name = cfg.name || prex || cfg.pattern } if(!this.name) this.name = 'it_is_anonymous_action'; return this; };
// input: string // output: normlized string function normalizer(str, callback) { if (_.isArray(str)) { // console.log("array") str = str[0] } str = str.trim() str = bars.biunormalizer(str) onlycontent(str, function (err,strcontent){ if (_.compact(strcontent).length == 0) strcontent = str.split(" ") strcontentlemma = lemmatize(strcontent) strcontentlemma = elimination(strcontentlemma) if (strcontentlemma.length == 0) strcontentlemma = strcontent strcontentlemma = _.compact(strcontentlemma) callback(err, strcontentlemma) }) }
function filternan(input) { if (_.isArray(input)) { var output = [] _.each(input, function(value, key, list){ if (bars.isNumber(value)) { if (value != -1) output.push(value) else output.push("?") } else output.push("?") }, this) } else { var output = '' if (bars.isNumber(input)) { if (input != -1) output = input else output = "?" } else output = "?" } return output }
_.toArray = function(iterable) { if (!iterable) return []; if (iterable.toArray) return iterable.toArray(); if (_.isArray(iterable)) return slice.call(iterable); if (_.isArguments(iterable)) return slice.call(iterable); return _.values(iterable); };
_.each(args, function(arg) { if (_.isNumber(arg) || _.isString(arg)) { var criteria = {}; criteria[self.table.pk] = args[0]; return self.where(criteria); } var columns = arg.columns || arg; if (_.isArray(columns)) { self.sql = self.sql.replace("*", columns.join(",")); } if (_.isString(columns)) { self.sql = self.sql.replace("*", columns); } delete arg.columns; var where = arg.where || arg; if (!_.isArray(where) && _.isObject(where) && _.size(where) > 0) { self.where(where); } });
apiCall(endpoint, params, function(err, response) { if(err) { loop(err); return; } // We're only interested in holding onto everything when we'll be firing a callback. if(callback) { allResponse.results = allResponse.results.concat(response.results); } // Call IDs will be appended. allResponse.callId += response.callId + ' '; // Global objects count needs to include the objects in this chunk. allResponse.objectsCount += response.objectsCount; allResponse.totalCount = response.totalCount // Loop through each result and emit if(_.isArray(response.results)) { for(var i = 0; i < response.results.length; i++) { emitter.emit('result', response.results[i]); } } // Set cursorId if available, otherwise false will end the loop cursorId = response.nextCursorId && fetchAll === true ? response.nextCursorId : false; loop(); });
QueryOptions.prototype.selectList = function () { if (_.isArray(this.select)) { return this.select.join(','); } return this.select; };
function splitPartEqually(json) { // return _.map(_.uniq(_.flatten(json.map(this.splitJson)) ), function(num){ return [num];}) var label = [] if (json == null) return null if (!(_.isArray(json))) json = [json] _(3).times(function(n){ var buf = [] _.each(json.map(Compensate), function(value, key, list){ if (value.length > n) { if (_.compact(value[n].toString()).length != 0) buf = buf.concat(value[n]) } }) // buf = _.uniq(_.compact(buf)) // buf = _.uniq(_.compact(buf)) // if (buf.length != 0) label[n] = buf buf = _.uniq(buf) if ((buf.length > 0) && (typeof(buf[0])!="undefined")) label[n] = buf if ((typeof(buf[0])=="undefined")) label[n] = [] }) return label }
'setconfig': function(event) { var configPathString = event.params[1], configKey = _.last(configPathString.split('.')), newOption = event.params[2]; if(!_.include(noChangeConfig, configKey)) { var configPath = getCurrentConfig(configPathString); if(configPath == false || _.isUndefined(configPath.value)) { event.reply(dbot.t("no_config_key")); return; } var currentOption = configPath.value; // Convert to boolean type if config item boolean if(_.isBoolean(currentOption)) { newOption = (newOption == "true"); } if(_.isArray(currentOption)) { event.reply(dbot.t("config_array",{"alternate": "pushconfig"})); } event.reply(configPathString + ": " + currentOption + " -> " + newOption); configPath['user'][configKey] = newOption; dbot.reloadModules(); } else { event.reply(dbot.t("config_lock")); } },
DB.prototype.bulkSave = function (docs, /*optional*/ options, callback) { if (!_.isArray(docs)) { throw new Error( 'bulkSave requires an array of documents to work properly' ); } if (!callback) { callback = options; options = {}; } options.docs = docs; try { var data = JSON.stringify(options); } catch (e) { return callback(e); } var req = { type: 'POST', url: this.url + '/_bulk_docs', data: data, processData: false, contentType: 'application/json', expect_json: true }; exports.request(req, callback); };
Query.prototype.selectList = function () { if (_.isArray(this.columns)) { return this.columns.join(','); } return this.columns; };
_.each(conditions, function(value, key) { var condition = exports.parseKey(key); if (condition.field === 'or') { if (!_.isArray(value)) { value = [value]; } var groupResult = _.reduce(value, function (acc, v) { // assemble predicates for each subgroup in this 'or' array var subResult = exports.generate({ params: [], predicates: [], offset: result.params.length + acc.offset // ensure the offset from predicates outside the subgroup is counted }, v, generator); // encapsulate and join the individual predicates with AND to create the complete subgroup predicate acc.predicates.push(util.format('(%s)', subResult.predicates.join(' AND '))); acc.params = acc.params.concat(subResult.params); acc.offset += subResult.params.length; return acc; }, { params: [], predicates: [], offset: result.offset }); // join the compiled subgroup predicates with OR, encapsulate, and push the // complex predicate ("((x = $1 AND y = $2) OR (z = $3))") onto the result object result.params = result.params.concat(groupResult.params); result.predicates.push(util.format('(%s)', groupResult.predicates.join(' OR '))); } else { // no special behavior, just add this predicate and modify result in-place result = exports[generator](result, condition, value, conditions); } });
Query.prototype.queryOptions = function () { if (_.isArray(this.order)) { var orderBody = this.orderBody; this.order = _.reduce(this.order, function (acc, val) { val.direction = val.direction || "asc"; if (orderBody) { val.field = util.format("body->>'%s'", val.field); } if (val.type) { acc.push(util.format("(%s)::%s %s", val.field, val.type, val.direction)); } else { acc.push(util.format("%s %s", val.field, val.direction)); } return acc; }, []).join(","); } var sql = ""; if (this.order) { sql = " order by " + this.order; } if (this.offset) { sql += " offset " + this.offset; } if (this.limit || this.single) { sql += " limit " + (this.limit || "1"); } return sql; };
getValidOrderForPos: function(unit, pos) { 'use strict'; var stuff = this.map.at(pos.x, pos.y), enemies, order; if (_.isArray(stuff)) { enemies = _.filter(stuff, function(u) { return u instanceof Unit && u.isEnemy(unit); }); if (enemies.length > 0) { order = new orders.SeekAndDestroy({ unitID: unit.id, targetID: enemies[0].id }); } } else { if (stuff instanceof items.Console) { order = new orders.MoveToConsole({ unitID: unit.id, destination: {x: pos.x, y: pos.y} }); } else if (this.isWalkable(pos.x, pos.y)) { order = new orders.Move({ unitID: unit.id, destination: {x: pos.x, y: pos.y} }); } } if (order && order.isValid(this, unit.ownerID)) { return order; } return null; }
'setconfig': function(event) { var configPathString = event.params[1], configKey = _.last(configPathString.split('.')), newOption = event.params[2]; if(!_.include(noChangeConfig, configKey)) { var configPath = getCurrentConfig(configPathString); if(configPath == false || _.isUndefined(configPath.value)) { event.reply("Config key doesn't exist bro"); return; } var currentOption = configPath.value; // Convert to boolean type if config item boolean if(_.isBoolean(currentOption)) { newOption = (newOption == "true"); } if(_.isArray(currentOption)) { event.reply("Config option is an array. Try 'pushconfig'."); } event.reply(configPathString + ": " + currentOption + " -> " + newOption); configPath['user'][configKey] = newOption; dbot.reloadModules(); } else { event.reply("This config option cannot be altered while the bot is running."); } },
}).then(function(res) { var results; if (job.operation === 'query') { var conn = bulk._conn; var resultIds = res['result-list'].result; results = res['result-list'].result; results = _.map(_.isArray(results) ? results : [ results ], function(id) { return { id: id, batchId: batchId, jobId: jobId }; }); } else { results = _.map(res, function(ret) { return { id: ret.Id || null, success: ret.Success === "true", errors: ret.Error ? [ ret.Error ] : [] }; }); } self.emit('response', results); return results; }, function(err) {
var getItemsWait = exports.getItemsWait = function(keys, cb) { if (typeof cb !== "undefined" && typeof cb !== "function") { throw new Error("The 2nd argument (if supplied) is expected to be a callback function"); } if (!_.isArray(keys)) { cb && cb("'keys' is expected to be an array of string values"); } else { var items = {}; var sem = keys.length; _.each(keys, function(key) { getItem(key, function(err, item) { if (err) (cb && cb(err)); else { if (item === null) { getItemWait(key, function(err, item) { if (err) (cb && cb(err)); else { items[key] = item; sem--; if (sem === 0) { cb(null, items); } } }); } else { items[key] = item; sem--; if (sem === 0) { cb(null, items); } } } }); }); } };