return _.map(values, function (value) {
      var subValues = value.split('/');
      if (subValues.length != 2) {
        return null;
      }

      var indicesStr = subValues[ 0 ];
      var lengthStr = subValues[ 1 ];

      var indices = indicesStr.split('-');
      if (indices.length != 2) {
        return null;
      }

      var startIndexStr = indices[ 0 ];
      var startIndex = _.parseInt(startIndexStr);
      var endIndexStr = indices[ 1 ];
      var endIndex = _.parseInt(endIndexStr);
      if (!_.isNaN(startIndex) && !_.isNaN(endIndex)) {
        var length = _.parseInt(lengthStr);
        if (!_.isNaN(length)) {
          entity.length = length;
        }

        return {
          index: startIndex,
          length: endIndex - startIndex + 1
        };
      }
    });
  (req, res, next) => {
    const projectId = _.parseInt(req.params.projectId);
    const attachmentId = _.parseInt(req.params.id);

    models.ProjectAttachment.findOne(
      {
        where: {
          id: attachmentId,
          projectId,
        },
      })
    .then((attachment) => {
      if (!attachment) {
        const err = new Error('Record not found');
        err.status = 404;
        return Promise.reject(err);
      }
      if (process.env.NODE_ENV === 'development' || config.get('enableFileUpload') === false) {
        return ['dummy://url'];
      }
      return util.getFileDownloadUrl(req, attachment.filePath);
    })
    .then((result) => {
      const url = result[1];
      res.status(200).json(util.wrapResponse(req.id, { url }));
    })
    .catch((error) => {
      req.log.error('Error fetching attachment', error);
      const rerr = error;
      rerr.status = rerr.status || 500;
      next(rerr);
    });
  },
Beispiel #3
0
        function translation(str) {
            var c = [];
            for (var i = 0; i < str.length; i++) {
                var ch = str[i];
                var chHex = str.charCodeAt(i).toString(16);
                chHex = _.parseInt(chHex, 16);
                // console.log(typeof chHex);
                // console.log('before:');
                // console.log(chHex);
                /*全角=>半角*/
                if (chHex > 0xFF00 && chHex < 0xFF5F)
                    chHex = (chHex - 0xFEE0);

                /*大写=>小写*/
                if (chHex > 0x40 && chHex < 0x5b)
                    chHex = (chHex + 0x20);

                /*繁体=>简体*/
                if (chHex > 0x4E00 && chHex < 0x9FFF) {
                    var index = traChn.indexOf(ch);
                    if (index > 0) {
                        ch = simChn[index];
                        chHex = simChn.charCodeAt(index).toString(16);
                        chHex = _.parseInt(chHex, 16);
                    }
                    ;
                }
                // console.log('after:');
                // console.log(chHex);
                c.push(String.fromCharCode(chHex));
            }
            ;
            return c;
        };
exports.constructRequest = function(applicationName, commandName, sessionId) {
    var application = findApplication(applicationName);
    if (application == undefined) {
        throw new Error('Application ' + applicationName + ' not found in dictionary. ');
    }
    var command = findCommand(commandName);
    if (command === undefined) {
        throw new Error('Command ' + commandName + ' not found in dictionary. ');
    }

    var request = {
        header: {
            version: 1,
            commandCode: _.parseInt(command.code),
            flags: {
                request: true,
                proxiable: false,
                error: false,
                potentiallyRetransmitted: false
            },
            applicationId: _.parseInt(application.code),
            application: application.name,
            hopByHopId: -1, // needs to be set by client
            endToEndId: diameterUtil.random32BitNumber()
        },
        body: [],
        command: command.name
    };

    request.body.push(['Session-Id', sessionId.toString()]);

    return request;
};
exports.list = function*(next) {
    var page = _.parseInt(this.query.page),
        limit = _.parseInt(this.query.limit);

    if (_.isNaN(page)) page = 1;
    if (_.isNaN(limit)) limit = 10;
    if (limit <= 0) limit = 10;
    if (limit > 200) limit = 200;
    if (page < 0) page = 1;
    if (page > 100) page = 100;
    var skip = limit * (page - 1);

    var gifts;
    if (this.from === 'client') {
        gifts = yield Gift.find(this.condition, 'id info.name info.cover info.price')
            .limit(limit)
            .skip(skip)
            .sort('-_id')
            .exec();
        this.body = [this.count, gifts];
    }
    if (this.from === 'merchant') {
        gifts = yield Gift.find(this.condition, 'id info time status.online num')
            .limit(limit)
            .skip(skip)
            .sort('-_id')
            .exec();
        this.body = gifts;
    }
    return;
};
Beispiel #6
0
var prepareRequest = function (request) {
  var params = {};

  // For GET
  if (request.query) {
    params = request.query;
  }

  // For POST
  if (request.payload) {
    params = request.payload;

    // Crude hack for pagination lack of support for POST
    if (_.has(request.payload, 'page')) {
      request.page = _.parseInt(request.payload.page);
      request.payload = _.omit(request.payload, 'page');
    }

    if (_.has(request.payload, 'limit')) {
      request.limit = _.parseInt(request.payload.limit);
      request.payload = _.omit(request.payload, 'limit');
    }
  }

  return params;
};
Beispiel #7
0
Controller.prototype.getPaymentTypes = function(query, user){
   var limit = query['limit'] ? _.parseInt(query['limit']) : 10;
   var skip = query['skip'] ? _.parseInt(query['skip']) : 0;
   var match = {"inputLocation": objectId(user.location._id)};

   if(query['date'])
     match['date'] = new Date(query['date']);

   return model.aggregate([
       {"$match": match},
       {"$unwind": "$items"},
       {
         "$group": {
           "_id": "$payment.type",
           "colli": {"$sum": "$items.colli.quantity"},
           "weight": {"$sum": "$items.dimensions.weight"},
           "price": {"$sum": "$cost.total"},
           "shippings": {"$sum": 1}
         }
       },
       {"$lookup": {"from": "paymentTypes", "localField": "_id", "foreignField": "_id", "as": "category"}},
       {"$sort": {"category.name": 1}},
       {"$skip": skip},
       {"$limit": limit}
   ]).exec();
}
Beispiel #8
0
	listTweets: function(params) {
		var opts = {
			skip: _.parseInt( params.skip ) || 0,
			limit: _.parseInt( params.limit ) || app.config.feed.pagesize,
			sort: { id: -1 }
		};
		var query = {
			hidden: { $exists: false }
		};
		if(params.before && Date.parse( params.before )) {
			_.assign(query, { timestamp: { $lt: new Date( params.before ) } });
		}
		if(params.after && Date.parse( params.after )) {
			_.assign(query, { timestamp: { $gt: new Date( params.after ) } });
		}
		if(params.since && !_.isNaN( parseInt( params.since ) )) {
			_.assign(query, { id: { $gt: params.since } });
		}
		if(params.priorTo && !_.isNaN( parseInt( params.priorTo ) )) {
			_.assign(query, { id: { $lt: params.priorTo } });
		}

		var result = this.tweets.find( query, opts )
		.error(function(err) {
			console.log( '## Data error: ', err );
		});
		return Promise.cast( result );
	},
function updateVersionNumber(alloyConfig, alloyLogger, config) {

    alloyLogger.trace('********************* STARTING updateVersionNumber ***************************');
    var tiapp_path = path.join(alloyConfig.dir.project, 'tiapp.xml');
	alloyLogger.trace('tiapp.xml path:  ' + tiapp_path);
    var tiapp = require('tiapp.xml').load(tiapp_path);
    var stamp = Math.round((new Date()).getTime() / 1000.0);

	var releaseDate = tiapp.getProperty('releaseDate');
    var daysSinceRelease = Date.create().daysSince(releaseDate);
	alloyLogger.debug("releaseDate=" + releaseDate);
	alloyLogger.debug("daysSinceRelease=" + daysSinceRelease);

    var versions = tiapp.version.split('.');

    var buildNumber = _.parseInt(versions[2] || 0) || 0;
    //buildNumber++;

    
    var revisionNumber = _.parseInt(versions[3] || 0) || 0;
    revisionNumber++;

    //versions[3] = stamp.toString();

    
	versions[3] = ( versions[2] === daysSinceRelease.toString() ) ? revisionNumber.toString() : 0;
    versions[2] = daysSinceRelease.toString();

    tiapp.version = versions.join('.');
    tiapp.write();

    alloyLogger.trace('********************* FINISHED updateVersionNumber ***************************');
}
Beispiel #10
0
const getCanvasMousePoint = (e, viewCanvas) => {
    let scrollOffset = window.pageYOffset || document.documentElement.scrollTop,
        mouseX = e.clientX - viewCanvas.offsetLeft,
        mouseY = e.clientY - viewCanvas.offsetTop + scrollOffset,
        x = _.parseInt(mouseX / getTileSize()),
        y = _.parseInt(mouseY / getTileSize())
    return new Point(x, y)
}
var encodeAvp = function(avp, appId) {
    var avpTag;
    if (!_.isNumber(avp[0])) {
        avpTag = dictionary.getAvpByName(avp[0]);
    } else {
        avpTag = dictionary.getAvpByCode(avp[0]);
    }
    if (avpTag == null) {
        throw new Error('Unknown AVP code ' + avp[0] + ' for app ' + appId);
    }
    var value = avp[1];
    var avpDataBuffer;
    if (avpTag.type === 'Grouped') {
        avpDataBuffer = encodeAvps(value, appId);
    } else {
        if (avpTag.enums) {
            var enumCode;
            if (!_.isNumber(value)) {
                enumCode = _.find(avpTag.enums, {
                    name: value
                });
            } else {
                enumCode = _.find(avpTag.enums, {
                    code: value
                });
            }
            if (enumCode == null) {
                throw new Error('Invalid enum value ' + value + ' for ' + avpTag.name);
            }
            value = enumCode.code;
        }
        avpDataBuffer = diameterTypes.encode(avpTag.type, value);
    }

    var avpHeaderLength = DIAMETER_MESSAGE_AVP_HEADER_LENGTH_IN_BYTES;
    if (avpTag.flags.vendorBit) {
        // 4 extra bytes for vendor id
        avpHeaderLength += DIAMETER_MESSAGE_VENDOR_ID_LENGTH_IN_BYTES;
    }
    var avpHeaderBuffer = new Buffer(avpHeaderLength);
    avpHeaderBuffer.writeUInt32BE(_.parseInt(avpTag.code), DIAMETER_MESSAGE_AVP_CODE);

    var flags = [avpTag.flags.vendorBit, avpTag.flags.mandatory, avpTag.flags['protected']];
    var flagsInt = getIntFromBits(_.flatten([flags, [false, false, false, false, false]]));
    avpHeaderBuffer.writeUInt8(flagsInt, DIAMETER_MESSAGE_AVP_FLAGS);
    writeUInt24BE(avpHeaderBuffer, DIAMETER_MESSAGE_AVP_LENGTH, avpDataBuffer.length + avpHeaderBuffer.length);

    if (avpTag.vendorId > 0) {
        avpHeaderBuffer.writeUInt32BE(_.parseInt(avpTag.vendorId), DIAMETER_MESSAGE_AVP_VENDOR_ID);
    }

    if (avpDataBuffer.length % 4 !== 0) {
        var filler = new Buffer(4 - avpDataBuffer.length % 4);
        filler.fill(0);
        avpDataBuffer = Buffer.concat([avpDataBuffer, filler]);
    }
    return Buffer.concat([avpHeaderBuffer, avpDataBuffer]);
};
Beispiel #12
0
 return collection.fetch(options).tap(function() {
   res.paging = {
     total: _.parseInt(collection.total),
     count: _.parseInt(collection.models.length),
     limit: _.parseInt(options.limit),
     offset: _.parseInt(options.skip),
     page: Math.ceil(_.parseInt(options.skip) / _.parseInt(options.limit)) + 1,
     pages: Math.ceil(_.parseInt(collection.total) / _.parseInt(options.limit)),
     has_more: _.parseInt(collection.models.length) < _.parseInt(collection.total)
   };
 }).bind(this).then(this.render(req, res, next)).catch(next);
Beispiel #13
0
						getHits(to, parts[1], function(err, data) {
							if (err) {
								log('getHits err:', err, data);
								return;
							}

							if (_.parseInt(data, 10) > 0) {
								bot.say(to, parts[1] + ' has been searched for ' + data + ' time' + (_.parseInt(data, 10) !== 1 ? 's.' : '.'));
							} else {
								bot.say(to, parts[1] + ' has never been searched for.');
							}
						});
Beispiel #14
0
  .transform(function (parts, v, i) {
    var name = versions[i];

    if (name !== 'patch') {
      parts[name] = _.parseInt(v);
      return;
    }

    // patch is two parts, a version number and an optional tag
    v = v.split('-');
    parts.patch = _.parseInt(v.shift());
    parts.tag = v.join('-');
  }, {})
					.findOne({_id: node.name}).exec(function(err, field){
						if(err) {
							console.log(err);
							throw new Error(err);
						} 

						if(!!_.parseInt(field.fieldValue)){
							that.expressionScope[node.name] = _.parseInt(field.fieldValue);
						}else {
							that.expressionScope[node.name] = field.fieldValue;						
						}
						console.log('_id: '+node.name);
						console.log('value: '+that.expressionScope[node.name]);
			    });
var processAge = function(url, age) {
    var now,
        endDate,
        startDate;

    // If age is a valid integer
    if (age && _.isFinite(_.parseInt(age))) {
        now = moment();
        endDate = now.format('YYYY-MM-DD');
        startDate = now.subtract(_.parseInt(age), 'months').format('YYYY-MM-DD');
        url += '+AND+recall_initiation_date:[' + startDate + '+TO+' + endDate + ']';
    }
    return url;
};
Beispiel #17
0
function please(config) {
    /* set default values if not specified */
    config.repeat = nconf.get('repeat') || null;
    /* this is parsing concurrency, but the amount retrieved if server side fixed of 5 */
    config.snippetConcurrency = _.parseInt(nconf.get('concurrency')) || 5;

    if(!_.isObject(config.requirements)) {
        throw new Error(
            "Developer, requirements has to be an object and check `repeat`");
    }

    return importKey(config)
        .then(function(xtConfig) {
            return snippetAvailable(xtConfig, 'content')
                .map(function(snippet) {
                    var newmeta = config.implementation(snippet);
                    return commitResult(config, newmeta, snippet);
                }, {concurrency: config.snippetConcurrency});
        })
        .then(function(done) {
            return _.size(done);
        })
        .catch(function(error) {
            console.error("Execution failure, consult the documentaton");
            console.error(error);
        });
};
function assertWorker(t, worker) {
  var isN = _.isFinite;
  t.assert(isN(_.parseInt(worker.id, 10)), 'id invalid: ' + worker.id);
  t.assert(isN(worker.uptime), 'uptime invalid: ' + worker.uptime);
  t.assert(isN(worker.startTime), 'startTime invalid: ' + worker.startTime);
  t.assert(isN(worker.pid) && worker.pid >= 1, 'pid invalid: ' + worker.pid);
}
Beispiel #19
0
app.delete('/api/comments/:id', function(req, res) {
  commendId = req.params.id;
  if(_.isEmpty(commendId)) {
    res.status(500).send('invalid comment id');
    return;
  }
  commendId = _.parseInt(commendId);
  fs.readFile(COMMENTS_FILE, function(err, data){
    if(err) {
      console.error(err);
      process.exit(1);
    }
    var comments = JSON.parse(data);
    _.remove(comments, function(comment) {
      return comment.id === commendId
    });
    fs.writeFile(COMMENTS_FILE, JSON.stringify(comments, null, 4), function(err) {
      if(err) {
        console.error(err);
        process.exit(1);
      }
      res.json(comments);
    });
  });
});
Beispiel #20
0
function getSVG(emblem, opts, fnCallback) {
    if (!emblem) {
        fnCallback('NoEmblem');
    }
    else {
        const outputSize = _.parseInt(opts.size).toString();
        const bgColor = (_.isString(opts.bgColor) && opts.bgColor.length > 0)
            ? `#${opts.bgColor}`
            : 'none';

        const background = getEmblemBackground(emblem, outputSize);
        const foreground = getEmblemForeground(emblem, outputSize);


        const emblemSvg = [
            `<svg width="${outputSize}" height="${outputSize}" viewBox="0 0 ${outputSize} ${outputSize}" shape-rendering="geometricPrecision" version="1.1" xmlns="http://www.w3.org/2000/svg">`,
                '<desc>Created by https://guilds.gw2w2w.com/</desc>',
                `<rect x="0" y="0" width="${outputSize}" height="${outputSize}" fill="${bgColor}" stroke="none" />`,
                background,
                foreground,
            '</svg>',
        ].join('');


        fnCallback(null, emblemSvg);
        // optimizeSVG(emblemSvg, fnCallback);
    }
}
Beispiel #21
0
			database.query( countquery, pager_args.condition_args, function (err, result) {
				if ( err ) { console.log( countquery ); callback(err, null); return; }

				var total_count = _.parseInt( App.model('common').safeGetCount( result ) );
				
				if( !_.isNull( current ) )
				{
					offset_limit = self.culcOffset( current, limit, total_count );
				}

				var arg = {
					prelink		: pager_args.prelink,
					current		: offset_limit.current,//pager_args.current,
					rowsPerPage	: pager_args.rowsPerPage,
					totalResult	: total_count,
					pageLinks	: 20
				};

				var pager = new pagination.SearchPaginator( arg );

				var paginator = {
					page_index : self.renderPager( pager.getPaginationData() ),
					page_detail: pager.getPaginationData()
				};
				
				var valuequery = "SELECT " + column + " FROM " + from + " " + where + ( ( order ) ? " ORDER BY " + order : "" ) + ( ( limit ) ? " LIMIT " + limit : "" ) + ( " OFFSET " + offset_limit.offset );

				database.query( valuequery, pager_args.condition_args, function (err, result) {
					if ( err ) { console.log( valuequery ); callback(err, null); return; }

					var data = App.model('common').safeGetResult( result );
					
					exit( err, { paginator : paginator, data: data } );
				});
			});
Validation.validateSample = function(sample) {

    var errors = [];
    if (!validator.isInt(sample.type) || _.parseInt(sample.type) <= 0) {
        errors.push(Validation.INVALID_DATA_TYPE_ID + sample.type);
    }
    /* //Biobank Code is autogenerate if missing??
     *
    if (!sample.biobankCode) {
        errors.push(Validation.MISSING_BIOBANK_CODE);
    } */
    if (!sample.metadata || _.isEmpty(sample.metadata)) {
        errors.push(Validation.MISSING_METADATA);
    }
    if (!validator.isJSON(JSON.stringify(sample.metadata)) || !_.isObject(sample.metadata)) {
        errors.push(Validation.INVALID_METADATA + sample.metadata);
    }
    if (!sample.biobank) {
        errors.push(Validation.MISSING_BIOBANK_ID); 
    }
    if (sample.biobank && !validator.isInt(sample.biobank)) {
        errors.push(Validation.INVALID_BIOBANK_ID + sample.biobank);
    }
    if (sample.donor && !validator.isInt(sample.donor)) {
        errors.push(Validation.INVALID_DONOR_ID + sample.donor);
    }
    if (sample.parentSample && !validator.isInt(sample.parentSample)) {
        errors.push(Validation.INVALID_PARENT_SAMPLE_ID + sample.parentSample);
    }

    return errors.length ? errors : null;

};
Validation.validateSubject = function(subject) {

    var errors = [];
    if (!validator.isInt(subject.type) || _.parseInt(subject.type) <= 0) {
        errors.push(Validation.INVALID_DATA_TYPE_ID + subject.type);
    }
    if (subject.tags && !_.isArray(subject.tags)) {
        errors.push(Validation.INVALID_TAG + subject.tags);
    }
    // silently fix sex errors
    if (!subject.sex || !validator.isIn(subject.sex, ['M', 'F', 'N.D.', 'UNKNOWN', 'UNDIFFERENTIATED'])) {
        subject.sex = 'N.D.';
    }
    /*
    if (subject.personalInfo && !validator.isInt(subject.personalInfo)) {
        errors.push(Validation.INVALID_PERSONAL_INFO_ID + subject.personalInfo);
    } */
    /* // is Metadata required for Subjects?? 
     *
    if (!data.metadata || _.isEmpty(data.metadata)) {
        errors.push(Validation.MISSING_METADATA);
    } */
    if (!validator.isJSON(JSON.stringify(subject.metadata)) || !_.isObject(subject.metadata)) {
        errors.push(Validation.INVALID_METADATA + subject.metadata);
    }
    errors.forEach(function(error) {
        console.log(error);
    });
    return errors.length ? errors : null;
};
Beispiel #24
0
        .then((top) => {
            let end = new Date();

            console.log(' '.repeat(16) + 'Done!'.header, '耗时:', `${end - start} ms,`.em, '最近',
                        `${_.parseInt(top.option.qs.span)}`.em, '月', (type === 'BV')?'买入总额前':'卖出总额前',
                        `${top.data.length}`.em, ' '.repeat(3), 'By TraceInvest.com\n' );
        })
Beispiel #25
0
function timelineSearch(timewindow, user) {

    var filter = {
        startTime: {
            "$gt": new Date(timewindow.start),
            "$lt": new Date(timewindow.end) 
        },
        nonfeed: { "$exists": false },
        userId: _.parseInt(user.id)
    };
   
    return mongo
        .read(nconf.get('schema').timelines, filter, { startTime: -1 })
        .map(function(e, i) {
            e.name = user.name;
            return e;
        })
        .tap(function(r) {
            debug("¹ user %j contributed with %d timelines in %s between %s and %s",
                user, _.size(r), 
                moment.duration(moment(timewindow.start) - moment(timewindow.end) ).humanize(),
                timewindow.start, timewindow.end
            );
        })
        .map(lookintoHTMLs, { concurrency: 1 })
        .then(_.flatten)
        .tap(function(r) {
            debug("² user %j contributed with %d posts", user, _.size(r));
        });
};
Beispiel #26
0
                        getTotalHits(to, function(err, data) {
                            if (err) {
                                log('getTotalHits err', err, data);
                            }

                            var totalHits = _.parseInt((_.isNull(data) ? 0 : data), 10);

                            getLeaderboard(to, function(err, data) {
                                if (err) {
                                    log('getLeaderboard err', err, data);
                                }

                                var leaders = _.map(
										_.sortBy(
											_.filter(
													_.map(data, function(item, key) {
														return [key, item];
													}), function(item) {
														return item[0] !== 'TOTAL';
											}) ,
									function (value){
										return _.parseInt(value[1], 10);
									})
								.reverse()
								.slice(0, 15),
                                function(item) {
									return item[0] + ': ' + item[1] + ' (' + _.parseInt((item[1] / totalHits) * 100, 10) + '%)';
								}).join(', ');

					            bot.say(to, totalHits + ' total CFDocs search' + ( totalHits !== 1 ? 'es' : '') + '. Most searched queries: ' + leaders);
                            });
                        });
Validation.validateData = function(data) {

    var errors = [];
    if (!validator.isInt(data.type) || _.parseInt(data.type) <= 0) {
        errors.push(Validation.INVALID_DATA_TYPE_ID + data.type);
    }
    if (data.date && !validator.isDate(data.date)) {
        errors.push(Validation.INVALID_DATE + data.date);
    }
    if (data.tags && !_.isArray(data.tags)) {
        errors.push(Validation.INVALID_TAG + data.tags);
    }
    if (!data.metadata || _.isEmpty(data.metadata)) {
        errors.push(Validation.MISSING_METADATA);
    }
    if (!validator.isJSON(JSON.stringify(data.metadata)) || !_.isObject(data.metadata)) {
        errors.push(Validation.INVALID_METADATA + data.metadata);
    }
    if (data.parentSubject && !validator.isInt(data.parentSubject)) {
        errors.push(Validation.INVALID_PARENT_SUBJECT_ID + data.parentSubject);
    }
    if (data.parentSample && !validator.isInt(data.parentSample)) {
        errors.push(Validation.INVALID_PARENT_SAMPLE_ID + data.parentSample);
    }
    if (data.parentData && !validator.isInt(data.parentData)) {
        errors.push(Validation.INVALID_PARENT_DATA_ID + data.parentData);
    }
    return errors.length ? errors : null;

};
Beispiel #28
0
exports.create = function *create(field, files) {
  var e;

  if (files.length < 2) {
    e = new Error('at least two files required');
    e.expose = true;
    throw e;
  }

  var bikeshed = {
    id: field.id,
    time: _.now(),
    name: field.name || '',
    description: field.description || '',
    hidden: (field.hidden === 'true') || false,
    limit: _.parseInt(field.limit) || 60,
    totalVotes: 0
  };

  for (var i = files.length - 1; i >= 0; i--) {
    bikeshed[(i + 1)] = {
      score: 0,
      fieldname: files[i].fieldname,
      filename: files[i].filename,
      fileId: files[i].fileId,
      path: files[i].path
    };
  }

  return yield r.table('bikesheds').insert(bikeshed, {returnVals: true}).run();

};
    _.forEach(charVals.params, function (param, idx) {
        var valType = charVals.types[idx];

        if ( valType === 'string' ) {
            if (self.uuid === '0x2a46') chunkRules.push(ru.string(param, bBuf.length - 2));
            else chunkRules.push(ru.string(param, bBuf.length));
        } else if (_.startsWith(valType, 'addr')) {
            chunkRules.push(ru['charAddr'](param, _.parseInt(valType.slice(4))));
        } else if ( valType === 'nibble') {
            nibbleBuf.push(param);
            if (nibbleBuf.length === 2) {
                chunkRules.push(ru[valType](nibbleBuf[0], nibbleBuf[1]));
            }
        } else if ( valType === 'uuid' ) {
            if (self.uuid === '0x2802') {
                chunkRules.push(ru['uuid'](param, bBuf.length - 4));
            } else if (self.uuid === '0x2803' || self.uuid === '0x7890') {
                chunkRules.push(ru['uuid'](param, bBuf.length - 3));
            } else if (self.uuid === '0x2a7d') {
                chunkRules.push(ru['uuid'](param, bBuf.length - 2));
            } else {
                chunkRules.push(ru['uuid'](param, bBuf.length));
            }
        } else if ( valType === 'obj' ) {
            chunkRules.push(ru['obj'](param, charVals.objInfo, bBuf.length));
        } else {
            chunkRules.push(ru[valType](param));
        }
    });
Beispiel #30
0
function exportText(req) {

    var sharedFields = ['permaLink', 'source', 'text', 'impressionId', 'id', 'savingTime', 'feedBasicInfo' ];

    if( req.params.key !== nconf.get('password') )
        return { text: "key error" };

    var now = _.parseInt(req.params.seconds);
    if(_.isNaN(now)) {
        now = moment().utc().unix();
        debug("Sanity check fail [%s], forced now at %s %s",
            req.params.seconds,
            now,
            moment.unix(now)
        );
    }

    if(_.isNull(last)) {
        last = moment()
                .subtract(3, 'minutes')
                .unix();
        debug("because `last` is null, is configured to check three minutes ago: %s",
            moment.unix(last).utc()
        );
    }

    if(moment.unix(last).isBefore(moment.utc().subtract(1, 'hour'))) {
        debug("because the `last is too old (%s), will be forced to 1 hour ago",
            moment.unix(last).utc()
        ); 
        last = moment().subtract(1, 'hour').unix();
        debug("and now is: %s", moment.unix(last).utc() );
    }

    var filter = {
        "text": { "$exists": true },
        savingTime: {
            "$gt": new Date(last * 1000),
            "$lt": new Date(now * 1000)
        }
    };

    last = now;

    return mongo
        .read(nconf.get('schema').htmls, filter)
        .map(function(html) {
            return _.pick(html, sharedFields);
        })
        .map(function(info) {
            info.visibility = "public";
            return info;
        })
        .then(function(infos) {
            debug("with filter %j are returned %d impressions", filter, _.size(infos));
            return { json: infos };
        });

};