instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Improve documentation using docstrings
# Copyright (c) 2023 Amphion. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # This code is borrowed from https://github.com/yl4579/PitchExtractor/blob/main/model.py import torch from torch import nn class JDCNet(nn.Module): def __i...
--- +++ @@ -5,11 +5,20 @@ # This code is borrowed from https://github.com/yl4579/PitchExtractor/blob/main/model.py +""" +Implementation of model from: +Kum et al. - "Joint Detection and Classification of Singing Voice Melody Using +Convolutional Recurrent Neural Networks" (2019) +Link: https://www.semanticscholar.o...
https://raw.githubusercontent.com/index-tts/index-tts/HEAD/indextts/utils/maskgct/models/codec/facodec/modules/JDC/model.py
Create documentation for each function signature
# Copyright (c) 2023 Amphion. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # # Copyright (c) ByteDance, Inc. and its affiliates. # Copyright (c) Chutong Meng # # This source code is licensed under the CC BY-NC license found in the # LICENS...
--- +++ @@ -17,6 +17,7 @@ class VectorQuantize(nn.Module): + """Vector quantization w/ exponential moving averages (EMA)""" def __init__( self, @@ -107,6 +108,7 @@ class ResidualVQ(nn.Module): + """Residual VQ following algorithm 1. in https://arxiv.org/pdf/2107.03312.pdf""" def __i...
https://raw.githubusercontent.com/index-tts/index-tts/HEAD/indextts/utils/maskgct/models/codec/vevo/vevo_repcodec.py
Add docstrings for internal functions
import torch import librosa import json5 from huggingface_hub import hf_hub_download from transformers import SeamlessM4TFeatureExtractor, Wav2Vec2BertModel import safetensors import numpy as np from indextts.utils.maskgct.models.codec.kmeans.repcodec_model import RepCodec from indextts.utils.maskgct.models.tts.maskgc...
--- +++ @@ -13,6 +13,15 @@ def _load_config(config_fn, lowercase=False): + """Load configurations into a dictionary + + Args: + config_fn (str): path to configuration file + lowercase (bool, optional): whether changing keys to lower case. Defaults to False. + + Returns: + dict: diction...
https://raw.githubusercontent.com/index-tts/index-tts/HEAD/indextts/utils/maskgct_utils.py
Write docstrings for this repository
import argparse import base64 import configparser import datetime import io import json import os import re from collections import namedtuple import arxiv import fitz import numpy as np import openai # 导入所需的库 import requests import tenacity import tiktoken from bs4 import BeautifulSoup from PIL import Image ArxivPar...
--- +++ @@ -73,6 +73,12 @@ return first_page_text def get_image_path(self, image_path=''): + """ + 将PDF中的第一张图保存到image.png里面,存到本地目录,返回文件名称,供gitee读取 + :param filename: 图片所在路径,"C:\\Users\\Administrator\\Desktop\\nwd.pdf" + :param image_path: 图片提取后的保存路径 + :return: + ...
https://raw.githubusercontent.com/kaixindelele/ChatPaper/HEAD/others/chat_arxiv_maomao.py
Fully document this Python code with docstrings
import argparse import base64 import configparser import datetime import io import json import os import re from collections import namedtuple # import arxiv import fitz import numpy as np import openai # 导入所需的库 import requests import tenacity import tiktoken from bs4 import BeautifulSoup from PIL import Image import ...
--- +++ @@ -75,6 +75,12 @@ return first_page_text def get_image_path(self, image_path=''): + """ + 将PDF中的第一张图保存到image.png里面,存到本地目录,返回文件名称,供gitee读取 + :param filename: 图片所在路径,"C:\\Users\\Administrator\\Desktop\\nwd.pdf" + :param image_path: 图片提取后的保存路径 + :return: + ...
https://raw.githubusercontent.com/kaixindelele/ChatPaper/HEAD/chat_arxiv.py
Generate docstrings with examples
# Copyright (c) 2023 Amphion. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # This source file is copied from https://github.com/facebookresearch/encodec # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This ...
--- +++ @@ -10,6 +10,7 @@ # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. +"""Residual vector quantizer implementation.""" from dataclasses import dataclass, field import math @@ -31,6 +32,18 @@ class ResidualVectorQuantizer(nn.Module): ...
https://raw.githubusercontent.com/index-tts/index-tts/HEAD/indextts/utils/maskgct/models/codec/speechtokenizer/modules/quantization/vq.py
Generate NumPy-style docstrings
# Standard library imports import ast import asyncio import logging import random import re import ssl import sys from typing import Dict, List, Optional, Tuple from urllib.parse import quote # Third party imports import aiodns from alive_progress import alive_bar from aiohttp import ClientSession, TCPConnector, http_...
--- +++ @@ -592,6 +592,41 @@ *args, **kwargs, ) -> QueryResultWrapper: + """Main search func + + Checks for existence of username on certain sites. + + Keyword Arguments: + username -- Username string will be used for search. + site_dict -- Dictionary containing sites...
https://raw.githubusercontent.com/soxoj/maigret/HEAD/maigret/checking.py
Document this script properly
import numpy as np import os import re import datetime import arxiv import tenacity import base64, requests import argparse import configparser import fitz, io, os from PIL import Image import gradio import markdown from optimizeOpenAI import chatPaper class Paper: def __init__(self, path, title='', url='', abs='',...
--- +++ @@ -43,6 +43,12 @@ self.pdf.close() def get_image_path(self, image_path=''): + """ + 将PDF中的第一张图保存到image.png里面,存到本地目录,返回文件名称,供gitee读取 + :param filename: 图片所在路径,"C:\\Users\\Administrator\\Desktop\\nwd.pdf" + :param image_path: 图片提取后的保存路径 + :retu...
https://raw.githubusercontent.com/kaixindelele/ChatPaper/HEAD/HuggingFaceDeploy/Private/app.py
Generate consistent documentation across files
import numpy as np import os import re import datetime import arxiv import openai, tenacity import base64, requests import argparse import configparser import fitz, io, os from PIL import Image import gradio import markdown import json import tiktoken import concurrent.futures from optimizeOpenAI import chatPaper impor...
--- +++ @@ -130,6 +130,12 @@ return first_page_text def get_image_path(self, image_path=''): + """ + 将PDF中的第一张图保存到image.png里面,存到本地目录,返回文件名称,供gitee读取 + :param filename: 图片所在路径,"C:\\Users\\Administrator\\Desktop\\nwd.pdf" + :param image_path: 图片提取后的保存路径 + :return: + ...
https://raw.githubusercontent.com/kaixindelele/ChatPaper/HEAD/HuggingFaceDeploy/Public/app.py
Annotate my code with docstrings
import asyncio import sys import time from typing import Any, Iterable, List, Callable import alive_progress from alive_progress import alive_bar from .types import QueryDraft def create_task_func(): if sys.version_info.minor > 6: create_asyncio_task = asyncio.create_task else: loop = asynci...
--- +++ @@ -111,6 +111,7 @@ # TODO: tests async def increment_progress(self, count): + """Update progress by calling the provided progress function.""" if self.progress: if asyncio.iscoroutinefunction(self.progress): await self.progress(count) @@ -120,6 +121,7 @@...
https://raw.githubusercontent.com/soxoj/maigret/HEAD/maigret/executors.py
Replace inline comments with docstrings
import sys from colorama import Fore, Style, init from .result import MaigretCheckStatus from .utils import get_dict_ascii_tree class QueryNotify: def __init__(self, result=None): self.result = result return def start(self, message=None, id_type="username"): return def upd...
--- +++ @@ -1,3 +1,8 @@+"""Sherlock Notify Module + +This module defines the objects for notifying the caller about the +results of queries. +""" import sys @@ -8,34 +13,109 @@ class QueryNotify: + """Query Notify Object. + + Base class that describes methods available to notify the results of + a que...
https://raw.githubusercontent.com/soxoj/maigret/HEAD/maigret/notify.py
Replace inline comments with docstrings
import numpy as np import pandas as pd import textstat import spacy from collections import Counter from itertools import groupby nlp = spacy.load("en_core_web_sm") PRESENT_TENSE_VERB_LIST = ["VB", "VBP", "VBZ", "VBG"] VERB_LIST = ["VB", "VBP", "VBZ", "VBG", "VBN", "VBD"] NOUN_LIST = ["NNP", "NNPS"] SECTIONS_MAPS ...
--- +++ @@ -38,6 +38,14 @@ def compute_readability_stats(text): + """ + Compute reading statistics of the given text + Reference: https://github.com/shivam5992/textstat + + Parameters + ========== + text: str, input section or abstract text + """ try: readability_dict = { ...
https://raw.githubusercontent.com/kaixindelele/ChatPaper/HEAD/scipdf_parser-master/scipdf/features/text_utils.py
Add documentation for all methods
import os import re import random import torch import torchaudio MATPLOTLIB_FLAG = False def load_audio(audiopath, sampling_rate): audio, sr = torchaudio.load(audiopath) #print(f"wave shape: {audio.shape}, sample_rate: {sr}") if audio.size(0) > 1: # mix to mono audio = audio[0].unsqueeze(0) ...
--- +++ @@ -26,6 +26,22 @@ def tokenize_by_CJK_char(line: str) -> str: + """ + Tokenize a line of text with CJK char. + + Note: All return charaters will be upper case. + + Example: ...
https://raw.githubusercontent.com/index-tts/index-tts/HEAD/indextts/utils/utils.py
Help me document legacy Python code
import re import os import os.path as op from glob import glob import urllib import subprocess import requests from bs4 import BeautifulSoup, NavigableString from tqdm import tqdm, tqdm_notebook GROBID_URL = "http://localhost:8070" DIR_PATH = op.dirname(op.abspath(__file__)) PDF_FIGURES_JAR_PATH = op.join( DIR_PA...
--- +++ @@ -17,10 +17,16 @@ def list_pdf_paths(pdf_folder: str): + """ + list of pdf paths in pdf folder + """ return glob(op.join(pdf_folder, "*", "*", "*.pdf")) def validate_url(path: str): + """ + Validate a given ``path`` if it is URL or not + """ regex = re.compile( r"...
https://raw.githubusercontent.com/kaixindelele/ChatPaper/HEAD/scipdf_parser-master/scipdf/pdf/parse_pdf.py
Add docstrings to existing functions
# Each `paper` is a dictionary containing: # (1) paper_id (2) title (3) authors (4) year (5) link (6) abstract (7) journal (8) embeddings # # Generate references: # `Reference` class: # 1. Read a given .bib file to collect papers; use `search_paper_abstract` method to fill missing abstract. # 2. Giv...
--- +++ @@ -46,6 +46,7 @@ return 0.0 def chunks(lst, chunk_size=MAX_BATCH_SIZE): + """Splits a longer list to respect batch size""" for i in range(0, len(lst), chunk_size): yield lst[i : i + chunk_size] @@ -306,6 +307,13 @@ return keywords_dict def collect_papers(self, keywo...
https://raw.githubusercontent.com/kaixindelele/ChatPaper/HEAD/auto_survey/utils/references.py
Add docstrings to meet PEP guidelines
# ****************************** -*- import copy import json import sys from typing import Optional, List, Dict, Any, Tuple from .utils import CaseConverter, URLMatcher, is_country_tag class MaigretEngine: site: Dict[str, Any] = {} def __init__(self, name, data): self.name = name self.__dict...
--- +++ @@ -1,4 +1,5 @@ # ****************************** -*- +"""Maigret Sites Information""" import copy import json import sys @@ -177,6 +178,10 @@ return None def extract_id_from_url(self, url: str) -> Optional[Tuple[str, str]]: + """ + Extracts username from url. + It's outdat...
https://raw.githubusercontent.com/soxoj/maigret/HEAD/maigret/sites.py
Create documentation strings for testing functions
from enum import Enum class MaigretCheckStatus(Enum): CLAIMED = "Claimed" # Username Detected AVAILABLE = "Available" # Username Not Detected UNKNOWN = "Unknown" # Error Occurred While Trying To Detect Username ILLEGAL = "Illegal" # Username Not Allowable For This Site def __str__(self): ...
--- +++ @@ -1,8 +1,16 @@+"""Maigret Result Module + +This module defines various objects for recording the results of queries. +""" from enum import Enum class MaigretCheckStatus(Enum): + """Query Status Enumeration. + + Describes status of query about a given username. + """ CLAIMED = "Claimed"...
https://raw.githubusercontent.com/soxoj/maigret/HEAD/maigret/result.py
Write beginner-friendly docstrings
# Stock Analysis Agent with AI Agents, using OWL 🦉 # This is a stock analysis system based on OWL multi-agent technology # The system contains two core components: # 1. Stock Analysis Assistant - Provides comprehensive stock investment advice and analysis # 2. SEC Financial Data Analysis Assistant - Focuses on analyzi...
--- +++ @@ -54,6 +54,10 @@ def run_society_with_strict_limit(society, round_limit=5, progress_callback=None) -> tuple[str, List[dict[Any, Any]], dict[Any, Any]]: + """Wrapper around run_society to ensure round limit is strictly enforced + + This implementation hijacks the step method to force termination ...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/stock-analysis/run.py
Generate missing documentation strings
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. ========= # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
--- +++ @@ -1,106 +1,172 @@-# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. ========= -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/lic...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/Whatsapp-MCP/app.py
Add structured docstrings to improve clarity
def get_system_prompt() -> str: return """ You are an advanced Interview Preparation Assistant powered by OWL multi-agent technology. Your primary task is to provide COMPREHENSIVE, EXTREMELY DETAILED, and HIGHLY SPECIFIC interview preparation materials with practical examples and actionable advice. ...
--- +++ @@ -1,4 +1,5 @@ def get_system_prompt() -> str: + """Get the enhanced system prompt for the interview assistant.""" return """ You are an advanced Interview Preparation Assistant powered by OWL multi-agent technology. Your primary task is to provide COMPREHENSIVE, EXTREMELY DETAILED, and HIGHL...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/OWL Interview Preparation Assistant/config/prompts.py
Help me document legacy Python code
import logging from typing import Dict, Any, List, Optional import pandas as pd from src.agents.base_agent import BaseAgent from src.roles import create_role_agent from src.models import AnalysisSignal, StockData, ResearchReport from camel.messages import BaseMessage class DebateRoomAgent(BaseAgent): def _...
--- +++ @@ -1,3 +1,6 @@+""" +辩论室代理实现 +""" import logging from typing import Dict, Any, List, Optional import pandas as pd @@ -10,13 +13,34 @@ class DebateRoomAgent(BaseAgent): + """辩论室代理类""" def __init__(self, show_reasoning: bool = False, model_name: str = "gemini"): + """初始化辩论室代理 + ...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/a_share_investment_agent_camel/src/agents/debate_room.py
Create Google-style docstrings for my code
import os import asyncio import sys from pathlib import Path from typing import List from dotenv import load_dotenv from camel.models import ModelFactory from camel.toolkits import FunctionTool, MCPToolkit from camel.types import ModelPlatformType, ModelType from camel.logger import get_logger, set_log_file from owl...
--- +++ @@ -1,135 +1,137 @@-import os -import asyncio -import sys -from pathlib import Path -from typing import List - -from dotenv import load_dotenv - -from camel.models import ModelFactory -from camel.toolkits import FunctionTool, MCPToolkit -from camel.types import ModelPlatformType, ModelType -from camel.logger im...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/Notion-MCP/notion_manager.py
Document all public functions with docstrings
import logging from typing import Dict, Any, List, Optional import pandas as pd from src.agents.base_agent import BaseAgent from src.roles import create_role_agent from src.models import AnalysisSignal, StockData from camel.messages import BaseMessage class FundamentalsAnalystAgent(BaseAgent): def __init__...
--- +++ @@ -1,3 +1,6 @@+""" +基本面分析代理实现 +""" import logging from typing import Dict, Any, List, Optional import pandas as pd @@ -10,13 +13,32 @@ class FundamentalsAnalystAgent(BaseAgent): + """基本面分析代理类""" def __init__(self, show_reasoning: bool = False, model_name: str = "gemini"): + """初始化基本...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/a_share_investment_agent_camel/src/agents/fundamentals_analyst.py
Write clean docstrings for readability
# Define Prompts for Agents from datetime import datetime def get_system_prompt() -> str: current_date = datetime.now().strftime("%Y-%m-%d") return f""" You are an advanced Stock Analysis Assistant powered by OWL multi-agent technology. Your primary task is to provide COMPREHENSIVE, EXTREME...
--- +++ @@ -3,6 +3,7 @@ from datetime import datetime def get_system_prompt() -> str: + r"""Get the enhanced system prompt for the stock analysis assistant.""" current_date = datetime.now().strftime("%Y-%m-%d") @@ -40,6 +41,7 @@ the entire unabridged content directly in your response. ...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/stock-analysis/prompts.py
Create documentation strings for testing functions
from typing import Dict, Any, Optional, List from abc import ABC, abstractmethod import json import logging import re from camel.agents import ChatAgent from camel.messages import BaseMessage # 配置日志 logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', hand...
--- +++ @@ -1,3 +1,8 @@+""" +代理基类模块 + +定义所有代理的共同基类和接口 +""" from typing import Dict, Any, Optional, List from abc import ABC, abstractmethod import json @@ -18,14 +23,27 @@ class BaseAgent(ABC): + """代理基类""" def __init__(self, role_agent: ChatAgent, show_reasoning: bool = False, model_name: str = "g...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/a_share_investment_agent_camel/src/agents/base_agent.py
Add clean documentation to messy code
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. ========= # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
--- +++ @@ -47,6 +47,14 @@ def construct_cooking_society(task: str) -> RolePlaying: + """Construct a society of agents for the cooking companion. + + Args: + task (str): The cooking-related task to be addressed. + + Returns: + RolePlaying: A configured society of agents for the cooking compan...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/cooking-assistant/run_gpt4o.py
Add return value explanations in docstrings
import logging from typing import Dict, Any, List, Optional import pandas as pd from src.agents.base_agent import BaseAgent from src.roles import create_role_agent from src.models import AnalysisSignal, StockData from camel.messages import BaseMessage class SentimentAnalystAgent(BaseAgent): def __init__(se...
--- +++ @@ -1,3 +1,6 @@+""" +情绪分析代理实现 +""" import logging from typing import Dict, Any, List, Optional import pandas as pd @@ -10,13 +13,32 @@ class SentimentAnalystAgent(BaseAgent): + """情绪分析代理类""" def __init__(self, show_reasoning: bool = False, model_name: str = "gemini"): + """初始化情绪分析代理 ...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/a_share_investment_agent_camel/src/agents/sentiment_analyst.py
Write docstrings describing functionality
import logging from typing import Dict, Any, List, Optional import pandas as pd from src.agents.base_agent import BaseAgent from src.roles import create_role_agent from src.models import AnalysisSignal, StockData from camel.messages import BaseMessage class ValuationAnalystAgent(BaseAgent): def __init__(se...
--- +++ @@ -1,3 +1,6 @@+""" +估值分析代理实现 +""" import logging from typing import Dict, Any, List, Optional import pandas as pd @@ -10,13 +13,33 @@ class ValuationAnalystAgent(BaseAgent): + """估值分析代理类""" def __init__(self, show_reasoning: bool = False, model_name: str = "gemini"): + """初始化估值分析代理 ...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/a_share_investment_agent_camel/src/agents/valuation_analyst.py
Write documentation strings for class attributes
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. ========= # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
--- +++ @@ -45,6 +45,14 @@ def construct_learning_society(task: str) -> RolePlaying: + """Construct a society of agents for the learning journey companion. + + Args: + task (str): The learning task description including what the user wants to learn and what they already know. + + Returns: + R...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/learning-assistant/run_gpt4o.py
Include argument descriptions in docstrings
from camel.agents import ChatAgent from camel.messages import BaseMessage from camel.models import ModelFactory from camel.types import ModelType, ModelPlatformType from camel.configs.qwen_config import QwenConfig from camel.configs.openai_config import ChatGPTConfig import os from typing import Dict, Any, List, Option...
--- +++ @@ -1,3 +1,8 @@+""" +角色定义模块 + +使用Camel框架定义系统中的各种AI代理角色 +""" from camel.agents import ChatAgent from camel.messages import BaseMessage from camel.models import ModelFactory @@ -144,6 +149,14 @@ # 创建模型配置 def get_model_config(model_name: str = "gemini") -> tuple: + """获取模型配置 + + Args: + mode...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/a_share_investment_agent_camel/src/roles.py
Add docstrings to existing functions
import logging import os from datetime import datetime from typing import Optional def setup_logger(name: str, log_level: int = logging.INFO, log_dir: str = "logs") -> logging.Logger: # 确保日志目录存在 os.makedirs(log_dir, exist_ok=True) # 获取日志记录器 logger = logging.getLogger(name) # 如果已配置,直接返回 ...
--- +++ @@ -1,3 +1,6 @@+""" +日志工具模块 +""" import logging import os from datetime import datetime @@ -5,6 +8,17 @@ def setup_logger(name: str, log_level: int = logging.INFO, log_dir: str = "logs") -> logging.Logger: + """ + 设置日志记录器 + + Args: + name: 日志记录器名称 + log_level: 日志级别 + log...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/a_share_investment_agent_camel/src/utils/logging_utils.py
Add docstrings for utility scripts
import logging from typing import Dict, Any, List, Optional import pandas as pd from src.agents.base_agent import BaseAgent from src.roles import create_role_agent from src.models import AnalysisSignal, StockData, ResearchReport from camel.messages import BaseMessage class ResearcherBullAgent(BaseAgent): d...
--- +++ @@ -1,3 +1,6 @@+""" +多头研究员代理实现 +""" import logging from typing import Dict, Any, List, Optional import pandas as pd @@ -10,13 +13,36 @@ class ResearcherBullAgent(BaseAgent): + """多头研究员代理类""" def __init__(self, show_reasoning: bool = False, model_name: str = "gemini"): + """初始化多头研究员代理...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/a_share_investment_agent_camel/src/agents/researcher_bull.py
Create documentation strings for testing functions
import logging from typing import Dict, Any, List, Optional import pandas as pd import numpy as np from datetime import datetime import json from src.agents.base_agent import BaseAgent from src.roles import create_role_agent from src.models import StockData, AnalysisSignal from camel.messages import BaseMessage cla...
--- +++ @@ -1,3 +1,6 @@+""" +技术分析代理实现 +""" import logging from typing import Dict, Any, List, Optional import pandas as pd @@ -13,13 +16,32 @@ class TechnicalAnalystAgent(BaseAgent): + """技术分析代理类""" def __init__(self, show_reasoning: bool = False, model_name: str = "gemini"): + """初始化技术分析代理 ...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/a_share_investment_agent_camel/src/agents/technical_analyst.py
Generate consistent docstrings
import logging from typing import Dict, Any, List, Optional import pandas as pd import math from src.agents.base_agent import BaseAgent from src.roles import create_role_agent from src.models import AnalysisSignal, StockData, RiskAnalysis, TradingDecision from camel.messages import BaseMessage class PortfolioManage...
--- +++ @@ -1,3 +1,6 @@+""" +投资组合管理代理实现 +""" import logging from typing import Dict, Any, List, Optional import pandas as pd @@ -11,13 +14,39 @@ class PortfolioManagerAgent(BaseAgent): + """投资组合管理代理类""" def __init__(self, show_reasoning: bool = False, model_name: str = "gemini"): + """初始化投资组...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/a_share_investment_agent_camel/src/agents/portfolio_manager.py
Document all endpoints with docstrings
import os import logging from typing import Dict, Any, List, Optional import pandas as pd import akshare as ak from datetime import datetime, timedelta from src.agents.base_agent import BaseAgent from src.roles import create_role_agent from src.models import StockData from camel.messages import BaseMessage, OpenAIUse...
--- +++ @@ -1,3 +1,6 @@+""" +市场数据分析代理实现 +""" import os import logging from typing import Dict, Any, List, Optional @@ -13,13 +16,34 @@ class MarketDataAgent(BaseAgent): + """市场数据分析代理类""" def __init__(self, show_reasoning: bool = False, model_name: str = "gemini"): + """初始化市场数据分析代理 + ...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/a_share_investment_agent_camel/src/agents/market_data_agent.py
Write reusable docstrings
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. ========= # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
--- +++ @@ -31,6 +31,7 @@ # 配置日志系统 def setup_logging(): + """配置日志系统,将日志输出到文件和内存队列以及控制台""" # 创建logs目录(如果不存在) logs_dir = os.path.join(os.path.dirname(__file__), "logs") os.makedirs(logs_dir, exist_ok=True) @@ -81,6 +82,7 @@ # 日志读取和更新函数 def log_reader_thread(log_file): + """后台线程,持续读取日志文件并将新行添加到队...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/owl/webapp_zh.py
Add docstrings to meet PEP guidelines
import logging from typing import Dict, Any, List, Optional import pandas as pd from src.agents.base_agent import BaseAgent from src.roles import create_role_agent from src.models import RiskAnalysis, StockData, Portfolio from camel.messages import BaseMessage class RiskManagerAgent(BaseAgent): def __init_...
--- +++ @@ -1,3 +1,6 @@+""" +风险管理代理实现 +""" import logging from typing import Dict, Any, List, Optional import pandas as pd @@ -10,13 +13,34 @@ class RiskManagerAgent(BaseAgent): + """风险管理代理类""" def __init__(self, show_reasoning: bool = False, model_name: str = "gemini"): + """初始化风险管理代理 + ...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/a_share_investment_agent_camel/src/agents/risk_manager.py
Add docstrings that explain purpose and usage
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. ========= # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
--- +++ @@ -31,6 +31,7 @@ # ロギングシステムを設定 def setup_logging(): + """ログをファイル、メモリキュー、およびコンソールに出力するようにロギングシステムを設定""" # logsディレクトリを作成(存在しない場合) logs_dir = os.path.join(os.path.dirname(__file__), "logs") os.makedirs(logs_dir, exist_ok=True) @@ -81,6 +82,7 @@ # ログの読み取りと更新の関数 def log_reader_thread(log_fil...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/owl/webapp_jp.py
Add docstrings to incomplete code
#app.py import os import streamlit as st import logging import queue import time import sys # Add parent directory to path for OWL imports sys.path.append('../') try: from main import research_company, generate_interview_questions, create_interview_prep_plan except ImportError as e: st.error(f"Error importing...
--- +++ @@ -146,6 +146,7 @@ """, unsafe_allow_html=True) def display_conversation(chat_history): + """Display the conversation history in a structured format""" if not chat_history: st.info("No conversation available") return @@ -178,6 +179,7 @@ st.markdown("</div>", unsafe_allow_html=T...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/OWL Interview Preparation Assistant/app.py
Help me write clear docstrings
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. ========= # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
--- +++ @@ -31,6 +31,7 @@ # Configure logging system def setup_logging(): + """Configure logging system to output logs to file, memory queue, and console""" # Create logs directory (if it doesn't exist) logs_dir = os.path.join(os.path.dirname(__file__), "logs") os.makedirs(logs_dir, exist_ok=True) ...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/owl/webapp.py
Write docstrings for utility functions
import pandas as pd import akshare as ak from datetime import datetime, timedelta import logging from typing import Dict, Any, List, Optional logger = logging.getLogger(__name__) def get_stock_data(ticker: str, start_date: str, end_date: str) -> pd.DataFrame: try: logger.info(f"获取股票 {ticker} 的历史数据") ...
--- +++ @@ -1,3 +1,6 @@+""" +数据辅助工具模块 +""" import pandas as pd import akshare as ak from datetime import datetime, timedelta @@ -8,6 +11,17 @@ def get_stock_data(ticker: str, start_date: str, end_date: str) -> pd.DataFrame: + """ + 获取股票历史数据 + + Args: + ticker: 股票代码 + start_date: 开始日期 (...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/a_share_investment_agent_camel/src/tools/data_helper.py
Document all public functions with docstrings
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. ========= # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
--- +++ @@ -35,6 +35,16 @@ class GAIABenchmark(BaseBenchmark): + r"""GAIA Benchmark adapted from `"GAIA: a benchmark for General AI + Assistants" + <https://huggingface.co/datasets/gaia-benchmark/GAIA>`_. + + Args: + data_dir (str): The directory to save the data. + save_to (str): The file...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/owl/utils/gaia.py
Add well-formatted docstrings
import os import logging import time import functools import inspect import re from typing import Dict, Any, List, Tuple, Callable, Optional import queue # Create a singleton log queue that can be shared between modules class LogQueueSingleton: _instance = None @classmethod def get_instance(cls): ...
--- +++ @@ -19,6 +19,9 @@ # Custom logging wrapper for tools def log_tool_usage(func): + """ + Decorator to log when a tool is being used. + """ @functools.wraps(func) async def wrapper(*args, **kwargs): tool_name = func.__name__ @@ -41,6 +44,9 @@ # Non-async version for synchronous fun...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/OWL Interview Preparation Assistant/logging_utils.py
Create documentation for each function signature
from typing import List from typing import Optional from camel.toolkits.base import BaseToolkit from camel.toolkits.function_tool import FunctionTool from camel.utils import api_keys_required, dependencies_required import requests import html2text import re class SECToolkit(BaseToolkit): @dependencies_required("s...
--- +++ @@ -8,6 +8,17 @@ import re class SECToolkit(BaseToolkit): + r"""A class representing a toolkit for SEC filings analysis. + + This toolkit provides functionality to: + - Fetch and process 10-K (annual) reports + - Fetch and process 10-Q (quarterly) reports + - Clean and format filing conten...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/stock-analysis/tools/sec_tools.py
Write docstrings for algorithm functions
#main.py import os import logging import time from typing import Dict, Any, Callable, Optional from pathlib import Path import sys # Add parent directory to path for OWL imports sys.path.append('../') from dotenv import load_dotenv import numpy as np # Explicitly import numpy to avoid 'numpy' errors from camel.models...
--- +++ @@ -41,6 +41,10 @@ os.makedirs(INTERVIEW_PREP_DIR, exist_ok=True) def run_society_with_strict_limit(society, round_limit=5, progress_callback=None): + """Wrapper around run_society to ensure round limit is strictly enforced + + This implementation hijacks the step method to force termination after ...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/OWL Interview Preparation Assistant/main.py
Generate consistent docstrings
import argparse import logging import json import os import sys from datetime import datetime, timedelta from typing import Dict, Any, List, Optional # 添加项目根目录到Python路径 current_dir = os.path.dirname(os.path.abspath(__file__)) project_root = os.path.dirname(current_dir) sys.path.append(project_root) from src.agents.ma...
--- +++ @@ -1,3 +1,6 @@+""" +基于Camel框架的A股投资代理系统主程序 +""" import argparse import logging import json @@ -44,6 +47,21 @@ num_of_news: int = 5, model_name: str = "gemini" ) -> TradingDecision: + """ + 运行投资分析流程 + + Args: + ticker: 股票代码 + start_date: 开始日期 (YYYY-MM-DD) + end_date...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/a_share_investment_agent_camel/src/main.py
Auto-generate documentation strings for this file
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. ========= # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
--- +++ @@ -39,6 +39,10 @@ class DocumentProcessingToolkit(BaseToolkit): + r"""A class representing a toolkit for processing document and return the content of the document. + + This class provides method for processing docx, pdf, pptx, etc. It cannot process excel files. + """ def __init__( ...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/owl/utils/document_toolkit.py
Add docstrings to meet PEP guidelines
import logging from typing import Dict, Any, List, Optional import pandas as pd from src.agents.base_agent import BaseAgent from src.roles import create_role_agent from src.models import AnalysisSignal, StockData, ResearchReport from camel.messages import BaseMessage class ResearcherBearAgent(BaseAgent): d...
--- +++ @@ -1,3 +1,6 @@+""" +空头研究员代理实现 +""" import logging from typing import Dict, Any, List, Optional import pandas as pd @@ -10,13 +13,36 @@ class ResearcherBearAgent(BaseAgent): + """空头研究员代理类""" def __init__(self, show_reasoning: bool = False, model_name: str = "gemini"): + """初始化空头研究员代理...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/a_share_investment_agent_camel/src/agents/researcher_bear.py
Add docstrings for utility scripts
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. ========= # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
--- +++ @@ -54,6 +54,14 @@ root_logger.addHandler(file_handler) def construct_society(question: str) -> RolePlaying: + r"""Construct a society of agents based on the given question. + + Args: + question (str): The task or question to be addressed by the society. + + Returns: + RolePlaying: A c...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/virtual_fitting_room/run_gpt4o.py
Add docstrings that explain inputs and outputs
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. ========= # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
--- +++ @@ -41,6 +41,15 @@ question: str, tools: List[FunctionTool], ) -> OwlRolePlaying: + r"""Build a multi-agent OwlRolePlaying instance for task completion. + + Args: + question (str): The task to perform. + tools (List[FunctionTool]): The MCP tools to use for interaction. + + Retur...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/qwen3_mcp/run_mcp_qwen3.py
Include argument descriptions in docstrings
import logging from typing import Dict, Any, List, Optional import json import re from src.agents.base_agent import BaseAgent from src.roles import create_role_agent from src.models import StockData from camel.messages import BaseMessage class InvestmentAgent(BaseAgent): def __init__(self, show_reasoning: ...
--- +++ @@ -1,3 +1,6 @@+""" +投资分析代理实现 +""" import logging from typing import Dict, Any, List, Optional import json @@ -11,13 +14,28 @@ class InvestmentAgent(BaseAgent): + """投资分析代理类""" def __init__(self, show_reasoning: bool = False, model_name: str = "gemini"): + """初始化投资分析代理 + + ...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/a_share_investment_agent_camel/src/agents/investment_agent.py
Document all public functions with docstrings
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. ========= # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
--- +++ @@ -305,6 +305,14 @@ def format_chat_history(chat_history: List[Dict[str, str]]) -> List[List[str]]: + """将聊天历史格式化为Gradio聊天组件可接受的格式 + + Args: + chat_history: 原始聊天历史 + + Returns: + List[List[str]]: 格式化后的聊天历史 + """ formatted_history = [] for message in chat_history: ...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/owl/webapp_backup.py
Annotate my code with docstrings
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. ========= # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
--- +++ @@ -222,6 +222,14 @@ return answer, chat_history, token_info def construct_society(question: str) -> ExcelRolePalying: + r"""Construct a society of agents based on the given question. + + Args: + question (str): The task or question to be addressed by the society. + + Returns: + Ow...
https://raw.githubusercontent.com/camel-ai/owl/HEAD/community_usecase/excel_analyzer/data_analyzer_zh.py
Help me document legacy Python code
import os from pydantic import BaseModel, Field class EncoderConfig(BaseModel, frozen=True): head_dim: int = Field(default=128, gt=0) hidden_act: str = Field(default="silu") hidden_size: int = Field(default=1024, gt=0) initializer_range: float = Field(default=0.02) intermediate_size: int = Fiel...
--- +++ @@ -1,3 +1,17 @@+"""Configuration management module for the Dia model. + +This module provides comprehensive configuration management for the Dia model, +utilizing Pydantic for validation. It defines configurations for data processing, +model architecture (encoder and decoder), and training settings. + +Key com...
https://raw.githubusercontent.com/nari-labs/dia/HEAD/dia/config.py
Create structured documentation for my script
from dataclasses import dataclass from typing import Optional import torch from .config import DiaConfig def create_attn_mask( q_padding_mask_1d: torch.Tensor, k_padding_mask_1d: torch.Tensor, device: torch.device, is_causal: bool = False, ) -> torch.Tensor: # B1, Tq = q_padding_mask_1d.shape ...
--- +++ @@ -12,6 +12,9 @@ device: torch.device, is_causal: bool = False, ) -> torch.Tensor: + """ + Creates the attention mask (self or cross) mimicking JAX segment ID logic. + """ # B1, Tq = q_padding_mask_1d.shape # B2, Tk = k_padding_mask_1d.shape @@ -38,6 +41,7 @@ @dataclass class ...
https://raw.githubusercontent.com/nari-labs/dia/HEAD/dia/state.py
Add docstrings that explain inputs and outputs
import argparse import contextlib import io import random import tempfile import time from pathlib import Path from typing import Optional, Tuple import gradio as gr import numpy as np import soundfile as sf import torch from dia.model import Dia # --- Global Setup --- parser = argparse.ArgumentParser(description="...
--- +++ @@ -55,6 +55,7 @@ def set_seed(seed: int): + """Sets the random seed for reproducibility.""" random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) @@ -77,6 +78,10 @@ speed_factor: float, seed: Optional[int] = None, ): + """ + Runs Nari inference using the globally ...
https://raw.githubusercontent.com/nari-labs/dia/HEAD/app.py
Provide docstrings following PEP 257
import torch import torch.nn as nn import torch.nn.functional as F from huggingface_hub import PyTorchModelHubMixin from torch import Tensor from torch.nn import RMSNorm from .config import DecoderConfig, DiaConfig, EncoderConfig from .state import DecoderInferenceState, EncoderInferenceState, KVCache def _normalize...
--- +++ @@ -14,6 +14,20 @@ class DenseGeneral(nn.Module): + """ + PyTorch equivalent of flax.linen.DenseGeneral with shapes defined at init. + Stores weights (`kernel`) in the same layout as Jax and uses torch.tensordot + for the generalized matrix multiplication. Weight/bias shapes are calculated + ...
https://raw.githubusercontent.com/nari-labs/dia/HEAD/dia/layers.py
Add clean documentation to messy code
import time from enum import Enum from typing import Callable import numpy as np import torch import torch.nn.functional as F import torchaudio from .audio import apply_audio_delay, build_delay_indices, build_revert_indices, revert_audio_delay from .config import DiaConfig from .layers import DiaModel from .state imp...
--- +++ @@ -100,6 +100,17 @@ device: torch.device | None = None, load_dac: bool = True, ): + """Initializes the Dia model. + + Args: + config: The configuration object for the model. + compute_dtype: The computation dtype to use. + device: The device ...
https://raw.githubusercontent.com/nari-labs/dia/HEAD/dia/model.py
Add docstrings to my Python code
import typing as tp import torch def build_delay_indices(B: int, T: int, C: int, delay_pattern: tp.List[int]) -> tp.Tuple[torch.Tensor, torch.Tensor]: delay_arr = torch.tensor(delay_pattern, dtype=torch.int32) t_idx_BxT = torch.broadcast_to( torch.arange(T, dtype=torch.int32)[None, :], [B, T...
--- +++ @@ -4,6 +4,10 @@ def build_delay_indices(B: int, T: int, C: int, delay_pattern: tp.List[int]) -> tp.Tuple[torch.Tensor, torch.Tensor]: + """ + Precompute (t_idx_BxTxC, indices_BTCx3) so that out[t, c] = in[t - delay[c], c]. + Negative t_idx => BOS; t_idx >= T => PAD. + """ delay_arr = torch...
https://raw.githubusercontent.com/nari-labs/dia/HEAD/dia/audio.py
Generate consistent docstrings
from typing import Tuple from .. import Provider as AddressProvider class Provider(AddressProvider): city_suffixes = ( "-des-Bois", "-les-Bains", "-la-Ville", "-Dessus", "-Dessous", " am Rhein", " am See", " am Albis", " an der Aare", ) ...
--- +++ @@ -332,18 +332,36 @@ ) def street_prefix(self) -> str: + """ + :example: 'rue' + """ return self.random_element(self.street_prefixes) def city_prefix(self) -> str: + """ + :example: 'rue' + """ return self.random_element(self.city_pr...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/address/fr_CH/__init__.py
Add docstrings with type hints explained
import re import string from collections import OrderedDict from typing import Any, Collection, List, Optional, Sequence, TypeVar, Union from ..generator import Generator from ..typing import OrderedDictType from ..utils.distribution import choices_distribution, choices_distribution_unique _re_hash = re.compile(r"#"...
--- +++ @@ -284,9 +284,14 @@ } def __init__(self, generator: Any) -> None: + """ + Base class for fake data providers + :param generator: `Generator` instance + """ self.generator = generator def locale(self) -> str: + """Generate a random underscored i18n l...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/__init__.py
Expand my code with proper documentation strings
from typing import Tuple from ..de import Provider as AddressProvider class Provider(AddressProvider): city_formats = ("{{city_name}}",) building_number_formats = ("%", "%#", "%#", "%#", "%##") street_suffixes = ["strasse"] street_name_formats = ("{{last_name}}{{street_suffix}}",) street_address_...
--- +++ @@ -217,15 +217,31 @@ ) def canton(self) -> Tuple[str, str]: + """ + Randomly returns a swiss canton ('Abbreviated', 'Name'). + :example ('ZH', 'Zürich') + """ return self.random_element(self.cantons) def city_name(self) -> str: + """ + Random...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/address/de_CH/__init__.py
Document this module using docstrings
from .. import Provider as AutomotiveProvider class Provider(AutomotiveProvider): license_formats = ( # Private vehicles "{{district}}-####-3#", "{{district}}-####-4#", "{{district}}-####-7#", "{{district}}-####-9#", # Public transport "{{district}}-####-30...
--- +++ @@ -2,6 +2,12 @@ class Provider(AutomotiveProvider): + """Implement automotive provider for ``ar_PS`` locale. + + Sources: + + - https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_the_Palestinian_National_Authority + """ license_formats = ( # Private vehicles @@ -34,6 +...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/automotive/ar_PS/__init__.py
Write clean docstrings for readability
from .. import Provider as AddressProvider class Provider(AddressProvider): cities = ( "Warszawa", "Kraków", "Łódź", "Wrocław", "Poznań", "Gdańsk", "Szczecin", "Bydgoszcz", "Lublin", "Katowice", "Białystok", "Gdynia", ...
--- +++ @@ -654,45 +654,97 @@ address_formats = ("{{street_address}}\n{{postcode}} {{city}}",) def street_prefix(self) -> str: + """ + Randomly returns a street prefix + :example: 'aleja' + """ return self.random_element(self.street_prefixes) def street_prefix_femi...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/address/pl_PL/__init__.py
Generate NumPy-style docstrings
from typing import Tuple from .. import Provider as AddressProvider class Provider(AddressProvider): city_suffixes = ( "do Sul", "do Norte", "de Minas", "do Campo", "Grande", "da Serra", "do Oeste", "de Goiás", "Paulista", "da Mata",...
--- +++ @@ -878,21 +878,47 @@ ) def street_prefix(self) -> str: + """ + :example: 'rua' + """ return self.random_element(self.street_prefixes) def estado(self) -> Tuple[str, str]: + """ + Randomly returns a Brazilian State ('sigla' , 'nome'). + :exam...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/address/pt_BR/__init__.py
Auto-generate documentation strings for this file
from collections import OrderedDict from typing import Optional, Tuple from ..en import Provider as AddressProvider class Provider(AddressProvider): city_prefixes = ("North", "East", "West", "South", "New", "Lake", "Port") city_suffixes = ( "town", "ton", "land", "ville", ...
--- +++ @@ -505,6 +505,17 @@ include_territories: bool = True, include_freely_associated_states: bool = True, ) -> str: + """ + :returns: A random two-letter USPS postal code + + By default, the resulting code may abbreviate any of the fifty states, + five US territorie...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/address/en_US/__init__.py
Provide clean and structured docstrings
from faker.providers.person.bn_BD import translate_to_bengali_digits from .. import Provider as AddressProvider class Provider(AddressProvider): area_names = ( "আলি", "আলম", "অভয়", "আনোয়ার", "ব্রাহ্মণ", "বটিয়া", "বাঘার", "বেগম", "বিজয়", ...
--- +++ @@ -486,31 +486,62 @@ address_formats = ("{{street_address}}, {{town}}, {{city}}, {{postcode}}",) def administrative_unit(self) -> str: + """ + :example: 'ঢাকা' + """ return self.random_element(self.cities) def area_name(self) -> str: + """ + :exampl...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/address/bn_BD/__init__.py
Add docstrings to meet PEP guidelines
import argparse import itertools import logging import os import random import sys import textwrap from io import TextIOWrapper from pathlib import Path from typing import Dict, List, Optional, TextIO, TypeVar, Union from . import VERSION, Faker, documentor, exceptions from .config import AVAILABLE_LOCALES, DEFAULT_L...
--- +++ @@ -120,6 +120,10 @@ self.prog_name = Path(self.argv[0]).name def execute(self) -> None: + """ + Given the command-line arguments, this creates a parser appropriate + to that command, and runs it. + """ # retrieve default language from system environment ...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/cli.py
Create documentation for each function signature
import re from typing import Optional from .. import Provider as AutomotiveProvider class Provider(AutomotiveProvider): license_formats = ( # New format "#### ???", ) # New format suffix letters (excluding vocals and Q from ascii uppercase) license_plate_new_format_suffix_letters =...
--- +++ @@ -6,6 +6,18 @@ class Provider(AutomotiveProvider): + """Implement automotive provider for ``es_ES`` locale. + + Sources: + + - https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Spain + + .. |license_plate_unified| replace:: + :meth:`license_plate_unified() <faker.providers.aut...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/automotive/es_ES/__init__.py
Add verbose docstrings with examples
class BaseFakerException(Exception): class UniquenessException(BaseFakerException): class UnsupportedFeature(BaseFakerException): def __init__(self, msg: str, name: str) -> None: self.name = name super().__init__(msg)
--- +++ @@ -1,11 +1,16 @@ class BaseFakerException(Exception): + """The base exception for all Faker exceptions.""" class UniquenessException(BaseFakerException): + """To avoid infinite loops, after a certain number of attempts, + the "unique" attribute of the Proxy will throw this exception. + """ ...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/exceptions.py
Provide clean and structured docstrings
from typing import Dict, List, Optional, Tuple from faker.providers.address import Provider as AddressProvider Range = Tuple[int, int] class Provider(AddressProvider): # City and States names taken from wikipedia # Street format taken from some common famous places in India # Link for cities: https://en...
--- +++ @@ -510,10 +510,18 @@ state = administrative_unit def union_territory(self) -> str: + """Returns random union territory name""" return self.random_element(self.union_territories)[0] def pincode_in_state(self, state_abbr: Optional[str] = None, include_union_territories: bool =...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/address/en_IN/__init__.py
Create structured documentation for my script
from string import ascii_uppercase from typing import List from .. import Provider as AutomotiveProvider class Provider(AutomotiveProvider): protocol_licenses = [str(x) for x in range(1, 18) if x != 15] motorcycle_license_formats = [ "??####", # 1981 series "??#####", # 2014 series ] ...
--- +++ @@ -5,6 +5,19 @@ class Provider(AutomotiveProvider): + """Implement automotive provider for ``en_PH`` locale. + + Vehicle registration in the Philippines has many controversies and is full + of quirks. On top of that, some terms are highly subject to interpretation + or to varying definitions wh...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/automotive/en_PH/__init__.py
Create Google-style docstrings for my code
import re from collections import OrderedDict from .. import Provider as AutomotiveProvider class Provider(AutomotiveProvider): license_plate_old_format_first_letters = "ABCDFGHJKLPRSTVWXYZ" license_plate_old_format_second_letters = "ABCDFGHIJKLPRSTVWXYZ" license_plate_new_format_letters = "BCDFGHJKLPR...
--- +++ @@ -6,6 +6,13 @@ class Provider(AutomotiveProvider): + """Implement automotive provider for ``es`` locale. + + Sources: + + - https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Chile + + """ license_plate_old_format_first_letters = "ABCDFGHJKLPRSTVWXYZ" license_plate_old_fo...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/automotive/es_CL/__init__.py
Add return value explanations in docstrings
import string from .. import Provider as AddressProvider ALPHABET = string.ascii_uppercase class Provider(AddressProvider): building_suffixes = ( "빌라", "아파트", "연립", "마을", "타운", "타워", ) road_suffixes = ("로", "길", "거리", "가") town_suffixes = ("동", "읍", "...
--- +++ @@ -6,6 +6,35 @@ class Provider(AddressProvider): + """ + Korean Address Provider + ======================= + + Korea has two address and postal code system. + + Address: + - Address based on land parcel numbers + (지번 주소, OLD, but someone use consistently) + - Address b...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/address/ko_KR/__init__.py
Generate consistent documentation across files
import re from typing import Optional from faker.providers import ElementsType from ..en import Provider as AddressProvider class Provider(AddressProvider): # Source: https://www.canadapost.ca/tools/pg/manual/PGaddress-e.asp#1449294 # # 'W' and 'Z' are valid in non-initial position (easily verified i...
--- +++ @@ -356,6 +356,7 @@ secondary_address_formats = ("Apt. ###", "Suite ###") def administrative_unit(self) -> str: + """ """ return self.random_element(self.provinces) province = administrative_unit @@ -370,16 +371,31 @@ return self.numerify(self.random_element(self.second...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/address/en_CA/__init__.py
Document functions with clear intent
import random as random_module import re from typing import TYPE_CHECKING, Any, Callable, Dict, Hashable, List, Optional, Type, Union from .typing import SeedType if TYPE_CHECKING: from .providers import BaseProvider _re_token = re.compile(r"\{\{\s*(\w+)(:\s*\w+?)?\s*\}\}") random = random_module.Random() mod_r...
--- +++ @@ -54,6 +54,7 @@ return None def get_providers(self) -> List["BaseProvider"]: + """Returns added providers.""" return self.providers @property @@ -65,6 +66,7 @@ self.__random = value def seed_instance(self, seed: Optional[SeedType] = None) -> "Generator"...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/generator.py
Write documentation strings for class attributes
import re from .. import Provider as AutomotiveProvider class Provider(AutomotiveProvider): LICENSE_FORMAT_EN = "#### ???" LICENSE_FORMAT_AR = "? ? ? ####" PLATE_CHARS_EN = "ABDEGHJKLNRSTUVXZ" PLATE_CHARS_AR = "أبدعقهحكلنرسطوىصم" PLATE_MAP = { "A": "ا", "B": "ب", "D": "...
--- +++ @@ -4,6 +4,15 @@ class Provider(AutomotiveProvider): + """Implement automotive provider for ``ar_SA`` locale. + + Sources: + + - https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Saudi_Arabia + + .. |license_plate_en| replace:: + :meth:`license_plate_en()` + """ LICEN...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/automotive/ar_SA/__init__.py
Auto-generate documentation strings for this file
import re from string import ascii_uppercase from .. import BaseProvider, ElementsType localized = True def calculate_vin_str_weight(s: str, weight_factor: list) -> int: def _get_char_weight(c: str) -> int: if ord(c) <= 64: # 0-9 return int(c) if ord(c) <= 73: # A-I r...
--- +++ @@ -8,8 +8,20 @@ def calculate_vin_str_weight(s: str, weight_factor: list) -> int: + """ + multiply s(str) by weight_factor char by char + e.g. + input: s="ABCDE", weight_factor=[1, 2, 3, 4, 5] + return: A*1 + B*2 + C*3 + D*4 + E*5 + + will multiply 0 when len(weight_factor) less than len(...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/automotive/__init__.py
Write docstrings including parameters and return values
from .. import BaseProvider, ElementsType, date_time localized = True class Provider(BaseProvider): city_suffixes: ElementsType[str] = ["Ville"] street_suffixes: ElementsType[str] = ["Street"] city_formats: ElementsType[str] = ("{{first_name}} {{city_suffix}}",) street_name_formats: ElementsType[str]...
--- +++ @@ -21,37 +21,69 @@ alpha_3_country_codes: ElementsType[str] = [country.alpha_3_code for country in date_time.Provider.countries] def city_suffix(self) -> str: + """ + :example: 'town' + """ return self.random_element(self.city_suffixes) def street_suffix(self) ->...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/address/__init__.py
Write docstrings describing functionality
from collections import OrderedDict from string import ascii_uppercase from .. import Provider as AutomotiveProvider class Provider(AutomotiveProvider): license_plate_old_format_first_letter = ascii_uppercase.replace("YZ", "") license_plate_new_first_letter = OrderedDict( [ ("A", 0.99),...
--- +++ @@ -5,6 +5,13 @@ class Provider(AutomotiveProvider): + """Implement automotive provider for ``es_AR`` locale. + + Sources: + + - https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Argentina + + """ license_plate_old_format_first_letter = ascii_uppercase.replace("YZ", "") @@ -5...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/automotive/es_AR/__init__.py
Write docstrings describing functionality
from typing import Tuple from .. import Provider as AddressProvider class Provider(AddressProvider): city_suffixes = ( "Ville", "Bourg", "-les-Bains", "-sur-Mer", "-la-Forêt", "boeuf", "nec", "dan", ) city_prefixes = ("Saint", "Sainte") ...
--- +++ @@ -426,27 +426,53 @@ ) def street_prefix(self) -> str: + """ + :example: 'rue' + """ return self.random_element(self.street_prefixes) def city_prefix(self) -> str: + """ + :example: 'rue' + """ return self.random_element(self.city_pr...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/address/fr_FR/__init__.py
Add professional docstrings to my codebase
from collections import OrderedDict from ..th import Provider as AddressProvider class Provider(AddressProvider): street_name_formats = ("{{street_prefix}}{{last_name}}",) street_address_formats = ("{{building_number}} {{street_name}}",) address_formats = OrderedDict( ( ( ...
--- +++ @@ -354,21 +354,37 @@ city_suffixes = ("นคร",) def street_prefix(self) -> str: + """ + :example: 'ถนน' + """ return self.random_element(self.street_prefixes) def administrative_unit(self) -> str: + """ + :example: 'อุบลราชธานี' + """ ...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/address/th_TH/__init__.py
Write docstrings describing each step
from faker.providers.person.bn_BD import translate_to_bengali_digits from .. import Provider as AutomotiveProvider class Provider(AutomotiveProvider): # noinspection DuplicatedCode cities = ( "বরগুনা", "বরিশাল", "বরিশাল মেট্রো", "ভোলা", "বান্দরবান", "ব্রাহ্মণব...
--- +++ @@ -4,6 +4,12 @@ class Provider(AutomotiveProvider): + """Implement automotive provider for ``bn_BD`` locale. + + Sources: + + - https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Bangladesh + """ # noinspection DuplicatedCode cities = ( @@ -214,17 +220,34 @@ ) d...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/automotive/bn_BD/__init__.py
Expand my code with proper documentation strings
import inspect import warnings from enum import Enum, auto from typing import Any, Dict, List, Optional, Tuple, Type, Union from .generator import Generator from .providers import BaseProvider from .proxy import Faker class FakerEnum(Enum): A = auto B = auto class Documentor: def __init__(self, gener...
--- +++ @@ -10,6 +10,7 @@ class FakerEnum(Enum): + """Required for faker.providers.enum""" A = auto B = auto @@ -17,6 +18,11 @@ class Documentor: def __init__(self, generator: Union[Generator, Faker]) -> None: + """ + :param generator: a localized Generator with providers filled,...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/documentor.py
Provide docstrings following PEP 257
from .. import Provider as AddressProvider class Provider(AddressProvider): area_names = ( "Ali", "Alam", "Abhay", "Anwar", "Brahmin", "Botia", "Baghar", "Begum", "Bijoy", "Bandar", "Balia", "Bajit", "Baker", ...
--- +++ @@ -1,3 +1,6 @@+""" +Contributed by: @aamibhoot 🇧🇩 +""" from .. import Provider as AddressProvider @@ -483,31 +486,62 @@ address_formats = ("{{street_address}}, {{town}}, {{city}}, {{postcode}}",) def administrative_unit(self) -> str: + """ + :example: 'Dhaka' + """ ...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/address/en_BD/__init__.py
Add detailed documentation for each class
from collections import OrderedDict from typing import Dict, List, Optional from ... import ElementsType from ..en import Provider as AddressProvider # https://en.wikipedia.org/wiki/Addresses_in_Malaysia class Provider(AddressProvider): # 'Bandar' and 'Taman' are the most common township prefix # https://en...
--- +++ @@ -388,6 +388,9 @@ ) def street_name(self) -> str: + """ + :example: 'Crist Parks' + """ pattern: str = self.bothify(self.random_element(self.street_name_formats)) return self.generator.parse(pattern) @@ -427,6 +430,10 @@ street_address_formats: ElementsT...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/address/en_MS/__init__.py
Replace inline comments with docstrings
from .. import Provider as AutomotiveProvider class Provider(AutomotiveProvider): license_formats = ( "{{initials}}-####", "{{initials}}-#####", ) def initials(self) -> str: return self.random_element( [ "1", # Ministers "2", ...
--- +++ @@ -2,6 +2,12 @@ class Provider(AutomotiveProvider): + """Implement automotive provider for ``ar_JO`` locale. + + Sources: + + - https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Jordan + """ license_formats = ( "{{initials}}-####", @@ -9,6 +15,7 @@ ) def in...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/automotive/ar_JO/__init__.py
Create documentation for each function signature
from collections import OrderedDict from typing import Optional, Tuple from .. import Provider as AddressProvider class Provider(AddressProvider): city_prefixes = ("Thành phố", "Quận", "Huyện", "Thị xã") city_suffixes = ( "Thành phố", "Quận", "Huyện", "Thị xã", "Xã"...
--- +++ @@ -1,3 +1,4 @@+"""This module provides address-related functionalities for Vietnamese addresses.""" from collections import OrderedDict from typing import Optional, Tuple @@ -6,6 +7,11 @@ class Provider(AddressProvider): + """Provider for generating Vietnamese addresses. + Sources: + + # https...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/address/vi_VN/__init__.py
Help me write clear docstrings
import random from typing import Optional, Tuple from .. import Provider as AutomotiveProvider class Provider(AutomotiveProvider): plate_number_formats = ("####",) license_region_data = { "Crimea": (("AK", "KK", "TK", "MK"), "01"), "Kyiv": (("AA", "KA", "TT", "TA"), "11"), "Vinnytsi...
--- +++ @@ -211,6 +211,20 @@ raise KeyError(f"Keys name must be only {region_names}") def license_plate(self, region_name: Optional[str] = None, temporary_plate: bool = False) -> str: + """Generate a license plate. + + - If ``region_name`` is ``None`` (default), its value will be set to...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/automotive/uk_UA/__init__.py
Please document this code using docstrings
import re import string from math import ceil from string import ascii_uppercase from typing import Dict, Optional from .. import BaseProvider localized = True default_locale = "en_GB" class Provider(BaseProvider): ALPHA: Dict[str, str] = {c: str(ord(c) % 55) for c in string.ascii_uppercase} bban_format: ...
--- +++ @@ -12,12 +12,27 @@ class Provider(BaseProvider): + """Implement default bank provider for Faker. + + .. important:: + Bank codes, account numbers, and other ID's generated by this provider + are only valid in form, i.e. they conform to some standard/format, are + of the expected len...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/bank/__init__.py
Add docstrings to incomplete code
from .. import Provider as AutomotiveProvider # flake8: noqa: E501 class Provider(AutomotiveProvider): license_plate_area_names = ( "品川", "足立", "練馬", "横浜", "川崎", "名古屋", "大阪", "神戸", "福岡", "札幌", "尾張小牧", "伊勢志摩", ) ...
--- +++ @@ -4,6 +4,13 @@ class Provider(AutomotiveProvider): + """Implement automotive provider for ``ja_JP`` locale. + + Sources (retrieved on 2025-09-15): + + - https://ja.wikipedia.org/wiki/%E6%97%A5%E6%9C%AC%E3%81%AE%E3%83%8A%E3%83%B3%E3%83%90%E3%83%BC%E3%83%97%E3%83%AC%E3%83%BC%E3%83%88%E4%B8%80%E8%A6...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/automotive/ja_JP/__init__.py
Generate helpful docstrings for debugging
import re from itertools import product from typing import Dict, Optional, Pattern from .. import PrefixType from .. import Provider as BarcodeProvider class Provider(BarcodeProvider): local_prefixes = ( *product((0,), range(10)), *product((1,), range(4)), ) upc_e_base_pattern: Pattern...
--- +++ @@ -8,6 +8,12 @@ class Provider(BarcodeProvider): + """Implement barcode provider for ``en_US`` locale. + + Sources: + + - https://gs1.org/standards/id-keys/company-prefix + """ local_prefixes = ( *product((0,), range(10)), @@ -40,6 +46,36 @@ ) def ean13(self, prefixes...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/barcode/en_US/__init__.py
Create Google-style docstrings for my code
from .. import Provider as AutomotiveProvider class Provider(AutomotiveProvider): license_plate_letters = ("A", "B", "E", "K", "M", "Н", "О", "Р", "С", "Т", "У", "Х") vehicle_categories = ( "M", "A", "A1", "B", "B1", "BE", "C", "C1", "C...
--- +++ @@ -2,6 +2,13 @@ class Provider(AutomotiveProvider): + """Implement automotive provider for ``ru_RU`` locale. + + Sources: + + - https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Russia + - https://ru.wikipedia.org/wiki/Категории_транспортных_средств + """ license_plate_lett...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/automotive/ru_RU/__init__.py
Help me add docstrings to my project
from typing import Tuple, Union from .. import BaseProvider localized = True PrefixType = Tuple[Union[int, str, Tuple[Union[int, str], ...]], ...] class Provider(BaseProvider): local_prefixes: PrefixType = () def _ean(self, length: int = 13, prefixes: PrefixType = ()) -> str: if length not in (8,...
--- +++ @@ -8,6 +8,12 @@ class Provider(BaseProvider): + """Implement default barcode provider for Faker. + + Sources: + + - https://gs1.org/standards/id-keys/company-prefix + """ local_prefixes: PrefixType = () @@ -33,19 +39,84 @@ return "".join(str(x) for x in code) def ean(sel...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/barcode/__init__.py
Write reusable docstrings
from .. import Provider as BarcodeProvider class Provider(BarcodeProvider): local_prefixes = (4, 5), (4, 9) def jan(self, length: int = 13) -> str: return self.localized_ean(length) def jan8(self) -> str: return self.localized_ean8() def jan13(self) -> str: return self.loca...
--- +++ @@ -2,14 +2,48 @@ class Provider(BarcodeProvider): + """Implement barcode provider for ``ja_JP`` locale. + + Japanese local EAN barcodes are called JAN-codes. + + Sources: + + - https://gs1.org/standards/id-keys/company-prefix + - https://www.dsri.jp/jan/about_jan.html + + .. |JaJpProvider...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/barcode/ja_JP/__init__.py
Add inline docstrings for readability
from typing import List from .. import Provider as AutomotiveProvider class Provider(AutomotiveProvider): license_formats = ( "?? #####", "?? ####?", "?? ###??", "?? #?###", "?? #??##", "??? ?###", "??? ##??", "??? #?##", "??? ##?#", ...
--- +++ @@ -4,6 +4,12 @@ class Provider(AutomotiveProvider): + """Implement automotive provider for ``pl_PL`` locale. + + Sources: + + - https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Poland + """ license_formats = ( "?? #####", @@ -23,4 +29,11 @@ ) def license_p...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/automotive/pl_PL/__init__.py
Write reusable docstrings
import re import string from .. import Provider as AutomotiveProvider class Provider(AutomotiveProvider): # License formats for cars / other vehicles than motorbikes license_formats = ( # Format 6 "##-%?-??", # Format 7 "##-%??-#", # Format 8 "#-@??-##", ...
--- +++ @@ -5,6 +5,18 @@ class Provider(AutomotiveProvider): + """Implement automotive provider for `nl_NL` locale. + + Sources: + - https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_the_Netherlands + - https://www.cbs.nl/en-gb/figures/detail/82044eng + + .. |license_plate_car| replace:: +...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/automotive/nl_NL/__init__.py
Add documentation for all methods
from typing import List, Optional, Tuple from .. import Provider as BankProvider def get_clabe_control_digit(clabe: str) -> int: factors = [3, 7, 1] products: List[int] = [] for i, digit in enumerate(clabe[:17]): products.append((int(digit) * factors[i % 3]) % 10) return (10 - sum(products)...
--- +++ @@ -4,6 +4,11 @@ def get_clabe_control_digit(clabe: str) -> int: + """Generate the checksum digit for a CLABE. + + :param clabe: CLABE. + :return: The CLABE checksum digit. + """ factors = [3, 7, 1] products: List[int] = [] @@ -14,6 +19,11 @@ def is_valid_clabe(clabe: str) -> boo...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/bank/es_MX/__init__.py
Generate documentation strings for clarity
import logging from faker.providers.bank import Provider as BankProvider logger = logging.getLogger(__name__) class Provider(BankProvider): country_code = "PH" bban_format = "################" swift_bank_codes = ( "ANZB", "AUBK", "BKCH", "BKKB", "BNOR", "...
--- +++ @@ -6,6 +6,7 @@ class Provider(BankProvider): + """Implement bank provider for ``en_PH`` locale.""" country_code = "PH" bban_format = "################" @@ -80,9 +81,29 @@ ) def bban(self) -> str: + """Generate a Basic Bank Account Number (BBAN). + + .. warning:: + ...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/bank/en_PH/__init__.py
Add docstrings following best practices
from .. import Provider as BankProvider class Provider(BankProvider): bban_format = "############" country_code = "BE" banks = ( "Argenta Spaarbank", "AXA Bank", "Belfius Bank", "BNP Paribas Fortis", "Bpost Bank", "Crelan", "Deutsche Bank AG", ...
--- +++ @@ -2,6 +2,12 @@ class Provider(BankProvider): + """Implement bank provider for `nl_BE` locale. + + Information about the Belgian banks can be found on the website + of the National Bank of Belgium: + https://www.nbb.be/nl/betalingen-en-effecten/betalingsstandaarden/bankidentificatiecodes + "...
https://raw.githubusercontent.com/joke2k/faker/HEAD/faker/providers/bank/nl_BE/__init__.py