Пример #1
0
def main():
    args.init()
    c = args.sub('jobs', jobs_c, help="List all jobs matching JOBPATTERN")
    c.arg('jobpattern', metavar="JOBPATTERN")

    c = args.sub('builds', builds_c, help="Show recent builds for JOB")
    c.arg('job', metavar="JOB")

    c = args.sub('log', log_c, help="Show console output for JOB, build# BUILD (or latest)")
    c.arg('jobname', nargs='?', metavar="JOB")

    c.arg('build', type=int, nargs='?', metavar="BUILD")

    c = args.sub('set', set_c, help="Set permanent config variable (e.g. 'jenq set repository http://foo-jenkins.busyware.com')")
    c.arg('variable', metavar="VARIABLE")
    c.arg('value', metavar="VALUE")

    c = args.sub('sync', sync_c, help="Fetch list of jobs from repository to local cache")

    c  = args.sub('fav', fav_c, help="Favorite a job")
    c.arg('jobname', nargs='?', metavar="JOB")

    c = args.sub('favs', favs_c, help="Show recent builds for all favorited jobs")

    c = args.sub('alias', alias_c, help="Create convenient alias for JOB")
    c.arg('shortname', nargs='?', metavar="SHORTNAME")
    c.arg('jobname', nargs='?', metavar="JOB")

    c = args.sub('jobinfo', job_c, help="Display raw job info (json)")
    c.arg('jobname', nargs='?', metavar="JOB")

    c = args.sub('go', go_c, help="Open newest build for JOB in browser")
    c.arg('jobname', nargs='?', metavar="JOB")

    args.parse()
Пример #2
0
def main():
    pp = argparse.ArgumentParser(prog = "wpp",
    description="PATH optimization and management utility for Windows",
    epilog="See https://github.com/vivainio/wpathr for detailed documentation.")

    args.init(pp)
    args.sub("ls", ls, help = "List paths alphabetically")
    sqc = args.sub("squash", squash, help = "Shorten paths by squashing (convert to progra~1 format)")
    args.sub("dump", dump, help = "Dump paths to screen in original format (for backup)")
    ddc = args.sub("dedupe", dedupe, help = "Remove duplicate paths")
    exc = args.sub("exists", exists, help = "Remove nonexisting paths")
    src = args.sub("search", search, help = "Scan through path for files matching PATTERN")
    lnc = args.sub("long", longnames, help = "Show long names (progra~1 -> Program Files)")
    fac = args.sub("factor", factor, help = "Factor out runs of VALUE in path to %%VARIABLE%% referenses")
    fac.arg("variable", metavar="VARIABLE")
    fac.arg("value", metavar="VALUE")
    sset = args.sub("sset", sset_c, help="Set SYSTEM env variable to VALUE. Like xset /s, really")
    sset.arg("variable", metavar="VARIABLE")
    sset.arg("value", metavar="VALUE")

    syc = args.sub("sync", sync, help="Notify other processes to sync the environment")

    src.arg("pattern", type=str, nargs="+")

    adc = args.sub("add", add_s, help='Add directory to System path')
    adc.arg('directory', nargs="+")

    rmc = args.sub('remove', remove_s, help="Remove directory from path")
    rmc.arg('directory', nargs="+")

    pvc = args.sub('env', env_paths, help="List env variables that refer to existing paths")
    # operations that support --commit

    slc = args.sub('symlink', symlink_c, help="Create symbolic link at LINKPATH from SOURCE")
    slc.arg('linkname', metavar="LINKPATH")
    slc.arg('filepath', metavar="FILEPATH")

    alias = args.sub('alias', alias_c, help="Create alias for a command")
    alias.arg('name', nargs="?")
    alias.arg('command', nargs="?")

    runalias = args.sub('r', runalias_c, help="Run aliased command with arguments")
    runalias.arg('name', metavar="ALIAS")
    runalias.arg('args', metavar="ARGUMENTS", nargs=argparse.REMAINDER)

    up = args.sub('up', run_up_c, help="Run command that exist in any parent directory")
    up.arg("command")
    up.arg("argument", nargs="*")

    for a in [sqc, ddc, exc, fac, adc, rmc]:
        a.arg("--commit", action='store_true')

    args.parse()
Пример #3
0
def main():
    """Client side of Dice Wars
    """
    args, log_level = parse()
    logging.basicConfig(level=log_level)
    logger = logging.getLogger('CLIENT')

    game = Game(args.address, args.port)

    if args.ai:
        if args.ai == 1:
            from ai.ai1 import AI
        elif args.ai == 2:
            from ai.ai2 import AI
        elif args.ai == 3:
            from ai.ai3 import AI
        elif args.ai == 4:
            from ai.ai4 import AI
        elif args.ai == 5:
            from ai.ai5 import AI
        elif args.ai == 6:
            from ai.ai6 import AI
        elif args.ai == 7:
            from ai.ai7 import AI
        else:
            logging.error("No AI version {0}.".format(args.ai))
            exit(1)

        ai = AI(game)
        ai.run()

    else:
        app = QApplication(sys.argv)
        ui = ClientUI(game)
        sys.exit(app.exec_())
Пример #4
0
def main():
  config = args.parse()
  say_hello()
  print('cli arguments as understood:\n')
  pprint(config, indent=2)
  print('\n\n')

  # dry run
  if config['dry'] is True:
    dry_run(config['dry_opts'])
  # real run
  elif len(config['watchers']):
    YOUTUBE_FILENAME_PATTERN = "(.*\\/)?([a-zA-Z0-9\\_\\-]{10,})\\.(mp3|m4a)$"
    watcher = Watcher()

    for watcher_config in config['watchers']:
      rc_json = get_configuration_from_file(watcher_config['rc_filename'])
      on_event = ConditionalFileEventHandler(
        both(is_moved_event, partial(filename_matches, YOUTUBE_FILENAME_PATTERN)),
        partial(on_youtube_music_file, rc_json=rc_json, watcher_config=watcher_config)
      )
      watcher.schedule(on_event, watcher_config['watch'], recursive=config['recursive'])
    
    watcher.start()

    try:
      while True:
        time.sleep(1)
    except KeyboardInterrupt:
      if watcher is not None:
        watcher.stop()
  # inconsistent state
  else:
    raise ValueError('ValueError: Program should be run with either the --dry flag or with some --watch and --out values')
Пример #5
0
def main():
    settings = config.load()
    arguments = args.parse()

    action.load(settings)

    action.dispatch(arguments["action"], arguments["filter"])
Пример #6
0
def main():
    args.init()

    args.sub('here', here_c, help = 'Set current dir as prjroot')
    s = args.sub('g', grep_c, help = 'Grep the project')
    s.arg("pattern", type=str)
    sc = args.sub('s', scan_c, help ='Search with context')
    sc.arg('--all', help="Do not limit hits per file", action='store_true')
    sc.arg('-e', nargs=argparse.REMAINDER)
    sc.arg("pattern", type=str, nargs=argparse.REMAINDER)

    pick = args.sub('p', pick_c, help = 'Use peco to quick pick one of the earlier choices')
    pick.arg('choice', type=int, help='Choice number to pick immediately', nargs='?')
    args.sub('co', checkout_c, help = "select and check out a branch")
    args.sub('r', recent_c, help="select and check out a recently used branch")

    args.parse()
Пример #7
0
def main():
    """
    Server for Dice Wars
    """
    args, log_level = parse()
    logging.basicConfig(level=log_level)
    logger = logging.getLogger('SERVER')
    logger.debug("Command line arguments: {0}".format(args))

    game = Game(args.number_of_players, args.address, args.port)
    game.run()
Пример #8
0
import args
import colorclass
import lang.en as lang
import sys
import tacview
import utils

colorclass.Windows.enable()

try:
    args.parse()
    utils.log.tentative(lang.execution.VALIDATING)
    if args.MAIN.MODE == "range":
        args.check_range()
        args.check_target()
    args.convert()
    utils.log.success(lang.execution.VALIDATED)
except SystemExit:
    raise
except IOError:
    utils.log.fail(lang.error.MISSING_FILE)
    sys.exit()
except ValueError as ex:
    if ex.args[0] == "range":
        utils.log.fail(lang.error.INVALID_RANGE % (ex.args[1]))
    elif ex.args[0] == "target":
        utils.log.fail(lang.error.INVALID_TARGET % (ex.args[1], ex.args[2]))
    sys.exit()
except Exception as ex:
    if args.MAIN.DEBUG:
        utils.log.fail(lang.error.DEBUG % (str(ex)))
Пример #9
0
#! /usr/bin/env python3

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
import os

import helpers
import constants
import editor
import menu
import args

argfiles, verbose = args.parse()

if verbose:
    editor.verbose = True
    menu.verbose = True
    helpers.verbose = True
    editor.helpers.verbose = True
    menu.helpers.verbose = True

printv = helpers.printv


class Window(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="Ahead")
        self.connect("destroy", Gtk.main_quit)

        self.set_size_request(constants.HEIGHT, constants.WIDTH)
Пример #10
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*

from sys import stderr

import args
import files
import translate

if __name__ == '__main__':
    args = args.parse()
    input_buf = files.try_read(args.source_file)
    c_source_buf = ''
    try:
        c_source_buf = translate.uck_to_c(input_buf,
                                          default_function=args.default_function,
                                          memory_size=args.memory_size,
                                          do_emit_bf_mem=args.bf_memory)
    except SyntaxError as se:
        print('Uck syntax error: ' + str(se).format(input_file=args.source_file), file=stderr)
    files.try_write(args.output_file, c_source_buf)
Пример #11
0
#!/usr/bin/env python3

import os
import shutil
import sys
from tempfile import TemporaryDirectory

import args
from file_utils import replace_in_file, append_line
from timer import time_cmd

COMMAND, COPY_START, COPY_STOP = args.parse(sys.argv)

for copies in range(COPY_START, COPY_STOP + 1):
    with TemporaryDirectory() as tmpdir:
        workingdir = tmpdir + "/demo"
        shutil.copytree("/Users/tim/Projects/prbx/demo", workingdir)

        for n in range(1, copies):
            nstr = str(n).zfill(3)

            classdest = workingdir + "/lib/demo/palindrome" + nstr + ".rb"
            shutil.copyfile(workingdir + "/lib/demo/palindrome.rb", classdest)
            replace_in_file(classdest, "class Palindrome", "class Palindrome" + nstr)
            append_line(workingdir + "/lib/demo.rb", "require \"demo/palindrome" + nstr + "\"")

            specdest = workingdir + "/spec/demo/palindrome" + nstr + "_spec.rb"
            shutil.copyfile(workingdir + "/spec/demo/palindrome_spec.rb", specdest)
            replace_in_file(specdest, "describe Palindrome", "describe Palindrome" + nstr)

        runtime = time_cmd(COMMAND, workingdir)
Пример #12
0
def main(cargs):
    # folder from where dude is called
    cfolder = os.getcwd()

    # parse command line
    (options, cargs) = parser.parse_args(cargs)

    # check if a command has been given
    if cargs == []:
        parser.print_help()
        sys.exit()

    # create requires no Dudefile, so we deal with it right here
    if cargs[0] == "create":
        if len(cargs) < 2:
            expgen.create()
        else:
            expgen.create(cargs[1])
        sys.exit(0)

    # all other commands require a Dudefile, so we first load it (in "cfg")
    cfg = None

    # use a given dudefile in options
    if options.expfile != None:
        try:
            cfg = imp.load_source('', options.expfile)
        except IOError:
            print >> sys.stderr, 'ERROR: Loading', options.expfile, 'failed'
            parser.print_help()
            sys.exit(1)
    else:  # try default file names
        current = os.getcwd()
        max_folder = 10  # arbitrary number of parent directories
        i = 0
        while i < max_folder:
            for f in ['desc.py', 'dudefile', 'Dudefile', 'dudefile.py']:
                try:
                    if os.path.exists(f) and i > 0:
                        print "Opening Dudefile: ", os.path.abspath(f)
                    cfg = imp.load_source('', f)
                    break
                except IOError:
                    pass
            if cfg != None:
                break
            else:
                i += 1
                parent, last = os.path.split(current)
                os.chdir(parent)
                current = parent

        if cfg == None:
            print >> sys.stderr, 'ERROR: no dudefile found'
            parser.print_help()
            sys.exit(1)

    # add to actual folder as root in cfg
    cfg.root = os.getcwd()

    # check if cfg can be used for core functions
    core.check_cfg(cfg)

    # check if cfg can be used for summaries
    summary.check_cfg(cfg)

    # parse arguments to module
    if options.margs:
        margs = args.parse(";".join(options.margs))
        print "Passing arguments:", margs
        args.set_args(cfg, margs)

    if hasattr(cfg, 'dude_version') and cfg.dude_version >= 3:
        dimensions.update(cfg)

    # collect filters
    filters = []
    if options.filter and options.filter != []:
        for fi in options.filter:
            for f in fi.split(','):
                filters.append(cfg.filters[f])

    if options.filter_inline and options.filter_inline != []:
        filters += filt.create_inline_filter(cfg, options.filter_inline)

    if options.filter_path:
        current = os.getcwd()
        if current != cfolder:
            # this assumes Dudefile is in the root of the experiment folder
            os.chdir(cfolder)
            path = os.path.abspath(options.filter_path)
            os.chdir(current)
            path = os.path.relpath(path)  # get raw_output_dir/exp_... format
        else:
            path = options.filter_path

        filters += filt.filter_path(cfg, path)

    # get experiments
    experiments = core.get_experiments(cfg)

    # select the set of experiments to be considered (successful,
    # failed or pending)
    if (options.success and options.failed and options.pending) or\
            not (options.success or options.failed or options.pending):
        pass
    else:
        failed, pending = core.get_failed_pending_exp(cfg, experiments)
        expin = []
        expout = []

        if options.failed:
            expin += failed
        else:
            expout += failed

        if options.pending:
            expin += pending
        else:
            expout += pending

        if options.success:
            experiments = [exp for exp in experiments if exp not in expout]
        else:
            experiments = expin

    # apply filters
    if filters != []:
        experiments = filt.filter_experiments(cfg, filters, options.invert,
                                              False, experiments)

    cmd = cargs[0]
    if cmd == 'run':
        if options.force:
            clean.clean_experiments(cfg, experiments)
        execute.run(cfg, experiments, options)
    elif cmd == 'run-once':
        assert len(experiments) == 1
        optpt = experiments[0]
        folder = "once"
        utils.checkFolder(folder)  # create if necessary
        if options.force:
            clean.clean_experiment(folder)
        execute.execute_isolated(cfg, optpt, folder, options.show_output)
    elif cmd == 'sum':
        summary.summarize(cfg, experiments, cargs[1:], options.backend,
                          options.ignore_status)
    elif cmd == 'list':
        for experiment in experiments:
            if options.dict:
                print "experiment:", experiment
            else:
                print core.get_folder(cfg, experiment)
    elif cmd == 'failed':
        failed = core.get_failed(cfg, experiments, False)
        for ffile in failed:
            print ffile
    elif cmd == 'missing':
        failed = core.get_failed(cfg, experiments, True)
        for exp in failed:
            print exp
    elif cmd == 'clean':
        if options.invalid:
            clean.clean_invalid_experiments(cfg, experiments)
        else:
            # TODO if no filter applied, ask if that's really what the
            # user wants.
            r = 'y'
            if options.filter == None and \
                    options.filter_inline == None:
                print "sure to wanna delete everything? [y/N]"
                r = utils.getch()  #raw_input("Skip, quit, or continue?
                #[s/q/c]")

            if r == 'y':
                clean.clean_experiments(cfg, experiments)
    elif cmd == 'visit':
        if len(cargs) < 2:
            print "Specify a bash command after visit"
            sys.exit(1)
        elif len(cargs) > 2:
            print "Surround multi-term bash commands with \"\"."
            print "e.g., \"%s\"" % ' '.join(cargs[1:])
            sys.exit(1)
        visit.visit_cmd_experiments(cfg, experiments, cargs[1])
    elif cmd == 'info':
        info.show_info(cfg, experiments)
    elif cmd == 'status':
        info.print_status(cfg, experiments)
    else:
        print >> sys.stderr, "ERROR: wrong command. %s" % cargs[0]
        parser.print_help()
Пример #13
0
def main(args=None):
    sw = switch_4()
    smb = I2C()
    par = parse()
    adc = ADC()
    pers = _8bitIO()
    port = _16bitIO()
    parser = par.get_parser()
    args = parser.parse_args(args)  #inspect the command line

    err_flag = False

    if ((args.i2c0 and not args.i2c1) or (args.i2c1 and not args.i2c0)):
        try:
            data = smb.parse_func(args.data[0])
        except:
            err_flag = True
            raise
            print('Error parsing or invalid syntax, use "-h" for help')
        if not err_flag:
            if i2c.w_found and not i2c.r_found:
                try:
                    smb.write(data[0], data[1], not args.i2c0) # data[0] is data_i, data[1] is data_w
                    print('ACK')
                except IOError:
                    print('NACK...confirm you are transacting with the correct bus')
                except:
                    raise
                    print('Invalid Syntax')
            if not i2c.w_found and not i2c.r_found:
                try:
                    smb.detect(data[0], not args.i2c0)
                    print('ACK')
                except:
                    print('NACK...confirm you are transacting with the correct bus')
            if i2c.r_found and not i2c.w_found:
                try:
                    smb.read(data[0], data[2], not args.i2c0)
                except IOError:
                    print('NACK...confirm you are transacting with the correct bus')
                except:
                    raise
                    print('Invalid Syntax')
            if i2c.r_found and i2c.w_found:
                smb.write_read(data[0], data[2], data[1], not args.i2c0)

    elif args.gpio and 'getall' in args.data:
        try:
            os.system('raspi-gpio get')
        except:
            print('Invalid syntax')

    elif args.gpio and 'get' in args.data:
        try:
            os.system('raspi-gpio get ' + args.data[1])
            print('Success')
        except:
            print('Invalid syntax')

    elif args.gpio and 'set' in args.data:
        if len(args.data) == 3:
            try:
                os.system('raspi-gpio set ' + args.data[1] + ' ' + args.data[2])
                print('Success')
            except:
                print('Invalid syntax')

        if len(args.data) == 4:
            try:
                os.system('raspi-gpio set ' + args.data[1] + ' ' + args.data[2] + ' ' + args.data[3])
                print('Success')
            except:
                print('Invalid syntax')

        if len(args.data) == 5:
            try:
                os.system('raspi-gpio set ' + args.data[1] + ' ' + args.data[2] + ' ' + args.data[3] + ' ' + args.data[4])
                print('Success')
            except:
                print('Invalid syntax')
    elif args.adc:

        if args.data[0] == 'raw' and len(args.data) == 2:
            try:
                adc.raw_adc(args.data[1])
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        elif args.data[0] ==  'volt' and len(args.data) == 2:
            try:
                print(adc.volt_adc(args.data[1]))
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        else:
            print('Invalid syntax')
    elif args.per:
        if(args.data[0] == 'config'):
            try:
                pers.configPorts()
                print('Success')
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Fail!')
        elif(args.data[0] == 'arm'):
            try:
                pers.arm(args.data[1], False)
                print('Success')
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        elif(args.data[0] == 'disarm'):
            try:
                pers.arm(args.data[1], True)
                print('Success')
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        elif(args.data[0] == 'read'):
            try:
                pers.read_inputs()
                print('Success')
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
    elif args.port:
        if(args.data[0] == 'config'):
            try:
                port.configPorts()
                print('Success')
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Fail!')
        elif args.data[0] == 'readall':
            try:
                port.zone_readall(args.data[1])
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        elif args.data[0] == 'read':
            try:
                port.zone_read(args.data[1], args.data[2])
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        elif args.data[0] == 'led':
            try:
                port.led_toggle(args.data[1], args.data[2], args.data[3])
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        else:
            print('Invalid syntax')
    elif args.switch:
        if args.data[0] == 'write':
            try:
                sw.ch_write(args.data[1], args.data[2], args.data[3])
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        elif args.data[0] == 'readint':
            try:
                sw.read_int(args.data[1])
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        elif args.data[0] == 'read':
            try:
                sw.read_dat(args.data[1], args.data[2])
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')

    else:
        print('Invalid syntax')
Пример #14
0
    Use it to check stopping conditions.
    Doesn't reset unles memoization is deleted.

    '''
    try:
        countdown.value -= 1
        return countdown.value > 0
    except AttributeError:
        countdown.value = n
        return True


if __name__ == '__main__':
    opt = args.parse([('folds', 10, int),
                      ('testfold', 0, int),
                      ('rounds', None, int),
                      ('beststump', False, None)], sys.argv)
    print
    print 'Boosting {} decision stumps {}.'.format(
        'optimal' if opt['beststump'] else 'random',
        'until convergence' if opt['rounds'] is None else 'for {} rounds'.format(opt['rounds']))
    if opt['rounds'] is None:
        print 'Convergence occurs when test error fails to decrease by {} for {} rounds in a row.'.format(MINDIFF, PERSISTENCE)
    print 'Using spambase data folded {} ways. Testing on fold {}.'.format(
        opt['folds'], opt['testfold'])

    # stopping conditions
    if opt['rounds'] is None:
        def doround(err, rndct):
            return checkconverged(err)
    else:
Пример #15
0
import opencage.geocoder as geo
import pickle
import os

import haversine
import data
import args

arg = args.parse()

if not os.path.exists("key.pickle"):
    print("No key found.")
    print("If you need an API key please visit https://opencagedata.com/api.")
    print(
        "The following prompt will be asked only once, and key will be saved to 'key.pickle' in current directory.\n"
    )
    API_key = {
        "name": input("Enter a name to associate this key with:> "),
        "key": input("To utilize geocode please enter your API key:> ")
    }
    with open('key.pickle', 'wb') as file:
        pickle.dump(API_key, file)

# unpickle existing key
with open('key.pickle', 'rb') as file:
    GeoKey = pickle.load(file)

print("Query may take a moment...please wait.\n")

try:
    coder = geo.OpenCageGeocode(GeoKey['key'])
Пример #16
0
    _pair = re.compile(r"(\d+,\d+)")  # find buckets like (*,*) --|
    _num = re.compile(r"\d+")  # parse out the number ------> (15,20) -> 15 20
    buck_list = _pair.findall(str_buck)
    if len(buck_list) < 1:
        raise ValueError(
            "There should be at least 1 specific bucket.\nPlease set buckets in configuration."
        )
    buckets = []
    for buck in buck_list:
        tmp = _num.findall(buck)
        d_tmp = (int(tmp[0]), int(tmp[1]))
        buckets.append(d_tmp)
    return buckets


FLAGS = args.parse()
_buckets = parse_buckets(FLAGS.buckets)


def train_GAN():
    os.environ['CUDA_VISIBLE_DEVICES'] = '1'
    from keras.backend.tensorflow_backend import set_session
    config = tf.ConfigProto()
    config.gpu_options.per_process_gpu_memory_fraction = 0.3
    set_session(tf.Session(config=config))

    if not os.path.exists(FLAGS.model_dir):
        os.makedirs(FLAGS.model_dir)

    if not os.path.exists(FLAGS.pretrain_dir):
        os.makedirs(FLAGS.pretrain_dir)
Пример #17
0
    Use it to check stopping conditions.
    Doesn't reset unles memoization is deleted.

    '''
    try:
        countdown.value -= 1
        return countdown.value > 0
    except AttributeError:
        countdown.value = n
        return True


if __name__ == '__main__':
    opt = args.parse([('folds', 10, int), ('testfold', 0, int),
                      ('rounds', None, int), ('beststump', False, None)],
                     sys.argv)
    print
    print 'Boosting {} decision stumps {}.'.format(
        'optimal' if opt['beststump'] else 'random', 'until convergence'
        if opt['rounds'] is None else 'for {} rounds'.format(opt['rounds']))
    if opt['rounds'] is None:
        print 'Convergence occurs when test error fails to decrease by {} for {} rounds in a row.'.format(
            MINDIFF, PERSISTENCE)
    print 'Using spambase data folded {} ways. Testing on fold {}.'.format(
        opt['folds'], opt['testfold'])

    # stopping conditions
    if opt['rounds'] is None:

        def doround(err, rndct):
Пример #18
0
    def get_groups(self):
        self.groups = self._normal_loader.read(mkurl(self.url, 'groups'), 'group', True)
    
    def get_recs(self):
        self.recs = self._normal_loader.read(mkurl(self.url, 'recs'), 'rec')

    def get_saying(self):
        self.saying = self._normal_loader.read(mkurl(self.url, 'miniblogs?type=saying'), 'saying')

    #recs, miniblogs, reviews, subjects, online, recs

if __name__ == '__main__':

    args.init([
        ('user', 'user name to backup', ''),
        #('minbs', '最小块大小', 'int'),
        ('item', 'data items to backup, seperated by comma, default \'all\'', 'list'),
        #('stride_count', '条带数目, 用于stride模式,默认为1', 'int optional'),
        #('file', '测试用的文件名字,不提供的话会自动创建', 'optional'),
        ])
    conf = args.parse()
    me = User(conf.user)
    if not me.exists():
        error('user %s not exists' % conf.user)
        sys.exit(-1)
    print "<?xml version='1.0' encoding='UTF-8'?>\n"
    me.get(conf.item)
    print obj2xml(me, 'user')
    sys.exit(0)