Esempio n. 1
0
def common_options(func: Callable) -> Callable:
    """A decorator that combines commonly appearing @click.option decorators."""

    @click.option("--private-key", required=True, help="Path to a private key store.")
    @click.option(
        "--password-file",
        help="Text file containing the password for the provided account",
        default=None,
        type=click.Path(exists=True, dir_okay=False),
        show_default=True,
        callback=lambda ctx, param, value: Path(value) if value is not None else None,
    )
    @click.option(
        "--rpc-provider",
        default="http://127.0.0.1:8545",
        help="Address of the Ethereum RPC provider",
    )
    @click.option("--wait", default=300, help="Max tx wait time in s.")
    @click.option("--gas-price", default=5, type=IntRange(min=1), help="Gas price to use in gwei")
    @click.option("--gas-limit", default=5_500_000)
    @click.option(
        "--contracts-version",
        default=None,
        help="Contracts version to verify. Current version will be used by default.",
    )
    @functools.wraps(func)
    def wrapper(*args: List, **kwargs: Dict) -> Any:
        return func(*args, **kwargs)

    return wrapper
def common_options(func: Callable) -> Callable:
    """A decorator that combines commonly appearing @click.option decorators."""
    @click.option("--private-key",
                  required=True,
                  help="Path to a private key store.")
    @click.option(
        "--rpc-provider",
        default="http://127.0.0.1:8545",
        help="Address of the Ethereum RPC provider",
    )
    @click.option("--wait", default=300, help="Max tx wait time in s.")
    @click.option("--gas-price",
                  default=5,
                  type=IntRange(min=1),
                  help="Gas price to use in gwei")
    @click.option("--gas-limit", default=5_500_000)
    @click.option(
        "--contracts-version",
        default=None,
        help=
        "Contracts version to verify. Current version will be used by default.",
    )
    @functools.wraps(func)
    def wrapper(*args: List, **kwargs: Dict) -> Any:
        return func(*args, **kwargs)

    return wrapper
Esempio n. 3
0
class RunDevelopmentServer(Command):
    """Run a development api server. Don't use this in production.
    Specify the port with -p or --port otherwise defaults to 5000"""

    option_list = (Option('--port',
                          '-p',
                          dest='port',
                          type=IntRange(0, 2**16 - 1),
                          default=5000), )

    # pylint: disable=arguments-differ
    def run(self, port):
        if config.cfg.has_option('devel', 'debug'):
            debug = config.cfg.getboolean('devel', 'debug')
        else:
            debug = False
        # We need to import api here so that the functions within it get
        # registered (via `rest_call`), though we don't use it directly:
        # pylint: disable=unused-variable
        from hil import api
        server.init()
        migrations.check_db_schema()
        server.stop_orphan_consoles()
        rest.serve(port, debug=debug)
Esempio n. 4
0
)
@option(
    "report_dir",
    "-R",
    "--report",
    help="set the report directory",
    type=Path(file_okay=False, writable=True),
    envvar=_ENV_REPORT,
)
@option(
    "retry",
    "-r",
    "--retry",
    help="set the max retry count",
    metavar="num",
    type=IntRange(min=0),
    envvar=_ENV_RETRY,
    default=0,
)
@option(
    "delay",
    "-d",
    "--delay",
    help="set the delay between attempts in seconds",
    metavar="sec",
    type=FloatRange(min=0.0),
    envvar=_ENV_DELAY,
    default=0.1,
)
@option(
    "timeout",
Esempio n. 5
0
            break
        id += 1

    deleted_move_ids = []
    for move in Move.query:
        if not move.valid:
            move.delete()
            deleted_move_ids.append(move.id)

    if deleted_move_ids:
        echo(f'Following moves were removed.')
        for deleted_move_id in deleted_move_ids:
            echo(f'   {deleted_move_id}')

    db.session.commit()


@cli.command()
@option('--host', default='127.0.0.1', help='Host to listen')
@option('--port',
        type=IntRange(0, 65535),
        metavar='PORT',
        default=5000,
        help='Port number to listen')
def dev(host: str, port: int) -> None:
    app.run(debug=True, host=host, port=port)


if __name__ == '__main__':
    cli()
Esempio n. 6
0
        logging.fatal(
            f"Failed to connect to Raiden node at {url}: {fail_reason}")
        exit("Aborting")


@command()
@option("--raiden-url",
        default="http://127.0.0.1:5001",
        help="URL of the Raiden node to use")
@option("--logic",
        default="echo",
        type=Choice(logic_choices),
        help="Logic the bot will implement")
@option(
    "--timeout",
    type=IntRange(min=0),
    default=0,
    help=
    "Seconds to wait for the Raiden API to become available before aborting.")
@option("--single-token",
        type=str,
        default=None,
        help="Token to restrict the node to")
@configuration_option()
def main(raiden_url, logic, timeout, single_token):
    """
    Run a bot on top of a Raiden node. It polls the Raiden node for incoming
    payments and reacts in the way specified with the --logic option.

    Currently the only available behavior setting is 'echo', turning the Raiden
    node into an echo node (see Raiden docs for further information).
Esempio n. 7
0
          envvar='GITSTERY_TEMP_DIR')
@option('--force',
        '-f',
        is_flag=True,
        help='Override directory even if exists.')
@option('--seed',
        '-s',
        'seed_value',
        type=bytes.fromhex,
        metavar='SEED',
        envvar='GITSTERY_SEED',
        help='Set random seed for reproducible runs.')
@option('--phase',
        '-p',
        'chosen_phases',
        type=IntRange(1, PHASES_COUNT),
        default=[],
        show_default=f'1..{PHASES_COUNT}',
        metavar='INDEX',
        multiple=True,
        help='Generate only selected phases.')
@option('--no-phases',
        '-P',
        is_flag=True,
        show_default=True,
        help="Don't generate any phases.")
@option('--no-solution',
        '-S',
        is_flag=True,
        show_default=True,
        help="Don't generate solution.")
Esempio n. 8
0

@attack.command()
@click.option("--axis",
              required=True,
              type=EnumType(FlipAxis),
              help="Flip axis")
def flip(axis: FlipAxis, **kwargs) -> None:
    attack_video(Flip(axis), **kwargs)


@attack.command()
@click.option(
    "-x",
    default=0,
    type=IntRange(min=0),
    help="The x coordinate of the first pixel in frame",
)
@click.option(
    "-y",
    default=0,
    type=IntRange(min=0),
    help="The y coordinate of the first pixel in frame",
)
@click.option("--width", type=IntRange(min=0), help="New frame width")
@click.option("--height", type=IntRange(min=0), help="New frame height")
def crop(y: int, x: int, height: int, width: int, **kwargs) -> None:
    attack_video(Crop(y, x, height, width), **kwargs)


@attack.command()
Esempio n. 9
0
default_options.append((
    ("check_external_urls", '-e', '--external'),
    {
        'default': False,
        'is_flag': True,
        'show_default': False,
        'help': 'Enables external resources check',
    },
))

# Retries ------------------------------------------------------------------
default_options.append((
    ('-r', '--retry'),
    {
        'default': 0,
        'type': IntRange(0, 10),
        'is_flag': False,
        'show_default': True,
        'metavar': '',
        'help': 'Number of Retries [0...10]',
    },
))

# Concurrent Crawlers ------------------------------------------------------
default_options.append((
    ('-n', '--threads'),
    {
        'default': 1,
        'type': IntRange(1, 10),
        'is_flag': False,
        'show_default': True,
Esempio n. 10
0
              current["number"],
              convert_time(current["time"], "all"),
              diffi["block"],
              issuers,
              len(diffi["levels"]),
              current["powMin"],
              match_pattern(int(current["powMin"]))[0],
              tabulate(sorted_diffi,
                       headers="keys",
                       tablefmt="orgtbl",
                       stralign="center"),
          ))


@command("blocks", help="Display blocks: default: 0 for current window size")
@argument("number", default=0, type=IntRange(0, 5000))
@option(
    "--detailed",
    "-d",
    is_flag=True,
    help="Force detailed view. Compact view happen over 30 blocks",
)
@coroutine
async def list_blocks(number, detailed):
    head_block = await HeadBlock().head_block
    current_nbr = head_block["number"]
    if number == 0:
        number = head_block["issuersFrame"]
    client = ClientInstance().client
    blocks = await client(bma.blockchain.blocks, number,
                          current_nbr - number + 1)
Esempio n. 11
0
        elif single == DatasetManagerTask.UNIFY:
            params['certdb'] = certdb
        elif single == DatasetManagerTask.ANALYSE:
            params = _prepare_analyser_arg(certdb, reference_date)

        tasks.append((single, params))

    collected, unified, analysed = ctx.obj['manager'].run(tasks)
    click.echo('Collected Datasets: {}'.format(collected))
    click.echo('Unified Datasets: {}'.format(unified))
    click.echo('Analysed Datasets: {}'.format(analysed))
    certdb.commit()


@manager_group.command('enrichments')
@click.option('--depth', type=IntRange(min=0), default=100, help='Enrichment depth (default is 100)')
@click.pass_context
def enrichments(ctx, depth):
    """Generate database enrichment stats."""
    for dataset in ctx.obj['datasets']:
        certs_file = dataset.full_path(DatasetState.COLLECTED, 'certs', True)
        hosts_file = dataset.full_path(DatasetState.COLLECTED, 'hosts', True)

        if certs_file and hosts_file:
            EnrichmentAnalyzer(certs_file, hosts_file, depth).run()
        else:
            click.echo("Dataset not found (or incomplete)")


@manager_group.command('stats')
@click.option('--aggregate', '-a', is_flag=True, help='Shows aggregation statistics.')
Esempio n. 12
0
                echo(f"{blue}{t:%Y-%m-%d %H:%M:%S}{reset} {yellow}{e}{reset}", color=ctx.color)
    finally:
        db.commit()

    if clear:
        echo(f"Removed {yellow}{removed}{reset} entries.")


@database_app.command("search", short_help="Search database entries.", no_args_is_help=True)
@argument("table", nargs=1, required=True, is_eager=True, type=TableChoice())
@argument("query", nargs=-1, required=False, callback=lambda _c, _p, v: " ".join(v))
@option("--column", metavar="COLUMN", type=SearchColumnsChoice(), multiple=True, callback=column_callback,
        help=f"Select {yellow}COLUMN{reset} and use {yellow}WIDTH{reset} in table output.")
@option("--sort", metavar="<COLUMN [asc|desc]>", multiple=True, type=(SortColumnsChoice(), SearchOrderChoice()),
        help=f"Sort by {yellow}COLUMN{reset}.", callback=sort_callback)
@option("--limit", type=IntRange(0, min_open=True), help="Limit query results.")
@option("--offset", type=IntRange(0, min_open=True), help="Offset query results.")
@option("--sql", is_flag=True, help="Treat query as SQLite WHERE statement.")
@option("--show-sql", is_flag=True, help="Show generated SQLite WHERE statement.")
@option("--output", default="table", type=SearchOutputChoice(), help="Specify output type.")
@option("--table-widths", metavar="WIDTH,[WIDTH...]", type=str, callback=table_width_callback,
        help="Specify width of table columns.")
@option("--ignore-width", is_flag=True, help="Ignore terminal width when printing results in table format.")
@option("--total", is_flag=True, help="Print number of results.")
@database_exists_option
@color_option
@help_option
@pass_context
@docstring_format(c=cyan, i=italic, r=reset, prog_name=__prog_name__, version=__version__,
                  outputs="\n    ".join(f" * {s.value}\t{s.help}" for s in SearchOutputChoice.completion_items))
def database_search(ctx: Context, database: Callable[..., Database], table: str, query: str, column: tuple[str],
Esempio n. 13
0
class TagDef(Resource):
    __type__ = 'Tag'
    ID_CONVERTER = Converters.string
    VIEW = TagView
    TAG_HASH_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    TAG_HASH_MIN = 5
    CLI_PATH = cli.Path(dir_okay=False, writable=True)

    def __init__(self,
                 app,
                 import_name=__package__,
                 static_folder=None,
                 static_url_path=None,
                 template_folder=None,
                 url_prefix='',
                 subdomain=None,
                 url_defaults=None,
                 root_path=None):
        cli_commands = ((self.create_tags, 'create-tags'), (self.set_tags,
                                                            'set-tags'),
                        (self.export_tags, 'export'), (self.import_tags,
                                                       'import'))
        super().__init__(app, import_name, static_folder, static_url_path,
                         template_folder, url_prefix, subdomain, url_defaults,
                         root_path, cli_commands)
        self.hashids = Hashids(salt=app.config['TAG_HASH_SALT'],
                               min_length=self.TAG_HASH_MIN,
                               alphabet=self.TAG_HASH_ALPHABET)

    @option('--csv',
            type=CLI_PATH,
            help='The path of a CSV file to save the IDs.')
    @option('--etag/--no-etag',
            default=False,
            help='Generate eTags instead of regular tags.')
    @argument('num', type=IntRange(1))
    def create_tags(self, num: int, csv: Path, etag: bool):
        """
        Creates NUM empty tags (only with the ID) and optionally saves
        a CSV of those new ids into a file.
        """
        T = ETag if etag else Tag
        tags = tuple(T() for _ in range(num))
        db.session.add_all(tags)
        db.session.commit()
        self.tags_to_csv(csv, tags)
        print('Created all tags and saved them in the CSV {}'.format(csv))

    @option('--csv',
            type=CLI_PATH,
            help='The path of a CSV file to save the tags that were set.')
    @argument('ending-tag', type=IntRange(2))
    @argument('starting-tag', type=IntRange(1))
    @argument('devicehub')
    def set_tags(self, devicehub: str, starting_tag: int, ending_tag: int,
                 csv: Path):
        """
        "Sends" the tags to the specific devicehub,
        so they can only be linked in that devicehub.

        Actual implementation does not send them but rather update the
        internal database as it did send them. You will need to create
        them manually in the destination devicehub.

        This method in the future will probably actually (virtually)
        send them.
        """
        assert starting_tag < ending_tag
        assert URL(devicehub) and devicehub[
            -1] != '/', 'Provide a valid URL without leading slash'
        tags = Tag.query.filter(between(Tag.id, starting_tag,
                                        ending_tag)).all()
        for tag in tags:
            tag.devicehub = devicehub
        db.session.commit()
        self.tags_to_csv(csv, tags)
        print('All tags set to {}'.format(devicehub))

    @staticmethod
    def tags_to_csv(path: Path, tags: Iterable[Tag]):
        """
        Generates tags
        :param path:
        :param tags:
        :return:
        """
        with path.open('w') as f:
            csv_writer = csvm.writer(f)
            for tag in tags:
                csv_writer.writerow([url_for_resource(Tag, tag.id)])

    @argument('csv', type=CLI_PATH)
    def export_tags(self, csv: Path):
        """Exports the Tag database in a CSV file.  The rows are:
        ``id``, ``secondary``, ``devicehub``, ``type``, ``updated``, ``created``.
        """
        with csv.open('w') as f:
            csv_writer = csvm.writer(f)
            for tag in Tag.query:
                dh = tag.devicehub.to_url() if tag.devicehub else None
                row = tag.id, tag.secondary, dh, tag.type, tag.updated, tag.created
                csv_writer.writerow(row)

    @argument('csv', type=CLI_PATH)
    def import_tags(self, csv: Path):
        """Imports the database from a CSV from ``export``.
        This truncates only the Tag table.
        """
        db.session.execute('TRUNCATE TABLE {} RESTART IDENTITY'.format(
            Tag.__table__.name))
        max_id = 0
        """The maximum ID of the tags. Sequence is reset to this + 1."""
        with csv.open() as f:
            for row in csvm.reader(f):
                id, secondary, dh, type, updated, created = row
                cls = Tag if type == 'Tag' else ETag
                dh = URL(dh) if dh else None
                t = cls(id=id, secondary=secondary)
                db.session.add(t)
                max_id = max(max_id, cls.decode(id))
        db.session.execute(
            'ALTER SEQUENCE tag_id RESTART WITH {}'.format(max_id + 1))
        db.session.commit()
Esempio n. 14
0
        type=str,
        help='Set output file name.')
@option('--halign',
        '-h',
        default='center',
        type=Choice(['left', 'center', 'right']),
        help='Set horizon position.')
@option('--valign',
        '-v',
        default='bottom',
        type=Choice(['top', 'center', 'bottom']),
        help='Set vertical position.')
@option('--margin',
        '-m',
        default=10,
        type=IntRange(0, 100),
        help='Set mergin.')
@option('--font', '-f', default=PDF2DOC_FONT, help='Set font name.')
@option('--size', '-s', default=PDF2DOC_FONTSIZE, help='Set font size.')
@option('--start', '-n', default=PDF2DOC_START_NUM, help='Set start number.')
@option('--merge', is_flag=True, help='Merge document.')
@option('--blank', is_flag=True, help='Add blank page for double print.')
def cli(files, output, halign, valign, margin, font, size, start, merge,
        blank):
    """ тнРя╕П Add pages to PDFs and merge(optional) -> PERFECT DOCUMENT! ЁЯУС"""

    file_paths = [os.path.join(cwd, file) for file in files]

    output_paths = []
    for path in file_paths:
        root, ext = os.path.splitext(path)