Example #1
0
exports.map = function(events, str){
  var a = normalize(str);
  var ret = [];

  // no events
  if (!events) return ret;

  // object
  if ('object' == type(events)) {
    for (var k in events) {
      var item = events[k];
      var b = normalize(k);
      if (b == a) ret.push(item);
    }
  }

  // array
  if ('array' == type(events)) {
    if (!events.length) return ret;
    if (!events[0].key) return ret;

    for (var i = 0; i < events.length; ++i) {
      var item = events[i];
      var b = normalize(item.key);
      if (b == a) ret.push(item.value);
    }
  }

  return ret;
};
Example #2
0
exports = module.exports = function jsPDF(orientation, unit, format) {
  // Defaults
  if(type(orientation) === "undefined") orientation = "p";
  if(type(unit) === "undefined") unit = "mm";
  if(type(format) === "undefined") format = "a4";

  this.orientation = orientation.toString().toLowerCase();
  this.unit = unit.toString().toLowerCase();
  this.format = format.toString().toLowerCase();

  this.content = [];
  this.contentLength = 0;
  this.textColor = '0 g';
  this.drawColor = '0 G';
  this.page = 0;
  this.pages = [];
  this.objectNumber = 2; // 'n' Current object number
  this.outOfPages = false; // switches where out() prints. outToPages true = push to pages obj. outToPages false = doc builder content
  this.offsets = []; // List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
  this.fonts = {}; // collection of font objects, where key is fontKey - a dynamically created label for a given font.
  this.fontmap = {}; // mapping structure fontName > fontStyle > font key - performance layer. See addFont()
  this.activeFontSize = 16;
  this.activeFontKey; // will be string representing the KEY of the font as combination of fontName + fontStyle
  this.lineWidth = 0.200025; // 2mm
  this.documentProperties = {'title':'','subject':'','author':'','keywords':'','creator':''};
  this.lineCapID = 0;
  this.lineJoinID = 0;
  this.k = chooseScale(unit);

  // Dimensions are stored as user units and converted to points on output
  if(pageFormats[this.format]) {
    this.pageHeight = pageFormats[this.format][1] / this.k;
    this.pageWidth = pageFormats[this.format][0] / this.k;
  }
  else {
    try {
      this.pageHeight = format[1];
      this.pageWidth = format[0];
    }
    catch (e) {
      throw new Error("Invalid format: "+format);
    }
  }

  if(this.orientation === "p" || orientation === "portrait") {
    this.orientation = "p";
    if(this.pageWidth > this.pageHeight) {
      swapValues.call(this, "pageWidth", "pageHeight");
    }
  }
  else if (this.orientation === 'l' || this.orientation === 'landscape') {
    this.orientation = 'l';
    if(this.pageWidth < this.pageHeight) {
      swapValues.call(this, "pageWidth", "pageHeight");
    }
  }
  else {
    throw new Error("Invalid orientation: "+this.orientation);
  };
};
Example #3
0
Skybox.prototype.url = function (path, q) {
    var i, key, params = {},
        str = "";

    // Setup scheme://host:port/path
    str += ('https:' === document.location.protocol ? "https://" : "http://");
    str += (isEmpty(this.host) ? "localhost" : this.host);
    str += (isEmpty(this.port) || this.port === 80 ? "" : ":" + this.port);
    str += path;

    // Flatten query parameters.
    if (type(q) === "object") {
        for (key in q) {
            if (q.hasOwnProperty(key)) {
                if (type(q[key]) === "object") {
                    for (i in q[key]) {
                        if (q[key].hasOwnProperty(i)) {
                            params[key + "." + i] = q[key][i];
                        }
                    }
                } else {
                    params[key] = q[key];
                }
            }
        }
    }

    // Append parameters to the end, if there are any.
    if (!isEmpty(params)) {
        str += "?" + querystring.stringify(params);
    }

    return str;
};
Example #4
0
 it('should match numbers', function(){
   assert('number' === type(12));
   assert('number' === type(1.0));
   assert('number' === type(-5));
   assert('number' === type(new Number(123)));
   assert('number' === type(Infinity));
 });
Example #5
0
exports.$set = function $set(obj, path, val){
  var key = path.split('.').pop();
  obj = dot.parent(obj, path, true);

  switch (type(obj)) {
    case 'object':
      if (!eql(obj[key], val)) {
        return function(){
          obj[key] = val;
          return val;
        };
      }
      break;

    case 'array':
      if (numeric(key)) {
        if (!eql(obj[key], val)) {
          return function(){
            obj[key] = val;
            return val;
          };
        }
      } else {
        throw new Error('can\'t append to array using string field name [' + key + ']');
      }
      break;

    default:
      throw new Error('$set only supports object not ' + type(obj));
  }
};
Example #6
0
exports.map = function(obj, str){
  var a = normalize(str);
  var ret = [];

  // noop
  if (!obj) return ret;

  // object
  if ('object' == type(obj)) {
    for (var k in obj) {
      var item = obj[k];
      var b = normalize(k);
      if (b == a) ret.push(item);
    }
  }

  // array
  if ('array' == type(obj)) {
    if (!obj.length) return ret;
    if (!obj[0].key) return ret;

    for (var i = 0; i < obj.length; ++i) {
      var item = obj[i];
      var b = normalize(item.key);
      if (b == a) ret.push(item.value);
    }
  }

  return ret;
};
Example #7
0
  track : function (event, properties, context, callback) {
    if (!this.initialized) return;

    // Allow for not passing context, but passing a callback.
    if (type(context) === 'function') {
      callback = context;
      context = null;
    }

    // Allow for not passing properties, but passing a callback.
    if (type(properties) === 'function') {
      callback = properties;
      properties = null;
    }

    // Call `track` on all of our enabled providers that support it.
    each(this.providers, function (provider) {
      if (provider.track && utils.isEnabled(provider, context)) {
        var args = [event, clone(properties), clone(context)];

        if (provider.ready) provider.track.apply(provider, args);
        else provider.enqueue('track', args);
      }
    });

    if (callback && type(callback) === 'function') {
      setTimeout(callback, this.timeout);
    }
  },
Example #8
0
exports.$inc = function $inc(obj, path, inc){
  if ('number' != type(inc)) {
    throw new Error('Modifier $inc allowed for numbers only');
  }

  obj = dot.parent(obj, path, true);
  var key = path.split('.').pop();

  switch (type(obj)) {
    case 'array':
    case 'object':
      if (obj.hasOwnProperty(key)) {
        if ('number' != type(obj[key])) {
          throw new Error('Cannot apply $inc modifier to non-number');
        }

        return function(){
          obj[key] += inc;
          return inc;
        };
      } else if('object' == type(obj) || numeric(key)){
        return function(){
          obj[key] = inc;
          return inc;
        };
      } else {
        throw new Error('can\'t append to array using string field name [' + key + ']');
      }
      break;

    default:
      throw new Error('Cannot apply $inc modifier to non-number');
  }
};
Example #9
0
  track : function (event, properties, options, callback) {
    if (!this.initialized) return;

    // Allow for optional arguments.
    if (type(options) === 'function') {
      callback = options;
      options = undefined;
    }
    if (type(properties) === 'function') {
      callback = properties;
      properties = undefined;
    }

    // Call `track` on all of our enabled providers that support it.
    each(this.providers, function (provider) {
      if (provider.track && isEnabled(provider, options)) {
        var args = [event, clone(properties), clone(options)];
        if (provider.ready) {
          provider.track.apply(provider, args);
        } else {
          provider.enqueue('track', args);
        }
      }
    });

    if (callback && type(callback) === 'function') {
      setTimeout(callback, this.timeout);
    }
  },
Example #10
0
	each(Object.keys(_schema), function(_key) {

		properties  = getSchemaProperties(_schema[_key]);
		objectData  = {};
		defaultData = type(properties._default) != 'undefined' || _disableAutoDefaults ? properties._default : properties._typeDefault;

		// Find non system keys (probably an object)
		each(Object.keys(properties), function(_propertyKey){

			if (/^[^_]/.test(_propertyKey)) {

				objectData[_propertyKey] = properties[_propertyKey];

			}

		});

		// If it's mandatory or it's optional and there's data
		if (properties._optional == false || (properties._optional == true && type(_data[_key]) != 'undefined')) {

			_schema[_key] = (isEmpty(objectData) && (type(_data[_key]) != 'object' || properties._type == Object)) || properties._type == '*'
			              ? cast(_data[_key], properties._type, defaultData, properties._values, properties)
			              : parseResult(objectData, cast(_data[_key], Object, {}), _disableAutoDefaults)

		}  else {

			delete _schema[_key];

		}

	});
Example #11
0
// path 支持字符串和数组两种形式
// 数组的规则为 ['/a/b', 'c', {d: 1, e: 2}] => '#!/a/b/c?d=1!!e=2'
function Context(path, state) {
    var hashbang = location.hash.length === 0 || /^#!/.test(location.hash),
        item,
        queries = {},
        i;

    if (type(path) === 'array' && path.length >= 0) {
        this.path = '';
        while (path.length) {
            item = path.shift();
            if (type(item) === 'string') {
                this.path += normalize(item);
            }
            else {
                queries = extend(queries, item);
            }
        }
        this.path += (this.path.indexOf('?') < 0 ? '?' : '&') + parseParam(queries);
    }
    else {
        this.path = normalize(path);
    }

    path = this.path;

    this.state = state || {};
    this.target = path ? '#' + (hashbang ? '!' : '') + path : path;

    i = path.indexOf('?');
    this.pathname = ~i ? path.slice(0, i) : path;
    this.search = ~i ? path.slice(i) : '';
    this.queries = parseSearch(this.search);
    this.params = {};
    this.dispatch = true;
}
Collection.prototype.remove = function(id, silent){
  var _this = this;
  var splice = function(i, m){
    if (i < 0) return;
    _this.models.splice(i, 1);
    _this.emit('remove', m);
  };

  var getIndex = function(model){
    splice(_this.indexOf(model), model);
  };

  if (type(id) == 'array'){
    each(id, function(obj){
     getIndex(obj);
    });
  } else if (type(id) == 'object') {
    getIndex(id);
  } else if (type(id) == 'string'){
    getIndex(this.find(function(m){
      return m._id === id;
    }));
  }

};
Example #13
0
function apply(_schema, _data, _disableAutoDefaults) {

	var schema = type(_schema) == 'object' ? clone(_schema) : {}
	  , data   = type(_data)   == 'object' ? clone(_data)   : {}

	return isEmpty(schema) ? _data : parseResult(schema, data, _disableAutoDefaults);

}
Example #14
0
/**
    @example
    router('*', handler);
    router('/user/:id', load, user);
    router('/user/' + user.id, {some: 'thing'});
    router('/user/' + user.id);
    router(options);
 */
function router(path, state) {
    if (type(state) === 'function') {
        router.bind.apply(router, arguments);
    } else if (type(path) === 'string') {
        router.route(path, state);
    } else {
        router.start(path);
    }
}
Example #15
0
// (any, any, [array]) -> boolean
function equals(a, b, memos){
  // All identical values are equivalent
  if (a === b) return true
  var fnA = types[type(a)]
  var fnB = types[type(b)]
  return fnA && fnA === fnB
    ? fnA(a, b, memos)
    : false
}
Example #16
0
function pull(arr, vals, pulled){
  var indexes = [];

  for (var a = 0; a < arr.length; a++) {
    var val = arr[a];

    for (var i = 0; i < vals.length; i++) {
      var matcher = vals[i];
      if ('object' == type(matcher)) {
        // we only are only interested in obj <-> obj comparisons
        if ('object' == type(val)) {
          var match = false;

          if (keys(matcher).length) {
            for (var i in matcher) {
              if (matcher.hasOwnProperty(i)) {
                // we need at least one matching key to pull
                if (eql(matcher[i], val[i])) {
                  match = true;
                } else {
                  // if a single key doesn't match we move on
                  match = false;
                  break;
                }
              }
            }
          } else if (!keys(val).length) {
            // pull `{}` matches [{}]
            match = true;
          }

          if (match) {
            indexes.push(a);
            pulled.push(val);
            continue;
          }
        } else {
          debug('ignoring pull match against object');
        }
      } else {
        if (eql(matcher, val)) {
          indexes.push(a);
          pulled.push(val);
          continue;
        }
      }
    }
  }

  return function(){
    for (var i = 0; i < indexes.length; i++) {
      var index = indexes[i];
      arr.splice(index - i, 1);
    }
  };
}
Example #17
0
Schema.prototype.addIndex = function(name, field, opts) {
  if (type(name) != 'string') throw new TypeError('`name` is required');
  if (type(field) != 'string') throw new TypeError('`field` is required');
  var store = this._current.store;
  var index = { store: store, name: name, field: field, opts: opts || {} };
  if (store.indexes[name]) throw new TypeError('index is already defined');
  store.indexes[name] = index;
  this._versions[this.getVersion()].indexes.push(index);
  return this;
};
Example #18
0
function type(el) {
  var group = 'array' == typeOf(el) || 'object' == typeOf(el);
  if (group) el = el[0];
  var name = el.nodeName.toLowerCase();
  var type = el.getAttribute('type');

  if (group && type && 'radio' == type.toLowerCase()) return 'radiogroup';
  if ('input' == name && type && 'checkbox' == type.toLowerCase()) return 'checkbox';
  if ('input' == name && type && 'radio' == type.toLowerCase()) return 'radio';
  if ('select' == name) return 'select';
  return name;
}
Example #19
0
  identify : function (userId, traits, options, callback) {
    if (!this.initialized) return;

    // Allow for optional arguments.
    if (type(options) === 'function') {
      callback = options;
      options = undefined;
    }
    if (type(traits) === 'function') {
      callback = traits;
      traits = undefined;
    }
    if (type(userId) === 'object') {
      if (traits && type(traits) === 'function') callback = traits;
      traits = userId;
      userId = undefined;
    }

    // Use our cookied ID if they didn't provide one.
    if (userId === undefined || user === null) userId = user.id();

    // Update the cookie with the new userId and traits.
    var alias = user.update(userId, traits);

    // Clone `traits` before we manipulate it, so we don't do anything uncouth
    // and take the user.traits() so anonymous users carry over traits.
    traits = clone(user.traits());

    // Convert dates from more types of input into Date objects.
    if (traits && traits.created) traits.created = newDate(traits.created);
    if (traits && traits.company && traits.company.created) {
      traits.company.created = newDate(traits.company.created);
    }

    // Call `identify` on all of our enabled providers that support it.
    each(this.providers, function (provider) {
      if (provider.identify && isEnabled(provider, options)) {
        var args = [userId, clone(traits), clone(options)];
        if (provider.ready) {
          provider.identify.apply(provider, args);
        } else {
          provider.enqueue('identify', args);
        }
      }
    });

    // If we should alias, go ahead and do it.
    // if (alias) this.alias(userId);

    if (callback && type(callback) === 'function') {
      setTimeout(callback, this.timeout);
    }
  },
Example #20
0
function eql(a, b){
  var compare = type(a);

  // sanity check
  if (compare != type(b)) return false;
  if (a === b) return true;

  // compare
  return (compare = eql[compare])
    ? compare(a, b)
    : a == b;
}
Example #21
0
function CIF_var (rtype, types, numFixedArgs, abi) {

  // the return and arg types are expected to be coerced at this point...
  assert(!!rtype, 'expected a return "type" object as the first argument');
  assert(Array.isArray(types), 'expected an Array of arg "type" objects as the second argument');
  assert(numFixedArgs >= 1, 'expected the number of fixed arguments to be at least 1');

  // the buffer that will contain the return `ffi_cif *` instance
  var cif = new Buffer(FFI_CIF_SIZE);

  var numTotalArgs = types.length;
  var _argtypesptr = new Buffer(numTotalArgs * POINTER_SIZE);
  var _rtypeptr = Type(rtype);

  for (var i = 0; i < numTotalArgs; i++) {
    var ffiType = Type(types[i]);
    _argtypesptr.writePointer(ffiType, i * POINTER_SIZE);
  }

  // prevent GC of the arg type and rtn type buffers (not sure if this is required)
  cif.rtnTypePtr = _rtypeptr;
  cif.argTypesPtr = _argtypesptr;

  if (typeof abi === 'undefined') {
    abi = FFI_DEFAULT_ABI;
  }

  var status = ffi_prep_cif_var(cif, numFixedArgs, numTotalArgs, _rtypeptr, _argtypesptr, abi)

  if (status !== FFI_OK) {
    switch (status) {
      case FFI_BAD_TYPEDEF:
        var errtypedef = new Error('ffi_prep_cif_var() returned an FFI_BAD_TYPEDEF error');
        errtypedef.code = 'FFI_BAD_TYPEDEF';
        errtypedef.errno = status;
        throw errtypedef;
        break;
      case FFI_BAD_ABI:
        var errabi = new Error('ffi_prep_cif_var() returned an FFI_BAD_ABI error');
        errabi.code = 'FFI_BAD_ABI';
        errabi.errno = status;
        throw errabi;
        break;
      default:
        var err = new Error('ffi_prep_cif_var() returned an error: ' + status);
        err.errno = status;
        throw err;
        break;
    }
  }
  return cif;
}
Example #22
0
exports.$pullAll = function $pullAll(obj, path, val){
  if ('array' != type(val)) {
    throw new Error('Modifier $pushAll/pullAll allowed for arrays only');
  }

  obj = dot.parent(obj, path, true);
  var key = path.split('.').pop();
  var t = type(obj);

  switch (t) {
    case 'object':
      if (obj.hasOwnProperty(key)) {
        if ('array' == type(obj[key])) {
          var pulled = [];
          var splice = pull(obj[key], val, pulled);
          if (pulled.length) {
            return function(){
              splice();
              return pulled;
            };
          }
        } else {
          throw new Error('Cannot apply $pull/$pullAll modifier to non-array');
        }
      }
      break;

    case 'array':
      if (obj.hasOwnProperty(key)) {
        if ('array' == type(obj[key])) {
          var pulled = [];
          var splice = pull(obj[key], val, pulled);
          if (pulled.length) {
            return function(){
              splice();
              return pulled;
            };
          }
        } else {
          throw new Error('Cannot apply $pull/$pullAll modifier to non-array');
        }
      } else {
        debug('ignoring pull to non array');
      }
      break;

    default:
      if ('undefined' != t) {
        throw new Error('LEFT_SUBFIELD only supports Object: hello not: ' + t);
      }
  }
};
Example #23
0
function plan (code, callback) {
  debug('%s', code);

  if ('function' != type(callback)) {
    throw new Error('Missing callback');
  }

  if ('undefined' == type(code)) {
    return callback(new Error('Missing plan code'));
  }

  this.request('get', '/plans/' + code, callback);
}
Example #24
0
function serialize(params, obj, traditional, scope){
  var array = type(obj) === 'array';
  for (var key in obj) {
    var value = obj[key];

    if (scope) key = traditional ? scope : scope + '[' + (array ? '' : key) + ']'
    // handle data in serializeArray() format
    if (!scope && array) params.add(value.name, value.value)
    // recurse into nested objects
    else if (traditional ? (type(value) === 'array') : (type(value) === 'object'))
      serialize(params, value, traditional, key)
    else params.add(key, value)
  }
}
Example #25
0
    Model.prototype[name] = function (val) {

      if(0 == arguments.length) {

        if(type(getter) === 'function') return getter.call(this, get.call(this));

        return get.call(this);
      }

      if(type(setter) === 'function') val = setter.apply(this, arguments);

      set.call(this, val);

    };
Example #26
0
function getSchemaProperties(_properties) {

	var properties

	properties               = type(_properties) == 'object' ? _properties : /function|string/i.test(type(_properties)) ? { _type : _properties } : {};
	properties._type         = properties.hasOwnProperty('_type') ? properties._type : Object;
	properties._optional     = cast(properties['_optional'], Boolean, false);
	properties._default      = properties['_default'];
	properties._values       = cast(properties['_values'], Array, []);
	properties._typeAsString = type(properties._type) == 'string' ? properties._type : cast(properties._type, String, '').match(/^function ([^\(]*)\(\)/)[1];
	properties._typeDefault  = getDefault(properties._typeAsString);

	return properties;

}
Example #27
0
function Cast(from, to) {
  if (1 == arguments.length) {
    to = type(from);
    from = false;
  } else {
    from = type(from);
    to = type(to);
  }

  return function cast(value) {
    return !from || type(value) == from
      ? typecast(value, to)
      : value;
  }
}
Example #28
0
module.exports = function(instance, schema, ctx){
  if (!('array' == type(instance))) return;
  var items = schema.items
    , additional = schema.additionalItems

  // per sec. 8.2.2 of spec
  if (undefined === items) items = {};
  if (undefined === additional) additional = {};

  var itemstype = type(items)
    , additionaltype = type(additional)

  if (!('object' == itemstype) && !('array' == itemstype)) return;

  if ('array' == itemstype){
    var subsch, subctx
    for (var i=0;i<instance.length;++i){
      subsch = items[i]
      if ('object' == type(subsch)) {
        subctx = ctx.subcontext([i],['items',i])
        ctx.assert( this.validate(instance[i], subsch, subctx ),
                    "item " + (i+1) + " is invalid"
                  ).property('items');

      } else if ('boolean' == additionaltype) {
        ctx.assert(additional,
                   "contains additional items"
                  ).property('additionalItems')
                   .expected(additional)
                   .actual(true);

      } else if ('object' == additionaltype) {
        subctx = ctx.subcontext([i],['additionalItems'])
        ctx.assert( this.validate( instance[i], additional, subctx ),
                     "additional item " + (i+1) + " is invalid"
                  ).property('additionalItems');
      }
    }
  } else if ('object' == itemstype) {
     var subctx
     for (var i=0;i<instance.length;++i){
       subctx = ctx.subcontext([i],['items'])
       ctx.assert( this.validate( instance[i], items, subctx ),
                   "item " + (i+1) + " is invalid"
                 ).property('items');
     }
  }
}
Example #29
0
exports.$pushAll = function $pushAll(obj, path, val){
  if ('array' != type(val)) {
    throw new Error('Modifier $pushAll/pullAll allowed for arrays only');
  }

  obj = dot.parent(obj, path, true);
  var key = path.split('.').pop();

  switch (type(obj)) {
    case 'object':
      if (obj.hasOwnProperty(key)) {
        if ('array' == type(obj[key])) {
          return function(){
            obj[key].push.apply(obj[key], val);
            return val;
          };
        } else {
          throw new Error('Cannot apply $push/$pushAll modifier to non-array');
        }
      } else {
        return function(){
          obj[key] = val;
          return val;
        };
      }
      break;

    case 'array':
      if (obj.hasOwnProperty(key)) {
        if ('array' == type(obj[key])) {
          return function(){
            obj[key].push.apply(obj[key], val);
            return val;
          };
        } else {
          throw new Error('Cannot apply $push/$pushAll modifier to non-array');
        }
      } else if (numeric(key)) {
        return function(){
          obj[key] = val;
          return val;
        };
      } else {
        throw new Error('can\'t append to array using string field name [' + key + ']');
      }
      break;
  }
};
Example #30
0
List.prototype.removeClass = function(name){
  var el;

  if ('regexp' == type(name)) {
    for (var i = 0; i < this.els.length; ++i) {
      el = this.els[i];
      el._classes = el._classes || classes(el);
      var arr = el._classes.array();
      for (var j = 0; j < arr.length; j++) {
        if (name.test(arr[j])) {
          el._classes.remove(arr[j]);
        }
      }
    }
    return this;
  }

  for (var i = 0; i < this.els.length; ++i) {
    el = this.els[i];
    el._classes = el._classes || classes(el);
    el._classes.remove(name);
  }

  return this;
};