def generate_service_account( service_account_path: pathlib.Path, ) -> CoCoHubServiceAccount: """ generate service account and attach to the user profile on cocohub """ service_account = CoCoHubServiceAccount( name=platform.uname().node, client_id=secrets.token_urlsafe(12), client_secret=secrets.token_urlsafe(24), ) service_account_path.parent.mkdir(exist_ok=True) with service_account_path.open("w") as f: json.dump(service_account.dict(), f, indent=True) with service_account_path.open("r") as f: base64_service_account = base64.b64encode( f.read().encode("utf-8")).decode("utf-8") typer.launch(COCOHUB_AUTHORIZE_SERVICE_ACCOUNT_URL + f"?serviceAccount={base64_service_account}") if not typer.confirm("Are you done authenticating at CoCoHub?"): service_account_path.unlink() raise Exception( "No service account. try again after authenticating at CoCoHub") return service_account
def create(name: str = typer.Argument(...)): """ Create an API Object """ config_path = os.path.join(arc["arco"]["app_dir"], name) config_file = os.path.join(config_path, "arco.yml") config = benedict() try: if not os.path.exists(config_path): logger.debug(f"Creating directory {config_path}") os.mkdir(config_path) if not os.path.exists(config_file): logger.debug(f"Creating {config_file}") config.to_yaml(filepath=config_file) typer.launch(config_file) except Exception as e: logger.error(f"{e}") typer.launch(config_file) return True
def fetch_protein_ids() -> None: adapter = HTTPAdapter(max_retries=5) with requests.Session() as session: session.mount(URL, adapter) try: response = session.get( URL, timeout=600, ) # Create a fasta file with filtered protein ids. This file is then uploaded # to http://weizhong-lab.ucsd.edu/cdhit_suite/cgi-bin/index.cgi?cmd=cd-hit to # perform homology mapping with default settings and 30% sequence identity cutoff. typer.echo( "Opening CD-Hit: perform homology mapping with default settings and 30%% sequence identity cutoff." ) typer.launch( "http://weizhong-lab.ucsd.edu/cdhit_suite/cgi-bin/index.cgi?cmd=cd-hit" ) out_path = Path("filtered_protein_ids.fasta") out_path.write_text(response.text) except ConnectionError as connection_error: print(connection_error)
def hello_world(): """our first CLI with typer! """ typer.echo("Opening blog post...") typer.launch( "https://pluralsight.com/tech-blog/python-cli-utilities-with-poetry-and-typer" )
def dest(name, ctx: typer.Context): storage = ctx.obj["storage"] destinations = storage.destinations if destinations.get(name, False): typer.secho(f"Taking you to {destinations[name]}. 🚀") typer.launch(destinations[name]) else: typer.secho(f"No destination found with name: {name}", fg="red")
def createAccount(): """" this allows user to create new account """ check = typer.confirm( "Can you verify for me that you don't have a connections account?") if check: typer.echo("launching site so you can create your account....") typer.launch("http://127.0.0.1:5000/")
def launch(): """ Launch gradio instance """ typer.echo("Launching gradio instance") _, gradio_interface_url, _ = gr.Interface( fn=greet, inputs="text", outputs="text" ).launch() typer.launch(gradio_interface_url)
def main(): app_dir = typer.get_app_dir(APP_NAME) app_dir_path = Path(app_dir) app_dir_path.mkdir(parents=True, exist_ok=True) config_path: Path = Path(app_dir) / "config.json" if not config_path.is_file(): config_path.write_text('{"version": "1.0.0"}') config_file_str = str(config_path) print("Opening config directory") typer.launch(config_file_str, locate=True)
def pinhop( yearsago: int = typer.Option( 1, "--yearsago", "-y", help="Number of years ago this month" ), cli_token: str = typer.Option( None, "--token", help=( "Pinboard API token (see https://pinboard.in/settings/password). " "Required if PINBOARD_TOKEN environment variable not set." ), envvar="PINBOARD_TOKEN", ), fname: str = typer.Option("pinhop.html", "--out", help="Output file"), date: str = typer.Option( None, help=( "Get posts for particular month (YYYY-MM format) or day " "(YYYY-MM-DD) (overrides y)" ), ), browse: bool = typer.Option( False, help="Load output file in browser when finished", ), ): """ Get pinboard posts from a previous month or day. By default, writes posts from this month one year ago to pinhop.html. """ global auth_token auth_token = cli_token year, month, day = None, None, None if date: try: date_dt = dt.strptime(date, "%Y-%m") year, month, day = date_dt.year, date_dt.month, None except ValueError: date_dt = dt.strptime(date, "%Y-%m-%d") year, month, day = date_dt.year, date_dt.month, date_dt.day title = date else: suffix = "" if yearsago == 1 else "s" title = f"{yearsago} year{suffix} ago" posts = get_posts(yearsago=yearsago, year=year, month=month, day=day) page = assemble_page(posts, title=title) with open(fname, "w") as f: f.write(page) if browse: typer.launch(fname)
def edit(default: bool = typer.Option(False, help="Edit the default context file")): """ Edit the context file. Will use context_dir to determine the file to edit """ default_context_file = os.path.join(arc["arco"]["app_dir"], "arco.yml") current_context_file = os.path.join(arc["arco"]["context"]["dir"], "arco.yml") if os.path.exists(current_context_file) and not default: typer.launch(current_context_file) else: typer.launch(default_context_file)
def build( show: bool = typer.Option( False, help="Open the docs in a browser after they have been built."), sphinx_args: List[str] = typer.Argument(None), ): """ Build the documentation. \f :param show: Open the docs in a browser after they have been built, defaults to False. :param sphinx_args: Any remaining arguments will be passed to the underlying ``sphinx_main()`` function that actually builds the docs. .. important:: If these arguments contain ``-`` or ``--`` flags, you will need to preface this argument list with ``--``. **Examples:** .. code-block:: shell :caption: Simple build $ docs build .. code-block:: shell :caption: Open the docs afterwards $ docs build --show .. code-block:: shell :caption: Perform a full rebuild with debug logging $ docs --log-level DEBUG build -- a """ # Check that both the schema and the sample component.yaml file are correct _validate_component_schema() built_path = pathlib.Path("docs") / "built" logger.info("Generating docs at %s", built_path.as_posix()) result = sphinx_main(["-b", "html", "docs/source", "docs/built"]) if not result: logger.success("Docs generated at %s", built_path.as_posix()) else: logger.error("Docs not generated") raise typer.Abort("Failed to build docs") if show: logger.notice("Opening generated docs in a browser") typer.launch((built_path / "index.html").as_posix())
def edit(): """Edit catalogues Work in progress """ app_path = Path(typer.get_app_dir(APP_NAME)) if not app_path.is_dir(): app_path.mkdir() config_path: Path = app_path / "config.yaml" if not config_path.is_file(): config_path.write_text('{"version": "1.0.0"}') print(config_path) typer.launch(str(config_path), locate=True)
def show(): """ Open the documentation in a browser. \f **Example:** .. code-block:: shell :caption: Open the docs $ docs show """ logger.notice("Opening generated docs in a browser") built_path = pathlib.Path("docs") / "built" / "index.html" typer.launch(built_path.as_posix())
def http(): """ Runs the REST API http endpoint on localhost. """ # See: # https://www.uvicorn.org/deployment/ # https://fastapi.tiangolo.com/#example # https://typer.tiangolo.com/tutorial/launch/ typer.echo("Launching web browser to api docs:") typer.launch("http://127.0.0.1:8000/docs") uvicorn.run( "senserecord.main:web", host="127.0.0.1", port=8000, reload=True, # For development log_level="info", )
def edit() -> None: """Edit the configuration""" config_path = Config.path() typer.launch(str(config_path))
def github(): """open github repo for Kiki""" typer.echo('Opening GitHub Repo...') typer.launch('https://github.com/VijayStroup/Kiki')
def launch(): """ Opens the configuration file in default editor """ if not typer.launch(config_path.as_uri()): console.print()
async def proxy_example( proxy: str = "http://127.0.0.1", host: str = "https://www.amazon.com/ap/signin?openid.pape.max_auth_age=0&openid.return_to=https%3A%2F%2Fwww.amazon.com%2F%3Fref_%3Dnav_signin&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.assoc_handle=usflex&openid.mode=checkid_setup&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&", callback: str = "", timeout: int = 300, debug: bool = False, ): """Run proxy example for Amazon.com. Args: proxy (str, optional): The url to connect to the proxy. If no port specified, will generate random port. Defaults to "http://127.0.0.1". host (str, optional): The signing page to proxy. Defaults to "https://www.amazon.com/ap/signin?openid.pape.max_auth_age=0&openid.return_to=https%3A%2F%2Fwww.amazon.com%2F%3Fref_%3Dnav_signin&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.assoc_handle=usflex&openid.mode=checkid_setup&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&". callback (str, optional): Callback url to redirect browser to on success. Defaults to "". timeout (int, optional): How long to leave the proxy running without success. Defaults to 300. debug (bool, optional): Whether to print debug messages to console. Defaults to False. """ if debug: logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) proxy_url = URL() host_url = URL() callback_url = URL() if proxy: proxy_url = URL(proxy) if host: host_url = URL(host) if callback: callback_url = URL(callback) proxy_obj: AuthCaptureProxy = AuthCaptureProxy(proxy_url=proxy_url, host_url=host_url) def test_url(resp: httpx.Response, data: Dict[Text, Any], query: Dict[Text, Any]): """Test for a successful Amazon URL. Args: resp (httpx.Response): The httpx response. data (Dict[Text, Any]): Dictionary of all post data captured through proxy with overwrites for duplicate keys. query (Dict[Text, Any]): Dictionary of all query data with overwrites for duplicate keys. Returns: Optional[Union[URL, Text]]: URL for a http 302 redirect or Text to display on success. None indicates test did not pass. """ # Did we reach specific url? typer.echo(f"URL {resp.url}") if "https://www.amazon.com/?ref_=nav_signin" in str(resp.url): # save any needed info from resp, data, or query # cookies will be in proxy.session.cookie_jar asyncio.create_task(proxy_obj.stop_proxy(3)) # stop proxy in 3 seconds if callback_url: return URL(callback_url) # 302 redirect return f"Successfully logged in {data.get('email')} and {data.get('password')}. Please close the window.<br /><b>Post data</b><br />{json.dumps(data)}<br /><b>Query Data:</b><br />{json.dumps(query)}<br /><b>Cookies:</b></br>{json.dumps(list(proxy_obj.session.cookies.items()))}" await proxy_obj.start_proxy() # add tests and modifiers after the proxy has started so that port data is available for self.access_url() # add tests. See :mod:`authcaptureproxy.examples.testers`. proxy_obj.tests = {"test_url": test_url} # add modifiers like autofill to manipulate html returned to browser. See :mod:`authcaptureproxy.examples.modifiers`. # this will add to any default modifiers proxy_obj.modifiers.update( { "text/html": { "autofill": partial( autofill, { "password": "******", }, ) } } ) # add filter to redirect check. Filter out all urls from redirect check. proxy_obj.redirect_filters = {"url": ["^.*$"]} # connect to proxy at proxy.access_url() and sign in typer.echo( f"Launching browser to connect to proxy at {proxy_obj.access_url()} and sign in using logged-out account." ) typer.launch(str(proxy_obj.access_url())) typer.echo(f"Proxy will timeout and close in {datetime.timedelta(seconds=timeout)}.") asyncio.create_task(proxy_obj.stop_proxy(timeout)) # or stop the proxy when done manually while proxy_obj.active: # loop until proxy done await asyncio.sleep(1) typer.echo("Proxy completed; exiting") raise typer.Exit()
def docs_callback(value: bool): """function to open docs""" if value: typer.echo("Opening https://eaton-lab.org/traversome in default browser") typer.launch("https://eaton-lab.org/traversome") raise typer.Exit()
def docs_callback(value: bool): "function to open docs" if value: typer.echo("Opening https://eaton-lab.org/kmerkit in default browser") typer.launch("https://eaton-lab.org/kmerkit") raise typer.Exit()
def open_conf_path(): """ Open the config file location """ typer.secho("Opening config file...") typer.launch(str(config_file_path), locate=True)
def main(): typer.echo("Opening Typer's docs") typer.launch("https://typer.tiangolo.com")
def cli( image_path: Path = typer.Argument( ..., help="Image file which contains bread and banana" ), num_slices: int = typer.Option( 22, help="Total number of slices to cut the banana into. This number defines the slice thickness.", ), mask_threshold: float = typer.Option(0.6, help="Threshold of segmentation mask."), peel_scaler: float = typer.Option( 0.8, help="Fraction of slice that is assumed to belong to banana insides versus the peel.", ), ellipse_ratio: float = typer.Option( 0.85, help="Assumed ratio of minor axis to major axis of banana slice ellipses" ), plot_segmentation: bool = typer.Option( False, help="Whether or not to plot the segmentation masks" ), plot_slicing: bool = typer.Option( False, help="Whether or not to plot the slicing circle and skeleton" ), output: str = typer.Option("perfect_sandwich.jpg", help="Name of file to output"), suppress: bool = typer.Option( False, help="Whether or not to suppress the output file from being automatically opened", ), ): typer.secho(f"Segmenting image looking for {_BANANA} and {_BREAD}", fg=_FG) try: with click_spinner.spinner(): image, banana, bread = segmentation.run(image_path) except SegmentNotFound: typer.secho( "Oh no! Can't find the banana or bread in the image", fg=typer.colors.RED, ) raise SegmentNotFound typer.secho(f"Slicing the {_BANANA}", fg=_FG) with click_spinner.spinner(): slices, banana_circle, banana_centroid, banana_skeleton = slicing.run( banana.mask, num_slices=num_slices, mask_threshold=mask_threshold, peel_scaler=peel_scaler, ellipse_ratio=ellipse_ratio, ) typer.secho("Optimizing slice coverage", fg=_FG) with click_spinner.spinner(): slices, bread_box = nesting.run(slices, bread, mask_threshold=mask_threshold) viz.plot( image, slices=slices, banana=banana if plot_segmentation else None, bread=bread if plot_segmentation else None, banana_skeleton=banana_skeleton if plot_slicing else None, banana_circle=banana_circle if plot_slicing else None, banana_centroid=banana_centroid if plot_slicing else None, bread_box=bread_box if plot_slicing else None, output=output, ) typer.secho(f"Nested nanner saved to {output}", fg=_FG) if not suppress: typer.launch(output)