Example #1
0
    def parser():
        from argparse import ArgumentParser
        parser = ArgumentParser(prog='z', description=__doc__)

        parser.add_argument('patterns', metavar='REGEX', nargs='+',
                            help='Names to match')

        parser.add_argument('-c', default=False,
                            action='store_true', dest='subdir_only',
                            help='restrict matches to subdirectories of the current directory')

        actions = parser.add_mutually_exclusive_group()
        actions.add_argument('-e', const='echo', default='cd',
                           action='store_const', dest='action',
                           help="echo the best match, don't cd")
        actions.add_argument('-l', const='list', default='cd',
                           action='store_const', dest='action',
                           help='list only')
        actions.add_argument('-x', const='remove', default='cd',
                           action='store_const', dest='action',
                           help='remove the current directory from the datafile')
        # actions.add_argument('-h', const='help', default='cd',
        #                    action='store_const', dest='action',
        #                    help='show a brief help message')

        modes = parser.add_mutually_exclusive_group()
        modes.add_argument('-r', const='rank', default='frecency',
                           action='store_const', dest='mode',
                           help="match by rank only")
        modes.add_argument('-t', const='time', default='frecency',
                           action='store_const', dest='mode',
                           help="match by recent access only")

        return parser
Example #2
0
def parse_cmdline():
    from argparse import ArgumentParser
    parser = ArgumentParser(description=__doc__)
    g = parser.add_mutually_exclusive_group()
    g.add_argument('--serial',
        help="Arduino serial port [default: auto]")
    g.add_argument('--no-serial', action='store_true',
        help="There is no arduino, just print")
    parser.add_argument('--source',
        help="Pulseaudio source [default: auto]")
    parser.add_argument('--list-sources', action='store_true',
        help="List pulseaudio sources and exit")

    g = parser.add_mutually_exclusive_group()
    g.add_argument('-q', '--quiet', help="Talk less", dest='loglevel',
        action='store_const', const=logging.WARN, default=logging.INFO)
    g.add_argument('-v', '--verbose', help="Talk more", dest='loglevel',
        action='store_const', const=logging.DEBUG, default=logging.INFO)

    opt = parser.parse_args()

    if opt.list_sources:
        opt.no_serial = True

    return opt
Example #3
0
def main():

    parser = ArgumentParser(description="YTFS - YouTube Filesystem: search and play materials from YouTube using filesystem operations.", epilog="Streaming may not work if your player will read whole file into its buffer.", prog="ytfs", formatter_class=lambda prog: HelpFormatter(prog, max_help_position=50))
    parser.add_argument('mountpoint', type=str, nargs=1, help="Mountpoint")

    avgrp = parser.add_mutually_exclusive_group()
    avgrp.add_argument('-a', action='store_true', default=False, help="Download only audio")
    avgrp.add_argument('-v', action='store_true', default=False, help="Download only video")

    parser.add_argument('-f', default=False, help="Preferred video format as video height (e.g. 720). Ignored if -a specified.")
    parser.add_argument('-r', action='store_true', default=False, help="RickRoll flag")

    s_grp = parser.add_mutually_exclusive_group()
    s_grp.add_argument('-P', action='store_true', default=False, help="Always download whole data before reading. Useful for obtaining heighest video quality.")
    parser.add_argument('-d', action='store_true', default=False, help="debug: run in foreground")

    x = parser.parse_args()

    if x.a:
        YTStor.preferences['audio'] = True
        YTStor.preferences['video'] = False
    elif x.v:
        YTStor.preferences['video'] = True
        YTStor.preferences['audio'] = False

    if x.r: YTStor.rickastley = True

    if x.f: YTStor.preferences['format'] = x.f

    elif x.P:
        YTStor.preferences['stream'] = False

    print("Mounting YTFS ver. " + __version__ + ".\nIf you encounter any bugs, please open an issue on GitHub: https://github.com/rasguanabana/ytfs")

    FUSE(YTFS(), x.mountpoint[0], foreground=x.d)
Example #4
0
def compose(parser=None, **kwargs):
	global _prog

	if not parser:
		parser = ArgumentParser(**kwargs)
	parser.add_argument("--config", type=check_isfile, default=None,
			help="Specify a PyInq config file.")
	parser.add_argument("--outfile", type=check_filepath, default=None,
			help="The destination for the output file. (default: ./<filename>_report)")
	parser.add_argument("--suite",default=config._DEFAULT_SUITE,
			help="The suite to run. If not provided, all tests are run.")
	
	writer_parser = parser.add_mutually_exclusive_group()
	writer_parser.add_argument("--html", action="store_true",
			help="Output the report using the built-in HTML Report Writer")
	writer_parser.add_argument("--cli", action="store_true",
			help="Output the report using the built-in CLI Report Writer")
	
	action_parser = parser.add_mutually_exclusive_group()
	action_parser.add_argument("--print", action="store_true", dest="print_",
			help="Write the report to the command line.")
	action_parser.add_argument("--write", action="store_true",
			help="Write the report to the file specified by outfile.")
	
	_prog = parser.prog
	
	return parser
Example #5
0
def get_args():
    from argparse import ArgumentParser
    parser = ArgumentParser()

    parser.add_argument("-t", "--training",
                        choices=("handwritten", "typed", "digits",
                                 "shrinked"),
                        required=True,
                        help="Training data type.")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-d", "--training_dir",
                       help="Directory containing training data. The "
                       "directory structure depends on the training data "
                       "type.")
    group.add_argument("-f", "--training_file",
                       help="File containing training data.")
    parser.add_argument("-k", "--knearest", type=int, default=5,
                        help="Number of neighbors to compare against. "
                        "Defaults to %(default)d.")
    parser.add_argument("--thresh", type=int,
                        help="Background pixel threshold.")
    parser.add_argument("--width", type=int, default=20,
                        help="Sample image width. Defaults to %(default)d.")
    parser.add_argument("--height", type=int, default=20,
                        help="Sample image height. Defaults to %(default)d.")
    parser.add_argument("-r", "--retain", type=float, default=0.8,
                        help="Percentage of sample data to use as training "
                        "data. The rest will be used as test data. This "
                        "number is given as a float from 0.0 to 1.0, not a "
                        "value from 0 to 100. "
                        "Defaults to %(default)0.1f.")
    parser.add_argument("--samples", type=int, default=5,
                        help="Number of samples of each class to use. "
                        "Defaults to %(default)d.")

    group = parser.add_mutually_exclusive_group()
    group.add_argument("-s", "--save", nargs="?",
                       const="classifier.{timestamp}.p", default=None,
                       help="filename to save the classifier as. "
                       "Defaults to '%(const)s' if the flag is provided where "
                       "{timestamp} is the current system time.")
    group.add_argument("-p", "--pickle",
                       help="Saved classifier to load and test.")
    parser.add_argument("-v", "--verbose", action="count", default=0,
                        help="Logging verbosity. More verbose means more "
                        "logging info.")

    args = parser.parse_args()

    # Set logging verbosity
    logging.basicConfig(format="[%(asctime)s] %(levelname)s: %(message)s",
                        stream=sys.stderr)
    if args.verbose == 1:
        LOGGER.setLevel(logging.INFO)
    elif args.verbose == 2:
        LOGGER.setLevel(logging.DEBUG)

    return args
Example #6
0
def define_arguments():
    std_args = ArgumentParser(add_help=False)
    std_args.add_argument("profile", help="(aka environment)")
    std_args.add_argument("region", help="e.g. us-east-1, us-west-2, etc.")
    std_args.add_argument("vpc", help="VPC ID or 'classic'")

    logging = std_args.add_mutually_exclusive_group()
    logging.add_argument("--verbose", action="store_true", default=False)
    logging.add_argument("--debug", action="store_true", default=False)

    group_selection = std_args.add_mutually_exclusive_group()
    group_selection.add_argument("--groups", nargs="*", metavar="GROUP", default=[],
                                 help="Only list/modify these groups")

    ap = ArgumentParser()
    sp = ap.add_subparsers(title="Subcommands", dest="subcommand")
    sp.required = True

    #=====
    listcmd = sp.add_parser("list", parents=[std_args],
                            description="List current rules")
    listcmd.add_argument("--names", action='store_true', default=False)
    listcmd.set_defaults(do=do_list_rules)

    # the rest of the command require file input ...
    std_args.add_argument("--files", nargs="*", metavar="FILE", default=["-"],
                          help="Read rules from FILE instead of stdin. To include stdin explicitly, use '-'")
    std_args.add_argument("--tty", action="store_true", default=False,
                          help="Allow input from a tty")
    # ... and can make changes
    std_args.add_argument("--noop", action="store_true", default=False,
                          help="Don't change anything, just print what would have changed")

    #=====
    addcmd = sp.add_parser("add", parents=[std_args],
                           description="Add given rules")
    addcmd.add_argument("--create", help="Create named groups if needed")
    addcmd.set_defaults(do=do_add_rules)

    #=====
    delcmd = sp.add_parser("remove", parents=[std_args])
    delcmd.set_defaults(do=do_remove_rules)

    #=====
    upd_order = std_args.add_mutually_exclusive_group()
    upd_order.add_argument("--add-before-remove", action='store_true', default=True)
    upd_order.add_argument("--remove-before-add", action='store_false',
                           dest="add_before_remove")
    group_selection.add_argument("--obliterate", action="store_true", default=False,
                                 help="Remove all rules from groups not mentioned in the rule set")

    updcmd = sp.add_parser("update", parents=[std_args])
    updcmd.set_defaults(do=do_update_rules)

    return ap
def main():
    """Main method, entry point of the script."""
    from argparse import ArgumentParser
    description = "Download a bunch of thumbnails from Wikimedia Commons"
    parser = ArgumentParser(description=description)
    source_group = parser.add_mutually_exclusive_group()
    source_group.add_argument("-l", "--list", metavar="LIST",
                              dest="file_list",
                              type=argparse.FileType('r'),
                              help='A list of files <filename,width>')
    source_group.add_argument("-c", "--category", metavar="CATEGORY",
                              dest="category_name",
                              type=str,
                              help='A category name (without prefix)')
    parser.add_argument("files", nargs='*',
                        metavar="FILES",
                        help='A list of filenames')
    parser.add_argument("-o", "--output", metavar="FOLDER",
                        dest="output_path",
                        action=Folder,
                        default=os.getcwd(),
                        help='The directory to download the files to')
    parser.add_argument("-w", "--width",
                        dest="width",
                        type=int,
                        default=100,
                        help='The width of the thumbnail (default: 100)')
    verbosity_group = parser.add_mutually_exclusive_group()
    verbosity_group.add_argument("-v",
                                 action="count",
                                 dest="verbose",
                                 default=1,
                                 help="Verbosity level. -v for DEBUG")
    verbosity_group.add_argument("-q", "--quiet",
                                 action="store_const",
                                 dest="verbose",
                                 const=0,
                                 help="To silence the INFO messages")
    args = parser.parse_args()
    logging_map = {0: logging.WARNING,
                   1: logging.INFO,
                   2: logging.DEBUG}
    logging_level = logging_map.get(args.verbose, logging.DEBUG)
    logging.basicConfig(level=logging_level)
    logging.info("Starting")

    if args.file_list:
        download_from_file_list(args.file_list, args.output_path)
    elif args.category_name:
        download_from_category(args.category_name, args.output_path, args.width)
    elif args.files:
        download_from_files(args.files, args.output_path, args.width)
    else:
        parser.print_help()
Example #8
0
def build_parser(description):
    """Create ArgumentParser instance with all suported options."""
    parser = ArgumentParser(
        description=description,
        usage="%(prog)s [options] SOURCE [PATH[:PATH]]")

    parser.add_argument(
        "source", type=str,
        help="python module or reStructured text file",
        metavar="SOURCE")
    parser.add_argument(
        "path", default="", type=str, nargs='?', metavar="PATH[:PATH]",
        help="template paths separated by colon")
    parser.add_argument(
        "-O", "--output", type=str, metavar="FILE",
        help="write html to output file insead of stdout")
    parser.add_argument(
        "--encoding", default="utf-8", type=str, metavar="STRING",
        help="write html to output file insead of stdout")
    parser.add_argument(
        "--stylesheet",  default="style.css", type=str, metavar="FILE[,FILE]",
        help="stylesheet file name (default style.css)")
    parser.add_argument(
        "--embed-stylesheet", action="store_true",
        help="embed the stylesheet(s) in the output HTML file "
             "(default: False)")
    parser.add_argument(
        "--system-message", action="store_true",
        help="output system messages to output html (default: False)")
    link_group = parser.add_mutually_exclusive_group()
    link_group.add_argument(
        "--link", default="link", type=str, metavar="STRING",
        help="the `link' string (default: `link')")
    link_group.add_argument(
        "--no-link", action="store_const", const='', dest='link',
        help="don't create the `link' link for sections.")
    top_group = parser.add_mutually_exclusive_group()
    top_group.add_argument(
        "--top", default="top", type=str, metavar="STRING",
        help="the `top' string (default: `top')")
    top_group.add_argument(
        "--no-top", action="store_const", const='', dest='top',
        help="don't create the `top' link for sections.")
    parser.add_argument(
        "--traceback", action="store_true",
        help="Enable Python tracebacks.")
    parser.add_argument(
        "-v", "--verbose", action="store_true",
        help="verbose mode")
    parser.add_argument(
        '--version', action='version', version='%%(prog)s %s' % __version__)
    return parser
Example #9
0
class CmdOption(object):
    def __init__(self):
        self.version = 'PyShanb %s' % __version__
        description = 'An command line tool for shanbay.com.'
        self.parser = ArgumentParser(description=description)

        self.parser.add_argument('-V', '--version', action='version',
                                 version=self.version)
        self.parser.add_argument('-s', '--settings', dest='settings',
                                 help='the settings file of the application',
                                 default=default_configfile)
        self.parser.add_argument('-u', '--username', dest='username',
                                 help='the account username of shanbay.com')
        self.parser.add_argument('-p', '--password', dest='password',
                                 help='the account password of shanbay.com')

        group_example = self.parser.add_mutually_exclusive_group()
        group_example.add_argument('-e', '--add-example', action='store_true', default=None,
                                   dest='ask_add_example',
                                   help='enable "Add example" feature')
        group_example.add_argument('-E', '--disable-add-example', action='store_false', default=None,
                                   dest='ask_add_example',
                                   help='disable "Add example" feature')


        self.parser.add_argument('--color', dest='colour', default='green',
                                 choices=['black', 'white', 'red', 'green',
                                          'yellow', 'blue', 'magenta', 'cyan',
                                          'gray'],
                                 help='colorize keyword (default: green)')


        group_ex = self.parser.add_mutually_exclusive_group()
        group_ex.add_argument('--example', '--enable-example', action='store_true',
                              dest='example', help='enable examples',
                              default=None)
        group_ex.add_argument('--disable-example', action='store_false',
                              dest='example', help='disable examples',
                              default=None)

        group_en = self.parser.add_mutually_exclusive_group()
        group_en.add_argument('--english', action='store_true',
                              dest='english', help='enable english definition',
                              default=None)
        group_en.add_argument('--disable-english', action='store_false',
                              dest='english', help='disable english definition',
                              default=None)

        self.options = self.parser.parse_args()
Example #10
0
def get_args():
    p = ArgumentParser(description="estimate combined number of generations between pairs of individuals")
    p.add_argument("matchfile", help="input match file")
    p.add_argument("-a", "--alpha", help="significance level (default: %(default).2f)",
                   type=float, default=0.05)
    p.add_argument("--avuncular-adj", help="apply the adjustment to Na from Li et al. (2014) for avuncular (a=2, d=3) relationships",
                   action="store_true")
    p.add_argument("-c", help="number of autosomes (default: %(default)d for humans)",
                   type=int, default=22)
    p.add_argument("-ci", help="generate confidence intervals",
                   action='store_true')
    p.add_argument("-d", "--dmax", help="max combined number of generations to test (default: %(default)d)",
                   type=int, default=10)
    p.add_argument("--first_deg_adj", help="Include adjustments for first-degree relationships",
                   action="store_true")
    p.add_argument("-H", help="input matchfile contains an extra column at the end of each line with haploscores (discarded by ersa)",
                   action='store_true')
    p.add_argument("-l", help="mean number of segments shared in the population (default: %(default).1f)",
                   type=float, default=13.73)
    p.add_argument("--merge-segs", help="merge segments that are on the same chromosome and <= MERGE-SEGS bp apart (default No merge)",
                   type=int, default=-1)
    p.add_argument("--nomask", help="disable genomic region masking",
                   action="store_true")
    p.add_argument("-r", help="expected number of recombination events per haploid genome per generation (default %(default).1f for humans)",
                   type=float, default=35.2548101)
    p.add_argument("-t", help="min segment length (in cM) to include in comparisons (default %(default).1f)",
                   type=float, default=2.5)
    p.add_argument("-u", "--user", help="filter input file to only look at USER",
                   type=str)
    p.add_argument("-th", "--theta", help="mean shared segment length (in cM) in the population (default %(default).3f)",
                   type=float, default=3.197036753)
    p.add_argument("--skip-soft-delete", help="Assume the database is empty, don't soft-delete before inserting new data",
                   action='store_true', default=False)

    group = p.add_mutually_exclusive_group()
    group.add_argument("-D", help="direct output to database D")
    group.add_argument("-o", "--ofile", help="direct output to OFILE")

    group2 = p.add_mutually_exclusive_group()
    group2.add_argument("--insig-threshold", help="Threshold (cM) minimum to keep insignificant results (default: off)",
                        type=float, default=None)
    group2.add_argument("--keep-insig-by-seg", help="Keep insignificant results that have at least <first value> segments shared of the specified size <second value> (default: off)",
                        type=float, default=None, nargs=2)
    group2.add_argument("--keep-insignificant", help="push insignificant results to the database where d_est is NULL (default: discard below INSIG-THRESHOLD)",
                        action='store_true')

    args = p.parse_args()
    return args
Example #11
0
    def _parse_snapshot_restore_command(cls, args, action):
        """
        Parse command line arguments for snapshot command.
        """
        argparser = ArgumentParser(prog="cluster %s" % action)

        group = argparser.add_mutually_exclusive_group(required=True)
        group.add_argument("--id", dest="cluster_id",
                          help="execute on cluster with this id")
        group.add_argument("--label", dest="label",
                          help="execute on cluster with this label")
        argparser.add_argument("--s3_location",
                          help="s3_location where backup is stored", required=True)
        if action == "snapshot":
            argparser.add_argument("--backup_type",
                          help="backup_type: full/incremental, default is full")
        elif action == "restore_point":
            argparser.add_argument("--backup_id",
                          help="back_id from which restoration will be done", required=True)
            argparser.add_argument("--table_names",
                          help="table(s) which are to be restored", required=True)
            argparser.add_argument("--no-overwrite", action="store_false",
                          help="With this option, restore overwrites to the existing table if theres any in restore target")
            argparser.add_argument("--no-automatic", action="store_false",
                          help="With this option, all the dependencies are automatically restored together with this backup image following the correct order")
        arguments = argparser.parse_args(args)

        return arguments
Example #12
0
    def _parse_list(cls, args):
        """
        Parse command line arguments to construct a dictionary of cluster
        parameters that can be used to determine which clusters to list.

        Args:
            `args`: sequence of arguments

        Returns:
            Dictionary that can be used to determine which clusters to list
        """
        argparser = ArgumentParser(prog="cluster list")

        group = argparser.add_mutually_exclusive_group()

        group.add_argument("--id", dest="cluster_id",
                           help="show cluster with this id")

        group.add_argument("--label", dest="label",
                           help="show cluster with this label")

        group.add_argument("--state", dest="state", action="store",
                           choices=['up', 'down', 'pending', 'terminating'],
                           help="list only clusters in the given state")

        arguments = argparser.parse_args(args)
        return vars(arguments)
Example #13
0
 def make_parser():
     parser = ArgumentParser(add_help=False)
     parser.add_argument("--foo", action="store_true")
     group = parser.add_mutually_exclusive_group()
     group.add_argument("--bar", action="store_true")
     group.add_argument("--no-bar", action="store_true")
     return parser
Example #14
0
 def make_parser():
     parser = ArgumentParser(add_help=False)
     parser.add_argument("name", choices=["name1", "name2"])
     group = parser.add_mutually_exclusive_group()
     group.add_argument("--get", action="store_true")
     group.add_argument("--set", action="store_true")
     return parser
Example #15
0
def process_args():
    usage_str = """
    %(prog)s [OPTIONS] [FILES] """
    epilog_str = """

    """
    parser = ArgumentParser(description='seL4 System Call Stub Generator.',
                            usage=usage_str,
                            epilog=epilog_str)
    parser.add_argument("-o", "--output", dest="output", default="/dev/stdout",
                        help="Output file to write stub to. (default: %(default)s).")
    parser.add_argument("-b", "--buffer", dest="buffer", action="store_true", default=False,
                        help="Use IPC buffer exclusively, i.e. do not pass syscall arguments by registers. (default: %(default)s)")
    parser.add_argument("-a", "--arch", dest="arch", required=True, choices=WORD_SIZE_BITS_ARCH,
                        help="Architecture to generate stubs for.")

    wsizegroup = parser.add_mutually_exclusive_group()
    wsizegroup.add_argument("-w", "--word-size", dest="wsize",
                            help="Word size(in bits), for the platform.")
    wsizegroup.add_argument("-c", "--cfile", dest="cfile",
                            help="Config file for Kbuild, used to get Word size.")

    parser.add_argument("files", metavar="FILES", nargs="+",
                        help="Input XML files.")

    return parser
Example #16
0
def main():
	parser = ArgumentParser()

	# Add a required argument called num
	parser.add_argument("num", help="position where fibonacci" + \
		"number is needed", type=int)

	# Add an optional argument called output
	parser.add_argument("-o", "--output", help="Output the result " +\
		"to a file", action="store_true")

	# Add a mutually exclusive group for 2 new arguments
	group = parser.add_mutually_exclusive_group()
	group.add_argument("-v", "--verbose", help="Print verbose result", action="store_true")
	group.add_argument("-q", "--quiet", help="Only print the result", action="store_true")

	args = parser.parse_args()

	result = fib(args.num)
	if args.verbose:
		print "The "+str(args.num)+"th fibonacci number is "+str(result)
	elif args.quiet:
		print result
	else:
		print "fib("+str(args.num)+") = "+str(result)
	if args.output:
		f = open("fib.txt", 'a')
		f.write(str(result)+"\n")
def main():
    parser = ArgumentParser(description="armarx version script")

    verbose_group = parser.add_mutually_exclusive_group()
    verbose_group.add_argument('-v', '--verbose', action='store_true', help='be verbose')
    verbose_group.add_argument('-q', '--quiet', action='store_true', help='be quiet')

    parser.add_argument('-s', '--serial-port', default='/dev/ttyUSB0', help='the serial port')
    parser.add_argument('-f', '--calibration-file', default='bno055.json', help='the output calibration file')

    args = parser.parse_args()

    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)
    elif args.quiet:
        logging.basicConfig(level=logging.ERROR)

    device = BNO055(serial_port=args.serial_port)
    device.set_external_crystal(True)

    calibration_status = device.get_calibration_status()
    while calibration_status != (3, ) * 4:
        logger.debug('waiting for device to be fully calibrated. please rotate IMU.')
        logger.debug('calibration status is {} {} {} {} '.format(*calibration_status))

        try:
            time.sleep(1)
        except KeyboardInterrupt:
            logger.info('keyboard interrupt. existing')
            sys.exit()

    logger.info('done calibrating device.')
    # os.makedirs(os.path.dirname(calibration_file))
    device.write_calibration(args.calibration_file)
Example #18
0
 def _get_opts(self, args):
     opts = {}
     
     parser = ArgumentParser(description = 'A static blog generator.')
     
     parser.add_argument('src', nargs = '?', default = '.', metavar = 'source', help = 'The location %(prog)s looks for source files.')
     parser.add_argument('dest', metavar = 'destination', help = 'The location %(prog)s outputs to.')
     
     level = parser.add_mutually_exclusive_group()
     
     level.add_argument('-l', '--level', default = b'INFO', type = str.upper, choices = ['DEBUG', 'INFO', 'WARNING', 'ERROR'], help = 'Sets %(prog)s\'s log level.')
     level.add_argument('-q', '--quiet', action = 'store_const', const = 'ERROR', dest = 'level', help = 'Sets %(prog)s\'s log level to ERROR.')
     level.add_argument('-v', '--verbose', action = 'store_const', const = 'DEBUG', dest = 'level', help = 'Sets %(prog)s\'s log level to DEBUG.')
     
     parser.add_argument('--base-url', help = 'Sets the site\'s base URL.')
     parser.add_argument('-f', '--force', action = 'store_true', help = 'Forces generation deleting the destination if it already exists.')
     
     parser.add_argument('-V', '--version', action = 'version', version = '%(prog)s v{0}'.format(__version__), help = 'Prints %(prog)s\'s version and exits.')
     
     for option, value in vars(parser.parse_args(args)).iteritems():
         if value is not None:
             if isinstance(option, str):
                 option = option.decode('utf-8')
             
             if isinstance(value, str):
                 value = value.decode('utf-8')
             
             opts[option] = value
     
     return opts
Example #19
0
def main():
    parser = ArgumentParser(prog='findgit',
                            description=DESCRIPTION,
                            formatter_class=RawTextHelpFormatter)
    parser.add_argument(dest='directory', metavar='DIR',
                        help='Path to scanning')
    group = parser.add_mutually_exclusive_group(required=False)
    group.add_argument('-l', '--local', action='store_true',
                       help='Search local repositories only')
    group.add_argument('-r', '--remote', action='store_true',
                       help='Search remote repositories only')
    group.add_argument('-o', '--outdated', action='store_true',
                       help='Search outdated repositories only')

    args = parser.parse_args()
    if args.local:
        search_mask = TYPE_LOCAL
    elif args.remote:
        search_mask = TYPE_REMOTE
    elif args.outdated:
        search_mask = TYPE_OUTDATED
    else:
        search_mask = TYPE_LOCAL | TYPE_REMOTE
    try:
        find_git_repos(args.directory, search_mask)
    except KeyboardInterrupt:
        print('Cancelled')
Example #20
0
def main():
    #GENERAL SETTINGS!
    directory      = path[0] + "/config/"
    extention      = ".ini"
    description    = "Cool Command-line Cheatsheets"
    help_general   = "The cheatsheet you want to see"
    help_inline    = "One cheat per line, this is default"
    help_breakline = "Break lines"

    #COMMAND-LINE ARGUMENTS!
    argumentparser = ArgumentParser(description=description)
    printertype = argumentparser.add_mutually_exclusive_group()

    argumentparser.add_argument('cheatsheet', help=help_general)
    printertype.set_defaults(printer='InlinePrinter')
    printertype.add_argument('-l', help=help_inline, action='store_const', dest='printer', const='InlinePrinter')
    printertype.add_argument('-b', help=help_breakline, action='store_const', dest='printer', const='BreaklinePrinter')

    #WHERE THE RUBBER MEETS THE ROAD!
    cmd_arguments = argumentparser.parse_args()
    filename = directory + cmd_arguments.cheatsheet + extention
    CheatPrinterConstructor = globals()[cmd_arguments.printer]
    configparser = ConfigParser()
    cheatprinter = CheatPrinterConstructor(configparser)

    try:
        configparser.read(filename)
        cheatprinter.printsheet()
        exitcode = 0
    except:
        #I know lazy handling, but it works perfect... Sorry.
        print(filename + " not available or contains errors.")
        exitcode = 1
    finally:
        exit(exitcode)
Example #21
0
def main():
    from os import path
    import sys

    parser = ArgumentParser(prog="gcMapExplorer hic2gcmap", description="Convert hic files to gcmap",
                            allow_abbrev=False)
    parser.add_argument("input", type=HicFileType(), help="hic input file")
    parser.add_argument("output", type=str, nargs="?", help="output file or directory", default=".")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-c", "--chromosomes", type=str, nargs=2, metavar=("A", "B"), help="a pair of chromosomes A B")
    group.add_argument("-l", "--list", action="store_true", help="list all available chromosomes")
    parser.add_argument("--compression", type=str, choices=("lzf", "gzip"), default="lzf", metavar="C",
                        help="compression type, choose between lzf, gzip (default: lzf)")
    parser.add_argument("-r", "--resolution", type=resolution, default="finest", metavar="R",
                        help="the resolution, as an integer or as kb (default: finest)")
    parser.add_argument("-n", "--norm", type=str, choices=("VC", "VC_SQRT", "KR", "none"), metavar="N",
                        default="none",
                        help="the type of norm to use, choose between VC, VC_SQRT, KR, none (default: none)")
    parser.add_argument("--downsampling", type=str, choices=("sum", "mean", "max", "none"), default="sum", metavar="D",
                        help="the downsampling method to use, choose between sum, mean, max, none (default: sum)")

    args = parser.parse_args(args=sys.argv[sys.argv.index("hic2gcmap") + 1:])

    hic = args.input

    if args.list:
        print(", ".join(hic.chromosomes))
        return

    if path.isdir(args.output):
        filename = path.splitext(path.basename(args.input.name))[0]
        output_file = path.join(args.output, filename)
        if args.chromosomes:
            output_file += "_" + "_".join(args.chromosomes)
        if args.downsampling == "none" and args.resolution != "finest":
            output_file += "_" + str(args.resolution)[:-3] + "kb"
        if args.norm != "none":
            output_file += "_" + args.norm
        output_file += "_" + args.compression
        output_file += ".gcmap"
    else:
        output_file = args.output

    if args.chromosomes:
        chr1, chr2 = args.chromosomes
        try:
            hic2gcmap(hic, chr1, chr2, output_file, resolution=args.resolution, norm_type=norm(args.norm),
                      compression=args.compression,
                      downsampling=args.downsampling)
        except Exception as e:
            print("Error: {}".format(e))
    else:  # all chromosomes
        chromosome_names = filter(lambda pair: "All" not in pair, (hic.chromosome_names(r) for r in hic.records))
        for chr1, chr2 in chromosome_names:
            try:
                hic2gcmap(hic, chr1, chr2, output_file, resolution=args.resolution, norm_type=norm(args.norm),
                          compression=args.compression,
                          downsampling=args.downsampling)
            except Exception as e:
                print("Error: {}".format(e))
Example #22
0
def main():
    parser = ArgumentParser()
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-p", "--primary", action="store_true", default=False)
    group.add_argument("-b", "--backup", action="store_true", default=False)
    args = parser.parse_args()

    ctx = zmq.Context()
    statepub = ctx.socket(zmq.PUB)
    statesub = ctx.socket(zmq.SUB)
    statesub.setsockopt_string(zmq.SUBSCRIBE, u"")
    frontend = ctx.socket(zmq.ROUTER)

    fsm = BStarState(0, 0, 0)

    if args.primary:
        print("I: Primary master, waiting for backup (slave)")
        frontend.bind("tcp://*:5001")
        statepub.bind("tcp://*:5003")
        statesub.connect("tcp://localhost:5004")
        fsm.state = STATE_PRIMARY
    elif args.backup:
        print("I: Backup slave, waiting for primary (master)")
        frontend.bind("tcp://*:5002")
        statepub.bind("tcp://*:5004")
        statesub.connect("tcp://localhost:5003")
        statesub.setsockopt_string(zmq.SUBSCRIBE, u"")
        fsm.state = STATE_BACKUP

    send_state_at = int(time.time() * 1000 + HEARTBEAT)
    poller = zmq.Poller()
    poller.register(frontend, zmq.POLLIN)
    poller.register(statesub, zmq.POLLIN)

    while True:
        time_left = send_state_at - int(time.time() * 1000)
        if time_left < 0:
            time_left = 0
        socks = dict(poller.poll(time_left))
        if socks.get(frontend) == zmq.POLLIN:
            msg = frontend.recv_multipart()
            fsm.event = CLIENT_REQUEST
            try:
                run_fsm(fsm)
                frontend.send_multipart(msg)
            except BStarException:
                del msg

        if socks.get(statesub) == zmq.POLLIN:
            msg = statesub.recv()
            fsm.event = int(msg)
            del msg
            try:
                run_fsm(fsm)
                fsm.peer_expiry = int(time.time() * 1000) + (2 * HEARTBEAT)
            except BStarException:
                break
        if int(time.time() * 1000) >= send_state_at:
            statepub.send("%d" % fsm.state)
            send_state_at = int(time.time() * 1000) + HEARTBEAT
Example #23
0
def parse_args(output_formats):
    parser = ArgumentParser(description='crate shell')
    parser.add_argument('-v', '--verbose', action='count',
                        dest='verbose', default=0,
                        help='use -v to get debug output')
    parser.add_argument('--history',
                        type=str,
                        help='the history file to use', default=HISTORY_PATH)

    group = parser.add_mutually_exclusive_group()
    group.add_argument('-c', '--command', type=str,
                        help='execute sql statement')
    group.add_argument('--sysinfo', action='store_true', default=False,
                        help='show system information')

    parser.add_argument('--hosts', type=str, nargs='*',
                        help='the crate hosts to connect to', metavar='HOST')
    parser.add_argument('--format', type=str, default='tabular', choices=output_formats,
                        help='output format of the sql response', metavar='FORMAT')
    parser.add_argument('--version', action='store_true', default=False,
                        help='show crash version and exit')
    try:
        import argcomplete
        argcomplete.autocomplete(parser)
    except ImportError:
        pass
    args = parser.parse_args()
    return args
Example #24
0
def gen_argpsr():
    from argparse import ArgumentParser
    from _version_data import VERSION
    psr = ArgumentParser(description='Generate n-grams of method calls')
    psr.add_argument('-a', '--asm-directory', action='store')

    psr.add_argument('-n', '--ngram-size', action='store', type=int, default=6)
    psr.add_argument('-v', '--verbose', action='store_true')
    psr.add_argument('--max-branch', action='store', type=int, default=-1,
            help='max branches in a method (such as ifs and switch-cases). =-1 means unlimited')
    psr.add_argument('--max-call-depth', action='store', type=int, default=-1,
            help='max depth in expanding method calls. =-1 means specify ngram-size as limit')
    psr.add_argument('--max-method-definition', action='store', type=int, default=-1,
            help='max method defintions for a signiture. =-1 means unlimited')
    psr.add_argument('--target-class-method', action='store', nargs='*')
    psr.add_argument('-e', '--exclude', action='store', nargs='*',
            help="specify classes by fully-qualified name, e.g. org/myapp/MyClass$AInnerClass. A wildcard '*' can be used as class name, e.g. org/myapp/*")
    psr.add_argument('--include-ctors', action='store_true',
            help='include "<init>" and access$... methods as targets')

    grp = psr.add_mutually_exclusive_group(required=False)
    grp.add_argument('--mode-diagnostic', action='store_true',
            help='show bytecode info and the filtering results')
    grp.add_argument('--mode-method-signature', action='store_true',
            help='show method signatures')
    grp.add_argument('--mode-method-body', action='store_true',
            help='show method bodies (byte code)')

    psr.add_argument('--version', action='version', version='%(prog)s ' + VERSION)
    return psr
Example #25
0
def create_args_parser():
    parser = ArgumentParser(description=description,
                            epilog=epilog,
                            formatter_class=RawTextHelpFormatter)

    parser.add_argument("-o", "--host",
                        help=host_help)
    parser.add_argument("-p", "--port", type=int,
                        help=port_help)
    parser.add_argument("-u", "--username", metavar='NAME',
                        help=username_help)
    parser.add_argument("-w", "--password", metavar='PASS',
                        help=password_help)
    parser.add_argument("-c", "--config-file", metavar='CONF_FILE',
                        help=config_file_help)
    parser.add_argument("-r", "--reboot",
                        action='store_true', help=reboot_help)
    parser.add_argument("-s", "--simulate",
                        action='store_true', help=simulate_help)

    group = parser.add_mutually_exclusive_group()
    group.add_argument("-v", dest='verbosity',
                       default=0, action='count', help=v_help)
    group.add_argument("--verbose", dest='verbosity',
                       default=0, type=int, help=verbose_help)

    return parser
Example #26
0
class ArgsWrapper():
    """Wraps argparse."""

    def __init__(self):
        self.parser = ArgumentParser(description='Manage gunicorn servers')
        self._build()

    def parse(self):
        """Parse the command line and return results."""
        args = self.parser.parse_args()
        if args.task in ['status',]:
            console_level = 'ERROR'
        elif args.verbose:
            console_level = 'DEBUG'
        elif args.quiet:
            console_level = 'ERROR'
        else:
            console_level = 'INFO'
        return (args, console_level)

    def _build(self):
        """Initialize with arguments."""
        self.parser.add_argument(
                    'task', help='operation to perform',
                    choices=['stop', 'start', 'status', 'restart'])
        self.parser.add_argument(
                'instances', metavar='instance', nargs='+', help='server numbers')
        exclusive = self.parser.add_mutually_exclusive_group()
        exclusive.add_argument('-v', '--verbose', action='store_true',
                help='show debug logging on console')
        exclusive.add_argument('-q', '--quiet', action='store_true',
                help='suppress non-error logging on console')
Example #27
0
    def get_parser(self):
        p = ArgumentParser(self.description)
        p.formatter_class = argparse.RawDescriptionHelpFormatter
        p.add_argument('-a', '--all', action='store_true', default=False,
                       help="Display all images")
        p.add_argument('-l', '--long', action='store_true', default=False,
                       help='Display extra information for each image')
        p.add_argument('--sharedwith', action='store_true', default=False,
                       help='modifier flag.  See epilog for examples.')
        g = p.add_mutually_exclusive_group()
        g.add_argument('-u', '--user', help='List images owned by USER')
        g.add_argument('-g', '--group', help="List images shared with GROUP.")
        p.epilog = """\
Example Usages:

    repoman list
        list the current users images

    repoman list --sharedwith
        list all images shared with the current user

    repoman list --user bob
        list all images owned by the user 'bob'

    repoman list --sharedwith --user bob
        list all images shared with the user 'bob'

    repoman list --group babar
        list all images accessible by members of the 'babar' group

    repoman list --sharedwith --group babar
        has the same effect as the previous example."""

        return p
Example #28
0
def main():

    #arg parser stuff
    parser = ArgumentParser(description='pyS3backup - A program to manage backing up important data '
                                        'to an offsite s3 backup')
    action = parser.add_mutually_exclusive_group(required= True)
    action.add_argument('-l','--list', action='store_true', help='List current offsite backups')
    action.add_argument('-b','--backup', action='store_true', help='run the backup')
    action.add_argument('-r','--restore', help='restore file')
    action.add_argument('-x','--delete', help='delete backup')
    parser.add_argument('-d','--dest', help='restore destination')

    args = parser.parse_args()

    try:
        cfg = configuration.get()
        ACCESS_KEY = cfg.get('s3_info', 'access_key')
        SECRET_KEY = cfg.get('s3_info', 'secret_key')
        S3_BUCKET = cfg.get('s3_info', 's3_bucket')


    except Exception,e:
        sys.stderr.write("Error parsing configuration file, read the docs")
        log.info(e)
        exit(0)
Example #29
0
def arguments():
    """Define the command line arguments for the script.

    :returns: the argument parser

    """
    main_desc = '''Manage dotfiles (configuration files in a Linux system)'''

    parser = ArgumentParser(description=main_desc)
    input_file = parser.add_mutually_exclusive_group(required=True)
    input_file.add_argument(
        "-i",
        "--ical",
        help="the icalendar (*.ics) input file",
    )
    input_file.add_argument(
        "-r",
        "--remote",
        help="the remote ical calendars file",
    )
    parser.add_argument(
        "-o",
        "--org",
        required=True,
        help="the org-mode (*.org) output file",
    )
    return parser
Example #30
0
def arguments():
    """Defines the command line arguments for the script."""
    cur_dir = os.path.curdir
    main_desc = """Move (or copy/remove) all files selected by extension into a
    directory tree to a destination directory."""
    usage = "%(prog)s ext [-s SRC] [-d DST] [-c | -r] [--help]"

    parser = ArgumentParser(description=main_desc, usage=usage)
    parser.add_argument("ext", nargs='+', help="the extension(s) of the files "
                        "to process. To use more than one extension, separate "
                        "them with a space")
    parser.add_argument("-s", "--src", dest="src", default=cur_dir, help="the "
                        "source path. Current dir if none is provided")
    parser.add_argument("-d", "--dst", dest="dst", default=cur_dir, help="the "
                        "destination path. Current dir if none is provided")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-c", "--copy", dest="cp", action="store_true",
                       help="copy all the files with the given extension(s) "
                       "to the destination directory.")
    group.add_argument("-r", "--remove", dest="rm", action="store_true",
                       help="remove all the files with the given extension(s)."
                       " Use with caution! remove also in the subdirectories")
    parser.add_argument("-v", "--version", action="version",
                        version="%(prog)s {0}".format(__version__),
                        help="show program's version number and exit")
    return parser
Example #31
0
 def configure_parser(self, parser: ArgumentParser):
     """
     configure the argument parser
     """
     group = parser.add_mutually_exclusive_group()
     group.add_argument(
         "--md5",
         dest="hash_fnc",
         action="store_const",
         const=hashlib.md5,
         default=hashlib.md5,
         help="use md5 for fingerprint",
     )
     group.add_argument(
         "--sha1",
         dest="hash_fnc",
         action="store_const",
         const=hashlib.sha1,
         help="use sha1 for fingerprint",
     )
     group.add_argument(
         "--sha256",
         dest="hash_fnc",
         action="store_const",
         const=hashlib.sha256,
         help="use sha256 for fingerprint",
     )
     group.add_argument(
         "--sha384",
         dest="hash_fnc",
         action="store_const",
         const=hashlib.sha384,
         help="use sha384 for fingerprint",
     )
     group.add_argument(
         "--sha512",
         dest="hash_fnc",
         action="store_const",
         const=hashlib.sha512,
         help="use sha512 for fingerprint",
     )
     parser.add_argument("-r",
                         "--recursive",
                         action="store_true",
                         help="visit folder content")
     parser.add_argument(
         "-l",
         "--len",
         dest="length",
         type=int,
         metavar="N",
         help="truncate fingerprint to N chars",
     )
     parser.add_argument("-e",
                         "--ext",
                         action="store_true",
                         help="append file extension")
     parser.add_argument(
         "-o",
         "--output",
         dest="folder",
         type=Path,
         help="rename files in specific folder",
     )
     parser.add_argument("files",
                         nargs=argparse.ONE_OR_MORE,
                         type=Path,
                         help="files to rename")
     return parser
def rasl_arg_parser(description,
                    path=None,
                    tform=AffineTransform,
                    grid=(3, 10),
                    frame=5):
    """standard argument parser for RASL utilities that load an image directory

    Parameters
    ----------
    description : string
        command description
    path : string or None
        path to image directory. If provided, becomes the default value
        for --path. If None, path is a required commandline argument
    tform : TForm
        default transform type
    grid : tuple(2)
        shape of image grid to display
    frame : real or real(2) or (real(2), real(2))
        crop images to specified frame:
        pixel-width of boundary (single number), cropped image
        size (tuple, centered) or boundary points (minimum and
        maximum points) as pixel offsets into the image, values
        ranging [0, max-1]. Negative values are subtracted from
        the dimension size, as with python array indexing.

    Returns
    -------
    parser : ArgumentParser
        configured argument parser

    """
    parser = ArgumentParser(description=description)
    parser.set_defaults(tform=tform)
    tformspec = parser.add_mutually_exclusive_group()
    tformspec.add_argument("--euclidean",
                           dest='tform',
                           action='store_const',
                           const=EuclideanTransform,
                           help="Align using rotation and translation")
    tformspec.add_argument(
        "--similarity",
        dest='tform',
        action='store_const',
        const=SimilarityTransform,
        help="Align using a similarity transform (rotate, scale, translate)")
    tformspec.add_argument(
        "--affine",
        dest='tform',
        action='store_const',
        const=AffineTransform,
        help="Align using an affine transform (rotate, shear, translate)")
    tformspec.add_argument(
        "--projective",
        dest='tform',
        action='store_const',
        const=ProjectiveTransform,
        help="Align using a projective transform (affine + perspective)")
    parser.add_argument("--grid",
                        type=int,
                        nargs=2,
                        default=grid,
                        help=dedent("""\
        image grid shape (rows cols). Note that the entire set of images
        is always aligned, even if --grid only displays a subset of them.
        %(default)s"""))
    parser.add_argument(
        "--stop",
        type=float,
        default=0.005,
        help="halt when objective changes less than this (%(default)s)")
    framespec = parser.add_mutually_exclusive_group()  #äø€ę¬”č¾“å‡ŗå¤šč”Œę³Ø释
    parser.set_defaults(frame=frame)
    framespec.add_argument("--inset",
                           type=int,
                           dest='frame',
                           help=dedent("""\
        inset images by this many pixels to avoid going out
        of bounds during alignment (%(default)s)"""))
    framespec.add_argument("--crop",
                           type=int,
                           nargs=2,
                           dest='frame',
                           help=dedent("""\
        crop the image to a specified size, centered. (height, width)
        (%(default)s)"""))
    framespec.add_argument("--bounds",
                           type=int,
                           nargs=4,
                           dest='frame',
                           help=dedent("""\
        crop the image to specified min and max points (vmin hmin vmax hmax)
        (%(default)s)"""))
    parser.add_argument("--noise",
                        type=float,
                        default=0,
                        help="percentage noise to add to images (%(default)s)")
    if path:
        parser.add_argument("--path",
                            default=path,
                            help="path to directory of images (%(default)s)")
    else:
        parser.add_argument("path",
                            help="path to directory of images (%(default)s)")

    return parser
Example #33
0
def _add_run_options(parser: argparse.ArgumentParser) -> None:
    parser.add_argument('hook', nargs='?', help='A single hook-id to run')
    parser.add_argument('--verbose', '-v', action='store_true', default=False)
    mutex_group = parser.add_mutually_exclusive_group(required=False)
    mutex_group.add_argument(
        '--all-files',
        '-a',
        action='store_true',
        default=False,
        help='Run on all the files in the repo.',
    )
    mutex_group.add_argument(
        '--files',
        nargs='*',
        default=[],
        help='Specific filenames to run hooks on.',
    )
    parser.add_argument(
        '--show-diff-on-failure',
        action='store_true',
        help='When hooks fail, run `git diff` directly afterward.',
    )
    parser.add_argument(
        '--hook-stage',
        choices=C.STAGES,
        default='commit',
        help='The stage during which the hook is fired.  One of %(choices)s',
    )
    parser.add_argument(
        '--from-ref',
        '--source',
        '-s',
        help=(
            '(for usage with `--from-ref`) -- this option represents the '
            'original ref in a `from_ref...to_ref` diff expression.  '
            'For `pre-push` hooks, this represents the branch you are pushing '
            'to.  '
            'For `post-checkout` hooks, this represents the branch that was '
            'previously checked out.'),
    )
    parser.add_argument(
        '--to-ref',
        '--origin',
        '-o',
        help=(
            '(for usage with `--to-ref`) -- this option represents the '
            'destination ref in a `from_ref...to_ref` diff expression.  '
            'For `pre-push` hooks, this represents the branch being pushed.  '
            'For `post-checkout` hooks, this represents the branch that is '
            'now checked out.'),
    )
    parser.add_argument(
        '--commit-msg-filename',
        help='Filename to check when running during `commit-msg`',
    )
    parser.add_argument(
        '--remote-name',
        help='Remote name used by `git push`.',
    )
    parser.add_argument('--remote-url', help='Remote url used by `git push`.')
    parser.add_argument(
        '--checkout-type',
        help=('Indicates whether the checkout was a branch checkout '
              '(changing branches, flag=1) or a file checkout (retrieving a '
              'file from the index, flag=0).'),
    )
Example #34
0
def create_parser():
    parser = ArgumentParser()

    parser.add_argument("path", help="Directory containing the dataset.")

    parser.add_argument(
        "--layer_name",
        "-l",
        help="Name of the cubed layer (color or segmentation)",
        default="color",
    )

    parser.add_argument(
        "--from_mag",
        "--from",
        "-f",
        help="Resolution to base downsampling on",
        type=str,
        default="1",
    )

    # Either provide the maximum resolution to be downsampled OR a specific, anisotropic magnification.
    group = parser.add_mutually_exclusive_group()
    group.add_argument(
        "--max",
        "-m",
        help="Max resolution to be downsampled. In case of anisotropic downsampling, the process is considered "
        "done when max(current_mag) >= max(max_mag) where max takes the largest dimension of the mag tuple "
        "x, y, z. For example, a maximum mag value of 8 (or 8-8-8) will stop the downsampling as soon as a "
        "magnification is produced for which one dimension is equal or larger than 8.",
        type=int,
        default=512,
    )

    group.add_argument(
        "--anisotropic_target_mag",
        help="Specify an explicit anisotropic target magnification (e.g., --anisotropic_target_mag 16-16-4)."
        "All magnifications until this target magnification will be created. Consider using --anisotropic "
        "instead which automatically creates multiple anisotropic magnifications depending "
        "on the dataset's scale",
        type=str,
    )

    parser.add_argument(
        "--buffer_cube_size",
        "-b",
        help="Size of buffered cube to be downsampled (i.e. buffer cube edge length)",
        type=int,
        default=None,
    )

    parser.add_argument(
        "--no_compress",
        help="Don't compress data during downsampling",
        default=False,
        action="store_true",
    )

    add_interpolation_flag(parser)
    add_verbose_flag(parser)
    add_isotropic_flag(parser)
    add_distribution_flags(parser)

    return parser
#!/usr/bin/python3

from termcolor import colored
from argparse import ArgumentParser

from lib.Engine import XSST
from lib.Globals import Color
from lib.Functions import starter, exit_handler

parser = ArgumentParser(
    description=colored("XSS Terminal", color='yellow'),
    epilog=colored(
        '<script>window.location="https://bit.ly/3n60FQ4";</script>',
        color='yellow'))
string_group = parser.add_mutually_exclusive_group()
parser.add_argument('-u', '--base-url', type=str, help="Base URL")
parser.add_argument('-p', '--payload', type=str, help="Starting payload")
string_group.add_argument('-e',
                          '--error-string',
                          type=str,
                          help="Error string")
string_group.add_argument('-s',
                          '--match-string',
                          type=str,
                          help="Match string")
#string_group.add_argument('-b', '--blind-string', type=str, help="Blind error string")
parser.add_argument('-m',
                    '--method',
                    type=str,
                    choices=['GET', 'POST'],
                    help="HTTP Method")
Example #36
0
def main():
    parser = ArgumentParser(epilog=__doc__,
                            formatter_class=RawDescriptionHelpFormatter)
    task = parser.add_mutually_exclusive_group()
    task.add_argument('--dry-run',
                      action='store_true',
                      help='Print which notebooks would have been stripped')
    task.add_argument('--install',
                      action='store_true',
                      help='Install nbstripout in the current repository (set '
                      'up the git filter and attributes)')
    task.add_argument('--uninstall',
                      action='store_true',
                      help='Uninstall nbstripout from the current repository '
                      '(remove the git filter and attributes)')
    task.add_argument(
        '--is-installed',
        action='store_true',
        help='Check if nbstripout is installed in current repository')
    task.add_argument(
        '--status',
        action='store_true',
        help='Print status of nbstripout installation in current '
        'repository and configuration summary if installed')
    parser.add_argument('--keep-count',
                        action='store_true',
                        help='Do not strip the execution count/prompt number')
    parser.add_argument('--keep-output',
                        action='store_true',
                        help='Do not strip output',
                        default=None)
    parser.add_argument(
        '--extra-keys',
        default='',
        help=
        'Extra keys to strip from metadata, e.g. metadata.foo cell.metadata.bar'
    )
    parser.add_argument('--attributes',
                        metavar='FILEPATH',
                        help='Attributes file to add the filter to (in '
                        'combination with --install/--uninstall), '
                        'defaults to .git/info/attributes')
    parser.add_argument('--global',
                        dest='_global',
                        action='store_true',
                        help='Use global git config (default is local config)')
    task.add_argument('--version', action='store_true', help='Print version')
    parser.add_argument(
        '--force',
        '-f',
        action='store_true',
        help='Strip output also from files with non ipynb extension')

    parser.add_argument('--textconv',
                        '-t',
                        action='store_true',
                        help='Prints stripped files to STDOUT')

    parser.add_argument('files', nargs='*', help='Files to strip output from')
    args = parser.parse_args()

    git_config = ['git', 'config'] + (['--global'] if args._global else [])
    if args.install:
        sys.exit(
            install(git_config, user=args._global, attrfile=args.attributes))
    if args.uninstall:
        sys.exit(
            uninstall(git_config, user=args._global, attrfile=args.attributes))
    if args.is_installed:
        sys.exit(status(git_config, user=args._global, verbose=False))
    if args.status:
        sys.exit(status(git_config, user=args._global, verbose=True))
    if args.version:
        print(__version__)
        sys.exit(0)

    try:
        extra_keys = check_output(git_config +
                                  ['filter.nbstripout.extrakeys']).strip()
        if args.extra_keys:
            extra_keys = ' '.join((extra_keys, args.extra_keys))
    except (CalledProcessError, FileNotFoundError):
        extra_keys = args.extra_keys

    input_stream = None
    if sys.version_info < (3, 0):
        import codecs
        # Use UTF8 reader/writer for stdin/stdout
        # http://stackoverflow.com/a/1169209
        if sys.stdin:
            input_stream = codecs.getreader('utf8')(sys.stdin)
        output_stream = codecs.getwriter('utf8')(sys.stdout)
    else:
        # Wrap input/output stream in UTF-8 encoded text wrapper
        # https://stackoverflow.com/a/16549381
        if sys.stdin:
            input_stream = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
        output_stream = io.TextIOWrapper(sys.stdout.buffer,
                                         encoding='utf-8',
                                         newline='')

    for filename in args.files:
        if not (args.force or filename.endswith('.ipynb')):
            continue
        try:
            with io.open(filename, 'r', encoding='utf8') as f:
                with warnings.catch_warnings():
                    warnings.simplefilter("ignore", category=UserWarning)
                    nb = read(f, as_version=NO_CONVERT)
            nb = strip_output(nb, args.keep_output, args.keep_count,
                              extra_keys)
            if args.dry_run:
                output_stream.write(
                    'Dry run: would have stripped {}\n'.format(filename))
                continue
            if args.textconv:
                with warnings.catch_warnings():
                    warnings.simplefilter("ignore", category=UserWarning)
                    write(nb, output_stream)
                output_stream.flush()
            else:
                with io.open(filename, 'w', encoding='utf8', newline='') as f:
                    with warnings.catch_warnings():
                        warnings.simplefilter("ignore", category=UserWarning)
                        write(nb, f)
        except NotJSONError:
            print("'{}' is not a valid notebook".format(filename),
                  file=sys.stderr)
            sys.exit(1)
        except FileNotFoundError:
            print("Could not strip '{}': file not found".format(filename),
                  file=sys.stderr)
            sys.exit(1)
        except Exception:
            # Ignore exceptions for non-notebook files.
            print("Could not strip '{}'".format(filename), file=sys.stderr)
            raise

    if not args.files and input_stream:
        try:
            with warnings.catch_warnings():
                warnings.simplefilter("ignore", category=UserWarning)
                nb = read(input_stream, as_version=NO_CONVERT)
            nb = strip_output(nb, args.keep_output, args.keep_count,
                              extra_keys)
            if args.dry_run:
                output_stream.write('Dry run: would have stripped input from '
                                    'stdin\n')
            else:
                with warnings.catch_warnings():
                    warnings.simplefilter("ignore", category=UserWarning)
                    write(nb, output_stream)
                output_stream.flush()
        except NotJSONError:
            print('No valid notebook detected', file=sys.stderr)
            sys.exit(1)
Example #37
0
    def _make_argparser(self):
        '''Return a an ArgumentParser set up for our command line options.'''
        from argparse import (ArgumentParser, ArgumentDefaultsHelpFormatter,
                              SUPPRESS)
        description = 'plot a heatmap from coordinate data'
        parser = ArgumentParser(description=description,
                                formatter_class=ArgumentDefaultsHelpFormatter)

        inputs = parser.add_mutually_exclusive_group()
        inputs.add_argument('-p', '--points', help=SUPPRESS)
        inputs.add_argument('--csv', metavar='FILE', help=SUPPRESS)
        parser.add_argument('--shp_file', help=SUPPRESS)
        inputs.add_argument('-g', '--gpx', help=SUPPRESS)
        parser.add_argument(
            '--filetype',
            choices=list(self._filetypes.keys()),
            default='auto',
            help=('Treat all input files as this type. ("auto" will guess '
                  'based on the filename extension.); default: %(default)s'))
        parser.add_argument('--ignore_csv_header',
                            action='store_true',
                            help='ignore first line of CSV input files')
        parser.add_argument('-s',
                            '--scale',
                            type=float,
                            help='meters per pixel, approximate'),
        parser.add_argument('-W',
                            '--width',
                            type=int,
                            help='width of output image'),
        parser.add_argument('-H',
                            '--height',
                            type=int,
                            help='height of output image'),
        parser.add_argument('-P',
                            '--projection',
                            metavar='NAME',
                            choices=list(self._projections.keys()),
                            default='mercator',
                            help='default: %(default)s')
        parser.add_argument(
            '-e',
            '--extent',
            metavar='RANGE',
            help=('Clip results to RANGE, which is specified as '
                  'lat1,lon1,lat2,lon2;'
                  ' (for square mercator: -85.0511,-180,85.0511,180)'))
        parser.add_argument(
            '-R',
            '--margin',
            type=int,
            default=0,
            help=('Try to keep data at least this many pixels away from image '
                  'border.'))
        parser.add_argument(
            '-r',
            '--radius',
            type=int,
            default=5,
            help='pixel radius of point blobs; default: %(default)s')
        parser.add_argument(
            '-d',
            '--decay',
            type=float,
            default=0.95,
            help=('float in [0,1]; Larger values give more weight to data '
                  'magnitude.  Smaller values are more democratic.  default:'
                  '%(default)s'))
        parser.add_argument('-S',
                            '--save',
                            metavar='FILE',
                            help='save processed data to FILE')
        parser.add_argument('-L',
                            '--load',
                            metavar='FILE',
                            help='load processed data from FILE')
        parser.add_argument('-o',
                            '--output',
                            metavar='FILE',
                            help='name of output file (image or video)')
        parser.add_argument('-a',
                            '--animate',
                            action='store_true',
                            help='Make an animation instead of a static image')
        parser.add_argument(
            '--frequency',
            type=int,
            default=1,
            help='input points per animation frame; default: %(default)s')
        parser.add_argument(
            '--straggler_threshold',
            type=int,
            default=1,
            help='add one more animation frame if >= this many inputs remain')
        parser.add_argument(
            '-F',
            '--ffmpegopts',
            metavar='STR',
            help='extra options to pass to ffmpeg when making an animation')
        parser.add_argument(
            '-K',
            '--keepframes',
            action='store_true',
            help='keep intermediate images after creating an animation')
        parser.add_argument(
            '-b',
            '--background',
            metavar='COLOR',
            help='composite onto this background (color name or #rrggbb)')
        parser.add_argument('-I',
                            '--background_image',
                            metavar='FILE',
                            help='composite onto this image')
        parser.add_argument(
            '-B',
            '--background_brightness',
            type=float,
            help='Multiply each pixel in background image by this.')
        parser.add_argument(
            '-m',
            '--hsva_min',
            metavar='HEX',
            default=ColorMap.DEFAULT_HSVA_MIN_STR,
            help='hhhssvvaa hex for minimum data values; default: %(default)s')
        parser.add_argument(
            '-M',
            '--hsva_max',
            metavar='HEX',
            default=ColorMap.DEFAULT_HSVA_MAX_STR,
            help='hhhssvvaa hex for maximum data values; default: %(default)s')
        parser.add_argument(
            '-G',
            '--gradient',
            metavar='FILE',
            help=(
                'Take color gradient from this the first column of pixels in '
                'this image.  Overrides -m and -M.'))
        parser.add_argument(
            '-k',
            '--kernel',
            default='linear',
            choices=list(self._kernels.keys()),
            help=('Kernel to use for the falling-off function; '
                  'default: %(default)s'))
        parser.add_argument('--osm',
                            action='store_true',
                            help='Composite onto OpenStreetMap tiles')
        parser.add_argument('--osm_base',
                            metavar='URL',
                            default='http://tile.openstreetmap.org',
                            help='Base URL for map tiles; default %(default)s')
        parser.add_argument(
            '-z',
            '--zoom',
            type=int,
            help='Zoom level for OSM; 0 (the default) means autozoom')
        parser.add_argument('-v', '--verbose', action='store_true')
        parser.add_argument('--debug', action='store_true')
        parser.add_argument('--version',
                            action='version',
                            version='%(prog)s ' + str(__version__))
        parser.add_argument('files',
                            nargs='*',
                            help='input files',
                            metavar='FILE')
        return parser
Example #38
0
def argparser():
    '''Construct the command-line argument parser.'''
    parser = ArgumentParser(description='Generate one or more random names.')
    parser.add_argument('--version',
                        action='version',
                        version='%(prog)s {}'.format(__version__))
    parser.add_argument('-v',
                        '--verbose',
                        action='count',
                        default=0,
                        help=('show detailed information (may be specified '
                              'twice for extra detail)'))

    action = parser.add_mutually_exclusive_group()
    action.add_argument('-G',
                        '--generate',
                        action='store_const',
                        const='generate',
                        dest='action',
                        help='generate a name (the default action)')
    action.add_argument('-V',
                        '--validate',
                        action='store_const',
                        const='validate',
                        dest='action',
                        help=('rebuild and validate the database (instead of '
                              'generating a name)'))
    parser.add_argument('--skip-rebuild',
                        action='store_true',
                        help=("don't rebuild the database when performing "
                              "validation"))

    gen_args = parser.add_argument_group('Generation options')
    gen_args.add_argument('-o',
                          '--outfile',
                          help=('write output to the named '
                                'file (instead of standard '
                                'output)'))
    gen_args.add_argument('--overwrite',
                          action='store_true',
                          help=('overwrite the output file, instead of '
                                'appending to it (the default behaviour)'))
    gen_args.add_argument('-c',
                          '--count',
                          type=int,
                          default=1,
                          help=('the number of names to generate (defaults '
                                'to 1)'))
    gen_args.add_argument('-n',
                          '--nat',
                          help=('the nationality of the '
                                'name(s) to be generated; '
                                'either a full name, such as '
                                '"Russian", or an ISO 639 two- '
                                'or three-letter code, such as '
                                '"ru"'))
    gen_args.add_argument('-g',
                          '--gender',
                          choices=[MASCULINE, FEMININE],
                          help='the gender of the name(s) generated')

    return parser
Example #39
0
from __future__ import print_function, division
from pyasn import mrtx, __version__
from time import time
from sys import argv, exit, stdout
from glob import glob
from datetime import datetime, timedelta
from subprocess import call
from argparse import ArgumentParser

# Parse command line options
parser = ArgumentParser(
    description="Script to convert MRT/RIB archives to IPASN databases.",
    epilog="MRT/RIB archives can be downloaded using "
    "'pyasn_util_download.py', or directly from RouteViews (or RIPE RIS).")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--single",
                   nargs=2,
                   metavar=("RIBFILE", "IPASN.DAT"),
                   action="store",
                   help="convert single file (use bz2 or gz suffix)")
group.add_argument("--dump-screen",
                   nargs=1,
                   metavar="RIBFILE",
                   action="store",
                   help="parse and dump archive to screen")
group.add_argument("--bulk",
                   nargs=2,
                   metavar=("START-DATE", "END-DATE"),
                   action="store",
                   help="bulk conversion (dates are Y-M-D, files need to be "
Example #40
0
                     dest='interface_exit',
                     type=FileType('w'),
                     help='Extract interface info and exit')
 parser.add_argument(
     '--potaroo',
     dest='potaroo',
     action='store_true',
     help=
     'Include AS identifiers and names from http://bgp.potaroo.net/cidr/autnums.html'
 )
 parser.add_argument(
     '--trace-exit',
     dest='trace_exit',
     type=FileType('w'),
     help='Extract adjacencies and addresses from the traceroutes and exit')
 providers_group = parser.add_mutually_exclusive_group()
 providers_group.add_argument('-r',
                              '--rel-graph',
                              dest='rel_graph',
                              help='CAIDA relationship graph')
 providers_group.add_argument('-p',
                              '--asn-providers',
                              dest='asn_providers',
                              help='List of ISP ASes')
 providers_group.add_argument('-q',
                              '--org-providers',
                              dest='org_providers',
                              help='List of ISP ORGs')
 parser.add_argument('--bgp-compression',
                     dest='bgp_compression',
                     choices=['infer', 'gzip', 'bzip2'],
Example #41
0
def parse_options():

    description = "This example script performs discovery of HANA database tenants."

    usage = "%(prog)s [options] -d <remote host>"

    parser = ArgumentParser(usage=usage,
                            description=description,
                            epilog=pysap.epilog)

    target = parser.add_argument_group("Target")
    target.add_argument("-d",
                        "--remote-host",
                        dest="remote_host",
                        help="Remote host")
    target.add_argument("-p",
                        "--remote-port",
                        dest="remote_port",
                        type=int,
                        default=39013,
                        help="Remote port [%(default)d]")
    target.add_argument(
        "--route-string",
        dest="route_string",
        help="Route string for connecting through a SAP Router")

    tls = parser.add_argument_group("TLS")
    tls.add_argument("--tls", dest="tls", action="store_true", help="Use TLS")
    tls.add_argument("--tls-no-trust-cert",
                     dest="tls_cert_trust",
                     action="store_false",
                     help="Do not trust the TLS certificate and validate it")
    tls.add_argument(
        "--tls-cert-file",
        dest="tls_cert_file",
        help=
        "Path to the certificate file to use when validating server's TLS certificate."
    )
    tls.add_argument(
        "--tls-check-hostname",
        dest="tls_check_hostname",
        action="store_true",
        help="Validate the hostname provided in the TLS certificate")

    discovery = parser.add_mutually_exclusive_group()
    discovery.add_argument(
        "-t",
        "--tenants",
        dest="tenants",
        default="SYSTEMDB",
        help="List of comma separated tenants to try [%(default)s]")
    discovery.add_argument("--dictionary",
                           dest="dictionary",
                           metavar="FILE",
                           help="File to read the list of tenants to try")

    output = parser.add_argument_group("Output")
    output.add_argument(
        "-o",
        "--output",
        dest="output",
        default="-",
        help="File to write the results in JSON format [stdout]")

    misc = parser.add_argument_group("Misc options")
    misc.add_argument("-v",
                      "--verbose",
                      dest="verbose",
                      action="store_true",
                      help="Verbose output")

    options = parser.parse_args()

    if not options.remote_host:
        parser.error("Remote host is required")

    return options
Example #42
0
def parse_arguments(argv=None):
  """
  Return `namespace` with parsed arguments and options.

  """
  description = (
    "Capture *audio* and *video* from the desktop and stream it to the "
      "local network using `avconv` and `vlc`."
  )
  usage = (
    "\n  stream_desktop [-n|--gui] [-a|-A] [capture options] [stream options]\n"
      "  stream_desktop --version\n"
      "  stream_desktop --help"
  )
  ap = ArgumentParser(
    usage=usage,
    description=description,
    version=__version__,
    argument_default=SUPPRESS
  )
  ap_x_modes = ap.add_mutually_exclusive_group()
  ap_x_modes.add_argument(
    '-n', '--noop', action='store_true', dest='show_commands',
    help="do nothing - only print the commands"
  )
  ap_x_modes.add_argument(
    '--gui', action='store_true',
    help="show GUI"
  )
  # SETTINGS
  ag_set = ap.add_argument_group(
    "Settings",
    "Options to load and save settings. "
      "Which file is used to store them can be set with `--cgf-file`. "
      "The default is: `{}`.".format(DesktopStreamer.CFG_FILE)
  )
  ag_set.add_argument(
    '--save', action='store_true',
    help="save settings"
  )
  ag_set.add_argument(
    '--load', action='store_true',
    help="load settings"
  )
  ag_set.add_argument(
    '--cfg-file', metavar='FILENAME',
    help="full path to the config file"
  )
  # CAPTURE
  ag_cap = ap.add_argument_group(
    "Capture",
    "These options govern how the stream is being captured."
  )
  ag_x_audio = ag_cap.add_mutually_exclusive_group()
  ag_x_audio.add_argument(
    '-a', '--audio-only', action='store_false', dest='video',
    help="only capture audio (no video)"
  )
  ag_x_audio.add_argument(
    '-A', '--no-audio', action='store_false', dest='audio',
    help="don't capture audio (just video)"
  )
  ag_cap.add_argument(
    '-f', '--framerate', type=int, metavar='INT',
    help="framerate for the stream [25]"
  )
  ag_cap.add_argument(
    '-r', '--res-in', metavar='INTxINT',
    help="size of the capture area [full screen]"
  )
  ag_cap.add_argument(
    '-R', '--res-out', metavar='INTxINT',
    help="transcode to this output resolution [same as res-in]"
  )
  # STREAM
  ag_strm = ap.add_argument_group(
    "Stream",
    "These options govern how the stream is sent to the network."
  )
  ag_strm.add_argument(
    '-p', '--port', type=int,
    help="serve the stream on this port [1312]"
  )
  # return args
  return ap.parse_args()
Example #43
0
def get_args():
    parser = ArgumentParser(description="CLI Kudu API Frontend")
    parser.add_argument("-a",
                        "--app",
                        metavar=("NAME"),
                        help="azure app service name")
    parser.add_argument(
        "-C",
        "--config",
        type=chkpath,
        metavar=("PATH"),
        default=f"{os.path.expanduser('~')}/.azure.ini",
        help="path to azure configuration file",
    )
    parser.add_argument("-r",
                        "--rg",
                        metavar=("NAME"),
                        help="azure resource group")
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument(
        "-c",
        "--cmd",
        metavar=("COMMAND"),
        help="command to run (use quotes for multi-word commands)",
    )
    group.add_argument("-e",
                       "--endpoint",
                       metavar=("SLUG"),
                       help="api endpoint slug")
    group.add_argument("-l",
                       "--logs",
                       const=50,
                       type=int,
                       nargs="?",
                       help="get logs lines")
    group.add_argument(
        "-z",
        "--deploy_zip",
        metavar=("PATH"),
        type=chkpath,
        help="upload a zip to the server",
    )
    group.add_argument(
        "-Z",
        "--download_zip",
        default=["site/wwwroot", f"{os.path.expanduser('~')}/backup.zip"],
        nargs=2,
        metavar=("SOURCE", "DESTINATION"),
        help="download a zip of a remote path",
    )
    parser.add_argument(
        "-p",
        "--cwd",
        default="site/wwwroot",
        metavar=("PATH"),
        help="server current working directory",
    )
    parser.add_argument("-v",
                        action="count",
                        default=0,
                        help="increase verbosity")
    return parser.parse_args()
Example #44
0
def main():
    """Entry point"""
    # Parse Options
    parser = ArgumentParser()

    targetnames = TARGET_NAMES
    targetnames.sort()
    toolchainlist = list(EXPORTERS.keys())
    toolchainlist.sort()

    parser.add_argument("-m", "--mcu",
                        metavar="MCU",
                        help="generate project for the given MCU ({})".format(
                            ', '.join(targetnames)))

    parser.add_argument("-i",
                        dest="ide",
                        type=argparse_force_lowercase_type(
                            toolchainlist, "toolchain"),
                        help="The target IDE: %s"% str(toolchainlist))

    parser.add_argument("-c", "--clean",
                        action="store_true",
                        default=False,
                        help="clean the export directory")

    group = parser.add_mutually_exclusive_group(required=False)
    group.add_argument(
        "-p",
        type=test_known,
        dest="program",
        help="The index of the desired test program: [0-%s]"% (len(TESTS)-1))

    group.add_argument("-n",
                       type=test_name_known,
                       dest="program",
                       help="The name of the desired test program")

    parser.add_argument("-b",
                      dest="build",
                      default=False,
                      action="store_true",
                      help="use the mbed library build, instead of the sources")

    group.add_argument("-L", "--list-tests",
                       action="store_true",
                       dest="list_tests",
                       default=False,
                       help="list available programs in order and exit")

    group.add_argument("-S", "--list-matrix",
                       dest="supported_ides",
                       default=False,
                       const="matrix",
                       choices=["matrix", "ides"],
                       nargs="?",
                       help="displays supported matrix of MCUs and IDEs")

    parser.add_argument("-E",
                        action="store_true",
                        dest="supported_ides_html",
                        default=False,
                        help="writes tools/export/README.md")

    parser.add_argument("--build",
                        type=argparse_filestring_type,
                        dest="build_dir",
                        default=None,
                        help="Directory for the exported project files")

    parser.add_argument("--source",
                        action="append",
                        type=argparse_filestring_type,
                        dest="source_dir",
                        default=[],
                        help="The source (input) directory")

    parser.add_argument("-D",
                        action="append",
                        dest="macros",
                        help="Add a macro definition")

    parser.add_argument("--profile", dest="profile", action="append",
                        type=argparse_profile_filestring_type,
                        help="Build profile to use. Can be either path to json" \
                        "file or one of the default one ({})".format(", ".join(list_profiles())),
                        default=[])

    parser.add_argument("--update-packs",
                        dest="update_packs",
                        action="store_true",
                        default=False)
    parser.add_argument("--app-config",
                        dest="app_config",
                        default=None)

    parser.add_argument("--ignore", dest="ignore", type=argparse_many(str),
                        default=None, help="Comma separated list of patterns to add to mbedignore (eg. ./main.cpp)")

    options = parser.parse_args()

    # Print available tests in order and exit
    if options.list_tests is True:
        print('\n'.join([str(test) for test in  sorted(TEST_MAP.values())]))
        sys.exit()

    # Only prints matrix of supported IDEs
    if options.supported_ides:
        if options.supported_ides == "matrix":
            print_large_string(mcu_ide_matrix())
        elif options.supported_ides == "ides":
            print(mcu_ide_list())
        exit(0)

    # Only prints matrix of supported IDEs
    if options.supported_ides_html:
        html = mcu_ide_matrix(verbose_html=True)
        try:
            with open("./export/README.md", "w") as readme:
                readme.write("Exporter IDE/Platform Support\n")
                readme.write("-----------------------------------\n")
                readme.write("\n")
                readme.write(html)
        except IOError as exc:
            print("I/O error({0}): {1}".format(exc.errno, exc.strerror))
        except:
            print("Unexpected error:", sys.exc_info()[0])
            raise
        exit(0)

    if options.update_packs:
        from tools.arm_pack_manager import Cache
        cache = Cache(True, True)
        cache.cache_everything()

    # Target
    if not options.mcu:
        args_error(parser, "argument -m/--mcu is required")

    # Toolchain
    if not options.ide:
        args_error(parser, "argument -i is required")

    # Clean Export Directory
    if options.clean:
        if exists(EXPORT_DIR):
            rmtree(EXPORT_DIR)

    zip_proj = not bool(options.source_dir)

    notify = TerminalNotifier()

    if (options.program is None) and (not options.source_dir):
        args_error(parser, "one of -p, -n, or --source is required")
    exporter, toolchain_name = get_exporter_toolchain(options.ide)
    mcu = extract_mcus(parser, options)[0]
    if not exporter.is_target_supported(mcu):
        args_error(parser, "%s not supported by %s"%(mcu,options.ide))
    profile = extract_profile(parser, options, toolchain_name, fallback="debug")
    if options.clean:
        for cls in EXPORTERS.values():
            try:
                cls.clean(basename(abspath(options.source_dir[0])))
            except (NotImplementedError, IOError, OSError):
                pass
        for f in list(EXPORTERS.values())[0].CLEAN_FILES:
            try:
                remove(f)
            except (IOError, OSError):
                pass
    try:
        export(mcu, options.ide, build=options.build,
               src=options.source_dir, macros=options.macros,
               project_id=options.program, zip_proj=zip_proj,
               build_profile=profile, app_config=options.app_config,
               export_path=options.build_dir, notify=notify,
               ignore=options.ignore)
    except NotSupportedException as exc:
        print("[ERROR] %s" % str(exc))
Example #45
0
def parse_args():
    """Parse ncinet args off of argv"""
    version = "%(prog)s {}".format(__version__)

    arg_parser = ArgumentParser(prog="ncinet")
    arg_parser.add_argument('--version', action='version', version=version)

    # Evaluation mode
    mode_grp = arg_parser.add_mutually_exclusive_group(required=True)
    mode_grp.add_argument('--train',
                          action='store_const',
                          const='train',
                          dest='mode',
                          help="Train the model")
    mode_grp.add_argument('--eval',
                          action='store_const',
                          const='eval',
                          dest='mode',
                          help="Evaluate the latest checkpoint")
    mode_grp.add_argument('--xval',
                          action='store_const',
                          const='xval',
                          dest='mode',
                          help="Cross validate a parameter selection")
    mode_grp.add_argument('--serialize',
                          action='store_const',
                          const='serialize',
                          dest='mode',
                          help="Serialize a trained model and write to disk")

    mode_action = FlagAction('mode')
    mode_grp.add_argument('--predict',
                          action=mode_action,
                          nargs=2,
                          metavar=('MODEL_PATH', 'DATA_CONFIG'),
                          help="Predict new results from a trained model.")

    mode_grp.add_argument('--grid',
                          action=mode_action,
                          metavar='GRID_CONF',
                          help="Run grid search hyperparameter optimization")

    mode_grp.add_argument('--rand',
                          action=mode_action,
                          nargs=2,
                          metavar=('RAND_CONF', 'N_RUNS'),
                          help="Optimize parameters through random selection")

    # which model to train
    model_grp_w = arg_parser.add_argument_group(title="Model type options")
    model_grp = model_grp_w.add_mutually_exclusive_group()
    model_grp.add_argument('--ae',
                           action='store_const',
                           dest='model',
                           const='encoder',
                           help="Build autoencoder model")
    model_grp.add_argument(
        '--topo',
        action='store_const',
        dest='model',
        const='topo',
        help="Build inference model for topology prediction")
    model_grp.add_argument(
        '--sign',
        action='store_const',
        dest='model',
        const='sign',
        help="Build inference model for predicting the sign of stability")
    model_grp.add_argument(
        '--stable',
        action='store_const',
        dest='model',
        const='stable',
        help="Build a model to predict the `stable?` column.")
    model_grp.add_argument('--conf',
                           action=FlagAction('model'),
                           metavar='CONFIG',
                           help="Specify hyperparameters via a config file.")

    arg_parser.add_argument('--out_file',
                            action='store',
                            dest='output',
                            help="File to write optimization")

    # specify work directory
    arg_parser.add_argument('--work_dir',
                            action='store',
                            type=str,
                            help="Directory to write model outputs")

    arg_parser.add_argument('--basename',
                            action='store',
                            type=str,
                            help="Part of naming of work directory.")

    arg_parser.add_argument('--t_rest',
                            action='store',
                            type=int,
                            dest='topo_restrict',
                            default=None,
                            help="Train model on topology T",
                            metavar="TOPO")

    args = arg_parser.parse_args()
    return args
Example #46
0
def parse_args(parser: argparse.ArgumentParser):

    parser.add_argument("--annotation",
                        type=Path,
                        required=True,
                        help="ć‚¢ćƒŽćƒ†ćƒ¼ć‚·ćƒ§ćƒ³zipć€ć¾ćŸćÆzipć‚’å±•é–‹ć—ćŸćƒ‡ć‚£ćƒ¬ć‚Æ惈ćƒŖ")

    parser.add_argument(
        "-tq",
        "--task_query",
        type=str,
        help=
        "ć‚æć‚¹ć‚Æ悒ēµžć‚Šč¾¼ć‚€ćŸć‚ć®ć‚Æć‚ØćƒŖę”ä»¶ć‚’JSONå½¢å¼ć§ęŒ‡å®šć—ć¾ć™ć€‚ä½æē”Øć§ćć‚‹ć‚­ćƒ¼ćÆ task_id, status, phase, phase_stage 恧恙怂"
        "`file://`ć‚’å…ˆé ­ć«ä»˜ć‘ć‚‹ćØ态JSONå½¢å¼ć®ćƒ•ć‚”ć‚¤ćƒ«ć‚’ęŒ‡å®šć§ćć¾ć™ć€‚",
    )

    id_name_list_group = parser.add_mutually_exclusive_group()
    id_name_list_group.add_argument(
        "-t",
        "--task_id",
        type=str,
        nargs="+",
        help="ęŠ½å‡ŗ恙悋ć‚æć‚¹ć‚Æ恮task_idć‚’ęŒ‡å®šć—ć¦ćć ć•ć„ć€‚" +
        "`file://`ć‚’å…ˆé ­ć«ä»˜ć‘ć‚‹ćØ态task_id 恮äø€č¦§ćŒčØ˜č¼‰ć•ć‚ŒćŸćƒ•ć‚”ć‚¤ćƒ«ć‚’ęŒ‡å®šć§ćć¾ć™ć€‚",
    )

    id_name_list_group.add_argument(
        "--exclude_task_id",
        type=str,
        nargs="+",
        help="é™¤å¤–ć™ć‚‹ć‚æć‚¹ć‚Æ恮task_idć‚’ęŒ‡å®šć—ć¦ćć ć•ć„ć€‚" +
        "`file://`ć‚’å…ˆé ­ć«ä»˜ć‘ć‚‹ćØ态task_id 恮äø€č¦§ćŒčØ˜č¼‰ć•ć‚ŒćŸćƒ•ć‚”ć‚¤ćƒ«ć‚’ęŒ‡å®šć§ćć¾ć™ć€‚",
    )

    id_name_list_group.add_argument(
        "-i",
        "--input_data_id",
        type=str,
        nargs="+",
        help="ęŠ½å‡ŗć™ć‚‹å…„åŠ›ćƒ‡ćƒ¼ć‚æ恮input_data_idć‚’ęŒ‡å®šć—ć¦ćć ć•ć„ć€‚" +
        "`file://`ć‚’å…ˆé ­ć«ä»˜ć‘ć‚‹ćØ态input_data_id 恮äø€č¦§ćŒčØ˜č¼‰ć•ć‚ŒćŸćƒ•ć‚”ć‚¤ćƒ«ć‚’ęŒ‡å®šć§ćć¾ć™ć€‚",
    )
    id_name_list_group.add_argument(
        "--exclude_input_data_id",
        type=str,
        nargs="+",
        help="é™¤å¤–ć™ć‚‹å…„åŠ›ćƒ‡ćƒ¼ć‚æ恮input_data_idć‚’ęŒ‡å®šć—ć¦ćć ć•ć„ć€‚" +
        "`file://`ć‚’å…ˆé ­ć«ä»˜ć‘ć‚‹ćØ态input_data_id 恮äø€č¦§ćŒčØ˜č¼‰ć•ć‚ŒćŸćƒ•ć‚”ć‚¤ćƒ«ć‚’ęŒ‡å®šć§ćć¾ć™ć€‚",
    )

    id_name_list_group.add_argument(
        "--input_data_name",
        type=str,
        nargs="+",
        help="ęŠ½å‡ŗć™ć‚‹å…„åŠ›ćƒ‡ćƒ¼ć‚æ恮input_data_nameć‚’ęŒ‡å®šć—ć¦ćć ć•ć„ć€‚" +
        "`file://`ć‚’å…ˆé ­ć«ä»˜ć‘ć‚‹ćØ态input_data_name 恮äø€č¦§ćŒčØ˜č¼‰ć•ć‚ŒćŸćƒ•ć‚”ć‚¤ćƒ«ć‚’ęŒ‡å®šć§ćć¾ć™ć€‚",
    )
    id_name_list_group.add_argument(
        "--exclude_input_data_name",
        type=str,
        nargs="+",
        help="é™¤å¤–ć™ć‚‹å…„åŠ›ćƒ‡ćƒ¼ć‚æ恮input_data_nameć‚’ęŒ‡å®šć—ć¦ćć ć•ć„ć€‚" +
        "`file://`ć‚’å…ˆé ­ć«ä»˜ć‘ć‚‹ćØ态input_data_name 恮äø€č¦§ćŒčØ˜č¼‰ć•ć‚ŒćŸćƒ•ć‚”ć‚¤ćƒ«ć‚’ęŒ‡å®šć§ćć¾ć™ć€‚",
    )

    parser.add_argument("-o",
                        "--output_dir",
                        type=Path,
                        required=True,
                        help="å‡ŗåŠ›å…ˆćƒ‡ć‚£ćƒ¬ć‚Æ惈ćƒŖć®ćƒ‘ć‚¹")

    parser.set_defaults(subcommand_func=main)
Example #47
0
def main(args=None):
    parser = ArgumentParser()
    inputGroup = parser.add_argument_group(
        title='Input arguments',
        description='The following arguments are mutually exclusive.')
    xInputGroup = inputGroup.add_mutually_exclusive_group(required=True)
    xInputGroup.add_argument('-g',
                             '--glyphs-path',
                             metavar='GLYPHS',
                             help='Path to .glyphs source file')
    xInputGroup.add_argument('-u',
                             '--ufo-paths',
                             nargs='+',
                             metavar='UFO',
                             help='One or more paths to UFO files')
    xInputGroup.add_argument('-m',
                             '--mm-designspace',
                             metavar='DESIGNSPACE',
                             help='Path to .designspace file')

    outputGroup = parser.add_argument_group(title='Output arguments')
    outputGroup.add_argument(
        '-o',
        '--output',
        nargs='+',
        default=('otf', 'ttf'),
        metavar="FORMAT",
        help='Output font formats. Choose between: %(choices)s. '
        'Default: otf, ttf',
        choices=('ufo', 'otf', 'ttf', 'ttf-interpolatable', 'variable'))
    outputGroup.add_argument(
        '-i',
        '--interpolate',
        action='store_true',
        help='Interpolate masters (for Glyphs or MutatorMath sources only)')
    outputGroup.add_argument('-M',
                             '--masters-as-instances',
                             action='store_true',
                             help='Output masters as instances')
    outputGroup.add_argument(
        '--family-name',
        help='Family name to use for masters, and to filter output instances')

    contourGroup = parser.add_argument_group(title='Handling of contours')
    contourGroup.add_argument('--keep-overlaps',
                              dest='remove_overlaps',
                              action='store_false',
                              help='Do not remove any overlap.')
    contourGroup.add_argument(
        '--keep-direction',
        dest='reverse_direction',
        action='store_false',
        help='Do not reverse contour direction when output is ttf or '
        'ttf-interpolatable')
    contourGroup.add_argument(
        '-e',
        '--conversion-error',
        type=float,
        default=None,
        metavar='ERROR',
        help='Maximum approximation error for cubic to quadratic conversion '
        'measured in EM')
    contourGroup.add_argument(
        '-a',
        '--autohint',
        nargs='?',
        const='',
        help='Run ttfautohint. Can provide arguments, quoted')

    layoutGroup = parser.add_argument_group(
        title='Handling of OpenType Layout')
    layoutGroup.add_argument(
        '--interpolate-binary-layout',
        action='store_true',
        help='Interpolate layout tables from compiled master binaries. '
        'Requires Glyphs or MutatorMath source.')
    layoutGroup.add_argument(
        '--use-afdko',
        action='store_true',
        help='Use makeOTF instead of feaLib to compile FEA.')
    layoutGroup.add_argument(
        '--mti-source',
        help='Path to mtiLib .txt feature definitions (use instead of FEA)')
    layoutGroup.add_argument(
        '--kern-writer-module',
        metavar="MODULE",
        dest='kern_writer_class',
        type=PyClassType('KernFeatureWriter'),
        help='Module containing a custom `KernFeatureWriter` class.')
    layoutGroup.add_argument(
        '--mark-writer-module',
        metavar="MODULE",
        dest='mark_writer_class',
        type=PyClassType('MarkFeatureWriter'),
        help='Module containing a custom `MarkFeatureWriter` class.')

    glyphnamesGroup = parser.add_mutually_exclusive_group(required=False)
    glyphnamesGroup.add_argument(
        '--production-names',
        dest='use_production_names',
        action='store_true',
        help='Rename glyphs with production names if available otherwise use '
        'uninames.')
    glyphnamesGroup.add_argument('--no-production-names',
                                 dest='use_production_names',
                                 action='store_false')

    subsetGroup = parser.add_mutually_exclusive_group(required=False)
    subsetGroup.add_argument(
        '--subset',
        dest='subset',
        action='store_true',
        help='Subset font using export flags set by glyphsLib')
    subsetGroup.add_argument('--no-subset',
                             dest='subset',
                             action='store_false')

    subroutinizeGroup = parser.add_mutually_exclusive_group(required=False)
    subroutinizeGroup.add_argument(
        '-s',
        '--subroutinize',
        action='store_true',
        help='Optimize CFF table using compreffor (default)')
    subroutinizeGroup.add_argument('-S',
                                   '--no-subroutinize',
                                   dest='subroutinize',
                                   action='store_false')

    parser.set_defaults(use_production_names=None,
                        subset=None,
                        subroutinize=True)

    logGroup = parser.add_argument_group(title='Logging arguments')
    logGroup.add_argument('--timing',
                          action='store_true',
                          help="Print the elapsed time for each steps")
    logGroup.add_argument(
        '--verbose',
        default='INFO',
        metavar='LEVEL',
        choices=('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'),
        help='Configure the logger verbosity level. Choose between: '
        '%(choices)s. Default: INFO')
    args = vars(parser.parse_args(args))

    project = FontProject(timing=args.pop('timing'),
                          verbose=args.pop('verbose'))

    glyphs_path = args.pop('glyphs_path')
    ufo_paths = args.pop('ufo_paths')
    designspace_path = args.pop('mm_designspace')
    if glyphs_path:
        project.run_from_glyphs(glyphs_path, **args)
        return

    exclude_args(parser, args, ['family_name'], 'Glyphs')
    if designspace_path:
        project.run_from_designspace(designspace_path, **args)
        return

    exclude_args(parser, args, ['interpolate', 'interpolate_binary_layout'],
                 'Glyphs or MutatorMath')
    project.run_from_ufos(ufo_paths,
                          is_instance=args.pop('masters_as_instances'),
                          **args)
Example #48
0
def main(argv=sys.argv[1:]):
    if PY2:
        argv = [unicode(arg, sys.getfilesystemencoding())
                for arg in argv]  # noqa

    # Insert positional argument separator, if not already present
    if "--" not in argv:
        for i, argument in enumerate(argv):
            if not argument.startswith("-"):
                argv.insert(i, "--")
                break

    arg_parser = ArgumentParser(
        prog="maybe",
        usage="%(prog)s [options] command [argument ...]",
        description=
        "Run a command without the ability to make changes to your system " +
        "and list the changes it would have made.",
        epilog="For more information, to report issues or to contribute, " +
        "visit https://github.com/p-e-w/maybe.",
    )
    arg_parser.add_argument("command",
                            nargs="+",
                            help="the command to run under maybe's control")
    arg_group = arg_parser.add_mutually_exclusive_group()
    arg_group.add_argument(
        "-a",
        "--allow",
        nargs="+",
        metavar="OPERATION",
        help="allow the command to perform the specified operation(s). " +
        "all other operations will be denied. " +
        "possible values for %(metavar)s are: " +
        ", ".join(sorted(SYSCALL_FILTERS.keys())) +
        "; as well as any filter scopes defined by loaded plugins")
    arg_group.add_argument(
        "-d",
        "--deny",
        nargs="+",
        metavar="OPERATION",
        help="deny the command the specified operation(s). " +
        "all other operations will be allowed. " +
        "see --allow for a list of possible values for %(metavar)s. " +
        "--allow and --deny cannot be combined")
    arg_parser.add_argument(
        "-p",
        "--plugin",
        nargs="+",
        metavar="FILE",
        help="load the specified plugin script(s). " +
        "see the README for details and plugin API documentation")
    arg_parser.add_argument(
        "-l",
        "--list-only",
        action="store_true",
        help="list operations without header, indentation and rerun prompt")
    arg_parser.add_argument(
        "--style-output",
        choices=["yes", "no", "auto"],
        default="auto",
        help="colorize output using ANSI escape sequences (yes/no) " +
        "or automatically decide based on whether stdout is a terminal (auto, default)"
    )
    arg_parser.add_argument(
        "-v",
        "--verbose",
        action="count",
        help="if specified once, print every filtered syscall. " +
        "if specified twice, print every syscall, highlighting filtered syscalls"
    )
    arg_parser.add_argument("--version",
                            action="version",
                            version="%(prog)s 0.4.0")
    args = arg_parser.parse_args(argv)

    initialize_terminal(args.style_output)

    if args.plugin is not None:
        for plugin_path in args.plugin:
            try:
                module_name = splitext(basename(plugin_path))[0]
                # Note: imp.load_source is *long* deprecated and not even documented
                # in Python 3 anymore, but it still seems to work and the "alternatives"
                # (see http://stackoverflow.com/a/67692) are simply too insane to use
                load_source(module_name, plugin_path)
            except Exception as error:
                print(
                    T.red("Error loading %s: %s." %
                          (T.bold(plugin_path) + T.red, error)))
                return 1

    if args.allow is not None:
        for filter_scope in args.allow:
            if filter_scope not in SYSCALL_FILTERS:
                print(
                    T.red("Unknown operation in --allow: %s." %
                          (T.bold(filter_scope) + T.red)))
                return 1
        filter_scopes = set(SYSCALL_FILTERS.keys()) - set(args.allow)
    elif args.deny is not None:
        for filter_scope in args.deny:
            if filter_scope not in SYSCALL_FILTERS:
                print(
                    T.red("Unknown operation in --deny: %s." %
                          (T.bold(filter_scope) + T.red)))
                return 1
        filter_scopes = args.deny
    else:
        filter_scopes = SYSCALL_FILTERS.keys()

    syscall_filters = {}

    for filter_scope in SYSCALL_FILTERS:
        if filter_scope in filter_scopes:
            for syscall in SYSCALL_FILTERS[filter_scope]:
                syscall_filters[syscall] = SYSCALL_FILTERS[filter_scope][
                    syscall]

    # Suppress logging output from python-ptrace
    getLogger().addHandler(NullHandler())

    # Prevent python-ptrace from decoding arguments to keep raw numerical values
    DIRFD_ARGUMENTS.clear()
    SYSCALL_ARG_DICT.clear()
    ARGUMENT_CALLBACK.clear()

    # This is basically "shlex.join"
    command = " ".join([(("'%s'" % arg) if (" " in arg) else arg)
                        for arg in args.command])

    try:
        args.command[0] = locateProgram(args.command[0])
        pid = createChild(args.command, False)
    except Exception as error:
        print(
            T.red("Error executing %s: %s." %
                  (T.bold(command) + T.red, error)))
        return 1

    debugger = PtraceDebugger()
    debugger.traceFork()
    debugger.traceExec()

    process = debugger.addProcess(pid, True)
    process.syscall()

    try:
        operations = get_operations(debugger, syscall_filters, args.verbose)
    except Exception as error:
        print(T.red("Error tracing process: %s." % error))
        return 1
    except KeyboardInterrupt:
        print(
            T.yellow("%s terminated by keyboard interrupt." %
                     (T.bold(command) + T.yellow)))
        return 2
    finally:
        # Cut down all processes no matter what happens
        # to prevent them from doing any damage
        debugger.quit()

    if operations:
        if not args.list_only:
            print(
                "%s has prevented %s from performing %d file system operations:\n"
                % (T.bold("maybe"), T.bold(command), len(operations)))
        for operation in operations:
            print(("" if args.list_only else "  ") + operation)
        if not args.list_only:
            print(
                "\nDo you want to rerun %s and permit these operations? [y/N] "
                % T.bold(command),
                end="")
            try:
                choice = input()
            except KeyboardInterrupt:
                choice = ""
                # Ctrl+C does not print a newline automatically
                print("")
            if choice.lower() == "y":
                subprocess.call(args.command)
    else:
        print("%s has not detected any file system operations from %s." %
              (T.bold("maybe"), T.bold(command)))
def create_parser():
    parser = ArgumentParser(description=__doc__, add_help=True)
    parser.add_argument('files',
                        type=str,
                        default=None,
                        nargs='+',
                        help='One or more paths to PDF files.')

    parser.add_argument("--version",
                        "-v",
                        action="version",
                        version="pdfminer.six v{}".format(
                            pdfminer.__version__))
    parser.add_argument('--debug',
                        '-d',
                        default=False,
                        action='store_true',
                        help='Use debug logging level.')
    procedure_parser = parser.add_mutually_exclusive_group()
    procedure_parser.add_argument('--extract-toc',
                                  '-T',
                                  default=False,
                                  action='store_true',
                                  help='Extract structure of outline')
    procedure_parser.add_argument('--extract-embedded',
                                  '-E',
                                  type=str,
                                  help='Extract embedded files')

    parse_params = parser.add_argument_group(
        'Parser', description='Used during PDF parsing')
    parse_params.add_argument(
        '--page-numbers',
        type=int,
        default=None,
        nargs='+',
        help='A space-seperated list of page numbers to parse.')
    parse_params.add_argument(
        '--pagenos',
        '-p',
        type=str,
        help='A comma-separated list of page numbers to parse. Included for '
        'legacy applications, use --page-numbers for more idiomatic '
        'argument entry.')
    parse_params.add_argument(
        '--objects',
        '-i',
        type=str,
        help='Comma separated list of object numbers to extract')
    parse_params.add_argument(
        '--all',
        '-a',
        default=False,
        action='store_true',
        help='If the structure of all objects should be extracted')
    parse_params.add_argument(
        '--password',
        '-P',
        type=str,
        default='',
        help='The password to use for decrypting PDF file.')

    output_params = parser.add_argument_group(
        'Output', description='Used during output generation.')
    output_params.add_argument(
        '--outfile',
        '-o',
        type=str,
        default='-',
        help='Path to file where output is written. Or "-" (default) to '
        'write to stdout.')
    codec_parser = output_params.add_mutually_exclusive_group()
    codec_parser.add_argument('--raw-stream',
                              '-r',
                              default=False,
                              action='store_true',
                              help='Write stream objects without encoding')
    codec_parser.add_argument('--binary-stream',
                              '-b',
                              default=False,
                              action='store_true',
                              help='Write stream objects with binary encoding')
    codec_parser.add_argument('--text-stream',
                              '-t',
                              default=False,
                              action='store_true',
                              help='Write stream objects as plain text')

    return parser
Example #50
0
def add_arguments(config: dict, parser: argparse.ArgumentParser):
    logger.info('Adding arguments')
    parser.add_argument('-v', '--version',
        action='store_true',
        dest='version',
        help='Display the current version of awsume',
    )
    parser.add_argument('-o', '--output-profile',
        action='store',
        dest='output_profile',
        metavar='output_profile',
        help='A profile to output credentials to',
    )
    parser.add_argument('--clean',
        action='store_true',
        dest='clean',
        help='Clean expired output profiles',
    )
    parser.add_argument('profile_name',
        nargs='?',
        action='store',
        metavar='profile_name',
        help='The target profile name',
    )
    parser.add_argument('-r', '--refresh',
        action='store_true',
        dest='force_refresh',
        help='Force refresh credentials',
    )
    parser.add_argument('-s', '--show-commands',
        action='store_true',
        dest='show_commands',
        help='Show the commands to set the credentials',
    )
    parser.add_argument('-u', '--unset',
        action='store_true',
        dest='unset_variables',
        help='Unset your aws environment variables',
    )
    parser.add_argument('-a', '--auto-refresh',
        action='store_true',
        dest='auto_refresh',
        help='Auto refresh credentials',
    )
    parser.add_argument('-k', '--kill-refresher',
        action='store_true',
        default=False,
        dest='kill',
        help='Kill autoawsume',
    )
    parser.add_argument('-l', '--list-profiles',
        nargs='?',
        action='store',
        default=None,
        const='list',
        choices=['more', 'list', None],
        metavar='more',
        dest='list_profiles',
        help='List profiles, "more" for detail (slow)',
    )
    parser.add_argument('--refresh-autocomplete',
        action='store_true',
        dest='refresh_autocomplete',
        help='Refresh all plugin autocomplete profiles',
    )
    parser.add_argument('--role-arn',
        action='store',
        dest='role_arn',
        metavar='role_arn',
        help='Role ARN or <partition>:<account_id>:<role_name>',
    )
    parser.add_argument('--principal-arn',
        action='store',
        dest='principal_arn',
        metavar='principal_arn',
        help='Principal ARN or <partition>:<account_id>:<provider_name>',
    )
    parser.add_argument('--source-profile',
        action='store',
        dest='source_profile',
        metavar='source_profile',
        help='source_profile to use (role-arn only)',
    )
    parser.add_argument('--external-id',
        action='store',
        dest='external_id',
        metavar='external_id',
        help='External ID to pass to the assume_role',
    )
    parser.add_argument('--mfa-token',
        action='store',
        dest='mfa_token',
        metavar='mfa_token',
        help='Your mfa token',
    )
    parser.add_argument('--region',
        action='store',
        dest='region',
        metavar='region',
        help='The region you want to awsume into',
    )
    parser.add_argument('--session-name',
        action='store',
        dest='session_name',
        metavar='session_name',
        help='Set a custom role session name',
    )
    parser.add_argument('--role-duration',
        action='store',
        dest='role_duration',
        type=custom_duration_argument_type,
        metavar='role_duration',
        help='Seconds to get role creds for',
    )
    assume_role_method = parser.add_mutually_exclusive_group()
    assume_role_method.add_argument('--with-saml',
        action='store_true',
        dest='with_saml',
        help='Use saml (requires plugin)',
    )
    assume_role_method.add_argument('--with-web-identity',
        action='store_true',
        dest='with_web_identity',
        help='Use web identity (requires plugin)',
    )
    parser.add_argument('--json',
        action='store',
        dest='json',
        metavar='json',
        help='Use json credentials',
    )
    parser.add_argument('--credentials-file',
        action='store',
        dest='credentials_file',
        metavar='credentials_file',
        help='Target a shared credentials file',
    )
    parser.add_argument('--config-file',
        action='store',
        dest='config_file',
        metavar='config_file',
        help='Target a config file',
    )
    parser.add_argument('--config',
        nargs='*',
        dest='config',
        action='store',
        metavar='option',
        help='Configure awsume',
    )
    parser.add_argument('--list-plugins',
        action='store_true',
        dest='list_plugins',
        help='List installed plugins',
    )
    parser.add_argument('--info',
        action='store_true',
        dest='info',
        help='Print any info logs to stderr',
    )
    parser.add_argument('--debug',
        action='store_true',
        dest='debug',
        help='Print any debug logs to stderr',
    )
Example #51
0
def parse_args():
    parser = ArgumentParser()
    parser.add_argument('--noop', action='store_true',
                        help="don't actually run the cmds",
                        default=False)
    parser.add_argument('--secure-vars-file', required=False,
                        metavar="SECURE_VAR_FILE", default=None,
                        help="path to secure-vars from the root of "
                        "the secure repo. By default <deployment>.yml and "
                        "<environment>-<deployment>.yml will be used if they "
                        "exist in <secure-repo>/ansible/vars/. This secure file "
                        "will be used in addition to these if they exist.")
    parser.add_argument('--stack-name',
                        help="defaults to ENVIRONMENT-DEPLOYMENT",
                        metavar="STACK_NAME",
                        required=False)
    parser.add_argument('-p', '--play',
                        help='play name without the yml extension',
                        metavar="PLAY", required=True)
    parser.add_argument('--playbook-dir',
                        help='directory to find playbooks in',
                        default='configuration/playbooks/edx-east',
                        metavar="PLAYBOOKDIR", required=False)
    parser.add_argument('-d', '--deployment', metavar="DEPLOYMENT",
                        required=True)
    parser.add_argument('-e', '--environment', metavar="ENVIRONMENT",
                        required=True)
    parser.add_argument('-v', '--verbose', action='store_true',
                        help="turn on verbosity")
    parser.add_argument('--no-cleanup', action='store_true',
                        help="don't cleanup on failures")
    parser.add_argument('--vars', metavar="EXTRA_VAR_FILE",
                        help="path to extra var file", required=False)
    parser.add_argument('--configuration-version', required=False,
                        help="configuration repo gitref",
                        default="master")
    parser.add_argument('--configuration-secure-version', required=False,
                        help="configuration-secure repo gitref",
                        default="master")
    parser.add_argument('--configuration-secure-repo', required=False,
                        default="[email protected]:edx-ops/prod-secure",
                        help="repo to use for the secure files")
    parser.add_argument('--configuration-internal-version', required=False,
                        help="configuration-internal repo gitref",
                        default="master")
    parser.add_argument('--configuration-internal-repo', required=False,
                        default="",
                        help="repo to use for internal (non-secure) configuration data")
    parser.add_argument('--configuration-private-version', required=False,
                        help="configuration-private repo gitref",
                        default="master")
    parser.add_argument('--configuration-private-repo', required=False,
                        default="",
                        help="repo to use for private playbooks")
    parser.add_argument('-c', '--cache-id', required=True,
                        help="unique id to use as part of cache prefix")
    parser.add_argument('-i', '--identity', required=False,
                        help="path to identity file for pulling "
                             "down configuration-secure",
                        default=None)
    parser.add_argument('-r', '--region', required=False,
                        default="us-east-1",
                        help="aws region")
    parser.add_argument('-k', '--keypair', required=False,
                        default="deployment",
                        help="AWS keypair to use for instance")
    parser.add_argument('-t', '--instance-type', required=False,
                        default="m1.large",
                        help="instance type to launch")
    parser.add_argument("--role-name", required=False,
                        default="abbey",
                        help="IAM role name to use (must exist)")
    parser.add_argument("--msg-delay", required=False,
                        default=5,
                        help="How long to delay message display from sqs "
                             "to ensure ordering")
    parser.add_argument("--hipchat-room-id", required=False,
                        default=None,
                        help="The API ID of the Hipchat room to post"
                             "status messages to")
    parser.add_argument("--ansible-hipchat-room-id", required=False,
                        default='Hammer',
                        help="The room used by the abbey instance for "
                             "printing verbose ansible run data.")
    parser.add_argument("--hipchat-api-token", required=False,
                        default=None,
                        help="The API token for Hipchat integration")
    parser.add_argument("--callback-url", required=False,
                        default=None,
                        help="The callback URL to send notifications to")
    parser.add_argument("--root-vol-size", required=False,
                        default=50,
                        help="The size of the root volume to use for the "
                             "abbey instance.")
    parser.add_argument("--datadog-api-key", required=False,
                        default="",
                        help="The datadog api key used for capturing task"
                             "and playbook metrics abbey instance.")

    group = parser.add_mutually_exclusive_group()
    group.add_argument('-b', '--base-ami', required=False,
                       help="ami to use as a base ami",
                       default="ami-cd0f5cb6")
    group.add_argument('--blessed', action='store_true',
                       help="Look up blessed ami for env-dep-play.",
                       default=False)

    return parser.parse_args()
Example #52
0
    def setup_parser():
        parser = ArgumentParser()

        #Is stdin attached?
        requireTargetArg = True
        if not sys.stdin.isatty():
            requireTargetArg = False

        targets = parser.add_mutually_exclusive_group(
            required=requireTargetArg)

        targets.add_argument(
            '-t',
            dest='target',
            required=False,
            help='Specify a target or domain name either in comma format, '
            'CIDR notation, glob notation, or a single target.')

        targets.add_argument(
            '-tL',
            dest='target_list',
            required=False,
            help='Specify a list of targets or domain names.',
            metavar="FILE",
            type=lambda x: InputHelper.readable_file(parser, x))

        # exclusions group
        exclusions = parser.add_mutually_exclusive_group()

        exclusions.add_argument(
            '-e',
            dest='exclusions',
            required=False,
            help='Specify an exclusion either in comma format, '
            'CIDR notation, or a single target.')

        exclusions.add_argument(
            '-eL',
            dest='exclusions_list',
            required=False,
            help='Specify a list of exclusions.',
            metavar="FILE",
            type=lambda x: InputHelper.readable_file(parser, x))

        parser.add_argument(
            '-threads',
            dest='threads',
            required=False,
            help="Specify the maximum number of threads to run (DEFAULT:5)",
            default=5,
            type=lambda x: InputHelper.check_positive(parser, x))

        parser.add_argument(
            '-timeout',
            dest='timeout',
            required=False,
            help="Command timeout in seconds (DEFAULT:600)",
            default=600,
            type=lambda x: InputHelper.check_positive(parser, x))

        parser.add_argument(
            '-pL',
            dest='proxy_list',
            required=False,
            help='Specify a list of proxies.',
            metavar="FILE",
            type=lambda x: InputHelper.readable_file(parser, x))

        commands = parser.add_mutually_exclusive_group(required=True)
        commands.add_argument('-c',
                              dest='command',
                              help='Specify a single command to execute.')

        commands.add_argument(
            '-cL',
            dest='command_list',
            required=False,
            help='Specify a list of commands to execute',
            metavar="FILE",
            type=lambda x: InputHelper.readable_file(parser, x))

        parser.add_argument(
            '-o',
            dest='output',
            help=
            'Specify an output folder variable that can be used in commands as _output_'
        )

        parser.add_argument(
            '-p',
            dest='port',
            help=
            'Specify a port variable that can be used in commands as _port_')

        parser.add_argument(
            '--proto',
            dest='proto',
            help='Specify protocols that can be used in commands as _proto_')

        parser.add_argument(
            '-rp',
            dest='realport',
            help=
            'Specify a real port variable that can be used in commands as _realport_'
        )

        parser.add_argument(
            '-random',
            dest='random',
            help=
            'Specify a directory of files that can be randomly used in commands as _random_',
            type=lambda x: InputHelper.check_path(parser, x))

        parser.add_argument(
            '--no-cidr',
            dest='nocidr',
            action='store_true',
            default=False,
            help=
            'If set then CIDR notation in a target file will not be automatically '
            'be expanded into individual hosts.')

        parser.add_argument(
            '--no-color',
            dest='nocolor',
            action='store_true',
            default=False,
            help='If set then any foreground or background colours will be '
            'stripped out.')

        parser.add_argument(
            '--no-bar',
            '--sober',
            dest='sober',
            action='store_true',
            default=False,
            help='If set then progress bar will be stripped out')

        parser.add_argument('--repeat',
                            dest='repeat',
                            help='repeat the given command x number of times.')

        output_types = parser.add_mutually_exclusive_group()
        output_types.add_argument(
            '-v',
            '--verbose',
            dest='verbose',
            action='store_true',
            default=False,
            help='If set then verbose output will be displayed in the terminal.'
        )
        output_types.add_argument(
            '--silent',
            dest='silent',
            action='store_true',
            default=False,
            help='If set only findings will be displayed and banners '
            'and other information will be redacted.')

        return parser
Example #53
0
    add_help=False,
)
mode_parser.add_argument(
    '-m',
    '--mode',
    default=None,
    help=mode_help
)

# Options parser shared actions all pipeline run options
pipeline_run_options = ArgumentParser(
    description='Specify actions related to running pipelines',
    add_help=False
)

group = pipeline_run_options.add_mutually_exclusive_group(required=False)
group.add_argument(
    '-f',
    '--force',
    action='store_true',
    help='Destroy previous versions of this pipeline, if they exist'
)
group.add_argument(
    '-nf',
    '--no-force',
    action='store_false',
    help='Do not destroy previous versions of this pipeline, if they exist'
)
pipeline_run_options.set_defaults(force=True)

pipeline_run_options.add_argument(
Example #54
0
def main():
    # The main argument parser
    parser = ArgumentParser(
        description="CLI for accessing the FireCloud methods repository.")

    # Core application arguments
    parser.add_argument(
        '-u',
        '--url',
        dest='firecloudUrl',
        default='https://firecloud.dsde-prod.broadinstitute.org/service/api',
        action='store',
        help=
        'Firecloud API location. Default is https://firecloud.dsde-prod.broadinstitute.org/service/api'
    )
    parser.add_argument(
        '-k',
        '--insecure',
        dest='insecureSsl',
        default='False',
        action='store_true',
        help='use insecure ssl (allow self-signed certificates)')

    endpoint_group = parser.add_mutually_exclusive_group(required=True)
    endpoint_group.add_argument(
        '-c',
        '--configurations',
        action='store_true',
        help='Operate on task-configurations, via the /configurations endpoint'
    )
    endpoint_group.add_argument(
        '-m',
        '--methods',
        action='store_true',
        help='Operate on tasks and workflows, via the /methods endpoint')
    subparsers = parser.add_subparsers(
        help='FireCloud Methods Repository actions')

    # POST arguments
    push_parser = subparsers.add_parser(
        'push',
        description='Push a method to the FireCloud Methods Repository',
        help='Push a method to the FireCloud Methods Repository')
    push_parser.add_argument(
        '-s',
        '--namespace',
        dest='namespace',
        action='store',
        help=
        'The namespace for method addition. Default value is your user login name'
    )
    push_parser.add_argument(
        '-n',
        '--name',
        dest='name',
        action='store',
        help=
        'The method name to provide for method addition. Default is the name of the PAYLOAD_FILE.'
    )
    push_parser.add_argument(
        '-d',
        '--documentation',
        dest='docs',
        action='store',
        help=
        'A file containing user documentation. Must be <10kb. May be plain text. Marking languages such as HTML or Github markdown are also supported'
    )
    push_parser.add_argument(
        '-t',
        '--entityType',
        dest='entityType',
        action='store',
        help='The type of the entities you are trying to get',
        choices=['Task', 'Workflow', 'Configuration'],
        required=True)
    push_parser.add_argument(
        '-y',
        '--synopsis',
        dest='synopsis',
        action='store',
        help='The synopsis for the entity you are pushing')
    push_parser.add_argument(
        'PAYLOAD_FILE',
        help=
        'A file containing the payload. For configurations, JSON. For tasks + workflows, the method description in WDL'
    )
    push_parser.set_defaults(func=push)

    # GET (namespace/name/id) arguments
    pull_parser = subparsers.add_parser(
        'pull',
        description=
        'Get a specific method snapshot from the FireCloud Methods Repository',
        help=
        'Get a specific method snapshot from the FireCloud Methods Repository')
    pull_parser.add_argument(
        '-o',
        '--onlyPayload',
        dest='onlyPayload',
        action='store_true',
        help=
        'Get only the payload for the method of interest (ie the WDL or configuration JSON)'
    )
    pull_parser.add_argument(
        'NAMESPACE',
        action='store',
        help='The namespace for the entity you are trying to get')
    pull_parser.add_argument(
        'NAME',
        action='store',
        help='The name of the entity you are trying to get')
    pull_parser.add_argument(
        'SNAPSHOT_ID',
        type=int,
        action='store',
        help='The snapshot-id of the entity you are trying to get')
    pull_parser.set_defaults(func=pull)

    # GET (query-paremeters) arguments
    list_parser = subparsers.add_parser(
        'list',
        description=
        'List methods in the FireCloud Methods Repository based on metadata',
        help=
        'List methods in the FireCloud Methods Repository based on metadata')
    list_parser.add_argument(
        '-f',
        '--includedFields',
        dest='includedFields',
        nargs='*',
        action='store',
        help=
        'Any specific metadata fields you wish to be included in the response entities'
    )
    list_parser.add_argument(
        '-e',
        '--excludedFields',
        dest='excludedFields',
        nargs='*',
        action='store',
        help=
        'Any specific metadata fields you wish to be excluded from the response entities'
    )
    list_parser.add_argument(
        '-s',
        '--namespace',
        dest='namespace',
        action='store',
        help='The namespace for the entities you are trying to get')
    list_parser.add_argument(
        '-n',
        '--name',
        dest='name',
        action='store',
        help='The name of the entities you are trying to get')
    list_parser.add_argument(
        '-i',
        '--snapshotId',
        dest='snapshotId',
        type=int,
        action='store',
        help='The snapshot-id of the entities you are trying to get')
    list_parser.add_argument(
        '-y',
        '--synopsis',
        dest='synopsis',
        action='store',
        help='The exact synopsis of the entities you are trying to get')
    list_parser.add_argument(
        '-d',
        '--documentation',
        dest='docs',
        action='store',
        help='The exact documentation of the entities you are trying to get')
    list_parser.add_argument(
        '-o',
        '--owner',
        dest='owner',
        action='store',
        help='The owner of the entities you are trying to get')
    list_parser.add_argument(
        '-p',
        '--payload',
        dest='payload',
        action='store',
        help='The exact payload of the entities you are trying to get')
    list_parser.add_argument(
        '-t',
        '--entityType',
        dest='entityType',
        action='store',
        help='The type of the entities you are trying to get',
        choices=['Task', 'Workflow', 'Configuration'])
    list_parser.set_defaults(func=list_entities)

    # DELETE (namespace/name/id) arguments
    redact_parser = subparsers.add_parser(
        'redact',
        description=
        'Redact a specific method snapshot and all of its associated configurations from the FireCloud Methods Repository',
        help=
        'Redact a specific method snapshot and all of its associated configurations from the FireCloud Methods Repository'
    )
    redact_parser.add_argument(
        'NAMESPACE',
        action='store',
        help='The namespace for the entity you are trying to redact')
    redact_parser.add_argument(
        'NAME',
        action='store',
        help='The name of the entity you are trying to redact')
    redact_parser.add_argument(
        'SNAPSHOT_ID',
        type=int,
        action='store',
        help='The snapshot-id of the entity you are trying to redact')
    redact_parser.set_defaults(func=redact)

    # Call the appropriate function for the given subcommand, passing in the parsed program arguments
    args = parser.parse_args()
    args.func(args)
Example #55
0
def main():
    no_touch_dirs = ('.git', '.hg', '.svn')

    parser = ArgumentParser(description=DESC)
    parser.add_argument('--version', action='version', version=VERSION)

    # Source file indentation specs
    source_specs = parser.add_mutually_exclusive_group(required=True)
    source_specs.add_argument(
        '--source-tabs',
        help='Source file uses tabs for indentation.',
        action='store_true',
    )
    source_specs.add_argument('--source-size',
                              help='Indents size in source file(s).',
                              type=int,
                              metavar='SIZE')

    # Destination file indentation specs
    target_specs = parser.add_mutually_exclusive_group(required=True)
    target_specs.add_argument(
        '--dest-tabs',
        help='Use tabs for indentation in destination file.',
        action='store_true')
    target_specs.add_argument('--dest-size',
                              help='Indents size in destination file.',
                              type=int,
                              default=4,
                              metavar='SIZE')
    # Source and target paths
    parser.add_argument('--source',
                        help='File of folder from which code should be read.',
                        required=True)
    output_group = parser.add_mutually_exclusive_group(required=True)
    output_group.add_argument(
        '--dest', help='File or folder to which code should be written.')
    output_group.add_argument(
        '--debug',
        help="Output converted data to console, don't write anything.",
        action='store_true',
        default=False)
    parser.add_argument(
        '--exclude',
        help=('Comma-separated list of directory names to ignore. '
              'Only useful when SOURCE is a directory.'),
        metavar='FOLDERS')
    parser.add_argument(
        '--extensions',
        help=('Comma-separated list of specific file extensions to convert. '
              'Only useful when SOURCE is a directory.'))
    args = parser.parse_args()

    # Arguments checks
    if not os.path.exists(args.source):
        parser.error('file or directory not found: %s' % args.source)
    if (not args.source_tabs) and (args.source_size == 0):
        parser.error("--source-size value can't be 0")
    if (not args.dest_tabs) and (args.dest_size == 0):
        parser.error("--dest-size value can't be 0")

    # File input
    if os.path.isfile(args.source):
        if (not args.debug) and os.path.exists(args.dest):
            if overwrite_file(args.dest):
                convert_indents(args.source, args.dest, args.source_tabs,
                                args.source_size, args.dest_tabs,
                                args.dest_size, args.debug)
        else:
            convert_indents(args.source, args.dest, args.source_tabs,
                            args.source_size, args.dest_tabs, args.dest_size,
                            args.debug)

    # Directory input
    else:
        if args.source == args.dest:
            parser.error("--source and --dest values can't be the same.")
        no_touch_dirs += () if args.exclude is None else tuple(
            args.exclude.split(','))
        if args.debug:
            args.dest = '.'  # Prevents errors
        else:
            if not args.dest.endswith(os.path.sep):
                args.dest += os.path.sep
        for dirpath, dirnames, filenames in os.walk(args.source,
                                                    followlinks=True):
            for d in no_touch_dirs:
                if d in dirnames:
                    dirnames.remove(d)
            if args.extensions is not None:
                handled_files = set()
                for ext in args.extensions.split(','):
                    for f in filenames:
                        if f[-(len(ext)):] == ext:
                            handled_files.add(f)
            else:
                handled_files = filenames
            for filename in handled_files:
                in_path = os.path.abspath(os.path.join(dirpath, filename))
                out_path = os.path.abspath(
                    os.path.join(args.dest, dirpath, filename))
                out_dir = os.path.dirname(out_path)
                if (not args.debug) and (not os.path.exists(out_dir)):
                    os.makedirs(out_dir)
                if (not args.debug) and os.path.exists(out_path):
                    if overwrite_file(out_path):
                        convert_indents(in_path, out_path, args.source_tabs,
                                        args.source_size, args.dest_tabs,
                                        args.dest_size, args.debug)
                else:
                    convert_indents(in_path, out_path, args.source_tabs,
                                    args.source_size, args.dest_tabs,
                                    args.dest_size, args.debug)
Example #56
0
try:
    asyncio.ensure_future
except AttributeError:
    asyncio.ensure_future = getattr(
        asyncio, 'async')  # Compatibility with 3.4.4 and 3.5
parser = ArgumentParser(description="""
Fixate Command Line Interface

""",
                        formatter_class=RawTextHelpFormatter)

logger = logging.getLogger(__name__)

# Optional Arguments
mutex_group = parser.add_mutually_exclusive_group()
mutex_group.add_argument(
    '-p',
    '--path',
    help="""Path to the directory where the script file is located. 
                         This is mutually exclusive with --zip""")
mutex_group.add_argument(
    '-z',
    '--zip',
    help="""Path to zip file of test scripts. Mutually exclusive with --path""",
)
parser.add_argument(
    '-l',
    '--local_log',
    '--local-log',
    help=
Example #57
0
            if args.out_dir:
                plt.savefig(
                    os.path.join(args.out_dir, passage.ID + "." + args.format))
                plt.close()
            else:
                plt.show()


if __name__ == "__main__":
    argparser = ArgumentParser(
        description="Visualize the given passages as graphs.")
    argparser.add_argument(
        "passages",
        nargs="+",
        help="UCCA passages, given as xml/pickle file names")
    group = argparser.add_mutually_exclusive_group()
    group.add_argument("-t",
                       "--tikz",
                       action="store_true",
                       help="print tikz code rather than showing plots")
    group.add_argument("-s",
                       "--standoff",
                       action="store_true",
                       help="print standoff code rather than showing plots")
    argparser.add_argument(
        "-o",
        "--out-dir",
        help="directory to save figures in (otherwise displayed immediately)")
    argparser.add_argument("-i",
                           "--node-ids",
                           action="store_true",
Example #58
0
def main(args=None):
	"""Build a variable font from a designspace file and masters"""
	from argparse import ArgumentParser
	from fontemon_blender_addon.fontTools import configLogger

	parser = ArgumentParser(prog='varLib', description = main.__doc__)
	parser.add_argument('designspace')
	parser.add_argument(
		'-o',
		metavar='OUTPUTFILE',
		dest='outfile',
		default=None,
		help='output file'
	)
	parser.add_argument(
		'-x',
		metavar='TAG',
		dest='exclude',
		action='append',
		default=[],
		help='exclude table'
	)
	parser.add_argument(
		'--disable-iup',
		dest='optimize',
		action='store_false',
		help='do not perform IUP optimization'
	)
	parser.add_argument(
		'--master-finder',
		default='master_ttf_interpolatable/{stem}.ttf',
		help=(
			'templated string used for finding binary font '
			'files given the source file names defined in the '
			'designspace document. The following special strings '
			'are defined: {fullname} is the absolute source file '
			'name; {basename} is the file name without its '
			'directory; {stem} is the basename without the file '
			'extension; {ext} is the source file extension; '
			'{dirname} is the directory of the absolute file '
			'name. The default value is "%(default)s".'
		)
	)
	logging_group = parser.add_mutually_exclusive_group(required=False)
	logging_group.add_argument(
		"-v", "--verbose",
                action="store_true",
                help="Run more verbosely.")
	logging_group.add_argument(
		"-q", "--quiet",
                action="store_true",
                help="Turn verbosity off.")
	options = parser.parse_args(args)

	configLogger(level=(
		"DEBUG" if options.verbose else
		"ERROR" if options.quiet else
		"INFO"))

	designspace_filename = options.designspace
	finder = MasterFinder(options.master_finder)

	vf, _, _ = build(
		designspace_filename,
		finder,
		exclude=options.exclude,
		optimize=options.optimize
	)

	outfile = options.outfile
	if outfile is None:
		ext = "otf" if vf.sfntVersion == "OTTO" else "ttf"
		outfile = os.path.splitext(designspace_filename)[0] + '-VF.' + ext

	log.info("Saving variation font %s", outfile)
	vf.save(outfile)
Example #59
0
def main():
    """Parse command line arguments and start main script for analysis."""
    parser = ArgumentParser(prog="PLIP", description=description)
    pdbstructure = parser.add_mutually_exclusive_group(
        required=True)  # Needs either PDB ID or file
    # '-' as file name reads from stdin
    pdbstructure.add_argument("-f",
                              "--file",
                              dest="input",
                              nargs="+",
                              help="Set input file, '-' reads from stdin")
    pdbstructure.add_argument("-i", "--input", dest="pdbid", nargs="+")
    outputgroup = parser.add_mutually_exclusive_group(
        required=False)  # Needs either outpath or stdout
    outputgroup.add_argument("-o", "--out", dest="outpath", default="./")
    outputgroup.add_argument("-O",
                             "--stdout",
                             dest="stdout",
                             action="store_true",
                             default=False,
                             help="Write to stdout instead of file")
    parser.add_argument("--rawstring",
                        dest="use_raw_string",
                        default=False,
                        action="store_true",
                        help="Use Python raw strings for stdin")
    parser.add_argument("-v",
                        "--verbose",
                        dest="verbose",
                        default=False,
                        help="Turn on verbose mode",
                        action="store_true")
    parser.add_argument("-q",
                        "--quiet",
                        dest="quiet",
                        default=False,
                        help="Turn on quiet mode",
                        action="store_true")
    parser.add_argument("-s",
                        "--silent",
                        dest="silent",
                        default=False,
                        help="Turn on silent mode",
                        action="store_true")
    parser.add_argument("-p",
                        "--pics",
                        dest="pics",
                        default=False,
                        help="Additional pictures",
                        action="store_true")
    parser.add_argument("-x",
                        "--xml",
                        dest="xml",
                        default=False,
                        help="Generate report file in XML format",
                        action="store_true")
    parser.add_argument("-t",
                        "--txt",
                        dest="txt",
                        default=False,
                        help="Generate report file in TXT (RST) format",
                        action="store_true")
    parser.add_argument("-y",
                        "--pymol",
                        dest="pymol",
                        default=False,
                        help="Additional PyMOL session files",
                        action="store_true")
    parser.add_argument(
        "--maxthreads",
        dest="maxthreads",
        default=multiprocessing.cpu_count(),
        help=
        "Set maximum number of main threads (number of binding sites processed simultaneously)."
        "If not set, PLIP uses all available CPUs if possible.",
        type=int)
    parser.add_argument(
        "--breakcomposite",
        dest="breakcomposite",
        default=False,
        help=
        "Don't combine ligand fragments with covalent bonds but treat them as single ligands for the analysis.",
        action="store_true")
    parser.add_argument(
        "--altlocation",
        dest="altlocation",
        default=False,
        help=
        "Also consider alternate locations for atoms (e.g. alternate conformations).",
        action="store_true")
    parser.add_argument("--nofix",
                        dest="nofix",
                        default=False,
                        help="Turns off fixing of PDB files.",
                        action="store_true")
    parser.add_argument("--nofixfile",
                        dest="nofixfile",
                        default=False,
                        help="Turns off writing files for fixed PDB files.",
                        action="store_true")
    parser.add_argument(
        "--nopdbcanmap",
        dest="nopdbcanmap",
        default=False,
        help=
        "Turns off calculation of mapping between canonical and PDB atom order for ligands.",
        action="store_true")
    parser.add_argument(
        "--dnareceptor",
        dest="dnareceptor",
        default=False,
        help=
        "Uses the DNA instead of the protein as a receptor for interactions.",
        action="store_true")
    parser.add_argument(
        "--name",
        dest="outputfilename",
        default="report",
        help=
        "Set a filename for the report TXT and XML files. Will only work when processing single structures."
    )
    ligandtype = parser.add_mutually_exclusive_group(
    )  # Either peptide/inter or intra mode
    ligandtype.add_argument(
        "--peptides",
        "--inter",
        dest="peptides",
        default=[],
        help=
        "Allows to define one or multiple chains as peptide ligands or to detect inter-chain contacts",
        nargs="+")
    ligandtype.add_argument(
        "--intra",
        dest="intra",
        help="Allows to define one chain to analyze intra-chain contacts.")
    parser.add_argument("--keepmod",
                        dest="keepmod",
                        default=False,
                        help="Keep modified residues as ligands",
                        action="store_true")
    parser.add_argument(
        "--nohydro",
        dest="nohydro",
        default=False,
        help=
        "Do not add polar hydrogens in case your structure already contains hydrogens.",
        action="store_true")
    parser.add_argument(
        "--model",
        dest="model",
        default=1,
        help="Model number to be used for multi-model structures.",
        action="store_true")
    # Optional threshold arguments, not shown in help
    thr = namedtuple('threshold', 'name type')
    thresholds = [
        thr(name='aromatic_planarity', type='angle'),
        thr(name='hydroph_dist_max', type='distance'),
        thr(name='hbond_dist_max', type='distance'),
        thr(name='hbond_don_angle_min', type='angle'),
        thr(name='pistack_dist_max', type='distance'),
        thr(name='pistack_ang_dev', type='other'),
        thr(name='pistack_offset_max', type='distance'),
        thr(name='pication_dist_max', type='distance'),
        thr(name='saltbridge_dist_max', type='distance'),
        thr(name='halogen_dist_max', type='distance'),
        thr(name='halogen_acc_angle', type='angle'),
        thr(name='halogen_don_angle', type='angle'),
        thr(name='halogen_angle_dev', type='other'),
        thr(name='water_bridge_mindist', type='distance'),
        thr(name='water_bridge_maxdist', type='distance'),
        thr(name='water_bridge_omega_min', type='angle'),
        thr(name='water_bridge_omega_max', type='angle'),
        thr(name='water_bridge_theta_min', type='angle')
    ]
    for t in thresholds:
        parser.add_argument('--%s' % t.name,
                            dest=t.name,
                            type=lambda val: threshold_limiter(parser, val),
                            help=argparse.SUPPRESS)
    arguments = parser.parse_args()
    # configure log levels
    config.VERBOSE = True if arguments.verbose else False
    config.QUIET = True if arguments.quiet else False
    config.SILENT = True if arguments.silent else False
    if config.VERBOSE:
        logger.setLevel(logging.DEBUG)
    elif config.QUIET:
        logger.setLevel(logging.WARN)
    elif config.SILENT:
        logger.setLevel(logging.CRITICAL)
    else:
        logger.setLevel(config.DEFAULT_LOG_LEVEL)
    config.MAXTHREADS = arguments.maxthreads
    config.XML = arguments.xml
    config.TXT = arguments.txt
    config.PICS = arguments.pics
    config.PYMOL = arguments.pymol
    config.STDOUT = arguments.stdout
    config.RAWSTRING = arguments.use_raw_string
    config.OUTPATH = arguments.outpath
    config.OUTPATH = tilde_expansion(
        "".join([config.OUTPATH, '/']
                ) if not config.OUTPATH.endswith('/') else config.OUTPATH)
    config.BASEPATH = config.OUTPATH  # Used for batch processing
    config.BREAKCOMPOSITE = arguments.breakcomposite
    config.ALTLOC = arguments.altlocation
    config.PEPTIDES = arguments.peptides
    config.INTRA = arguments.intra
    config.NOFIX = arguments.nofix
    config.NOFIXFILE = arguments.nofixfile
    config.NOPDBCANMAP = arguments.nopdbcanmap
    config.KEEPMOD = arguments.keepmod
    config.DNARECEPTOR = arguments.dnareceptor
    config.OUTPUTFILENAME = arguments.outputfilename
    config.NOHYDRO = arguments.nohydro
    config.MODEL = arguments.model
    # Make sure we have pymol with --pics and --pymol
    if config.PICS or config.PYMOL:
        try:
            import pymol
        except ImportError:
            logger.error('PyMOL is required for the --pics and --pymol option')
            sys.exit(1)
    # Assign values to global thresholds
    for t in thresholds:
        tvalue = getattr(arguments, t.name)
        if tvalue is not None:
            if t.type == 'angle' and not 0 < tvalue < 180:  # Check value for angle thresholds
                parser.error(
                    "Threshold for angles need to have values within 0 and 180."
                )
            if t.type == 'distance':
                if tvalue > 10:  # Check value for angle thresholds
                    parser.error(
                        "Threshold for distances must not be larger than 10 Angstrom."
                    )
                elif tvalue > config.BS_DIST + 1:  # Dynamically adapt the search space for binding site residues
                    config.BS_DIST = tvalue + 1
            setattr(config, t.name.upper(), tvalue)
    # Check additional conditions for interdependent thresholds
    if not config.HALOGEN_ACC_ANGLE > config.HALOGEN_ANGLE_DEV:
        parser.error(
            "The halogen acceptor angle has to be larger than the halogen angle deviation."
        )
    if not config.HALOGEN_DON_ANGLE > config.HALOGEN_ANGLE_DEV:
        parser.error(
            "The halogen donor angle has to be larger than the halogen angle deviation."
        )
    if not config.WATER_BRIDGE_MINDIST < config.WATER_BRIDGE_MAXDIST:
        parser.error(
            "The water bridge minimum distance has to be smaller than the water bridge maximum distance."
        )
    if not config.WATER_BRIDGE_OMEGA_MIN < config.WATER_BRIDGE_OMEGA_MAX:
        parser.error(
            "The water bridge omega minimum angle has to be smaller than the water bridge omega maximum angle"
        )
    expanded_path = tilde_expansion(
        arguments.input) if arguments.input is not None else None
    run_analysis(expanded_path, arguments.pdbid)  # Start main script
Example #60
0
def main():
    """Main method, entry point of the script."""
    from argparse import ArgumentParser
    description = "Download a bunch of thumbnails from Wikimedia Commons"
    parser = ArgumentParser(description=description)
    source_group = parser.add_mutually_exclusive_group()
    source_group.add_argument("-l",
                              "--list",
                              metavar="LIST",
                              dest="file_list",
                              type=argparse.FileType('r'),
                              help='A list of files <filename,width>')
    source_group.add_argument("-c",
                              "--category",
                              metavar="CATEGORY",
                              dest="category_name",
                              type=str,
                              help='A category name (without prefix)')
    parser.add_argument("files",
                        nargs='*',
                        metavar="FILES",
                        help='A list of filenames')
    parser.add_argument("-o",
                        "--output",
                        metavar="FOLDER",
                        dest="output_path",
                        action=Folder,
                        default=os.getcwd(),
                        help='The directory to download the files to')
    parser.add_argument("-w",
                        "--width",
                        dest="width",
                        type=int,
                        default=100,
                        help='The width of the thumbnail (default: 100)')
    verbosity_group = parser.add_mutually_exclusive_group()
    verbosity_group.add_argument("-v",
                                 action="count",
                                 dest="verbose",
                                 default=1,
                                 help="Verbosity level. -v for DEBUG")
    verbosity_group.add_argument("-q",
                                 "--quiet",
                                 action="store_const",
                                 dest="verbose",
                                 const=0,
                                 help="To silence the INFO messages")
    args = parser.parse_args()
    logging_map = {0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG}
    logging_level = logging_map.get(args.verbose, logging.DEBUG)
    logging.basicConfig(level=logging_level)
    logging.info("Starting")

    if args.file_list:
        download_from_file_list(args.file_list, args.output_path)
    elif args.category_name:
        download_from_category(args.category_name, args.output_path,
                               args.width)
    elif args.files:
        download_from_files(args.files, args.output_path, args.width)
    else:
        parser.print_help()