Example #1
0
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);
  }
};
Example #2
0
        '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.");
            }
        },
Example #3
0
 _.reduce(initial, function(memo, el, i) {
   if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
     memo[memo.length] = el;
     result[result.length] = array[i];
   }
   return memo;
 }, []);
Example #4
0
var returnPathInfo = function(reqUrl) {
	var querystring = require('querystring')
		,	url = require('url')
		,	path = url.parse(reqUrl).pathname
		,	query = url.parse(reqUrl).query || ''
		,	pathArray = _.compact(path.split('/'))
		,	pathInfo = {}
		,	lastElement = pathArray[pathArray.length-1] || []
			
	pathInfo.path = path
	if (lastElement.indexOf('.') !== -1) {
		pathInfo.file = {}
		pathInfo.file.name = lastElement.split('.')[0]
		pathInfo.file.ext = _.last(lastElement.split('.'))
		pathInfo.file.contentType = app.contentTypes[pathInfo.file.ext] || ''
		if (pathInfo.file.contentType === '') console.log(('Missing content type for ' + pathInfo.file.ext).warn)
		pathInfo.file.cache = app.contentTypes[pathInfo.file.ext[1]] || 'nocache'
	}
	else {
		pathInfo.rest = {}
		pathInfo.rest.page = pathArray[0] || 'home'
		pathInfo.rest.control = '/' + (pathArray[0] || '')
		pathInfo.rest.type = pathArray[1] || ''
		pathInfo.rest.item = pathArray[2] || null
		pathInfo.rest.title = pathArray[3] || ''
	}
	;(query !== '')
		? pathInfo.query = querystring.parse(query)
		: pathInfo.query = {}

	return pathInfo
}
Example #5
0
        '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"));
            }
        },
Example #6
0
exports.getReportingViewArgs = function (dates) {
    var startdate = _.first(dates.list),
        enddate = _.last(dates.list),
        startkey = [dates.form],
        endkey = [dates.form, enddate.year()];

    if (dates.reporting_freq === 'week') {
        startkey.push(startdate.year());
        startkey.push(getWeek(startdate));

        endkey.push(getWeek(enddate));
    } else {
        startdate = nextMonth(startdate);
        startkey.push(startdate.year());
        startkey.push(startdate.month() + 1);

        endkey.push(enddate.month() + 1);
    }
    startkey.push({});
    endkey.push('');

    return {
        startkey: startkey,
        endkey: endkey,
        descending: true
    };
};
      that.processPage(options, function (err, links) {
        if (err) {
          LOG.error(util.format('[STATUS] [Failure] [%s] [%s] [%s] Processing page failed %s', site, language, url, err));
          return finishPageProcessing(err);
        }

        if (!_.isEmpty(links) && lastUrl !== _.last(links)) {
          lastUrl = _.last(links);
        }
        else {
          pageRepeats = true;

          LOG.info(util.format('[STATUS] [OK] [%s] [%s] Gathering offers finished', site, language, pageNumber));
        }

        return finishPageProcessing();
      });
Example #8
0
  .action(function(){
    cmd = _.last(arguments)._name;
    rawCmd = rawCmd || cmd;
    var stopwords = WordPos.stopwords;

    if (program.json)
      output(stopwords);
    else
      console.log(stopwords.join(program.brief ? ' ' : '\n'))
  });
Example #9
0
 this.beginGroup = function (path) {
     this.depth += 1;
     var name = _.last(path);
     var css_class = 'clear group level-' + this.depth;
     return (
         '<div class="' + h(css_class) + '">' +
         '<div class="heading">' +
             h(name.substr(0, 1).toUpperCase() +
                 name.substr(1).replace(/_/g, ' ')) +
         '</div>'
     );
 };
Example #10
0
function exec(/* args, ..., program.command */){
  var args = _.initial(arguments);
  cmd = _.last(arguments)._name;
  rawCmd = rawCmd || cmd;

  if (program.file) {
    fs.readFile(program.file, 'utf8', function(err, data){
      if (err) return console.log(err);
      run(data);
    });
  } else if (args.length || cmd == 'rand'){
    run(args.join(' '));
  } else {
    read_stdin(run);
  }
}
Example #11
0
 this.api.getRecentlyPlayed(sid, function(err, games) {
     if(!err) {
         if(games.total_count != 0) {
             event.reply(dbot.t('steam_last_played', {
                 'user': user.currentNick,
                 'game': _.last(games.games).name
             }));
         } else {
             event.reply(dbot.t('steam_not_played', {
                 'user': user.currentNick
             }));
         }
     } else {
         event.reply('Unknown Steam Username');
     }
 });
Example #12
0
        'showconfig': function(event) {
            var configPathString = event.params[1];
            var configPath = getCurrentConfig(configPathString);
            
            if(configPathString) {
                var configKey = _.last(configPathString.split('.'));
                if(configKey) {
                    event.reply(dbot.t("no_config_path"));
                    return;
                }

                if(_.isArray(configPath.value)) {
                    event.reply(configKey + ': ' + configPath.value);
                } else if(_.isObject(configPath.value)) {
                    event.reply(dbot.t("config_keys_location",{"path":configPathString,"value":Object.keys(configPath.value)}));
                } else {
                    event.reply(configKey + ': ' + configPath.value);
                }
            } else {
                event.reply(dbot.t("config_keys_location",{"path":"root","value":Object.keys(configPath['default'])}));
            }
        }
Example #13
0
        'showconfig': function(event) {
            var configPathString = event.params[1];
            var configPath = getCurrentConfig(configPathString);
            
            if(configPathString) {
                var configKey = _.last(configPathString.split('.'));
                if(configKey == false) {
                    event.reply("Config path doesn't exist");
                    return;
                }

                if(_.isArray(configPath.value)) {
                    event.reply(configKey + ': ' + configPath.value);
                } else if(_.isObject(configPath.value)) {
                    event.reply('Config keys in ' + configPathString + ': ' + Object.keys(configPath.value));
                } else {
                    event.reply(configKey + ': ' + configPath.value);
                }
            } else {
                event.reply('Config keys in root: ' + Object.keys(configPath['default']));
            }
        }
Example #14
0
        'pushconfig': 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 currentArray = configPath.value;

                if(!_.isArray(currentArray)) {
                    event.reply(dbot.t("config_array",{"alternate": "setconfig"}));
                    return;
                }

                event.reply(configPathString + ": " + currentArray + " << " + newOption);
                currentArray.push(newOption);
                dbot.reloadModules(); 
            }
        },
Example #15
0
        'pushconfig': 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 currentArray = configPath.value;

                if(!_.isArray(currentArray)) {
                    event.reply("Config option is not an array. Try 'setconfig'.");
                    return
                }

                event.reply(configPathString + ": " + currentArray + " << " + newOption);
                currentArray.push(newOption);
                dbot.reloadModules(); 
            }
        },
Example #16
0
    var getCurrentConfig = function(configKey) {
        var defaultConfigPath = dbot.config;
        var userConfigPath = dbot.db.config;

        if(configKey) {
            var configKey = configKey.split('.');
            for(var i=0;i<configKey.length-1;i++) {
                if(_.has(defaultConfigPath, configKey[i])) {
                    if(!_.has(userConfigPath, configKey[i])) {
                        userConfigPath[configKey[i]] = {};
                    }
                    userConfigPath = userConfigPath[configKey[i]];
                    defaultConfigPath = defaultConfigPath[configKey[i]];
                } else {
                    return false;
                }
            }
        }

        var currentOption;
        if(configKey && configKey.length != 1) {
            configKey = _.last(configKey);
            if(_.has(userConfigPath, configKey) && !_.isUndefined(userConfigPath[configKey])) {
                currentOption = userConfigPath[configKey];
            } else if(_.has(defaultConfigPath, configKey)) {
                currentOption = defaultConfigPath[configKey];
            }
        } else {
            currentOption = defaultConfigPath[configKey];
        }

        return { 
            'user': userConfigPath,
            'default': defaultConfigPath,
            'value': currentOption
        };
   };
Example #17
0
	Parser.prototype.getTitle = function () {
		var fileName = _.last(this.filePath.split("/"));
		return _s.titleize(_s.humanize(_.first(fileName.split("."))));
	};
Example #18
0
File: rand.js Project: moos/wordpos
  return new Promise(function(resolve, reject) {

    //console.log('-- ', startsWith, num, self.fastIndex.indexKeys.length);
    if (startsWith) {
      key = startsWith.slice(0, KEY_LENGTH);

      /**
       * if key is 'a' or 'ab' (<3 chars), search for ALL keys starting with that.
       */
      if (key.length < KEY_LENGTH) {

        // calc trie if haven't done so yet
        if (!trie) {
          trie = new Trie();
          trie.addStrings(self.fastIndex.indexKeys);
          self.fastIndex.trie = trie;
          //console.log(' +++ Trie calc ');
        }

        try {
          // trie throws if not found!!!!!
          keys = trie.keysWithPrefix(startsWith);
        } catch (e) {
          keys = [];
        }

        // read all keys then select random word.
        // May be large disk read!
        key = keys[0];
        nextKey = _.last(keys);
      }

      if (!key || !(key in self.fastIndex.offsets))  {
        callback && callback([], startsWith);
        resolve([]);
      }

    } else {
      // no startWith given - random select among keys
      keys = _.sample(self.fastIndex.indexKeys, num);

      // if num > 1, run each key independently and collect results
      if (num > 1) {
        var results = [], ii = 0;
        _(keys).each(function (startsWith) {
          self.rand(startsWith, 1, function (result) {
            results.push(result[0]);
            if (++ii == num) {
              callback && callback(results, '');
              resolve(results);
            }
          });
        });
        return;
      }
      key = keys;
    }

    // prepare the piper
    var args = [key, nextKey, self],
      task = 'rand:' + key + nextKey,
      context = [startsWith, num, callback]; // last arg MUST be callback

    // pay the piper
    self.piper(task, IndexFile.readIndexBetweenKeys, args, context, collector);

    function collector(key, nextKey, index, startsWith, num, callback, buffer) {
      var lines = buffer.toString().split('\n'),
        matches = lines.map(function (line) {
          return line.substring(0, line.indexOf(' '));
        });
      //console.log(' got lines for key ', key, lines.length);

      // we got bunch of matches for key - now search within for startsWith
      if (startsWith !== key) {
        // binary search for startsWith within set of matches
        var ind = _.sortedIndex(matches, startsWith);
        if (ind >= lines.length || matches[ind].indexOf(startsWith) === -1) {
          callback && callback([], startsWith);
          resolve([]);
          return;
        }

        var trie = new Trie();
        trie.addStrings(matches);
        //console.log('Trie > ', trie.matchesWithPrefix( startsWith ));
        matches = trie.keysWithPrefix(startsWith);
      }

      var words = _.sample(matches, num);
      callback && callback(words, startsWith);
      resolve(words);
    }

  }); // Promise
Example #19
0
 self.connection.zrange(key, 0, -1, function(e, res) {
     if (spec === _.last(meta.relationships.has_many)) {
         callback(null, instance);
     }
 });
		processor.save(category+".txt", categoriesObj[category]).then(function() {
			processor.recSave(_.last(categories, categories.length-1),categoriesObj);
		})
		.catch(function (error) {
			notify("Error: "+category + " - " + error);
			processor.recSave(_.last(categories, categories.length-1),categoriesObj);
		});
Example #22
0
 .action(function(){
   rawCmd = 'exp';
   _.last(arguments)._name = 'lookup';
   exec.apply(this, arguments);
 });
Example #23
0
    Channel: function(model) {
        this.model = model;
        this.users = [];
        if(this.model.pictures.length > 0) {
            this.current_picture = _.last(this.model.pictures);
        }
        else {
            this.current_picture = null;
        }

        this.addUser = function(user) {
            this.preventNickDuplication(user);
            this.users.push(user);
            user.channel = this;
        };

        this.removeUser = function(user) {
            if(this.users.indexOf(user) >= 0) {
                this.users.splice(this.users.indexOf(user), 1);
            }
        };

        this.preventNickDuplication = function(user) {
            while(this.nickDuplicated(user)) {
                user.nick = user.nick + '_';
            }
        };

        this.nickDuplicated = function(user) {
            var usernicks = [];
            for(var i in this.users) {
                if(this.users[i] != user) {
                    usernicks.push(this.users[i].nick);
                }
            }
            return _.contains(usernicks, user.nick);
        };

        this.transmit = function(msg, from) {
            _.each(this.users, function(user) {
                if(user != from) {
                    user.socket.emit('chat', {from: from.nick, msg: msg, from_me: false});
                }
            });
        };

        this.notice = function(msg) {
            _.each(this.users, function(user) {
                user.socket.emit('notice', {msg: msg});
            });
        };

        this.updateUserlist = function() {
            var userlist = [];
            for(var i in this.users) {
                userlist.push(this.users[i].nick);
            }
            _.each(this.users, function(user) {
                user.socket.emit('update_userlist', {userlist: userlist});
            });
        };

        this.addPicture = function(picture) {
            if(!_.contains(this.model.pictures, picture)) {
                this.model.pictures.push(picture);
                this.model.save();
            }
        };

        this.changePicture = function(picture) {
            this.current_picture = picture;
            _.each(this.users, function(user) {
                user.socket.emit('picture_changed', {pid: picture._id, width: picture.width, height: picture.height});
            });
            this.notice('Picture has been changed to '+picture._id);
        };
    }
Example #24
0
 it( 'appends arguments to .includes', function () {
   One.append(Two);
   assert.equal(_.last(One.includes), Two);
 });