Example #1
0
            }

            if (!(/^2/.test('' + response.statusCode))) {
                return reject(response.statusCode);
            }

            resolve(new Response(body));
        });
    });
};

var Bot_Github = function(project) {
    Bot.call(this, project);
};

Bot_Github.prototype = _.create(Bot.prototype);

Bot_Github.prototype.fetchTags = function (account, repo, test) {

    var data = [];

    return this.fetch('https://github.com/' + account + '/' + repo + '/releases')

        .then(function (response) {
    
            var $tags = response.$('.release-timeline-tags > li'),
                matches;

            if (test) {
                test = new RegExp(test);
            }
Example #2
0
    delete self._config.box;
    self._debug = self._config.debug || 0;
    self._config.debug = function(data){
        self._log(2, 'Imap: ', data);
    };
    self._criteria = _.clone(criteria, true);
    self._messages = {};
};
ImapQuery.defaults = {
    host: "imap.gmail.com",
    port: 993,
    tls: true,
    tlsOptions: { rejectUnauthorized: false },
    keepalive: false
};
ImapQuery.prototype = _.create(EventEmitter.prototype);
ImapQuery.prototype.messages = function(){
    var self = this;
    return _.clone(self._messages);
};
ImapQuery.prototype.check = function(){
    var self = this;
    if (!self._check){
        self._check = check(self);
        var clear = function(){delete self._check};
        self._check.then(clear, clear);
    }
    return self._check;
};
ImapQuery.prototype._log = function(level, text){
    var self = this;
var Request = require('request');
var sprintf = require('sprintf-js').sprintf;

var Config = require('../config.js'),
	BaseService = require('./BaseService'),
	VerifiedEmailAddress = require('../components/Account/VerifiedEmailAddress');

/**
 * Performs all actions pertaining to scheduling Constant Contact Account's
 */

function AccountService() {
	BaseService.apply(this, arguments);
}

AccountService.prototype = _.create(BaseService.prototype, { constructor: AccountService });

/**
 * Get all verified email addresses associated with an account
 * @param string $accessToken - Constant Contact OAuth2 Access Token
 * @param array $params - array of query parameters/values to append to the request
 * @return array of VerifiedEmailAddress
 */
AccountService.prototype.getVerifiedEmailAddresses = function(accessToken, params) {
	var req = {
		url: this.buildUrl(sprintf(Config.endpoints.account_verified_addresses, params)),
		headers: this.getHeaders(accessToken),
		json: true
	};

	return new Promise(function(resolve, reject) {
Example #4
0
function changePrototype(obj){
  var item = _.create(Item.prototype, obj);
  return item;
}
var Promise = require('bluebird');

var Config = require('../config.js'),
	BaseService = require('./BaseService'),
	ResultSet = require('../components/ResultSet'),
	Schedule = require('../components/EmailMarketing/Schedule'),
	TestSend = require('../components/EmailMarketing/TestSend');

/**
 * Performs all actions pertaining to scheduling Constant Contact Campaigns
 */
function CampaignScheduleService() {
	BaseService.apply(this, arguments);
}

CampaignScheduleService.prototype = _.create(BaseService.prototype, { constructor: CampaignScheduleService });


/**
 * Create a new schedule for a campaign
 * @param string accessToken - Constant Contact OAuth2 access token
 * @param int campaignId - Campaign id to be scheduled
 * @param Schedule schedule - Schedule to be created
 * @return Schedule
 */
CampaignScheduleService.prototype.addSchedule = function(accessToken, campaignId, schedule) {
	var self = this;
	var req = {
		url: this.buildUrl(sprintf(Config.endpoints.campaign_schedules, campaignId)),
		headers: this.getHeaders(accessToken),
		body: schedule.toJson(),
Example #6
0
describe('memoize', function() {
  function CustomCache() {
    this.clear();
  }

  CustomCache.prototype = {
    'clear': function() {
      this.__data__ = [];
      return this;
    },
    'get': function(key) {
      var entry = lodashStable.find(this.__data__, ['key', key]);
      return entry && entry.value;
    },
    'has': function(key) {
      return lodashStable.some(this.__data__, ['key', key]);
    },
    'set': function(key, value) {
      this.__data__.push({ 'key': key, 'value': value });
      return this;
    }
  };

  function ImmutableCache() {
    this.__data__ = [];
  }

  ImmutableCache.prototype = lodashStable.create(CustomCache.prototype, {
    'constructor': ImmutableCache,
    'clear': function() {
      return new ImmutableCache;
    },
    'set': function(key, value) {
      var result = new ImmutableCache;
      result.__data__ = this.__data__.concat({ 'key': key, 'value': value });
      return result;
    }
  });

  it('should memoize results based on the first argument given', function() {
    var memoized = memoize(function(a, b, c) {
      return a + b + c;
    });

    assert.strictEqual(memoized(1, 2, 3), 6);
    assert.strictEqual(memoized(1, 3, 5), 6);
  });

  it('should support a `resolver`', function() {
    var fn = function(a, b, c) { return a + b + c; },
        memoized = memoize(fn, fn);

    assert.strictEqual(memoized(1, 2, 3), 6);
    assert.strictEqual(memoized(1, 3, 5), 9);
  });

  it('should use `this` binding of function for `resolver`', function() {
    var fn = function(a, b, c) { return a + this.b + this.c; },
        memoized = memoize(fn, fn);

    var object = { 'memoized': memoized, 'b': 2, 'c': 3 };
    assert.strictEqual(object.memoized(1), 6);

    object.b = 3;
    object.c = 5;
    assert.strictEqual(object.memoized(1), 9);
  });

  it('should throw a TypeError if `resolve` is truthy and not a function', function() {
    assert.throws(function() { memoize(noop, true); }, TypeError);
  });

  it('should not error if `resolver` is nullish', function() {
    var values = [, null, undefined],
        expected = lodashStable.map(values, stubTrue);

    var actual = lodashStable.map(values, function(resolver, index) {
      try {
        return isFunction(index ? memoize(noop, resolver) : memoize(noop));
      } catch (e) {}
    });

    assert.deepStrictEqual(actual, expected);
  });

  it('should check cache for own properties', function() {
    var props = [
      'constructor',
      'hasOwnProperty',
      'isPrototypeOf',
      'propertyIsEnumerable',
      'toLocaleString',
      'toString',
      'valueOf'
    ];

    var memoized = memoize(identity);

    var actual = lodashStable.map(props, function(value) {
      return memoized(value);
    });

    assert.deepStrictEqual(actual, props);
  });

  it('should cache the `__proto__` key', function() {
    var array = [],
        key = '__proto__';

    lodashStable.times(2, function(index) {
      var count = 0,
          resolver = index ? identity : undefined;

      var memoized = memoize(function() {
        count++;
        return array;
      }, resolver);

      var cache = memoized.cache;

      memoized(key);
      memoized(key);

      assert.strictEqual(count, 1);
      assert.strictEqual(cache.get(key), array);
      assert.ok(!(cache.__data__ instanceof Array));
      assert.strictEqual(cache.delete(key), true);
    });
  });

  it('should allow `_.memoize.Cache` to be customized', function() {
    var oldCache = memoize.Cache;
    memoize.Cache = CustomCache;

    var memoized = memoize(function(object) {
      return object.id;
    });

    var cache = memoized.cache,
        key1 = { 'id': 'a' },
        key2 = { 'id': 'b' };

    assert.strictEqual(memoized(key1), 'a');
    assert.strictEqual(cache.has(key1), true);

    assert.strictEqual(memoized(key2), 'b');
    assert.strictEqual(cache.has(key2), true);

    memoize.Cache = oldCache;
  });

  it('should works with an immutable `_.memoize.Cache` ', function() {
    var oldCache = memoize.Cache;
    memoize.Cache = ImmutableCache;

    var memoized = memoize(function(object) {
      return object.id;
    });

    var key1 = { 'id': 'a' },
        key2 = { 'id': 'b' };

    memoized(key1);
    memoized(key2);

    var cache = memoized.cache;
    assert.strictEqual(cache.has(key1), true);
    assert.strictEqual(cache.has(key2), true);

    memoize.Cache = oldCache;
  });
});
Example #7
0
 * @param {String} key				Mode key
 */
function SVGSpriteCss(spriter, config, data, key) {
	SVGSpriteBase.apply(this, [spriter, config, data, key]);
}

/**
 * Prototype
 *
 * @type {Object}
 */
SVGSpriteCss.prototype = _.create(SVGSpriteBase.prototype, {
	constructor						: SVGSpriteCss,
	mode							: SVGSpriteBase.prototype.MODE_CSS,
	tmpl							: 'css',

	LAYOUT_VERTICAL					: 'vertical',
	LAYOUT_HORIZONTAL				: 'horizontal',
	LAYOUT_DIAGONAL					: 'diagonal',
	LAYOUT_PACKED					: 'packed'
});

/**
 * Initialization (non-CSS modes)
 *
 * @return {void}
 */
SVGSpriteCss.prototype._init = function() {

	// Prepare the dimension suffix
	if (this.config.dimensions && (this.config.dimensions !== true)) {
		this.config.dimensions		= /%s/g.test((this.config.dimensions || '').split('%%').join('')) ? util.format(this.config.dimensions, this.config.prefix) : (this.config.prefix + this.config.dimensions);
Example #8
0
let _ = require('lodash');
let engine = require('./engine');

export const URL_PATH_END_MARKER = "__url_path_end__";

function AcceptEndpointComponent(endpoint, parent) {
  engine.SharedComponent.call(this, endpoint.id, parent);
  this.endpoint = endpoint
}

AcceptEndpointComponent.prototype = _.create(engine.SharedComponent.prototype, { "constructor": AcceptEndpointComponent });

(function (cls) {

  cls.match = function (token, context, editor) {
    if (token !== URL_PATH_END_MARKER) {
      return null;
    }
    if (this.endpoint.methods && -1 === _.indexOf(this.endpoint.methods, context.method)) {
      return null;
    }
    var r = Object.getPrototypeOf(cls).match.call(this, token, context, editor);
    r.context_values = r.context_values || {};
    r.context_values['endpoint'] = this.endpoint;
    if (_.isNumber(this.endpoint.priority)) {
      r.priority = this.endpoint.priority;
    }
    return r;
  }
})(AcceptEndpointComponent.prototype);
Example #9
0
  };

DiscardDeck.prototype = _.create(Deck.prototype, {
  'constructor': DiscardDeck,
  'placeCards': function (cards) {
    var cardsAry = _.flatten([cards]);

    if (_.uniq(_.pluck(cardsAry, "points")).length !== 1) {
      throw new Error("Cannot place cards of multiple point values. Got " + _.pluck(cardsAry, "points") + ".");
    }

    _.each(cardsAry, function (card) {
      this.cards.push(card);
    }, this);
  },

  'takeTop': function () {
    return this.cards && this.cards.length > 0 ? this.cards.pop() : null;
  },

  'takeBottom': function () {
    return this.cards && this.cards.length > 0 ? this.cards.shift() : null;
  },

  'takeAllMiddleCards': function () {
    var middleCards = this.cards.slice(1, this.cards.length-1);
    this.cards = [_.first(this.cards), _.last(this.cards)];
    return middleCards;
  }
});

module.exports = DiscardDeck;
Example #10
0
GruntBrowserifyRunner.prototype = _.create(GruntBrowserifyRunner.prototype, {
  run: function (files, destination, options, next) {
    var self = this;

    //set constructor options and instantiate
    var bOpts = options.browserifyOptions || {};
    bOpts.entries = bOpts.entries || files;

    // Watchify requires specific arguments
    if(options.watch) {
      bOpts = _.extend({ cache: {}, packageCache: {}, fullPaths: true }, bOpts);
    }

    //determine watchify or browserify
    var b = options.watch ? this.watchify(this.browserify(bOpts)) : this.browserify(bOpts);

    b.on('error', function (err) {
      self.logger.fail.warn(err);
    });

    if(options.bundleOptions) {
      throw new Error('bundleOptions is no longer used. Move all option in browserifyOptions.');
    }

    if (options.alias) {
      _.forEach(options.alias, function (aliasPair) {
        if (!aliasPair.match(':')) {
          self.logger.fail.warn('Aliases must be split with a colon');
        }
        else {
          aliasPair = aliasPair.split(':');
          b.require(aliasPair[0], {expose: aliasPair[1]});
        }
      });

    }

    if (options.require) {
      _.forEach(options.require, function (file) {
        b.require(file);
      });
    }

    if (options.exclude) {
      _.forEach(options.exclude, function (file) {
        runOptionForGlob(b, 'exclude', file);
      });
    }

    if (options.ignore) {
      _.forEach(options.ignore, function (file) {
        runOptionForGlob(b, 'ignore', file);
      });
    }

    if (options.external) {
      _.forEach(options.external, function (id) {
        //allow externalizing of alias lists
        if (id.match(':')) {
          id = id.split(':')[1];
        }

        if (testForGlob(id)) {
          runOptionForGlob(b, 'external', id);
        }
        else {
          b.external(id);
        }
      });
    }

    if (options.transform) {
      _.forEach(options.transform, function (transformer) {
        if (typeof transformer !== 'object') {
          b.transform(transformer);
        }
        else {
          b.transform(transformer[1], transformer[0]);
        }
      });
    }

    if (options.plugin) {
      _.forEach(options.plugin, function (plugin) {
        if (typeof plugin !== 'object') {
          b.plugin(plugin);
        }
        else {
          b.plugin(plugin[0], plugin[1]);
        }
      });
    }


    var destPath = this.createDestDir(destination);
    var keepAlive = this.keepAliveFn.bind(this, options);
    var done = options.keepAlive? keepAlive : next;
    var bundleComplete = this.onBundleComplete(destination, options, done);

    if (options.watch) {
      var bundleUpdate = this.onBundleComplete(destination, options, keepAlive);
      b.on('update', function (ids) {
        ids.forEach(function (id) {
          self.logger.log.ok(id + ' changed, updating browserify bundle.');
        });
        doBundle(b, options, bundleUpdate);
      });
    }

    doBundle(b, options, bundleComplete);
  },

  createDestDir: function (destination) {
    var destPath = path.dirname(path.resolve(destination));
    if (!this.writer.exists(destPath)) {
      this.writer.mkdir(destPath);
    }
    return destPath;
  },

  keepAliveFn: function (options) {
    this.logger.log.ok('Watchifying...');
  },

  onBundleComplete: function (destination, options, next) {
    var self = this;
    return function (err, buf) {
      if (err) {
        self.logger.log.error(err);
        if (self.firstBuild || !options.keepAlive) {
          self.logger.fail.warn('Error running grunt-browserify.');
        }
      }
      else if (buf) {
        self.writer.write(destination, buf);
      }

      self.firstBuild = false;
      next();
    };
  }
});
 scope.edit = function(group) {
     scope.group.edit = _.create(group);
 };
Example #12
0
GruntBrowserifyRunner.prototype = _.create(GruntBrowserifyRunner.prototype, {
  run: function (files, destination, options, next) {
    var self = this;

    //set constructor options and instantiate
    var bOpts = _.cloneDeep(options.browserifyOptions) || {};
    bOpts.entries = bOpts.entries || files;

    // watchify options
    var wOpts = options.watchifyOptions || {};

    // Watchify requires specific arguments
    if(options.watch) {
      bOpts = _.extend({ cache: {}, packageCache: {}, fullPaths: true }, bOpts);
    }

    //determine watchify or browserify
    var b = options.watch ? this.watchify(this.browserify(bOpts), wOpts) : this.browserify(bOpts);

    b.on('error', function (err) {
      self.logger.fail.warn(err);
    });

    if(options.bundleOptions) {
      throw new Error('bundleOptions is no longer used. Move all option in browserifyOptions.');
    }

    // concat both array of require and alias
    var requiredFiles = (options.require || []).concat(options.alias || []);
    _.forEach(requiredFiles, function (file) {
      var filePath, opts;
      if (Array.isArray(file)) {
        filePath = file[0];
        opts = file[1];
      } else {
        var filePair = file.split(':');
        filePath = filePair[0];
        opts = {
          expose: filePair.length === 1 ? filePair[0] : filePair[1]
        };
      }
      b.require(filePath, opts);
    });

    if (options.exclude) {
      _.forEach(options.exclude, function (file) {
        runOptionForGlob(b, 'exclude', file);
      });
    }

    if (options.ignore) {
      _.forEach(options.ignore, function (file) {
        runOptionForGlob(b, 'ignore', file);
      });
    }

    if (options.external) {
      _.forEach(options.external, function (id) {
        //allow externalizing of alias lists
        if (id.match(':')) {
          id = id.split(':')[1];
        }

        if (testForGlob(id)) {
          runOptionForGlob(b, 'external', id);
        }
        else {
          b.external(id);
        }
      });
    }

    if (options.transform) {
      _.forEach(options.transform, function (transformer) {
        if (typeof transformer !== 'object') {
          b.transform(transformer);
        }
        else {
          b.transform(transformer[1], transformer[0]);
        }
      });
    }

    if (options.plugin) {
      _.forEach(options.plugin, function (plugin) {
        if (typeof plugin !== 'object') {
          b.plugin(plugin);
        }
        else {
          b.plugin(plugin[0], plugin[1]);
        }
      });
    }


    var destPath = this.createDestDir(destination);
    var keepAlive = this.keepAliveFn.bind(this, destination);
    var done = options.keepAlive? keepAlive : next;
    var bundleComplete = this.onBundleComplete(destination, options, done);

    if (options.watch) {
      var bundleUpdate = this.onBundleComplete(destination, options, keepAlive);
      b.on('update', function (ids) {
        ids.forEach(function (id) {
          self.logger.log.ok(id.cyan + ' changed, updating bundle.');
        });
        doBundle(b, options, bundleUpdate);
      });
    }

    if (options.configure) {
      options.configure(b);
    }

    doBundle(b, options, bundleComplete);
  },

  createDestDir: function (destination) {
    var destPath = path.dirname(path.resolve(destination));
    if (!this.writer.exists(destPath)) {
      this.writer.mkdir(destPath);
    }
    return destPath;
  },

  keepAliveFn: function (destination) {
    //this.logger.log.ok('Watchifying...');
  },

  onBundleComplete: function (destination, options, next) {
    var self = this;
    return function (err, buf) {
      if (err) {
        self.logger.log.error(err);
        if (self.firstBuild || !options.keepAlive) {
          self.logger.fail.warn('Error running grunt-browserify.');
        }
      }
      else if (buf) {
          // prepend the banner
          if(options.banner) {
              buf = Buffer.concat([new Buffer(options.banner + '\n', 'utf8'), buf]);
          }

        self.logger.log.ok('Bundle ' + destination.cyan + ' created. ' + (options.keepAlive ? 'Watchifying...' : ''));
        self.writer.write(destination, buf);
      }

      self.firstBuild = false;
      next();
    };
  }
});
Example #13
0
//HELPER
//
function reProto(account){
  return _.create(Account.prototype, account);
}
Example #14
0
//Private function
function changePrototype(obj){
  var student = _.create(Student.prototype, obj);
  return student;
}
Example #15
0
 user.save(()=>{
   _.create(User.prototype, this);
   fn(user);
 });
Example #16
0
GruntBrowserifyRunner.prototype = _.create(GruntBrowserifyRunner.prototype, {
  run: function (files, destination, options, next) {
    var self = this;

    //determine watchify or browserify
    var engine = options.watch? this.watchify: this.browserify;

    //set constructor options and instantiate
    var bOpts = options.browserifyOptions || {};
    bOpts.entries = files;
    var b = engine(bOpts);

    b.on('error', function (err) {
      self.logger.fail.warn(err);
    });


    //define default bundle options
    var ignoredAliases = [];
    options.bundleOptions = (options.bundleOptions || {});
    options.bundleOptions.filter = function (requireId) {
      return (ignoredAliases.indexOf(requireId) < 0);
    };


    if (options.alias) {
      _.forEach(options.alias, function (aliasPair) {
        if (!aliasPair.match(':')) {
          self.logger.fail.warn('Aliases must be split with a colon');
        }
        else {
          //first, try the module path as it is since
          //it may be a node module name
          var modulePath;
          aliasPair = aliasPair.split(':');
          try {
            modulePath = resolve.sync(aliasPair[0]);
          }
          catch (e) {
            //if resolution fails, the path is probably not
            //a node module so resolve the full module path
            modulePath = resolve.sync(path.resolve(aliasPair[0]));
          }

          b.require(resolve.sync(modulePath), {expose: aliasPair[1]});
        }
      });

    }

    if (options.require) {
      _.forEach(options.require, function (file) {
        b.require(file);
      });
    }

    if (options.exclude) {
      _.forEach(options.exclude, function (file) {
        if (testForGlob(file)) {
          runOptionForGlob(b, 'exclude', file);
        }
        else {
          b.exclude(file);
        }
      });
    }

    if (options.ignore) {
      _.forEach(options.ignore, function (file) {
        runOptionForGlob(b, 'ignore', file);
      });
    }

    if (options.external) {
      _.forEach(options.external, function (id) {
        //allow externalizing of alias lists
        if (id.match(':')) {
          id = id.split(':')[1];
        }

        if (testForGlob(id)) {
          runOptionForGlob(b, 'external', id);
        }
        else {
          try {
            require.resolve(id);
          }
          catch (e) {
            //it's an arbitary alias that can't be resolved,
            //add it to the ignore list
            ignoredAliases.push(id);
          }
          b.external(id);
        }
      });
    }

    if (options.transform) {
      _.forEach(options.transform, function (transformer) {
        if (typeof transformer !== 'object') {
          b.transform(transformer);
        }
        else {
          b.transform(transformer[1], transformer[0]);
        }
      });
    }

    if (options.plugin) {
      _.forEach(options.plugin, function (plugin) {
        if (typeof plugin !== 'object') {
          b.plugin(plugin);
        }
        else {
          b.plugin(plugin[0], plugin[1]);
        }
      });
    }


    var destPath = this.createDestDir(destination);
    var keepAlive = this.keepAliveFn.bind(this, options);
    var done = options.keepAlive? keepAlive : next;
    var bundleComplete = this.onBundleComplete(destination, done, options.bundleOptions);

    if (options.watch) {
      var bundleUpdate = this.onBundleComplete(destination, keepAlive, _.extend({allowErrors: true}, options.bundleOptions));
      b.on('update', function (ids) {
        ids.forEach(function (id) {
          self.logger.log.ok(id + ' changed, updating browserify bundle.');
        });
        doBundle(b, options, bundleUpdate);
      });
    }

    doBundle(b, options, bundleComplete);
  },

  createDestDir: function (destination) {
    var destPath = path.dirname(path.resolve(destination));
    if (!this.writer.exists(destPath)) {
      this.writer.mkdir(destPath);
    }
    return destPath;
  },

  keepAliveFn: function (options) {
    this.logger.log.ok('Watchifying...');
  },

  onBundleComplete: function (destination, next, options) {
    var self = this;
    options = (options || {});
    return function (err, src) {
      if (err) {
        self.logger.log.error(err);
        if (!options.allowErrors) {
          self.logger.fail.warn('Error running grunt-browserify.');
        }
      }

      if (src) {
        if (!options.debug && !src.match(/;$/)) {
          src += ';';
        }

        self.writer.write(destination, src);
      }

      next();
    };
  }
});
Example #17
0
include.prototype = _.create(include.prototype, {
    compileOne: function (popt) {
        var self = this;


        fs.readFile(popt.from, function (err, content) {
            var options = self._createOptions(popt, {
                content: content.toString()
            });
            var compiled = self.compileContent(options);
            var dir = path.dirname(options.to);

            if (options.filterNoMethod &&
                crypto.createHash('sha256').update(compiled).digest('base64') ===
                crypto.createHash('sha256').update(content).digest('base64')) {
                options.done("No method");
                return;
            }

            //TODO: make async
            if (!fs.existsSync(dir)) {
                mkdirp.sync(dir);
            }

            fs.writeFile(options.to, compiled, function (err) {
                if (_.isFunction(options.done)) {
                    options.done(err);
                }

                log(options.log, 'File "' + options.to + '" created."');
            });
        });
    },
    //TODO: make async
    compileContent: function (popt) {
        var self = this;
        var options = this._createOptions(popt);


        return options.content.replace(this._getPattern(options.name), function (match, p1) {
            var includeFilePath = self._getIncludePath(options.basePath, p1);

            var value = fs.readFileSync(includeFilePath).toString();

            if(options.replaceRules && options.replaceRules.length > 0) {

                for(var i = 0; i < options.replaceRules.length; i++) {
                    value = value.replace(new RegExp(options.replaceRules[i].pattern, "gi"), options.replaceRules[i].replacement);
                }
            }

            if (options.minify) {
                value = minify(value, options.minifyOptions);
                value = value.replace(/\n/g, '');
            }

            if (options.escapeWrap && options.wrap) {
                var wrapPattern = new RegExp('', 'ig');
                value = value.replace(new RegExp(options.wrap, 'ig'), '\\' + options.wrap);
                value = value.replace(/\\\\/g, '\\\\\\');
            }

            if(options.isBase64) {
                value = new Buffer(value).toString('base64');
            }

            return options.wrap + value + options.wrap;
        });
    },
    compile: function (popt) {
        var globPath;
        var self = this;
        var options = this._createOptions(popt);

        if (_.isString(options.src)) {
            globPath = options.cwd + options.src;
        } else {
            globPath = options.src.map(function (el) {
                return options.cwd + el;
            });
        }

        glob(globPath, function (err, files) {
            async.each(files, function (file, callback) {
                var destinationPath = file.replace(options.cwd, options.dest);

                self.compileOne(self._createOptions(options, {
                    from: file,
                    to: destinationPath,
                    done: function (err) {
                        callback(err);
                    }
                }));
            }, function (err) {
                if (_.isFunction(options.done)) {
                    options.done(err);
                }
            });
        });
    },
    _getPattern: function (name) {
        return new RegExp(name + '\\([\'"]?([^\'\"\\(\\)]+)[\'"]?\\)', 'ig');
    },
    _createOptions: function () {
        var args = [].concat([{
            wrap: '',
            minify: false,
            minifyOptions: {},
            name: 'include',
            basePath: '',
            filterNoMethod: true,
            log: false
        }], _.map(arguments, function (val) {
            return val;
        }));

        return _.extend.apply(this, args);
    },
    _getIncludePath: function (basePath, path) {
        if ((/^\//).test(path)) {
            return basePath + path;
        }

        return path;
    }
});
Example #18
0
 var memes = objs.map(o=>_.create(Meme.prototype, o));
WarDeployer.prototype = _.create(EventEmitter.prototype, {
	init: function(options) {
		EventEmitter.call(this);

		this._validateOptions(options);

		var siteURL = options.url || 'http://*****:*****@liferay.com'));
		}

		if (!this.password) {
			questions.push(this._getQuestion('password', 'test'));
		}

		if (questions.length) {
			inquirer.prompt(questions, function(answers) {
				Object.keys(answers).forEach(function(key) {
					instance[key] = answers[key];
				});

				instance._makeRequest();
			});
		}
		else {
			instance._makeRequest();
		}
	},

	_setURLSettings: function(siteURL) {
		var parsedURL = url.parse(siteURL);

		this.host = parsedURL.hostname;
		this.port = parsedURL.port;
		this.protocol = _.trimRight(parsedURL.protocol, ':');
	},

	_validateOptions: function(options) {
		if (!options.fileName) {
			throw new Error('fileName required');
		}
	},

	_validateURLSettings: function() {
		if (['http', 'https'].indexOf(this.protocol) < 0) {
			throw new Error('http or https must be used as protocol');
		}
	},

	_writeWarFile: function(req) {
		var instance = this;

		var boundaryKey = this._getBoundaryKey();

		req.write(this._getFileHeaders(this._fileName, boundaryKey));

		fs.createReadStream(path.join(CWD, 'dist', this.fileName + '.war'))
			.on('end', function() {
				req.end('\r\n--' + boundaryKey + '--');

				instance.emit('end');
			})
			.pipe(req, {
				end: false
			});
	}
});
            };
        } else {
            if (response.rval) {
                return {
                    links: new self.Collection(response.rval.links)
                };
            } else {
                return {};
            }
        }
    };

    self.selectable = [
        'CustomerId',
        'CurrencyCode',
        'DateTimeZone',
        'DescriptiveName',
        'CanManageClients',
        'TestAccount'
    ];

    self.xmlns = 'https://adwords.google.com/api/adwords/mcm/' + self.version;
    self.wsdlUrl = self.xmlns + '/CustomerService?wsdl';
}

Service.prototype = _.create(AdWordsService.prototype, {
    'constructor': Service
});

module.exports = (Service);
Example #21
0
 Item.collection.findOne({_id: query}, function(err, item){
   var item = _.create(Item.prototype, item);
   cb(item);
 });
Example #22
0
function changePrototype(obj){
  return _.create(Priority.prototype, obj);
}
Example #23
0
 Goal.collection.findOne({_id:id}, function(err, goal){
   cb(_.create(Goal.prototype, goal));
 });
Example #24
0
 users.findOne({_id:userId}, (e, user)=>{
   user = _.create(User.prototype, user);
   fn(user);
 });
Example #25
0
function IsObjectWithProperties(properties) {
	const propertyMatchers = _.mapValues(properties, asMatcher);
	return _.create(new IsObject(), {
		matchesSafely: function (actual) {
			const results = _.mapValues(propertyMatchers, (matcher, key) => {
				return matcher.matches(actual[key]);
			});

			return promiseAgnostic.matchesAggregate(results, _.every);
		},
		describeTo: function (description) {
			description.append('an object with {');

			let first = true;
			_.forEach(propertyMatchers, (matcher, key) => {
				if (!first) {
					description.append(', ');
				}
				first = false;

				description
					.append(key)
					.append(': ')
					.appendDescriptionOf(matcher);
			});

			description.append('}');
		},
		describeMismatchSafely: function (actual, description) {
			const results = _.mapValues(propertyMatchers, (matcher, key) => {
				return matcher.matches(actual[key]);
			});

			let first = true;
			const describeVerbose = this.describeVerbose;
			return promiseAgnostic.describeMismatchAggregate(results, (result, key) => {
				if (result) {
					return;
				}

				if (!first) {
					description.append(',\n');
				}
				first = false;

				description
					.append(key)
					.append(' ');
				return description.indented(() => propertyMatchers[key].describeMismatch(actual[key], description));
			}, () => {
				if (describeVerbose) {
					description.append('\nfor ')
						.appendValue(actual);
				}
			});
		},
		verbose: function () {
			this.describeVerbose = true;
			return this;
		}
	});
}
Example #26
0
function rePrototype(obj){
  var p = _.create(Person.prototype, obj);
  return p;
}
Example #27
0
 User.collection.findOne({_id:_id}, function(err, obj){
   cb(err, _.create(User.prototype, obj));
 });
Example #28
0
 users.save(this, ()=>{
   _.create(User.prototype, this);
   fn();
 });
Example #29
0
namespace.factory('Palette', ['Color', '$cacheFactory', function(Color, $cacheFactory){
	/**
	 * @constructor Palette
	 * Represents a collection of colors
	 *
	 * @extends {EventEmitter}
	 */
	function Palette(colors){
		this._colors = {};
		EventEmitter.apply(this);

		_.bindAll(this, ['_onColorUpdate']);

		this.addColors(colors, true);
	}

	Palette.prototype = _.create(EventEmitter.prototype, {
		/**
		 * Update event
		 *
		 * @event Palette#update
		 * @property {Palette} event.target - the instance emitting the event
		 * @property {colors[]} colors - An array of colors that have changed
		 */
		constructor: Palette,
		/**
		 * Adds some colors to this palette
		 * @param {String | String[] | Object | Object[]} colors - 
		 */
		addColors : function(colors, silent){
			var _this = this,
				updatedColors = [];

			if(!colors) {
				return;
			}

			if(_.isPlainObject(colors)){
				colors = _.map(colors, function(value, key){
					return {
						id : key,
						color : value
					};
				});
			} else if(!_.isArray(colors)){
				colors = [colors];
			}

			updatedColors = _.chain(colors)
				.map(function(value){
					var id, colorObj;
					if(value instanceof Color){
						colorObj = value;
					} else if (_.isObject(value)){
						colorObj = new Color(value.id, value.color);
					} else {
						colorObj = new Color(value && value.toString());
					}

					id = colorObj.id;

					if(_this._colors.hasOwnProperty(id)){
						_this._colors[id].setColor(colorObj.getCss(), true);
						colorObj = _this._colors[id];
					} else {
						_this._colors[id] = colorObj;
						colorObj.on('update', _this._onColorUpdate);
					}

					return colorObj;
				})
				.indexBy(_.property('id'))
				.value();

			if(!silent){
				this.emit('update', updatedColors);
			}
		},
		getColors : function(){
			return this._colors;
		},
		_onColorUpdate: function(event){
			var target = event.target;
			var colors = {};
			colors[target.id] = target;
			this.emit('update', colors);
		},
		toJSON : function(){
			return _.map(this._colors, function(value){
				return value.toJSON();
			});
		}
	});
	
	return Palette;
}]);
test.beforeEach(function() {
	prototype = _.create(KickstartPrompt.prototype);
});