Пример #1
0
 request.then(response => {
   clearTimeout(requestTimeout);
   if (isRequestAlive) {
     // We got a response, we can clear the timeout.
     if (response.status >= 200 && response.status < 300) {
       // Got a response code that indicates success, resolve the promise.
       resolve(response);
     } else if (shouldRetry(requestsAttempted)) {
       // Fetch was not successful, retrying.
       // TODO(#7595849): Only retry on transient HTTP errors.
       warning(false, 'fetchWithRetries: HTTP error, retrying.'),
       retryRequest();
     } else {
       // Request was not successful, giving up.
       const error: any = new Error(sprintf(
         'fetchWithRetries(): Still no successful response after ' +
         '%s retries, giving up.',
         requestsAttempted
       ));
       error.response = response;
       reject(error);
     }
   }
 }).catch(error => {
Пример #2
0
correos.getInfo = function (id, cb) {
    request(sprintf(URL, utils.getPostalCode(id), id), function (error, response, body) {
        if (error || response.statusCode != 200) {
            cb(utils.errorDown())
            return
        }

        // Not found
        if (body.indexOf('portlet-msg-error') != -1) {
            cb(utils.errorNoData())
            return
        }

        let entity = null
        try {
            entity = createCorreosEntity(body, id)
            entity.retries = response.attempts
        } catch (error) {
            return cb(utils.errorParser(id, error.message))
        }

        cb(null, entity)
    })
}
Пример #3
0
db.open(function(err, db) {
    if (!err) {
        console.log(sprintf("Connected to the %s database.", dbName.toString()));
        db.collection(collectionName, {strict : true}, function(err, collection) {
            if (err) {
                console.log(sprintf("The %s collection does not exist.", collectionName));
                db.createCollection(collectionName, function(err, result) {
                    if (err) {
                        console.log("The collection could not be created.");

                    }
                    else
                    {
                        console.log(sprintf("The collection %s was successfully created!", collectionName));
                    }
                });
            }
        });
    }
    else
    {
        console.log("There was an error connecting to the database.");
    }
});
Пример #4
0
export function genRange(prompt, id, cls, minv, maxv, defval ){
	return sprintf('<label id="lab_%s">%s<input type="range" id="%s" class="%s" min="%d" max="%d" value="%d"></label>', 
			id, prompt, id, cls, minv, maxv, defval );
}
Пример #5
0
export function genMsg(prompt, id, cls, initval){
	var html = sprintf('<label id="lab_%s">%s <span id="%s" class="%s">%s</span></label>', 
			id, prompt, id, cls, initval);
	return html;
}
Пример #6
0
CtorCall.prototype.print = function(ind) {
  return ind + sprintf('%s(%s)',
    this.identifier.print(),
    this.args.map(function(x) { return x.print(''); }).join(', ')
  );
};
Пример #7
0
 angular.forEach(shareMessage, function(val, key) {
   shareMessage[key] = sprintf(val, shareURL);
 });
Пример #8
0
'use strict';

const {PropTypes} = require('React');

const isRelayContainer = require('isRelayContainer');
const isRelayEnvironment = require('isRelayEnvironment');
const sprintf = require('sprintf');

const RelayPropTypes = {
  Container(props: Object, propName: string, componentName: string): ?Error {
    const component = props[propName];
    if (component == null) {
      return new Error(sprintf(
        'Required prop `%s` was not specified in `%s`.',
        propName,
        componentName
      ));
    } else if (!isRelayContainer(component)) {
      return new Error(sprintf(
        'Invalid prop `%s` supplied to `%s`, expected a RelayContainer.',
        propName,
        componentName
      ));
    }
    return null;
  },

  Environment(props: Object, propName: string, componentName: string): ?Error {
    const context = props[propName];
    if (!isRelayEnvironment(context)) {
Пример #9
0
 (function next() {
   ch.put(sprintf('%s %d', msg, i++), function () {
     setTimeout(next, Math.floor(Math.random() * 1000));
   });
 })();
Пример #10
0
	handlebars.registerHelper("tag", function(tag, options) {
		return new handlebars.SafeString(
			sprintf("<a class='tag' href='/tag/%s' style='background-color: %s;'>%s</a>", tag, hashStringToColor(tag), tag)
		)
	})
Пример #11
0
 serverDetailsURL: function() {
   return sprintf( "%s/$/server", this.baseURL() );
 },
 function () {
   return sprintf('It is hard to adapt to %s, but it can be done.',
                  coolSample(states));
 }
Пример #13
0
 .forEach(function(pair) {
     console.log(sprintf('%15s: %s', pair[0], pair[1]));
 });
 function () {
   return sprintf('Everything was %s, and nothing %s.',
                  coolSample(adjectives),
                  coolSample(pastVerbs));
 },
Пример #15
0
 lodashForOwn(attributes, function(value, key) {
   if (typeof value === 'undefined') {
     throw new Error(sprintf(ERROR_MESSAGES.UNDEFINED_ATTRIBUTE, MODULE_NAME, key));
   }
 });
Пример #16
0
	results.forEach(function (s){
		console.log(sprintf("%5s %9s %s", s[0], filesize(s[1]), s[2]));
		t += s[1];
	});
Пример #17
0
 datasetEndpointURL: function( endpoint ) {
   return sprintf( "%s%s/%s", this.baseURL(), this.name(), endpoint );
 },
NumberFormatter.prototype.format = function (value) {
    return sprintf(this.formatString, value.getRealValue());
};
Пример #19
0
 statisticsURL: function() {
   return sprintf( "%s/$/stats%s", this.baseURL(), this.name() );
 },
Пример #20
0
 .then(function(page) {
   // if page found, cannot cannot rename to that path
   return res.json(ApiResponse.error(sprintf('このページ名は作成できません (%s)。ページが存在します。', newPagePath)));
 }).catch(function(err) {
Пример #21
0
 statsURL: function() {
   return sprintf( "%s/$/stats", this.managementURL() );
 },
Пример #22
0
 it('should throw an error if the object is not valid', function() {
   assert.throws(function() {
     jsonSchemaValidator.validate({'type': 'number'}, 'not a number');
   }, sprintf(ERROR_MESSAGES.INVALID_DATAFILE, 'JSON_SCHEMA_VALIDATOR', '', 'string value found, but a number is required'));
 });
Пример #23
0
 args.forEach(function(v) {
   if (/^-[a-zA-Z0-9]$/.test(v) && !~cfg.indexOf(v)) throw ArgParseError(sprintf('Invalid option %s', args[i]));
 });
Пример #24
0
 it('should throw an error if no schema is passed in', function() {
   assert.throws(function() {
     jsonSchemaValidator.validate();
   }, sprintf(ERROR_MESSAGES.JSON_SCHEMA_EXPECTED, 'JSON_SCHEMA_VALIDATOR'));
 });
Пример #25
0
function loc(start, end) {
  end = end || start;
  // console.log($$.toString(), $$);
  var sprintf = require('sprintf');
  return sprintf("$$.loc = yy.src.loc(@%d, @%d);", start, end);
}
Пример #26
0
 it('should throw an error if no json object is passed in', function() {
   assert.throws(function() {
     jsonSchemaValidator.validate({'type': 'number'});
   }, sprintf(ERROR_MESSAGES.NO_JSON_PROVIDED, 'JSON_SCHEMA_VALIDATOR'));
 });
Пример #27
0
/**
 * Returned message could have "\n" - this indicates a multi-line response.
 */
function universalMessageHandler(DbClient, db, playerSteam64Id, personaName, message, callback) {
    // all commands sent to bot need to start with ! (exclamation point)
    // shortest message is !help so ensure message at least 5 chars
    if (message.substring(0, 1) == "!" && message.length >= 5) {

        var responseMsg = "Something went terribly wrong if you are reading this. Please inform my creator at " + config.creator.email + ".";

        var params = message.split(" ");
        var command = params[0] == null ? "" : params[0];
        var param = params[1] == null ? "" : params[1];

        var trueCommand = command.toLowerCase();
        switch (trueCommand) {
            case "!register":
                //trace.debug("universalMessageHandler: !register for " + playerSteam64Id);
                DbClient.Register(db, playerSteam64Id, personaName, ranking.InitialRating, 0, function (err) {
                    //trace.debug("universalMessageHandler: error code from database " + err);
                    switch (err) {
                        case errCodes.DATABASE_FAILURE:
                            responseMsg = personaName+", I couldn't register you due to a database error. Please try again later.";
                            break;
                        case errCodes.USER_ALREADY_REGISTERED:
                            responseMsg = personaName+", you are already registered.";
                            break;
                        case errCodes.SUCCESS:
                            responseMsg = personaName+", you are now registered.";
                            break;
                    }
                    return callback (err, responseMsg);
                });
                break;
            case "!games":
                DbClient.GetCurrentGames(db, function (err, games) {
                    switch (err) {
                        case errCodes.DATABASE_FAILURE:
                            responseMsg = "I can't list the current games due to a database error. Please try again later.";
                            break;
                        case errCodes.NO_SEASONS_FOUND:
                            responseMsg = "No seasons were found. Please alert my creator or find an admin.";
                            break;
                        case errCodes.SUCCESS:
                            if (games.length == 0) {
                                err = errCodes.NO_CURRENT_GAMES;
                                responseMsg = sprintf("%s, there are currently no games waiting for players or in progress.", personaName);
                            } else {
                                // we have to clear our default
                                responseMsg = "";
                                for (var i = 0; i < games.length; i++) {
                                    var game = games[i];
                                    responseMsg += sprintf("Game #%04u | %17s | %2u players signed\n", game.gameNum, game.status, game.players.length);
                                }
                            }
                            break;
                    }
                    return callback(err, responseMsg);
                });
                break;
            case "!newgame":
                DbClient.NewGame(db, playerSteam64Id, function (err, currGame) {
                    switch (err) {
                        case errCodes.DATABASE_FAILURE:
                            responseMsg = personaName+", I cannot create a new game for you due to a database error. Please try again later.";
                            break;
                        case errCodes.NO_SEASONS_FOUND:
                            responseMsg = "No seasons were found. Please alert my creator or find an admin.";
                            break;
                        case errCodes.USER_NOT_REGISTERED:
                            responseMsg = personaName+", you must register before you attempt to create a game.";
                            break;
                        case errCodes.USER_ALREADY_SIGNED:
                            responseMsg = personaName+", you are already signed into game #" + currGame.gameNum;
                            break;
                        case errCodes.SUCCESS:
                            responseMsg = personaName+", I have created game #" + currGame.gameNum + " for you.";
                            break;
                    }
                    return callback(err, responseMsg);
                });
                break;
            case "!cancel":
                var targetGameNum = parseInt(param);
                if (targetGameNum >= 0) {
                    DbClient.CancelGame(db, playerSteam64Id, targetGameNum, false /* no sysOverride */, function (err) {
                        switch (err) {
                            case errCodes.DATABASE_FAILURE:
                                responseMsg = personaName+", I cannot cancel game #" + targetGameNum+ " for you due to a database error. Please try again later.";
                                break;
                            case errCodes.NO_SEASONS_FOUND:
                                responseMsg = "No seasons were found. Please alert my creator or find an admin.";
                                break;
                            case errCodes.USER_NOT_REGISTERED:
                                responseMsg = personaName+", you must register before you attempt to cancel a game.";
                                break;
                            case errCodes.UNAUTHORIZED:
                                responseMsg = personaName+", you must be the game creator or an admin to cancel a game.";
                                break;
                            case errCodes.SUCCESS:
                                responseMsg = personaName+", I have cancelled game #" + targetGameNum + " for you.";
                                break;
                        }
                        return callback(err, responseMsg);
                    });
                } else {
                    responseMsg = personaName+", please specify a game number to cancel.";
                    return callback(errCodes.SUCCESS, responseMsg);
                }
                break;
            case "!sign":
                var targetGameNum = parseInt(param);
                if (targetGameNum >= 0) {
                    DbClient.SignGame(db, playerSteam64Id, targetGameNum, function (err, updatedGame) {
                        switch (err) {
                            case errCodes.DATABASE_FAILURE:
                                responseMsg = sprintf("%s, I cannot sign you into game #%u due to a database error. Please try again later.", personaName, targetGameNum);
                                break;
                            case errCodes.NO_SEASONS_FOUND:
                                responseMsg = "No seasons were found. Please alert my creator or find an admin.";
                                break;
                            case errCodes.USER_NOT_REGISTERED:
                                responseMsg = personaName+", you must register before you attempt to sign into a game.";
                                break;
                            case errCodes.GAME_NOT_FOUND:
                                responseMsg = sprintf("%s, I could not find game #%u to sign you into.", personaName, targetGameNum);
                                break;
                            case errCodes.USER_ALREADY_SIGNED:
                                responseMsg = personaName + ", you are already signed into game #" + targetGameNum+".";
                                break;
                            case errCodes.SUCCESS:
                                var playersNeeded = 10 - updatedGame.players.length;
                                if (playersNeeded > 0) {
                                    responseMsg = sprintf("%s, you are now signed into game #%u. The game needs %u more players to start.", personaName, targetGameNum, playersNeeded);
                                } else {
                                    responseMsg = sprintf("%s, you are now signed into game #%u.", personaName, targetGameNum);
                                    responseMsg += sprintf("\nGame #%u can be started at any time by the game creator or an admin.", targetGameNum);
                                }
                                break;
                        }
                        return callback(err, responseMsg);
                    });
                } else {
                    responseMsg = personaName+", please specify a game number to sign to.";
                    return callback(errCodes.SUCCESS, responseMsg);
                }
                break;
            case "!unsign":
                var targetGameNum = parseInt(param);
                if (targetGameNum >= 0) {
                    DbClient.UnsignGame(db, playerSteam64Id, targetGameNum, function (err, game) {
                        switch (err) {
                            case errCodes.DATABASE_FAILURE:
                                responseMsg = sprintf("%s, I cannot unsign you from game #%u due to a database error. Please try again later.", personaName, targetGameNum);
                                break;
                            case errCodes.NO_SEASONS_FOUND:
                                responseMsg = "No seasons were found. Please alert my creator or find an admin.";
                                break;
                            case errCodes.USER_NOT_REGISTERED:
                                responseMsg = sprintf("%s, you must register before you attempt to unsign from a game.", personaName);
                                break;
                            case errCodes.GAME_NOT_FOUND:
                                responseMsg = sprintf("%s, I could not find game #%u to unsign you from.", personaName, targetGameNum);
                                break;
                            case errCodes.USER_NOT_SIGNED:
                                responseMsg = sprintf("%s, you are not signed into game #%u..", personaName, targetGameNum);
                                break;
                            case errCodes.SUCCESS:
                                break;
                        }
                    });
                }
                break;
            case "!start":
                var targetGameNum = parseInt(param);
                if (targetGameNum >= 0) {
                    DbClient.StartGame(db, playerSteam64Id, targetGameNum, function (err, startedGame) {
                        switch (err) {
                            case errCodes.DATABASE_FAILURE:
                                responseMsg = sprintf("%s, I cannot start game #%u for you due to a database error. Please try again later.", personaName, targetGameNum);
                                break;
                            case errCodes.NO_SEASONS_FOUND:
                                responseMsg = "No seasons were found. Please alert my creator or find an admin.";
                                break;
                            case errCodes.USER_NOT_REGISTERED:
                                responseMsg = personaName+", you must register before you attempt to start a game.";
                                break;
                            case errCodes.GAME_NOT_FOUND:
                                responseMsg = sprintf("%s, I could not find game #%u to start.", personaName, targetGameNum);
                                break;
                            case errCodes.GAME_NOT_READY:
                                responseMsg = sprintf("%s, I couldn't start your game because it still requires %u more players to sign.", personaName, 10 - (startedGame.players.length));
                                break;
                            case errCodes.UNKNOWN_FAILURE:
                                //responseMsg will be the default
                                break;
                            case errCodes.SUCCESS:
                                DbClient.ResolvePlayerNames(db, startedGame.players, function (err, teams) {
                                    if (err == errCodes.DATABASE_FAILURE) {
                                        responseMsg = sprintf("%s, I cannot start game #%u for you due to a database error. Please try again later.", personaName, targetGameNum);
                                        return callback(err, responseMsg);
                                    } else {
                                        responseMsg = sprintf("%s, your game #%u is now started. Please form a lobby and start playing.", personaName, targetGameNum);
                                        responseMsg += "\nRadiant: ";
                                        for (var j = 0; j < teams.Radiant.length; j++) {
                                            var p = teams.Radiant[j];
                                            responseMsg += p.username + "(" + p.rating + ")";
                                            if (j <= 4) {
                                                responseMsg += ", ";
                                            }
                                        }
                                        responseMsg += "\nDire: ";
                                        for (var j = 0; j < teams.Dire.length; j++) {
                                            var p = teams.Dire[j];
                                            responseMsg += p.username + "(" + p.rating + ")";
                                            if (j <= 4) {
                                                responseMsg += ", ";
                                            }
                                        }
                                    }
                                });
                                break;
                        }
                        return callback(err, responseMsg);
                    });
                } else {
                    responseMsg = personaName+", please specify a game number to start.";
                    return callback(errCodes.SUCCESS, responseMsg);
                }
                break;
            case "!reportwin":
                DbClient.ReportScore(db, playerSteam64Id, "win", null /* no override */, function (err, updatedGame) {
                    switch (err) {
                        case errCodes.DATABASE_FAILURE:
                            responseMsg = sprintf("%s, I could not report your score due to a database error.", personaName);
                            break;
                        case errCodes.NO_SEASONS_FOUND:
                            responseMsg = "No seasons were found. Please alert my creator or find an admin.";
                            break;
                        case errCodes.USER_NOT_REGISTERED:
                            responseMsg = sprintf("%s, you must register before you can report scores.", personaName);
                            break;
                        case errCodes.USER_NOT_SIGNED:
                            responseMsg = sprintf("%s, you must be playing in a game to report a score.", personaName);
                            break;
                        case errCodes.SUCCESS:
                            responseMsg = sprintf("%s, thanks for the score report.", personaName);
                            break;
                    }
                    return callback(err, responseMsg);
                });
                break;
            case "!reportloss":
                DbClient.ReportScore(db, playerSteam64Id, "loss", null /* no override */, function (err, updatedGame) {
                    switch (err) {
                        case errCodes.DATABASE_FAILURE:
                            responseMsg = sprintf("%s, I could not report your score due to a database error.", personaName);
                            break;
                        case errCodes.NO_SEASONS_FOUND:
                            responseMsg = "No seasons were found. Please alert my creator or find an admin.";
                            break;
                        case errCodes.USER_NOT_REGISTERED:
                            responseMsg = sprintf("%s, you must register before you can report scores.", personaName);
                            break;
                        case errCodes.USER_NOT_SIGNED:
                            responseMsg = sprintf("%s, you must be playing in a game to report a score.", personaName);
                            break;
                        case errCodes.SUCCESS:
                            responseMsg = sprintf("%s, thanks for the score report.", personaName);
                            break;
                    }
                    return callback(err, responseMsg);
                });
                break;
            case "!stats":
                responseMsg = sprintf("%s, I apologize but this function has not been implemented yet.");
                return callback(errCodes.SUCCESS, responseMsg);
                break;
            case "!help":
                responseMsg = defaultHelpMsg;
                return callback(errCodes.SUCCESS, responseMsg);
                break;
            case "!newseason":
                DbClient.NewSeason(db, playerSteam64Id, param, function (err, newSeason) {
                    switch (err) {
                        case errCodes.DATABASE_FAILURE:
                            responseMsg = sprintf("%s, I could not create a new season due to a database error.", personaName);
                            break;
                        case errCodes.USER_NOT_REGISTERED:
                            responseMsg = sprintf("%s, you must register before you can create a new season.", personaName);
                            break;
                        case errCodes.UNAUTHORIZED:
                            responseMsg = sprintf("%s, you must be an admin to create a new season.", personaName);
                            break;
                        case errCodes.SUCCESS:
                            responseMsg = sprintf("%s, I have created a new season #%u for us.", personaName, newSeason.seasonNum);
                            break;
                    }
                    return callback(err, responseMsg);
                });
                break;
            case "!leaderboard":
            case "!leaderboards":
                responseMsg = sprintf("%s, I apologize but this function has not been implemented yet.");
                return callback(errCodes.SUCCESS, responseMsg);
                break;
        }
    }
}
Пример #28
0
const isClassicRelayEnvironment = require('../store/isClassicRelayEnvironment');
const isRelayContainer = require('./isRelayContainer');
const isRelayEnvironment = require('../environment/isRelayEnvironment');
const sprintf = require('sprintf');

const {isRelayContext} = require('../environment/RelayContext');

const RelayPropTypes = {
  Container(props: Object, propName: string, componentName: string): ?Error {
    const component = props[propName];
    if (component == null) {
      return new Error(
        sprintf(
          'Required prop `%s` was not specified in `%s`.',
          propName,
          componentName,
        ),
      );
    } else if (!isRelayContainer(component)) {
      return new Error(
        sprintf(
          'Invalid prop `%s` supplied to `%s`, expected a RelayContainer.',
          propName,
          componentName,
        ),
      );
    }
    return null;
  },
Пример #29
0
function dumpNodeResult(node) {
    var str = sprintf("    %-30s%s%s", node.browseName.name, (node.isForward ? "->" : "<-"), node.nodeId.displayText());
    log(str);
}
Пример #30
0
 onProgress: function( e, data ) {
   var complete = Math.round( 100.0 * data.loaded/ data.total);
   $(this.activeView.el).find( ".progress-bar" )
                        .attr( 'aria-valuenow', complete )
                        .css( 'width', sprintf( "%s%%", complete ));
 },