news 2026/6/12 15:51:08

SelectExamples 根据类名和语言寻找某一个类的示例代码

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
SelectExamples 根据类名和语言寻找某一个类的示例代码

一:主要的知识点

1、说明

本文只是教程内容的一小段,因博客字数限制,故进行拆分。主教程链接:vtk教程——逐行解析官网所有Python示例-CSDN博客

2、知识点纪要

本段代码主要涉及的有①根据类名寻找示例代码


二:代码及注释

#!/usr/bin/env python3 import json import os import random import tempfile from datetime import datetime from operator import itemgetter from pathlib import Path from urllib.error import HTTPError from urllib.request import urlretrieve def get_program_parameters(): import argparse description = 'Get examples that use a particular VTK class for a given language.' epilogue = ''' The JSON file needed by this script is obtained from the gh-pages branch of the vtk-examples GitHub site. It is stored in your tempfile directory. If you change the URL to the JSON file, remember that there is a ten minute wait before you can overwrite the last downloaded file. To force the download specify -o on the command line. Here is the URL for an alternative site for testing: "https://raw.githubusercontent.com/ajpmaclean/web-test/gh-pages/src/Coverage/vtk_vtk-examples_xref.json" ''' parser = argparse.ArgumentParser(description=description, epilog=epilogue, formatter_class=argparse.RawTextHelpFormatter) # parser.add_argument('vtk_class', default="vtkFiltersSources",help='The desired VTK class.') # parser.add_argument('language', default="Python",help='The desired language, one of: CSharp, Cxx, Java, Python.') parser.add_argument('-a', '--all_values', action="store_true", help='All examples (Warning: Can be a very long list).') parser.add_argument('-n', '--number', type=int, default=5, help='The maximum number of examples.') parser.add_argument('-m', '--md', action='store_true', help='Display links in markdown inline format e.g. [label](URL).') parser.add_argument('-j', '--json_xref_url', default='https://raw.githubusercontent.com/Kitware/vtk-examples/gh-pages/src/Coverage/vtk_vtk-examples_xref.json', help='The URL for the JSON cross-reference file.') parser.add_argument('-o', '--overwrite', action="store_true", help='Force an initial download of the JSON cross-reference file.') args = parser.parse_args() return args.all_values, args.md, args.number, args.json_xref_url, args.overwrite def download_file(dl_path, dl_url, overwrite=False): """ Use the URL to get a file. :param dl_path: The path to download the file to. :param dl_url: The URL of the file. :param overwrite: If true, do a download even if the file exists. :return: The path to the file as a pathlib Path. """ file_name = dl_url.split('/')[-1] # Create necessary subdirectories in the dl_path # (if they don't exist). Path(dl_path).mkdir(parents=True, exist_ok=True) # Download if it doesn't exist in the directory overriding if overwrite is True. path = Path(dl_path, file_name) if not path.is_file() or overwrite: try: urlretrieve(dl_url, path) except HTTPError as e: raise RuntimeError(f'Failed to download {dl_url}. {e.reason}') return path def get_examples(d, vtk_class, lang, all_values=False, number=5, md_fmt=False): """ For the VTK Class and language return the total number of examples and a list of examples. :param d: The dictionary. :param vtk_class: The VTK Class e.g. vtkActor. :param lang: The language, e.g. Cxx. :param all_values: True if all examples are needed. :param number: The number of values. :param md_fmt: Use Markdown format with label and URL defined together. :return: Total number of examples and a list of examples. """ try: kv = d[vtk_class][lang].items() except KeyError: return None, None if len(kv) > number: if all_values: samples = list(kv) else: samples = random.sample(list(kv), number) else: samples = kv if md_fmt: links = [f'[{s.rsplit("/", 1)[1]}]({s})' for s in sorted(map(itemgetter(1), samples))] else: links = sorted(map(itemgetter(1), samples)) return len(links), links def get_crossref_dict(ref_dir, xref_url, overwrite=False): """ Download and return the json cross-reference file. This function ensures that the dictionary is recent. :param ref_dir: The directory where the file will be downloaded. :param xref_url: The URL for the JSON cross-reference file. :param overwrite: If true, do a download even if the file exists. :return: The dictionary cross-referencing vtk classes to examples. """ path = download_file(ref_dir, xref_url, overwrite=overwrite) if not path.is_file(): print(f'The path: {str(path)} does not exist.') return None dt = datetime.today().timestamp() - os.path.getmtime(path) # Force a new download if the time difference is > 10 minutes. if dt > 600: path = download_file(ref_dir, xref_url, overwrite=True) with open(path) as json_file: return json.load(json_file) def main(): all_values, md, number, xref_url, overwrite = get_program_parameters() vtk_class = "vtkNamedColors" language = "Python" language = language.lower() available_languages = {k.lower(): k for k in ['CSharp', 'Cxx', 'Java', 'Python', 'PythonicAPI']} available_languages.update({'cpp': 'Cxx', 'c++': 'Cxx', 'c#': 'CSharp'}) if language not in available_languages: print(f'The language: {language} is not available.') tmp = ', '.join(sorted([lang for lang in set(available_languages.values())])) print(f'Choose one of these: {tmp}.') return else: language = available_languages[language] xref_dict = get_crossref_dict(tempfile.gettempdir(), xref_url, overwrite) if xref_dict is None: print('The dictionary cross-referencing vtk classes to examples was not downloaded.') return total_number, examples = get_examples(xref_dict, vtk_class, language, all_values=all_values, number=number, md_fmt=md) if examples: if total_number <= number or all_values: print(f'VTK Class: {vtk_class}, language: {language}\n' f'Number of example(s): {total_number}.') else: print(f'VTK Class: {vtk_class}, language: {language}\n' f'Number of example(s): {total_number} with {number} random sample(s) shown.') print('\n'.join(examples)) else: print(f'No examples for the VTK Class: {vtk_class} and language: {language}') if __name__ == '__main__': main()
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/5 18:39:52

强化学习笔记

基本概念 强化学习中涉及的基本概念&#xff1a; 环境 (Environment)&#xff1a;环境是智能体所处的外部系统&#xff0c;它负责产生当前的状态&#xff0c;接收智能体的动作并返回新的状态和对应的奖励。环境的作用相当于模拟现实中的条件和反应规则&#xff0c;智能体只能通…

作者头像 李华
网站建设 2026/6/10 16:19:56

揭秘要诀!AI应用架构师揭秘企业算力资源调度要诀

揭秘要诀&#xff01;AI应用架构师揭秘企业算力资源调度要诀 关键词&#xff1a;AI应用架构师、企业算力资源调度、资源分配、负载均衡、调度算法、算力优化、云计算 摘要&#xff1a;本文由AI应用架构师深入剖析企业算力资源调度的关键要诀。首先介绍算力资源调度在企业发展尤…

作者头像 李华
网站建设 2026/6/10 17:34:53

Java计算机毕设之基于SpringBoot的高尔夫球场管理系统场地预订、会员管理的设计与实现(完整前后端代码+说明文档+LW,调试定制等)

博主介绍&#xff1a;✌️码农一枚 &#xff0c;专注于大学生项目实战开发、讲解和毕业&#x1f6a2;文撰写修改等。全栈领域优质创作者&#xff0c;博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围&#xff1a;&am…

作者头像 李华
网站建设 2026/6/10 14:02:37

Java毕设项目:基于Springboot高尔夫场地预约网站管理系统基于SpringBoot的高尔夫球场管理系统的设计与实现(源码+文档,讲解、调试运行,定制等)

博主介绍&#xff1a;✌️码农一枚 &#xff0c;专注于大学生项目实战开发、讲解和毕业&#x1f6a2;文撰写修改等。全栈领域优质创作者&#xff0c;博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围&#xff1a;&am…

作者头像 李华
网站建设 2026/6/9 22:55:01

计算机Java毕设实战-基于SpringBoot的高尔夫球场管理系统的设计与实现基于SpringBoot+Vue的高尔夫球场服务系统设计与实现【完整源码+LW+部署说明+演示视频,全bao一条龙等】

博主介绍&#xff1a;✌️码农一枚 &#xff0c;专注于大学生项目实战开发、讲解和毕业&#x1f6a2;文撰写修改等。全栈领域优质创作者&#xff0c;博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围&#xff1a;&am…

作者头像 李华
网站建设 2026/6/10 14:03:54

Agentic AI的10大技术创新案例:提示工程架构师的必备技能

Agentic AI的10大技术创新案例&#xff1a;提示工程架构师的必备技能 1. 引入与连接&#xff1a;当AI从“回答者”变成“行动者” 清晨7点&#xff0c;你揉着眼睛打开手机&#xff0c;收到一条消息&#xff1a;“您的生日派对方案已优化完成&#xff1a;原本预订的法式餐厅因周…

作者头像 李华