Get the name, value pairs of start options provided on command-line.
Value is the entire argument including the name and starting hyphen.
776031
private HashMap<String, Object> getStartOptions(String[] args, String snappyHome,
      ArrayList<String> commandLine, HashMap<String, String> env)
      throws FileNotFoundException {
    StringBuilder classPath = new StringBuilder();
    // add the conf directory first
    classPath.append(snappyHome).append("/conf").append(java.io.File.pathSeparator);
    // then the default product jars directory
    classPath.append(snappyHome).append("/jars/*");

    final int numArgs = args.length;
    final LinkedHashMap<String, Object> options = new LinkedHashMap<>(numArgs);
    final ArrayList<String> vmArgs = new ArrayList<>(2);
    boolean hostData = !this.isLocator;

    // skip first two arguments for node type and action
    for (int i = 2; i < numArgs; i++) {
      String arg = args[i];
      // process special arguments separately
      if (arg.startsWith(DIR_OPT)) {
        processDirOption(arg.substring(DIR_OPT.length()));
      } else if (arg.startsWith(CLASSPATH_OPT)) {
        classPath.append(java.io.File.pathSeparator)
            .append(arg.substring(CLASSPATH_OPT.length()));
      } else if (arg.startsWith(HEAP_SIZE_OPT)) {
        processHeapSize(arg.substring(HEAP_SIZE_OPT.length()), vmArgs);
      } else if (arg.startsWith("-J")) {
        processVMArg(arg.substring(2), vmArgs);
      } else if (arg.startsWith("-D") || arg.startsWith("-XX:")) {
        processVMArg(arg, vmArgs);
      } else if (arg.startsWith(PASSWORD_OPT)) {
        String pwd;
        if (arg.length() > PASSWORD_OPT.length()) {
          // next character must be '='
          if (arg.charAt(PASSWORD_OPT.length()) != '=') {
            throw new IllegalArgumentException(
                "Unexpected option (should be -password or -password=): " + arg);
          }
          pwd = arg.substring(PASSWORD_OPT.length() + 1);
        } else {
          pwd = LauncherBase.readPassword("Password: ");
        }
        if (pwd != null) {
          // encryption should be done throughout from source and kept
          // encrypted throughout in the system (SNAP-1657)
          env.put(ENV1, ENV_MARKER + pwd);
        }
      } else if (arg.startsWith(WAIT_FOR_SYNC_OPT)) {
        processWaitForSync(arg.substring(WAIT_FOR_SYNC_OPT.length()));
      } else if (arg.length() > 0 && arg.charAt(0) == '-') {
        // put rest of the arguments as is
        int eqIndex = arg.indexOf('=');
        String key = eqIndex != -1 ? arg.substring(1, eqIndex) : arg.substring(1);
        options.put(key, arg);
        if (key.equals(HOST_DATA) && eqIndex != -1) {
          hostData = !"false".equalsIgnoreCase(arg.substring(eqIndex + 1));
        }
      } else {
        throw new IllegalArgumentException("Unexpected command-line option: " + arg);
      }
    }
    // set the classpath
    commandLine.add("-cp");
    commandLine.add(classPath.toString());
    // set default JVM args
    commandLine.add("-Djava.awt.headless=true");
    // configure commons-logging to use Log4J logging
    commandLine.add("-Dorg.apache.commons.logging.Log=" +
        "org.apache.commons.logging.impl.Log4JLogger");
    setDefaultVMArgs(options, hostData, commandLine);
    // add the provided JVM args after the defaults
    if (!vmArgs.isEmpty()) {
      commandLine.addAll(vmArgs);
    }

    return options;
  }
449917
def _get_argname_value(self, argname):
        '''
        
        '''
        # Let's see if there's a private function to get the value
        argvalue = getattr(self, '__get_{0}__'.format(argname), None)
        if argvalue is not None and callable(argvalue):
            argvalue = argvalue()
        if argvalue is None:
            # Let's see if the value is defined as a public class variable
            argvalue = getattr(self, argname, None)
        if argvalue is None:
            # Let's see if it's defined as a private class variable
            argvalue = getattr(self, '__{0}__'.format(argname), None)
        if argvalue is None:
            # Let's look for it in the extra dictionary
            argvalue = self.extra.get(argname, None)
        return argvalue
120706
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="polyglot"
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    # for k, v in locals().iteritems():
    #     print k, v

    if not destinationFolder:
        destinationFolder = os.getcwd()
    if not filenameFlag:
        filenameFlag = False
    if not cleanFlag:
        readability = False
    else:
        readability = True

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/polyglot/polyglot.yaml"
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    if pdf and url:
        filepath = printpdf.printpdf(
            log=log,
            settings=settings,
            url=url,
            folderpath=destinationFolder,
            title=filenameFlag,
            append=False,
            readability=readability
        ).get()

    if html and url:

        cleaner = htmlCleaner.htmlCleaner(
            log=log,
            settings=settings,
            url=url,
            outputDirectory=destinationFolder,
            title=filenameFlag,  # SET TO FALSE TO USE WEBPAGE TITLE,
            style=cleanFlag,  # add polyglot's styling to the HTML document
            metadata=True,  # include metadata in generated HTML (e.g. title),
            h1=True  # include title as H1 at the top of the doc
        )
        filepath = cleaner.clean()

    if epub:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import ebook
        epub = ebook(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag,
            bookFormat="epub",
            outputDirectory=destinationFolder
        )
        filepath = epub.get()

    if mobi:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import ebook
        mobi = ebook(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag,
            bookFormat="mobi",
            outputDirectory=destinationFolder,
        )
        filepath = mobi.get()

    if kindle:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import kindle
        sender = kindle(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag
        )
        success = sender.send()

    if kindleNB2MD:
        basename = os.path.basename(notebook)
        extension = os.path.splitext(basename)[1]
        filenameNoExtension = os.path.splitext(basename)[0]
        if destinationFolder:
            filepath = destinationFolder + "/" + filenameNoExtension + ".md"
        else:
            filepath = notebook.replace("." + extension, ".md")
        from polyglot.markdown import kindle_notebook
        nb = kindle_notebook(
            log=log,
            kindleExportPath=notebook,
            outputPath=filepath
        )
        nb.convert()

    if openFlag:
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
1353321
def get_command(arguments):
    
    return [k for k, v in arguments.items()
            if not k.startswith('-') and v is True][0]
115062
def _get_start_end(parts, index=7):
    
    start = parts[1]
    end = [x.split("=")[-1] for x in parts[index].split(";") if x.startswith("END=")]
    if end:
        end = end[0]
        return start, end
    return None, None
1280174
def parse_options(self, arg):
        

        if not arg.startswith('-'):
            return False

        value = None
        if '=' in arg:
            arg, value = arg.split('=')

        for option in self._option_list:

            if arg not in (option.shortname, option.longname):
                continue

            action = option.action
            if action:
                action()

            if option.key == option.shortname:
                self._results[option.key] = True
                return True

            if option.boolean and option.default:
                self._results[option.key] = False
                return True

            if option.boolean:
                self._results[option.key] = True
                return True

            # has tag, it should has value
            if not value:
                if self._argv:
                    value = self._argv[0]
                    self._argv = self._argv[1:]

            if not value:
                raise RuntimeError('Missing value for: %s' % option.name)

            self._results[option.key] = option.to_python(value)
            return True

        return False
1220472
def show_command(parameter):
    
    section = "cli"
    if "." in parameter:
        section, parameter = parameter.split(".", 1)

    value = lookup_option(parameter, section=section)

    if value is None:
        safeprint("{} not set".format(parameter))
    else:
        safeprint("{} = {}".format(parameter, value))
736184
def resolve_return_value_options(self, options):
        """"""
        for key, value in options.items():
            if isinstance(value, str) and value.startswith(RETURN_VALUE_OPTION_PREFIX):
                path, name = value[len(RETURN_VALUE_OPTION_PREFIX) :].rsplit(".", 1)
                result = self._find_result_by_path(path)
                options[key] = result.return_values.get(name)
851395
def main():
    
    parser = argparse.ArgumentParser(
        description='Performs option handling operations from the command-line. Calls JVM start/stop automatically.')
    parser.add_argument("-j", metavar="classpath", dest="classpath", help="additional classpath, jars/directories")
    parser.add_argument("-action", metavar="action", dest="action", required=True,
                        help="The action to perform on the options: join=create single string, "\
                             "split=create array from quoted option, code=generate code from options")
    parser.add_argument("option", nargs=argparse.REMAINDER, help="The option(s) to process")
    parsed = parser.parse_args()
    jars = []
    if parsed.classpath is not None:
        jars = parsed.classpath.split(os.pathsep)

    jvm.start(jars, packages=True)

    try:
        if parsed.action == "join":
            output = "cmdline = \"" + backquote(join_options(parsed.option)) + "\""
        elif parsed.action == "split" and len(parsed.option) == 1:
            output = "options = [\n"
            opts = split_options(parsed.option[0])
            for idx, opt in enumerate(opts):
                if idx > 0:
                    output += ",\n"
                output += "    \"" + backquote(opt) + "\""
            output += "]"
        elif parsed.action == "code":
            options = parsed.option[:]
            cname = None
            # classname + options?
            if options[0].find(".") > -1:
                cname = options[0]
                options = options[1:]
            output = "options = [ \n"
            for idx, opt in enumerate(options):
                if idx > 0:
                    output += ",\n"
                output += "    \"" + backquote(opt) + "\""
            output += "]\n"
            if cname is not None:
                output += 'handler = OptionHandler(JavaObject.new_instance("' + cname + '"))\n'
                output += 'handler.options = options\n'
        else:
            raise Exception("Unsupported action: " + parsed.action)
        if output is not None:
            print(output)
    except Exception as e:
        print(e)
    finally:
        jvm.stop()
17553
def parse(cmdline = ARGV)
			vals = {}
			required = {}

			opt :version, "Print version and exit" if @version && ! (@specs[:version] || @long["version"])
			opt :help, "Show this message" unless @specs[:help] || @long["help"]

			@specs.each do |sym, opts|
				required[sym] = true if opts.required?
				vals[sym] = opts.default
				vals[sym] = [] if opts.multi && !opts.default # multi arguments default to [], not nil
			end

			resolve_default_short_options!

			## resolve symbols
			given_args = {}
			@leftovers = each_arg cmdline do |arg, params|
				## handle --no- forms
				arg, negative_given = if arg =~ /^--no-([^-]\S*)$/
																["--#{$1}", true]
															else
																[arg, false]
															end

				sym = case arg
							when /^-([^-])$/      then @short[$1]
							when /^--([^-]\S*)$/  then @long[$1] || @long["no-#{$1}"]
							else                       raise CommandlineError, "invalid argument syntax: '#{arg}'"
							end

				sym = nil if arg =~ /--no-/ # explicitly invalidate --no-no- arguments

				next nil if ignore_invalid_options && !sym
				raise CommandlineError, "unknown argument '#{arg}'" unless sym

				if given_args.include?(sym) && !@specs[sym].multi?
					raise CommandlineError, "option '#{arg}' specified multiple times"
				end

				given_args[sym] ||= {}
				given_args[sym][:arg] = arg
				given_args[sym][:negative_given] = negative_given
				given_args[sym][:params] ||= []

				# The block returns the number of parameters taken.
				num_params_taken = 0

				unless params.empty?
					if @specs[sym].single_arg?
						given_args[sym][:params] << params[0, 1]  # take the first parameter
						num_params_taken = 1
					elsif @specs[sym].multi_arg?
						given_args[sym][:params] << params        # take all the parameters
						num_params_taken = params.size
					end
				end

				num_params_taken
			end

			## check for version and help args
			raise VersionNeeded if given_args.include? :version
			raise HelpNeeded if given_args.include? :help

			## check constraint satisfaction
			@constraints.each do |type, syms|
				constraint_sym = syms.find { |sym| given_args[sym] }
				next unless constraint_sym

				case type
				when :depends
					syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym].long} requires --#{@specs[sym].long}" unless given_args.include? sym }
				when :conflicts
					syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym].long} conflicts with --#{@specs[sym].long}" if given_args.include?(sym) && (sym != constraint_sym) }
				end
			end

			required.each do |sym, val|
				raise CommandlineError, "option --#{@specs[sym].long} must be specified" unless given_args.include? sym
			end

			## parse parameters
			given_args.each do |sym, given_data|
				arg, params, negative_given = given_data.values_at :arg, :params, :negative_given

				opts = @specs[sym]
				if params.empty? && !opts.flag?
					raise CommandlineError, "option '#{arg}' needs a parameter" unless opts.default
					params << (opts.array_default? ? opts.default.clone : [opts.default])
				end

				params[0].each do |p|
					raise CommandlineError, "option '#{arg}' only accepts one of: #{opts.permitted.join(', ')}" unless opts.permitted.include? p
				end unless opts.permitted.nil?

				vals["#{sym}_given".intern] = true # mark argument as specified on the commandline

				vals[sym] = opts.parse(params, negative_given)

				if opts.single_arg?
					if opts.multi?        # multiple options, each with a single parameter
						vals[sym] = vals[sym].map { |p| p[0] }
					else                  # single parameter
						vals[sym] = vals[sym][0][0]
					end
				elsif opts.multi_arg? && !opts.multi?
					vals[sym] = vals[sym][0]  # single option, with multiple parameters
				end
				# else: multiple options, with multiple parameters

				opts.callback.call(vals[sym]) if opts.callback
			end

			## modify input in place with only those
			## arguments we didn't process
			cmdline.clear
			@leftovers.each { |l| cmdline << l }

			## allow openstruct-style accessors
			class << vals
				def method_missing(m, *_args)
					self[m] || self[m.to_s]
				end
			end
			vals
		end
1094250
def get_arguments(self):
    """"""
    # In python 2, the command line is unicode, which needs to be converted to string before pickling;
    # In python 3, the command line is bytes, which can be pickled directly
    args = loads(self.grid_arguments)['kwargs'] if isinstance(self.grid_arguments, bytes) else loads(self.grid_arguments.encode())['kwargs']
    # in any case, the commands have to be converted to str
    retval = {}
    if 'pe_opt' in args:
      retval['pe_opt'] = args['pe_opt']
    if 'memfree' in args and args['memfree'] is not None:
      retval['memfree'] = args['memfree']
    if 'hvmem' in args and args['hvmem'] is not None:
      retval['hvmem'] = args['hvmem']
    if 'gpumem' in args and args['gpumem'] is not None:
      retval['gpumem'] = args['gpumem']
    if 'env' in args and len(args['env']) > 0:
      retval['env'] = args['env']
    if 'io_big' in args and args['io_big']:
      retval['io_big'] = True

    # also add the queue
    if self.queue_name is not None:
      retval['queue'] = str(self.queue_name)

    return retval
1237830
def get_name_value(self):
        
        name, value = self.get()
        if not isinstance(name, list):
            name = [name]
        if not isinstance(value, list):
            value = [value]
        return list(zip(name, value))
849433
protected String getOptionalAttributeValue(StartElement start,
                                               QName attributeName) {
        Attribute mapNameAttribute = start.getAttributeByName(attributeName);
        if (mapNameAttribute == null) {
            return null;
        } else {
            return mapNameAttribute.getValue();
        }
    }
999523
def parse_options(options, arg_split:':', valuesep: '=', opt_default: true, keyed_sep: "/")
			return {} unless options
			parsed_options={}
			options=options.split(arg_split) unless options.is_a?(Enumerable)
			options.each do |optvalue|
				opt,value=DR::SimpleParser.parse_namevalue(optvalue,sep: valuesep, default: opt_default)
				parsed_options.set_keyed_value(opt,value, sep: keyed_sep)
			end
			return parsed_options
		end
557352
def get_arguments(options):
   
   # These the next couple of lines defines the header of the Help output
   parser = ArgumentParser(
      formatter_class=RawDescriptionHelpFormatter,
      usage=("""%(prog)s
--------------------------------------------------------------------------------
"""),
      description=("""
Service Wrapper
===============
This is the service wrapper script, which is a part of the CGE services.
Read the online manual for help.
A list of all published services can be found at:
cge.cbs.dtu.dk/services

"""), epilog=("""
--------------------------------------------------------------------------------
      """))

   #ADDING ARGUMENTS
   setarg = parser.add_argument
   #SERVICE SPECIFIC ARGUMENTS
   if isinstance(options, str):
      options = [[x for i,x in enumerate(line.split()) if i in [1,2]] for line in options.split('\n') if len(line)>0]
      for o in options:
         try:
            setarg(o[1], type=str, dest=o[0], default=None, help=SUPPRESS)
         except:
            None
   else:
      for o in options:
         if o[2] is True:
            # Handle negative flags
            setarg(o[0], action="store_false", dest=o[1], default=o[2],
                   help=o[3])
         elif o[2] is False:
            # Handle positive flags
            setarg(o[0], action="store_true", dest=o[1], default=o[2],
                   help=o[3])
         else:
            help_ = o[3] if o[2] is None else "%s [%s]"%(o[3], '%(default)s')
            setarg(o[0], type=str, dest=o[1], default=o[2],
                   help=help_)
   # VALIDATION OF ARGUMENTS
   args = parser.parse_args()
   debug.log("ARGS: %s"%args)
   return args
460611
def get_default(name, value):
    """"""
    return os.environ.get('EXAMPLE_{}'.format(name.upper()), value)
390735
def get_args_and_values(parser, an_action):
    """"""
    args = inspect.getargspec(an_action.__class__.__init__).args
    kwargs = dict(
        (an_attr, getattr(an_action, an_attr))
        for an_attr in args
        if (
            an_attr not in ('self', 'required')
            and getattr(an_action, an_attr) is not None
        )
    )
    action_name = find_action_name_by_value(
        parser._optionals._registries,
        an_action
    )
    if 'required' in kwargs:
        del kwargs['required']
    kwargs['action'] = action_name
    if 'option_strings' in kwargs:
        args = tuple(kwargs['option_strings'])
        del kwargs['option_strings']
    else:
        args = ()
    return args, kwargs