Ejemplo n.º 1
0
Archivo: Node.js Proyecto: zcpara/mcf
Node.prototype.send = function(msg) {
    var msgSent = false;
    var node;
    
    if (msg === null || typeof msg === "undefined") {
        return;
    } else if (!util.isArray(msg)) {
        if (this._wire) {
            // A single message and a single wire on output 0
            // TODO: pre-load flows.get calls - cannot do in constructor
            //       as not all nodes are defined at that point
            node = flows.get(this._wire);
            if (node) {
                node.receive(msg);
            } else {
                // Add by MCF, node is on remote device
                console.log("Send flow single msg to node on remote devices");
                deviceServer.send(this._wire, msg);
                // Add by MCF, end
            }
            return;
        } else {
            msg = [msg];
        }
    }
    
    var numOutputs = this.wires.length;
    
    // Build a list of send events so that all cloning is done before
    // any calls to node.receive
    var sendEvents = [];
    
    // for each output of node eg. [msgs to output 0, msgs to output 1, ...]
    for (var i = 0; i < numOutputs; i++) {
        var wires = this.wires[i]; // wires leaving output i
        if (i < msg.length) {
            var msgs = msg[i]; // msgs going to output i
            if (msgs !== null && typeof msgs !== "undefined") {
                if (!util.isArray(msgs)) {
                    msgs = [msgs];
                }
                var k = 0;
                // for each recipent node of that output
                for (var j = 0; j < wires.length; j++) {
                    node = flows.get(wires[j]); // node at end of wire j
                    if (node) {
                        // for each msg to send eg. [[m1, m2, ...], ...]
                        for (k = 0; k < msgs.length; k++) {
                            if (msgSent) {
                                sendEvents.push({n:node,m:redUtil.cloneMessage(msgs[k])});
                            } else {
                                // first msg sent so don't clone
                                sendEvents.push({n:node,m:msgs[k]});
                                msgSent = true;
                            }
                        }
                    } else {
                        // Add by MCF, node is on remote device
                        console.log("Send flow array msg to node on remote devices");
                        deviceServer.send(wires[j], redUtil.cloneMessage(msgs[k]));
                        // Add by MCF, end
                    }
                }
            }
        }
    }
    
    for (i=0;i<sendEvents.length;i++) {
        var ev = sendEvents[i];
        ev.n.receive(ev.m);
    }
};
Ejemplo n.º 2
0
var Cosm = exports.Device = function(deviceID, deviceUID, info) {
  var actor, entity, params, place, self;

  self = this;

  self.whatami = info.deviceType;
  self.deviceID = deviceID.toString();
  self.deviceUID = deviceUID;
  self.name = info.device.name;

  self.info = utility.clone(info);
  delete(self.info.id);
  delete(self.info.device);
  delete(self.info.deviceType);
  self.status = 'waiting';
  self.elide = [ 'apikey' ];
  self.changed();

  self.cosm = new cosm.Cosm(info.apikey, { server: 'https://api.xively.com' });
  self.datastreams = {};

  broker.subscribe('readings', function(deviceID, point) { self.update(self, deviceID, point); });

  broker.subscribe('actors', function(request, taskID, actor, perform, parameter) {
    if (request === 'attention') {
      if (self.status === 'error') self.alert('please check login credentials at https://xively.com/login/');
      return;
    }

    if (actor !== ('device/' + self.deviceID)) return;

    if (request === 'perform') return self.perform(self, taskID, perform, parameter);
  });

  if (!!self.info.feed) return self.getfeed(self);

  actor = steward.actors.place;
  if (!!actor) {
    entity = actor.$lookup("1");
    if (!!entity) place = entity.proplist();
  }
  if (!place) place = { name: '', info: {} };

  params = { version       : '1.0.0'
           , title         : info.name || place.name
           , description   : info.description || null
           , location      :
             { disposition : 'fixed'
             , name        : place.name
             , exposure    : 'indoor'
             , domain      : 'physical'
             }
           , private       : (!!info.private) ? (info.private === 'on') : false
           };
  if (util.isArray(place.info.coordinates)) {
    params.location.lat = place.info.coordinates[0];
    params.location.lon = place.info.coordinates[1];
    if (place.info.coordinates.length > 2) params.location.ele = place.info.coordinates[2];
    if (!params.private) {
      params.location.lat = params.location.lat.toFixed(1);
      params.location.lon = params.location.lon.toFixed(1);
      params.location.ele = params.location.ele.toFixed(1);
    }
  }

  self.cosm.create(params, function(err, id) {
    if (!!err) {
      self.status = 'error';
      self.setInfo();
      return logger.error('device/' + self.deviceID, { event: 'cosm.create', diagnostic: err.message || err.errors });
    }

    self.info.feed = id.toString();
    self.setInfo();

    self.getfeed(self);
  });
};
Ejemplo n.º 3
0
 it("returns an empty array if no results are found", function(){
   var result = moby.search("doggg")
   assert(util.isArray(result))
   assert.equal(result.length, 0)
 })
Ejemplo n.º 4
0
			each(arg, function(value, key) {
				if (value !== undef) {
					if (typeof(target[key]) === typeof(value) && (typeof(value) === 'object' || util.isArray(value))) {
						extend(target[key], value);
					} else {
						target[key] = value;
					}
				}
			});
Ejemplo n.º 5
0
function Buffer(subject, encoding) {
  if (!util.isBuffer(this))
    return new Buffer(subject, encoding);

  if (util.isNumber(subject)) {
    this.length = subject > 0 ? subject >>> 0 : 0;

  } else if (util.isString(subject)) {
    if (!util.isString(encoding) || encoding.length === 0)
      encoding = 'utf8';
    this.length = Buffer.byteLength(subject, encoding);

  // Handle Arrays, Buffers, Uint8Arrays or JSON.
  } else if (util.isObject(subject)) {
    if (subject.type === 'Buffer' && util.isArray(subject.data))
      subject = subject.data;
    // Must use floor() because array length may be > kMaxLength.
    this.length = +subject.length > 0 ? Math.floor(+subject.length) : 0;

  } else {
    throw new TypeError('must start with number, buffer, array or string');
  }

  if (this.length > kMaxLength) {
    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
                         'size: 0x' + kMaxLength.toString(16) + ' bytes');
  }

  this.parent = undefined;
  if (this.length <= (Buffer.poolSize >>> 1) && this.length > 0) {
    if (this.length > poolSize - poolOffset)
      createPool();
    this.parent = sliceOnto(allocPool,
                            this,
                            poolOffset,
                            poolOffset + this.length);
    poolOffset += this.length;
  } else {
    alloc(this, this.length);
  }

  if (util.isNumber(subject)) {
    return;
  }

  if (util.isString(subject)) {
    // In the case of base64 it's possible that the size of the buffer
    // allocated was slightly too large. In this case we need to rewrite
    // the length to the actual length written.
    var len = this.write(subject, encoding);
    // Buffer was truncated after decode, realloc internal ExternalArray
    if (len !== this.length) {
      var prevLen = this.length;
      this.length = len;
      truncate(this, this.length);
      poolOffset -= (prevLen - len);
    }

  } else if (util.isBuffer(subject)) {
    subject.copy(this, 0, 0, this.length);

  } else if (util.isNumber(subject.length) || util.isArray(subject)) {
    // Really crappy way to handle Uint8Arrays, but V8 doesn't give a simple
    // way to access the data from the C++ API.
    for (var i = 0; i < this.length; i++)
      this[i] = subject[i];
  }
}
Ejemplo n.º 6
0
  function instrumentRequest(segment) {
    const transaction = segment.transaction
    const outboundHeaders = Object.create(null)

    if (agent.config.encoding_key && transaction.syntheticsHeader) {
      outboundHeaders[NEWRELIC_SYNTHETICS_HEADER] = transaction.syntheticsHeader
    }

    // TODO: abstract header logic shared with TransactionShim#insertCATRequestHeaders
    if (agent.config.distributed_tracing.enabled) {
      if (opts.headers && opts.headers[SHIM_SYMBOLS.DISABLE_DT]) {
        logger.trace('DT disabled by instrumentation.')
      } else {
        _addDistributedHeaders(transaction, outboundHeaders)
      }
    } else if (agent.config.cross_application_tracer.enabled) {
      if (agent.config.encoding_key) {
        _addCATHeaders(agent, transaction, outboundHeaders)
      } else {
        logger.trace('No encoding key found, not adding CAT headers')
      }
    } else {
      logger.trace('CAT disabled, not adding headers!')
    }

    if (util.isArray(opts.headers)) {
      opts.headers = opts.headers.slice()
      Array.prototype.push.apply(
        opts.headers,
        Object.keys(outboundHeaders).map(function getHeaderTuples(key) {
          return [key, outboundHeaders[key]]
        })
      )
    } else {
      opts.headers = Object.assign(
        Object.create(null),
        opts.headers,
        outboundHeaders
      )
    }

    segment.start()
    const request = makeRequest(opts)
    const parsed = urltils.scrubAndParseParameters(request.path)
    const proto = parsed.protocol || opts.protocol || 'http:'
    segment.name += parsed.path
    request.__NR_segment = segment

    if (parsed.parameters) {
      // Scrub and parse returns on object with a null prototype.
      for (let key in parsed.parameters) { // eslint-disable-line guard-for-in
        segment.addAttribute(`request.parameters.${key}`, parsed.parameters[key])
      }
    }
    segment.addAttribute('url', `${proto}//${hostname}${parsed.path}`)

    // Wrap the emit method. We're doing a special wrapper instead of using
    // `tracer.bindEmitter` because we want to do some logic based on certain
    // events.
    shimmer.wrapMethod(request, 'request.emit', 'emit', function wrapEmit(emit) {
      const boundEmit = agent.tracer.bindFunction(emit, segment)
      return function wrappedRequestEmit(evnt, arg) {
        if (evnt === 'error') {
          segment.end()
          handleError(segment, request, arg)
        } else if (evnt === 'response') {
          handleResponse(segment, hostname, request, arg)
        }

        return boundEmit.apply(this, arguments)
      }
    })
    _makeNonEnumerable(request, 'emit')

    return request
  }
Ejemplo n.º 7
0
var _ = function (data) {

	var pipeline = [];
	var inputStream;

	if (util.isArray(data)) {
		inputStream = new ArrayReader(data);
	}
	else if (isReadable(data)) {
		inputStream = data;
	}
	else {
		throw new Error('Not a readable stream');
	}

	return chainsaw(function (saw) {
		this.asStream = function () {
			return pipeline.reduce(function (stream, thru) {
				return stream.pipe(thru);
			}, inputStream);
		};

		this.pipe = function () {
			var stream = this.asStream();
			return stream.pipe.apply(stream, arguments);
		};

		this.then = function (cb) {
			var retVal = [];
			this.pipe(through2.obj(function (data, enc, done) {
				this.push(data);
				retVal.push(data);
				done();
			}, function (done) {
				done();
				cb(retVal);
			}));
		};

		this.compact = function () {
			pipeline.push(through2.obj(function (data, enc, done) {
				if (data) {
					this.push(data);
				}
				done();
			}));
			saw.next();
		};

		this.difference = function () {
			var values = Array.prototype.concat.apply([], arguments);
			var set = new Set();
			values.forEach(set.add.bind(set));
			pipeline.push(through2.obj(function (data, enc, done) {
				if (!set.has(data)) {
					this.push(data);
				}
				done();
			}));
			saw.next();
		};

		this.filter = function (callback, thisArg) {
			var cb = callback.bind(thisArg);
			var index = 0;
			pipeline.push(through2.obj(function (data, enc, done) {
				if (cb(data, index++)) {
					this.push(data);
				}
				done();
			}));
			saw.next();
		};

		this.flatten = function (isShallow, callback, thisArg) {
			var flatten = function (queue, a) {
				return Array.isArray(a) ? a.forEach(flatten.bind(null, queue)) : queue(a);
			};

			pipeline.push(through2.obj(function (data, enc, done) {
				flatten(this.push.bind(this), data);
				done();
			}));
			saw.next();
		};

		this.forEach = function (callback, thisArg) {
			var cb = callback.bind(thisArg);
			var exit = false;
			pipeline.push(through2.obj(function (data, enc, done) {
				this.push(data);
				if (!exit) {
					exit = cb(data) === false;
				}
				done();
			}));
			saw.next();
		};

		this.initial = function (n) {
			if (!n && n !== 0) {
				n = 1;
			}
			var buffer = new CBuffer(n);
			var stream = through2.obj(function (data, enc, done) {
				buffer.push(data);
				done();
			});
			buffer.overflow = stream.push.bind(stream);
			pipeline.push(stream);
			saw.next();
		};

		this.intersection = function () {
			var values = Array.prototype.concat.apply([], arguments);
			var set = new Set();
			values.forEach(set.add.bind(set));
			pipeline.push(through2.obj(function (data, enc, done) {
				if (set.has(data)) {
					this.push(data);
				}
				done();
			}));
			saw.next();
		};

		this.first = function (n) {
			if (!n && n !== 0) {
				n = 1;
			}
			var index = 0;
			pipeline.push(through2.obj(function (data, enc, done) {
				if (index++ < n) {
					this.push(data);
				}
				done();
			}));
			saw.next();
		};

		this.last = function (n) {
			if (!n && n !== 0) {
				n = 1;
			}
			var buffer = new CBuffer(n);
			pipeline.push(through2.obj(function (data, enc, done) {
				buffer.push(data);
				done();
			}, function (done) {
				buffer.forEach(this.push.bind(this));
				done();
			}));
			saw.next();
		};

		this.rest = function (n) {
			if (!n && n !== 0) {
				n = 1;
			}
			var i = 0;
			pipeline.push(through2.obj(function (data, enc, done) {
				if (i++ >= n) {
					this.push(data);
				}
				done();
			}));
			saw.next();
		};

		this.union = function () {
			var array = Array.prototype.concat.apply([], arguments);
			var seen = new Set();
			var enq = function (data) {
				if (!seen.has(data)) {
					seen.add(data);
					stream.push(data);
				}
			};
			var stream = through2.obj(function (data, enc, done) {
				enq(data);
				done();
			}, function (done) {
				array.forEach(enq);
				done();
			});
			pipeline.push(stream);
			saw.next();
		};

		this.uniq = function () {
			var args = Array.prototype.slice.call(arguments);
			var isSorted = false;
			var callback = identity;
			var context = null;
			if (args.length && typeof args[0] === 'boolean') {
				isSorted = args.shift();
			}
			if (args.length && typeof args[0] === 'function') {
				callback = args.shift();
			}
			if (args.length) {
				context = args.shift();
			}
			if (context) {
				callback = callback.bind(context);
			}

			var enq = (function () {
				if (isSorted) {
					var last;
					return function (data, enc, done) {
						var value = callback(data);
						if (isSorted) {
							if (last !== value) {
								stream.push(data);
							}
							last = value;
						}
						done();
					};
				}
				else {
					var seen = new Set();
					return function (data, enc, done) {
						var value = callback(data);
						if (!seen.has(value)) {
							seen.add(value);
							stream.push(data);
						}
						done();
					};
				}
			})();

			var stream = through2.obj(enq);
			pipeline.push(stream);
			saw.next();
		};

		this.without = function () {
			var values = Array.prototype.slice.call(arguments);
			var set = new Set();
			values.forEach(set.add.bind(set));
			pipeline.push(through2.obj(function (data, enc, done) {
				if (!set.has(data)) {
					this.push(data);
				}
				done();
			}));
			saw.next();
		};

		this.zip = function () {
			var arrays = Array.prototype.slice.call(arguments);
			var index = 0;
			pipeline.push(through2.obj(function (data, enc, done) {
				var retval = [data];
				arrays.forEach(function (array) {
					retval.push(array[index]);
				});
				this.push(retval);
				index++;
				done();
			}));
			saw.next();
		};
	});
};
Ejemplo n.º 8
0
  select: function (filters, options, callback) {
    var language;
    var params = [];
    var query = 'select * from ar a ';
    var supported = this.langs;


    var l = function(x) {
      // if supported is set, use it, else ignore it and join
      if (supported.indexOf(x) > 0 || supported.length == 0) {
        query += ' join ' + x + ' using(chapter,verse)';
      } else {
        console.log('unsupported lang',x);
      }
    };

    if (!callback && typeof (options) === 'function') {
      callback = options;
      options = {};
    }

    language = options.language || 'ar';

    if (language !== 'ar') {
      if (util.isArray(language)) {
        language.forEach(l);
      } else {
        l(language);
      }
    }

    if (filters) {
      Object.keys(filters).forEach(function (k) {
        var f = filters[k];
        if (f) {
          if (util.isArray(f)) {
            params.push(' a.' + k + ' in (' + f.join(',') + ')');
          } else {
            params.push(' a.' + k + '=' + f);
          }
        }
      });

      query += ' where ' + params.join(' and ');
    }

    query += ' order by chapter,verse ';

    if (options) {
      ['limit', 'offset'].forEach(function (x) {
        if (options[x]) {
          query += x + ' ' + options[x] + ' ';
        }
      });
    }

    if (options.debug) {
      console.log(query);
    }

    qurandb.all(query, function (err, res) {
      if (!err && res.length === 0) {
        err = new Error('Selectors out of range ' + query);
      }
      callback(err, res);
    });
  },
Ejemplo n.º 9
0
exports.checkServerIdentity = function checkServerIdentity(host, cert) {
  // Create regexp to much hostnames
  function regexpify(host, wildcards) {
    // Add trailing dot (make hostnames uniform)
    if (!/\.$/.test(host)) host += '.';

    // The same applies to hostname with more than one wildcard,
    // if hostname has wildcard when wildcards are not allowed,
    // or if there are less than two dots after wildcard (i.e. *.com or *d.com)
    //
    // also
    //
    // "The client SHOULD NOT attempt to match a presented identifier in
    // which the wildcard character comprises a label other than the
    // left-most label (e.g., do not match bar.*.example.net)."
    // RFC6125
    if (!wildcards && /\*/.test(host) || /[\.\*].*\*/.test(host) ||
        /\*/.test(host) && !/\*.*\..+\..+/.test(host)) {
      return /$./;
    }

    // Replace wildcard chars with regexp's wildcard and
    // escape all characters that have special meaning in regexps
    // (i.e. '.', '[', '{', '*', and others)
    var re = host.replace(
        /\*([a-z0-9\\-_\.])|[\.,\-\\\^\$+?*\[\]\(\):!\|{}]/g,
        function(all, sub) {
          if (sub) return '[a-z0-9\\-_]*' + (sub === '-' ? '\\-' : sub);
          return '\\' + all;
        });

    return new RegExp('^' + re + '$', 'i');
  }

  var dnsNames = [],
      uriNames = [],
      ips = [],
      matchCN = true,
      valid = false;

  // There're several names to perform check against:
  // CN and altnames in certificate extension
  // (DNS names, IP addresses, and URIs)
  //
  // Walk through altnames and generate lists of those names
  if (cert.subjectaltname) {
    cert.subjectaltname.split(/, /g).forEach(function(altname) {
      if (/^DNS:/.test(altname)) {
        dnsNames.push(altname.slice(4));
      } else if (/^IP Address:/.test(altname)) {
        ips.push(altname.slice(11));
      } else if (/^URI:/.test(altname)) {
        var uri = url.parse(altname.slice(4));
        if (uri) uriNames.push(uri.hostname);
      }
    });
  }

  // If hostname is an IP address, it should be present in the list of IP
  // addresses.
  if (net.isIP(host)) {
    valid = ips.some(function(ip) {
      return ip === host;
    });
  } else {
    // Transform hostname to canonical form
    if (!/\.$/.test(host)) host += '.';

    // Otherwise check all DNS/URI records from certificate
    // (with allowed wildcards)
    dnsNames = dnsNames.map(function(name) {
      return regexpify(name, true);
    });

    // Wildcards ain't allowed in URI names
    uriNames = uriNames.map(function(name) {
      return regexpify(name, false);
    });

    dnsNames = dnsNames.concat(uriNames);

    if (dnsNames.length > 0) matchCN = false;

    // Match against Common Name (CN) only if no supported identifiers are
    // present.
    //
    // "As noted, a client MUST NOT seek a match for a reference identifier
    //  of CN-ID if the presented identifiers include a DNS-ID, SRV-ID,
    //  URI-ID, or any application-specific identifier types supported by the
    //  client."
    // RFC6125
    if (matchCN) {
      var commonNames = cert.subject.CN;
      if (util.isArray(commonNames)) {
        for (var i = 0, k = commonNames.length; i < k; ++i) {
          dnsNames.push(regexpify(commonNames[i], true));
        }
      } else {
        dnsNames.push(regexpify(commonNames, true));
      }
    }

    valid = dnsNames.some(function(re) {
      return re.test(host);
    });
  }

  return valid;
};
Ejemplo n.º 10
0
  self.cloudapi.getGarden(function(err, plants, sensors) {
    var antoine, info, k, params, plant, sample, sensor, udn;

    if (!!err) return self.error(self, err);

    for (k in plants) {
      if (!plants.hasOwnProperty(k)) continue;
      plant = plants[k];

      if (!!sensors[plant.sensor_serial]) {
        sensors[plant.sensor_serial].location_name = plant.location_name || plant.plant_nickname;
        sensors[plant.sensor_serial].location = [ plant.latitude, plant.longitude ];
        sensors[plant.sensor_serial].samples = plant.samples;
      }
      if (!plant.status) plant.status = {};
      if (!plant.status.soil_moisture) plant.status.soil_moisture = {};
      if (!plant.status.fertilizer) plant.status.fertilizer = {};
      if (!plant.status.air_temperature) plant.status.air_temperature = { instruction_key: 'temperature_good' };
      if (!plant.status.light) plant.status.light = { instruction_key: 'light_good' };

      params = { placement       : plant.location_name
               , lastSample      : new Date(plant.last_sample_utc).getTime()
               , needsWater      : plant.status.soil_moisture.status_key !== 'status_ok'                ? 'true' : 'false'
               , needsFertilizer : plant.status.fertilizer.status_key    !== 'status_ok'                ? 'true' : 'false'
               , adviseChange    : plant.status.air_temperature.instruction_key.indexOf('_good') === -1 ? 'true' : 'false'
               , adviseLight     : plant.status.light.instruction_key.indexOf('_good') === -1           ? 'true' : 'false'
               };

      udn = 'flower-power:plant:' + k;
      if (!!devices.devices[udn]) {
        sensor = devices.devices[udn].device;
        sensor.update(sensor, params);
        continue;
      }

      info =  { source: self.deviceID, gateway: self, params: params };
      info.device = { url                          : null
                    , name                         : plant.plant_nickname || plant.description
                    , manufacturer                 : 'Parrot'
                    , model        : { name        : 'Flower Power'
                                     , description : ''
                                     , number      : ''
                                     }
                    , unit         : { serial      : k
                                     , udn         : udn
                                     }
                    };

      info.url = info.device.url;
      info.deviceType = '/device/climate/flower-power/plant';
      info.id = info.device.unit.udn;

      logger.info('device/' + self.deviceID, { name: info.device.name, id: info.device.unit.serial,  params: info.params });
      devices.discover(info);
      self.changed();
    }

    for (k in sensors) {
      if ((!sensors.hasOwnProperty(k)) || (!util.isArray(sensors[k].samples))) continue;
      sample = sensors[k].samples[0];

      // moisture = relativeHumidity * (saturationVaporPressure(temperatureC) / 100);
      antoine = 8.07131 - (1730.63 / (233.426 + sample.air_temperature_celsius));

      // sunlight is PPF (photons per square meter), convert to lux
      // according to http://www.apogeeinstruments.com/conversion-ppf-to-lux/

      params = { location     : utility.location_fuzz(sensors[k].location)
               , placement    : sensors[k].location_name
               , lastSample   : new Date(sample.capture_ts).getTime()
               , moisture     : sample.vwc_percent >= 0 ? sample.vwc_percent * Math.pow(10, antoine - 2) : undefined
               , temperature  : sample.air_temperature_celsius
               , light        : sample.par_umole_m2s * 54
               };

      udn = 'flower-power:sensor:' + k;
      if (!!devices.devices[udn]) {
        sensor = devices.devices[udn].device;
        sensor.update(sensor, params);
        continue;
      }

      info =  { source: self.deviceID, gateway: self, params: params };
      info.device = { url                          : null
                    , name                         : sensors[k].nickname
                    , manufacturer                 : 'Parrot'
                    , model        : { name        : 'Flower Power'
                                     , description : ''
                                     , number      : ''
                                     }
                    , unit         : { serial      : k
                                     , udn         : udn
                                     }
                    };

      info.url = info.device.url;
      info.deviceType = '/device/climate/flower-power/soil';
      info.id = info.device.unit.udn;

      logger.info('device/' + self.deviceID, { name: info.device.name, id: info.device.unit.serial,  params: info.params });
      devices.discover(info);
      self.changed();
    }
  });
Ejemplo n.º 11
0
var util = require('util');

console.log(util.isArray([]));
// true
console.log(util.isArray(new Array));
// true
console.log(util.isArray({}));
// false

Ejemplo n.º 12
0
    Parent.apply(this,arguments)
    this.name=name;
}
util.inherits(Child,Parent);

//Child.prototype=new Parent();
var child=new Child('child',6);
console.log(child.name);
console.log(child.age);
child.say();
console.log("==========================================")

function Person(){
    this.name="person";
    this.child={
        name:"child",
        grandson:{
            name:"gradson"
        }
    }
    this.toString=function(){
        return this.name;
    }
}

var p=new Person();
console.log(util.inspect(p,{showHidden:true,depth:1}));
console.log(util.isArray([])); //是否是一个数组
console.log(util.isRegExp(/\d/));//是否是一个正则
console.log(util.isDate(new Date()));
console.log(util.isError(new Error()));
Ejemplo n.º 13
0
Client.prototype._setQueryOptions = function (options, params, meta, callback) {
  var protocolVersion = this.controlConnection.protocolVersion;
  if (!options.prepare && params && !util.isArray(params) && protocolVersion < 3) {
    //Only Cassandra 2.1 and above supports named parameters
    return callback(new errors.ArgumentError('Named parameters for simple statements are not supported, use prepare flag'));
  }
  var paramsInfo;
  var self = this;
  utils.series([
    function fillRoutingKeys(next) {
      if (options.routingKey || options.routingIndexes || options.routingNames || !meta) {
        //it is filled by the user
        //or it is not prepared
        return next();
      }
      if (util.isArray(meta.partitionKeys)) {
        //the partition keys are provided as part of the metadata
        options.routingIndexes = meta.partitionKeys;
        return next();
      }
      self.metadata.getTable(meta.keyspace, meta.table, function (err, tableInfo) {
        if (err) {
          self.log('warning', util.format('Table %s.%s metadata could not be retrieved', meta.keyspace, meta.table));
          //execute without a routing key
          return next();
        }
        if (!tableInfo) {
          //The data is not there, maybe it is being recreated
          return next();
        }
        options.routingIndexes = tableInfo.partitionKeys.map(function (c) {
          return meta.columnsByName[c.name];
        });
        //Skip parsing metadata next time
        meta.partitionKeys = options.routingIndexes;
        next();
      });
    },
    function adaptParameterNames(next) {
      try {
        if (options.prepare) {
          paramsInfo = utils.adaptNamedParamsPrepared(params, meta.columns);
          //Add the type information provided by the prepared metadata
          options.hints = meta.columns.map(function (c) {
            return c.type;
          });
        }
        else {
          paramsInfo = utils.adaptNamedParamsWithHints(params, options);
        }
      }
      catch (err) {
        return next(err);
      }
      next();
    },
    function adaptParameterTypes(next) {
      if (options.prepare || !util.isArray(options.hints)) {
        return next();
      }
      //Only not prepared with hints
      //Adapting user hints is an async op
      self.metadata.adaptUserHints(self.keyspace, options.hints, next);
    }
  ], function finishSettingOptions(err) {
    if (err) {
      //There was an error setting the query options
      return callback(err);
    }
    try {
      if (typeof options.pageState === 'string') {
        //pageState can be a hex string
        options.pageState = new Buffer(options.pageState, 'hex');
      }
      //noinspection JSAccessibilityCheck
      self._getEncoder().setRoutingKey(paramsInfo.params, options, paramsInfo.keys);
    }
    catch (err) {
      return callback(err);
    }
    callback(null, paramsInfo.params);
  });
};
Ejemplo n.º 14
0
    this.parent={
        name:'aa'
    }
}
Person.prototype.toString=function(){
    console.log(this.name);
}
var p=new Person();
/**
 *
 * 递归的调用inspect
 * showHidden 是否隐藏
 * depth 对象的递归显示深度
 * colors 是否显示颜色
 */
console.log(util.inspect(p,true,0,true));
p.toString();


var ary1=[1,2];
var ary2=[3,4,5];

console.log(ary1.concat(ary2));
//Array.prototype.push.apply(ary1,ary2);
//console.log(ary1);

//Array.prototype.push.apply(ary1,ary2);
//console.log(ary1)

console.log(util.isArray(ary1));
Ejemplo n.º 15
0
 _.each(resultcontainer, function (item) {
   items.push({
     'title': util.isArray(item['dc:title']) ? item['dc:title'][0] : null,
     'uri': util.isArray(item.res) ? item.res[0]._ : null
   })
 })
Ejemplo n.º 16
0
netatmo.prototype.getMeasure = function(options, callback) {
  // Wait until authenticated.
  if (!access_token) {
    return this.on('authenticated', function() {
      this.getMeasure(options, callback);
    });
  }

  if (!options) {
    this.emit("error", new Error("getMeasure 'options' not set."));
    return this;
  }

  if (!options.device_id) {
    this.emit("error", new Error("getMeasure 'device_id' not set."));
    return this;
  }

  if (!options.scale) {
    this.emit("error", new Error("getMeasure 'scale' not set."));
    return this;
  }

  if (!options.type) {
    this.emit("error", new Error("getMeasure 'type' not set."));
    return this;
  }

  if (util.isArray(options.type)) {
    options.type = options.type.join(',');
  }

  // Remove any spaces from the type list if there is any.
  options.type = options.type.replace(/\s/g, '').toLowerCase();


  var url = util.format('%s/api/getmeasure', BASE_URL);

  var form = {
    access_token: access_token,
    device_id: options.device_id,
    scale: options.scale,
    type: options.type,
  };

  if (options) {

    if (options.module_id) {
      form.module_id = options.module_id;
    }

    if (options.date_begin) {
      if (options.date_begin <= 1E10) {
        options.date_begin *= 1E3;
      }

      form.date_begin = moment(options.date_begin).utc().unix();
    }

    if (options.date_end === 'last') {
      form.date_end = 'last';
    } else if (options.date_end) {
      if (options.date_end <= 1E10) {
        options.date_end *= 1E3;
      }
      form.date_end = moment(options.date_end).utc().unix();
    }

    if (options.limit) {
      form.limit = parseInt(options.limit, 10);

      if (form.limit > 1024) {
        form.limit = 1024;
      }
    }

    if (options.optimize !== undefined) {
      form.optimize = !!options.optimize;
    }

    if (options.real_time !== undefined) {
      form.real_time = !!options.real_time;
    }
  }

  request({
    url: url,
    method: "POST",
    form: form,
  }, function(err, response, body) {
    if (err || response.statusCode != 200) {
      console.log(body);
      this.emit("error", new Error("getMeasure error: " + response.statusCode));
      return this;
    }

    body = JSON.parse(body);

    var measure = body.body;

    this.emit('get-measure', err, measure);

    if (callback) {
      return callback(err, measure);
    }

    return this;

  }.bind(this));

  return this;
};
Ejemplo n.º 17
0
module.exports.spawn = function(command, args, options) {
	var i, ptyStream, ptyFds = [];
	// Argument Parsing
	if(!util.isArray(args)) {
		options = args;
		args = [];
	}

	options = extend(true, { stdio: [] }, options, {
		detached: true
	});

	// Opening and configuring the PTY.
	term = pty.open(options);
	if(typeof options.ptyInit === 'function')
		options.ptyInit(term);
	ptyStream = new PtyRwStream(term);

	for(i = 0; i < 3 || i < options.stdio; i++) {
		if((i < 3 && (options.stdio[i] === undefined || options.stdio[i] === null)) ||
				options.stdio[i] === 'pty') {
			options.stdio[i] = term.slave_fd;
			ptyFds.push(i);
		}
	}

	// add a message channel to retrieve error codes from EXEC_HELPER
	// also add file descriptor of the master pty, so the child can close it
	args.unshift(options.stdio.push('pipe') - 1, term.master_fd, command);

	child = child_process.spawn(EXEC_HELPER, args, options);
	child.pty = ptyStream;
	fs.close(term.slave_fd);

	for(i = 0; i < ptyFds.length; i++) {
		child.stdio[ptyFds[i]] = ptyStream;
		switch(ptyFds[i]) {
		case 0: child.stdin = ptyStream; break;
		case 1: child.stdout = ptyStream; break;
		// Dummy Emitter to be compatible to child_process
		case 2: child.stderr = new events.EventEmitter(); break;
		}
	}

	// set up message receiver on the client
	child.stdio.pop().once('data', function(data) {
		var err, errno = - data.readInt32BE(0);
		if(util._errnoException)
			err = util._errnoException(errno, 'spawn ' + command);
		else
			err = new Error('spawn ' + command + ' ' + errno);
		err.path = command;
		err.spawnargs = args.slice(2);
		child.emit('error', err);
		child.removeAllListeners();
		child.kill();
	});

	child.once('exit', function() {
		ptyStream.emit('end');
		ptyStream.end();
	});

	return child;
};
Ejemplo n.º 18
0
Encoder.prototype.setRoutingKey = function (params, options, keys) {
  if (util.isArray(options.routingKey)) {
    if (options.routingKey.length === 1) {
      options.routingKey = options.routingKey[0];
      return;
    }
    //Is a Composite key
    var totalLength = 0;
    options.routingKey.forEach(function (item) {
      totalLength += 2 + item.length + 1;
    });

    var routingKey = new Buffer(totalLength);
    var index = 0;
    options.routingKey.forEach(function (item) {
      routingKey.writeInt16BE(item.length, index);
      index += 2;
      item.copy(routingKey, index);
      index += item.length;
      routingKey[index] = 0;
      index++;
    });
    //Set the buffer containing the contents of the previous Array of buffers as routing key
    options.routingKey = routingKey;
    return;
  }
  if (options.routingKey instanceof Buffer ||
      (!util.isArray(options.routingIndexes) && !util.isArray(options.routingNames)) ||
      !params ||
      params.length === 0) {
    //There is already a routing key
    // or no parameter indexes for routing were provided
    // or there are no parameters to build the routing key
    return;
  }
  var routingKeys = [];
  var hints = options.hints;
  if (!hints) {
    hints = [];
  }
  if (options.routingNames && keys) {
    options.routingNames.forEach(function (name) {
      var paramIndex = keys[name];
      routingKeys.push(this.encode(params[paramIndex], hints[paramIndex]));
    }, this);
  }
  else if (options.routingIndexes) {
    options.routingIndexes.forEach(function (paramIndex) {
      routingKeys.push(this.encode(params[paramIndex], hints[paramIndex]));
    }, this);
  }
  if (routingKeys.length === 0) {
    return;
  }
  if (routingKeys.length === 1) {
    options.routingKey = routingKeys[0];
    return;
  }
  //Its a composite routing key
  options.routingKey = routingKeys;
  this.setRoutingKey(params, options);
};
Ejemplo n.º 19
0
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';
// Flags: --expose-internals
require('../common');
const assert = require('assert');
const util = require('util');
const errors = require('internal/errors');
const context = require('vm').runInNewContext;

// isArray
assert.strictEqual(util.isArray([]), true);
assert.strictEqual(util.isArray(Array()), true);
assert.strictEqual(util.isArray(new Array()), true);
assert.strictEqual(util.isArray(new Array(5)), true);
assert.strictEqual(util.isArray(new Array('with', 'some', 'entries')), true);
assert.strictEqual(util.isArray(context('Array')()), true);
assert.strictEqual(util.isArray({}), false);
assert.strictEqual(util.isArray({ push: function() {} }), false);
assert.strictEqual(util.isArray(/regexp/), false);
assert.strictEqual(util.isArray(new Error()), false);
assert.strictEqual(util.isArray(Object.create(Array.prototype)), false);

// isRegExp
assert.strictEqual(util.isRegExp(/regexp/), true);
assert.strictEqual(util.isRegExp(RegExp(), 'foo'), true);
assert.strictEqual(util.isRegExp(new RegExp()), true);
Ejemplo n.º 20
0
  get: function(o, fields, callback) {
    
    var single, self = this;
    
    if (callback == null) {
      callback = fields;
      fields = null;
    } else if (fields instanceof Array) {
      if (fields.indexOf('id') === -1) {
        fields.unshift('id'); // Ensure ID is included in query
      }
      fields = fields.join(', ');
    }
    
    if (typeof o == 'number') {
      
      // If `o` is number: Convert to object
      o = {id: o};

    } else if (util.isArray(o)) {
      
      // If `o` is an array of params, process args recursively using multi
      var arr = o;
      var multi = this.multi();
      
      for (var i=0; i < arr.length; i++) {
        multi.get(arr[i], fields);
      }
      
      return multi.exec(function(err, results) {
        results = results.filter(function(val) {
          return val; // Filter null values
        });
        callback.call(self, err, results);
      });
      
    } else if (typeof o == 'object') {
      
      // IF `o` is object: Validate without checking required fields
      this.propertyCheck(o);
      
    } else {
      
      return callback.call(self, new Error(util.format("%s: Wrong value for `o` argument", this.className)), null);
      
    }
    
    // Set single if ID is specified in query
    if (o.id) single = true;
      
    var keys = _.keys(o);
      
    // Prevent empty args
    if (keys.length === 0) {
      callback.call(self, new Error(util.format("%s: Empty arguments", this.className)));
      return;
    }
    
    // Get model data & return generated model (if found)
    this.driver.queryWhere({
      condition: keys.join('=? AND ') + '=?',
      columns: fields || undefined,
      params: _.values(o),
      table: this.context,
      appendSql: "ORDER BY id DESC"
    }, function(err, results) {
      if (err) {
        callback.call(self, err, null);
      } else {
        if (results.length === 0) {
          callback.call(self, null, single ? null : []);
        } else if (single) {
          callback.call(self, null, self.createModel(results[0]));
        } else {
          for (var models=[],i=0; i < results.length; i++) {
            models.push(self.createModel(results[i]));
          }
          callback.call(self, null, models);
        }
      }
    });
  },
Ejemplo n.º 21
0
SVGSprite.prototype.useSVGFiles = function(svgFiles) {
	this.files		= util.isArray(svgFiles) ? svgFiles : [];
	this.files.sort();
	return this;
};
Ejemplo n.º 22
0
		Object.keys(params).forEach(function(item) {
			if (util.isArray(params[item])) {
				params[item] = params[item].join(',');
			}
		});
Ejemplo n.º 23
0
var tap = require('../tap');

tap.count(29);

var fs = require('fs');
var util = require('util');

tap.ok(Buffer.isBuffer(fs.readFileSync(__dirname + '/files_fs/hello.txt')), 'fs.readFileSync is buffer')
tap.ok(typeof fs.readFileSync(__dirname + '/files_fs/hello.txt', 'utf-8') == 'string', 'fs.readFileSync accepts encoding')
tap.ok(util.isArray(fs.readdirSync(__dirname + '/files_fs/')), 'fs.readdirSync is array')
// tap.ok(fs.readdirSync(__dirname).indexOf('node_modules') > -1, '# TODO node_modules should exist?');

var output = __dirname + '/files_fs/output.txt';
var output2 = __dirname + '/files_fs/output2.txt';

var peeped = 'YOU MIGHT THINK YOUVE PEEPED THE SCENE\n', havent = 'YOU HAVENT\n';
fs.writeFileSync(output, peeped);
tap.ok(fs.readFileSync(output, 'utf-8') == peeped, 'writeFileSync == readFileSync of same file');
fs.appendFileSync(output, havent);
tap.ok(fs.readFileSync(output, 'utf-8') == peeped + havent, 'appendFileSync works');

tap.ok(fs.readdirSync(__dirname + '/files_fs').indexOf('output.txt') > -1, 'written file exists in readdirSync');
tap.ok(fs.existsSync(output) == true, 'written file exists');
fs.unlinkSync(output)
tap.ok(fs.readdirSync(__dirname + '/files_fs').indexOf('output.txt') == -1, 'unlinked file no longer in readdirSync');
tap.ok(fs.existsSync(output) == false, 'deleted file no longer exists');

fs.writeFileSync(output, 'THE WATERED DOWN ONE, THE ONE YOU KNOW\n');
tap.ok(fs.readdirSync(__dirname + '/files_fs').indexOf('output.txt') > -1, 'written file exists in readdirSync...');
fs.renameSync(output, output2);
tap.ok(fs.existsSync(output) == false, 'renamed file doesnt still exist');
Ejemplo n.º 24
0
BaseAuthHandler.prototype.process = function(username, credentials, req, callback)
{
    if (!this.options) {
        throw new Error('No options specified');
        return;
    }

    if (!this.options.adapter) {
        throw new Error('No adapter(s) were specified as option');
        return;
    }

    var self = this;

    if (!util.isArray(this.options.adapter)) {
        this.options.adapter = [this.options.adapter];
    }

    async.map(this.options.adapter, function(adapter, callback) {

        if ('function' !== typeof adapter.authentication) {
            return callback && callback(
                new Error('Specified adapter does not have a valid authentication method')
            );
        }

        adapter.authentication(username, credentials, function(err, isAuthenticated, entity) {

            if (err) {
                return callback && callback(err);
            }

            if (entity && req.greppy) {

                if (!req.greppy.auth) {
                    req.greppy.auth = {};
                }

                req.greppy.auth.entity = entity;
            }

            callback && callback(null, isAuthenticated);
        });

    }, function(err, results) {

        if (err) {

            if ('function' === typeof self.options.error) {
                self.options.error();
            }

            return callback && callback(err);
        }

        var success = false;

        results.forEach(function(result) {

            if (true === result) {
                success = true;
            }
        });

        logger.debug(
            'Authentification ' + (success ? 'succeeded' : 'failed')
            + ' for ' + (username ? username.green.bold : '[none]')
        );

        if (false === success && 'function' === typeof self.options.error) {
            self.options.error(username);
        }

        if (true === success && 'function' === typeof self.options.success) {
            self.options.success(username);
        }

        self.post(success, function() {
            return callback && callback(null, success);
        });
    });
};
Ejemplo n.º 25
0
module.exports = function (options) {
  if (!options)
    throw new Error('no options provided');
  else if (!options.rate || !options.callback || !options.done)
    throw new Error('missing required options');
  else if (!options.duration && !options.times)
    throw new Error('missing duration AND times, provide one or both');

  var rate = options.rate,
    duration = options.duration,
    times = Number(options.times || Infinity),
    maxPending = Number(options.max || Infinity),
    progress = options.progress,
    callback = options.callback,
    done = options.done;

  var started = 0,
    finished = 0,
    pending = 0,
    paused = false,
    errors = [],
    results = [];

  if (duration) {
    var d = duration.split(' ');
    duration = ms(Number(d[0]))[d[1]] / getRate(rate);
  }

  var max = (Number(duration) && duration < times) ? duration : times;

  if (progress) {
    var barFormat = (util.isArray(progress)) ? progress[0] : '[:bar] :percent | :current/:total | time: :elapsed | eta: :eta',
      barOpts = (util.isArray(progress)) ? progress[1] : {
        width: 20
      };
    barOpts.total = times || (getRate(rate) / duration);
    var bar = new Progress(barFormat, barOpts);
  }

  function getRate(rate) {
    if (typeof rate === 'string' && rate.indexOf('/') !== -1) {
      var r = rate.split('/');
      return ms(1)[r[1]] / r[0];
    } else if (typeof rate === 'function')
      return getRate(rate());
    else
      throw new Error('invalid rate: ', rate);
  }

  function start() {
    if (started >= max)
      return;
    started += 1;
    pending += 1;
    callback.call({
      pause: pause,
      resume: resume,
      stop: stop
    }, next);
  }

  function pause() {
    paused = true;
    clearInterval(interval);
  }

  function resume() {
    paused = false;
    if (started < max)
      interval = setInterval(start, getRate(rate));
  }

  function stop() {
    clearInterval(interval);
    return done(errors, results);
  }

  function next(err, result) {
    finished += 1;
    pending -= 1;

    errors.push(err);
    results.push(result);

    if (progress)
      bar.tick();

    if (finished >= max)
      return stop();
    else if (!paused && pending > maxPending)
      return pause();
    else if (paused && pending <= maxPending)
      return resume();

    var nextRate = getRate(rate);

    if (_rate !== nextRate) {
      _rate = nextRate;
      pause();
      resume();
    }
  }

  var _rate = getRate(rate);
  var interval = setInterval(start, _rate);
}
Ejemplo n.º 26
0
/**
 * Process the rule (unquote if required).
 *
 * Note: This is a recursive method (through `processArrayValue` and `processObjectValue`!
 * Whenever an object/array-value is encountered, this method is re-invoked on that value.
 *
 * @private
 * @param  {Object} rule Rule definition
 * @return {String}      JSON String to concatenate to the resulting TSS
 */
function processRule(rule, level) {
	var isObject = false,
		specialValues = {},
		placeholderPrefix = '-stss-ph',
		phIndex = 0,
		prettyTabs = '',
		body, ph, name, value;
	
	if (rule.comment) {
		return '';
	} else if (!rule.selector) {
		isObject = true;
	} 
		
	body = rule.body || {};	

	// Level is purely meant for "prettification"
	if (level === undefined) {
		// The first call, still on root-level
		level = 0;
	} else {
		// Add a tab per level
		for (; prettyTabs.length < level;) {
			prettyTabs += '\t';
		}
	}

	for (name in body) {
		value = body[name];
		
		// Value if an array
		if (util.isArray(value)) {
			phIndex++;
			ph = placeholderPrefix + phIndex;
			specialValues[ph] = processArrayValue(value, level);
			body[name] = ph;

		// Value is an object
		} else if (typeof value === 'object') {
			phIndex++;
			ph = placeholderPrefix + phIndex;
			specialValues[ph] = processObjectValue(value, rule, level);
			body[name] = ph;
		}
	}

	if (rule.selector === '-stss-value') {
		body = rule.unquote ? rule.value : '"' + rule.value + '"';
		return body;
	}

	body = JSON.stringify(body, null, (prettyTabs + '\t'));
	if (isObject) {
		body = body.substr(0, body.length - 1) + prettyTabs + '}';
	}

	for (ph in specialValues) {
		value = specialValues[ph];
		body = body.replace('"' + ph + '"', value);
	}

	if (rule.unquote) {
		rule.unquote.forEach(function(name) {
			body = body.replace(reDeclJSON(name), "$1: $4");
		});
	}

	// Unquote names (TODO: should be option?)
	body = body.replace(rePropName, "$3:");

	if (rule.selector) {
		// Root selectors
		return '"' + rule.selector + '"' + ": " + body + ",\n"; //prettify option
	} else {
		// Property objects
		return body;
	}
}
Ejemplo n.º 27
0
 it("is case insensitive", function(){
   var result = moby.search("DOG")
   assert(util.isArray(result))
   assert(result.length > 0)
 })
Ejemplo n.º 28
0
Query.prototype._makeConditionField = function(condition, field, type) {
    var self = this;

    // using name to find, not column
    var _field = field;
    field = λ.find(this.model._fieldsObject, function(f) {
        return f.name === _field;
    });
    if(undefined === field) {
        return "";
    }

    // if it's not an object
    if(typeof condition !== "object" || field.type.name === "Json") {
        if(field.type.name === "Json") {
            console.warn(colors.rainbow("!!! WARNING: YOU'D BETTER NOT USE JSON FIELD TO QUERY !!!"));
        }

        condition = field.type.restore(condition);

        var sql = "`" + field.column + "` = ";
        sql += (field.type.needQuotes ? "\"" + escaper.escape(condition) + "\"" : condition);

        return sql;
    }

    // if it's null
    if(condition === null) {
        var sql = "`" + field.column + "` IS NULL";
        return sql;
    }

    var size = λ.size(condition);
    var keys = λ.keys(condition);
    if(!size) {
        return "";
    }

    // get each condition strings
    var conditionStrings = [];
    var valueMapper = function(value) {
        return self._makeConditionField(value, field.name, type);
    };
    var _inMapper = function(value) {
        value = field.type.restore(value);
        return field.type.needQuotes ?
            ("\"" + escaper.escape(value) + "\"") :
            value;
    };
    var cdtMapper = function(symbol, value) {
        // add null support
        if(value === null) {
            if(symbol === "=") {
                conditionStrings.push("`" + field.column + "` IS NULL");
                return;
            } else if(symbol === "!=") {
                conditionStrings.push("`" + field.column + "` IS NOT NULL");
                return;
            }
        }

        value = field.type.restore(value);
        var cdt = util.format("`%s` %s %s", field.column, symbol,
            (field.type.needQuotes ? "\"" + escaper.escape(value) + "\"" : value));

        conditionStrings.push(cdt);
    };
    for(var i = 0; i < keys.length; i++) {
        var key = keys[i].toLowerCase();

        var value = condition[keys[i]];
        var symbol = null;

        // and / or logic
        if(key === "$and" || key === "$or") {
            // array supported
            //   eg. $or: [ "127.0.0.1", "localhost" ]
            if(!util.isArray(value)) {
                value = [ value ];
            }

            var type = key.substr(1);
            var temp = value.map(valueMapper);

            var tempString = "";
            for(var i = 0; i < temp.length; i++) {
                if(i) {
                    tempString += " " + type.toUpperCase() + " ";
                }

                tempString += temp[i];
            }

            conditionStrings.push(tempString);

            continue;
        }

        // general operations...
        switch(key) {
            case "$eq":
            case "===": symbol = "="; break;

            case "$neq":
            case "!==": symbol = "!="; break;

            case "$lt":
            case "<": symbol = "<"; break;

            case "$gt":
            case ">": symbol = ">"; break;

            case "$lte":
            case "<=": symbol = "<="; break;

            case "$gte":
            case ">=": symbol = ">="; break;

            case "$like": symbol = "LIKE"; break;

            // in... (if necessary)
            case "$in": symbol = "IN"; break;

            default: break;
        }

        // symbol is general operation above
        if(symbol) {
            // IN
            if(symbol === "IN") {
                var str = "`" + field.column + "` IN (";
                str += value.map(_inMapper).join(", ");
                str += ")";
                conditionStrings.push(str);
                continue;
            }

            // array supported:
            //   eg. { field: { $neq: [ "123", "456" ] } }
            if(!util.isArray(value)) {
                value = [ value ];
            }

            value.map(cdtMapper.bind(null, symbol));

            continue;
        }

        // TODO: maybe other operations...
    }

    // splice conditions
    var result = "";
    for(var i = 0; i < conditionStrings.length; i++) {
        if(i) {
            result += " " + type.toUpperCase() + " ";
        }

        result += conditionStrings[i];
    }

    return "(" + result + ")";
};
Ejemplo n.º 29
0
 it("returns an empty array when given an empty string", function(){
   var result = moby.search("")
   assert(util.isArray(result))
   assert.equal(result.length, 0)
 })
Ejemplo n.º 30
0
ServerResponse.prototype.writeHead = function(statusCode) {
  var reasonPhrase, headers, headerIndex;

  if (util.isString(arguments[1])) {
    reasonPhrase = arguments[1];
    headerIndex = 2;
  } else {
    reasonPhrase = STATUS_CODES[statusCode] || 'unknown';
    headerIndex = 1;
  }
  this.statusCode = statusCode;

  var obj = arguments[headerIndex];

  if (obj && this._headers) {
    // Slow-case: when progressive API and header fields are passed.
    headers = this._renderHeaders();

    if (util.isArray(obj)) {
      // handle array case
      // TODO: remove when array is no longer accepted
      var field;
      for (var i = 0, len = obj.length; i < len; ++i) {
        field = obj[i][0];
        if (!util.isUndefined(headers[field])) {
          obj.push([field, headers[field]]);
        }
      }
      headers = obj;

    } else {
      // handle object case
      var keys = Object.keys(obj);
      for (var i = 0; i < keys.length; i++) {
        var k = keys[i];
        if (k) headers[k] = obj[k];
      }
    }
  } else if (this._headers) {
    // only progressive api is used
    headers = this._renderHeaders();
  } else {
    // only writeHead() called
    headers = obj;
  }

  var statusLine = 'HTTP/1.1 ' + statusCode.toString() + ' ' +
                   reasonPhrase + CRLF;

  if (statusCode === 204 || statusCode === 304 ||
      (100 <= statusCode && statusCode <= 199)) {
    // RFC 2616, 10.2.5:
    // The 204 response MUST NOT include a message-body, and thus is always
    // terminated by the first empty line after the header fields.
    // RFC 2616, 10.3.5:
    // The 304 response MUST NOT contain a message-body, and thus is always
    // terminated by the first empty line after the header fields.
    // RFC 2616, 10.1 Informational 1xx:
    // This class of status code indicates a provisional response,
    // consisting only of the Status-Line and optional headers, and is
    // terminated by an empty line.
    this._hasBody = false;
  }

  // don't keep alive connections where the client expects 100 Continue
  // but we sent a final status; they may put extra bytes on the wire.
  if (this._expect_continue && !this._sent100) {
    this.shouldKeepAlive = false;
  }

  this._storeHeader(statusLine, headers);
};