Example #1
0
File: db.js Project: iilab/kanso
 function (ids, callback) {
     var fetch = _.map(ids, function (x) {
         return x.id;
     });
     appdb.bulkGet(fetch, { include_docs: true }, function (err, rv) {
         test.equal(err, undefined, 'bulkGet has no error');
         test.notEqual(rv, undefined, 'bulkGet returns a value');
         test.equal(rv.rows.length, ids.length, 'bulkGet yields an array');
         test.equal(
             _.inject(rv.rows, function (a, x) {
                 a += x.doc.offset;
                 return a;
             }, 0),
             ((max - 1) * max) / 2,
             "sum of bulkGet's return value is correct"
         );
         callback();
     });
 },
Example #2
0
Connection.prototype.upsert = function(type, records, extIdField, callback) {
  // You can omit "type" argument, when the record includes type information.
  if (arguments.length === 3) {
    type = null;
    records = type;
    extIdField = records;
    callback = extIdField;
  }
  var self = this;
  var isArray = _.isArray(records);
  records = isArray ? records : [ records ];
  if (records.length > self.maxRequest) {
    return Promise.reject(new Error("Exceeded max limit of concurrent call")).thenCall(callback);
  }
  return Promise.all(
    _.map(records, function(record) {
      var sobjectType = type || (record.attributes && record.attributes.type) || record.type;
      var extId = record[extIdField];
      if (!extId) {
        return Promise.reject(new Error('External ID is not defined in the record'));
      }
      record = _.clone(record);
      delete record[extIdField];
      delete record.type;
      delete record.attributes;

      var url = [ self._baseUrl(), "sobjects", sobjectType, extIdField, extId ].join('/');
      return self._request({
        method : 'PATCH',
        url : url,
        body : JSON.stringify(record),
        headers : {
          "Content-Type" : "application/json"
        }
      }, null, {
        noContentResponse: { success : true, errors : [] }
      });
    })
  ).then(function(results) {
    return !isArray && _.isArray(results) ? results[0] : results;
  }).thenCall(callback);
};
Example #3
0
var parse = exports.parse = function(def, doc) {
    var parts = doc.message.split('#'),
        header = parts[0].split('!'),
        name = header[1],
        vals = parts.slice(1);

    var n = 3;
    while (n < header.length) {
        header[2] += '!' + header[n++];
    }

    vals.unshift(header[2]);

    if(!def || !def.fields) {
        return {};
    }

    // put field and values into paired array
    var pairs = zip(
        // include key value in paired array
        _.map(def.fields, function(val, key) {
            var field = def.fields[key];
            field._key = key;
            return field;
        }),
        vals
    );

    return pairs.reduce(function (obj, v) {
        var field = v[0],
            val = v[1];

        if (!field) {
            // ignore extra form data that has no matching field definition.
            obj._extra_fields = true;
        } else {
            obj[field._key] = typeof val === 'string' ? val.trim() : val;
        }

        return obj;
    }, {});
};
Example #4
0
exports.choice = function (options) {
    if (!options || !options.values) {
        throw new Error('No values defined');
    }
    options = prependValidator(options, function (doc, value) {
        for (var i = 0; i < options.values.length; i++) {
            if (value === options.values[i][0]) {
                return;
            }
        }
        throw new Error('Invalid choice');
    });
    // use value as label if no label defined
    options.values = _.map(options.values, function (v) {
        return _.isArray(v) ? v: [v, v];
    });
    return new Field(_.defaults(options, {
        widget: widgets.select({values: options.values})
    }));
};
Example #5
0
 describeCache(table).then(function(sobject) {
   logger.debug('table '+table+'has been described');
   if (fpath.length > 1) {
     var rname = fpath.shift();
     var rfield = _.find(sobject.fields, function(f) {
       return f.relationshipName &&
              f.relationshipName.toUpperCase() === rname.toUpperCase();
     });
     if (rfield) {
       var rtable = rfield.referenceTo.length === 1 ? rfield.referenceTo[0] : 'Name';
       return expandAsteriskField(rtable, fpath.join('.')).then(function(fpaths) {
         return _.map(fpaths, function(fpath) { return rname + '.' + fpath; });
       });
     } else {
       return [];
     }
   } else {
     return _.map(sobject.fields, function(f) { return f.name; });
   }
 }) :
Example #6
0
      socket.get('chatId',function(err,chat){
        if(chat){
          if(io.sockets.manager.rooms['/' + chat]){
            var clients = io.sockets.clients(chat);
            var clients_info = _.map(clients,function(client){
              return {
                'name':client.handshake.user.user.name,
                'profile_pic_url':client.handshake.user.user.profile_pic_url,
                'socket_id':client.id
              };
            });
            console.log(clients_info);
            socket.emit('peoplesInRoom', clients_info);
          }
          console.log(io.sockets.manager.rooms['/'+chat].length);
        }else{
          console.log('cant count peoples in chat '+chat);
        }

      });
Example #7
0
Connection.prototype.retrieve = function(type, ids, callback) {
  var self = this;
  var isArray = _.isArray(ids);
  ids = isArray ? ids : [ ids ];
  if (ids.length > self.maxRequest) {
    callback({ message : "Exceeded max limit of concurrent call" });
    return;
  }
  async.parallel(_.map(ids, function(id) {
    return function(cb) {
      var url = [ self.urls.rest.base, "sobjects", type, id ].join('/');
      self._request({
        method : 'GET',
        url : url
      }, cb);
    };
  }), function(err, results) {
    callback(err, !isArray && _.isArray(results) ? results[0] : results);
  });
};
Example #8
0
Connection.prototype.retrieve = function(type, ids, options, callback) {
  if (typeof options === 'function') {
    callback = 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(url);
    })
  ).then(function(results) {
    return !isArray && _.isArray(results) ? results[0] : results;
  }).thenCall(callback);
};
Example #9
0
 socket.get('chatId',function(err,chat){
   if(chat){
     if(global.sockets.manager.rooms['/' + chat]){
       var clients = global.sockets.clients(chat);
       var clients_info = _.map(clients,function(client){
         return {
           'name':client.handshake.user.user.name,
           'profile_pic_url':client.handshake.user.user.profile_pic_url,
           'id':client.id
         };
       });
       callback(null,clients_info); 
     }
   }else{
     console.log('cant count peoples in chat '+chat);
   }
   var usr = socket.handshake.user.user;
   usr.id = socket.id;
 socket.broadcast.to(chat).emit('chatParticipants:create', usr);
 });
Example #10
0
lists.intersection = function (head, req) {

    var extraKeys = [];
    if (req.query.key) {
        extraKeys.push(req.query.key);
    }
    if (req.query.extra_keys) {
        var split = req.query.extra_keys.split(' ');
        extraKeys = extraKeys.concat(split);
    }

    extraKeys = _.uniq(_.map(extraKeys, function(key) {return key.toLowerCase()}));

    var realJson = true;
    if (req.query.streamJson) {
        realJson = false;
    }

    start({'headers' : {'Content-Type' : 'application/json'}});
    if (realJson) send('[\n');
    var count = 0;
    var row;
    while ((row = getRow())) {

        var doc_intersection = _.intersection(row.doc.tag, extraKeys);
        if (doc_intersection.length == extraKeys.length) {
            var res = {
                 id : row.id,
                 name : row.doc.name,
                 size : row.doc.size,
                 s : row.doc.s,
                 l : row.doc.l,
                 m : row.doc.m
            }
            var pre = '';
            if (count++ > 0 && realJson) pre = ',';
            send(pre + JSON.stringify(res) + '\n');
        }
    }
    if (realJson) send(']');
}
Example #11
0
Connection.prototype.destroy = function(type, ids, callback) {
  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
      }, null, {
        noContentResponse: { id : id, success : true, errors : [] }
      });
    })
  ).then(function(results) {
    return !isArray && _.isArray(results) ? results[0] : results;
  }).thenCall(callback);
};
Example #12
0
 }, function(error, response, body) {
     if(!error && response.statusCode == 200) {
         if(_.has(body, 'track')) {
             callback(dbot.t('track', {
                 'artist': _.map(body.track.artists, 
                     function(a) { return a.name }).join(', '), 
                 'album': body.track.album.name, 
                 'track': body.track.name
             }));
         } else if(_.has(body, 'album')) {
             callback(dbot.t('album', {
                 'artist': body.album.artist, 
                 'album': body.album.name
             }));
         } else if(_.has(body, 'artist')) {
             callback(dbot.t('artist', {
                 'artist': body.artist.name
             }));
         }
     }
 });
Example #13
0
  createTableQuery: function (tableName, attributes, options) {
    options = options || {}

    var query   = "CREATE TABLE IF NOT EXISTS <%= table %> (<%= attributes%>);"
      , primaryKeys = []
      , attrStr = _.map(attributes, function (dataType, attr) {
          var dt = dataType
          if (dt.indexOf('PRIMARY KEY') !== -1) {
            primaryKeys.push(attr)
            return helper.addTicks(attr) + " " + dt.replace(/PRIMARY KEY/, '')
          } else {
            return helper.addTicks(attr) + " " + dt
          }
        }).join(",")
      , values  = {table: helper.addTicks(tableName), attributes: attrStr}
      , pkString = primaryKeys.map(function (pk) {return helper.addTicks(pk)}).join(",")

    if (pkString.length > 0) values.attributes += ", PRIMARY KEY (" + pkString + ")"

    return  _.template(query)(values)
  },
Example #14
0
 }), function (error2) {
     if (error2) {
         next(error2);
     } else {
         var indexs = arguments[1];
         Group.create({
             title: thing.title,
             tags: thing.tags,
             indexs: _.map(indexs, function(dataitem, index) {
                 return dataitem._id;
             }),
             creator: USER_SYSTEM
         }, function(error3) {
             if (error3) {
                 next(error3);
             } else {
                 next(null);
             }
         });
     }
 });
Example #15
0
		fs.readdir("./server/views/client", function(err, files){
			//console.log("Matched " + files.length + " jade files")
			var fullFiles = _.map(files, function(file){return "./server/views/client/" + file});
			//console.log(fullFiles);
			var opts = {
			  files: fullFiles,
			  compress: true
			}
			compile(opts, function(err, result) {
				if(err) console.log(err);
				//console.log(result);
				jadeClientTemplates = result;

				res.header("Last-Modified", jadeCreationTime);
				res.header("If-Modified-Since", jadeCreationTime);
				res.header("Date", jadeCreationTime);
				res.header("Cache-Control", "public,max-age=31536000");
				res.header('Content-Type', 'text/javascript');
				res.send(jadeClientTemplates);				
			});
		});		
Example #16
0
exports.showInstallPopup = function (req, id) {
    var loc = window.location.toString();
    var dashboard_urls = _.map(dashboards.getURLs(), function (url, i) {
        return {id: i, url: url};
    });

    var content = templates.render('install_popup_content.html', req, {
        create_dashboard_url: 'http://garden20.com/?app_url=' + escape(loc)
    });
    popup.closeAll();
    var el = popup.open(req, {
        content: content,
        width: 900,
        height: 300
    });
    if (dashboard_urls.length > 0) {
            exports.createDefaultInstructions(el, req, id);
    } else {
        exports.showOtherOptionsPopup(req, id);
    }
};
Example #17
0
function shortestPathByHeap(graph, sNodeId) {
    'use strict';

    var sNode = graph.nodes[sNodeId];

    sNode.distance = 0;
    sNode.explored = true;

    _.each(graph.nodes[sNodeId].edges, function(edge) {
        var otherNode = edge.getOtherNode(sNode);
        otherNode.distance = Math.min(otherNode.distance, sNode.distance + edge.weight);
    });

    var unexplored = new Heap(graph.nodes);

    unexplored.remove(graph.nodes[sNodeId]);

    var closest;

    while (unexplored.heap.length) {
        closest = unexplored.getMin();
        closest.explored = true;

        _.each(closest.edges, function (edge) {
            var otherNode = edge.getOtherNode(closest);

            if (!otherNode.explored) {
                otherNode.distance = Math.min(otherNode.distance, closest.distance + edge.weight);
                unexplored.heapify(otherNode);
            }
        });
    }

    var ids = [7, 37, 59, 82, 99, 115, 133, 165, 188, 197];
    //var ids = [1,2,3,4,5,6,7,8,9,10];

    return _.map(ids, function(nodeId) {
        return graph.nodes[nodeId].distance;
    }).join(',');
}
Example #18
0
exports.showOtherOptionsPopup = function (req, id) {
    var loc = window.location.toString();
    var dashboard_urls = _.map(dashboards.getURLs(), function (url, i) {
        return {id: i, url: url};
    });

    var content = templates.render('install_popup_content.html', req, {
        create_dashboard_url: 'http://garden20.com/?app_url=' + escape(loc)
    });
    popup.closeAll();
    var el = popup.open(req, {
        content: content,
        width: 900,
        height: 300
    });
    if (dashboard_urls.length > 0) {
        $('.note-actions', el).prepend(
            '<a href="#" class="btn backbtn">&lt; Back</a>'
        );
    }

    $('#manual_install img').click(function (ev) {
        $('.note-actions .backbtn').remove();
        exports.createManualInstructions(el, req, id);
    });
    $('#install_to_dashboard img').click(function (ev) {
        $('.note-actions .backbtn').remove();
        exports.createDashboardInstructions(el, req, id);
    });
    $('#create_dashboard').click(function (ev) {
    });
    $('.note-actions .backbtn', el).click(function (ev) {
        ev.preventDefault();
        $('.note-actions .backbtn').remove();
        exports.createDefaultInstructions(el, req, id);
        return false;
    });


}
Example #19
0
/**
 * @param json a JSON object, such as: [ '{"Offer":{"Leased Car":"Without leased car"}}','{"Offer":{"Pension Fund":"10%"}}' ]
 * @return an array of three arrays with devision on intent, attribute and attribute:value
 * -- For example:  [ [ 'Offer' ],[ 'Leased Car', 'Pension Fund' ],[ 'Leased Car:Without leased car', 'Pension Fund:10%' ] ]
 */
function splitPartVersion1(json) {
	label = []	

	_(3).times(function(n){
		label[n] = []
		_.each(json.map(splitJson), function(value, key, list){
			if (n < value.length )
			{
				if (n!=2)
				{
					label[n] = label[n].concat(value[n])
				}
			else {
				label[n] = label[n].concat(label[n-1][key]+":"+value[n])
			}
			}
		}, this)
		// label[n] = _.uniq(_.compact(label[n]))
	}, this)

	return _.map(label, function(lab){ return _.uniq(_.compact(lab))})
}
Example #20
0
      })}},{'profile_url':1,'name':1},function(err,results){
        chatMessage.replies = [];
        _.map(results,function(replied){
          var replacer = new RegExp('@'+replied.name,'ig');
          chatMessage.replies.push({'to':replied.name});
          chatMessage.msg = chatMessage.msg.replace(replacer,'<a href="'+replied.profile_url+'">@'+replied.name+'</a>');
        });
        chatMessage.sender = {
          'profile_url' :socket.handshake.user.user.profile_url,
          'name' :socket.handshake.user.user.name,
          'profile_pic_url' :socket.handshake.user.user.profile_pic_url
        };
        socket.get('chatId', function(err, chat){
          if(socket.handshake.user.auth&&socket.handshake.user.auth.twitter&&msg.postToTwitter===true){
            var twitterKeys = socket.handshake.user.auth.twitter;
            streams.twitter.postMessage(twitterKeys.accessToken,twitterKeys.accessTokenSecret,chatMessage.msg+' #'+chat.replace('/',''),function(err,result){
              if(err){
                console.log(err);
                return false;
              }
              if(result){
                console.log(chatMessage.msg+ ' is posted!');
              }
            }); 
          }
          (new models.chatMsg({
            'user' :chatMessage.sender,
            'chatId' :chat,
            'message' :chatMessage.msg,
            'type' :'user',
            'replies': chatMessage.replies
          })).save(function(err, msg){
            chatMessage.id = msg._id;
            chatMessage.created_at = msg.created_at;
            io.sockets['in'](chat).emit('chatMsg', chatMessage);
          });

        });
      });
Example #21
0
Connection.prototype.create = function(type, records, callback) {
  if (arguments.length === 2) {
    type = null;
    records = type;
    callback = records;
  }
  var self = this;
  var isArray = _.isArray(records);
  records = isArray ? records : [ records ];
  if (records.length > self.maxRequest) {
    callback({ message : "Exceeded max limit of concurrent call" });
    return;
  }
  async.parallel(_.map(records, function(record) {
    return function(cb) {
      var sobjectType = type || (record.attributes && record.attributes.type) || record.type;
      if (!sobjectType) {
        cb({ message : 'No SObject Type defined in record' });
        return;
      }
      record = _.clone(record);
      delete record.Id;
      delete record.type;
      delete record.attributes;

      var url = [ self.urls.rest.base, "sobjects", sobjectType ].join('/');
      self._request({
        method : 'POST',
        url : url,
        body : JSON.stringify(record),
        headers : {
          "Content-Type" : "application/json"
        }
      }, cb);
    };
  }), function(err, results) {
    callback(err, !isArray && _.isArray(results) ? results[0] : results);
  });
};
Example #22
0
Connection.prototype.destroy = function(type, ids, callback) {
  var self = this;
  var isArray = _.isArray(ids);
  ids = isArray ? ids : [ ids ];
  if (ids.length > self.maxRequest) {
    callback({ message : "Exceeded max limit of concurrent call" });
    return;
  }
  async.parallel(_.map(ids, function(id) {
    return function(cb) {
      var url = [ self.urls.rest.base, "sobjects", type, id ].join('/');
      self._request({
        method : 'DELETE',
        url : url
      }, cb, {
        noContentResponse: { id : id, success : true, errors : [] }
      });
    };
  }), function(err, results) {
    callback(err, !isArray && _.isArray(results) ? results[0] : results);
  });
};
Example #23
0
 }, function (error, response, data) {
     if (!error && response.statusCode === 200) {
         var artistStr = '', time, artists = _.map(data.track.artists, function (artist) {
             return artist.name;
         });
         if (artists.length > 1) {
             artistStr = ' & ' + artists.pop();
             artistStr = artists.join(', ') + artistStr;
         } else {
             artistStr = artists[0];
         }
         time = utils.formatTime(Math.round(data.track.length));
         event.channel.say('Spotify: %s (Track No. %s on %s) [%s]',
             ircC.cyan.bold(artistStr + ' - ' + data.track.name),
             data.track['track-number'],
             ircC.olive.bold(data.track.album.name),
             time
             );
     } else {
         scriptLoader.debug('[urltitle/spotify/track] %s', error);
     }
 });
Example #24
0
 db.getView('types', q, function (err, result) {
     if (result.rows.length < 10) {
         more_link.remove();
     }
     if (!result.rows.length) {
         return;
     }
     var rows = result.rows;
     var f = _.map(rows, function (r) {
         var display_name = r.id;
         if (type && type.display_name) {
             display_name = type.display_name(r.doc);
         }
         return {id: r.id, display_name: display_name};
     });
     var html = templates.render('typelist_rows.html', req, {
         rows: f,
         app: req.query.app
     });
     more_link.data('last_id', rows[rows.length - 1].id);
     $('table.typelist tbody').append(html);
 });
Example #25
0
    return _.reduce(ids, function (errs, id, i) {

        var curr_errs = [];
        var nd = _.detect(nVal, function (v) {
            return v && v._id === id;
        });
        nd = nd || {_deleted: true};
        var od = _.detect(oVal, function (v) {
            return v && v._id === id;
        });
        var args = [nDoc, oDoc, nd, od, user];

        if (_.isFunction(perms)) {
            curr_errs = utils.getErrors(perms, args);
        }
        var fn;
        // on add
        if (nd && !od) {
            fn = perms.add;
        }
        // on remove
        else if (nd._deleted) {
            fn = perms.remove;
        }
        // on update
        else if (JSON.stringify(nd) !== JSON.stringify(od)) {
            fn = perms.update;
        }
        if (fn) {
            curr_errs = curr_errs.concat(utils.getErrors(fn, args));
        }
        curr_errs = _.map(curr_errs, function (e) {
            e.field = [i].concat(e.field || []);
            return e;
        });
        return errs.concat(curr_errs);

    }, []);
Example #26
0
  find_by_ids: function(ids, callback) {
    var self = this;
    var args = _.map(ids, function(id) { return self.redisKeyFor("id", id); });
    args.push(function(err, vals) {
      var insts = {};
      if (! err) {
        for (var i = 0; i < ids.length; ++i) {
          var id = ids[i];
          var attrs = vals[i];
          if (! attrs) {
            insts[id] = null;
          } else {
            attrs = JSON.parse(attrs);
            attrs.id = id;
            insts[id] = new self(attrs);
          }
        }
      }
      callback.call(self, err, insts);
    });

    this.client.mget.apply(this.client, args);
  },
Example #27
0
  app.get('/kern.min.js', function(req, res, next) {
    var files = [
        __dirname + '/common/methods.js',
        __dirname + '/common/bone.js',
        __dirname + '/kern.js'
      ]
      , fs = require('fs')
      , content = ''
    ;
    

    
    _.map(files, function(file, key){
      content = content + "\n// "+ file +"\n"+ fs.readFileSync(file).toString();
    });
    

    // TODO: adding the inline scripts assets to the 
    
    content += renderScriptsAssets(true);

    return res.send(content, { 'Content-Type': 'text/javascript' }, 200);
  });
Example #28
0
	setConnectedParticipants: function(users) {
        if (users.length > 10) { return false; }
        // Clean incoming users..
        users = _.map(users, function(u) {
            u = (u.toJSON ? u.toJSON() : u);
            return {
                id: u.id,
                displayName: u.displayName,
                picture: u.picture || (u.image && u.image.url ? u.image.url : "")
            }
        });
        // Has anything changed?
        var current = this.get("connectedParticipants");
        var intersection = _.intersection(_.pluck(users, "id"), _.pluck(current, "id"));
        if (users.length != current.length || intersection.length != current.length) {
            // We've changed.
            this.set("connectedParticipants", users);
            return true;
        } else {
            // No change.
            return false;
        }
	},
Example #29
0
  _.each(res, function iterateResult(result) {

    var email = result._id,
      wishes = result.wishes;

    LOG.info(util.format('[STATUS] [OK] [%s] Processing wishes. Found %d', email, _.size(wishes)));

    var functions = _.map(wishes, function (wish) {
      return function (done) {
        that.processWish(wish, done);
      };
    });

    async.series(functions, function (err, notifications) {
      if (err) {
        LOG.error(util.format('[STATUS] [Failure] [%s] Processing wishes failed', email, err));
        return callback(err);
      }

      LOG.info(util.format('[STATUS] [OK] [%s] Processing wishes finished', email));
      return callback();
    });
  });
Example #30
0
Action.convert = function(cfg, prex){

  if(Action.is(cfg)) return cfg;

  var result = [];

  if(_.isString(cfg)){
    ///为字符串时,pattern为通过匹配,handler为直接返回该值
    result.push(new Action(cfg))
  }else if(_.isFunction(cfg)){
    //为函数时,pattern为通过匹配,handler为该函数
    result.push(new Action(cfg))
  }else if(_.isArray(cfg)){
    //数组的时候,递归调用
    result = _.map(cfg, function(item){
      return new Action(item, prex);
    });
  }else if(_.isObject(cfg)){
    if(cfg.handler){
      result.push(new Action(cfg))
    }else{
      /**
       * Object, 每个key都是pattern, value是handler
       * @ignore
       */
      _.each(cfg, function(item, key){
        result.push(
          new Action({
            pattern: key,
            handler: item
          },prex)
        )
      })
    }
  }
  return result;
};