def ProcessCommandLine(self):
        Parser = OptionParser(description=self.__copyright__,
                              version=self.__version__,
                              prog=sys.argv[0],
                              usage=self.__usage__)
        Parser.add_option("-q",
                          "--quiet",
                          action="store_true",
                          type=None,
                          help="Disable all messages except FATAL ERRORS.")
        Parser.add_option(
            "--git",
            action="store_true",
            type=None,
            help="Use git to create commits for each file converted")
        Parser.add_option("--diff",
                          action="store_true",
                          type=None,
                          help="Show diff of conversion")
        Parser.add_option("-f",
                          "--force",
                          action="store_true",
                          type=None,
                          help="Force conversion even if unsupported")

        (Opt, Args) = Parser.parse_args()

        if not Opt.quiet:
            print self.__copyright__
            Parser.print_version()

        return (Opt, Args)
def main(args=sys.argv[1:], parser=None):
    """ Main entry point for the route53_dyndns command-line script """

    usage = "%prog [options] [args]\n\n"
    version = "%prog " + __version__

    usage += "%prog is the HTTP dynamic DNS server for Route53"

    if parser is None:  # pragma: no cover
        parser = OptionParser(usage=usage, version=version,
                              add_help_option=False)
    parser.remove_option("--version")  # Remove standard version option

    parser.add_option("-h", "--help", dest="help", action="store_true",
                      help="Show help and exit")
    parser.add_option("-V", "--version", dest="version", action="store_true",
                      help="Show version and exit")

    (options, parsed_args) = parser.parse_args(args)

    # Check if we should print help or version number
    if not parsed_args or (parsed_args and len(parsed_args) == 0):
        if options.version:
            parser.print_version()
            sys.exit(0)
        elif options.help:
            parser.print_help()
            sys.exit(0)

    configure_logging()

    app.run(debug=True)
def main():
    # 处理命令行参数
    usage = u"%prog <-p 帖子ID> [-t 线程数]"
    parser = OptionParser(usage=usage)
    parser.add_option('-p', dest='pid', type='int', help=u'设置帖子ID')
    parser.add_option('-t',
                      dest='max_thread_num',
                      type='int',
                      help=u'设置使用的线程数',
                      default=10)
    parser.add_option('-d',
                      dest='save_directory',
                      type='string',
                      help=u'设置图片的保存目录',
                      default=u'.')
    args, _ = parser.parse_args()
    # 未设置关键参数时显示帮助
    if not args.pid:
        parser.print_help()
        return
    parser.print_version()
    # 有异常?不管
    try:
        image_get_obj = ImageGet(args.max_thread_num, args.save_directory)
        image_get_obj(args.pid)
    except:
        print(u'\n出了一些问题, 你可以自己去main()里的try块改改自己看看bug\n')
Beispiel #4
0
def main():
    """
    Main
    """

    # 引数のパース
    usage   = "Usage: %prog [option ...]"
    version ="%%prog %s\nCopyright (C) 2014 Yuichiro SAITO." % ( PROGRAM_VERSION )
    parser  = OptionParser( usage = usage, version = version )
    parser.add_option("-w", "--warning",
                      type="string",
                      dest="warning",
                      metavar="<free>",
                      help="Exit with WARNING status if less than value of space is free. You can choice kilobyte (integer) or percent (%).")
    parser.add_option("-c", "--critical",
                      type="string",
                      dest="critical",
                      metavar="<free>",
                      help="Exit with CRITICAL status if less than value of space is free. You can choice kilobyte (integer) or percent (%).")
    parser.add_option("-s", "--without_swap",
                      action="store_true",
                      dest="withoutswap",
                      default=False,
                      help="Calculate without swap. Default is False.")
    parser.add_option("-V", "--verbose",
                      action="store_true",
                      dest="verbose",
                      default=False,
                      help="Verbose mode. (For debug only)")
    ( options, args ) = parser.parse_args()
    prog_name = parser.get_prog_name()

    if len( sys.argv ) < 4:
        OptionParser.print_version( parser )
        return _MemFree.STATE_UNKNOWN

    if options.verbose:
        logging.basicConfig( level=logging.DEBUG, format = LOG_FORMAT )
    else:
        logging.basicConfig( level=logging.WARNING, format = LOG_FORMAT )

    logging.debug( "START" )

    # 評価を実施
    mem_free = _MemFree()
    ret = mem_free.setWarning( options.warning )
    if ret != _MemFree.STATE_OK:
        logging.debug( "EXIT" )
        return ret
    ret = mem_free.setCritical( options.critical )
    if ret != _MemFree.STATE_OK:
        logging.debug( "EXIT" )
        return ret
    ret = mem_free.checkMemFree( options.withoutswap )
    if ret != _MemFree.STATE_OK:
        logging.debug( "EXIT" )
        return ret

    logging.debug( "END" )
def main():
    """
    Main
    """

    # 引数のパース
    usage   = "Usage: %prog [option ...]"
    version ="%%prog %s\nCopyright (C) 2014 Yuichiro SAITO." % ( PROGRAM_VERSION )
    parser  = OptionParser( usage = usage, version = version )
    parser.add_option("-w", "--warning",
                      type="string",
                      dest="warning",
                      metavar="<free>",
                      help="Exit with WARNING status if less than value of space is free. You can choice kilobyte (integer) or percent (%).")
    parser.add_option("-c", "--critical",
                      type="string",
                      dest="critical",
                      metavar="<free>",
                      help="Exit with CRITICAL status if less than value of space is free. You can choice kilobyte (integer) or percent (%).")
    parser.add_option("-V", "--verbose",
                      action="store_true",
                      dest="verbose",
                      default=False,
                      help="Verbose mode. (For debug only)")
    ( options, args ) = parser.parse_args()
    prog_name = parser.get_prog_name()

    if len( sys.argv ) < 4:
        OptionParser.print_version( parser )
        return _MemFree.STATE_UNKNOWN

    if options.verbose:
        logging.basicConfig( level=logging.DEBUG, format = LOG_FORMAT )
    else:
        logging.basicConfig( level=logging.WARNING, format = LOG_FORMAT )

    logging.debug( "START" )

    # 評価を実施
    mem_free = _MemFree()
    ret = mem_free.setWarning( options.warning )
    if ret != _MemFree.STATE_OK:
        logging.debug( "EXIT" )
        return ret
    ret = mem_free.setCritical( options.critical )
    if ret != _MemFree.STATE_OK:
        logging.debug( "EXIT" )
        return ret
    ret = mem_free.checkMemFree()
    if ret != _MemFree.STATE_OK:
        logging.debug( "EXIT" )
        return ret

    logging.debug( "END" )
Beispiel #6
0
def CLI(args=argv[1:]):
    parser = OptionParser(
        version='cassandra-cli/%s (using pycassa/%s, Python/%s)' % (
            ccli_version, pycassa_version, '.'.join(map(str, version_info[:3]))
            ),
        usage='Usage: %prog [OPTIONS] [keyspace]',
        description='Cassanda Command-Line Interface',
        add_help_option=False
    )

    parser.remove_option('--version')
    parser.add_option('-?', '--help', dest='show_help', help='Display this help and exit.', action='store_true', default=False)
    parser.add_option('-I', dest='show_help', help='Synonym for -?', action='store_true')
    parser.add_option('-V', '--version', dest='show_version', help='Output version information and exit.', action='store_true', default=False)
    parser.add_option('-v', '--verbose', dest='verbose', help='Write more.', metavar='verbose', action='count', default=0)

    parser.add_option('-h', '--host', dest='host', help='Connect to host.', metavar='name', default='localhost')
    parser.add_option('-P', '--port', dest='port', help='Port number to use for connection (default: %default).', metavar='#', default=9160, type='int')

    parser.add_option('-u', '--user', dest='username', help='User for login', metavar='name', default=None)
    parser.add_option('-p', '--password', dest='password', help="Password to use when connecting to server. If password is not given it's asked from the tty.", metavar='name', default=None, action='callback', callback=process_password)

    parser.add_option('-k', '--keyspace', dest='keyspace', help='Keyspace to use.', metavar='name', default=None)
    parser.add_option('-d', '--database', dest='keyspace', help='Synonym for -k (mysql client compatibility).', metavar='name')

    parser.add_option('--connect-timeout', dest='timeout', help='Number of seconds before connection timeout.', metavar='#', default=0.5, type='float')

    options, args = parser.parse_args(args=args)
    if len(args) == 1:
        options.keyspace = args[0]

    if options.show_help or len(args) > 1:
        parser.print_version()
        parser.print_help()
    elif options.show_version:
        parser.print_version()
    else:
        try:
            GUI(
                host=options.host, port=options.port, keyspace=options.keyspace,
                username=options.username, password=options.password, timeout=options.timeout,
                verbose=options.verbose
            ).run()
        except Exception as e:
            if options.verbose >= 2:
                raise

            print 'CCLI ERROR: %s' % str(e)
Beispiel #7
0
def main():
    p = OptionParser(version=version)
    p.add_option('-d', '--discovery', action='store_true', help="Discovery device")
    p.add_option('-i', '--interface', action='store', type='int', default=0, help="Interface number")
    p.add_option('-c', '--count', action='store', type='int', help="Packet send count", default=3)
    opts, args = p.parse_args()

    if opts.discovery:
        dev_discovery()

    elif opts.interface > 0:
        generator(opts)

    else:
        p.print_version()
        p.print_help()
def main():
    # 处理命令行参数
    usage = u"%prog <-p 帖子ID> [-t 线程数]"
    parser = OptionParser(usage=usage)
    parser.add_option('-p', dest='pid', type='int', help=u'设置帖子ID')
    parser.add_option('-t', dest='max_thread_num', type='int', help=u'设置使用的线程数', default=10)
    parser.add_option('-d', dest='save_directory', type='string', help=u'设置图片的保存目录', default=u'.')
    args, _ = parser.parse_args()
    # 未设置关键参数时显示帮助
    if not args.pid:
        parser.print_help()
        return
    parser.print_version()
    # 有异常?不管
    try:
        image_get_obj = ImageGet(args.max_thread_num, args.save_directory)
        image_get_obj(args.pid)
    except:
        print(u'\n出了一些问题, 你可以自己去main()里的try块改改自己看看bug\n')
Beispiel #9
0
    def ProcessCommandLine(self):
        Parser = OptionParser(
            description=self.__copyright__, version=self.__version__, prog=sys.argv[0], usage=self.__usage__
        )
        Parser.add_option(
            "-q", "--quiet", action="store_true", type=None, help="Disable all messages except FATAL ERRORS."
        )
        Parser.add_option(
            "--git", action="store_true", type=None, help="Use git to create commits for each file converted"
        )
        Parser.add_option("--diff", action="store_true", type=None, help="Show diff of conversion")
        Parser.add_option("-f", "--force", action="store_true", type=None, help="Force conversion even if unsupported")

        (Opt, Args) = Parser.parse_args()

        if not Opt.quiet:
            print self.__copyright__
            Parser.print_version()

        return (Opt, Args)
Beispiel #10
0
    def print_version(self, file = None) :
        OptionParser.print_version(self, file)

        assert(hasattr(self, "authors"))
        assert(callable(self.authors))
        assert(isinstance(self.authors(), list))

        print >> file, ""
        j = 0
        for i in self.authors() :
            if (j == 0) :
                header = "Copyright (C) 2008, 2009 "
            else :
                header = "                         "
            print >> file, header + i
            j = j + 1
        print >> file, ""

        print >> file, "This is free software.  You may redistribute copies of it under the terms of"
        print >> file, "the GNU General Public License <http://www.gnu.org/licenses/gpl.html>."
        print >> file, "There is NO WARRANTY, to the extent permitted by law."
import binascii
import usb.core
import usb.util
import sys

auc_vid = 0x29f1
auc_pid = 0x33f2
TYPE_TEST = "32"
TYPE_DETECT = "10"
DATA_OFFSET = 6
parser = OptionParser(version="%prog ver: 20171019_1156")
# TODO: Add voltage control
#       Add miner support
#       Add frequency support
(options, args) = parser.parse_args()
parser.print_version()


def CRC16(message):
    # CRC-16-CITT poly, the CRC sheme used by ymodem protocol
    poly = 0x1021
    # 16bit operation register, initialized to zeros
    reg = 0x0000
    # pad the end of the message with the size of the poly
    message += '\x00\x00'
    # for each bit in the message
    for byte in message:
        mask = 0x80
        while(mask > 0):
            # left shift by one
            reg <<= 1
Beispiel #12
0
 def print_version(self, file=None):
     from calibre.utils.terminal import ANSIStream
     s = ANSIStream(file)
     _OptionParser.print_version(self, file=s)
Beispiel #13
0
    def OnInit(self):
        version = 'gipyplot Ver. 2.0'
        filenames = []
        print_version = False
        verbose = False
        formt = None
        xlabel = 'X'
        ylabel = 'Y'
        title="GENESIS 3 Plot"

        cwd=os.getcwd()
        #os.chdir(cwd)

        description = """

gipyplot creates a frame with a toolbar that holds a G-3 graph (a 2D y vs x
plot).  The graph allows multiple plots from multicolumn data 'x, y1, y2,
...'  given at successive x-values, given in one or more files.  Wildcard
file names are accepted.

        """
        usage = "%s [OPTIONS] <files>"
        parser = OptionParser(usage=usage, version=version, description=description)
        parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
            default = False, help="show verbose output")
    
        parser.add_option("-V", "--show-version", action="store_true", dest="version_flag",
            default = False, help="print the program version")

        parser.add_option("-t", "--title", dest="title", type="string",
            default=title,  help="Title for the graph")

        parser.add_option("-f", "--format", dest="formt", type="string",
                      help="The plot format and color. e.g 'k' \
                      default: None cycles color for multiple plots")

        parser.add_option("-x", "--xlabel", dest="xlabel", type="string",
            default=xlabel, help="The label for the X axis")

        parser.add_option("-y", "--ylabel", dest="ylabel", type="string",
            default=ylabel, help="The label for the Y axis")

        rangegroup = optparse.OptionGroup(parser, "Axis Range Options: \n "
            ' Autoscaling is used unless both min and max values are given')

        rangegroup.add_option("--xmin", dest="xmin", type="float",
            default=None, help="Minimum value for the X axis")
        rangegroup.add_option("--xmax", dest="xmax", type="float",
            default=None, help="Maximum value for the X axis")
        rangegroup.add_option("--ymin", dest="ymin", type="float",
            default=None, help="Minimum value for the Y axis")
        rangegroup.add_option("--ymax", dest="ymax", type="float",
            default=None, help="Maximum value for the Y axis")
        parser.add_option_group(rangegroup)
        (options, args) = parser.parse_args()

        if options.version_flag is True:
            parser.print_version()
            return True

#        if len(args) < 1:
        
#             parser.error("Need at least one data file to read in")

        # collect options
        verbose = options.verbose
        if len(args) > 0:
            for a in args:
                if os.path.isfile( a ):
                    filenames.append(a)
                else:
                    parser.error("File '%s' doesn't exist" % a)

            formt = options.formt
            xlabel = options.xlabel
            ylabel = options.ylabel
            title = options.title

        # Now make the plot
        frame = G3Plot(files=filenames,
            verbose=verbose,
            xlabel=xlabel,
            ylabel=ylabel,
            title=title,
            formt=formt,
            xmin=options.xmin,
            xmax=options.xmax,
            ymin=options.ymin,
            ymax=options.ymax)

        frame.Show()
	self.SetTopWindow(frame)
	return True
        print "     ", option,":",cmd_options.__dict__[option]
    print "}"

    # load dataset
    dataset = load_data(dataset_dir)
    perform_clustering(dataset)

if __name__ == "__main__":
    desc="""Text Clustering laboratory.
This program aims to present an introdution to text clustering.
It performs experiences using kmeans and hierarchical clustering being dataset agnostic.
    """

    cmd_parser = OptionParser(version="%prog 0.1",description=desc)

    cmd_parser.print_version()

    cmd_parser.add_option("-D", "--dataset", type="string", action="store", dest="directory", help="Base directory with dataset files")    
    cmd_parser.add_option("-C", "--clust_method", default="kmeans", dest="clust_method",
                  help="Clustering method: hclust, kmeans [default: %default]")

    cmd_parser.add_option("-F", "--max_features", default=5, dest="max_features", type="int",
                  help="optional, None by default. If not None, consider the top max_features ordered by term frequency across the corpus")

    cmd_parser.add_option("-M", "--max_df", default=0.4, dest="max_df", type="float",
                  help="float in range [0.0, 1.0] or int, optional, 1.0 by default. When building the vocabulary ignore terms that have a term frequency strictly higher than the given threshold (corpus specific stop words). If float, the parameter represents a proportion of documents, integer absolute counts. This parameter is ignored if vocabulary is not None.")

    cmd_parser.add_option("-W", "--wordcloud", default=0.4, dest="wordcloud", type="float",
                  help="Compute wordcloud")
    (cmd_options, cmd_args) = cmd_parser.parse_args()
Beispiel #15
0
def main():
    global options, ctrl_c_Received

    flows = flowstore()

    parser = OptionParser(
        usage="usage: %prog [options] file", version="%prog: PCAP Slicer")
    parser.add_option('-f', '--bpf', dest='bpf', help='BPF input filter')
    parser.add_option('-o', '--outdir', dest='outdir', default='.',
                      help='directory to write output files (Default: current directory)')
    parser.add_option('--no-vlan', dest='novlan', action="store_true",
                      help='do not examine traffic which has VLAN headers present')
    parser.add_option('--debug', action='store_true', dest='debug')
    (options, args) = parser.parse_args(sys.argv[1:])

    if not args:
        parser.print_version()
        parser.print_help()
        sys.exit()

    filter = ''
    if options.bpf != None:
        filter = options.bpf
    if not options.novlan and not(filter.startswith('vlan')):
        if filter:
            filter = '( ' + filter + ' ) or ( vlan and ( ' + filter + ' ) )'
        else:
            filter = ''  # fix for null filter case

    pcount = 0
    for f in args:
        pcapreader = pcap.pcap(f)
        if options.bpf:
            pcapreader.setfilter(filter)
        while True:
            # Pick a packet
            try:
                ts, spkt = pcapreader.next()
            except:
                break  # EOF
            # Parse IP/Port/Proto Information
            try:
                pkt = dpkt.ethernet.Ethernet(spkt)
                # Only handle IP4/6
                if type(pkt.data) == dpkt.ip.IP:
                    proto = pkt.data.p
                elif type(pkt.data) == dpkt.ip6.IP6:
                    proto = pkt.data.nxt
                else:
                    continue
                # Populate addr tuple
                # (proto, sip, sport, dip, dport)
                if proto == dpkt.ip.IP_PROTO_TCP or proto == dpkt.ip.IP_PROTO_UDP:
                    addr = (
                        proto, pkt.data.src, pkt.data.data.sport, pkt.data.dst, pkt.data.data.dport)
                else:
                    addr = (proto, pkt.data.src, None, pkt.data.dst, None)
            except:
                continue  # Skip Packet if unable to parse
            pcount += 1
            #
            # Look for existing open flow or start new one
            #
            thisflow = flows.find(addr)
            if thisflow == None:
                thisflow = flow(addr)
                flows.add(thisflow)
                warn("New flow to file: %s" % str(thisflow))
            #
            # Write this packet to correct flow
            #
            thisflow.write(len(spkt), spkt, ts)
            #
            # Check for TCP reset or fin
            #
            try:
                if pkt.data.data.flags & (dpkt.tcp.TH_RST | dpkt.tcp.TH_FIN):
                    thisflow.done()
            except:
                pass  # probably not a TCP packet
            #
            # Cleanup Routine
            #
            if pcount % 1000 == 0:
                flows.cleanup(ts)
            #
            # Clean exit
            #
            if ctrl_c_Received:
                sys.stderr.write("Exiting on interrupt signal.\n")
                sys.exit(0)
    def __init__(self,
                 name,
                 description=None,
                 version=None,
                 epilog=None,
                 where=None,
                 **parse_args):
        self._rundir = None
        self.args = None
        self.name = name

        self._commands = {}
        for name in dir(self.__class__):
            attr = getattr(self.__class__, name)
            if hasattr(attr, '_is_command') and \
                    (attr.name != 'config' or 'config_files' in parse_args):
                self._commands[attr.name or name] = getattr(self, name)

        parser = OptionParser(usage='%prog [OPTIONS]',
                              description=description,
                              add_help_option=False)

        if version:
            parser.add_option('-V',
                              '--version',
                              help=_('show version number and exit'),
                              action='version')
            parser.print_version = lambda: sys.stdout.write('%s\n' % version)

        parser.add_option('-h',
                          '--help',
                          help=_('show this help message and exit'),
                          action='store_true')

        options, self.args = Option.parse_args(parser, **parse_args)

        def print_desc(term, desc):
            text = []
            for num, line in enumerate(desc.split('\n')):
                if num == 0:
                    for i in line:
                        if i.isalpha() and not i.isupper():
                            break
                    else:
                        term += ' ' + line
                        continue
                text.extend(textwrap.wrap(line, 54))
            if len(term) < 24:
                sys.stdout.write('  %-22s' % term)
            else:
                text.insert(0, '')
                sys.stdout.write('  %s' % term)
            print('\n' + ' ' * 24).join(text)

        def print_commands():
            if not self._commands:
                return
            print ''
            print _('Commands') + ':'
            for name, attr in sorted(self._commands.items(),
                                     lambda x, y: cmp(x[0], y[0])):
                if attr.hidden:
                    continue
                if attr.args:
                    name += ' ' + attr.args
                print_desc(name, attr.description)

        if not self.args and not options.help:
            prog = basename(sys.argv[0])
            print _('Usage') + ': %s [OPTIONS] [COMMAND]' % prog
            print '       %s -h|--help' % prog
            print
            print description
            print_commands()
            if epilog:
                print ''
                print epilog
            exit(0)

        if options.help:
            parser.print_help()
            print_commands()
            if where:
                print ''
                print _('Where') + ':'
                for term in sorted(where):
                    print_desc(term, where[term])
            if epilog:
                print ''
                print epilog
            exit(0)

        if not debug.value:
            logging_level = logging.WARNING
        elif debug.value == 1:
            logging_level = logging.INFO
        elif debug.value == 2:
            logging_level = logging.DEBUG
        elif debug.value > 2:
            logging_level = 0
        logging_format = _LOGFILE_FORMAT

        root_logger = logging.getLogger('')
        for i in root_logger.handlers:
            root_logger.removeHandler(i)

        logging.basicConfig(level=logging_level, format=logging_format)
Beispiel #17
0
 def print_version(self, file=None):
     from calibre.utils.terminal import ANSIStream
     s = ANSIStream(file)
     _OptionParser.print_version(self, file=s)
Beispiel #18
0
 def print_version(self, f=None):
    f = self._pick_file(f)
    OptionParser.print_version(self, self._pick_file(f))
    f.flush()
Beispiel #19
0
                  default=1,
                  help="Load data every st grid points over t dimension")
parser.add_option('--useindex',
                  action='store_true',
                  dest="useindex",
                  default=False,
                  help="Use index for arrays and not values of dimensions")
# plot options --> upper case. see ppplot.
parser = ppplot.opt(parser)
parser = ppplot.opt1d(parser)
parser = ppplot.opt2d(parser)
###########################
(opt, args) = parser.parse_args()
# remains G R
if (len(args) == 0):
    parser.print_version()

######################################
# get arguments (one or several files)
######################################
if args is None:
    print "Stop here! I need file(s) as argument(s)!"
    exit()
else:
    files = args

#############################################
# a possibility to simply inspect the file(s)
#############################################
if opt.var is None:
    for filename in files:
Beispiel #20
0




from optparse import OptionParser
from os.path import exists
import sys

if __name__ == "__main__":
  opt = OptionParser(usage="%prog [options] unipatch-file", version="python-patch %s" % __version__)
  opt.add_option("-d", action="store_true", dest="debugmode", help="debug mode")
  (options, args) = opt.parse_args()

  if not args:
    opt.print_version()
    print("")
    opt.print_help()
    sys.exit()
  debugmode = options.debugmode
  patchfile = args[0]
  if not exists(patchfile) or not isfile(patchfile):
    sys.exit("patch file does not exist - %s" % patchfile)


  if debugmode:
    logging.basicConfig(level=logging.DEBUG, format="%(levelname)8s %(message)s")
  else:
    logging.basicConfig(level=logging.INFO, format="%(message)s")

Beispiel #21
0
    changelog = '''
	+++ 0.2a +++
	Change format to JSON instead of importing over .py file.
	Cleaner, more efficient, and I know should've been my go to
	before I even started.

	+++ 0.1a +++
	import class from personal file, add stuff to class,
	then export it over the original personal file'''

    p = OptionParser(usage=usage, version=version)
    p.add_option('-n', '--name', help='Change name of worker.')
    p.add_option('-s',
                 '--settings-file',
                 help='Name of settings file.(current path only)')
    p.add_option('-v',
                 '--verbose',
                 action='store_true',
                 help='Extra output for debugging')
    p.add_option('--changelog',
                 action='store_true',
                 help='Output Version and Changelog')
    options, args = p.parse_args()
    if options.changelog:
        p.print_version()
        print changelog
        exit()

    a = Worker(verbose=options.verbose)
    a.run(2)
    print "}"

    # load dataset
    dataset = load_data(dataset_dir)
    perform_clustering(dataset)


if __name__ == "__main__":
    desc = """Text Clustering laboratory.
This program aims to present an introdution to text clustering.
It performs experiences using kmeans and hierarchical clustering being dataset agnostic.
    """

    cmd_parser = OptionParser(version="%prog 0.1", description=desc)

    cmd_parser.print_version()

    cmd_parser.add_option("-D",
                          "--dataset",
                          type="string",
                          action="store",
                          dest="directory",
                          help="Base directory with dataset files")
    cmd_parser.add_option(
        "-C",
        "--clust_method",
        default="kmeans",
        dest="clust_method",
        help="Clustering method: hclust, kmeans [default: %default]")

    cmd_parser.add_option(
Beispiel #23
0
def main():
    from optparse import OptionParser
    from os.path import exists
    import sys

    opt = OptionParser(usage="1. %prog [options] unified.diff\n"
                       "       2. %prog [options] http://host/patch\n"
                       "       3. %prog [options] -- < unified.diff",
                       version="python-patch %s" % __version__)
    opt.add_option("-q",
                   "--quiet",
                   action="store_const",
                   dest="verbosity",
                   const=0,
                   help="print only warnings and errors",
                   default=1)
    opt.add_option("-v",
                   "--verbose",
                   action="count",
                   dest="verbosity",
                   default=0,
                   help="verbosity level (use up to 3 times)")
    opt.add_option("--diffstat",
                   action="store_true",
                   dest="diffstat",
                   help="print diffstat and exit")
    opt.add_option("-d",
                   "--directory",
                   metavar='DIR',
                   help="specify root directory for applying patch")
    opt.add_option("-p",
                   "--strip",
                   type="int",
                   metavar='N',
                   default=0,
                   help="strip N path components from filenames")
    opt.add_option("--revert",
                   action="store_true",
                   help="apply patch in reverse order (unpatch)")
    (options, args) = opt.parse_args()

    if not args and sys.argv[-1:] != ['--']:
        opt.print_version()
        opt.print_help()
        sys.exit()
    readstdin = (sys.argv[-1:] == ['--'] and not args)

    setup_logging(options.verbosity)

    if readstdin:
        patch = PatchSet(sys.stdin)
    else:
        patchfile = args[0]
        urltest = patchfile.split(':')[0]
        if ':' in patchfile and urltest.isalpha() and len(urltest) > 1:
            # one char before : is a windows drive letter
            patch = fromurl(patchfile)
        else:
            if not exists(patchfile) or not isfile(patchfile):
                sys.exit("patch file does not exist - %s" % patchfile)
            patch = fromfile(patchfile)

    if options.diffstat:
        print(patch.diffstat())
        sys.exit(0)

    if options.revert:
        patch.revert(options.strip, root=options.directory) or sys.exit(-1)
    else:
        patch.apply(options.strip, root=options.directory) or sys.exit(-1)
Beispiel #24
0
 def print_version(self, file=None):
     self.command = NoOpCommand()
     return OptionParser.print_version(self, file)
Beispiel #25
0
def main():
    global options, ctrl_c_Received

    flows = flowstore()

    parser = OptionParser(usage="usage: %prog [options] file",
                          version="%prog: PCAP Slicer")
    parser.add_option('-f', '--bpf', dest='bpf', help='BPF input filter')
    parser.add_option(
        '-o',
        '--outdir',
        dest='outdir',
        default='.',
        help='directory to write output files (Default: current directory)')
    parser.add_option(
        '--no-vlan',
        dest='novlan',
        action="store_true",
        help='do not examine traffic which has VLAN headers present')
    parser.add_option('--debug', action='store_true', dest='debug')
    (options, args) = parser.parse_args(sys.argv[1:])

    if not args:
        parser.print_version()
        parser.print_help()
        sys.exit()

    filter = ''
    if options.bpf != None:
        filter = options.bpf
    if not options.novlan and not (filter.startswith('vlan')):
        if filter:
            filter = '( ' + filter + ' ) or ( vlan and ( ' + filter + ' ) )'
        else:
            filter = ''  # fix for null filter case

    pcount = 0
    for f in args:
        pcapreader = pcap.pcap(f)
        if options.bpf:
            pcapreader.setfilter(filter)
        while True:
            # Pick a packet
            try:
                ts, spkt = pcapreader.next()
            except:
                break  # EOF
            # Parse IP/Port/Proto Information
            try:
                pkt = dpkt.ethernet.Ethernet(spkt)
                # Only handle IP4/6
                if type(pkt.data) == dpkt.ip.IP:
                    proto = pkt.data.p
                elif type(pkt.data) == dpkt.ip6.IP6:
                    proto = pkt.data.nxt
                else:
                    continue
                # Populate addr tuple
                # (proto, sip, sport, dip, dport)
                if proto == dpkt.ip.IP_PROTO_TCP or proto == dpkt.ip.IP_PROTO_UDP:
                    addr = (proto, pkt.data.src, pkt.data.data.sport,
                            pkt.data.dst, pkt.data.data.dport)
                else:
                    addr = (proto, pkt.data.src, None, pkt.data.dst, None)
            except:
                continue  # Skip Packet if unable to parse
            pcount += 1
            #
            # Look for existing open flow or start new one
            #
            thisflow = flows.find(addr)
            if thisflow == None:
                thisflow = flow(addr)
                flows.add(thisflow)
                warn("New flow to file: %s" % str(thisflow))
            #
            # Write this packet to correct flow
            #
            thisflow.write(len(spkt), spkt, ts)
            #
            # Check for TCP reset or fin
            #
            try:
                if pkt.data.data.flags & (dpkt.tcp.TH_RST | dpkt.tcp.TH_FIN):
                    thisflow.done()
            except:
                pass  # probably not a TCP packet
            #
            # Cleanup Routine
            #
            if pcount % 1000 == 0:
                flows.cleanup(ts)
            #
            # Clean exit
            #
            if ctrl_c_Received:
                sys.stderr.write("Exiting on interrupt signal.\n")
                sys.exit(0)
Beispiel #26
0
def main():
    from optparse import OptionParser
    from os.path import exists
    from json import load

    opt = OptionParser(
        usage="%prog [options] to_patch_directory/ unified.diff",
        version="patch_hunk %s" % __version__)
    opt.add_option("-q",
                   "--quiet",
                   action="store_const",
                   dest="verbosity",
                   const=0,
                   help="print only warnings and errors",
                   default=1)
    opt.add_option("-v",
                   "--verbose",
                   action="store_const",
                   dest="verbosity",
                   const=2,
                   help="be verbose")
    opt.add_option("--debug",
                   action="store_true",
                   dest="debugmode",
                   help="debug mode")
    opt.add_option("-c",
                   "--conf",
                   dest='conf',
                   metavar='CONF_FILE.json',
                   default='default-conf.json',
                   help="specify the configuration file")
    (options, args) = opt.parse_args()

    verbosity_levels = {0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG}
    loglevel = verbosity_levels[options.verbosity]
    logformat = "%(message)s"
    logger.setLevel(loglevel)
    streamhandler.setFormatter(logging.Formatter(logformat))

    if not args or not len(args) == 2:
        opt.print_version()
        opt.print_help()
        sys.exit()

    dir_to_patch = args[0]
    patchfile = args[1]

    # patch existance check
    if not exists(patchfile) or not isfile(patchfile):
        sys.exit("patch file does not exist - %s" % patchfile)
    with open(patchfile) as patch_file:
        patch_str = patch_file.read()

    # directory existance check
    if not exists(dir_to_patch) or not isdir(dir_to_patch):
        sys.exit("source directory does not exist - %s" % dir_to_patch)

    # conf file existance check
    if not exists(options.conf) or not isfile(options.conf):
        sys.exit("conf JSON file does not exist - %s" % options.conf)
    with open(options.conf) as conf_file:
        config = load(conf_file)

    adapt(patch_str, dir_to_patch, config)
Beispiel #27
0
def main():
  from optparse import OptionParser
  from os.path import exists
  import sys

  opt = OptionParser(usage="1. %prog [options] unified.diff\n"
                    "       2. %prog [options] http://host/patch\n"
                    "       3. %prog [options] -- < unified.diff",
                     version="python-patch %s" % __version__)
  opt.add_option("-q", "--quiet", action="store_const", dest="verbosity",
                                  const=0, help="print only warnings and errors", default=1)
  opt.add_option("-v", "--verbose", action="store_const", dest="verbosity",
                                  const=2, help="be verbose")
  opt.add_option("--debug", action="store_true", dest="debugmode", help="debug mode")
  opt.add_option("--diffstat", action="store_true", dest="diffstat",
                                           help="print diffstat and exit")
  opt.add_option("-d", "--directory", metavar='DIR',
                                           help="specify root directory for applying patch")
  opt.add_option("-p", "--strip", type="int", metavar='N', default=0,
                                           help="strip N path components from filenames")
  opt.add_option("--revert", action="store_true",
                                           help="apply patch in reverse order (unpatch)")
  (options, args) = opt.parse_args()

  if not args and sys.argv[-1:] != ['--']:
    opt.print_version()
    opt.print_help()
    sys.exit()
  readstdin = (sys.argv[-1:] == ['--'] and not args)

  verbosity_levels = {0:logging.WARNING, 1:logging.INFO, 2:logging.DEBUG}
  loglevel = verbosity_levels[options.verbosity]
  logformat = "%(message)s"
  logger.setLevel(loglevel)
  streamhandler.setFormatter(logging.Formatter(logformat))

  if options.debugmode:
    setdebug()  # this sets global debugmode variable

  if readstdin:
    patch = PatchSet(sys.stdin)
  else:
    patchfile = args[0]
    urltest = patchfile.split(':')[0]
    if (':' in patchfile and urltest.isalpha()
        and len(urltest) > 1): # one char before : is a windows drive letter
      patch = fromurl(patchfile)
    else:
      if not exists(patchfile) or not isfile(patchfile):
        sys.exit("patch file does not exist - %s" % patchfile)
      patch = fromfile(patchfile)

  if options.diffstat:
    print patch.diffstat()
    sys.exit(0)

  #pprint(patch)
  if options.revert:
    patch.revert(options.strip, root=options.directory) or sys.exit(-1)
  else:
    patch.apply(options.strip, root=options.directory) or sys.exit(-1)
Beispiel #28
0
    opt = OptionParser(usage="%prog [options] unipatch-file",
                       version="python-patch %s" % __version__)
    opt.add_option("-d",
                   "--debug",
                   action="store_true",
                   dest="debugmode",
                   help="Print debugging messages")
    opt.add_option("-q",
                   "--quiet",
                   action="store_true",
                   dest="quiet",
                   help="Only print messages on warning/error")
    (options, args) = opt.parse_args()

    if not args:
        opt.print_version()
        opt.print_help()
        sys.exit()
    debugmode = options.debugmode
    patchfile = args[0]
    if not exists(patchfile) or not isfile(patchfile):
        sys.exit("patch file does not exist - %s" % patchfile)

    if debugmode:
        loglevel = logging.DEBUG
        logformat = "%(levelname)8s %(message)s"
    elif options.quiet:
        loglevel = logging.WARN
        logformat = "%(message)s"
    else:
        loglevel = logging.INFO
Beispiel #29
0
    def OnInit(self):
        version = 'gipyplot Ver. 2.0'
        filenames = []
        print_version = False
        verbose = False
        formt = None
        xlabel = 'X'
        ylabel = 'Y'
        title = "GENESIS 3 Plot"

        cwd = os.getcwd()
        #os.chdir(cwd)

        description = """

gipyplot creates a frame with a toolbar that holds a G-3 graph (a 2D y vs x
plot).  The graph allows multiple plots from multicolumn data 'x, y1, y2,
...'  given at successive x-values, given in one or more files.  Wildcard
file names are accepted.

        """
        usage = "%s [OPTIONS] <files>"
        parser = OptionParser(usage=usage,
                              version=version,
                              description=description)
        parser.add_option("-v",
                          "--verbose",
                          action="store_true",
                          dest="verbose",
                          default=False,
                          help="show verbose output")

        parser.add_option("-V",
                          "--show-version",
                          action="store_true",
                          dest="version_flag",
                          default=False,
                          help="print the program version")

        parser.add_option("-t",
                          "--title",
                          dest="title",
                          type="string",
                          default=title,
                          help="Title for the graph")

        parser.add_option("-f",
                          "--format",
                          dest="formt",
                          type="string",
                          help="The plot format and color. e.g 'k' \
                      default: None cycles color for multiple plots")

        parser.add_option("-x",
                          "--xlabel",
                          dest="xlabel",
                          type="string",
                          default=xlabel,
                          help="The label for the X axis")

        parser.add_option("-y",
                          "--ylabel",
                          dest="ylabel",
                          type="string",
                          default=ylabel,
                          help="The label for the Y axis")

        rangegroup = optparse.OptionGroup(
            parser, "Axis Range Options: \n "
            ' Autoscaling is used unless both min and max values are given')

        rangegroup.add_option("--xmin",
                              dest="xmin",
                              type="float",
                              default=None,
                              help="Minimum value for the X axis")
        rangegroup.add_option("--xmax",
                              dest="xmax",
                              type="float",
                              default=None,
                              help="Maximum value for the X axis")
        rangegroup.add_option("--ymin",
                              dest="ymin",
                              type="float",
                              default=None,
                              help="Minimum value for the Y axis")
        rangegroup.add_option("--ymax",
                              dest="ymax",
                              type="float",
                              default=None,
                              help="Maximum value for the Y axis")
        parser.add_option_group(rangegroup)
        (options, args) = parser.parse_args()

        if options.version_flag is True:
            parser.print_version()
            return True

#        if len(args) < 1:

#             parser.error("Need at least one data file to read in")

# collect options
        verbose = options.verbose
        if len(args) > 0:
            for a in args:
                if os.path.isfile(a):
                    filenames.append(a)
                else:
                    parser.error("File '%s' doesn't exist" % a)

            formt = options.formt
            xlabel = options.xlabel
            ylabel = options.ylabel
            title = options.title

        # Now make the plot
        frame = G3Plot(files=filenames,
                       verbose=verbose,
                       xlabel=xlabel,
                       ylabel=ylabel,
                       title=title,
                       formt=formt,
                       xmin=options.xmin,
                       xmax=options.xmax,
                       ymin=options.ymin,
                       ymax=options.ymax)

        frame.Show()
        self.SetTopWindow(frame)
        return True
def main():
    from optparse import OptionParser
    from os.path import exists
    import sys

    opt = OptionParser(usage="1. %prog [options] unified.diff\n"
                             "       2. %prog [options] http://host/patch\n"
                             "       3. %prog [options] -- < unified.diff",
                       version="python-patch %s" % __version__)
    opt.add_option("-q", "--quiet", action="store_const", dest="verbosity",
                   const=0, help="print only warnings and errors", default=1)
    opt.add_option("-v", "--verbose", action="store_const", dest="verbosity",
                   const=2, help="be verbose")
    opt.add_option("--debug", action="store_true", dest="debugmode", help="debug mode")
    opt.add_option("--diffstat", action="store_true", dest="diffstat",
                   help="print diffstat and exit")
    opt.add_option("-d", "--directory", metavar='DIR',
                   help="specify root directory for applying patch")
    opt.add_option("-p", "--strip", type="int", metavar='N', default=0,
                   help="strip N path components from filenames")
    opt.add_option("--revert", action="store_true",
                   help="apply patch in reverse order (unpatch)")
    (options, args) = opt.parse_args()

    if not args and sys.argv[-1:] != ['--']:
        opt.print_version()
        opt.print_help()
        sys.exit()
    readstdin = (sys.argv[-1:] == ['--'] and not args)

    verbosity_levels = {0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG}
    loglevel = verbosity_levels[options.verbosity]
    logformat = "%(message)s"
    logger.setLevel(loglevel)
    streamhandler.setFormatter(logging.Formatter(logformat))

    if options.debugmode:
        setdebug()  # this sets global debugmode variable

    if readstdin:
        patch = PatchSet(sys.stdin)
    else:
        patchfile = args[0]
        urltest = patchfile.split(':')[0]
        if (':' in patchfile and urltest.isalpha()
            and len(urltest) > 1):  # one char before : is a windows drive letter
            patch = fromurl(patchfile)
        else:
            if not exists(patchfile) or not isfile(patchfile):
                sys.exit("patch file does not exist - %s" % patchfile)
            patch = fromfile(patchfile)

    if options.diffstat:
        print(patch.diffstat())
        sys.exit(0)

    # pprint(patch)
    if options.revert:
        patch.revert(options.strip, root=options.directory) or sys.exit(-1)
    else:
        patch.apply(options.strip, root=options.directory) or sys.exit(-1)
Beispiel #31
0
def parseOptions():
    global options, args, cmdparser, infile, zlevels

    from optparse import OptionParser # optparse/optik - Powerful parser for command line options
    usage = "usage: %prog [options] <stl file>"
    cmdparser = OptionParser(conflict_handler="resolve", version=version, usage=usage)

    cmdparser.add_option("-o", "--output", dest="outfile", default="", help="<optional> output file (*.xhtml , *.html , *.svg, *.cli, *.txt, *.hpgl, *.plt, *.bmp, *.jpg, *.png, *.tif, *.gif).\nThe HTML output uses an embedded SVG file and can be viewed in a compatible browser.\nSome browsers might require you to install a plugin for viewing SVG files.\nIf an output file is omitted, results are printed to the console window.")
    cmdparser.add_option("-m", "--multiple", action="store_true", dest="multiple", default="", help="in connection with output to an image format, write one file per z level")
    cmdparser.add_option("-z", "--zheights", dest="z", default="", help="<optional> slice at these z heights (comma separated list of values, can be of form 'lo, hi, step')")
    cmdparser.add_option("-d", "--difference", type="float", dest="wdiff", default=0.0, help="if set, adaptive steps so that slices don't differ by more than this")
    cmdparser.add_option("-t", "--type", type="choice", dest="tooltype", default="disk", choices=["disk", "sphere"], help="type of slicing tool (disk or sphere; default is disk)")
    cmdparser.add_option("-r", "--radius", type="float", dest="radius", default=1.0, help="<optional> tool radius")
    cmdparser.add_option("-f", "--offset", type="string", dest="offset", default="-radius", help="offset contours (<0 to offset inwards, defaults to -radius for default tool)")
    cmdparser.add_option("-s", "--resolution", type="float", dest="wres", default=-1.0, help="resolution (if omitted this calculated from the STL dimensions)")
    cmdparser.add_option("-l", "--layer", type="float", dest="layerthickness", default=-1.0, help="layer thickness for slicing with a disk (height of disk), default is 10% of the z height")
    cmdparser.add_option("-v", "--verbose", action="store_true", dest="verbose", default="", help="print information")
    cmdparser.add_option("-w", "--width", type="int", dest="imgwidth", default=370, help="image width (default 370) (used for output image formats)")
    cmdparser.add_option("-h", "--height", type="int", dest="imgheight", default=370, help="image height (default 370) (used for output image formats)")
    cmdparser.add_option("-a", "--aspect", type="string", dest="aspect", default="xy", help="aspect (default is xy, other values yz or xz)")
    cmdparser.add_option("--cavity", type="string", dest="cavity", default="white", help="color of cavity areas (default is white). Colors can be given as names (white, black, ...), or hex codes (#ffffff, #000000, #ff0000, ...)")
    cmdparser.add_option("--core", type="string", dest="core", default="black", help="color of core areas (default is black). Colors can be given as names (white, black, ...), or hex codes (#ffffff, #000000, #ff0000, ...)")
    cmdparser.add_option("--background", type="string", dest="background", default="", help="background color (defaults to cavity color selection). Colors can be given as names (white, black, ...), or hex codes (#ffffff, #000000, #ff0000, ...)")
    cmdparser.add_option("--noprogress", action="store_true", dest="noprogress", default="", help="do not print progress bar")
    cmdparser.add_option("--shell", action="store_true", dest="shell", default="", help="slice STL as shell (default is solid)")
    
    (options, args) = cmdparser.parse_args()

    if len(args) != 1 or (not os.path.isfile(args[0])): # need an input file
        cmdparser.print_version()
        cmdparser.print_help()
        sys.exit(0)

    infile = args[0]
    if options.verbose:
        cmdparser.print_version()

    zlevels = options.z
    if zlevels:
        # parse into floats
        zlist = zlevels.split(",")
        try:
            zlevels = [float(z) for z in zlist]
        except:
            print "Could not parse z levels: ", options.z
            cmdparser.print_version()
            cmdparser.print_help()
            sys.exit(0)

        if len(zlevels) == 3:
            # try to interpret as "lo, hi, step", allowing for a negative step
            lo, hi, step = zlevels[0], zlevels[1], zlevels[2]
            if ((lo < hi) == (step > 0)) and ((hi - lo) > step) and ((lo + step) > lo):
                zlevels = [lo]
                while (step > 0 and (zlevels[-1] + step <= hi)) or (step < 0 and (zlevels[-1] + step >= hi)):
                    zlevels.append(zlevels[-1] + step)


    if options.wdiff:
        if not (len(zlevels) == 2):
            print "For adaptive stepdown, two z values are expected."
            cmdparser.print_version()
            cmdparser.print_help()
            sys.exit(0)

    if options.radius <= 0:
            print "Radius expected to be > 0"
            cmdparser.print_version()
            cmdparser.print_help()
            sys.exit(0)
            
    if not options.background:
        options.background = options.cavity
Beispiel #32
0
if __name__ == "__main__":
	usage = '%prog [options]'
	version = '%prog v0.2a'
	changelog = '''
	+++ 0.2a +++
	Change format to JSON instead of importing over .py file.
	Cleaner, more efficient, and I know should've been my go to
	before I even started.

	+++ 0.1a +++
	import class from personal file, add stuff to class,
	then export it over the original personal file'''

	p = OptionParser(usage=usage, version=version)
	p.add_option('-n', '--name',
	             help='Change name of worker.')
	p.add_option('-s', '--settings-file',
	             help='Name of settings file.(current path only)')
	p.add_option('-v', '--verbose', action='store_true',
	             help='Extra output for debugging')
	p.add_option('--changelog', action='store_true',
	             help='Output Version and Changelog')
	options, args = p.parse_args()
	if options.changelog:
		p.print_version()
		print changelog
		exit()

	a = Worker(verbose=options.verbose)
	a.run(2)
Beispiel #33
0
 def print_version(self, stream=None):
     OptionParser.print_version(self, sys.stdinfo)