Check and format --server arg
14423
def server_check(arg):
    
    if arg.startswith(('http://', 'https://', 'http+unix://')):
        return arg
    if arg.startswith('./'):
        arg = os.path.abspath(arg)
    elif not arg.startswith('/'):
        raise argparse.ArgumentTypeError(
            'Unix socket path must start with / or ./')
    # assume it is a unix socket
    return 'http+unix://{}'.format(url_escape(arg, ''))
1343097
def check_arguments(params, *args)
      contains = true
      args.each do |arg|
        contains = false unless params.key? arg.to_sym
      end
      contains
    end
214681
def check_arguments(cls, conf):
        
        # Perform sanity checking on CIDR
        utils.ip_check(conf['fixed_cidr'], netmask_expected=True)

        # Perform sanity checking on host list
        for host in conf['fixed_hosts'].split(":"):
            utils.ip_check(host)
845585
def check_args(parser, args):
    """"""
    # Make sure only one action has been specified
    if len([a for a in [args.create, args.extract, args.verify, args.list,
                        args.list_detailed, args.hash, args.add_signature] if a
            is not None]) != 1:
        parser.error("Must specify something to do (one of -c, -x, -t, -T, -v, --hash, --add-signature)")

    if args.create and not args.files:
        parser.error("Must specify at least one file to add to marfile")

    if args.extract and args.compression not in (None, 'bz2', 'xz', 'auto'):  # pragma: nocover
        parser.error('Unsupported compression type')

    if args.create and args.compression not in (None, 'bz2', 'xz'):  # pragma: nocover
        parser.error('Unsupported compression type')

    if args.hash and len(args.files) != 1:
        parser.error("Must specify a file to output the hash for")
66301
function handleArgs (_regex, _config) {
	/* Identify regex pattern. */
	let pattern;
	if (_regex) {
		if (typeof _regex === 'string') {
			pattern = _regex;
		} else {
			try {
				pattern = _regex.source;
			} catch (e) {
				log(`Invalid regex:`);
				log(_regex);
			}
		}
	} else {
		log(`Invalid regex: none provided`);
	}
	if (!pattern) {
		let errObj = { msg: 'Invalid args' };
		throw errObj;
	}

	/* Identify config. Accept a variety of flavors and fall back to defaults as needed. */
	let config = {};
	if (!_config) {
		config.server = defaultServerConfig;
		config.cache = defaultCacheConfig;
	} else {
		config.server = handleServerConfig(_config.server);
		config.cache = handleCacheConfig(_config.cache);
	}

	return [pattern, config];
}
736048
def check(args):
    
    session = c.Session(args)
    if str(args["url"]) != 'None':
        url = args["url"]
        name = "DEFAULT"
    else:
        try:
            url = session.feeds[args["feed"]]["url"]
            name = args["feed"]
        except KeyError:
            sys.exit("You don't appear to have a feed with that name.")
    podcast = aux.parse_podcast(url)
    for entry in enumerate(podcast.entries):
        listentry = list(entry)
        print(listentry[0], end=": ")
        try:
            print(listentry[1]["title"], end=" (")
        except:
            print(listentry[1]["link"], end=" (")
        try:
            print(listentry[1]["updated"], end=")")
        except:
            print("", end=")")
        print()
    dumpfilename = os.path.join(session.data_dir, 'feeddump')
    with open(dumpfilename, mode='wb') as dumpfile:
        dump = [name, podcast]
        pickle.dump(dump, dumpfile)
50022
private void checkArgs(final String[] argv) throws DevFailed {
        if (argv.length < 1) {
            throw DevFailedUtils.newDevFailed(INIT_ERROR, getUsage());
        }
        instanceName = argv[0];
        useDb = true;
        DatabaseFactory.setUseDb(true);
        List<String> noDbDevices = new ArrayList<String>();
        for (int i = 1; i < argv.length; i++) {
            final String arg = argv[i];
            if (arg.startsWith("-h")) { // trace instance name
                System.out.println("instance list for server " + execName + ": "
                        + Arrays.toString(DatabaseFactory.getDatabase().getInstanceNameList(execName)));
            } else if (arg.startsWith("-v")) { // logging level
                try {
                    final int level = Integer.parseInt(arg.substring(arg.lastIndexOf('v') + 1));
                    LoggingManager.getInstance().setLoggingLevel(level,
                            tangoClasses.values().toArray(new Class<?>[0]));
                } catch (final NumberFormatException e) {
                    throw DevFailedUtils.newDevFailed("Logging level error. Must be a number");
                }
            } else if (arg.startsWith("-dlist")) {
                noDbDevices = configureNoDB(argv, i);
                useDb = false;
            } else if (arg.startsWith("-file")) {
                configureNoDBFile(argv, arg, noDbDevices);
                useDb = false;
            }
        }
    }
1110823
def check_arguments(cls, conf):
        
        # Checking the interval
        if not conf['tcp_check_interval']:
            raise ArgsError("A TCP health-test interval needs to be "
                            "specified (--tcp_check_interval).")

        if not (1 <= conf['tcp_check_interval'] <= 3600):
            raise ArgsError("Specified TCP health-test interval must be "
                            "between 1 and 3600 seconds")

        # Checking the port
        if not conf['tcp_check_port']:
            raise ArgsError("A port for the TCP health-test needs to be "
                            "specified (--tcp_check_port).")

        if not (1 <= conf['tcp_check_port'] <= 65535):
            raise ArgsError("Specified port for TCP health-test must be "
                            "between 1 and 65535")
528263
def spec_check(self, auth_list, fun, args, form):
        '''
        
        '''
        if not auth_list:
            return False
        if form != 'cloud':
            comps = fun.split('.')
            if len(comps) != 2:
                # Hint at a syntax error when command is passed improperly,
                # rather than returning an authentication error of some kind.
                # See Issue #21969 for more information.
                return {'error': {'name': 'SaltInvocationError',
                                  'message': 'A command invocation error occurred: Check syntax.'}}
            mod_name = comps[0]
            fun_name = comps[1]
        else:
            fun_name = mod_name = fun
        for ind in auth_list:
            if isinstance(ind, six.string_types):
                if ind[0] == '@':
                    if ind[1:] == mod_name or ind[1:] == form or ind == '@{0}s'.format(form):
                        return True
            elif isinstance(ind, dict):
                if len(ind) != 1:
                    continue
                valid = next(six.iterkeys(ind))
                if valid[0] == '@':
                    if valid[1:] == mod_name:
                        if self.__fun_check(ind[valid], fun_name, args.get('arg'), args.get('kwarg')):
                            return True
                    if valid[1:] == form or valid == '@{0}s'.format(form):
                        if self.__fun_check(ind[valid], fun, args.get('arg'), args.get('kwarg')):
                            return True
        return False
1166696
def format(arg)
      arg = Yummi::Context::new(arg) unless arg.is_a? Context
      call value
    end
1279474
def _check_args(*argl, **argd):
    
    args = {"_": []}
    for item in argl:
        args["_"].append(_tracker_str(item))
           
    for key, item in argd.items():
        args[key] = _tracker_str(item)
        
    return args
307350
function validate(cmd, args, info) {
  AbstractCommand.prototype.validate.apply(this, arguments);
  var offset = 2
    , arg
    , expires;

  // need string args (except for key, value)
  args.forEach(function(a, i, arr) {
    if(i > 1) {
      arr[i] = '' + a;
    }
  })

  if(args.length > 7) {
    throw new CommandArgLength(cmd);
  }else if(args.length > 2) {
    arg = args[offset];
    while(arg !== undefined) {
      arg = arg.toLowerCase();
      args[offset] = arg;
      if(arg !== Constants.EX
        && arg !== Constants.PX
        && arg !== Constants.NX
        && arg !== Constants.XX) {
        throw CommandSyntax;
      }
      if(arg === Constants.EX || arg === Constants.PX) {
        expires = parseInt('' + args[offset + 1]);
        if(isNaN(expires)) {
          throw IntegerRange;
        }
        args[++offset] = expires;
      }
      arg = args[++offset];
    }
  }
}
176675
public void runArgs(String[] args) {
        CommandLineParser clParser = new DefaultParser();
        CommandLine line;
        String host;
        String port;
        CMD cmd;
        String[] cmdArgs;
        final PrintStream CONSOLE = System.out;
        try {
            // parse the command line arguments
            line = clParser.parse(options, args);

            if (line.hasOption("output")){
                String location = line.getOptionValue("output");
                File output = new File(location);
                FileOutputStream fos;
                try {
                    fos = new FileOutputStream(output);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    throw new ParseException(String.format("Wrong -o option. args %s\n",Arrays.asList(args)));
                }
                PrintStream out = new PrintStream(fos);
                System.setOut(out);

            }
            if (line.getOptions().length==0 || line.hasOption("help")) {
                if ((line.getOptions().length > 2) || (line.getOptions().length==2 && !line.hasOption("output"))){
                    throw new ParseException(String.format("Wrong -help option. args %s\n", Arrays.asList(args)));
                }
                printUsage(System.out);
            }
            if (line.hasOption("server")) {
                String server = line.getOptionValue("server");
                try {
                    host = server.split(":")[0];
                    port = server.split(":")[1];
                }catch (Exception e){
                    throw new ParseException(String.format("Wrong -server option. args %s\n", Arrays.asList(args)));
                }
                ServiceDirectory.getServiceDirectoryConfig().setProperty(
                        DirectoryServiceRestfulClient.SD_API_SD_SERVER_FQDN_PROPERTY,
                        host);
                ServiceDirectory.getServiceDirectoryConfig().setProperty(
                        DirectoryServiceRestfulClient.SD_API_SD_SERVER_PORT_PROPERTY,
                        port);
            }

            if (line.hasOption("exec")) {
                String commandString = line.getOptionValue("exec");
                cmdArgs = parseCommand(commandString);
                try {
                    cmd = CMD.valueOf(cmdArgs[0]);
                } catch (IllegalArgumentException e) {
                    throw new ParseException(String.format("Unknown command [ %s ] \n", commandString));
                }
                if (cmd.sizeOfArgs + 1 != cmdArgs.length) {
                    throw new ParseException(
                            String.format("Wrong arguments number for command %s, required %s but %s \n",
                                    cmdArgs[0], cmd.sizeOfArgs, cmdArgs.length - 1));
                }
                switch (cmd) {
                    case getInstanceOf:
                        lookupInstance(cmdArgs);
                        break;
                    case getAllInstancesOf:
                        lookupInstances(cmdArgs);
                        break;
                    case getAllServices:
                        getAllServices();
                        break;
                    case registerService:
                        registerService(cmdArgs);
                        break;
                    default:
                        fail("command " + cmd + " is unsupported yet");
                        break;
                }

            }
        } catch (ParseException exp) {
            // oops, something went wrong
            exp.printStackTrace();
            try {
                TimeUnit.MILLISECONDS.sleep(100L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            printUsage(System.err);
        }
        System.setOut(CONSOLE);
    }
502789
def _parse_arguments(arguments=None):
    """"""
    dir_hash = hashlib.sha1(os.getcwd().encode("utf-8")).hexdigest()

    parser = argparse.ArgumentParser(description="""Lint for Polysquare style guide""")
    parser.add_argument("--checks",
                        nargs=0,
                        action=ShowAvailableChecksAction,
                        help="""list available checks""")
    parser.add_argument("files",
                        nargs="*",
                        metavar=("FILE"),
                        help="""read FILE""",
                        type=str)
    parser.add_argument("--whitelist",
                        nargs="*",
                        help="""list of checks that should only be run""",
                        default=None)
    parser.add_argument("--blacklist",
                        nargs="*",
                        help="""list of checks that should never be run""",
                        default=None)
    parser.add_argument("--fix-what-you-can",
                        action="store_const",
                        help="""fix errors automatically""",
                        const=True)
    parser.add_argument("--spellcheck-cache",
                        help="""path to spell-checking cache file""",
                        default=None)
    parser.add_argument("--log-technical-terms-to",
                        help="""path to file to log technical terms to""",
                        default=None)
    parser.add_argument("--stamp-file-path",
                        help="""path to directory to store cached results""",
                        default=os.path.join(tempfile.gettempdir(),
                                             "jobstamps",
                                             "spellcheck_linter",
                                             dir_hash))
    parser.add_argument("--block-regexps",
                        help="""Regular expressions to exclude from all checks.""",
                        nargs="*",
                        default=None)

    return parser.parse_args(arguments)
486800
def _inspectArguments(self, args):
        """"""
        if args:
            self.exec_path = PathStr(args[0])
        else:
            self.exec_path = None

        session_name = None
        args = args[1:]

        openSession = False
        for arg in args:
            if arg in ('-h', '--help'):
                self._showHelp()
            elif arg in ('-d', '--debug'):
                print('RUNNGING IN DEBUG-MODE')
                self.opts['debugMode'] = True
            elif arg in ('-l', '--log'):
                print('CREATE LOG')
                self.opts['createLog'] = True
            elif arg in ('-s', '--server'):
                self.opts['server'] = True
            elif arg in ('-o', '--open'):
                openSession = True
            elif openSession:
                session_name = arg
            else:
                print("Argument '%s' not known." % arg)
                return self._showHelp()
        return session_name
948003
function format(arg) {
    if (typeof arg === 'number') {
        return '0x' + arg.toString(16).toUpperCase();
    }

    if (typeof arg === 'string') {
        return '"' + arg + '"';
    }

    return arg.toString();
}
841550
def validate_args(args):
    
    if not os.path.isdir(args.directory):
        print "Directory {} does not exist".format(args.directory)
        sys.exit(5)
    return args