globifyTargets( cwd, globs, function( finalGlobs ){
     async.map(_.map(finalGlobs, _.partial(append,cwd)), globContent, function( err, sources ){
         if( err ){
             callback( err );
             return;
         }
         //remove the cwd from the resolved paths, for a relative-path
         sources = _.map(sources, function(sourceList, i ){
             return _.map( sourceList, function( s, j ){
                 return s.slice(cwd.length);
             });
         });
         callback( null, _.object(finalGlobs, sources) );
     });
 });
Amygdala.prototype._emitChange = function(type) {

  // TODO: Add tests for debounced events
  if (!this._changeEvents[type]) {
    this._changeEvents[type] = _.debounce(_.partial(function(type) {
      // emit changes events
      this.emit('change', type);
      // change:<type>
      this.emit('change:' + type);
      // TODO: compare the previous object and trigger change events
    }.bind(this), type), 150);
  }

  this._changeEvents[type]();
}
Example #3
0
  var cleanSimVEight = function (keepKeychains, tempDir, cb) {

    var base = path.resolve(this.getRootDir(), this.udid, "data");
    var keychainPath = path.resolve(base, "Library", "Keychains");
    var tempKeychainPath = path.resolve(tempDir, "simkeychains_" + this.udid);

    var removeKeychains = _.partial(ncp, keychainPath, tempKeychainPath);

    var returnKeychains = function (err, cb) {
      if (err) {
        return cb(err);
      }
      mkdirp(keychainPath, function (err) {
        if (err) { return cb(err); }
        ncp(tempKeychainPath, keychainPath, cb);
      });
    };

    var performWhileSavingKeychains = function (enclosed, cb) {
      async.waterfall([
        removeKeychains,
        enclosed,
        returnKeychains
      ], cb);
    };

    var cleanSim = _.partial(simctl.eraseDevice, this.udid);

    if (keepKeychains) {
      logger.debug("Resetting simulator and saving Keychains");
      performWhileSavingKeychains(cleanSim, cb);
    } else {
      cleanSim(cb);
    }

  }.bind(this);
Example #4
0
 var filterAll = function(forms, options, user) {
   // clone the forms list so we don't affect future filtering
   forms = forms.slice();
   var promises = _.map(forms, _.partial(filter, _, options, user));
   return $q.all(promises)
     .then(function(resolutions) {
       // always splice in reverse...
       for (var i = resolutions.length - 1; i >= 0; i--) {
         if (!resolutions[i]) {
           forms.splice(i, 1);
         }
       }
       return forms;
     });
 };
Amygdala.prototype.add = function(type, object, options) {
  // POST/PUT request for `object` in `type`
  //
  // type: schema key/store (teams, users)
  // object: object to update local and remote
  // options: extra options
  // -  url: url override

  // Default to the URI for 'type'
  options = options || {};
  _.defaults(options, {'url': this._getURI(type)});

  return this._post(options.url, object)
    .then(_.partial(this._setAjax, type).bind(this));
};
Example #6
0
 renderLayer: function() {
   if (!_.isNumber(this.state.lightboxSeqNum)) return null;
   var page = _.findWhere(this.props.workflow.get('pages'),
                          {sequence_num: this.state.lightboxSeqNum})
   var imageUrl = util.getPageUrl(this.props.workflow, page.capture_num,
                                  this.state.imageType, false);
   return (
     <Overlay>
       <Lightbox
         imageUrl={imageUrl} sequenceNumber={this.state.lightboxSeqNum}
         sequenceLength={this.props.workflow.get('pages').length}
         onBrowse={this.setLightbox}
         onClose={_.partial(this.setLightbox, null)} />
     </Overlay>);
 }
Example #7
0
exports.cr = function(req, res, next) {
  async.parallel([
      _.partial(db.getUserData, req.params.uname),
      _.partial(db.getAssignmentData, req.params.assign_id),
      _.partial(db.getSubmittedData, req.params.uname, req.params.assign_id),
      _.partial(db.getCRFiles, req.params.uname, req.params.assign_id),
      _.partial(db.getAssignmentGrade, req.params.uname, req.params.assign_id)],

  function(err, results) {
    if (err) {
      next(err);
      return;
    }
    
    console.assert(results.length === 5);
    res.render('cr', {
      student: results[0],
      assign: results[1],
      submitted: results[2],
      files: results[3],
      grade: results[4]
    });
  });
}
Example #8
0
var pushWithoutManifest = function(projectId, srcDir) {
	var fetchDir = new tmp.Dir();
	var buildPath = fetchDir.path;

	// Fetch project and create manifest; overwrite fetched project with srcDir;
	// and re-upload.
	return fetch(projectId, buildPath)
		.then(function(project) {
			var toDelete = buildPath + '/*.{js,html}';
			del.sync([toDelete], { force: true });
			fs.copySync(srcDir, buildPath);
			return gaps.upload(buildPath);
		})
		.then(_.partial(fs.removeSync, buildPath));
};
},{"underscore":7,"backbone":8,"./fn":6}],4:[function(require,module,exports){

var mixin    = require('./fn').mixin
  , _        = require('underscore')
  , Backbone = require('backbone')

/*
 * Base Collection
 */

module.exports = Backbone.Collection.extend({}, {
  mixin: _.partial(mixin, this)
})

},{"underscore":7,"backbone":8,"./fn":6}],6:[function(require,module,exports){
Amygdala.prototype.get = function(type, params, options) {
  // GET request for `type` with optional `params`
  //
  // type: schema key/store (teams, users)
  // params: extra queryString params (?team=xpto&user=xyz)
  // options: extra options
  // - url: url override

  // Default to the URI for 'type'
  options = options || {};
  _.defaults(options, {'url': this._getURI(type)});

  return this._get(options.url, params)
    .then(_.partial(this._setAjax, type).bind(this));
};
Example #11
0
 .then(function(){
   // Server 1
   return Q()
     .then(function() {
       return cat.selfCertPromise();
     })
     .then(function() {
       return toc.selfCertPromise();
     })
     .then(function() {
       return tic.selfCertPromise();
     })
     .then(_.partial(toc.certPromise, cat))
     .then(_.partial(cat.certPromise, toc))
     .then(_.partial(cat.certPromise, tic))
     .then(cat.joinPromise)
     .then(toc.joinPromise)
     .then(tic.joinPromise)
     .then(commitS1)
     .then(commitS1)
     .then(commitS1)
     .then(commitS1)
     .then(commitS1);
 })
Example #12
0
    render: function()
    {
        AmpersandFormView.prototype.render.apply(this, arguments);

        $( this.el ).find('input').prop('autocomplete', 'off');

        this.buttonTemplate = '<div class="btn-group"> \
  <a class="btn btn-large btn-primary dropdown-toggle" data-toggle="dropdown" href="#"> \
    New Model \
    <span class="caret"></span> \
  </a> \
  <ul class="dropdown-menu"> \
    <li><a data-hook="concentration" tabindex="-1" href="#">Concentration, Well-mixed</a></li> \
    <li><a data-hook="population" tabindex="-1" href="#">Population, Well-mixed</a></li> \
    <li><a data-hook="spatial" tabindex="-1" href="#">Population, Spatial</a></li> \
  </ul> \
</div>';

        this.button = $( this.buttonTemplate ).appendTo( $( this.el ) );

        $( this.el ).find('[data-hook=concentration]').click( _.bind(_.partial(this.submitCallback, 'concentration'), this));
        $( this.el ).find('[data-hook=population]').click( _.bind(_.partial(this.submitCallback, 'population'), this));
        $( this.el ).find('[data-hook=spatial]').click( _.bind(_.partial(this.submitCallback, 'spatial'), this));
    }
Example #13
0
module.exports = function (req, callback) {
    logger.log('application', 'Running delete topics task');

    var task = _.partial(hodRequestLib.deleteFromTextIndexPollingService,
        [req.session.domain, nconf.get('havenondemand:nps_index')].join(':'),
        true,
        req.session.tokenProxy
    );

    apiQueue.queueAsyncTask(task.bind(hodRequestLib), function(err, response) {
        if(err) return callback(err, response);

        return callback(null, response.result)
    });
};
Example #14
0
module.exports = function(config){
  

  var configuration = _.defaults({}, config, {
    file : './.cache.json',
    every : 60000,
    onexit : true
  });

  var cache = require('cachy-memory')();

  // on startup, load
  if(fs.existsSync(configuration.file)){
    var saved = fs.readJsonSync(configuration.file);
    if(saved) cache.load(saved);
    else throw new Error('Unable to load existing cache data @ ' + configuration.file);
  }

  var write = _.throttle(function(callback){
    fs.writeJson(configuration.file, cache.get(), callback);
  }, configuration.every);

  var intervalID = setInterval(write, configuration.every);
  intervalID.unref();

  var clean = _.partial(fs.removeSync,configuration.file);

 // on shutdown, write
  process.on('exit', function(code){
    if(configuration.onexit) fs.writeJsonSync(configuration.file, cache.get());
  });

 // xx- wrap in operation counter/flag, only write if diff
  return {
    write : cache.write,
    has : cache.has,
    read : cache.read,
    remove : cache.remove,
    clear : function(callback){
      clean();
      return cache.clear(callback);
    },
    keys : cache.keys,
    size : cache.size,
    version : pkg.version
  };

};
 addCommands(commandProcessor) {
   // !shaped-import-statblock
   return commandProcessor.addCommand('import-statblock', this.importStatblock.bind(this), true)
     .option('overwrite', ShapedConfig.booleanValidator)
     .option('replace', ShapedConfig.booleanValidator)
     .withSelection({
       graphic: {
         min: 1,
         max: Infinity,
       },
     })
     // !shaped-import-monster , !shaped-monster
     .addCommand(['import-monster', 'monster'], this.importMonstersFromJson.bind(this), true)
     .optionLookup('monsters', _.partial(this.entityLookup.findEntity.bind(this.entityLookup), 'monsters', _, false),
       true)
     .option('overwrite', ShapedConfig.booleanValidator)
     .option('relist', ShapedConfig.jsonValidator, false)
     .option('replace', ShapedConfig.booleanValidator)
     .option('as', ShapedConfig.stringValidator)
     .withSelection({
       graphic: {
         min: 0,
         max: 1,
       },
     })
     .addCommand('import-by-token', this.importByToken.bind(this), true)
     .option('overwrite', ShapedConfig.booleanValidator)
     .option('replace', ShapedConfig.booleanValidator)
     .withSelection({
       graphic: {
         min: 1,
         max: Infinity,
       },
     })
     .addCommand('update-character', this.updateCharacter.bind(this), true)
     .withSelection({
       character: {
         min: 0,
         max: Infinity,
         anyVersion: true,
       },
     })
     .option('all', ShapedConfig.booleanValidator)
     .addCommand('remove-monster', this.removeMonster.bind(this), true)
     .option('character', ShapedConfig.getCharacterValidator(this.roll20), true)
     .option('confirm', ShapedConfig.booleanValidator, true)
     .option('relist', ShapedConfig.jsonValidator, false);
 }
Example #16
0
 return function (done) {
   return co(function *() {
     let members = [];
     let nonmembers = [];
     let peers = yield dal.getRandomlyUPsWithout(without); // Peers with status UP
     for (let i = 0, len = peers.length; i < len; i++) {
       let p = peers[i];
       let isMember = yield dal.isMember(p.pubkey);
       isMember ? members.push(p) : nonmembers.push(p);
     }
     members = chooseXin(members, constants.NETWORK.MAX_MEMBERS_TO_FORWARD_TO);
     nonmembers = chooseXin(nonmembers, constants.NETWORK.MAX_NON_MEMBERS_TO_FORWARD_TO);
     return members.map((p) => (p.member = true) && p).concat(nonmembers);
   })
     .then(_.partial(done, null)).catch(done);
 };
Example #17
0
ElectionMap.prototype.drawBackgroundDistricts = function(districts) {
  if (!districts) { return; }
  var states = _.chain(districts)
    .map(function(district) {
      return Math.floor(district / 100);
    })
    .unique()
    .value();
  var stateDistricts = _.filter(utils.districtFeatures.features, function(feature) {
    return states.indexOf(Math.floor(feature.id / 100)) !== -1 &&
      districts.indexOf(feature.id) === -1;
  });
  L.geoJson(stateDistricts, {
    onEachFeature: _.partial(this.onEachDistrict.bind(this), _, _, {color: '#bbbbbb'})
  }).addTo(this.overlay);
};
Example #18
0
function addPicture(image, outputFolder, card) {
        
    var intermediaryImageOutput = outputFolder + "pokemon.png";

    function writeIntermediaryPicture(image) {
        return Q.ninvoke(image, "write",intermediaryImageOutput);
    }   
  
    console.log("Adding picture To card");
    
    return Q(image)
             .then(fitToCardBox)
             .then(writeIntermediaryPicture)
             .then(_.partial(mergePictureWithCard,intermediaryImageOutput,card));
    
}
Example #19
0
 function composeCreateServerPromise(command) {
     return Promise.resolve(command)
         .then(serverConverter.fetchGroupId)
         .then(_.partial(setGroupIdToCommand, command))
         .then(serverConverter.loadTemplate)
         .then(serverConverter.setManagedOs)
         .then(serverConverter.setHyperscaleServer)
         .then(serverConverter.setTemplateName)
         .then(serverConverter.convertDns)
         .then(serverConverter.convertMachine)
         .then(serverConverter.convertCustomFields)
         .then(serverConverter.convertTtl)
         .then(serverConverter.setPolicies)
         .then(serverConverter.setDefaultValues)
         .then(serverConverter.clearConfig);
 }
function fakeGlob(pattern, options, callbackFn) {
  should.deepEqual(options, {cwd: ROOT_SRC_DIR});

  if (pattern == '*fail-for-test*') {
    callbackFn(new Error('intentional glob failure for testing'));
    return;
  }

  var resolvedFiles = FAKE_RESOLUTIONS[pattern];
  if (!resolvedFiles) {
    should.fail('Not expecting glob.Glob() call with pattern ' + pattern);
  }

  // Return answer async.
  setTimeout(underscore.partial(callbackFn, null, resolvedFiles), 2 /* ms */);
}
Example #21
0
    return function (message, done) {
        function jobDone(result, next) {
            _this._isHandlingMessage = false;
            _this._lastJobDone = new moment();

            done(result);

            if(next) {
                // TODO: Add message to next queue
                throw new Error('next is not implemented yet');
            }
        }

        _this._isHandlingMessage = true;
        _this._options.handleMessage(message, jobDone, _.partial(jobDone, _, true));
    }
Example #22
0
export var fetch = function (options, cb) {
  options = _.clone(options);
  var ranges = options.ranges;
  options.after = getNextContiguous(options.after, ranges);
  options.before = getPrevContiguous(options.before, ranges);
  if (options.after >= options.before) return cb();
  api.get(options.url, {
    upcoming: true,
    per_page: PER_PAGE,
    after: options.after,
    before: options.before,
    direction: options.direction,
    restrict_to_portal: options.scope === 'portal' ? false : undefined,
    include_opportunities: options.scope === 'community' ? true : undefined,
    statuses: options.statuses
  }, _.partial(handleFetch, options, cb));
};
Example #23
0
 function action() {
     return db.collection('topics').findOneAsync({ '_id': tid }).
     then(function(topic) {return fill_topic_user_ratings(topic).return(topic);}).
     then(_.partial(topics.manageConsensusStage,_,0)).
     then(function(topic) {
         return db.collection('groups').find({ 'tid': tid, 'level': topic.level }).
         toArrayAsync().then(function(groups) {
             response_text += "<br/>level: " + topic.level + ", number of groups: " + _.size(groups) + ", sizes of each group: ";
             return groups;
         }).map(function(group) {
             return db.collection('group_relations').countAsync({'gid': group._id}).
             then(function(count) {
                 response_text += count + " ";
             });
         });
     });
 },true)).then(function() {res.status(200).send("<pre>"+response_text+"</pre>");});
Example #24
0
        _initializeList: function() {
            this.$listContainer.find('tbody').itemsManagerTable({
                collection:   this.collection,
                itemTemplate: this.itemTemplate,
                itemRender: function itemRenderer(template, data) {
                    var context = _.extend({__: __}, data);

                    return template(context);
                },
                deleteHandler: _.partial(function(collection, model, data) {
                    collection.remove(model);
                }, this.collection),
                sorting: false
            });
            // emulate reset for first time
            this._onCollectionChange();
        },
Example #25
0
DAGSP.prototype.calculateShortestPaths = function calculateShortestPaths(){
    var self = this;
    var topoOrder = topologicalSort(self.dag);
    var a, neighbors;
    var root = topoOrder[topoOrder.length-1];
    self.distTo[root] = 0;

    function _relax(a, b){
        self.relax([a, b, self.dag.edges[a][b]]);
    }

    while(topoOrder.length > 0){
        a = topoOrder.pop();
        neighbors = _.keys(self.dag.edges[a]);
        _.each(neighbors, _.partial(_relax, a));
    }
};
Example #26
0
const TopicListItem = component(({topicTreeNode, domainTopicTreeNode, options},
                                 {onClickTopic}) => {
    const topicClass = classNames({
        "topic-item": true,
        faded: options.get("showDownloadsOnly") &&
            getDownloadCount(topicTreeNode),
        [getId(domainTopicTreeNode)]: true,
    });
    return <li className={topicClass}>
        { getKey(topicTreeNode) === getKey(domainTopicTreeNode) &&
            <div className="color-block"/> }
        <a href="javascript:void(0)"
           onClick={_.partial(onClickTopic, topicTreeNode, domainTopicTreeNode)}>
            <p className="topic-title">{getTitle(topicTreeNode)}</p>
        </a>
    </li>;
}).jsx;
Example #27
0
Chromedriver.prototype.createSession = function (caps, cb) {
  logger.debug("Creating Chrome session");
  caps.chromeOptions.androidDeviceSerial = this.deviceId;
  if (this.enablePerformanceLogging) {
    caps.loggingPrefs = {performance: 'ALL'};
  }
  var data = {
    sessionId: null,
    desiredCapabilities: caps
  };
  async.waterfall([
    this.ensureChromedriverExists.bind(this),
    this.killOldChromedrivers.bind(this),
    this.start.bind(this),
    _.partial(this.proxyNewSession.bind(this), data)
  ], cb);
};
 function(docs, skip) {
   return Promise.resolve()
     .then(_.partial(utils.filterByDate, docs, startTimestamp, endTimestamp))
     .then(_.partial(utils.filterByType, _, 'person'))
     .then(_.partial(utils.filterFamilyMembers, _, logdir))
     // Remove contact links
     .then(_.partial(utils.cleanContactPersons, db, dryrun, logdir))
     .then(_.partial(utils.writeDocsToFile, logdir + '/persons_deleted_' + skip + '.json'))
     .then(_.partial(utils.writeDocsIdsToFile, logdir + '/persons_deleted_ids.json'))
     .then(_.partial(utils.deleteDocs, dryrun, db))
     .then(function(result) {
       console.log(result.length + ' persons deleted!\n');
       return result;
     });
 });
Example #29
0
 exports.loadPartial = function () {
     if (!this.config) {
         throw new Error('This DataLoader is disposed');
     }
     var configKeys = u.flatten([].slice.call(arguments, 0));
     var origConfig = this.getConfig();
     var config;
     if (u.isArray(origConfig)) {
         // 从数组中的每一个object中抽取出configKeys中指定的字段,
         // 组成一个新的数组并过滤掉空的object
         config = u.chain(origConfig).map(u.partial(u.pick, u, configKeys)).reject(u.isEmpty).value();
     }
     else {
         config = u.pick(origConfig, configKeys);
     }
     return this.loadByConfig(config).then(u.bind(this.reportLoadResult, this));
 };
Example #30
0
 fetchPage(daySeq) {
     //logger.debug("fetchPage start.day seq:" + daySeq);
     let nextLabel = "";
     if (daySeq != 0) {
         nextLabel = {
             "day": this.option.beginTime.format('YYYYMMDD'),
             "page": 0,
             "setPage": false,
             "setDay": true,
             "day_seq": daySeq,
             "setDay_seq": true
         };
         nextLabel = JSON.stringify(nextLabel);
     }
     let orderJar = request.jar();
     this.token.cookies.split(';').forEach((v)=> {
         orderJar.setCookie(request.cookie(v), meituanUri);
     });
     let orderOption = {
         jar: orderJar,
         headers: {
             'User-Agent': 'MeituanWaimai/3.0.1.0/32 Windows/6.1 Id/{5B0BFF35-BAF5-4403-A92B-C47497952E87}'
         },
         strictSSL: false,
         json: true,
         timeout: 5000
     };
     let orderParam = {
         getNewVo: 1,
         wmOrderPayType: 2,
         wmOrderStatus: -2,
         sortField: 1,
         startDate: this.option.beginTime.format('YYYY-MM-DD'),
         endDate: this.option.endTime.format('YYYY-MM-DD'),
         lastLabel: '',
         nextLabel: nextLabel
     };
     let getOrderURL = 'https://waimaie.meituan.com/v2/order/history/r/query?' + qs.stringify(orderParam);
     //logger.debug(getOrderURL);
     return request.getAsync(getOrderURL, orderOption).then((res)=> {
         //logger.debug("fetchPage end.");
         //logger.debug(JSON.stringify(res.body));
         return res.body.wmOrderList || [];
     }).map(_.partial(this.fetchPhone,this.token));
 }