Example #1
0
def samples(
    context: click.Context,
    identifiers: click.Tuple([str, str]),
    kwargs: click.Tuple([str, str]),
    skip_lims: bool,
    yes: bool,
    case_id: str,
):
    """Set values on many samples at the same time"""
    store: Store = context.obj.status_db
    sample_objs = _get_samples(case_id=case_id,
                               identifiers=identifiers,
                               store=store)

    if not sample_objs:
        LOG.error("No samples to alter!")
        context.abort()

    LOG.info("Would alter samples:")

    for sample_obj in sample_objs:
        LOG.info(f"{sample_obj}")

    if not (yes or click.confirm(CONFIRM)):
        raise click.Abort

    for sample_obj in sample_objs:
        context.invoke(sample,
                       sample_id=sample_obj.internal_id,
                       kwargs=kwargs,
                       yes=yes,
                       skip_lims=skip_lims)
Example #2
0
def click_type(object: typing.Union[type, tuple],
               default=None) -> typing.Union[type, click.types.ParamType]:
    """Translate python types to click's subset of types."""
    if isinstance(object, typing._GenericAlias):
        return click_type(object.__args__[0], default)
    elif isinstance(object, type):
        if issubclass(object, datetime.datetime):
            return click.DateTime()
        if issubclass(object, typing.Tuple):
            return click.Tuple(object.__args__)
        if issubclass(object, uuid.UUID):
            return click.UUID(default)
        if object is list:
            return
        if issubclass(object, set):
            return click.Choice(object)

        if issubclass(object, pathlib.Path):
            return click.Path()
        if object in {builtins.object, typing.Any}:
            return
        return object
    else:
        if isinstance(object, tuple):
            if all(isinstance(x, int) for x in object[:2]):
                return click.IntRange(*object)
            if all(isinstance(x, float) for x in object[:2]):
                return click.FloatRange(*object)
Example #3
0
def get_arguments() -> True:
    """
    Get arguments from command line
    :return: True
    """
    @click.group(help='CLI for Learn_Pygame')
    @click.option('--n_moving_items',
                  '-n',
                  default=100,
                  type=click.IntRange(1, 1e4),
                  help='Number of moving items. Default: 100, Range: [1,1e4]')
    @click.option(
        '--size_field',
        '-sz',
        nargs=2,
        default=(500, 500),
        type=click.Tuple([click.IntRange(1, 5000),
                          click.IntRange(1, 5000)]),
        help='X, Y size of the field. ' + 'Default: [50,50], Range: [1...5000]'
    )
    @click.pass_context
    def cli(ctx, n_moving_items, size_field):
        """CLI for Learn_Pygame"""
        ctx.obj['n_moving_items'] = n_moving_items
        ctx.obj['size_field'] = size_field

    @cli.command('run')
    @click.pass_context
    def run_game(ctx):
        """Start the game"""
        start_game(ctx.obj['n_moving_items'], ctx.obj['size_field'])

    cli(obj={})
    return True
Example #4
0
def cases(
        context: click.Context,
        dry_run: bool,
        identifiers: click.Tuple([str, str]),
):
    """Delete many cases of samples at the same time"""
    store = context.obj.status_db
    _cases = _get_cases(identifiers, store)

    if not _cases:
        LOG.error("No cases to delete!")
        raise click.Abort

    if dry_run:
        LOG.info("Cases (that will NOT be deleted due to --dry-run):")
    else:
        LOG.info("Would DELETE cases:")

    for _case in _cases:
        LOG.info(_case)

    if not (click.confirm(CONFIRM)):
        raise click.Abort

    for _case in _cases:
        context.invoke(
            case,
            case_id=_case.internal_id,
            dry_run=dry_run,
        )
def _get_param_type_from_str(
    type_name: str = None,
    param_doc: docstring_parser.DocstringParam = None,
) -> t.Tuple[_ParamArgs, t.Union[click.ParamType, None]]:
    """Guess parameter type from parameter type name."""
    type_name = type_name or ""
    desc = param_doc.description if param_doc else ""
    if type_name == "int":
        return _ParamArgs.single, int
    elif type_name == "float":
        return _ParamArgs.single, float
    elif type_name == "bytes":
        return _ParamArgs.single, bytes
    elif type_name == "bool":
        return _ParamArgs.flag, None
    elif type_name[:4] == "list":
        args, element = _get_param_type_from_str(type_name[5:-1], param_doc)
        assert args is _ParamArgs.single
        return _ParamArgs.multiple, element
    elif type_name[:5] == "tuple":
        els = (_get_param_type_from_str(n)[1]
               for n in type_name[6:-1].split(", "))
        return _ParamArgs.single, click.Tuple(els)
    elif type_name == "io.FileIO":
        return _ParamArgs.single, _build_file_param_type(desc)
    elif type_name == "pathlib.Path":
        return _ParamArgs.single, _build_path_param_type(desc)
    elif type_name == "datetime.datetime":
        return _ParamArgs.single, click.DateTime()
    elif type_name == "uuid.UUID":
        return _ParamArgs.single, click.UUID
    else:
        logger.warning("Cannot guess parameter type from name: %s", type_name)
    return _ParamArgs.single, None
Example #6
0
def families(
        context: click.Context,
        action: Optional[str],
        priority: Optional[Priority],
        panels: Optional[Tuple[str]],
        customer_id: Optional[str],
        identifiers: click.Tuple([str, str]),
):
    """Set values on many families at the same time"""
    store: Store = context.obj.status_db
    cases: List[models.Family] = _get_cases(identifiers, store)

    if not cases:
        LOG.error("No cases to alter!")
        raise click.Abort

    LOG.info("Would alter cases:")

    for case in cases:
        LOG.info(case)

    if not (click.confirm(CONFIRM)):
        raise click.Abort

    for case in cases:
        context.invoke(
            family,
            action=action,
            priority=priority,
            panels=panels,
            family_id=case.internal_id,
            customer_id=customer_id,
        )
Example #7
0
def click_type(object: typing.Union[type, tuple],
               default=None) -> typing.Union[type, click.types.ParamType]:
    if isinstance(object, type):
        if issubclass(object, datetime.datetime):
            return click.DateTime()
        if issubclass(object, typing.Tuple):
            return click.Tuple(object.__args__)
        if issubclass(object, uuid.UUID):
            return click.UUID(default)
        if object is list:
            return
        if issubclass(object, typing.List):
            return click_type(object.__args__[0], default)
        if issubclass(object, set):
            return click.Choice(object)

        if issubclass(object, pathlib.Path):
            return click.Path()
        return object
    else:
        if isinstance(object, tuple):
            if all(isinstance(x, int) for x in object[:2]):
                return click.IntRange(*object)
            if all(isinstance(x, float) for x in object[:2]):
                return click.FloatRange(*object)
Example #8
0
def _get_samples_by_identifiers(identifiers: click.Tuple([str, str]),
                                store: Store) -> List[models.Sample]:
    """Get samples matched by given set of identifiers"""
    identifier_args = {
        identifier_name: identifier_value
        for identifier_name, identifier_value in identifiers
    }

    return list(store.samples_by_ids(**identifier_args))
Example #9
0
    def test_defaults(self):
        """Validate formatting of user documented defaults."""
        @click.command()
        @click.option('--num-param', type=int, default=42, show_default=True)
        @click.option(
            '--param',
            default=lambda: None,
            show_default='Something computed at runtime',
        )
        @click.option(
            '--group',
            default=[('foo', 'bar')],
            nargs=2,
            type=click.Tuple([str, str]),
            multiple=True,
            show_default=True,
        )
        @click.option(
            '--only-show-default',
            show_default="Some default computed at runtime!",
        )
        def foobar(bar):
            """A sample command."""
            pass

        ctx = click.Context(foobar, info_name='foobar')
        output = list(ext._format_command(ctx, nested='short'))

        self.assertEqual(
            textwrap.dedent("""
        A sample command.

        .. program:: foobar
        .. code-block:: shell

            foobar [OPTIONS]

        .. rubric:: Options

        .. option:: --num-param <num_param>

            :default: 42

        .. option:: --param <param>

            :default: Something computed at runtime

        .. option:: --group <group>

            :default: ('foo', 'bar')

        .. option:: --only-show-default <only_show_default>

            :default: Some default computed at runtime!
        """).lstrip(),
            '\n'.join(output),
        )
Example #10
0
def test_nargs_tup_composite(runner):
    variations = [
        dict(type=(str, int)),
        dict(type=click.Tuple([str, int])),
        dict(nargs=2, type=click.Tuple([str, int])),
        dict(nargs=2, type=(str, int)),
    ]

    for opts in variations:

        @click.command()
        @click.argument("item", **opts)
        def copy(item):
            click.echo("name={0[0]} id={0[1]:d}".format(item))

        result = runner.invoke(copy, ["peter", "1"])
        assert not result.exception
        assert result.output.splitlines() == ["name=peter id=1"]
Example #11
0
def init():
    """Return top level command handler"""
    @click.command()
    @click.option('--cell',
                  required=True,
                  envvar='TREADMILL_CELL',
                  callback=cli.handle_context_opt,
                  expose_value=False)
    @click.option('--monitor',
                  nargs=2,
                  type=click.Tuple([str, int]),
                  multiple=True,
                  required=True)
    @click.option('--once', help='Run once.', is_flag=True, default=False)
    @click.option('--interval',
                  help='Wait interval between checks.',
                  default=_DEFAULT_INTERVAL)
    @click.argument('name')
    def controller(monitor, once, interval, name):
        """Control app monitors across cells"""
        monitors = list(monitor)

        while True:

            intended_total = 0
            actual_total = 0
            intended = 0

            for cellname, count in monitors:
                if cellname == context.GLOBAL.cell:
                    intended = count
                else:
                    actual = _count(cellname, name)

                    _LOGGER.info('state for cell %s, actual: %s, intended: %s',
                                 cellname, actual, count)

                    intended_total += count
                    actual_total += actual

            missing = intended_total - actual_total

            # If there are missing instances, start them locally. If there are
            # extra instances (missing < 0) just keep the indended state for
            # the cell.
            my_count = intended + max(0, missing)
            _LOGGER.info('intended: %s, actual: %s, missing: %s, my count: %s',
                         intended_total, actual_total, missing, my_count)

            _configure_monitor(name, my_count)

            if once:
                break

            time.sleep(utils.to_seconds(interval))

    return controller
Example #12
0
def _get_cases(identifiers: click.Tuple([str, str]),
               store: Store) -> [models.Family]:
    """Get cases that have samples that match identifiers if given"""
    samples_by_id = _get_samples_by_identifiers(identifiers, store)
    _cases = set()
    for sample in samples_by_id:

        for link in sample.links:
            _cases.add(link.family)

    return _cases
Example #13
0
def _get_cases(identifiers: click.Tuple([str, str]), store: Store) -> List[
        models.Family]:
    """Get cases that have samples that match identifiers if given"""
    samples_by_id: List[models.Sample] = _get_samples_by_identifiers(
        identifiers, store)
    cases: Set[models.Family] = set()
    for sample in samples_by_id:
        for link in sample.links:
            cases.add(link.family)

    return list(cases)
Example #14
0
def test_nargs_tup_composite(runner):
    variations = [
        dict(type=(str, int)),
        dict(type=click.Tuple([str, int])),
        dict(nargs=2, type=click.Tuple([str, int])),
        dict(nargs=2, type=(str, int)),
    ]

    for opts in variations:

        @click.command()
        @click.argument('item', **opts)
        def copy(item):
            click.echo('name=%s id=%d' % item)

        result = runner.invoke(copy, ['peter', '1'])
        assert not result.exception
        assert result.output.splitlines() == [
            'name=peter id=1',
        ]
Example #15
0
def d_reduce_options(f):
    """Create common options for dimensionality reduction"""
    f = click.option('--axes', nargs=2, type=click.Tuple([int, int]),
                     help='Plot the projection along which projection axes.',
                     default=[0, 1])(f)
    f = click.option('--dimension', '-d',
                     help='Number of the dimensions to keep in the output XYZ file.',
                     default=10)(f)
    f = click.option('--scale/--no-scale',
                     help='Standard scaling of the coordinates.',
                     default=True)(f)
    return f
Example #16
0
File: cli.py Project: basecue/cd
def debug_option(func):
    @wraps(func)
    def debug_wrapper(debug, **kwargs):
        if debug:
            DebugSettings.settings = DebugSettings(dict(debug))

        return func(**kwargs)

    return click.option('--debug',
                        type=click.Tuple([str, str]),
                        multiple=True,
                        metavar='<variable> <value>',
                        help='Debug options.')(debug_wrapper)
Example #17
0
def _get_samples(case_id: str, identifiers: click.Tuple([str, str]),
                 store: Store) -> List[models.Sample]:
    """Get samples that match both case_id and identifiers if given"""
    samples_by_case_id = None
    samples_by_id = None

    if case_id:
        samples_by_case_id = _get_samples_by_case_id(case_id, store)

    if identifiers:
        samples_by_id = _get_samples_by_identifiers(identifiers, store)

    if case_id and identifiers:
        sample_objs = set(set(samples_by_case_id) & set(samples_by_id))
    else:
        sample_objs = samples_by_case_id or samples_by_id

    return sample_objs
Example #18
0
def common_options(f):
    options = [
        click.option('-d',
                     '--debug',
                     envvar="CLOUDCTL_DEBUG",
                     show_default=True,
                     is_flag=True,
                     help='Enable debug mode'),
        click.option('--dry-run',
                     envvar="CLOUDCTL_DRY_RUN",
                     show_default=True,
                     is_flag=True,
                     help='Dry Run mode'),
        click.option('-a',
                     '--auto-approve',
                     envvar="CLOUDCTL_AUTO_APPROVE",
                     show_default=True,
                     is_flag=True,
                     help='Auto Approve operation'),
        click.option('-c',
                     '--cloud',
                     type=click.Choice(['aws', 'gcp', 'azure'],
                                       case_sensitive=False),
                     envvar="CLOUDCTL_CLOUD",
                     default='aws',
                     show_default=True,
                     help='Cloud provider to query'),
        click.option('-t',
                     '--tags',
                     multiple=True,
                     type=click.Tuple([str, str]),
                     help='Query resources by tags'),
        click.option('-r',
                     '--role',
                     multiple=False,
                     type=str,
                     help='Query resource by role Tag'),
    ]
    return functools.reduce(lambda x, opt: opt(x), options, f)
def _get_param_type_from_generic(
    param_hint,
    param_doc: docstring_parser.DocstringParam = None,
) -> t.Tuple[_ParamArgs, t.Union[click.ParamType, None]]:
    """Guess parameter type from parameter type-hint generic."""
    desc = param_doc.description if param_doc else ""
    if issubclass(param_hint.__origin__, list):
        args, element = _get_param_type(param_hint.__args__[0], param_doc)
        assert args is _ParamArgs.single
        return _ParamArgs.multiple, element
    elif issubclass(param_hint.__origin__, tuple):
        elements = (_get_param_type(p)[1] for p in param_hint.__args__)
        return _ParamArgs.single, click.Tuple(elements)
    elif issubclass(param_hint.__origin__, io.FileIO):
        return _ParamArgs.single, _build_file_param_type(desc)
    elif issubclass(param_hint.__origin__, pathlib.Path):
        return _ParamArgs.single, _build_path_param_type(desc)
    elif issubclass(param_hint.__origin__, datetime.datetime):
        return _ParamArgs.single, click.DateTime()
    elif issubclass(param_hint.__origin__, uuid.UUID):
        return _ParamArgs.single, click.UUID
    logger.warning("Cannot guess parameter type from generic: %s", param_hint)
    return _ParamArgs.single, None
Example #20
0
                               collect_authors=True,
                               attachments_path=attachments_path)
    project = _dumps(project, fmt=format)
    if out_file:
        LOG.info('writing export to %s', out_file)
        with codecs.open(out_file, 'wb', encoding='utf-8') as out_f:
            out_f.write(project)
    else:
        click.echo(project)


@cli.command()
@click.option(
    '-u',
    '--umap',
    type=click.Tuple([str, str]),
    nargs=2,
    multiple=True,
    help='Mapping from a Trac username to a GitLab username',
)
@click.option(
    '--umap-file',
    type=click.Path(exists=True, readable=True),
    multiple=True,
    help=
    'Additional file to be read for user mappings ([tracboat.usermap] section in toml format)',
)
@click.option(
    '--fallback-user',
    default='*****@*****.**',
    show_default=True,
Example #21
0
    return kwik_path


@click.command()
@click.argument(
    'prm_file',
    type=click.Path(exists=True, file_okay=True, dir_okay=False),
)
@click.option(
    '--output-dir',
    type=click.Path(file_okay=False, dir_okay=True),
    help='Output directory.',
)
@click.option(
    '--interval',
    type=click.Tuple([float, float]),
    help='Interval in seconds, e.g. `--interval 0 2`.',
    default=(None, None),
)
@click.option(
    '--channel-group',
    type=click.INT,
    help='Channel group to cluster (all by default).',
)
@click.option(
    '--detect-only',
    help='Only do spike detection.',
    default=False,
    is_flag=True,
)
@click.option(
Example #22
0
def print_tiles(ctx, param, value):
    if value:
        processor = TileProcessor(Config(ctx.params['config']))
        processor.print_tiles_to_process()
        ctx.exit()


@click.command()
@click.option('--config', help='The config file')
@click.option('--retile',
              is_flag=True,
              callback=print_tiles,
              help='Identify tiles to be computed for a new run')
@click.option('--tile',
              nargs=2,
              type=click.Tuple([int, int]),
              help='The tile index')
@click.option('--log', help='The log file')
@click.option('--jobid', help='Optional Job ID')
def main(config, retile, tile, log, jobid):
    if config:
        cfg = Config(config)
    else:
        cfg = Config(
            '/g/data/u46/users/aj9439/wofs/configs/template_client.yaml')
    if log:
        logging.basicConfig(filename=log, level=logging.INFO)
    else:
        logging.basicConfig(filename=cfg.cfg['logs']['path'] +
                            '/confidence.log',
                            level=logging.INFO)
Example #23
0
"""

import click
from flask.cli import with_appcontext

from .api_functions import create_predictions, select_list
from ..database import manage_db


@click.command("construct")
@click.option("-n", "--name")
@click.option("-d", "--description")
@click.option("-e",
              "--event",
              nargs=2,
              type=click.Tuple([str, float]),
              multiple=True)
@with_appcontext
def construct_command(name, description, event):
    """ Create a new prediction """
    prediction = {}

    if name:
        prediction["name"] = name
    else:
        prediction["name"] = click.prompt("Name of the prediction ", type=str)

    if description:
        prediction["description"] = description
    else:
        prediction["description"] = click.prompt(
Example #24
0
    "--tcp-server",
    help="websocket url with username and password",
    required=True,
)
@click.option(
    "-R",
    "--rulefile",
    "rulefiles",
    multiple=True,
    type=click.Path(exists=True, dir_okay=False),
    help="rule file absolute path",
)
@click.option(
    "-NS", "--nameserver", "nameservers", multiple=True, help="set dns servers"
)
@click.argument("address", type=click.Tuple([str, int]), default=("127.0.0.1", 3128))
def client(
    proxy_policy: Literal["AUTO", "PROXY", "DIRECT", "BLACK", "WHITE"],
    rulefiles: typing.List[str],
    tcp_server: str,
    nameservers: typing.List[str],
    address: typing.Tuple[str, int],
):
    FilterRule(rulefiles)
    Client(
        client_host=address[0],
        client_port=address[1],
        tcp_server=tcp_server,
        nameservers=nameservers,
        proxy_policy=proxy_policy,
    ).run()
Example #25
0
@click.option(
    '--gsize',
    type=click.INT,
    help='Number of genes per genome (see it as the number of simulations)')
@click.option(
    '--edprob',
    default=0.1,
    type=isProb,
    help=
    'RNA editing probability at a random site, per genome. The number of edited site is a taken from a normal distribution '
)
@click.option(
    '--glen_range',
    default=(200, 500),
    nargs=2,
    type=click.Tuple([int, int]),
    help='Min and Max length (as number of AA) of each coding gene of genomes')
@click.option('--dnds',
              default=(0.5, 1),
              nargs=2,
              type=click.Tuple([float, float]),
              help='Rate of synonymous and nonsynonymous changes (dN, dS)')
@click.option('--tau', type=click.FLOAT, help='Transition / Transversion rate')
@click.option(
    '--delrate',
    type=isProb,
    help=
    'Sequence random deletion rate for codons (Pyvolve does not allow indel, so this randomly choose some position of the alignment then delete the amino acid.'
)
@click.option('--from_al',
              type=click.Path(exists=True),
Example #26
0
@click.option('--local',
              'coords',
              flag_value=Local(),
              help='Local (cartesian) mapping.',
              type=CoordsType())
@click.option('--global',
              'coords',
              flag_value=Geocentric(),
              help='Global (spherical) mapping.',
              type=CoordsType())
@click.option('--coords', default=Local(), type=CoordsType())
@click.option('--in-coords',
              'input_coords',
              nargs=2,
              multiple=True,
              type=click.Tuple([str, CoordsType()]))
# Logging and verbosity
@click.option('--debug', 'verbosity', flag_value='debug')
@click.option('--info', 'verbosity', flag_value='info', default=True)
@click.option('--user', 'verbosity', flag_value='user')
@click.option('--warning', 'verbosity', flag_value='warning')
@click.option('--error', 'verbosity', flag_value='error')
@click.option('--rich/--no-rich', default=True)
# Filenames
@click.argument('infile', type=str, required=True)
@click.argument('outfile', type=str, required=False)
@click.pass_context
@suppress_warnings
def convert(ctx, verbosity, rich, infile, fmt, outfile, **kwargs):
    # Set up logging
    if rich:
Example #27
0
class PhilipsMoonlight(Device):
    """Main class representing Xiaomi Philips Zhirui Bedside Lamp.

    Not yet implemented features/methods:

    add_mb                          # Add miband
    get_band_period                 # Bracelet work time
    get_mb_rssi                     # Miband RSSI
    get_mb_mac                      # Miband MAC address
    enable_mibs
    set_band_period
    miIO.bleStartSearchBand
    miIO.bleGetNearbyBandList

    enable_sub_voice                # Sub voice control?
    enable_voice                    # Voice control

    skip_breath
    set_sleep_time
    set_wakeup_time
    en_sleep
    en_wakeup
    go_night                        # Night light / read mode
    get_wakeup_time
    enable_bl                       # Night light

    """
    @command(default_output=format_output(
        "", "Power: {result.power}\n"
        "Brightness: {result.brightness}\n"
        "Color temperature: {result.color_temperature}\n"
        "RGB: {result.rgb}\n"
        "Scene: {result.scene}\n"))
    def status(self) -> PhilipsMoonlightStatus:
        """Retrieve properties."""
        properties = [
            'pow', 'sta', 'bri', 'rgb', 'cct', 'snm', 'spr', 'spt', 'wke',
            'bl', 'ms', 'mb', 'wkp'
        ]
        values = self.send("get_prop", properties)

        properties_count = len(properties)
        values_count = len(values)
        if properties_count != values_count:
            _LOGGER.debug(
                "Count (%s) of requested properties does not match the "
                "count (%s) of received values.", properties_count,
                values_count)

        return PhilipsMoonlightStatus(
            defaultdict(lambda: None, zip(properties, values)))

    @command(
        default_output=format_output("Powering on"), )
    def on(self):
        """Power on."""
        return self.send("set_power", ["on"])

    @command(
        default_output=format_output("Powering off"), )
    def off(self):
        """Power off."""
        return self.send("set_power", ["off"])

    @command(click.argument("rgb",
                            default=[255] * 3,
                            type=click.Tuple([int, int, int])),
             default_output=format_output("Setting color to {rgb}"))
    def set_rgb(self, rgb: Tuple[int, int, int]):
        """Set color in RGB."""
        for color in rgb:
            if color < 0 or color > 255:
                raise PhilipsMoonlightException("Invalid color: %s" % color)

        return self.send("set_rgb", [rgb_to_int(rgb)])

    @command(click.argument("level", type=int),
             default_output=format_output("Setting brightness to {level}"))
    def set_brightness(self, level: int):
        """Set brightness level."""
        if level < 1 or level > 100:
            raise PhilipsMoonlightException("Invalid brightness: %s" % level)

        return self.send("set_bright", [level])

    @command(
        click.argument("level", type=int),
        default_output=format_output("Setting color temperature to {level}"))
    def set_color_temperature(self, level: int):
        """Set Correlated Color Temperature."""
        if level < 1 or level > 100:
            raise PhilipsMoonlightException("Invalid color temperature: %s" %
                                            level)

        return self.send("set_cct", [level])

    @command(
        click.argument("brightness", type=int),
        click.argument("cct", type=int),
        default_output=format_output(
            "Setting brightness to {brightness} and color temperature to {cct}"
        ))
    def set_brightness_and_color_temperature(self, brightness: int, cct: int):
        """Set brightness level and the correlated color temperature."""
        if brightness < 1 or brightness > 100:
            raise PhilipsMoonlightException("Invalid brightness: %s" %
                                            brightness)

        if cct < 1 or cct > 100:
            raise PhilipsMoonlightException("Invalid color temperature: %s" %
                                            cct)

        return self.send("set_bricct", [brightness, cct])

    @command(click.argument("brightness", type=int),
             click.argument("rgb", type=int),
             default_output=format_output(
                 "Setting brightness to {brightness} and color to {rgb}"))
    def set_brightness_and_rgb(self, brightness: int, rgb: int):
        """Set brightness level and the color."""
        if brightness < 1 or brightness > 100:
            raise PhilipsMoonlightException("Invalid brightness: %s" %
                                            brightness)

        if rgb < 0 or rgb > 16777215:
            raise PhilipsMoonlightException("Invalid color: %s" % rgb)

        return self.send("set_brirgb", [brightness, rgb])

    @command(click.argument("number", type=int),
             default_output=format_output("Setting fixed scene to {number}"))
    def set_scene(self, number: int):
        """Set scene number."""
        if number < 1 or number > 4:
            raise PhilipsMoonlightException("Invalid fixed scene number: %s" %
                                            number)

        return self.send("apply_fixed_scene", [number])
Example #28
0
                             default=30.,
                             show_default=True,
                             help='the plane wave cutoff energy in Ry')

ecutrho = overridable_option('-R',
                             '--ecutrho',
                             type=click.FLOAT,
                             default=240.,
                             show_default=True,
                             help='the charge density cutoff energy in Ry')

hubbard_u = overridable_option('-U',
                               '--hubbard-u',
                               nargs=2,
                               multiple=True,
                               type=click.Tuple([unicode, float]),
                               help='add a Hubbard U term to a specific kind',
                               metavar='<KIND MAGNITUDE>...')

hubbard_v = overridable_option(
    '-V',
    '--hubbard-v',
    nargs=4,
    multiple=True,
    type=click.Tuple([int, int, int, float]),
    help='add a Hubbard V interaction between two sites',
    metavar='<SITE SITE TYPE MAGNITUDE>...')

hubbard_file = overridable_option(
    '-H',
    '--hubbard-file',
Example #29
0
                                    mapping_type,
                                    indent=indent)
        output.write(template)


@cli.command('jinja_to_mapping')
@click.argument('template', type=click.File('r'), default='-')
@click.argument('output', type=click.File('w'), default='-')
@click.option('--context_path',
              multiple=True,
              help='Context templates. It can either be a directory ' +
              'containing jinja files or a jinja file.',
              type=click.Path(dir_okay=True, file_okay=True, exists=True))
@click.option('--context_package',
              multiple=True,
              nargs=2,
              help='Context templates. It must be an existing package name ' +
              'followed by the path to the templates in that package.',
              type=click.Tuple([click.STRING, click.STRING]))
@click.option('--indent',
              '-i',
              default=4,
              type=click.INT,
              help='Output template indentation step.')
def jinja_to_mapping_cli(template, output, context_path, context_package,
                         indent):
    """Generate Elasticsearch mapping from jinja import templates."""
    result = jinja_to_mapping(template.read(), context_path, context_package)
    # dump the mapping to the output
    json.dump(result, output, indent=indent)
Example #30
0
              'num_pts',
              type=click.IntRange(1, None),
              default=1,
              show_default=True,
              help='Number of crossover points.')
@click.option(
    '-mp',
    'mut_pr',
    type=click.FloatRange(0.0, None),
    default=1.0,
    show_default=True,
    help='Mutation probability. Values greater than 1 imply uniform mutation.')
@click.option(
    '-md',
    'mut_down',
    type=click.Tuple([float, int]),
    default=(None, None),
    show_default=True,
    help='Final mutation and generation for variable mutation probability.')
@click.option('-e',
              'epochs',
              type=click.IntRange(1, None),
              default=10,
              show_default=True,
              help='Epochs for ANN training.')
@click.option('-ts',
              'train_size',
              type=click.FloatRange(0.1, 0.9),
              default=0.7,
              show_default=True,
              help='Split ratio for training and validation.')