Example #1
0
kern.notify = function(tmpl, vars, opt){
  K = K || this;
  var args = _.toArray(arguments);
  vars = vars || {};
  opt = opt || {};
  
  try {
    args = [
        "-u", opt.urgency || "normal"
      , "-i", K.publicDir() +"/apple-touch-icon.png"
    ];
    args.push('"'+ (vars.title || '').split(' ').join('\ ') +'"');
    args.push('"'+ (vars.text || '').split(' ').join('\ ') +'"');
    require('child_process').exec("notify-send "+ args.join(' '));
  }
  catch (e) {
    K.log('error', '', e);
  }
  
  if (opt.socketEvent) {
    try {
      K.io.sockets.emit(opt.socketEvent, opt.socketData || {});
    }
    catch(e) {
      K.log('error', '', e);
    }
  }
  if (typeof opt.callback == 'function') opt.callback.call(K, vars, opt);
};
Example #2
0
    walker.on('end', function() {
      var response = [];
      files = __.toArray( filesObject );

      folders = folders.map( function ( folder ) {
        var temporal = {
          label: folder.folder,
          parent: folder.parent,
          data: folder.data
        };

        temporal.children = files.filter( function ( file ) {
          return file.parent === folder.folder;
        }).map( function ( file ) {
          return {
            label: file.label
          };
        });

        return temporal;
      });

      folders
        .filter( function ( folder ) {
          return folder.parent === undefined;
        })
        .forEach( function ( folder ) {
          response = recursive( folder, folders);
        });
      res.send(response);
  });
Example #3
0
Game.prototype.removePlayer = function(player) {
  player.game = null;
  delete this.players[player.id];
  if (this.creator.id == player.id && _.size(this.players) > 0) {
    this.creator = _.first(_.toArray(this.players));
  }
}
Example #4
0
SchemaArray.prototype.push = function ()
{
    // Values are passed through the setter before being allowed onto the array if arrayType is set.
    // In the case of rejection, the setter returns undefined, which is not appended to the array.
    var values;
    if (this._properties.arrayType)
    {
        values = [].map.call(arguments, function (value)
        {
            return setter.call(this._self, this._index, value, undefined, this._properties.arrayType);
        }, this);
    } else
    {
        values = arguments;
    }

    if (this._properties.unique)
    {
        values = _.difference(values, _.toArray(this));
    }

    var ret = [].push.apply(this, values);

    return ret;
};
exports.forceToArray = function (l) {
	if (typeof l === 'string' || typeof l === 'number') {
		return [ l ];
	}
	if (_.isArray(l)) {
		return l;
	} 
	return _.toArray(l);
};
Example #6
0
// single or multi key iterator for underscore
function iterator (key) { 
  var args = _.toArray(arguments);
  return function (obj) {
    if (obj[key] === undefined)       return obj;
    if (args.length === 1 ||
        typeof obj[key] === 'number') return obj[key];
    return args.map(function (arg) {
      return obj[arg];
    }).join(' ');
  };
}
Example #7
0
 _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
   var initial = arguments.length > 2;
   if (obj == null) obj = [];
   if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
     if (context) iterator = _.bind(iterator, context);
     return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
   }
   var reversed = _.toArray(obj).reverse();
   if (context && !initial) iterator = _.bind(iterator, context);
   return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);
 };
Example #8
0
 return function(/*client, errorType, errorData*/) {
   if (logger) {
     e.apply(this, arguments);
   } else {
     var me = this,
       args = _.toArray(arguments);
     cache.getItemWait("feather-logger", function(err, _logger) {
       _logger && (logger = _logger) && e.apply(me, args);
     });
   }
 };
Example #9
0
  dispose: function(cb) {
    cb = cb || noop;
    
    var me = this,
      args = _.toArray(arguments);

    this.removeAll(function(err) {
      RedisRegistry.super.prototype.dispose.apply(me, args);

      cb();
    });    
  }
Example #10
0
var triggerViewMethod = function(channel, method) {
	var currentView = Backbone.Wreqr.radio.channel(channel).reqres.request('getView');

	// June 17: addied isDestroyed check.
	if (currentView && currentView instanceof Backbone.View && !currentView.isDestroyed) {
		return currentView.triggerMethod.apply(currentView, _.toArray(arguments).slice(1));
	}

	if (currentView && currentView.isDestroyed) {
		console.log('Warning: Method "triggerViewMethod", currentView for channel "' + channel + '" isDestroyed');
	} else {
		console.log('Warning: Method "triggerViewMethod", no currentView for channel "' + channel + '" method (' + method + ')'); 
	}

};
/**
* @param f ,  original function to call, f(arg1, arg2, ..., argN, cb),
*			  where cb has the form callback(err, res)
* @param times, max times for retry
* @param ... pass in all arguments of f behind these f and times
*/
function retry(f, times) {
	var tried = 0,
		args = _.toArray(arguments).slice(2),
		cb = last(args),
		ncb = function(err, res) {
			if(!existy(err) || tried >= times - 1) 
				cb(err, res);
			else {
				tried ++;
				f.apply(null, setLast(args, ncb));
			}
		};
	
	f.apply(null, setLast(args, ncb));
}
Example #12
0
  .action(function(/* arg, ..., program.command */){
    var args = _.toArray(arguments),
      num = args.length > 1 && Number(args[0]);
    delete program.count;

    // first arg is count?
    if (num) {
      args.shift();
      program.num = num;
    }
    // no startsWith given, add a placeholder
    if (args.length === 1){
      args.unshift(RAND_PLACEHOLDER);
    }
    exec.apply(this, args);
  });
Example #13
0
      sandbox[k] = function() {
        if (sandboxRoot._error) return;

        var args = _.toArray(arguments);
        var callback;
        var callbackIndex;
        var result;
        
        for(var i = 0; i < args.length; i++) {
          if(typeof args[i] == 'function') {
            callback = args[i];
            callbackIndex = i;
            break;
          }
        }
        
        if (typeof callback === 'function') {
          events.emit('addCallback');
          args[callbackIndex] = function() {
            if (sandboxRoot._error) return;
            try {
              result = callback.apply(sandboxRoot._this, arguments);
              events.emit('finishCallback');
            } catch (err) {
              var wrappedErr = wrapError(err);
              sandbox._error = wrappedErr;
              return done(wrappedErr);
            }
          };
        } else {
          args.push(function() {
            if (sandboxRoot._error) return;
            events.emit('finishCallback');
          });
        }
        try {
          result = asyncFunctions[k].apply(sandboxRoot._this, args);
        } catch(err) {
          var wrappedErr = wrapError(err);
          sandbox._error = wrappedErr;
          return done(wrappedErr);
        }
        
        if(result !== undefined) {
          return result;
        }
      };
Example #14
0
	calculateStatsNoReturn: function() {
		this.retrieveLabels()

		this.macroPrecision = 0
		this.macroRecall = 0
		this.macroF1 = 0

		var macroPrecision = []
		var macroRecall = []
		var macroF1 = []

		// isNaN

		if (Object.keys(this.labels).length > 3)
		{

			var list_lab = _.toArray(this.labels)
			var macro_stats = {}
			
			_.each(['Precision', 'Recall', 'F1'], function(param, key, list){ 
				macro_stats[param] = _.pluck(list_lab, param)
				macro_stats[param] = _.filter(macro_stats[param], function(elem){ return (isNaN(elem))==false})
				macro_stats[param] = _.reduce(macro_stats[param], function(memo, num){ return memo + num; }) / macro_stats[param].length
			}, this)

			this.macroPrecision = macro_stats['Precision']
			this.macroRecall = macro_stats['Recall']
			this.macroF1 = macro_stats['F1']

		}

		this.Accuracy = (this.TRUE) / (this.count);
		this.HammingLoss = (this.FN+this.FP) / (this.FN+this.TP); // "the percentage of the wrong labels to the total number of labels"
		this.HammingGain = 1-this.HammingLoss;
		this.Precision = this.TP / (this.TP+this.FP);
		this.Recall = this.TP / (this.TP+this.FN);
		this.F1 = 2 / (1/this.Recall + 1/this.Precision);
		this.endTime = new Date();
		this.timeMillis = this.endTime-this.startTime;
		this.timePerSampleMillis = this.timeMillis / this.count;
		this.shortStatsString = sprintf("Accuracy=%d/%d=%1.0f%% HammingGain=1-%d/%d=%1.0f%% Precision=%1.0f%% Recall=%1.0f%% F1=%1.0f%% timePerSample=%1.0f[ms]",
				this.TRUE, this.count, this.Accuracy*100, (this.FN+this.FP), (this.FN+this.TP), this.HammingGain*100, this.Precision*100, this.Recall*100, this.F1*100, this.timePerSampleMillis);
		},
	return function() {
		var args = _.toArray(arguments);
		for(var i = 0; i < times; i++)
			f.apply(null, args);
	}
Example #16
0
    fs.readFile(url, 'UTF-8', function (err, data) {
        if (err) throw err;

        var exports = _findExports(data);
        var doxResult = dox.parseComments(data, {});

        var moduleDescription = "";
        var functions = [];
        var variables = [];
        var classes = {};

        doxResult.forEach(function (el) {
            if (el.code && el.code.indexOf("define(") == 0) {
                moduleDescription = el.description.full;
            }

            if (!el.ctx) return;

            el = _postProcess(el, exports);

            if (el.ctx.type == 'declaration') {
                variables.push(el);
            } else if (el.ctx.type == 'function') {
                if (el.isConstructor) {
                    classes[el.ctx.name] = {
                        constructor: el,
                        properties: [],
                        methods: []
                    };
                } else {
                    functions.push(el);
                }
            } else if (el.ctx.type == 'property') {
                if (classes[el.ctx.constructor]) {
                    classes[el.ctx.constructor].properties.push(el);
                }
            } else if (el.ctx.type == 'method') {
                if (classes[el.ctx.constructor]) {
                    classes[el.ctx.constructor].methods.push(el);
                }
            }
        });

        var dependencies = _.sortBy(_findDependencies(data), idFun);

        variables = _sortMembers(variables);
        functions = _sortMembers(functions);

        classes = _.toArray(classes).map(function(clazz){
            clazz.properties = _sortMembers(clazz.properties);
            clazz.methods = _sortMembers(clazz.methods);
            return clazz;
        });

        cb({
            description: moduleDescription,
            dependencies: dependencies,
            exports: exports,
            functions: functions,
            variables: variables,
            classes: classes
        });
    });
Example #17
0
var typecast = function(value, originalValue, properties) {
  // Allow transform to manipulate raw properties.
  if(properties.transform) {
    value = properties.transform.call(this, value, originalValue, properties);
  }

  switch(properties.type) {
    case 'string':
      // Reject if object or array.
      if(_.isObject(value) || _.isArray(value)) {
        throw new SetterError('String type cannot typecast Object or Array types.', value, originalValue, properties);
      }

      // If index is being set with null or undefined, set value and end.
      if(_.isUndefined(value) || value === null) {
        return value;
      }

      // Typecast to String.
      value = value + '';

      // If stringTransform function is defined, use.
      // This is used before we do validation checks (except to be sure we have a string at all).
      if(properties.stringTransform) {
        value = properties.stringTransform.call(this, value, originalValue, properties);
      }

      // If clip property & maxLength properties are set, the string should be clipped.
      // This is basically a shortcut property that could be done with stringTransform.
      if(properties.clip && !_.isUndefined(properties.maxLength)) {
        value = value.substr(0, properties.maxLength);
      }

      // If enum is being used, be sure the value is within definition.
      if(_.isArray(properties.enum) && properties.enum.indexOf(value) === -1) {
        throw new SetterError('String does not exist in enum list.', value, originalValue, properties);
      }

      // If minLength is defined, check to be sure the string is > minLength.
      if(!_.isUndefined(properties.minLength) && value.length < properties.minLength) {
        throw new SetterError('String length too short to meet minLength requirement.', value, originalValue, properties);
      }

      // If maxLength is defined, check to be sure the string is < maxLength.
      if(!_.isUndefined(properties.maxLength) && value.length > properties.maxLength) {
        throw new SetterError('String length too long to meet maxLength requirement.', value, originalValue, properties);
      }

      // If regex is defined, check to be sure the string matches the regex pattern.
      if(properties.regex && !properties.regex.test(value)) {
        throw new SetterError('String does not match regular expression pattern.', value, originalValue, properties);
      }

      return value;
      break;

    case 'number':
      // Set values for boolean.
      if(_.isBoolean(value)) {
        value = value ? 1 : 0;
      }

      // Reject if array, object, or not numeric.
      if( _.isArray(value) || _.isObject(value) || !isNumeric(value)) {
        throw new SetterError('Number type cannot typecast Array or Object types.', value, originalValue, properties);
      }

      // Typecast to number.
      value = value * 1;

      // Transformation after typecasting but before validation and filters.
      if(properties.numberTransform) {
        value = properties.numberTransform.call(this, value, originalValue, properties);
      }

      if(!_.isUndefined(properties.min) && value < properties.min) {
        throw new SetterError('Number is too small to meet min requirement.', value, originalValue, properties);
      }

      if(!_.isUndefined(properties.max) && value > properties.max) {
        throw new SetterError('Number is too big to meet max requirement.', value, originalValue, properties);
      }

      return value;
      break;

    case 'boolean':
      // If is String and is 'false', return false.
      if(value === 'false') {
        return false;
      }

      // If is Number, <0 is true and >0 is false.
      if(isNumeric(value)) {
        return (value * 1) > 0 ? true : false;
      }

      // Use Javascript to eval and return boolean.
      value = value ? true : false;

      // Transformation after typecasting but before validation and filters.
      if(properties.booleanTransform) {
        value = properties.booleanTransform.call(this, value, originalValue, properties);
      }

      return value;
      break;

    case 'array':
      // If it's an object, typecast to an array and return array.
      if(_.isObject(value)) {
        value = _.toArray(value);
      }

      // Reject if not array.
      if(!_.isArray(value)) {
        throw new SetterError('Array type cannot typecast non-Array types.', value, originalValue, properties);
      }

      // Arrays are never set directly.
      // Instead, the values are copied over to the existing SchemaArray instance.
      // The SchemaArray is initialized immediately and will always exist.
      originalValue.length = 0;
      _.each(value, function(arrayValue) {
        originalValue.push(arrayValue);
      });

      return originalValue;
      break;

    case 'object':
      // If it's not an Object, reject.
      if(!_.isObject(value)) {
        throw new SetterError('Object type cannot typecast non-Object types.', value, originalValue, properties);
      }

      // If object is schema object and an entirely new object was passed, clear values and set.
      // This preserves the object instance.
      if(properties.objectType) {
        // The object will usually exist because it's initialized immediately for deep access within SchemaObjects.
        // However, in the case of Array elements, it will not exist.
        var schemaObject;
        if(!_.isUndefined(originalValue)) {
          // Clear existing values.
          schemaObject = originalValue;
          schemaObject.clear();
        } else {
          // The SchemaObject doesn't exist yet. Let's initialize a new one.
          // This is used for Array types.
          schemaObject = new properties.objectType;
        }

        // Copy value to SchemaObject and set value to SchemaObject.
        _.each(value, function(v, k) {
          schemaObject[k] = v;
        });
        value = schemaObject;
      }

      // Otherwise, it's OK.
      return value;
      break;

    case 'date':
      // Reject if object, array or boolean.
      if(!_.isDate(value) && !_.isString(value) && !_.isNumber(value)) {
        throw new SetterError('Date type cannot typecast Array or Object types.', value, originalValue, properties);
      }

      // Attempt to parse string value with Date.parse (which returns number of milliseconds).
      if(_.isString(value)) {
        value = Date.parse(value);
      }

      // If is timestamp, convert to Date.
      if(_.isNumber(value)) {
        value = new Date((value + '').length > 10 ? value : value * 1000);
      }

      // If the date couldn't be parsed, do not modify index.
      if(value == 'Invalid Date' || !_.isDate(value)) {
        throw new SetterError('Could not parse date.', value, originalValue, properties);
      }

      // Transformation after typecasting but before validation and filters.
      if(properties.dateTransform) {
        value = properties.dateTransform.call(this, value, originalValue, properties);
      }

      return value;
      break;

    default:
      return value;
      break;
  }
};
Example #18
0
 _.size = function(obj) {
   return _.toArray(obj).length;
 };
function loop(f, times, predicate) {
	// args for f
	var args = _.toArray(arguments).slice(3);
	for(var i = 0; i < times && predicate(); i++) 
		f.apply(null, args);
}
exports.enclose = function(func) {
	var args = _.toArray(arguments).slice(1);
	return function (context) {
		return func.apply(context || null, args);
	};
};
Example #21
0
 Backbone.Collection.prototype[method] = function() {
   return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
 };
var found = function(target, source) {
	if (!_.isArray(source)) {
		source = _.toArray(arguments).slice(1);
	}
	return _.intersection(target, source).length > 0;
};
Example #23
0
 self._append = function(sql) {
   self.sql += arguments.length == 1 ? sql : util.format.apply(null, _.toArray(arguments));
   return self;
 };
exports.args = function (a) {
	return (_.isArray(a) ? a : _.toArray(arguments));
};
Example #25
0
function getwordnet(string, pos, callbackg)
{
	console.vlog("DEBUGWORDNET: string:"+string+" pos:"+pos)

	var POS = {

		'n': ['NN', 'NNS', 'NNP', 'NNPS', 'noun','nn', 'nns', 'nnp', 'nnps'],
		'a': ['JJ', 'JJR', 'JJS', 'adj', 'jj', 'jjr', 'jjs'],
		// 's': ['JJ', 'JJR', 'JJS', 'adj'],
		'r': ['RB', 'RBR', 'RBS','WRB', 'adv', 'rb', 'rbr', 'rbs','wrb'],
		'v': ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ', 'verb','vb', 'vbd', 'vbg', 'vbn', 'vbp', 'vbz']
	}

	if (_.flatten(_.toArray(POS)).indexOf(pos) == -1)
		{
		console.vlog("DEBUGWORDNET: no pos")
		callbackg(null, {'synonyms':[], 'antonyms':[]})
		}
	else
	{

	var wnpos = ""

	_.each(POS, function(poslist, wnp, list){ 
		if (poslist.indexOf(pos) != -1)
			wnpos = wnp
	}, this)

	console.vlog("DEBUGWORDNET: string:"+string+" pos:"+wnpos)
	var wordnet = new WordNet()

	var synonyms = []
	var antonyms = []

	wordnet.lookup(string, function(results) {

		results = _.filter(results, function(num){ return !_.isNull(num) });

		results = _.filter(results, function(num){ return num.pos ==  wnpos });

		async.eachSeries(results, function(synset, callbackloc) {

				synonyms = synonyms.concat(synset.synonyms)

				synset.ptrs = _.filter(synset.ptrs, function(num){ return num.pointerSymbol ==  "!" });

				async.eachSeries(synset.ptrs, function(subsynset, callbacklocloc) {

						wordnet.get(subsynset.synsetOffset, subsynset.pos, function(anton) {
							antonyms = antonyms.concat(anton.synonyms)
   							callbacklocloc(null)
						});
					
				}, function(err){
					callbackloc(null)

				})

		 	}, function(err){

		 		synonyms = _.map(_.unique(synonyms), function(num){ return [num, wordCount.indexOf(num)] });
		 		antonyms = _.map(_.unique(antonyms), function(num){ return [num, wordCount.indexOf(num)] });

		 		synonyms = _.sortBy(synonyms, function(num){ return num[1] }).reverse()
		 		antonyms = _.sortBy(antonyms, function(num){ return num[1] }).reverse()

		 		wordnet.close()

				synonyms = _.filter(synonyms, function(num){ return (num[0].indexOf("_")==-1) })
		 		antonyms = _.filter(antonyms, function(num){ return (num[0].indexOf("_")==-1) })
		 		
				// eliminate the numbers

				synonyms = _.unique(_.flatten(_.map(synonyms, function(num){ return num[0] })))
		 		antonyms = _.unique(_.flatten(_.map(antonyms, function(num){ return num[0] })))

		 		console.vlog("DEBUGWORDNET: synonyms: "+JSON.stringify(synonyms, null, 4))
		 		console.vlog("DEBUGWORDNET: antonyms: "+JSON.stringify(antonyms, null, 4))

		 		callbackg(null, {
		 			'synonyms':_.filter(synonyms, function(num){ return (num[0].indexOf("_")==-1) }),
		 			'antonyms':_.filter(antonyms, function(num){ return (num[0].indexOf("_")==-1) })
		 		})
		})

	})
}
}