Example #1
0
 results.forEach(function(result) {
     var next = group();
     var parsingTime = +new Date;
     // Maintain a parsing environment from
     // stylesheet to stylesheet, so that frames
     // and effects are maintained.
     var parse_env = _.extend(
         _.extend(
             that.env,
             this.env
         ), { filename: result[0] });
     new carto.Parser(parse_env).parse(result[1],
         function(err, tree) {
         if (env.benchmark) console.warn('Parsing time: '
             + ((new Date - parsingTime))
             + 'ms');
         try {
             next(err, [
                 result[0],
                 tree]);
             return;
         } catch (e) {
             throw e;
             return;
         }
     });
 });
Example #2
0
function loadDeps(deps) {
    // TODO: ignore deps already merged in
    if (!deps) {
        return;
    }
    for (var k in deps) {
        var s = null;
        try {
            s = require('settings/packages/' + k);
        }
        catch (e) {
            // no settings, skip
        }
        if (s) {
            if (s.load) {
                var a = require(s.load);
                // should these always be concatenated?
                // TODO: this behaves differently to the build steps which only
                // use the rewrites from the root package
                exports._rewrites = exports._rewrites.concat(a.rewrites || []);

                // TODO: detect conflicting properties as the merge build step
                // would report them
                _.extend(exports._shows, a.shows);
                _.extend(exports._lists, a.lists);
                _.extend(exports._updates, a.updates);
            }
            loadDeps(s.dependencies);
        }
    }
}
Example #3
0
            _.each([ 'commands', 'pages', 'api' ], function(property) {
                var propertyObj = {};

                if(fs.existsSync(moduleDir + property + '.js')) {
                    try {
                        var propertyKey = require.resolve(moduleDir + property);
                        if(propertyKey) delete require.cache[propertyKey];
                        propertyObj = require(moduleDir + property).fetch(this);
                    } catch(err) {
                        this.status[name] = 'Error loading ' + propertyKey + ': ' + err + ' - ' + err.stack.split('\n')[1].trim();
                        console.log('Module error (' + module.name + ') in ' + property + ': ' + err);
                    } 
                }

                if(!_.has(module, property)) module[property] = {};
                _.extend(module[property], propertyObj);
                _.each(module[property], function(item, itemName) {
                    item.module = name; 
                    if(_.has(config, property) && _.has(config[property], itemName)) {
                        _.extend(item, config[property][itemName]);
                    }
                    module[property][itemName] = _.bind(item, module);
                    _.extend(module[property][itemName], item);
                }, this);

                if(property == 'api') {
                    this[property][name] = module[property];
                } else {
                    _.extend(this[property], module[property]);
                }
            }, this);
Example #4
0
  var inherits = function(parent, protoProps, staticProps) {
    var child;

    // The constructor function for the new subclass is either defined by you
    // (the "constructor" property in your `extend` definition), or defaulted
    // by us to simply call `super()`.
    if (protoProps && protoProps.hasOwnProperty('constructor')) {
      child = protoProps.constructor;
    } else {
      child = function(){ return parent.apply(this, arguments); };
    }

    // Inherit class (static) properties from parent.
    _.extend(child, parent);

    // Set the prototype chain to inherit from `parent`, without calling
    // `parent`'s constructor function.
    ctor.prototype = parent.prototype;
    child.prototype = new ctor();

    // Add prototype properties (instance properties) to the subclass,
    // if supplied.
    if (protoProps) _.extend(child.prototype, protoProps);

    // Add static properties to the constructor function, if supplied.
    if (staticProps) _.extend(child, staticProps);

    // Correctly set child's `prototype.constructor`.
    child.prototype.constructor = child;

    // Set a convenience property in case the parent's prototype is needed later.
    child.__super__ = parent.prototype;

    return child;
  };
Example #5
0
Redobl.define = function(name, config, proto) {
  // The name argument is optional.
  if (typeof name !== 'string') {
    proto = config; config = name;
    name = config.name;
  }

  //sys.log("Redobl.define " + name + " config = " + sys.inspect(config));
  var type_f = Redobl._getClass((config && config.type) || 'object');

  var f = function(setup) {
    var args = this._rsetup(setup || {});
    EventEmitter.call(this);
    type_f.call(this, setup);
    if (this.init) { this.init.apply(this, _.rest(arguments)); }
  };

  // Inherit instance methods from
  f.prototype = _.extend(new type_f(), EventEmitter.prototype);
  _.extend(f.prototype, {
    constructor: f,
    className: name
  });
  // and extend with the proto options.
  _.extend(f.prototype, proto);

  // Inherit class methods from type_f (i.e. the specific subclass of Redobl)
  _.extend(f, type_f.classMethods);

  // Now, call the 'constructor' for this new type.
  f._classConstructor(name, config || {});

  return f;
}
Example #6
0
function saveDataInRecentlyList() {
	var dataToSave = recentlyAppDataToSave;
	var positionOfProfileTagInCli = cli.argv.$_.indexOf('-P');
	if (process.argv.indexOf('--auto-device') !== -1) {
		var positionOfCertificateTagInCli = cli.argv.$_.indexOf('-V');
		var developmentData = {
			"developmentProfile" : cli.argv.$_[positionOfProfileTagInCli + 1],
			"developmentCertificate" : cli.argv.$_[positionOfCertificateTagInCli + 1]
		};
		_.extend(dataToSave, developmentData);
	} else {
		var positionOfCertificateTagInCli = cli.argv.$_.indexOf('-R');
		var adhocData = {
			"adhocProfile" : cli.argv.$_[positionOfProfileTagInCli + 1],
			"adhocCertificate" : cli.argv.$_[positionOfCertificateTagInCli + 1]
		};
		_.extend(dataToSave, adhocData);
	}

	tiadpHelper.setRecentlyUsedAppData(dataToSave, function(present) {
		if (present) {
			logger.info('App data modified in recently list.');
		} else {
			logger.info('App data saved in recently list.');
		}
		finished();
	});
}
Example #7
0
 _.each(module[property], function(item, itemName) {
     item.module = name; 
     if(_.has(config, property) && _.has(config[property], itemName)) {
         _.extend(item, config[property][itemName]);
     }
     module[property][itemName] = _.bind(item, module);
     _.extend(module[property][itemName], item);
 }, this);
Example #8
0
File: db.js Project: Becram/xovis
DB.prototype.bulkGet = function (keys, /*optional*/ q, callback) {
    if (keys && !_.isArray(keys)) {
        throw new Error(
            'bulkGet requires that _id values be supplied as a list'
        );
    }
    if (!callback) {
        callback = q;
        q = {};
    }

    /* Encode every query-string option:
        CouchDB requires that these be JSON, even though they
        will be URL-encoded as part of the request process. */

    try {
        for (var k in q) {
            q[k] = JSON.stringify(q[k]);
        }
    }
    catch (e) {
        return callback(e);
    }

    /* Make request:
        If we have a list of keys, use a post request containing
        a JSON-encoded list of keys. Otherwise, use a get request. */

    var req = {
        expect_json: true,
        url: this.url + '/_all_docs' + exports.escapeUrlParams(q)
    };
    if (keys) {
        try {
            var data = JSON.stringify({ keys: keys});
        }
        catch (e) {
            return callback(e);
        }
        req = _.extend(req, {
            type: 'POST',
            processData: false,
            contentType: 'application/json',
            data: data
        });
    } else {
        req = _.extend(req, {
            type: 'GET'
        });
    }

    exports.request(req, callback);
};
Example #9
0
  requests.fetch( function (err) {

    var response = {};

    if (err) {
      _.extend(response, err);
      response.statusCode = 500;
    } else {
      response.statusCode = 200;
      _.extend(response, { data: { requests: requests.toJSON() } });
    }
    Main.Render.code(req, res, response);
  });
Example #10
0
var getPackagePublisher = function(options, callback) {
  var publisher = resourcePublishersInUse.findById(options.cacheName);

  //if we're "flushing" the cache, dispose of the old publisher so a new one is created to force writing new content
  if (publisher && options.flushCache && publisher.getCurrentStateName() === 'published') {
    resourcePublishersInUse.remove(publisher);
    publisher.dispose();
    publisher = null;
  }

  var newCache = false,
    hrefPrefix = typeof options.hrefPrefix === "undefined" ? "/" : options.hrefPrefix,
    resourceOptions = options.appOptions.resources,
    pkg = _.detect(resourceOptions.packages, function(pkg) { 
      return pkg.name === options.cacheName || pkg.publishType === options.publishType; 
    }),
    publisherOptions = null;

    var pkgOptions = _.extend(_.extend({}, _.clone(resourceOptions.publish.defaults)), pkg || {});

  // A package can either contain its own publisher options or reference a pre-defined publisher.
  if (pkgOptions.publisher) {
    publisherOptions = pkgOptions.publisherOptions;
  } else if (pkgOptions.publisherId) {
    publisherOptions = _.detect(resourceOptions.publish.publishers, function(pub) {
      return pub.id === pkgOptions.publisherId;
    });
  }
  if (!publisher) {
    newCache = true;
    //build a publisher object, use it, and stuff in cache
    publisher = new ResourcePublisher({
      cacheName: options.cacheName,
      contentType: options.contentType,
      content: options.content,
      publishType: options.publishType,
      publisherOptions: publisherOptions
    });
    publisher.publishers.add(availableResourcePublishers.findById(publisherOptions.id));
    resourcePublishersInUse.add(publisher);
  } 

  callback(null, _.extend({
    publisher: publisher, 
    packageOptions: pkgOptions,
    newCache: newCache,
  }, options));
};
Example #11
0
  this.submit = function (opts, cb) {
    cb = _.isFunction(cb) ? cb : function () {};

    //Resolve RESTful stuff
    opts = opts || {};
    var content;
    if (opts.content) {
      content = JSON.stringify(opts.content);
    }
    opts = _.extend(opts, {
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': content ? Buffer.byteLength(content, 'utf8') : 0
      }
    });
    http.request(opts, function (res) {
      var data = '';
      res
        .on('data', function (c) { data += c; })
        .on('end', function () {
          try {
            data = JSON.parse(data);
          } catch (e) {
            return cb(e);
          }
          return cb(data.error, data.result);
        });
    })
    .on('error', cb)
    .end(content);
  };
Example #12
0
app.run = function(config){
  var config = _.extend({
      port: 3000
    , home: __dirname 
    , env : 'development'
  }, config);
  
  app.ReponseMessage = function(code , data) {
    return {
      code : code,
      data : data
    }
  };
  app.CONST = {
    errorCode : {
      NO_ERROR : 'NoError'
    }
  }

  app.pre(function(req, res, next) {
    return next();
  });

  routes(app);

  app.listen(config.port , function(){
    console.log("Restify server listening on port " + config.port + " in " + config.env + " mode");
  });
}
Example #13
0
var Square = module.exports = function Square (options) {
  var self = this
    , stdout = false;

  this.env = process.env.NODE_ENV || 'development';
  this.reqparse = reqparse;
  this.logger = new Logger({
      timestamp: false
    , namespacing: 0
    , notification: 0
  });

  /**
   * When the stdout properly is set we need to see if we should enable logging
   * or not.
   */

  Object.defineProperty(this, 'stdout', {
      get: function get () {
        return stdout;
      }
    , set: function set (bool) {
        // check if we need to silence the logger
        self.logger.set('level', bool ? 0 : 8);
        stdout = !!bool;
      }
  });

  _.extend(this, options || {});

  // should not be overridden
  this.config = require('../static');
  this.middleware = [];
  this.package = {};
};
Example #14
0
Square.prototype.tag = function tag (collection, type) {
  var branch = exec('git branch', { silent: true }).output
    , sha = exec('git show -s', { silent: true }).output
    , date = new Date();

  if (branch) {
    branch = /\*\s([\w\.]+)/g.exec(branch) || '';
    branch = branch.length ? branch[1] : branch;
  }

  if (sha) {
    sha = /commit\s(\w+)/g.exec(sha) || '';
    sha = sha.length ? sha[1] : sha;
  }

  return _.extend({
      type: type || 'min'
    , md5: createHash('md5').update(collection.content).digest('hex')
    , group: collection.group
    , branch: branch
    , sha: sha
    , ext: collection.extension || 'js'
    , date: date.toLocaleDateString()
    , year: date.getFullYear()
    , user: process.env.USER || 'anonymous'
    , host: os.hostname()
  }, this.package.configuration.vars || {});
};
 'settings-test': function() {
     // Get settings
     assert.response(app, {
         url: '/api/Settings/settings',
         method: 'GET',
     }, {
         status: 200
     }, function(res) {
         assert.deepEqual(JSON.parse(res.body), JSON.parse(settings1));
     });
     // Validation: mode may only be normal or minimal.
     var invalid = _.extend(JSON.parse(settings1), {
         mode: 'awesome'
     });
     assert.response(app, {
         url: '/api/Settings/settings',
         method: 'PUT',
         headers: {
             'content-type': 'application/json'
         },
         data: JSON.stringify(invalid)
     }, {
         status: 500
     }, function(res) {
         assert.equal(res.body, 'Editing mode may be \'normal\' or \'minimal\' to allow use of external editors.');
     });
 },
Example #16
0
						tiadpHelper.saveADPCredentials(res, function(value) {
							saveInRecent = true;
							_.extend(recentlyAppDataToSave, {
								"team" : selectedTeam
							});
							sendNetworkRequestToGetProvisionalProfile(data, options, _callback);
						});
Example #17
0
exports.update = function(req, res){
  var user = req.user
  user = _.extend(user, req.body)
  user.save(function(err) {
    res.jsonp(user)
  })
}
Example #18
0
  var promise = new Promise(function(resolve, reject) {
    var req = https.request(_.extend({}, options, {
      path: '/api/stat/device',
      method: 'POST',
      headers: {
        'Cookie': cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(data)
      }
    }), function(res) {
      if (res.statusCode === 200) {
        var str = '';
        res.on('data', function(chunk) {
          str += chunk;
        });
        res.on('end', function() {
          var object = JSON.parse(str);
          resolve(object.data);
        });
      }
      else {
        reject('error - server ' + res.statusCode);
      }
    });

    req.write(data);
    req.end();
  });
Example #19
0
function mkv_extract_internal_tracks(mkv, callback) {
    var tracks = _.map(mkv.tracks, function(track) {
	return _.extend(track, {
	    file_name: make_temp_name('tmp-' + safe_name(mkv.base_name) + '_track_' + track.number + '.' + track_extension(track)),
	    extracted: true
	});
    });
    
    var result = '';


    // test
    if(0) {
	mkv.mkvextract_output = "didn't run"; // for debugging
	mkv.mkvextract_result = 0;
	callback(null, _.extend(mkv, { tracks : tracks }));
	return;
    }
    // end of test

    spawn_collect(exe_mkvextract, 
		  [ 'tracks', mkv.file_name].concat(_.map(tracks, function (t) { return t.number + ':' + t.file_name })),
		  function(err, code, result) {
		      console.log('Extracted'.green);
		      if(err) 
			  callback(err);
		      else {
			  mkv.mkvextract_output = result; // for debugging
			  mkv.mkvextract_result = code;
			  callback(null, _.extend(mkv, { tracks : tracks }));
		      }
		  });
}
Example #20
0
 replicator.exists('', function (err, exists) {
     if (err) {
         return callback(err);
     }
     if (!exists) {
         replicator.client('GET', '', {}, function (err, info) {
             if (err) {
                 return callback(err);
             }
             var msg = 'You need at least CouchDB 1.1.0 to use the ' +
                 '_replicator database';
             if (info && info.version) {
                 msg += ', it appears you are using ' + info.version;
             }
             callback(new Error(msg));
         });
     }
     else {
         var doc = _.extend(options, {
             source: source,
             target: target
         });
         replicator.save(null, doc, callback);
     }
 });
Example #21
0
	defaults: function() {
		return _.extend(client_models.Session.prototype.defaults(), {
			"session-key":null,
			"hangout-url": null,
			"hangout-pending": null
		});
	},
var step3 = function(test) {

    var viewdata = {
        rows: [{
            doc: {
                tasks: []
            }
        }]
    };

    var next_req = {
        method: "GET",
        body: "",
        path: baseURL + "/add",
        headers: _.extend(helpers.headers(
                    'json', ''), {
                        "Authorization": "Basic cm9vdDpwYXNzd29yZA=="
                    }),
        query: {form: 'YYYY'}
    };

    var resp = fakerequest.list(lists.tasks_pending, viewdata, next_req);

    var resp_body = JSON.parse(resp.body);

    // there is no callback since there is no tasks
    test.same(resp_body.callback, undefined);
    test.same(resp_body.payload.success, true);

    test.done();

};
var step2 = function(test, req) {

    var clinic = example.clinic;

    var viewdata = {rows: [
        {
            "key": ["+13125551212"],
            "value": clinic
        }
    ]};

    var resp = fakerequest.list(lists.data_record, viewdata, req);

    var resp_body = JSON.parse(resp.body);

    test.same(resp_body.callback.options.headers.Authorization,
        "Basic cm9vdDpwYXNzd29yZA==");


    // form next request from callback data
    var next_req = {
        method: resp_body.callback.options.method,
        body: JSON.stringify(resp_body.callback.data),
        path: resp_body.callback.options.path,
        headers: _.extend(helpers.headers(
                    'json', JSON.stringify(resp_body.callback.data)), {
                        "Authorization": "Basic cm9vdDpwYXNzd29yZA=="
                    }),
        query: {form: 'YYYY'} // query.form gets set by rewriter
    };

    step3(test, next_req);

};
Example #24
0
 _.each(attrOrModel, function (error) {
   if (error instanceof Errors) {
     allErrors = _.extend(allErrors, error.errorsToJSON(prefix + name));
   } else {
     tmpErrs.push(error);
   }
 });
Example #25
0
exports.loadrepository = function(repoUrl, options) {
    options = _.extend(options, { process : retire.replaceVersion });
    if (options.nocache) {
        return loadJson(repoUrl, options);
    }
    return loadFromCache(repoUrl, options.cachedir, options);
};
Example #26
0
/**
 * @class Action
 * 
 * 动作规则
 * 
 * 执行流程: pattern -> handler -> register reply action
 * 
 * @constructor 动作规则
 * @param {Mixed}  cfg    Action的配置
 * @param {String} [prex] 动作名的前缀
 */
function Action(cfg, prex){
  if(_.isString(cfg)){
    //为字符串时,pattern为通过匹配,handler为直接返回该值
    this.name = prex + '_' + cfg;
    this.description = '发送任意字符,直接返回:' + cfg;
    this.handler = cfg;
  }else if(_.isFunction(cfg)){
    //为函数时,pattern为通过匹配,handler为该函数
    this.name =  prex + '_' + cfg.name;
    this.description = cfg.description || '发送任意字符,直接执行函数并返回';
    this.handler = cfg;
  }else if(_.isArray(cfg)){
    throw new Error('no support cfg type: Array')
  }else if(_.isObject(cfg)){
    /**
     * 匹配这种格式:
     * {
     *   name: 'say_hi', 
     *   description: 'pattern可以用正则表达式匹配,试着发送「hi」',
     *   pattern: /^Hi/i,
     *   handler: function(info) {
     *     //回复的另一种方式
     *     return '你也好哈';
     * }
     * @ignore
     */
    _.extend(this,cfg)
    this.name = cfg.name || prex || cfg.pattern
  }
  if(!this.name) this.name = 'it_is_anonymous_action';
  return this;
};
Example #27
0
 function(event, callback) {
     var linkUpdated = params.link && params.link !== event.link;
     _.extend(event, params);
     if (linkUpdated) {
         async.waterfall([
             function(callback) {
                 shortenUrl(params.link, callback);
             },
             function(shortUrl, callback) {
                 event.shortLink = shortUrl;
                 event.save(callback);
             }
         ], function(err, results) {
             if (err) {
                 callback(err);
             } else {
                 if (results instanceof Array) {
                     callback(null, results[0]);
                 } else {
                     callback(null, results);
                 }
             }
         });
     } else {
         event.save(callback);
     }
 }
Example #28
0
 offers: _.map(data.results, function (item) {
   return _.extend(item, {
     'id': that.languages[language] + '_' + item.skuid,
     'site': that.config.site,
     'language': that.languages[language]
   });
 })
Example #29
0
 }, errorHandler(cb, function(err, lists) {
   var changes = [];
   var ls1 = lists[0];
   var ls2 = lists[1];
   var deletedPaths = _.extend(ls1.byPath);
   // TODO: catch deleted files
   _.each(ls2.bySha1, function(path, sha1) {
     if (ls1.bySha1[sha1]) {
       if (ls1.bySha1[sha1] === path) {
         // no change
         delete deletedPaths[path];
       } else {
         // renamed; blob the same, though
         // note that we're not catching renames that are mostly the same... they're just counting as delete & add
         changes.push({ type: 'rename', before: { path: ls1.bySha1[sha1], sha1: sha1 }, after: { path: path, sha1: sha1 } });
         delete deletedPaths[ls1.bySha1[sha1]];
       }
     } else {
       if (ls1.byPath[path]) {
         // changed
         changes.push({ type: 'change', before: { path: path, sha1: ls1.byPath[path] }, after: { path: path, sha1: sha1 } });
         delete deletedPaths[path];
       } else {
         // added
         changes.push({ type: 'add', before: { }, after: { path: path, sha1: sha1 } });
       }
     }
   });
   _.each(_.keys(deletedPaths), function(path) {
     changes.push({ type: 'delete', before: { path: path, sha1: ls1.byPath[path] }, after: { } });
   });
   cb(null, changes);
 }));
Example #30
0
	.on('end', function () {
	    if(track) {
		tracks.push(track);
	    }
	    console.log('Found tracks '.green + sys.inspect(tracks).cyan);
	    callback(null, _.extend(mkv, { tracks: tracks }));
	});