Sample usage for this python module

    This main method simply illustrates sample usage for this python
    module.

    :return: None
13153
def main():
    
    mkdir_p('/tmp/test/test')
    source('/root/.bash_profile')
    yum_install(['httpd', 'git'])
    yum_install(['httpd', 'git'], dest_dir='/tmp/test/test', downloadonly=True)
    sed('/Users/yennaco/Downloads/homer_testing/network', '^HOSTNAME.*', 'HOSTNAME=foo.joe')
    test_script = '/Users/yennaco/Downloads/homer/script.sh'
    results = run_command([test_script], timeout_sec=1000)
    print('Script {s} produced exit code [{c}] and output:\n{o}'.format(
        s=test_script, c=results['code'], o=results['output']))
1103055
def should_sample(self):
        
        return self.span_context.trace_options.enabled \
            or self.sampler.should_sample(self.span_context.trace_id)
337939
public void printUsage() {
        String name = mainClass == null ? "<MainClass>" : mainClass.getName();
        String usage = "java " + name + " [OPTIONS]";
        final HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(usage, options, true);
    }
59615
def show_usage(out = STDERR, width = 80)
            lines = ['']
            pos_args = positional_args
            opt_args = size - pos_args.size
            usage_args = pos_args.map(&:to_use)
            usage_args << (requires_some? ? 'OPTIONS' : '[OPTIONS]') if opt_args > 0
            usage_args << rest_args.to_use if rest_args?
            lines.concat(wrap_text("USAGE: #{RUBY_ENGINE} #{$0} #{usage_args.join(' ')}", width))
            lines << ''
            lines << 'Specify the /? or --help option for more detailed help'
            lines << ''
            lines.each{ |line| out.puts line } if out
            lines
        end
254454
def run_example(example_cls: Example, args=None):
    
    values = parse_args(args)
    window_cls = get_window_cls(values.window)

    window = window_cls(
        title=example_cls.title,
        size=example_cls.window_size,
        fullscreen=values.fullscreen,
        resizable=example_cls.resizable,
        gl_version=example_cls.gl_version,
        aspect_ratio=example_cls.aspect_ratio,
        vsync=values.vsync,
        samples=values.samples,
        cursor=values.cursor,
    )

    window.example = example_cls(ctx=window.ctx, wnd=window)

    start_time = time.time()
    current_time = start_time
    prev_time = start_time
    frame_time = 0

    while not window.is_closing:
        current_time, prev_time = time.time(), current_time
        frame_time = max(current_time - prev_time, 1 / 1000)

        window.render(current_time - start_time, frame_time)
        window.swap_buffers()

    duration = time.time() - start_time
    window.destroy()
    print("Duration: {0:.2f}s @ {1:.2f} FPS".format(duration, window.frames / duration))
273868
def main():
    
    parser = optparse.OptionParser(usage="usage: pylon [options] input_file",
                                   version="%prog 0.4.4")

    parser.add_option("-o", "--output", dest="output", metavar="FILE",
        help="Write the solution report to FILE.")

#    parser.add_option("-q", "--quiet", action="store_true", dest="quiet",
#        default=False, help="Print less information.")

    parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
        default=False, help="Print more information.")

#    parser.add_option("-g", "--gui", action="store_true", dest="gui",
#        default=False, help="Use the portable graphical interface to Pylon.")

#    parser.add_option("-n", "--no-report", action="store_true",
#        dest="no_report", default=False, help="Suppress report output.")

    parser.add_option("-d", "--debug", action="store_true", dest="debug",
        default=False, help="Print debug information.")

    parser.add_option("-t", "--input-type", dest="type", metavar="TYPE",
        default="any", help="The argument following the -t is used to "
        "indicate the format type of the input data file. The types which are "
        "currently supported include: matpower, psse [default: %default]"
        " If not specified Pylon will try to determine the type according to "
        "the file name extension and the file header.")

    parser.add_option("-s", "--solver", dest="solver", metavar="SOLVER",
        default="acpf", help="The argument following the -s is used to"
        "indicate the type of routine to use in solving. The types which are "
        "currently supported are: 'dcpf', 'acpf', 'dcopf', 'acopf', 'udopf' "
        "and 'none' [default: %default].")

    parser.add_option("-a", "--algorithm", action="store_true",
        metavar="ALGORITHM", dest="algorithm", default="newton",
        help="Indicates the algorithm type to be used for AC power flow. The "
        "types which are currently supported are: 'newton' and 'fdpf' "
        "[default: %default].")

    parser.add_option("-T", "--output-type", dest="output_type",
        metavar="OUTPUT_TYPE", default="rst", help="Indicates the output "
        "format type.  The type swhich are currently supported include: rst, "
        "matpower, csv, excel and none [default: %default].")

    (options, args) = parser.parse_args()

    if options.verbose:
        logger.setLevel(logging.INFO)
    elif options.debug:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.ERROR)

    # Output.
    outext = {'psse': '.raw', 'matpower': '.m'}
    if options.output:
        if options.output == "-":
            outfile = sys.stdout
            logger.setLevel(logging.CRITICAL) # must stay quiet
#            options.output_type = "none"
        else:
            outfile = open(options.output, "wb")
    elif options.output_type is not None:
        if options.output_type in outext.keys():
            inname, ext = os.path.splitext(args[0])
            outfile = inname + outext[options.output_type]
        else:
            outfile = sys.stdout
    else:
        outfile = sys.stdout
#        if not options.no_report:
#            logger.setLevel(logging.CRITICAL) # must stay quiet

    # Input.
    if len(args) > 1:
        parser.print_help()
        sys.exit(1)
    elif (len(args) == 0) or (args[0] == "-"):
        filename = ""
        if sys.stdin.isatty():
            # True if the file is connected to a tty device, and False
            # otherwise (pipeline or file redirection).
            parser.print_help()
            sys.exit(1)
        else:
            # Handle piped input ($ cat ehv3.raw | pylon | rst2pdf -o ans.pdf).
            infile = sys.stdin
    else:
        filename = args[0]
        infile = open(filename, "rb")

    if options.type == "any":
        type = detect_data_file(infile, filename)
    else:
        type = options.type

    # Get the case from the input file-like object.
    case = read_case(infile, type)

    if case is not None:
        # Routine (and algorithm) selection.
        if options.solver == "dcpf":
            solver = DCPF(case)
        elif options.solver == "acpf":
            if options.algorithm == "newton":
                solver = NewtonPF(case)
            elif options.algorithm == "fdpf":
                solver = FastDecoupledPF(case)
            else:
                logger.critical("Invalid algorithm [%s]." % options.algorithm)
                sys.exit(1)
        elif options.solver == "dcopf":
            solver = OPF(case, True)
        elif options.solver == "acopf":
            solver = OPF(case, False)
        elif options.solver == "udopf":
            solver = UDOPF(case)
        elif options.solver == "none":
            solver = None
        else:
            logger.critical("Invalid solver [%s]." % options.solver)
#            sys.exit(1)
            solver = None

        # Output writer selection.
        if options.output_type == "matpower":
            writer = MATPOWERWriter(case)
        elif options.output_type == "psse":
            writer = PSSEWriter(case)
        elif options.output_type == "rst":
            writer = ReSTWriter(case)
        elif options.output_type == "csv":
            from pylon.io.excel import CSVWriter
            writer = CSVWriter(case)
        elif options.output_type == "excel":
            from pylon.io.excel import ExcelWriter
            writer = ExcelWriter(case)
        elif options.output_type == "pickle":
            writer = PickleWriter(case)
        else:
            logger.critical("Invalid output type [%s]." % options.output_type)
            sys.exit(1)

        if solver is not None:
            solver.solve()
        if options.output_type != "none":
            writer.write(outfile)
            print('Output file {0} written'.format(outfile))
    else:
        logger.critical("Unable to read case data.")

    # Don't close stdin or stdout.
    if len(args) == 1:
        infile.close()
    if options.output and not (options.output == "-"):
        outfile.close()
560736
def _use_methods(cls):
        
        use_dict = JobCalculation._use_methods
        use_dict.update({
            "surface_sample": {
                'valid_types': SinglefileData,
                'additional_parameter': None,
                'linkname': 'surface_sample',
                'docstring': "surface sample generated by zeo++",
            },
            "cell": {
                'valid_types': SinglefileData,
                'additional_parameter': None,
                'linkname': 'cell',
                'docstring': "cell file containing cell vectors",
            },
        })
        return use_dict
992478
def main():

    gtselect_keys = ['tmin', 'tmax', 'emin', 'emax', 'zmax', 'evtype', 'evclass',
                     'phasemin', 'phasemax', 'convtype', 'rad', 'ra', 'dec']

    gtmktime_keys = ['roicut', 'filter']

    usage = "usage: %(prog)s [options] "
    description = "Run gtselect and gtmktime on one or more FT1 files.  "
    ""
    parser = argparse.ArgumentParser(usage=usage, description=description)

    add_lsf_args(parser)

    for k in gtselect_keys:

        if k in ['evtype', 'evclass', 'convtype']:
            parser.add_argument('--%s' % k, default=None, type=int, help='')
        else:
            parser.add_argument('--%s' % k, default=None, type=float, help='')

    for k in gtmktime_keys:
        parser.add_argument('--%s' % k, default=None, type=str, help='')

    parser.add_argument('--rock_angle', default=None, type=float, help='')

    parser.add_argument('--outdir', default=None, type=str,
                        help='Path to output directory used when merge=False.')
    parser.add_argument('--output', default=None, type=str,
                        help='Path to output file used when merge=True.')
    parser.add_argument('--scfile', default=None, type=str, help='')

    parser.add_argument('--dry_run', default=False, action='store_true')
    parser.add_argument('--overwrite', default=False, action='store_true')
    parser.add_argument('--merge', default=False, action='store_true',
                        help='Merge input FT1 files into N files where N is determined '
                        'by files_per_split.')

    parser.add_argument('--files_per_split', default=100,
                        type=int, help='Set the number of files to combine in each '
                        'split of the input file list.')

    parser.add_argument('--file_idx_min', default=None,
                        type=int, help='Set the number of files to assign to '
                        'each batch job.')

    parser.add_argument('--file_idx_max', default=None,
                        type=int, help='Set the number of files to assign to '
                        'each batch job.')

    parser.add_argument('files', nargs='+', default=None,
                        help='List of files.')

    args = parser.parse_args()

    batch = vars(args).pop('batch')
    files = vars(args).pop('files')
    args.outdir = os.path.abspath(args.outdir)
    files = [os.path.abspath(f) for f in files]

    ft1_files = get_files(files, ['.fit', '.fits'])
    for i, f in enumerate(ft1_files):
        if re.search('^root\:\/\/', f) is None:
            ft1_files[i] = os.path.abspath(f)

    input_files = []
    output_files = []
    files_idx_min = []
    files_idx_max = []
    opts = []

    if args.file_idx_min is not None and args.file_idx_max is not None:

        files_idx_min = [args.file_idx_min]
        files_idx_max = [args.file_idx_max]
        input_files = [files]
        output_files = [args.output]

    elif args.merge:
        if not args.output:
            raise Exception('No output file defined.')

        nfiles = len(ft1_files)
        njob = int(np.ceil(nfiles / float(args.files_per_split)))
        for ijob, i in enumerate(range(0, nfiles, args.files_per_split)):

            if args.outdir is not None:
                mkdir(args.outdir)
                outdir = os.path.abspath(args.outdir)
            else:
                outdir = os.path.dirname(os.path.dirname(args.output))

            outfile = os.path.splitext(os.path.basename(args.output))[0]
            outfile += '_%03i.fits' % (ijob)
            outfile = os.path.join(outdir, outfile)
            input_files += [files]
            output_files += [outfile]
            files_idx_min += [i]
            files_idx_max += [i + args.files_per_split]
            opts += [vars(args).copy()]
            opts[-1]['output'] = outfile
            opts[-1]['file_idx_min'] = i
            opts[-1]['file_idx_max'] = i + args.files_per_split

    else:
        input_files = ft1_files
        files_idx_min = [i for i in range(len(ft1_files))]
        files_idx_max = [i + 1 for i in range(len(ft1_files))]
        output_files = [os.path.join(
            args.outdir, os.path.basename(x)) for x in ft1_files]
        opts = [vars(args).copy() for x in ft1_files]

    if batch:
        submit_jobs('fermipy-select',
                    input_files, opts, output_files, overwrite=args.overwrite,
                    dry_run=args.dry_run)
        sys.exit(0)

    logger = Logger.configure(os.path.basename(__file__), None, logging.INFO)
    logger.info('Starting.')

    if args.scfile is not None:
        args.scfile = os.path.abspath(args.scfile)

    cwd = os.getcwd()
    user = os.environ['USER']
    tmpdir = tempfile.mkdtemp(prefix=user + '.', dir='/scratch')
    os.chdir(tmpdir)

    logger.info('tmpdir %s', tmpdir)
    logger.info('outdir %s', args.outdir)
    logger.info('output %s', args.output)

    for infiles, outfile, idx_min, idx_max in zip(input_files, output_files,
                                                  files_idx_min, files_idx_max):

        logger.info('infiles %s', pprint.pformat(infiles))
        logger.info('outfile %s', outfile)
        infiles = get_files(infiles, ['.fit', '.fits'])
        if idx_min is not None:
            infiles = infiles[idx_min:idx_max]

        for i, f in enumerate(infiles):

            if re.search('^root\:\/\/', f) is None:
                continue
            os.system('xrdcp %s %s' % (f, f.split('/')[-1]))
            infiles[i] = os.path.join(tmpdir, f.split('/')[-1])

        kw = {k: args.__dict__[k] for k in gtselect_keys}
        if kw['emax'] is None:
            kw['emax'] = 1E6

        create_filelist(infiles, 'list.txt')
        kw['infile'] = 'list.txt'
        kw['outfile'] = 'out.fits'
        staged_outfile = kw['outfile']
        run_gtapp('gtselect', logger, kw)

        kw = {k: args.__dict__[k] for k in gtmktime_keys}
        if kw['roicut'] is None:
            kw['roicut'] = 'no'

        if kw['filter'] is None:
            kw['filter'] = 'DATA_QUAL==1 && LAT_CONFIG==1'
            if args.rock_angle is not None:
                kw['filter'] += ' && ABS(ROCK_ANGLE)<%(rock)s ' % dict(
                    rock=args.rock_angle)
        kw['evfile'] = 'out.fits'
        kw['outfile'] = 'out_filtered.fits'
        if args.scfile is not None:
            kw['scfile'] = args.scfile
            staged_outfile = kw['outfile']
            run_gtapp('gtmktime', logger, kw)

        logger.info('cp %s %s', staged_outfile, outfile)
        shutil.copy(staged_outfile, outfile)

    os.chdir(cwd)
    logger.info('Deleting %s', tmpdir)
    shutil.rmtree(tmpdir)
    logger.info('Done.')
1181338
def example():
    
    client = Client(ACCOUNT_SID, AUTH_TOKEN)

    # Get all messages
    all_messages = client.messages.list()
    print('There are {} messages in your account.'.format(len(all_messages)))

    # Get only last 10 messages...
    some_messages = client.messages.list(limit=10)
    print('Here are the last 10 messages in your account:')
    for m in some_messages:
        print(m)

    # Get messages in smaller pages...
    all_messages = client.messages.list(page_size=10)
    print('There are {} messages in your account.'.format(len(all_messages)))

    print('Sending a message...')
    new_message = client.messages.create(to='XXXX', from_='YYYY', body='Twilio rocks!')

    print('Making a call...')
    new_call = client.calls.create(to='XXXX', from_='YYYY', method='GET')

    print('Serving TwiML')
    twiml_response = VoiceResponse()
    twiml_response.say('Hello!')
    twiml_response.hangup()
    twiml_xml = twiml_response.to_xml()
    print('Generated twiml: {}'.format(twiml_xml))
166353
def main():
    
    prog = sys.argv[0]

    arg_parser = create_parser(prog)

    opts = parse_cmdline(arg_parser)

    print('Parameters: server=%s\n username=%s\n namespace=%s\n'
          ' classname=%s\n max_pull_size=%s\n use_pull=%s' %
          (opts.server, opts.user, opts.namespace, opts.classname,
           opts.max_object_count, opts.usepull))

    # call method to connect to the server
    conn = WBEMConnection(opts.server, (opts.user, opts.password),
                          default_namespace=opts.namespace,
                          no_verification=True,
                          use_pull_operations=opts.usepull)

    #Call method to create iterator
    instances = []
    try:
        iter_instances = conn.IterEnumerateInstances(
            opts.classname,
            MaxObjectCount=opts.max_object_count)

        # generate instances with
        for instance in iter_instances:
            print(' %s %s' % (type(instances), type(instance)))
            instances.append(instance)
            print('\npath=%s\n%s' % (instance.path, instance.tomof()))

    # handle exceptions
    except CIMError as ce:
        print('Operation Failed: CIMError: code=%s, Description=%s' %
              (ce.status_code_name, ce.status_description))
        sys.exit(1)
    except Error as err:
        print ("Operation failed: %s" % err)
        sys.exit(1)

    inst_paths = [inst.path for inst in instances]

    paths = []
    try:
        iter_paths = conn.IterEnumerateInstancePaths(
            opts.classname,
            MaxObjectCount=opts.max_object_count)

        # generate instances with
        for path in iter_paths:
            print('path=%s' % path)
            paths.append(path)

        if len(paths) != len(paths):
            print('Error path and enum response sizes different enum=%s path=%s'
                  % (len(paths), len(paths)))
        for path in paths:
            found = False
            for inst_path in inst_paths:                
                if path == inst_path:
                    found = True
                    break
                else:
                    print('No match \n%s\n%s' %(path, inst_path))
            if not found:
                print('Path %s not found in insts' % path)
    # handle exceptions
    except CIMError as ce:
        print('Operation Failed: CIMError: code=%s, Description=%s' %
              (ce.status_code_name, ce.status_description))
        sys.exit(1)
    except Error as err:
        print ("Operation failed: %s" % err)
        sys.exit(1)

    return 0
1106037
def main():
    
    if len(argv) < 3:
        print 'Usage for getting CFG: %s CFG_fileA CFG ' % argv[0]
        print 'Usage for getting STR: %s CFG_fileA STR ' \
              'Optimize[0 or 1] splitstring[0 or 1] ' % argv[0]
        print ''
        print 'For example: python pdacnf.py grammar.y STR 1 0'
        print '             python pdacnf.py grammar.y STR 1 1'
        print '             python pdacnf.py grammar.y CFG'
        return

    alphabet = createalphabet()

    mode = argv[2]

    optimized = 0
    splitstring = 0
    if mode == 'STR':
        optimized = int(argv[3])
        splitstring = int(argv[4])

    cfgtopda = CfgPDA(alphabet)
    print '* Parsing Grammar:',
    mma = cfgtopda.yyparse(argv[1])
    print 'OK'
    print ' - Total PDA states are ' + repr(len(mma.s))

    print '* Simplify State IDs:',
    simple_a = SimplifyStateIDs()
    mma.s, biggestid, newaccepted = simple_a.get(mma.s)
    if newaccepted:
        print 'OK'
    else:
        print 'OK'

    print '* Eliminate READ states:',
    replace = ReadReplace(mma.s, biggestid)
    mma.s = replace.replace_read()
    print 'OK'
    print ' - Total PDA states now are ' + repr(len(mma.s))
    maxstate = replace.nextstate() - 1

    print '* Reduce PDA:',
    simple_b = ReducePDA()
    mma.s = simple_b.get(mma.s)
    print 'OK'
    print ' - Total PDA states now are ' + repr(len(mma.s))

    print '* PDA to CFG transformation:',
    cnfgenerator = PdaCnf(mma.s)
    grammar = cnfgenerator.get_rules(optimized)
    print 'OK'
    print ' - Total CFG rules generated: ' + repr(len(grammar))

    if mode == 'STR':
        gen = CFGGenerator(CNFGenerator(grammar),
                           optimized=optimized,
                           splitstring=splitstring,
                           maxstate=maxstate)
        print gen.generate()
    else:
        print grammar
649785
def usage() -> None:
    

    print()
    print('Usage: setnym.py <config-ini>')
    print()
    print('where <config-ini> represents the path to the configuration file.')
    print()
    print('The operation submits a nym to a trustee anchor to send to the ledger,')
    print('if the ledger does not have it already as configured.')
    print()
    print('The configuration file has sections and entries as follows:')
    print('  * section [Node Pool]:')
    print('    - name: the name of the node pool to which the operation applies')
    print('    - genesis.txn.path: the path to the genesis transaction file')
    print('        for the node pool (may omit if node pool already exists)')
    print('  * section [Trustee Anchor]:')
    print("    - name: the trustee anchor's (wallet) name")
    print("    - wallet.type: (default blank) the trustee anchor's wallet type")
    print("    - wallet.access: (default blank) the trustee anchor's")
    print('        wallet access credential (password) value')
    print('  * section [VON Anchor]:')
    print('    - role: the role to request in the send-nym transaction; specify:')
    print('        - (default) empty value for user with no additional write privileges')
    print('        - TRUST_ANCHOR for VON anchor with write privileges for indy artifacts')
    print('        - TRUSTEE for VON anchor sending further cryptonyms to the ledger')
    print("    - name: the VON anchor's (wallet) name")
    print("    - seed: the VON anchor's seed (optional, for wallet creation only)")
    print("    - did: the VON anchor's DID (optional, for wallet creation only)")
    print('    - wallet.create: whether create the wallet if it does not yet exist')
    print('        (value True/False, 1/0, or Yes/No)')
    print("    - wallet.type: (default blank) the VON anchor's wallet type")
    print("    - wallet.access: (default blank) the VON anchor's")
    print('        wallet access credential (password) value.')
    print()
1625
def _main():
    
    import sys

    def log(message):
        print(message)

    def print_usage():
        log('usage: %s <application key> <application secret> send <number> <message> <from_number>' % sys.argv[0])
        log('       %s <application key> <application secret> status <message_id>' % sys.argv[0])

    if len(sys.argv) > 4 and sys.argv[3] == 'send':
        key, secret, number, message = sys.argv[1], sys.argv[2], sys.argv[4], sys.argv[5]
        client = SinchSMS(key, secret)
        if len(sys.argv) > 6:
            log(client.send_message(number, message, sys.argv[6]))
        else:
            log(client.send_message(number, message))
    elif len(sys.argv) > 3 and sys.argv[3] == 'status':
        key, secret, message_id = sys.argv[1], sys.argv[2], sys.argv[4]
        client = SinchSMS(key, secret)
        log(client.check_status(message_id))
    else:
        print_usage()
        sys.exit(1)

    sys.exit(0)
826935
def usage(self):
        
        if self._usage is None:
            self._usage = UsageList(self._version, account_sid=self._solution['sid'], )
        return self._usage
1083988
def show_command_line_usage(parser, usage=False):
    
    help_header_message = get_command_header(parser, "command", usage)
    loader = template.Loader(os.path.join(
        firenado.conf.ROOT, 'management', 'templates', 'help'))
    command_template = "  {0.name:15}{0.description:40}"
    help_message = loader.load("main_command_help.txt").generate(
        command_categories=command_categories,
        command_template=command_template
    ).decode(sys.stdout.encoding)
    # TODO: This print has to go. Use proper stream instead(stdout or stderr)
    print(''.join([help_header_message, help_message]))
143665
def _usage(shorthelp):
    
    doc = _sys.modules['__main__'].__doc__
    if not doc:
        doc = '\nUSAGE: %s [flags]\n' % _sys.argv[0]
        doc = flags.text_wrap(doc, indent='       ', firstline_indent='')
    else:
        # Replace all '%s' with sys.argv[0], and all '%%' with '%'.
        num_specifiers = doc.count('%') - 2 * doc.count('%%')
        try:
            doc %= (_sys.argv[0],) * num_specifiers
        except (OverflowError, TypeError, ValueError):
            # Just display the docstring as-is.
            pass
    if shorthelp:
        flag_str = flags.FLAGS.main_module_help()
    else:
        flag_str = str(flags.FLAGS)
    try:
        _sys.stdout.write(doc)
        if flag_str:
            _sys.stdout.write('\nflags:\n')
            _sys.stdout.write(flag_str)
        _sys.stdout.write('\n')
    except IOError as e:
        # We avoid printing a huge backtrace if we get EPIPE, because
        # "foo.par --help | less" is a frequent use case.
        if e.errno != _errno.EPIPE:
            raise
30463
def start_module(self):
        
        try:
            self._main()
        except Exception as exp:
            logger.exception('%s', traceback.format_exc())
            raise Exception(exp)