Пример #1
0
def main():
    clize.run({
        "start": start,
        "clean": do_clean,
        "list": list_arch,
        "install": install
    })
Пример #2
0
def main():
    subcommands = [runserver, delete_paste]
    subcommand_names = [clize.util.name_py2cli(name)
            for name in clize.util.dict_from_names(subcommands).keys()]
    if len(sys.argv) < 2 or sys.argv[1] not in subcommand_names:
        sys.argv.insert(1, subcommand_names[0])
    clize.run(runserver, delete_paste)
Пример #3
0
def main():
    """Run Erichek.

    Run all modules of Erichek.
    If no errors — validation success,
    Else — exit(1).
    """
    run(clize_log_level, alt=[version, v], exit=False)
    eric_encoding.eric_encoding_summary()
    eric_body.eric_body_summary()
    eric_asterisks.eric_asterisks_summary()
    eric_head.eric_head_summary()

    # If all instead of multiple if and:
    # https://stackoverflow.com/a/9504681/5951529
    if all([
            eric_body.BODY_EXIST, eric_encoding.ENCODING_WINDOWS_1251,
            eric_asterisks.ASTERISKS_EXISTS, eric_head.HEAD_DATA
    ]):
        green_foreground(
            "Congratulations! You haven't errors in your packages!")
        # cprint(figlet_format('\nSuccess', font='starwars'),
        # 'white', 'on_green', attrs=['bold'])
    else:
        red_foreground("You have errors in your packages. Please, fix them.")
        # cprint(figlet_format('\nFailure', font='starwars'),
        # 'yellow', 'on_red', attrs=['bold'])
        exit(1)
Пример #4
0
def main():
    """Run Erichek.

    Run all modules of Erichek.
    If no errors — validation success,
    Else — exit(1).

    [NOTE] Do not use “exit=False” or “exit=True” in “run” function!
    https://github.com/epsy/clize/issues/33#issuecomment-354849918
    If “exit=True”, “erichek” will not work;
    else “exit=False”, all erichek modules will run, if “erichek --version” will run.
    """
    run(clize_log_level, alt=[version], exit=False)
    # If all instead of multiple if and:
    # https://stackoverflow.com/a/9504681/5951529
    if all([
            eric_encoding_summary(),
            eric_body_summary(),
            eric_head_summary(),
            eric_regex_summary()
    ]):
        pyfancy_notice("Congratulations! You haven't errors in your packages!")
        # cprint(figlet_format('\nSuccess', font='starwars'),
        # 'white', 'on_green', attrs=['bold'])
    else:
        pyfancy_error("You have errors in your packages. Please, fix them.")
        # cprint(figlet_format('\nFailure', font='starwars'),
        # 'yellow', 'on_red', attrs=['bold'])
        exit(1)
Пример #5
0
def main():
    # clize.run(install, start, clean, list_arch, test)
    clize.run({
        "start": start,
        "clean": do_clean,
        "list": list_arch,
        "install": install
    })
Пример #6
0
def main():
    """Run the carpyncho CLI interface."""
    cli = CLI(client=Carpyncho())
    commands = tuple(cli.get_commands().values())
    clize.run(
        *commands,
        description=cli.__doc__,
        footnotes=cli.footnotes)
Пример #7
0
def main():
    run(clize_log_level, alt=[version, v], exit=False)
    sashatest.body_check.eric_body_summary()

    if sashatest.body_check.body_test is True:
        log.notice("Success!")
    else:
        log.error("Failure!")
Пример #8
0
 def runner(command_string):
     out, err = StringIO(), StringIO()
     run(
         cli,
         args=tuple(command_string.split()),
         out=out,
         err=err,
         exit=False,
     )
     return out.getvalue(), err.getvalue()
Пример #9
0
def convert_IDT_espec_to_platelibrary_file_cli():

    # This should "just work", with the right function annotations.
    # import fire
    # fire.Fire(convert_idt_coa_to_platelibrary_tsv)

    # defopt:
    # import defopt
    # defopt.run(convert_idt_coa_to_platelibrary_tsv)  # Seems to require docstring parameter type annotations.

    # clize:
    import clize
    clize.run(convert_idt_coa_to_platelibrary_tsv)
Пример #10
0
def main():
    clize.run([config, dump, validate], alt=[version, showid],
              description="""
              Generate an Envoy config, or manage an Ambassador deployment. Use

              ambassador.py command --help

              for more help, or

              ambassador.py --version

              to see Ambassador's version.
              """)
Пример #11
0
def main():
    clize.run([config, dump, validate], alt=[version, showid],
              description="""
              Generate an Envoy config, or manage an Ambassador deployment. Use

              ambassador.py command --help

              for more help, or

              ambassador.py --version

              to see Ambassador's version.
              """)
Пример #12
0
def main():
    subcommands = [
        runserver,
        delete_paste,
        infos,
        set_admin_password,
        clean_expired_pastes,
    ]
    subcommand_names = [
        clize.util.name_py2cli(name)
        for name in clize.util.dict_from_names(subcommands).keys()
    ]
    if len(sys.argv) < 2 or sys.argv[1] not in subcommand_names:
        sys.argv.insert(1, subcommand_names[0])
    clize.run(runserver, delete_paste, infos, set_admin_password,
              clean_expired_pastes)
Пример #13
0
def main():

    function_list = {
        'export-untagged': export_untagged,
        'compute-medians': compute_medians,
        'compute-nest-location': compute_nest_location,
        'compute-measures': compute_measures,
        'workflow-untagged': workflow_untagged,
        'extract-events': extract_events
    }

    run(function_list,
        description="""
    anTraX is a software for high-throughput tracking of color tagged insects, for full documentation, see antrax.readthedocs.io
    
    """)
Пример #14
0
def run_main(argv=None):
    """Overrides argv[0] to be 'improver' then runs main.

    Args:
        argv (list of str):
            Arguments that were from the command line.

    """
    from clize import run
    import sys
    # clize help shows module execution as `python -m improver.cli`
    # override argv[0] and pass it explicitly in order to avoid this
    # so that the help command reflects the way that we call improver.
    if argv is None:
        argv = sys.argv[:]
        argv[0] = 'improver'
    run(main, args=argv)  # pylint: disable=E1124
Пример #15
0
def main():

    function_list = {
        'configure': configure,
        'extract-trainset': extract_trainset,
        'merge-trainset': merge_trainset,
        'graph-explorer': graph_explorer,
        'export-dlc-trainset': export_dlc,
        'export-jaaba': export_jaaba,
        'run-jaaba': run_jaaba,
        'validate': validate,
        'track': track,
        'train': train,
        'classify': classify,
        'solve': solve,
        'exportxy': exportxy,
        'dlc': dlc,
        'pair-search': pair_search,
        'compile': compile_antrax
    }

    # print welcome message
    print('')
    print(
        '=================================================================================='
    )
    print('')
    print(
        'Welcome to anTraX - a software for tracking color tagged ants (and other insects)'
    )
    print('')
    print(
        '=================================================================================='
    )
    print('')

    run(function_list,
        description="""
    anTraX is a software for high-throughput tracking of color tagged insects, for full documentation,
    see antrax.readthedocs.io
    """)
Пример #16
0
def test_with_common_args(mocker):
    mocker.patch('uptime_report.cli.requests_cache')
    mocker.patch('uptime_report.cli.logging')

    cli.logging.ERROR = 'errz'
    cli.logging.DEBUG = 'blabla'
    del cli.logging.SILENCIO

    @cli.with_common_args
    def doit():
        pass

    run(doit, args=('', ), exit=False)

    cli.logging.basicConfig.assert_called_with(level='errz')

    doit(use_cache=True)
    cli.requests_cache.install_cache.assert_called_once()

    cli.requests_cache = None
    doit(use_cache=True)

    run(doit, args=('', '--log-level=debug'), exit=False)

    cli.logging.basicConfig.assert_called_with(level='blabla')

    mock_stderr = StringIO()
    run(doit, args=('', '--log-level=silencio'), exit=False, err=mock_stderr)
    assert 'Invalid log level: silencio' in mock_stderr.getvalue()
Пример #17
0
def main():
    from clize import run

    def _load_cases(*, url=CASES_URL, nocached=False, out=None):
        """Retrieve and store the database as an as CSV file.

        url: str
            The url for the excel table to parse. Default is ivco19 team table.

        out: PATH (default=stdout)
            The output path to the CSV file. If it's not provided the
            data is printed in the stdout.

        nocached:
            If you want to ignore the local cache or retrieve a new value.

        """
        cases = load_cases(url=url, cached=not nocached)
        if out is not None:
            cases.to_csv(out)
        else:
            cases.to_csv(sys.stdout)
    run(_load_cases)
Пример #18
0
from clize import run, parameters


def main(*, listen:('l', parameters.multi(min=1, max=3))):
    """Listens on the given addresses

    :param listen: An address to listen on.
    """
    for address in listen:
        print('Listening on {0}'.format(address))


run(main)
Пример #19
0
def static_entry_point():
    clize.run(static)
Пример #20
0
def main():
    clize.run(runserver)
Пример #21
0
    elif tracks or group:
        method = 'tracks'
    elif tags:
        method = 'tracks'
        opts = {'tags': tags}
    else:
        return
 
    client = soundcloud.Client(client_id='c4c979fd6f241b5b30431d722af212e8')
    if likes or tracks:
        user = likes or tracks
        track = client.get('/resolve', url='https://soundcloud.com/' + user)
        user_id = track.id
        url = '/users/%d/' % user_id
    elif group:
        track = client.get('/resolve', url='https://soundcloud.com/groups/' + group)
        group_id = track.id
        url = '/groups/%d/' % group_id
    else:
        url = '/'
 
    end = '%s%s' % (url, method)
    for i, sound in enumerate(client.get(end, **opts)):
        print("%d Loading %s..." % (i, sound.obj['title']))
        call(['mpc', '-h', '<motdepasse>@entrecote', 'load',
              'soundcloud://url/%s' % sound.obj['permalink_url'].replace('http:', 'https:')])
 
 
if __name__ == '__main__':
    run(sc_load)
Пример #22
0
        initial_epoch=epoch0,
        epochs=epochs,
        verbose=1,
        #         use_multiprocessing=True,
        #         workers=8,
        steps_per_epoch=batches_per_epoch,
        max_queue_size=512,
        shuffle=False,
        validation_data=val_datagen,
        validation_steps=val_batches_per_epoch,
        callbacks=[
            reduce_lr_callback, checkpointer, history_callback,
            viz_pred_callback, viz_grid_callback
        ])

    # Compute total elapsed time for training
    elapsed_train = time() - t0_train
    print("Total runtime: %.1f mins" % (elapsed_train / 60))

    # Save final model
    model.history = history_callback.history
    model.save(os.path.join(run_path, "final_model.h5"))


if __name__ == "__main__":
    # Turn interactive plotting off
    # plt.ioff()

    # Wrapper for running from commandline
    clize.run(train)
Пример #23
0
        else:
            if not packages:
                # Edit conf file directly
                conf = expanduser(os.path.join(root_dir, conf_file))
                cmd = " ".join([os.environ.get('EDITOR'), conf])
                ret = os.system(cmd)
            # Edit the file in cache.
            erase_packages(packages, message=message, conf_file=conf_file, root_dir=root_dir)

        print("Syncing {} packages...".format(pm.lower()))

    if dest:
        # We could be in a venv but in the root of anothe project and still
        # add a package to its requirement, that we give on the cli.
        print("destination to write: ", dest)
        exit

    # Do the job:
    check_conf_dir()
    ret_codes = []
    for _, val in req_files:
        ret_codes.append(sync_packages(val, root_dir=root_dir))

    return reduce(operator.or_, ret_codes, 0)

def run():
    exit(clize.run(main))

if __name__ == "__main__":
    exit(clize.run(main))
Пример #24
0
from . import config
from . import apikeys
import argparse

# Hack: Allow "python -m glitch database" to be the same as "glitch.database"
import sys
if len(sys.argv) > 1 and sys.argv[1] == "database":
	from . import database
	import clize
	sys.exit(clize.run(*database.commands, args=sys.argv[1:]))

import logging
parser = argparse.ArgumentParser(description="Invoke the Infinite Glitch server(s)")
parser.add_argument("server", help="Server to invoke", choices=["main", "renderer", "major_glitch"], nargs="?", default="main")
parser.add_argument("-l", "--log", help="Logging level", type=lambda x: x.upper(),
	choices=logging._nameToLevel, # NAUGHTY
	default="INFO")
parser.add_argument("--dev", help="Dev mode (no logins)", action='store_true')
arguments = parser.parse_args()
log = logging.getLogger(__name__)
logging.basicConfig(level=getattr(logging, arguments.log), format='%(asctime)s:%(levelname)s:%(name)s:%(message)s')

if arguments.server == "renderer":
	from . import renderer
	renderer.run() # doesn't return
elif arguments.server == "major_glitch":
	from . import renderer
	renderer.major_glitch()
	logging.info("Major Glitch built successfully.")
else:
	from . import server
Пример #25
0
                raise 'Et merde!'

        return json.dumps(sources)

    elif choice == 'news':
        return json.dumps(bottom_news)

    elif choice == 'imgur':
        return urllib.urlopen(imgur).read()

    elif choice == 'bottomline':
        return bottom_line[random.randrange(0, len(bottom_line))]


@clize.clize
def start(host="127.0.0.1", port=8000, debug=True):

    if debug is not None:
        _settings.DEBUG = debug

    if _settings.DEBUG:
        bottle.debug(True)
        run(host=host, port=port, reloader=_settings.DEBUG)
    else:
        run(host=host,  port=port, server="cherrypy")


if __name__ == "__main__":
    clize.run(start)

Пример #26
0
        shutil.rmtree(folder)
    prev_scale = scale // 2
    parent_model = os.path.join(
        "results", dataset, "{}x{}".format(prev_scale, prev_scale), "net.th"
    )
    if not os.path.exists(parent_model):
        use_parent = False
    params = dict(
        dataset=dataset,
        folder=folder,
        patch_size=scale,
        nz=nz,
        nb_filters=nb_filters,
        batch_size=batch_size,
        nb_draw_layers=nb_draw_layers,
        device=device,
        resume=resume,
        log_interval=log_interval,
        lr=lr,
        num_workers=num_workers,
        objective=objective,
    )
    if use_parent:
        print("Using parent scale")
        params.update(dict(parent_model=parent_model, freeze_parent=freeze_parent))
    train(**params)


if __name__ == "__main__":
    run([train, train_hierarchical])
Пример #27
0
#!/usr/bin/env python
from clize import run


def add(*text):
    """Adds an entry to the to-do list.

    text: The text associated with the entry.
    """
    return "OK I will remember that."


def list_():
    """Lists the existing entries."""
    return "Sorry I forgot it all :("


if __name__ == '__main__':
    run(add, list_, description="""
        A reliable to-do list utility.

        Store entries at your own risk.
        """)
Пример #28
0
    repository: A directory belonging to the repository to operate on

    branch: The name of the branch to operate on
    """
    return wrapped(*args, branch=get_branch_object(repository, branch), **kwargs)


@with_branch
def diff(*, branch=None):
    """Show the differences between the committed code and the working tree."""
    return "I'm different."


@with_branch
def commit(*text, branch=None):
    """Commit the changes.

    text: A message to store alongside the commit
    """
    return "All saved.: " + " ".join(text)


@with_branch
def revert(*, branch=None):
    """Revert the changes made in the working tree."""
    return "All changes reverted!"


run(diff, commit, revert, description="A mockup version control system(like git, hg or bzr)")
Пример #29
0
    global authors_db
    if not title:
        return None
    if not key:
        return None
    if isbn_10 is None:
        isbn_10 = []
    if isbn_13 is None:
        isbn_13 = []
    if authors is None:
        authors = []
    authors_names = []
    for author in authors:
        author_name = authors_db.get(author, None)
        if author_name:
            authors_names.append(author_name)
    isbns = isbn_10 + isbn_13
    return {"type": "add",
            "id":   key,
            "fields": {
                "title": title,
                "authors": authors_names,
                "isbns": isbns
                        }
            }


# COMMAND LINE INVOCATION
if __name__ == '__main__':
    run((make_author_cache, make_author_cache, prepare_for_amazon, generate_chunks_for_amazon))
Пример #30
0
Файл: cli.py Проект: edk0/cms7
def main():
    run(main_, alt=[compile_theme])
Пример #31
0

def urlize(text, repl):
    return re.sub(r'(https?://[^ ]+)', repl, text)


@clize.clize
def cli_main(src_dir, template_file, fmt='latex'):
    env = jinja2.Environment(
            loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
            block_start_string='@{',
            block_end_string='}@',
            variable_start_string='@{{',
            variable_end_string='}}@')

    template = env.get_template(template_file)

    history = []
    for src_file in sorted(os.listdir(src_dir)):
        filename = os.path.join(src_dir, src_file)
        with codecs.open(filename, encoding='utf-8') as src:
            lines = src.readlines()
            conversation = [line_to_message(line, fmt) for line in lines]
            conversation = [m for m in conversation if m is not None]
            history.append(conversation)
    sys.stdout.write(template.render(history=history))


if __name__ == '__main__':
    clize.run(cli_main)
Пример #32
0
def main(**kwargs):
    """Run the CLI application."""
    run([uptime, outages, write_config], alt=[version, backends], **kwargs)
Пример #33
0
    output_type = output_type.upper()
    pairs_param = json.loads(pairs_param)
    output_prefix = f'{output_dir}/{mosaic_name(pairs_param)}'
    existing_file = glob(f'{output_prefix}*{output_type}.tif')
    print(f'Looking for {output_prefix}*{output_type}.tif')
    if not existing_file:
        pairs = [f'{data_dir}/{pair["left"]}xx{pair["right"]}-median-{output_type}.tif' for pair in pairs_param]
        pairs = [pair for pair in pairs if path.exists(pair)]
        if output_type == 'DEM':
            args = ['dem_mosaic'] + pairs + ['-o', output_prefix]
            args_str = ' '.join(args)
            print(f'running dem_mosaic {args_str}')
            subprocess.run(['dem_mosaic'] + pairs + ['-o', output_prefix])
        elif output_type == 'DRG':
            args = ['otbcli_Mosaic', '-il'] + pairs + ['-out', output_prefix + '-median-DRG.tif']
            args_str = ' '.join(args)
            print(f'running otbcli_Mosaic {args_str}')
            subprocess.run(
                ['otbcli_Mosaic', '-il'] +
                pairs +
                ['-comp.feather', 'slim', '-comp.feather.slim.exponent', '1', '-comp.feather.slim.length', '0.1'] +
                ['-harmo.method', 'band', '-harmo.cost', 'rmse'] +
                ['-nodata', '-9999', '-out', output_prefix + '-median-DRG.tif']
            )
    else:
        print(f'Skipping mosaic generation because {existing_file[0]} already exists')


if __name__ == '__main__':
    run(mosaic_merge)
Пример #34
0
        label.find_element_by_xpath('../../td/input').send_keys(answer)
    driver.find_element_by_name('ok').click()
    driver.find_element_by_link_text('Home').click()

    sleep(1)

    for account_name in [row.find_elements_by_tag_name('td')[0].text.strip() for row in driver.find_element_by_class_name('dataRowBB').find_elements_by_xpath('../../tr')[1:]]:

        driver.find_element_by_link_text(account_name).click()

        recent_table_rows = driver.find_elements_by_css_selector('.recentTransactionsAccountData tr')
        if recent_table_rows:
            if len(recent_table_rows) == 2:
                available_balance = float(recent_table_rows[1].find_element_by_css_selector('td.transactionDataField').text.strip(' -+£'))
            else:
                available_balance = float(recent_table_rows[2].find_element_by_css_selector('td.transactionDataField').text.strip(' -+£'))
        else:
            available_balance = float(driver.find_elements_by_css_selector('td.transactionDataField')[1].text.strip(' -+£'))
        balance_datum = {
            'account_name': account_name,
            'balance': available_balance,
            '@timestamp': datetime.now()
        }
        print(balance_datum)
        elastic.index(index='lifestat', doc_type='balance', body=balance_datum)
        driver.find_element_by_link_text('Home').click()

                        
if __name__ == '__main__':
    clize.run(coop)
Пример #35
0
            dest_path=experiment_dest_path,
            n_classes=n_classes,
            use_ensemble=use_ensemble,
            ensemble_copies=ensemble_copies,
            voting=voting,
            noise=post_noise,
            noise_sets=post_noise_sets,
            noise_params=noise_params,
            batch_size=batch_size,
            seed=experiment_id)

        tf.keras.backend.clear_session()

    artifacts_reporter.collect_artifacts_report(experiments_path=dest_path,
                                                dest_path=dest_path,
                                                use_mlflow=use_mlflow)
    if Splits.GRIDS in data_file_path:
        fair_report_path = os.path.join(dest_path, Experiment.REPORT_FAIR)
        artifacts_reporter.collect_artifacts_report(experiments_path=dest_path,
                                                    dest_path=fair_report_path,
                                                    filename=Experiment.INFERENCE_FAIR_METRICS,
                                                    use_mlflow=use_mlflow)
    if use_mlflow:
        mlflow.set_experiment(experiment_name)
        mlflow.log_artifacts(dest_path, artifact_path=dest_path)
        shutil.rmtree(dest_path)


if __name__ == '__main__':
    clize.run(run_experiments)
Пример #36
0
def main():
    logging.basicConfig(level=logging.INFO)
    run(main_, alt=[compile_theme])
Пример #37
0
def conf_entry_point():
    clize.run(conf)
Пример #38
0
				cols = {row[0] for row in cur}
				is_new = not cols
				continue
			# Otherwise, it should be a column definition, starting (after whitespace) with the column name.
			colname, defn = line.strip().split(" ", 1)
			if colname in cols:
				# Column already exists. Currently, we assume there's nothing to change.
				cols.remove(colname)
			else:
				# Column doesn't exist. Add it!
				# Note that we include a newline here so that a comment will be properly terminated.
				# If you look at the query, it'll have all its commas oddly placed, but that's okay.
				coldefs.append("%s %s\n"%(colname,defn))
		finish()
	if not confirm: print("Add --confirm to actually make the changes.")

@cmdline
def testfiles():
	"""Test all audio files"""
	import pyechonest.track
	for file in get_many_mp3(status=0):
		if file.track_details['length'] < 700:
			print("Name: {} Length: {}".format(file.filename, file.track_details['length']))
			# TODO: Should this be pyechonest.track.track_from_filename?
			track = track.track_from_filename('audio/'+file.filename, force_upload=True)
			print(track.id)
		else:
			print("BIG ONE - Name: {} Length: {}".format(file.filename, file.track_details['length']))

if __name__ == "__main__": clize.run(*commands)
Пример #39
0
            #e3 = torch.abs(a2).mean()
            loss = e1
            loss.backward()
            optim.step()
            #for p in params:
            #    p.data -= lr * p.mem
            if nb_updates % 100 == 0:
                print('loss : %.3f %.3f %.3f' % (e1.data[0], e2.data[0], e3.data[0]))
                
                active = (hid.data>0).float().sum(1)
                print('nbActive : {:.4f} +- {:.4f}'.format(active.mean(), active.std()))
                im = Xrec.data.cpu().numpy()
                im = im.reshape(im.shape[0], c, h, w)
                im = grid_of_images_default(im, normalize=True)
                imsave('x.png', im)

                im = w1.data.cpu().numpy()
                im = im.reshape((c, h, w, z1)).transpose((3, 0, 1, 2))
                im = grid_of_images_default(im, normalize=True)
                imsave('w1.png', im)
                """
                im = wx_2.data.cpu().numpy()
                im = im.reshape((c, h, w, z2)).transpose((3, 0, 1, 2))
                im = grid_of_images_default(im, normalize=True)
                imsave('w2.png', im)
                """

            nb_updates += 1

run(train)
Пример #40
0
    branch: The name of the branch to operate on
    """
    return wrapped(
        *args, branch=get_branch_object(repository, branch), **kwargs)


@with_branch
@autokwoargs
def diff(branch=None):
    """Show the differences between the committed code and the working tree."""
    return "I'm different."

@with_branch
@autokwoargs
def commit(branch=None, *text):
    """Commit the changes.

    text: A message to store alongside the commit
    """
    return "All saved.: " + ' '.join(text)

@with_branch
@autokwoargs
def revert(branch=None):
    """Revert the changes made in the working tree."""
    return "There is no chip, John."

run(diff, commit, revert,
    description="A mockup version control system(like git, hg or bzr)")
Пример #41
0
                'Do not sent any email to {}'.format(present_from)
            )
            continue

        send_mail(**kwargs)


def local_handler(settings_file, *, apply=False, verbose=False):
    """
    Random drawing in a group to designate who will receive a gift.

    :param settings_file: settings file to load
    :param apply: Send emails to recipients
    :param verbose: Increase output verbosity
    """

    global settings

    settings = __import__(settings_file.split('.py')[0])
    for item in settings.PEOPLE:
        assert isinstance(item[0], tuple)
        assert isinstance(item[1], tuple)

    logger.setLevel(level=logging.DEBUG if verbose else logging.INFO)

    main(apply=apply)


if __name__ == '__main__':
    run(local_handler)
Пример #42
0
from clize import run

VERSION = "0.2"


def do_nothing():
    """Does nothing"""
    return "I did nothing, I swear!"


def version():
    """Show the version"""
    return 'Do Nothing version {0}'.format(VERSION)


run(do_nothing, alt=version)
Пример #43
0
from clize import run


VERSION = "0.2"


def do_nothing():
    """Does nothing"""
    return "I did nothing, I swear!"


def version():
    """Show the version"""
    return 'Do Nothing version {0}'.format(VERSION)


run(do_nothing, alt=version)
Пример #44
0
                raise 'Et merde!'

        return json.dumps(sources)

    elif choice == 'news':
        return json.dumps(bottom_news)

    elif choice == 'imgur':
        #return urllib.urlopen(imgur).read()
        pass

    elif choice == 'bottomline':
        return bottom_line[random.randrange(0, len(bottom_line))]


@clize.clize
def start(host="0.0.0.0", port=9009, debug=True):

    if debug is not None:
        _settings.DEBUG = debug

    if _settings.DEBUG:
        bottle.debug(True)
        run(host=host, port=port, reloader=_settings.DEBUG)
    else:
        run(host=host, port=port, server="cherrypy")


if __name__ == "__main__":
    clize.run(start)
Пример #45
0
def echo(reverse=False, *text):
    """Echoes text back

    reverse: reverse the text before echoing back?

    text: the text to echo back"""
    text = ' '.join(text)
    if reverse:
        text = text[::-1]
    print(text)


@clize(require_excess=False)
def shout(*text):
    """Echoes text back, but louder.

    text: the text to echo back

    Who shouts backwards anyway?"""

    print(' '.join(text).upper())

if __name__ == '__main__':
    run(
        (echo, shout),
        description="""\
        A collection of commands for eching text back""",
        footnotes="""\
        Now you know how to echo text back""",
        )
Пример #46
0

@decorator
def with_uppercase(wrapped, *args, uppercase=False, **kwargs):
    """
    Formatting options:

    :param uppercase: Print output in capitals
    """
    ret = wrapped(*args, **kwargs)
    if uppercase:
        return str(ret).upper()
    else:
        return ret


@with_uppercase
def hello_world(name=None):
    """Says hello world

    :param name: Who to say hello to
    """
    if name is not None:
        return 'Hello ' + name
    else:
        return 'Hello world!'


if __name__ == '__main__':
    run(hello_world)
Пример #47
0
import re
import clize
import sys

@clize.clize()
def main(active=0):
	"""Activate or deactivate bBox wifi.

    activate: 0 or 1 (0 by default)
    	0 = deactivate
    	1 = activate
    """
	if(active in (0,1)):
		pass
	else:
		print("active must be 0 or 1")
		sys.exit()

	connexion = urllib3.PoolManager()

	r = connexion.request('GET', 'http://192.168.1.254/novice/index.htm')

	token = re.search(r'\w{8}', re.search(r"var token = eval\(\\'\( \"\w{8}\" \)\\'\);", str(r.data)).group()).group()

	values = {'token': token, 'write': 'WLANConfig_RadioEnable:' + str(active)}

	p = connexion.request('POST', 'http://192.168.1.254/cgi-bin/generic.cgi', fields=values)
 
if __name__ == "__main__":
    clize.run(main)
    return new_img


def main(*text, font_size: 's'=13, edge_len: 'e'=50, wall_width: 'w'=20,  wall_length: 'l'=10, pic_dir: 'd'="./img",
         out_dir: 'o'="./out/", font_path: 'p'='./demo.ttf', method: 'm'='alpha'):
    """生成照片墙"""
    if len(text) >= 1:
        text_ = ' '.join(text)
        print(f"generate text wall for '{text_}' with picture path:{pic_dir}")
        if method not in effects_func.keys():
            raise Exception(f'param method[-m {method}] not defined! accept method is: size, alpha')
        text_img = gen_text_img(text_, font_size, font_path)
        img_ascii = picture_wall_mask(text_img, edge_len, pic_dir, method)
        img_ascii.show()
        img_ascii.save(out_dir + os.path.sep + '_'.join(text) + '.png')
    else:
        print(f"generate rectangle wall with picture path:{pic_dir}")
        img_rec = picture_wall_rectangle(wall_width, wall_length, edge_len, pic_dir)
        img_rec.show()
        img_rec.save(out_dir + os.path.sep + 'img_rec.png')


if __name__ == '__main__':
    run(main)
    pass





Пример #49
0
    # create DB tables if needed
    db.create_tables([Site, Comment], safe=True)

    # delete site record
    try:
        site = Site.select().where(Site.name == site_name).get()
        site.delete_instance(recursive=True)
    except Site.DoesNotExist:
        pass

    site = Site.create(name=site_name, url=url, token=salt(url), 
                       admin_email=admin_email)

    for dirpath, dirs, files in os.walk(comment_dir):
        for filename in files:
            if filename.endswith(('.md',)):
                comment_file = '/'.join([dirpath, filename])
                convert_comment(db, site, url, comment_file)
            else:
                logger.warn('ignore file %s' % filename)


@clize
def pecosys2stacosys(site, url, admin_email, comment_dir):
    convert(site, url, admin_email, comment_dir)


if __name__ == '__main__':
    run(pecosys2stacosys)
Пример #50
0
        ddi['Time'] = ddi['spacing']
        ddi['Unit'] = ddi['unit']

        if flavour == 'harmful':
            ddi['DDI Type'] = 'bad' if ddi[flavour] else 'good'
        if flavour == 'agonism':
            ddi['DDI Type'] = 'agonism' if ddi[flavour] else 'antagonism'

        writer.writerow({k: ddi[k] for k in fieldnames})


def block_until_chiron():
    goes = 10
    while goes:
        try:
            sock = socket.socket()
            time.sleep(1)
            sock.connect(('chiron', 3030))
        except Exception:
            goes -= 1
            continue
        else:
            return

    sys.exit(1)


if __name__ == '__main__':
    block_until_chiron()
    clize.run(main)
Пример #51
0
def main():
    clize.run(attach, start, plugin)
Пример #52
0
from sigtools.modifiers import kwoargs
from clize import run

@kwoargs('no_capitalize') # turns no_capitalize into a keyword-only parameter
                          # on Python 2
def hello_world(name=None, no_capitalize=False):
    """Greets the world or the given name.

    name: If specified, only greet this person.

    no_capitalize: Don't capitalize the given name.
    """
    if name:
        if not no_capitalize:
            name = name.title()
        return 'Hello {0}!'.format(name)
    return 'Hello world!'

if __name__ == '__main__':
    run(hello_world)
Пример #53
0
Файл: echo.py Проект: epsy/clize
from clize import ArgumentError, Parameter, run

def echo(*text:Parameter.REQUIRED,
         prefix:'p'='', suffix:'s'='', reverse:'r'=False, repeat:'n'=1):
    """Echoes text back

    :param text: The text to echo back
    :param reverse: Reverse text before processing
    :param repeat: Amount of times to repeat text
    :param prefix: Prepend this to each line in word
    :param suffix: Append this to each line in word
    """
    text = ' '.join(text)
    if 'spam' in text:
        raise ArgumentError("I don't want any spam!")
    if reverse:
        text = text[::-1]
    text = text * repeat
    if prefix or suffix:
        return '\n'.join(prefix + line + suffix
                         for line in text.split('\n'))
    return text

def version():
    """Show the version"""
    return 'echo version 0.2'

if __name__ == '__main__':
    run(echo, alt=version)
Пример #54
0
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
from clize import clize, run


@clize
def pecosys_server(config_pathname, no_git=False):

    os.environ['CONFIG_PATHNAME'] = config_pathname
    if no_git:
        os.environ['NO_GIT'] = str(no_git)
    else:
        os.environ['NO_GIT'] = ''

    from pecosys import app
    app.run(host=app.config['pecosys']['post']['host'], port=app.config['pecosys']['post']['port'],
            debug=True, use_reloader=False)

if __name__ == '__main__':
    run(pecosys_server)
Пример #55
0
def run():
    exit(clize.run(main))
Пример #56
0
def main():
    clize.run(_main)
Пример #57
0
def main():
    clize.run(runserver)
Пример #58
0
    # :param east: Eastern limit of the box, in -180 to 180 longitude, positive east
    # :param south: Southern limit of the box, in -90 to 90 latitude, positive north
    # :param north: Northern limit of the box, in -90 to 90 latitude, positive north
    :param plot: Whether to plot the footprints of the selected images
    :param find_covering: Whether to search for a minimal set of pairs covering the bounding box. Otherwise, outputs all
    pairs that have good sun and spacecraft geometry.
    :return: A StereoPairSet
    """

    search_poly_shapely = geom_helpers.corners_to_quadrilateral(west, east, south, north, lonC0=True)
    imgs = ImageSearch(polygon=wkt.dumps(search_poly_shapely))
    pairset = StereoPairSet(imgs)
    filtered_pairset = pairset.filter_sun_geometry().filter_small_overlaps()
    if find_covering:
        search_poly_shapely = wkt.loads(imgs.search_poly)
        filtered_pairset.pairs, stats = geom_helpers.covering_set_search(
            full_poly_set=filtered_pairset.pairs,
            search_poly=search_poly_shapely,
            plot=plot,
            verbose=False
        )
    print(filtered_pairset.pairs_json())
    if return_pairset:
        return filtered_pairset


if __name__ == '__main__':
    import clize, json

    clize.run(bounding_box, alt=trajectory)
Пример #59
0
Файл: main.py Проект: lowks/spy
def main():
    run(_main)