def convert(self, value, param, ctx): try: return self._annotation.parse_raw(value) except ValidationError as exc: typer.echo(exc, err=True, color=True) raise typer.Exit(code=1)
def main(skip_existing: bool = False, force: bool = False): """ Pull company metadata from LinkedIn and write to tags in README.md. Add tags <!--linkedin:company_name--><!--endlinkedin--> to README.md, where `company_name` corresponds to the last piece of the company's LinkedIn URL. """ # Read LinkedIn account details from .env or terminal. load_dotenv() email = os.getenv("LINKEDIN_EMAIL") password = os.getenv("LINKEDIN_PASSWORD") if email is None or password is None: typer.echo( "Enter LinkedIn account to query the API (or use .env file)") typer.echo( "WARNING: Accounts with excessive API calls are sometimes blocked " "by LinkedIn.") email = input("LinkedIn email: ") password = getpass.getpass() else: typer.echo("LinkedIn account details read from .env") # Set up LinkedIn API. api = Linkedin(email, password, refresh_cookies=True) def create_company_description(name): """Create a markup description of the company from its LinkedIn `name`.""" company = api.get_company(name) # Number of staff members. staff = company["staffCount"] staff_url = f"https://www.linkedin.com/company/{name}/people/" md = f" [👷 {staff}]({staff_url})" # Number of job openings. # Search for all jobs by the (full) company name first. # For generic company names, this will return a lot of false positives. full_name = company["name"] jobs_list = api.search_jobs(full_name, location_name="Berlin, Germany") # Then, filter by the company URN (unique identifier from LinkedIn). urn = company["entityUrn"] filtered_jobs_list = [ job for job in jobs_list if job["companyDetails"].get("company", "") == urn ] jobs = len(filtered_jobs_list) if jobs > 0: jobs_url = f"https://www.linkedin.com/company/{name}/jobs/" md += f" [🔎 {jobs}]({jobs_url})" # Funding round. if "fundingData" in company: funding_type = company["fundingData"]["lastFundingRound"][ "fundingType"] # Only show "Seed" or "Series X", otherwise show "X rounds" (there are some # other weird funding type names). if funding_type in [ "SEED", "SERIES_A", "SERIES_B", "SERIES_C", "SERIES_D" ]: funding = funding_type.replace("_", " ").title() else: funding_rounds = company["fundingData"]["numFundingRounds"] funding = f"{funding_rounds} round" if funding_rounds > 1: funding += "s" funding_url = company["fundingData"][ "fundingRoundListCrunchbaseUrl"] md += f" [💰 {funding}]({funding_url})" return md # Read README.md. with open("README.md", "r") as f: text = f.read() # Replace old descriptions with new ones. typer.echo("-" * 80) for name, old_desc in re.findall( "<!--linkedin:(.*?)-->(.*?)<!--endlinkedin-->", text): if skip_existing and old_desc: typer.echo(name + ": skipped") else: typer.echo(name + ":") new_desc = create_company_description(name) typer.echo(new_desc) text = text.replace( f"<!--linkedin:{name}-->{old_desc}<!--endlinkedin-->", f"<!--linkedin:{name}-->{new_desc}<!--endlinkedin-->", ) typer.echo() # typer.echo updated file content. typer.echo("-" * 80) typer.echo() typer.echo(text) typer.echo() typer.echo("-" * 80) # Write to file. if force: write = "y" else: write = input("Review modified text above. Write to README.md? (Y/n) ") if write.lower() in ["", "y", "yes"]: os.rename("README.md", "old-README.md") with open("README.md", "w") as f: f.write(text) typer.secho("✓ Updated README.md (old file stored in old-README.md", fg="green") else: typer.secho("✗ Did NOT update README.md", fg="red")
def main(key: str) -> None: """ Print config value of specified key. """ typer.echo(config.dict().get(key))
def users_create(user_name: str): typer.echo(f"Creating user: {user_name}")
def version_callback(value: bool): if value: typer.echo(f"Egon {__version__}") raise typer.Exit()
def config(user: str, cookies: str): typer.echo("正在设置用户和cookies") user = load_cfg().get('user', {}) user['user'], user['cookies'] = user, cookies
def main(config: typer.FileText = typer.Option(..., mode="a")): config.write("This is a single line\n") typer.echo("Config line written")
def download(assignment_id: int): """Download all assigned submissions for the given assignment ID""" typer.echo( f"Downloading assigned submissions for assignment no. {assignment_id}") scraper.download_all(assignment_id)
def marquis(title, description): """A display of the title + description that ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Looks Like This 'With a description in quotes' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ border_length = max(len(title), len(description or "")) + 8 border = "~" * border_length styled_title = typer.style(f" {title} ", bold=True, fg=typer.colors.MAGENTA) typer.echo(border) typer.echo() typer.echo(styled_title) if description: typer.echo(f" '{description}' ") typer.echo() typer.echo(border) typer.echo()
def print_name(name: str): typer.echo(name)
def check_parent_exists(path): if not path.parent.exists(): typer.echo(f"The path you've supplied {path} does not exist.") raise typer.Exit(code=1) return path
def check_client_secret_exists(): if not client_secrets_path.is_file(): typer.echo( "client_secrets.json file is not set yet, set using colab-cli set-config client_secrets.json" ) raise typer.Exit()
def info(): typer.echo("About Explosion: https://explosion.ai\n\n" "About spaCy: https://https://spacy.io\n\n")
def pull(manifest_url: str, target_path: str, on_conf_change: str = typer.Option( "", help="Shell command to execute if configuration changed")): """bucket -> fs""" try: bucket, manifest_path = cloud.get_bucket(manifest_url) except CloudStorageError: typer.echo(f"ERROR: Could not access bucket {manifest_url}") raise typer.Exit(code=1) bucketroot = os.path.dirname(manifest_path) pool_path = os.path.join(target_path, "_pool") os.makedirs(pool_path, exist_ok=True) changes = 0 # download manifest manif = io.BytesIO() try: bucket.get_blob(manifest_path).download(manif) except NotFoundError: typer.echo(f"ERROR: Manifest {manifest_path} does not exist") raise typer.Exit(code=1) manifest_str = manif.getvalue().decode("utf-8") manifest = json.loads(manifest_str) conf_path = os.path.join(target_path, "configs", manifest["meta"]["id"], manifest["meta"]["version"]) os.makedirs(conf_path, exist_ok=True) typer.echo("Creating configuration [%s]" % conf_path) open(os.path.join(conf_path, "manifest.json"), "w").write(manifest_str) # synchronize pool for fname, h in manifest["files"].items(): pool_file = os.path.join(pool_path, h) if not os.path.exists(pool_file): typer.echo("Pulling new version of [%s]" % fname) try: blobpath = os.path.join(bucketroot, "_pool", h) blob = bucket.get_blob(blobpath) except NotFoundError: typer.echo(f"ERROR: Manifest {blobpath} does not exist") raise typer.Exit(code=1) blob.download(pool_file) changes += 1 if os.path.isabs(fname): fname = fname[1:] conf_file = os.path.join(conf_path, fname) conf_file_dir = os.path.dirname(conf_file) os.makedirs(conf_file_dir, exist_ok=True) rel_link = os.path.relpath(pool_file, conf_file_dir) try: old_link = os.readlink(conf_file) except OSError: try: os.unlink(conf_file) except FileNotFoundError: pass os.symlink(rel_link, conf_file) changes += 1 else: if old_link != rel_link: # ~atomic symlink replacement os.symlink(rel_link, conf_file + ".tmp") os.replace(conf_file + ".tmp", conf_file) changes += 1 current_conf = os.path.join(target_path, "current") new_conf = os.path.relpath(conf_path, target_path) try: old_conf = os.readlink(current_conf) except OSError: try: os.unlink(current_conf) except FileNotFoundError: pass os.symlink(new_conf, current_conf) changes += 1 else: if old_conf != new_conf: # ~atomic symlink replacement os.symlink(new_conf, current_conf + ".tmp") os.replace(current_conf + ".tmp", current_conf) changes += 1 if changes and on_conf_change: os.system(on_conf_change)
def hello(name: str): typer.echo(f"Hello {name}")
def warn_missing_file(name): """A generic warning when a Procedure with the specified name does not exist""" message = typer.style(glot.localized("missing_file_warn", {"name": name}), **WARNING_STYLE) typer.echo(message)
def main( name: str = typer.Option( "World", help="The name to say hi to.", autocompletion=complete_name ) ): typer.echo(f"Hello {name}")
def send_command(command: str, c2: str, mobile_number: str = "xx"): client = Client(c2=c2, mobile_number=mobile_number) res = client.query(command) formatted_json = json.dumps(res, indent=2) typer.echo(formatted_json)
def upload(path: str): user = load_cfg().get('user', {}) if not user: typer.echo("请先设置用户和Cookies, Useage: easy_mindoc config [user_id] [cookies]") return
def analyze_apk(path: str, extract_dex: bool = False, verbose: bool = False): res = analyze(path, extract_dex, verbose) formatted_json = json.dumps(res, indent=2) typer.echo(formatted_json)
def users_delete(user_name: str): typer.echo(f"Deleting user: {user_name}")
def init(): typer.echo("Initializing user database")
def version() -> None: typer.echo(idom.__version__)
def create(username: str): typer.echo(f"Creating user: {username}")
def info(root: Optional[Path] = typer.Option(None)): """ Display information for local KB """ kb = KB(root=root) flat = sorted(services.flatten_dict(kb.info()).items()) output = tabulate(flat, tablefmt="pretty", colalign=("left", "right")) typer.echo(output)
def sites(): typer.echo(json.dumps(SITES_AVAILABLE, indent=4))
# completion testing import typer if __name__ == '__main__': import sys from pathlib import Path sys.path.insert(0, str(Path.cwd())) from centralcli import cache matches = [ f"{m[0]}\t{m[1]}" for m in cache.dev_template_completion(sys.argv[-1], sys.argv[1:-1]) ] typer.echo("\n".join(matches)) ...
def goodbye(name: str, formal: bool = False): if formal: typer.echo(f"Goodbye Ms. {name}. Have a good day.") else: typer.echo(f"Bye {name}!")
def main(name: str = typer.Argument("Wade Wilson")): typer.echo(f"Hello {name}")
def update_single_lang(lang: str): lang_path = docs_path / lang typer.echo(f"Updating {lang_path.name}") update_config(lang_path.name)