import click from ..exceptions import ParseError from ..settings import Settings from ..timesheet import TimesheetCollection from .base import cli, get_timesheet_collection_for_context @cli.command(short_help="Open the entries file in your editor.") @click.option('-f', '--file', 'file_to_edit', type=click.Path(dir_okay=False), help="Path to the file to edit.") @click.argument('previous_file', default=0, type=click.IntRange(min=0)) @click.pass_context def edit(ctx, file_to_edit, previous_file): """ Opens your timesheet file in your favourite editor. The PREVIOUS_FILE argument can be used to specify which nth previous file to edit. A value of 1 will edit the previous file, 2 will edit the second-previous file, etc. """ timesheet_collection = None autofill = not bool(file_to_edit) and previous_file == 0 if not file_to_edit: file_to_edit = ctx.obj['settings'].get_entries_file_path(False) # If the file was not specified and if it's the current file, autofill it if autofill: try: timesheet_collection = get_timesheet_collection_for_context( ctx, file_to_edit
#!/usr/bin/python3 # -*- coding: utf-8 -*- import ssl import click from bin import utils from butterfly.master import Master @click.command() @click.argument('host') @click.argument('port', type=click.IntRange(1, 65535)) @click.argument('passwd') @click.option('--api_key', required=True) @click.option('--api_sec', required=True) @click.option('--spl_rate', type=click.INT, default=44100) @click.option('--ch_num', type=click.INT, default=2) @click.option('--enable_ssl', is_flag=True) def main(enable_ssl, **kwargs): ssl_ctx = None if enable_ssl: ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ssl_ctx.verify_mode = ssl.CERT_REQUIRED ssl_ctx.set_default_verify_paths() slave = Master(ssl_ctx=ssl_ctx, **kwargs) slave.mainloop() if __name__ == '__main__': utils.fix_signal()
def create(general_config, transacting_staker_options, config_file, force, value, lock_periods): """ Initialize a new stake. """ emitter = _setup_emitter(general_config) STAKEHOLDER = transacting_staker_options.create_character(emitter, config_file) blockchain = transacting_staker_options.get_blockchain() economics = STAKEHOLDER.economics client_account, staking_address = handle_client_account_for_staking( emitter=emitter, stakeholder=STAKEHOLDER, staking_address=transacting_staker_options.staker_options.staking_address, individual_allocation=STAKEHOLDER.individual_allocation, force=force) # Dynamic click types (Economics) min_locked = economics.minimum_allowed_locked stake_value_range = click.FloatRange(min=NU.from_nunits(min_locked).to_tokens(), clamp=False) stake_duration_range = click.IntRange(min=economics.minimum_locked_periods, clamp=False) # # Stage Stake # if not value: token_balance = NU.from_nunits(STAKEHOLDER.token_agent.get_balance(staking_address)) lower_limit = NU.from_nunits(STAKEHOLDER.economics.minimum_allowed_locked) upper_limit = min(token_balance, NU.from_nunits(STAKEHOLDER.economics.maximum_allowed_locked)) value = click.prompt(f"Enter stake value in NU " f"({lower_limit} - {upper_limit})", type=stake_value_range, default=upper_limit.to_tokens()) value = NU.from_tokens(value) if not lock_periods: min_locktime = STAKEHOLDER.economics.minimum_locked_periods max_locktime = STAKEHOLDER.economics.maximum_rewarded_periods prompt = f"Enter stake duration ({min_locktime} - {max_locktime})" lock_periods = click.prompt(prompt, type=stake_duration_range, default=max_locktime) start_period = STAKEHOLDER.staking_agent.get_current_period() + 1 unlock_period = start_period + lock_periods # # ReviewPub # if not force: painting.paint_staged_stake(emitter=emitter, stakeholder=STAKEHOLDER, staking_address=staking_address, stake_value=value, lock_periods=lock_periods, start_period=start_period, unlock_period=unlock_period) confirm_staged_stake(staker_address=staking_address, value=value, lock_periods=lock_periods) # Last chance to bail click.confirm("Publish staged stake to the blockchain?", abort=True) # Authenticate password = transacting_staker_options.get_password(blockchain, client_account) # Consistency check to prevent the above agreement from going stale. last_second_current_period = STAKEHOLDER.staking_agent.get_current_period() if start_period != last_second_current_period + 1: emitter.echo("Current period advanced before stake was broadcasted. Please try again.", color='red') raise click.Abort # Authenticate and Execute STAKEHOLDER.assimilate(checksum_address=client_account, password=password) emitter.echo("Broadcasting stake...", color='yellow') new_stake = STAKEHOLDER.initialize_stake(amount=value, lock_periods=lock_periods) painting.paint_staking_confirmation(emitter=emitter, staker=STAKEHOLDER, new_stake=new_stake)
def get_click_type(*, annotation: Any, parameter_info: ParameterInfo) -> click.ParamType: if annotation == str: return click.STRING elif annotation == int: if parameter_info.min is not None or parameter_info.max is not None: min_ = None max_ = None if parameter_info.min is not None: min_ = int(parameter_info.min) if parameter_info.max is not None: max_ = int(parameter_info.max) return click.IntRange(min=min_, max=max_, clamp=parameter_info.clamp) else: return click.INT elif annotation == float: if parameter_info.min is not None or parameter_info.max is not None: return click.FloatRange( min=parameter_info.min, max=parameter_info.max, clamp=parameter_info.clamp, ) else: return click.FLOAT elif annotation == bool: return click.BOOL elif annotation == UUID: return click.UUID elif annotation == datetime: return click.DateTime(formats=parameter_info.formats) elif (annotation == Path or parameter_info.allow_dash or parameter_info.path_type or parameter_info.resolve_path): return click.Path( exists=parameter_info.exists, file_okay=parameter_info.file_okay, dir_okay=parameter_info.dir_okay, writable=parameter_info.writable, readable=parameter_info.readable, resolve_path=parameter_info.resolve_path, allow_dash=parameter_info.allow_dash, path_type=parameter_info.path_type, ) elif lenient_issubclass(annotation, FileTextWrite): return click.File( mode=parameter_info.mode or "w", encoding=parameter_info.encoding, errors=parameter_info.errors, lazy=parameter_info.lazy, atomic=parameter_info.atomic, ) elif lenient_issubclass(annotation, FileText): return click.File( mode=parameter_info.mode or "r", encoding=parameter_info.encoding, errors=parameter_info.errors, lazy=parameter_info.lazy, atomic=parameter_info.atomic, ) elif lenient_issubclass(annotation, FileBinaryRead): return click.File( mode=parameter_info.mode or "rb", encoding=parameter_info.encoding, errors=parameter_info.errors, lazy=parameter_info.lazy, atomic=parameter_info.atomic, ) elif lenient_issubclass(annotation, FileBinaryWrite): return click.File( mode=parameter_info.mode or "wb", encoding=parameter_info.encoding, errors=parameter_info.errors, lazy=parameter_info.lazy, atomic=parameter_info.atomic, ) elif lenient_issubclass(annotation, Enum): return click.Choice( [item.value for item in annotation], case_sensitive=parameter_info.case_sensitive, ) raise RuntimeError( f"Type not yet supported: {annotation}") # pragma no cover
def prompt_modify_sequence(self): """Prompts the user to modify the sequence number, with several different options. TODO: use scapy's built in seqnum...will improve speed + readability """ if not iot_click.confirm("Modify the sequence number?"): return iot_click.print( "\nChoose How you would like to modify the sequence number:") iot_click.print(" 0: Increase by 1 for each packet") iot_click.print(" 1: Increase by 1 for each transmission replay") iot_click.print(" 2: Manually change, one packet at a time") iot_click.print( " 3: Manually change, one transmission replay at a time") modify_type = iot_click.prompt( "Your choice", type=click.IntRange(0, 3)) if modify_type == 0 or modify_type == 1: increase_type = "packet" if modify_type == 0 else "transmission replay" if iot_click.confirm( "Increase the sequence number of the first {}?".format( increase_type) ): seq_add = 1 else: seq_add = 0 # Modify as a dot154 packet and then convert back to GnuradioPacket after modifications self.send_pkts = [ pkt for pkt in gnu_scapy.strip_gnuradio_layer(self.send_pkts) ] # strip gnuradio and FCS layer if modify_type == 0 or modify_type == 2: for ii in range(0, len(self.send_pkts)): packet_bytes = bytearray(bytes(self.send_pkts[ii])) while True: try: if modify_type == 0: seq_new = packet_bytes[2] + seq_add if seq_new > 255: seq_new %= 255 packet_bytes[2] = seq_new seq_add += 1 else: iot_click.print( "\nPacket: {}".format( self.send_pkts[ii].summary()) ) iot_click.print( "\nCurrent sequence number: {}".format( packet_bytes[2]) ) packet_bytes[2] = iot_click.prompt( "New sequence number", type=click.IntRange(0, 255) ) break except ValueError: print("Invalid sequence number!") self.send_pkts[ii] = gnuradio.GnuradioPacket() / dot15d4.Dot15d4FCS( bytes(packet_bytes[:-2]) + self.send_pkts[ii].compute_fcs( bytes(packet_bytes[:-2]) ) # re-compute the FCS after modifying the seq number ) elif modify_type == 1 or modify_type == 3: ii = 0 while ii < len(self.send_pkts): packets_bytes = [ bytearray(bytes(pkt)) for pkt in self.send_pkts[ii: ii + self.single_replay_length] ] while True: try: if modify_type == 1: for jj in range(len(packets_bytes)): seq_new = packets_bytes[jj][2] + seq_add if seq_new > 255: seq_new %= 255 packets_bytes[jj][2] = seq_new seq_add += 1 else: iot_click.print("\n") for jj in range( len(self.send_pkts[ii: ii + self.single_replay_length]) ): iot_click.print( "{}: {}".format( jj, self.send_pkts[jj].summary()) ) iot_click.print( "Current group sequence numbers: {}".format( list([pkt_bytes[2] for pkt_bytes in packets_bytes]) ) ) new_seq_number = iot_click.prompt( "New sequence number", type=click.IntRange(0, 255) ) for jj in range(len(packets_bytes)): packets_bytes[jj][2] = new_seq_number break except ValueError: print("Invalid sequence number!") self.send_pkts[ii: ii + self.single_replay_length] = [ gnuradio.GnuradioPacket() / dot15d4.Dot15d4FCS( bytes(pkt_bytes[:-2]) + dot15d4.Dot15d4FCS().compute_fcs(bytes(pkt_bytes[:-2])) ) for pkt_bytes in packets_bytes ] ii += self.single_replay_length
def devices(): '''Print available devices.''' if os.name == 'nt' or sys.platform == 'win32': from serial.tools.list_ports_windows import comports elif os.name == 'posix': from serial.tools.list_ports_posix import comports for port in sorted(comports()): click.echo(port[0], err=True) @cli.command() @click.option('--device', '-d', type=str, required=True, help='Device path.') @click.option('--interval', '-i', default=1, type=click.IntRange(1, 86400), help='Scan interval in seconds.') @click.option('--frequency', '-f', default=10000, type=click.IntRange(10, 1000000), help='Modulation frequency in Hz.') @click.option('--filtering', '-q', default='none', type=click.Choice(FILTERS), help='Algorithm for filtering.') @click.option('--samples', '-a', default=1, type=click.IntRange(1, 256),
def remove_materials_cmd(): """ Remove all materials from a CityJSON file. """ def processor(cm): print_cmd_status('Remove all material') cm.remove_materials() return cm return processor @cli.command('compress') @click.option('--digit', default=3, type=click.IntRange(1, 10), help='Number of digit to keep.') def compress_cmd(digit): """ Compress a CityJSON file, ie stores its vertices with integers. """ def processor(cm): print_cmd_status('Compressing the CityJSON (with %d digit)' % digit) try: cm.compress(digit) except Exception as e: click.echo("WARNING: %s." % e) return cm return processor
from app.gui import Gui @click.command() @click.option("-f", "--filename", type=click.Path(exists=True), help="Filename of the log to read from") @click.option("-m", "--mode", type=click.Choice( ['process', 'show_db', 'print', 'add_solution', 'gui'])) @click.option("-s", "--solution", type=click.STRING, help="The solution") @click.option("-p", "--priority", type=click.IntRange(0, 999), help="Priority of the solution") @click.option("-o", "--solved", type=click.BOOL, help="Is solution solved ?") def main(filename, mode, solution, priority, solved): if mode == 'print': print_log(load_from_file(filename)) elif mode == 'show_db': print(show_db()) elif mode == 'process': print(process_log(load_from_file(filename))) elif mode == 'add_solution': if priority is None or solved is None or solution is None or filename is None: print( '\033[91m', "Arguments: --priority, --solved, --solution, --filename are required for this mode. " )
def select_client_account(emitter, provider_uri: str, prompt: str = None, default: int = 0, registry=None, show_balances: bool = True, show_staking: bool = False, network: str = None) -> str: """ Note: Setting show_balances to True, causes an eager contract and blockchain connection. """ # TODO: Break show_balances into show_eth_balance and show_token_balance if not provider_uri: raise ValueError( "Provider URI must be provided to select a wallet account.") # Lazy connect the blockchain interface if not BlockchainInterfaceFactory.is_interface_initialized( provider_uri=provider_uri): BlockchainInterfaceFactory.initialize_interface( provider_uri=provider_uri, emitter=emitter) blockchain = BlockchainInterfaceFactory.get_interface( provider_uri=provider_uri) # Lazy connect to contracts token_agent = None if show_balances or show_staking: if not registry: registry = InMemoryContractRegistry.from_latest_publication( network=network) token_agent = NucypherTokenAgent(registry=registry) # Real wallet accounts enumerated_accounts = dict(enumerate(blockchain.client.accounts)) if len(enumerated_accounts) < 1: emitter.echo("No ETH accounts were found.", color='red', bold=True) raise click.Abort() # Display account info headers = ['Account'] if show_staking: headers.append('Staking') if show_balances: headers.extend(('', '')) rows = list() for index, account in enumerated_accounts.items(): row = [account] if show_staking: staker = Staker(is_me=True, checksum_address=account, registry=registry) staker.stakes.refresh() is_staking = 'Yes' if bool(staker.stakes) else 'No' row.append(is_staking) if show_balances: token_balance = NU.from_nunits( token_agent.get_balance(address=account)) ether_balance = Web3.fromWei( blockchain.client.get_balance(account=account), 'ether') row.extend((token_balance, f'{ether_balance} ETH')) rows.append(row) emitter.echo(tabulate(rows, headers=headers, showindex='always')) # Prompt the user for selection, and return prompt = prompt or "Select index of account" account_range = click.IntRange(min=0, max=len(enumerated_accounts) - 1) choice = click.prompt(prompt, type=account_range, default=default) chosen_account = enumerated_accounts[choice] emitter.echo(f"Selected {choice}: {chosen_account}", color='blue') return chosen_account
def select_config_file( emitter, config_class, config_root: str = None, checksum_address: str = None, ) -> str: # # Scrape Disk Configurations # config_root = config_root or DEFAULT_CONFIG_ROOT default_config_file = glob.glob( config_class.default_filepath(config_root=config_root)) glob_pattern = f'{config_root}/{config_class._NAME}-0x*.{config_class._CONFIG_FILE_EXTENSION}' secondary_config_files = glob.glob(glob_pattern) config_files = [*default_config_file, *secondary_config_files] if not config_files: emitter.message( f"No {config_class._NAME.capitalize()} configurations found. " f"run 'nucypher {config_class._NAME} init' then try again.", color='red') raise click.Abort() checksum_address = checksum_address or os.environ.get( NUCYPHER_ENVVAR_WORKER_ADDRESS, None) # TODO: Deprecate worker_address in favor of checksum_address if checksum_address: # # Manual # parsed_addresses = { extract_checksum_address_from_filepath(fp): fp for fp in config_files } try: config_file = parsed_addresses[checksum_address] except KeyError: raise ValueError( f"'{checksum_address}' is not a known {config_class._NAME} configuration account." ) elif len(config_files) > 1: # # Interactive # parsed_addresses = tuple([extract_checksum_address_from_filepath(fp)] for fp in config_files) # Display account info headers = ['Account'] emitter.echo( tabulate(parsed_addresses, headers=headers, showindex='always')) # Prompt the user for selection, and return prompt = f"Select {config_class._NAME} configuration" account_range = click.IntRange(min=0, max=len(config_files) - 1) choice = click.prompt(prompt, type=account_range, default=0) config_file = config_files[choice] emitter.echo(f"Selected {choice}: {config_file}", color='blue') else: # Default: Only one config file, use it. config_file = config_files[0] return config_file
from .. import filesystem, snapshot, ssh, task from ..compress import Compression from ..filesystem import FileSystem from ..filesystem import filesystem as filesystem_t from ..ssh import Cipher from .click import EnumChoice @click.command() @click.option("--verbose", "-v", is_flag=True, help="Print additional output.") @click.option("--dry-run", is_flag=True, help="Generate replication tasks but do not execute them.") @click.option( "--follow-delete", is_flag=True, help="Delete snapshots on REMOTE_FS that have been deleted from LOCAL_FS." ) @click.option("--recursive", is_flag=True, help="Recursively replicate snapshots.") @click.option("--port", "-p", type=click.IntRange(1, 65535), metavar="PORT", default=22, help="Connect to SSH on PORT.") @click.option("--login", "-l", "--user", "-u", "user", metavar="USER", help="Connect to SSH as USER.") @click.option( "-i", "--identity-file", type=click.Path(exists=True, dir_okay=False), required=True, help="SSH identity file to use.", ) @click.option( "--cipher", type=EnumChoice(Cipher), default=Cipher.STANDARD, help="One of: disable (no ciphers), fast (only fast ciphers), or standard (default ciphers).", ) @click.option(
@click.group() def cli(): pass @cli.command(context_settings=dict(max_content_width=500)) @click.argument('output_file', type=click.File('w')) @click.option('--output-format', default='JSON', type=click.Choice(['JSON', 'CSV'], case_sensitive=False), required=False) @click.option('--segments', '-s', type=click.IntRange(2, 4998), default=20, help="Number of segments", required=False) @click.option('--sample-data', '-d', type=SampleDataParamType(), default="(0,0), (1,0.1), (2,2), (4,6), (7,20), (9,50), (10,100)", help="Input data for interpolation", required=False) @click.option("--cookie-name", "-c", help="VPFQ cookie name (akavpfq_<VP-instance-label>)", required=True) @click.option("--queue-endpoint", "-e",
if ipaddress.ip_address(hostname).is_private: return "Private IP scanning is forbidden", 403 except ValueError: # raised when hostname isn't an ip address if not is_valid_hostname(hostname): return "Hostname does not resolve.", 400 # call ping args = ['ping', '-c', str(app.config['PING21_DEFAULT_ECHO']), hostname] try: out = subprocess.check_output(args, universal_newlines=True) except subprocess.CalledProcessError: return "Host was not reachable", 400 # format, jsonify, and return return jsonify(**{ 'ping': [line for line in out.split('\n') if line != ''], 'server': get_server_info() }) @click.command() @click.argument('defaultecho', type=click.IntRange(min=1), default=3) def run(defaultecho): app.config['PING21_DEFAULT_ECHO'] = defaultecho print("Server running...") app.run(host='0.0.0.0', port=5000) if __name__ == '__main__': run()
def timezone_check(ctx, param, value): """ Check if the supplied timezone is valid """ if value in pendulum.timezones: return value else: raise click.BadParameter(f'The timezone {value} isn\'t valid, try again.') @click.command(name='download-videos', context_settings=CONTEXT_SETTINGS) @click.option('-s', '--start-time', callback=datetime_check, help='Specify a start time in DD-MM-YYYY:HH:mm:ss') @click.option('-e', '--end-time', callback=datetime_check, help='Specify a start time in DD-MM-YYYY:HH:mm:ss') @click.option('-u', '--username', help='Unifi Video username', required=True, default='administrator', type=click.STRING) @click.option('-d', '--hostname', help='Domain name, hostname or IP address for the Video controller. E.g. 127.0.0.1', type=click.STRING, required=True) @click.option('-p', '--port', help='Port number for the Video controller. Defaults to 7443', default=7443, type=click.IntRange(1, 65535)) @click.option('-o', '--output-dir', help='Directory to save the videos to.', type=click.Path(exists=True, file_okay=False, writable=True, resolve_path=True, allow_dash=True)) @click.option('--password', help='UVC User\'s password. Script will prompt for password later on if not entered. This option exists for scripting.', prompt=True, hide_input=True) @click.option('-tz', '--timezone', callback=timezone_check, help='Set timezone to be something other than \'America/Denver\'. Default is \'America/Denver\'.', default='America/Denver', type=click.STRING) @click.argument('camera-names', nargs=-1) @click.pass_context def main(ctx, start_time, end_time, username, hostname, port, output_dir, password, camera_names, timezone): """Download videos for cameras for a specific time frame. Times default to America/Denver.""" console_log_level = 30 # Base logger logger.setLevel(logging.DEBUG) # Create console handler with a higher log level
'Path to a mask that will be considered as binary. The highest pixel value will be considered as information and all other values will be considered outside the mask - Required if input is an image' ) @click.option('-o', '--outputfile', required=True, help='Path to the output CSV file.') @click.option('-v', '--verbose', default=True, help='Provides additional debug output.') @click.option( '-d', '--dimensions', help= 'Optional number of dimensions upon which to run collage. Supported values are 2 and 3. If left out, we will default to the dimensionality of the image itself, which may not reflect expected behavior if the image has an alpha channel.', type=click.IntRange(2, 3, clamp=True)) @click.option( '-s', '--svdradius', default=5, help= 'SVD radius is used for the dominant angle calculation pixel radius. DEFAULTS to 5 and is suggested to remain at the default.' ) @click.option( '-h', '--haralickwindow', default=-1, help= 'Number of pixels around each pixel used to calculate the haralick texture. DEFAULTS to svdradius * 2 - 1.' ) @click.option(
) @click.option( "--operation-id", "-O", "operation_ids", type=str, multiple=True, help="Filter schemathesis test by operationId pattern.", callback=callbacks.validate_regex, ) @click.option( "--workers", "-w", "workers_num", help="Number of workers to run tests.", type=click.IntRange(1, MAX_WORKERS), default=DEFAULT_WORKERS, ) @click.option( "--base-url", "-b", help= "Base URL address of the API, required for SCHEMA if specified by file.", type=str, callback=callbacks.validate_base_url, ) @click.option("--app", help="WSGI application to test.", type=str, callback=callbacks.validate_app) @click.option(
) REQUEST_BATCH = click.option( '--batch', required=False, default=False, is_flag=True, help="Whether you want to perform the request as batch request (async)" ) REQUEST_ID_MULTI = click.option( '-id', '--request_id', required=True, metavar='<id>', multiple=True, help="The ID of the request" ) REQUEST_ID_OPTIONAL = click.option( '-id', '--request_id', required=False, default=None, metavar='<id>', help="The ID of the deployment request" ) PIPELINE_REQUEST_ID_OPTIONAL = click.option( '-pid', '--pipeline_request_id', required=False, default=None, metavar='<id>', help="The ID of the pipeline request" ) REQUEST_TIMEOUT = click.option( '-t', '--timeout', required=False, default=None, metavar='[10-345600]', type=click.IntRange(10, 345600), help="Timeout in seconds" ) REQUEST_DEPLOYMENT_TIMEOUT_DEPRECATED = click.option( '-t', '--timeout', required=False, default=300, type=click.IntRange(10, 3600), metavar='[10-3600]', show_default=True, help="Timeout in seconds" ) REQUEST_PIPELINE_TIMEOUT_DEPRECATED = click.option( '-pt', '--pipeline_timeout', required=False, default=3600, type=click.IntRange(10, 7200), metavar='[10-7200]', show_default=True, help="Timeout for the entire pipeline request in seconds" ) REQUEST_OBJECT_TIMEOUT = click.option( '-dt', '--deployment_timeout', required=False, default=None, type=click.IntRange(10, 3600), metavar='[10-3600]', help="Timeout for each deployment request in the pipeline in seconds" )
def _get_click_options(): import click return \ { 'architecture': { 'help': "The ResNet Architecture to use for extraction.", 'type': click.Choice(('resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152')) }, 'image_shape': { 'help': "The square size that all images will be resized to prior to extraction. Note that Torchvision's ResNet models only support 224x224 images." " So this is the default value.", }, 'extractor_batch_size': { 'help': "The extractor will process images in batches of this size. Use as big a value as your machine can handle. A power of two is preferred." }, 'num_workers': { 'help': f"Number of CPU cores to use for loading images from disk. Maximum that can be used in your machine is {__num_cores()}" }, 'vocab_size': { 'help': "The size of the vocabulary to be used. The larger the size, the more rare words will be covered. This should not be as much of an issue since" " SpaCy automatically replaces unknown words with their synonyms at runtime. Beware though, that a larger size will consume tons of memory since" " we'll be doing a softmax on the scores." }, 'caption_idx': { 'help': "The index of the captions to be used for training. The COCO dataset has 5 captions per image. While training, one of these is chosen according to" " the value of this parameter. If -1, indices will be randomly chosen at runtime for each image.", 'type': click.IntRange(-1, 5) }, 'prune_batch_size': { 'help': "SpaCy's vocabulary is pruned to vocab_size in batches of this size." }, 'rnn_type': { 'help': "The type of RNN to use. Karpathy et.al. report better performance with an LSTM.", 'type': click.Choice(('RNN', 'LSTM')) }, 'hidden_size': { 'help': "The hidden size of RNN layers." }, 'num_layers': { 'help': "Number of stacked RNN layers to use." }, 'epochs': { 'help': "Number of epochs to train." }, 'iterations': { 'help': "Number of iterations to train. If this is positive, then epochs is overriden with this. Useful for debugging (eg. train for 1 iteration)." }, 'shuffle': { 'help': "Whether to shuffle the dataset while training. Shuffling generally produces better performance since the model can't overfit to specific batches." }, 'optimizer': { 'help': "The type of optimizer to use. When the papers came out, they reported using RMSProp. Adam was invented shortly afterwards. Use it (with AMSGrad)!", 'type': click.Choice(('adam', )) }, 'learning_rate': { 'help': "Learning rate. Constant throughout training." }, 'save_every': { 'help': "The frequency (number of minutes) with which the model is saved during training." }, 'write_every': { 'help': "The frequency (number of minutes) with which the training history is appended." }, 'beam_size': { 'help': "Captions are sampled using beam search with this size." }, 'probabilistic': { 'help': "If True, the beam search retains nodes at each iteration according to their probabilities." } }
farmer_rpc_port: Optional[int], ) -> None: from .farm_funcs import summary import asyncio asyncio.run(summary(rpc_port, wallet_rpc_port, harvester_rpc_port, farmer_rpc_port)) @farm_cmd.command("challenges", short_help="Show the latest challenges") @click.option( "-fp", "--farmer-rpc-port", help="Set the port where the Farmer is hosting the RPC interface. See the rpc_port under farmer in config.yaml", type=int, default=None, show_default=True, ) @click.option( "-l", "--limit", help="Limit the number of challenges shown. Use 0 to disable the limit", type=click.IntRange(0), default=20, show_default=True, ) def challenges_cmd(farmer_rpc_port: Optional[int], limit: int) -> None: from .farm_funcs import challenges import asyncio asyncio.run(challenges(farmer_rpc_port, limit))
#!/usr/bin/env python # vim: sw=2 ts=2 import click import os import sys @click.command() ### Cluster options @click.option('--console-port', default='443', type=click.IntRange(1,65535), help='OpenShift web console port', show_default=True) @click.option('--deployment-type', default='openshift-enterprise', help='OpenShift deployment type', show_default=True) @click.option('--openshift-sdn', default='redhat/openshift-ovs-subnet', help='OpenShift SDN (redhat/openshift-ovs-subnet, redhat/openshift-ovs-multitenant, or other supported SDN)', show_default=True) ### AWS/EC2 options @click.option('--region', default='us-east-1', help='ec2 region', show_default=True) @click.option('--ami', default='ami-10251c7a', help='ec2 ami', show_default=True) @click.option('--node-instance-type', default='t2.medium', help='ec2 instance type', show_default=True) @click.option('--use-cloudformation-facts', is_flag=True, help='Use cloudformation to populate facts. Requires Deployment >= OCP 3.5', show_default=True) @click.option('--keypair', help='ec2 keypair name', show_default=True) @click.option('--subnet-id', help='Specify a Private subnet within the existing VPC', show_default=True)
@click.option('--security-group-id', help='EC2 security group id to assign to instances VPC.') @click.option('--service-account-file', help='GCE service account file for login credentials.') @click.option('--ssh-key-name', help='Optional SSH private key-pair name for EC2.') @click.option('--ssh-private-key-file', type=click.Path(exists=True), help='SSH private key file for accessing instance.') @click.option('-u', '--ssh-user', help='SSH user for accessing instance.') @click.option('--subnet-id', help='Subnet to launch the new instance into.') @click.option('--test-dirs', help='Directories to search for tests.') @click.option('--timeout', help='The time to wait when establishing an SSH ' 'connection and for instances to change state.', type=click.IntRange(min=1)) @click.option('--vnet-name', help='Azure virtual network name to attach network interface.') @click.option('--vnet-resource-group', help='Azure resource group name where virtual network is found.') @click.option( '--collect-vm-info', is_flag=True, help='Controls whether general info about VM in cloud should be collected') @click.argument('cloud', type=click.Choice(SUPPORTED_CLOUDS)) @click.option('--compartment-id', help='The OCI compartment to use for image testing.') @click.option( '--availability-domain', help='The domain to place the instance and networking for testing.') @click.option('--signing-key-fingerprint',
im.save(name, format='JPEG') return except IOError: if self.parameters['iterations'] == 1: raise click.BadParameter(message='This image is beyond\ repair, maybe try again?', param_hint=['image']) self.parameters['iterations'] -= 1 self.glitch_bytes() @click.command() @click.option('--amount', '-a', type=click.IntRange(0, 99, clamp=True), default=random.randint(0, 99), help="Insert high or low values?") @click.option('--seed', '-s', type=click.IntRange(0, 99, clamp=True), default=random.randint(0, 99), help="Begin glitching at the\ start on a bit later on.") @click.option('--iterations', '-i', type=click.IntRange(0, 115, clamp=True), default=random.randint(0, 115), help="How many values should\ get replaced.") @click.option('--jpg',
#!/usr/bin/env python # vim: sw=2 ts=2 import click, os, sys, fileinput, json, iptools, ldap @click.command() ### Cluster options @click.option('--console_port', default='8443', type=click.IntRange(1, 65535), help='OpenShift web console port', show_default=True) @click.option('--deployment_type', default='openshift-enterprise', help='OpenShift deployment type', show_default=True) ### VMware options @click.option('--vcenter_host', default='10.19.114.221', help='vCenter IP Address', show_default=True) @click.option('--vcenter_username', default='*****@*****.**', help='vCenter Username', show_default=True) @click.option('--vcenter_password', default='P@ssw0rd', help='vCenter Password', show_default=True, hide_input=True)
korad_device.current_actual)) @korad.command(help='Get/Set voltage target/real value.') @click.option('--read', is_flag=True, help='Show presen output voltage.') @click.argument('voltage', required=False, type=float) def voltage(voltage, read): if voltage: korad_device.voltage = voltage if read or not voltage: echo('Set: {0}, Actual: {1}'.format(korad_device.voltage_set, korad_device.voltage_actual)) @korad.command(help='Save present values to device memory.') @click.option('-m', required=True, type=click.IntRange(1, 5), help='Number of memory bank to save to.') def save(m): korad_device.save_to_memory(m) @korad.command(help='Load values from device memory.') @click.option('-m', required=True, type=click.IntRange(1, 5), help='Number of memory bank to load from.') def load(m): korad_device.recall_from_memory(m)
SHELL_OPTION = click.option( "--shell", "-S", metavar="<shell>", default=get_default_shell, help=("The shell to use. " "[default: $DOITLIVE_INTERPRETER or $SHELL or /bin/bash]"), show_default=False, ) SPEED_OPTION = click.option( "--speed", "-s", metavar="<int>", type=click.IntRange(1), default=1, help="Typing speed.", show_default=True, ) PROMPT_OPTION = click.option( "--prompt", "-p", metavar="<prompt_theme>", default="default", type=click.Choice(THEMES.keys()), help="Prompt theme.", show_default=True, )
metavar="LOG", show_default=True, default=Path.cwd().joinpath("align_traj.log"), type=click.Path(exists=False, file_okay=True, dir_okay=False, resolve_path=True), help="Log file", ) @click.option( "--dt", "step", metavar="OFFSET", default=0, show_default=True, type=click.IntRange(min=0, clamp=True), help="Trajectory output offset (0 = single step)", ) @click.option( "-m", "--mask", default="ca", show_default=True, type=click.Choice(_MASK.keys()), help="Atom selection", ) @click.option( "-n", "--nmodes", "n_modes", metavar="NMODES",
raise click.Abort # Authenticate and Execute STAKEHOLDER.assimilate(checksum_address=client_account, password=password) emitter.echo("Broadcasting stake...", color='yellow') new_stake = STAKEHOLDER.initialize_stake(amount=value, lock_periods=lock_periods) painting.paint_staking_confirmation(emitter=emitter, staker=STAKEHOLDER, new_stake=new_stake) @stake.command() @group_transacting_staker_options @option_config_file @click.option('--enable/--disable', help="Used to enable and disable re-staking", is_flag=True, default=True) @click.option('--lock-until', help="Period to release re-staking lock", type=click.IntRange(min=0)) @option_force @group_general_config def restake(general_config, transacting_staker_options, config_file, enable, lock_until, force): """ Manage re-staking with --enable or --disable. """ emitter = _setup_emitter(general_config) STAKEHOLDER = transacting_staker_options.create_character(emitter, config_file) blockchain = transacting_staker_options.get_blockchain() client_account, staking_address = handle_client_account_for_staking( emitter=emitter, stakeholder=STAKEHOLDER, staking_address=transacting_staker_options.staker_options.staking_address,
else: txt = "Toggling power" result = c_vizio.pow_toggle() _LOGGER.info(txt) _LOGGER.info("OK" if result else "ERROR") @cli.command() @click.argument("state", required=False, default="up", type=click.Choice(["up", "down"])) @click.argument("amount", required=False, default=1, type=click.IntRange(1, 100, clamp=True)) @pass_vizio def volume(c_vizio, state, amount): amount = int(amount) if "up" == state: txt = "Increasing volume" result = c_vizio.vol_up(amount) else: txt = "Decreasing volume" result = c_vizio.vol_down(amount) _LOGGER.info(txt) _LOGGER.info("OK" if result else "ERROR") @cli.command() @pass_vizio
def divide(general_config, transacting_staker_options, config_file, force, value, lock_periods, index): """ Create a new stake from part of an existing one. """ # Setup emitter = _setup_emitter(general_config) STAKEHOLDER = transacting_staker_options.create_character(emitter, config_file) blockchain = transacting_staker_options.get_blockchain() economics = STAKEHOLDER.economics action_period = STAKEHOLDER.staking_agent.get_current_period() client_account, staking_address = handle_client_account_for_staking( emitter=emitter, stakeholder=STAKEHOLDER, staking_address=transacting_staker_options.staker_options.staking_address, individual_allocation=STAKEHOLDER.individual_allocation, force=force) # Dynamic click types (Economics) min_locked = economics.minimum_allowed_locked stake_value_range = click.FloatRange(min=NU.from_nunits(min_locked).to_tokens(), clamp=False) stake_extension_range = click.IntRange(min=1, max=economics.maximum_allowed_locked, clamp=False) if transacting_staker_options.staker_options.staking_address and index is not None: # 0 is valid. STAKEHOLDER.stakes = StakeList( registry=STAKEHOLDER.registry, checksum_address=transacting_staker_options.staker_options.staking_address) STAKEHOLDER.stakes.refresh() current_stake = STAKEHOLDER.stakes[index] else: current_stake = select_stake(stakeholder=STAKEHOLDER, emitter=emitter, divisible=True) # # Stage Stake # # Value if not value: min_allowed_locked = NU.from_nunits(STAKEHOLDER.economics.minimum_allowed_locked) max_divide_value = max(min_allowed_locked, current_stake.value - min_allowed_locked) value = click.prompt(f"Enter target value ({min_allowed_locked} - {str(max_divide_value)})", type=stake_value_range) value = NU(value, 'NU') # Duration if not lock_periods: extension = click.prompt("Enter number of periods to extend", type=stake_extension_range) else: extension = lock_periods if not force: painting.paint_staged_stake_division(emitter=emitter, stakeholder=STAKEHOLDER, original_stake=current_stake, target_value=value, extension=extension) click.confirm("Publish stake division to the blockchain?", abort=True) # Authenticate password = transacting_staker_options.get_password(blockchain, client_account) # Consistency check to prevent the above agreement from going stale. last_second_current_period = STAKEHOLDER.staking_agent.get_current_period() if action_period != last_second_current_period: emitter.echo("Current period advanced before stake division was broadcasted. Please try again.", red='red') raise click.Abort # Execute STAKEHOLDER.assimilate(checksum_address=current_stake.staker_address, password=password) emitter.echo("Broadcasting Stake Division...", color='yellow') modified_stake, new_stake = STAKEHOLDER.divide_stake(stake_index=current_stake.index, target_value=value, additional_periods=extension) emitter.echo('Successfully divided stake', color='green', verbosity=1) paint_receipt_summary(emitter=emitter, receipt=new_stake.receipt, chain_name=blockchain.client.chain_name) # Show the resulting stake list painting.paint_stakes(emitter=emitter, stakes=STAKEHOLDER.stakes)
@cli.command() @click.option( "--data", type=click.Path(exists=True), required=True, help="The traintest folder containing the data", ) @click.option( "--config", type=click.Path(exists=True), required=True, help="The model configuration file", ) @click.option( "--epochs", type=click.IntRange(min=1), default=1, help="Epochs between testing the model.", ) @click.option( "--batchsize", type=click.IntRange(min=1), default=1000, help="Training batch size" ) @click.option( "--test_batchsize", type=click.IntRange(min=1), default=1000, help="Testing batch size", ) @click.option( "--iterations", type=click.IntRange(min=1),