before_code stringlengths 14 465k | reviewer_comment stringlengths 16 64.5k | after_code stringlengths 9 467k | diff_context stringlengths 0 97k | file_path stringlengths 5 226 | comment_line int32 0 26 | language stringclasses 37
values | quality_score float32 0.07 1 | comment_type stringclasses 9
values | comment_length int32 16 64.5k | before_lines int32 1 17.2k | after_lines int32 1 12.1k | is_negative bool 2
classes | pr_title stringlengths 1 308 | pr_number int32 1 299k | repo_name stringclasses 533
values | repo_stars int64 321 419k | repo_language stringclasses 27
values | reviewer_username stringlengths 0 39 | author_username stringlengths 2 39 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
)
pbar = tqdm(total=self.test_num) if self.is_test else tqdm(total=all_p_length)
index = 0
p_to_save_len = len(self.p_to_save)
try:
# Add the things that don't need to be translated first, so that you can see the img after the interruption
for item in self... | ```suggestion
for i in range(len(p_list)):
``` | key,
language,
api_base=model_api_base,
**prompt_config_to_kwargs(prompt_config),
)
self.is_test = is_test
self.test_num = test_num
self.translate_tags = translate_tags
self.allow_navigable_strings = allow_navigable_strings
... | @@ -92,12 +132,56 @@ def make_bilingual_book(self):
index = 0
p_to_save_len = len(self.p_to_save)
try:
+ # Add the things that don't need to be translated first, so that you can see the img after the interruption
for item in self.origin_book.get_items():
- ... | book_maker/loader/epub_loader.py | 26 | Python | 0.571 | suggestion | 68 | 51 | 51 | false | Cumulative translation | 148 | yihong0618/bilingual_book_maker | 3,321 | Python | danparizher | sunyuechi |
for p in plist:
temp_p = copy(p)
for sup in temp_p.find_all("sup"):
sup.extract()
new_str += temp_p.get_text().strip() + sep
if new_str.endswith(sep):
new_str = new_str[: -len(sep)]
plist_len = len(plist)
self.system_conte... | should be placed before while
```suggestion
``` | """,
file=f,
)
# usage = completion["usage"]
# print(f"total_token: {usage['total_tokens']}")
# if int(usage["total_tokens"]) > self.max_num_token:
# self.max_num_token = int(usage["total_tokens"])
# print(
# f"{usage['... | @@ -64,5 +76,79 @@ def translate(self, text):
t_text = self.get_translation(text)
# todo: Determine whether to print according to the cli option
- print(t_text.strip())
+ if needprint:
+ print(re.sub("\n{3,}", "\n\n", t_text))
return t_text
+
+ def translate_... | book_maker/translator/chatgptapi_translator.py | 26 | Python | 0.5 | suggestion | 49 | 51 | 51 | false | Cumulative translation | 148 | yihong0618/bilingual_book_maker | 3,321 | Python | danparizher | sunyuechi |
import time
import re
from copy import copy
import openai
from os import environ
from .base_translator import Base
class ChatGPTAPI(Base):
def __init__(self, key, language, api_base=None, prompt_template=None):
super().__init__(key, language)
self.key_len = len(key.split(","))
if api_bas... | ```suggestion
sleep_dur = 6
``` | f"bug: {plist_len} paragraphs of text translated into {len(result_list)} paragraphs"
)
print("continue")
def translate_list(self, plist):
sep = "\n\n\n\n\n"
# new_str = sep.join([item.text for item in plist])
new_str = ""
i = 1
for p in plist:
... | @@ -64,5 +76,79 @@ def translate(self, text):
t_text = self.get_translation(text)
# todo: Determine whether to print according to the cli option
- print(t_text.strip())
+ if needprint:
+ print(re.sub("\n{3,}", "\n\n", t_text))
return t_text
+
+ def translate_... | book_maker/translator/chatgptapi_translator.py | 26 | Python | 0.429 | suggestion | 43 | 155 | 44 | false | Cumulative translation | 148 | yihong0618/bilingual_book_maker | 3,321 | Python | danparizher | sunyuechi |
plist_len = len(plist)
self.system_content += f"""Please translate the following paragraphs individually while preserving their original structure(This time it should be exactly {plist_len} paragraphs, no more or less). Only translate the paragraphs provided below:
[Insert first paragraph here]
[Inser... | ```suggestion
state = "fail" if len(result_list) != plist_len else "success"
``` | # f"{usage['total_tokens']} {usage['prompt_tokens']} {usage['completion_tokens']} {self.max_num_token} (total_token, prompt_token, completion_tokens, max_history_total_token)"
# )
return t_text
def translate(self, text, needprint=True):
# print("=========================... | @@ -64,5 +76,79 @@ def translate(self, text):
t_text = self.get_translation(text)
# todo: Determine whether to print according to the cli option
- print(t_text.strip())
+ if needprint:
+ print(re.sub("\n{3,}", "\n\n", t_text))
return t_text
+
+ def translate_... | book_maker/translator/chatgptapi_translator.py | 26 | Python | 0.571 | bug | 90 | 51 | 51 | false | Cumulative translation | 148 | yihong0618/bilingual_book_maker | 3,321 | Python | danparizher | sunyuechi |
while len(result_list) != plist_len and retry_count < 3:
print(
f"bug: {plist_len} -> {len(result_list)} : Number of paragraphs before and after translation"
)
sleep_dur = 6
print(f"sleep for {sleep_dur}s and retry {retry_count+1} ...")
... | ```suggestion
for i in range(len(newlist)):
``` | max_attempts = 3
t_text = ""
while attempt_count < max_attempts:
try:
t_text = self.get_translation(text)
break
except Exception as e:
# todo: better sleep time? why sleep alawys about key_len
# 1. openai se... | @@ -64,5 +76,79 @@ def translate(self, text):
t_text = self.get_translation(text)
# todo: Determine whether to print according to the cli option
- print(t_text.strip())
+ if needprint:
+ print(re.sub("\n{3,}", "\n\n", t_text))
return t_text
+
+ def translate_... | book_maker/translator/chatgptapi_translator.py | 26 | Python | 0.571 | suggestion | 65 | 41 | 51 | false | Cumulative translation | 148 | yihong0618/bilingual_book_maker | 3,321 | Python | danparizher | sunyuechi |
{
"role": "user",
"content": text,
},
)
"""Returns the number of tokens used by a list of messages."""
try:
encoding = tiktoken.encoding_for_model(model)
except KeyError:
encoding = tiktoken.get_encoding("cl100k_base")
if model == "gpt-3.5-tur... | Have you checked if this result equals `completion[usage][total_tokens"]`?

| self.accumulated_num = accumulated_num
def deal_new(self, p, wait_p_list):
self.deal_old(wait_p_list)
new_p = copy(p)
new_p.string = self.translate_model.translate(p.text)
p.insert_after(new_p)
def deal_old(self, wait_p_list):
if len(wait_p_list) == 0:
... | @@ -15,6 +17,68 @@
from .base_loader import BaseBookLoader
+# ref: https://platform.openai.com/docs/guides/chat/introduction
+def num_tokens_from_text(text, model="gpt-3.5-turbo-0301"): | book_maker/loader/epub_loader.py | 26 | Python | 0.571 | question | 191 | 51 | 51 | false | Cumulative translation | 148 | yihong0618/bilingual_book_maker | 3,321 | Python | zstone12 | sunyuechi |
)
or (
len(result_list) < len(best_result_list)
and len(best_result_list) > plist_len
)
):
best_result_list = result_list
retry_count += 1
end_time = time.time()
result_li... | Create a `log` directory and add this directory to .gitignore.I think that would make the structure clearer:D |
def log_translation_mismatch(
self, plist_len, result_list, new_str, sep, log_path="log/buglog.txt"
):
if len(result_list) == plist_len:
return
newlist = new_str.split(sep)
with open(log_path, "a") as f:
print(f"problem size: {plist_len - len(result_list)... | @@ -90,5 +120,110 @@ def translate(self, text):
t_text = self.get_translation(text)
# todo: Determine whether to print according to the cli option
- print(t_text.strip())
+ if needprint:
+ print(re.sub("\n{3,}", "\n\n", t_text))
+
+ elapsed_time = time.time() - st... | book_maker/translator/chatgptapi_translator.py | 26 | Python | 0.5 | suggestion | 110 | 43 | 51 | false | Cumulative translation | 148 | yihong0618/bilingual_book_maker | 3,321 | Python | zstone12 | sunyuechi |
def translate(self, text, needprint=True):
print("=================================================")
start_time = time.time()
# todo: Determine whether to print according to the cli option
if needprint:
print(re.sub("\n{3,}", "\n\n", text))
try:
t_te... | There are some `print` statements that are used for debugging purposes, but I agree with your point that the `logging` module can be used instead. Users are primarily interested in the original text, translation, and progress, which are the original output.
What's your opinion? @yihong0618 | # print(
# f"{usage['total_tokens']} {usage['prompt_tokens']} {usage['completion_tokens']} {self.max_num_token} (total_token, prompt_token, completion_tokens, max_history_total_token)"
# )
return t_text
def translate(self, text, needprint=True):
# print("====... | @@ -90,5 +120,110 @@ def translate(self, text):
t_text = self.get_translation(text)
# todo: Determine whether to print according to the cli option
- print(t_text.strip())
+ if needprint:
+ print(re.sub("\n{3,}", "\n\n", t_text))
+
+ elapsed_time = time.time() - st... | book_maker/translator/chatgptapi_translator.py | 26 | Python | 0.786 | bug | 292 | 51 | 51 | false | Cumulative translation | 148 | yihong0618/bilingual_book_maker | 3,321 | Python | zstone12 | sunyuechi |
retry_count = 0
sleep_dur = 6
result_list = self.translate_and_split_lines(new_str)
start_time = time.time()
end_time = time.time()
best_result_list = result_list
while len(result_list) != plist_len and retry_count < 15:
print(
f"bu... | ` len(best_result_list) < len(result_list) <= plist_len`. from pycharm suggestion
| result_list = self.translate_and_split_lines(new_str)
if (
len(result_list) == plist_len
or len(best_result_list) < len(result_list) <= plist_len
or (
len(result_list) < len(best_result_list)
and len(best_res... | @@ -90,5 +120,110 @@ def translate(self, text):
t_text = self.get_translation(text)
# todo: Determine whether to print according to the cli option
- print(t_text.strip())
+ if needprint:
+ print(re.sub("\n{3,}", "\n\n", t_text))
+
+ elapsed_time = time.time() - st... | book_maker/translator/chatgptapi_translator.py | 26 | Python | 0.357 | suggestion | 83 | 51 | 51 | false | Cumulative translation | 148 | yihong0618/bilingual_book_maker | 3,321 | Python | zstone12 | sunyuechi |
retry_count += 1
result_list = self.translate_and_split_lines(new_str)
if (
len(result_list) == plist_len
or len(best_result_list) < len(result_list) <= plist_len
or (
len(result_list) < len(best_result_list)
... | Previously, I forgot about this. We need to ensure that the user has the 'log' directory. If it does not exist, create this; otherwise, the `write` operation will fail. You can refer to https://stackoverflow.com/questions/23793987/write-file-to-a-directory-that-doesnt-exist.
| return result_list, 0
best_result_list = result_list
retry_count = 0
while retry_count < max_retries and len(result_list) != plist_len:
print(
f"bug: {plist_len} -> {len(result_list)} : Number of paragraphs before and after translation"
)
... | @@ -90,5 +122,128 @@ def translate(self, text):
t_text = self.get_translation(text)
# todo: Determine whether to print according to the cli option
- print(t_text.strip())
+ if needprint:
+ print(re.sub("\n{3,}", "\n\n", t_text))
+
+ elapsed_time = time.time() - st... | book_maker/translator/chatgptapi_translator.py | 26 | Python | 0.786 | bug | 277 | 51 | 51 | false | Cumulative translation | 148 | yihong0618/bilingual_book_maker | 3,321 | Python | zstone12 | sunyuechi |
)
options = parser.parse_args()
PROXY = options.proxy
if PROXY != "":
os.environ["http_proxy"] = PROXY
os.environ["https_proxy"] = PROXY
translate_model = MODEL_DICT.get(options.model)
assert translate_model is not None, "unsupported model"
if options.model in ["gpt3", "cha... | do not call it openai_key let us make a new arg | )
parser.add_argument(
"--caiyun_key",
dest="caiyun_key",
type=str,
help="you can apply caiyun key from here (https://dashboard.caiyunapp.com/user/sign_in/)",
)
options = parser.parse_args()
PROXY = options.proxy
if PROXY != "":
os.environ["http_proxy"] =... | @@ -187,12 +187,7 @@ def main():
"OpenAI API key not provided, please google how to obtain it"
)
elif options.model == "caiyun":
- OPENAI_API_KEY = (
- options.openai_key
- or env.get(
- "BBM_CAIYUN_API_KEY"
- )
- )
+ ... | book_maker/cli.py | 26 | Python | 0.071 | suggestion | 47 | 51 | 51 | false | (#93) feat: add caiyun translator | 160 | yihong0618/bilingual_book_maker | 3,321 | Python | yihong0618 | voyageyang |
)
def _make_new_book(self, book):
new_book = epub.EpubBook()
new_book.metadata = book.metadata
new_book.spine = book.spine
new_book.toc = book.toc
return new_book
def _process_paragraph(self, p, index, p_to_save_len):
if not p.text or self._is_special_te... | better:
```python
if elf.translation_style:
do_something()
else:
p.insert_after(new_p)
```
readable | )
def _make_new_book(self, book):
new_book = epub.EpubBook()
new_book.metadata = book.metadata
new_book.spine = book.spine
new_book.toc = book.toc
return new_book
def _process_paragraph(self, p, index, p_to_save_len):
if not p.text or self._is_special_te... | @@ -120,7 +123,7 @@ def _process_paragraph(self, p, index, p_to_save_len):
new_p.string = self.translate_model.translate(p.text)
self.p_to_save.append(new_p.text)
- p.insert_after(new_p)
+ self.helper.insert_with_style(p, new_p.string, self.translation_style) | book_maker/loader/epub_loader.py | 26 | Python | 0.786 | style | 115 | 51 | 51 | false | support --translation_style | 185 | yihong0618/bilingual_book_maker | 3,321 | Python | yihong0618 | sunyuechi |
book_type = options.book_name.split(".")[-1]
support_type_list = list(BOOK_LOADER_DICT.keys())
if book_type not in support_type_list:
raise Exception(
f"now only support files of these formats: {','.join(support_type_list)}"
)
book_loader = BOOK_LOADER_DICT.get(book_type)
... | let us put it in here since other translator do not has this attr
https://github.com/yihong0618/bilingual_book_maker/blob/fa9e375a8ec8c94759dfad0c1c7f7704b1ab99ec/book_maker/cli.py#L295-L307 |
book_type = options.book_name.split(".")[-1]
support_type_list = list(BOOK_LOADER_DICT.keys())
if book_type not in support_type_list:
raise Exception(
f"now only support files of these formats: {','.join(support_type_list)}"
)
book_loader = BOOK_LOADER_DICT.get(book_type)
... | @@ -280,6 +286,7 @@ def main():
options.resume,
language=language,
model_api_base=model_api_base,
+ deployment_id=options.deployment_id, | book_maker/cli.py | 26 | Python | 0.357 | suggestion | 191 | 50 | 51 | false | feat: add Azure OpenAI service support | 213 | yihong0618/bilingual_book_maker | 3,321 | Python | yihong0618 | liby |
or self.DEFAULT_PROMPT
)
self.prompt_sys_msg = (
prompt_sys_msg
or environ.get(
"OPENAI_API_SYS_MSG"
) # XXX: for backward compatability, deprecate soon
or environ.get(PROMPT_ENV_MAP["system"])
or ""
)
... | if self.deployment_id:
do_something() | "OPENAI_API_SYS_MSG"
) # XXX: for backward compatability, deprecate soon
or environ.get(PROMPT_ENV_MAP["system"])
or ""
)
self.system_content = environ.get("OPENAI_API_SYS_MSG") or ""
self.deployment_id = None
def rotate_key(self):
... | @@ -59,10 +65,16 @@ def create_chat_completion(self, text):
{"role": "user", "content": content},
]
- return openai.ChatCompletion.create(
- model="gpt-3.5-turbo",
- messages=messages,
- )
+ if hasattr(self, "deployment_id"):
+ return openai.... | book_maker/translator/chatgptapi_translator.py | 26 | Python | 0.071 | suggestion | 42 | 51 | 51 | false | feat: add Azure OpenAI service support | 213 | yihong0618/bilingual_book_maker | 3,321 | Python | yihong0618 | liby |
PROMPT_ENV_MAP = {
"user": "BBM_CHATGPTAPI_USER_MSG_TEMPLATE",
"system": "BBM_CHATGPTAPI_SYS_MSG",
}
class ChatGPTAPI(Base):
DEFAULT_PROMPT = "Please help me to translate,`{text}` to {language}, please return only translated content not include the origin text"
def __init__(
self,
ke... | you can make a method
```
def set_deployment_id(self, deployment_id):
openai.api_type = "azure"
openai.api_version = "2023-03-15-preview"
self.deployment_id = deployment_id
``` |
PROMPT_ENV_MAP = {
"user": "BBM_CHATGPTAPI_USER_MSG_TEMPLATE",
"system": "BBM_CHATGPTAPI_SYS_MSG",
}
class ChatGPTAPI(Base):
DEFAULT_PROMPT = "Please help me to translate,`{text}` to {language}, please return only translated content not include the origin text"
def __init__(
self,
ke... | @@ -21,12 +21,18 @@ def __init__(
key,
language,
api_base=None,
+ deployment_id=None,
prompt_template=None,
prompt_sys_msg=None,
**kwargs,
):
super().__init__(key, language)
self.key_len = len(key.split(","))
+ if deployment_id:
... | book_maker/translator/chatgptapi_translator.py | 26 | Python | 0.929 | suggestion | 200 | 51 | 51 | false | feat: add Azure OpenAI service support | 213 | yihong0618/bilingual_book_maker | 3,321 | Python | yihong0618 | liby |
dest="translation_style",
type=str,
help="""ex: --translation_style "color: #808080; font-style: italic;" """,
)
parser.add_argument(
"--batch_size",
dest="batch_size",
type=int,
help="how many lines will be translated by aggregated translation(This option... | --single_translate ? maybe better? | dest="translation_style",
type=str,
help="""ex: --translation_style "color: #808080; font-style: italic;" """,
)
parser.add_argument(
"--batch_size",
dest="batch_size",
type=int,
help="how many lines will be translated by aggregated translation(This option... | @@ -230,6 +230,11 @@ def main():
python3 "make_book.py" --book_name "test_books/animal_farm.epub" --retranslate 'test_books/animal_farm_bilingual.epub' 'index_split_002.html' 'in spite of the present book shortage which'
""",
)
+ parser.add_argument(
+ "--no_bilingual",
+ action="store_t... | book_maker/cli.py | 26 | Python | 0.143 | question | 34 | 51 | 51 | false | support single_translate in epub | 237 | yihong0618/bilingual_book_maker | 3,321 | Python | yihong0618 | sunyuechi |
if book_type not in support_type_list:
raise Exception(
f"now only support files of these formats: {','.join(support_type_list)}",
)
book_loader = BOOK_LOADER_DICT.get(book_type)
assert book_loader is not None, "unsupported loader"
language = options.language
if options.... | if we add here we also need to add it in txt loader | if book_type not in support_type_list:
raise Exception(
f"now only support files of these formats: {','.join(support_type_list)}",
)
book_loader = BOOK_LOADER_DICT.get(book_type)
assert book_loader is not None, "unsupported loader"
language = options.language
if options.... | @@ -308,6 +313,7 @@ def main():
is_test=options.test,
test_num=options.test_num,
prompt_config=parse_prompt_arg(options.prompt_arg),
+ no_bilingual=options.no_bilingual, | book_maker/cli.py | 26 | Python | 0.214 | suggestion | 51 | 51 | 51 | false | support single_translate in epub | 237 | yihong0618/bilingual_book_maker | 3,321 | Python | yihong0618 | sunyuechi |
self._save_progress()
self._save_temp_book()
sys.exit(0)
def load_state(self):
try:
with open(self.bin_path, "rb") as f:
self.p_to_save = pickle.load(f)
except Exception:
raise Exception("can not load resume file")
... | not self.exclude_filelist or item.file_name not in self.exclude_filelist.split(",")
maybe better? |
def _save_temp_book(self):
# TODO refactor this logic
origin_book_temp = epub.read_epub(self.epub_name)
new_temp_book = self._make_new_book(origin_book_temp)
p_to_save_len = len(self.p_to_save)
trans_taglist = self.translate_tags.split(",")
index = 0
try:
... | @@ -464,7 +488,19 @@ def _save_temp_book(self):
index = 0
try:
for item in origin_book_temp.get_items():
- if item.get_type() == ITEM_DOCUMENT:
+ if (
+ item.get_type() == ITEM_DOCUMENT
+ and (
+ it... | book_maker/loader/epub_loader.py | 26 | Python | 0.429 | question | 100 | 51 | 51 | false | fix: bugs for using exlude_filelists and only_filelists | 324 | yihong0618/bilingual_book_maker | 3,321 | Python | yihong0618 | zerone01y |
e.translation_style = options.translation_style
if options.batch_size:
e.batch_size = options.batch_size
if options.retranslate:
e.retranslate = options.retranslate
if options.deployment_id:
# only work for ChatGPT api for now
# later maybe support others
asse... | this seems wrong it always raise error | e.translate_tags = options.translate_tags
if options.exclude_translate_tags:
e.exclude_translate_tags = options.exclude_translate_tags
if options.exclude_filelist:
e.exclude_filelist = options.exclude_filelist
if options.only_filelist:
e.only_filelist = options.only_filelist
... | @@ -423,7 +433,7 @@ def main():
if not options.api_base:
raise ValueError("`api_base` must be provided when using `deployment_id`")
e.translate_model.set_deployment_id(options.deployment_id)
- if options.model == "openai":
+ if options.model in ("openai", "groq"): | book_maker/cli.py | 26 | Python | 0.214 | bug | 38 | 40 | 50 | false | feat: support groq translator | 399 | yihong0618/bilingual_book_maker | 3,321 | Python | yihong0618 | umm233 |
"system": "BBM_CHATGPTAPI_SYS_MSG",
}
GPT35_MODEL_LIST = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-1106",
"gpt-3.5-turbo-16k",
"gpt-3.5-turbo-0613",
"gpt-3.5-turbo-16k-0613",
"gpt-3.5-turbo-0301",
"gpt-3.5-turbo-0125",
]
GPT4_MODEL_LIST = [
"gpt-4-1106-preview",
"gpt-4",
"gpt-4-32k"... | why we use global var here since it can set by user. | "system": "BBM_CHATGPTAPI_SYS_MSG",
}
GPT35_MODEL_LIST = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-1106",
"gpt-3.5-turbo-16k",
"gpt-3.5-turbo-0613",
"gpt-3.5-turbo-16k-0613",
"gpt-3.5-turbo-0301",
"gpt-3.5-turbo-0125",
]
GPT4_MODEL_LIST = [
"gpt-4-1106-preview",
"gpt-4",
"gpt-4-32k"... | @@ -36,6 +36,7 @@
"gpt-4o-mini",
"gpt-4o-mini-2024-07-18",
]
+CONTEXT_PARAGRAPH_LIMIT = 3 | book_maker/translator/chatgptapi_translator.py | 26 | Python | 0.286 | suggestion | 52 | 51 | 51 | false | feat: enable context flag and add context paragraph limit on chatgpt … | 420 | yihong0618/bilingual_book_maker | 3,321 | Python | yihong0618 | mkXultra |
}
GPT35_MODEL_LIST = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-1106",
"gpt-3.5-turbo-16k",
"gpt-3.5-turbo-0613",
"gpt-3.5-turbo-16k-0613",
"gpt-3.5-turbo-0301",
"gpt-3.5-turbo-0125",
]
GPT4_MODEL_LIST = [
"gpt-4-1106-preview",
"gpt-4",
"gpt-4-32k",
"gpt-4o-2024-05-13",
"gpt-4-06... | let's make a config.py file for these? | PROMPT_ENV_MAP = {
"user": "BBM_CHATGPTAPI_USER_MSG_TEMPLATE",
"system": "BBM_CHATGPTAPI_SYS_MSG",
}
GPT35_MODEL_LIST = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-1106",
"gpt-3.5-turbo-16k",
"gpt-3.5-turbo-0613",
"gpt-3.5-turbo-16k-0613",
"gpt-3.5-turbo-0301",
"gpt-3.5-turbo-0125",
]
GPT4_MO... | @@ -37,6 +40,7 @@
"gpt-4o-mini-2024-07-18",
]
CONTEXT_PARAGRAPH_LIMIT = 3
+BATCH_CONTEXT_UPDATE_INTERVAL = 50 | book_maker/translator/chatgptapi_translator.py | 26 | Python | 0.071 | question | 38 | 51 | 51 | false | supprt openai batch api | 423 | yihong0618/bilingual_book_maker | 3,321 | Python | yihong0618 | mkXultra |
i["id"] for i in self.openai_client.models.list().model_dump()["data"]
]
model_list = list(set(my_model_list) & set(GPT4_MODEL_LIST))
print(f"Using model list {model_list}")
self.model_list = cycle(model_list)
def set_gpt4omini_models(self):
#... | I think this name is not support windows
can we use `pathlib` or `os.path` | my_model_list = [
i["id"] for i in self.openai_client.models.list().model_dump()["data"]
]
model_list = list(set(my_model_list) & set(GPT4_MODEL_LIST))
print(f"Using model list {model_list}")
self.model_list = cycle(model_list)
def set_gpt... | @@ -388,3 +407,224 @@ def set_model_list(self, model_list):
model_list = list(set(model_list))
print(f"Using model list {model_list}")
self.model_list = cycle(model_list)
+
+ def batch_init(self, book_name):
+ self.book_name = self.sanitize_book_name(book_name) | book_maker/translator/chatgptapi_translator.py | 26 | Python | 0.429 | suggestion | 77 | 51 | 51 | false | supprt openai batch api | 423 | yihong0618/bilingual_book_maker | 3,321 | Python | yihong0618 | mkXultra |
print(f"Using model list {model_list}")
self.model_list = cycle(model_list)
def set_model_list(self, model_list):
model_list = list(set(model_list))
print(f"Using model list {model_list}")
self.model_list = cycle(model_list)
def batch_init(self, book_name):
... | ditto seems not support windows file name | model_list = list(set(my_model_list) & set(GPT4oMINI_MODEL_LIST))
print(f"Using model list {model_list}")
self.model_list = cycle(model_list)
def set_model_list(self, model_list):
model_list = list(set(model_list))
print(f"Using model list {model_list}")
... | @@ -388,3 +407,224 @@ def set_model_list(self, model_list):
model_list = list(set(model_list))
print(f"Using model list {model_list}")
self.model_list = cycle(model_list)
+
+ def batch_init(self, book_name):
+ self.book_name = self.sanitize_book_name(book_name)
+
+ def add_to_bat... | book_maker/translator/chatgptapi_translator.py | 26 | Python | 0.071 | suggestion | 41 | 51 | 51 | false | supprt openai batch api | 423 | yihong0618/bilingual_book_maker | 3,321 | Python | yihong0618 | mkXultra |
}
],
)
t_text = (
completion["choices"][0]
.get("message")
.get("content")
.encode("utf8")
.decode()
)
print(t_text)
return t_text
class BEPUB:
de... | No issues found. | }
],
)
t_text = (
completion["choices"][0]
.get("message")
.get("content")
.encode("utf8")
.decode()
)
print(t_text)
return t_text
class BEPUB:
de... | @@ -1,8 +1,10 @@
import argparse
+import pickle
import time
from abc import abstractmethod
from copy import copy
from os import environ as env
+from pathlib import Path
import openai
import requests
@@ -12,6 +14,7 @@
NO_LIMIT = False
IS_TEST = False
+RESUME = False
class Base:
@@ -114,11 +117,16 @@ de... | make_book.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | [feature] Support interrupt resume function | 10 | yihong0618/bilingual_book_maker | 3,321 | Python | Brikarl | |
new_book = self._make_new_book(complete_book)
complete_item = self.get_item(complete_book, fixname)
if complete_item is None:
return
ori_item = self.get_item(self.origin_book, fixname)
if ori_item is None:
return
soup_complete = bs(complete_ite... | No issues found. |
new_book = self._make_new_book(complete_book)
complete_item = self.get_item(complete_book, fixname)
if complete_item is None:
return
ori_item = self.get_item(self.origin_book, fixname)
if ori_item is None:
return
soup_complete = bs(complete_ite... | @@ -29,13 +29,17 @@ def __init__(
is_test=False,
test_num=5,
prompt_config=None,
+ chatgptaccount=None,
+ chatgptpassword=None,
):
self.epub_name = epub_name
self.new_epub = epub.EpubBook()
self.translate_model = model(
key,
... | book_maker/loader/epub_loader.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | feat:add ChatGPT Account translate method and input options to __init… | 43 | yihong0618/bilingual_book_maker | 3,321 | Python | guaguaguaxia | |
"-m",
"--model",
dest="model",
type=str,
default="chatgptapi",
choices=translate_model_list, # support DeepL later
metavar="MODEL",
help="model to use, available: {%(choices)s}",
)
parser.add_argument(
"--language",
type=str,
... | No issues found. | "-m",
"--model",
dest="model",
type=str,
default="chatgptapi",
choices=translate_model_list, # support DeepL later
metavar="MODEL",
help="model to use, available: {%(choices)s}",
)
parser.add_argument(
"--language",
type=str,
... | @@ -170,6 +170,18 @@ def main():
metavar="PROMPT_ARG",
help="used for customizing the prompt. It can be the prompt template string, or a path to the template file. The valid placeholders are `{text}` and `{language}`.",
)
+ parser.add_argument(
+ "--accumulated_num",
+ dest="accu... | book_maker/cli.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Cumulative translation | 148 | yihong0618/bilingual_book_maker | 3,321 | Python | sunyuechi | |
import json
import requests
from .base_translator import Base
class Caiyun(Base):
"""
caiyun translator
"""
def __init__(self, key, language, **kwargs):
super().__init__(key, language)
self.api_url = "http://api.interpreter.caiyunai.com/v1/translator"
self.headers = {
... | No issues found. | import json
import requests
from .base_translator import Base
class Caiyun(Base):
"""
caiyun translator
"""
def __init__(self, key, language, **kwargs):
super().__init__(key, language)
self.api_url = "http://api.interpreter.caiyunai.com/v1/translator"
self.headers = {
... | @@ -0,0 +1,43 @@
+import json
+
+import requests
+
+from .base_translator import Base
+
+
+class Caiyun(Base):
+ """
+ caiyun translator
+ """
+
+ def __init__(self, key, language, **kwargs):
+ super().__init__(key, language)
+ self.api_url = "http://api.interpreter.caiyunai.com/v1/translator"... | book_maker/translator/caiyun_translator.py | 0 | Python | 1 | none | 16 | 44 | 44 | true | (#93) feat: add caiyun translator | 160 | yihong0618/bilingual_book_maker | 3,321 | Python | voyageyang | |
self.insert_trans(
p, self.translate_model.translate(p.text), self.translation_style
)
def deal_old(self, wait_p_list):
if not wait_p_list:
return
result_txt_list = self.translate_model.translate_list(wait_p_list)
for i in range(len(wait_p_list)):
... | No issues found. | self.insert_trans(
p, self.translate_model.translate(p.text), self.translation_style
)
def deal_old(self, wait_p_list):
if not wait_p_list:
return
result_txt_list = self.translate_model.translate_list(wait_p_list)
for i in range(len(wait_p_list)):
... | @@ -3,16 +3,26 @@
class EPUBBookLoaderHelper:
- def __init__(self, translate_model, accumulated_num):
+ def __init__(self, translate_model, accumulated_num, translation_style):
self.translate_model = translate_model
self.accumulated_num = accumulated_num
+ self.translation_style = tr... | book_maker/loader/helper.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | support --translation_style | 185 | yihong0618/bilingual_book_maker | 3,321 | Python | sunyuechi | |
complete_item = self.get_item(complete_book, fixname)
if complete_item is None:
return
ori_item = self.get_item(self.origin_book, fixname)
if ori_item is None:
return
soup_complete = bs(complete_item.content, "html.parser")
soup_ori = bs(ori_ite... | No issues found. |
complete_item = self.get_item(complete_book, fixname)
if complete_item is None:
return
ori_item = self.get_item(self.origin_book, fixname)
if ori_item is None:
return
soup_complete = bs(complete_item.content, "html.parser")
soup_ori = bs(ori_ite... | @@ -49,7 +49,7 @@ def __init__(
)
self.retranslate = None
- # monkey pathch for # 173
+ # monkey patch for # 173
def _write_items_patch(obj):
for item in obj.book.get_items():
if isinstance(item, epub.EpubNcx):
@@ -73,7 +73,7 @@ def _write_items_p... | book_maker/loader/epub_loader.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | feat: add Azure OpenAI service support | 213 | yihong0618/bilingual_book_maker | 3,321 | Python | liby | |
new_book = self._make_new_book(complete_book)
complete_item = self.get_item(complete_book, fixname)
if complete_item is None:
return
ori_item = self.get_item(self.origin_book, fixname)
if ori_item is None:
return
soup_complete = bs(complete_item... | No issues found. | new_book = self._make_new_book(complete_book)
complete_item = self.get_item(complete_book, fixname)
if complete_item is None:
return
ori_item = self.get_item(self.origin_book, fixname)
if ori_item is None:
return
soup_complete = bs(complete_item... | @@ -29,6 +29,7 @@ def __init__(
is_test=False,
test_num=5,
prompt_config=None,
+ single_translate=False,
):
self.epub_name = epub_name
self.new_epub = epub.EpubBook()
@@ -51,6 +52,7 @@ def __init__(
self.retranslate = None
self.exclude_filelist ... | book_maker/loader/epub_loader.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | support single_translate in epub | 237 | yihong0618/bilingual_book_maker | 3,321 | Python | sunyuechi | |
from groq import Groq
from .chatgptapi_translator import ChatGPTAPI
from os import linesep
from itertools import cycle
GROQ_MODEL_LIST = [
"llama3-8b-8192",
"llama3-70b-8192",
"mixtral-8x7b-32768",
"gemma-7b-it",
]
class GroqClient(ChatGPTAPI):
def rotate_model(self):
if not self.model_l... | No issues found. | from groq import Groq
from .chatgptapi_translator import ChatGPTAPI
from os import linesep
from itertools import cycle
GROQ_MODEL_LIST = [
"llama3-8b-8192",
"llama3-70b-8192",
"mixtral-8x7b-32768",
"gemma-7b-it",
]
class GroqClient(ChatGPTAPI):
def rotate_model(self):
if not self.model_l... | @@ -0,0 +1,45 @@
+from groq import Groq
+from .chatgptapi_translator import ChatGPTAPI
+from os import linesep
+from itertools import cycle
+
+
+GROQ_MODEL_LIST = [
+ "llama3-8b-8192",
+ "llama3-70b-8192",
+ "mixtral-8x7b-32768",
+ "gemma-7b-it",
+]
+
+
+class GroqClient(ChatGPTAPI):
+ def rotate_model(s... | book_maker/translator/groq_translator.py | 0 | Python | 1 | none | 16 | 46 | 46 | true | feat: support groq translator | 399 | yihong0618/bilingual_book_maker | 3,321 | Python | umm233 | |
default="p",
help="example --translate-tags p,blockquote",
)
parser.add_argument(
"--exclude_translate-tags",
dest="exclude_translate_tags",
type=str,
default="sup",
help="example --exclude_translate-tags table,sup",
)
parser.add_argument(
... | No issues found. | default="p",
help="example --translate-tags p,blockquote",
)
parser.add_argument(
"--exclude_translate-tags",
dest="exclude_translate_tags",
type=str,
default="sup",
help="example --exclude_translate-tags table,sup",
)
parser.add_argument(
... | @@ -279,6 +279,13 @@ def main():
action="store_true",
help="adds an additional paragraph for global, updating historical context of the story to the model's input, improving the narrative consistency for the AI model (this uses ~200 more tokens each time)",
)
+ parser.add_argument(
+ "-... | book_maker/cli.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | feat: enable context flag and add context paragraph limit on chatgpt … | 420 | yihong0618/bilingual_book_maker | 3,321 | Python | mkXultra | |
segments
.iter()
.map(|segment| match segment {
JsonPathSegment::Key(key) => {
if key.contains('.') || key.contains('-') {
format!(".\"{}\"", key)
} els... | @corneliusroemer I would like to proceed with the merge, but please make a revision just regarding this https://github.com/ynqa/jnv/issues/3#issuecomment-2008950603. | segments
.iter()
.map(|segment| match segment {
JsonPathSegment::Key(key) => {
if key.contains('.') || key.contains('-') {
format!(".\"{}\"", key)
} els... | @@ -74,16 +74,16 @@ impl Jnv {
history: Default::default(),
prefix: String::from("❯❯ "),
mask: Default::default(),
- prefix_style: StyleBuilder::new().fgc(Color::DarkCyan).build(),
- active_char_style: StyleBuilder::new().bgc(Color::DarkMa... | src/jnv.rs | 26 | Rust | 0.357 | suggestion | 165 | 51 | 51 | false | fix: Use brighter colors for better accessibility | 4 | ynqa/jnv | 3,138 | Rust | ynqa | corneliusroemer |
mod keymap;
/// Deserializes a JSON string into a vector of `serde_json::Value`.
///
/// This function takes a JSON string as input and attempts to parse it into a vector
/// of `serde_json::Value`, which represents any valid JSON value (e.g., object, array, string, number).
/// It leverages `serde_json::Deserializer`... | How about dropping duplication?
```suggestion
let deserializer = Deserializer::from_str(json_str).into_iter::<serde_json::Value>();
let results = match limit_length {
Some(l) => deserializer.take(l).collect::<Result<Vec<_>, _>>(),
None => deserializer.collect::<Result<Vec<_>, _>>(),
... | mod keymap;
/// Deserializes a JSON string into a vector of `serde_json::Value`.
///
/// This function takes a JSON string as input and attempts to parse it into a vector
/// of `serde_json::Value`, which represents any valid JSON value (e.g., object, array, string, number).
/// It leverages `serde_json::Deserializer`... | @@ -35,11 +35,18 @@ mod keymap;
/// # Returns
/// An `anyhow::Result` wrapping a vector of `serde_json::Value`. On success, it contains the parsed
/// JSON data. On failure, it contains an error detailing what went wrong during parsing.
-fn deserialize_json(json_str: &str) -> anyhow::Result<Vec<serde_json::Value>> {... | src/jnv.rs | 26 | Rust | 0.929 | question | 369 | 51 | 51 | false | Improving perfomance for JSON Lines format | 41 | ynqa/jnv | 3,138 | Rust | ynqa | edy555 |
#[arg(
short = 'n',
long = "no-hint",
help = "Disables the display of hints.",
long_help = "
When this option is enabled, it prevents the display of
hints that typically guide or offer suggestions to the user.
"
)]
pub no_hint: bool,
#[arg(
... | `-s` will be used at https://github.com/ynqa/jnv/issues/29. Could it be replaced (or deleted)? |
#[arg(
short = 'n',
long = "no-hint",
help = "Disables the display of hints.",
long_help = "
When this option is enabled, it prevents the display of
hints that typically guide or offer suggestions to the user.
"
)]
pub no_hint: bool,
#[arg(
... | @@ -99,6 +99,18 @@ pub struct Args {
)]
pub json_expand_depth: Option<usize>,
+ #[arg(
+ short = 's', | src/main.rs | 26 | Rust | 0.429 | question | 94 | 51 | 51 | false | Improving perfomance for JSON Lines format | 41 | ynqa/jnv | 3,138 | Rust | ynqa | edy555 |
import openai
import pinecone
import time
from collections import deque
from typing import Dict, List
from dotenv import load_dotenv
import os
load_dotenv()
# Set API Keys
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")
PINECONE_ENVIRONMENT = os.getenv("PINECONE_ENVIRONME... | could use defaults here. would also be nice to throw in some `assert`s so that if your API key is blank, we early exit. | import openai
import pinecone
import time
from collections import deque
from typing import Dict, List
from dotenv import load_dotenv
import os
load_dotenv()
# Set API Keys
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
assert OPENAI_API_KEY, "OPENAI_API_KEY environment variable is missing from .env from .env"
PINE... | @@ -3,16 +3,22 @@
import time
from collections import deque
from typing import Dict, List
+from dotenv import load_dotenv
+import os
-#Set API Keys
-OPENAI_API_KEY = ""
-PINECONE_API_KEY = ""
-PINECONE_ENVIRONMENT = "us-east1-gcp" #Pinecone Environment (eg. "us-east1-gcp")
+load_dotenv()
-#Set Variables
-YOUR_TA... | babyagi.py | 21 | Python | 0.571 | suggestion | 120 | 46 | 46 | false | Added environment variables | 9 | yoheinakajima/babyagi | 6,266 | Python | DrewMcArthur | peteoxenham |
openai.api_key = OPENAI_API_KEY
pinecone.init(api_key=PINECONE_API_KEY, environment=PINECONE_ENVIRONMENT)
# Create Pinecone index
table_name = YOUR_TABLE_NAME
dimension = 1536
metric = "cosine"
pod_type = "p1"
if table_name not in pinecone.list_indexes():
pinecone.create_index(table_name, dimension=dimension, metr... | I'd prefer if we keep the parameter here. Even though it's not really properly used right now, having the parameter allow us to build a hybrid mode where some of the calls are made with GPT-3 models, and others with GPT-4 chat completions. | pinecone.init(api_key=PINECONE_API_KEY, environment=PINECONE_ENVIRONMENT)
# Create Pinecone index
table_name = YOUR_TABLE_NAME
dimension = 1536
metric = "cosine"
pod_type = "p1"
if table_name not in pinecone.list_indexes():
pinecone.create_index(table_name, dimension=dimension, metric=metric, pod_type=pod_type)
#... | @@ -67,11 +69,11 @@ def get_ada_embedding(text):
text = text.replace("\n", " ")
return openai.Embedding.create(input=[text], model="text-embedding-ada-002")["data"][0]["embedding"]
-def openai_call(prompt: str, use_gpt4: bool = False, temperature: float = 0.5, max_tokens: int = 100):
- if not use_gpt4:
-... | babyagi.py | 26 | Python | 0.5 | suggestion | 239 | 51 | 51 | false | Add support for specifying other gpt models | 41 | yoheinakajima/babyagi | 6,266 | Python | francip | davidbyttow |
#!/usr/bin/env python3
import os
import openai
import pinecone
import time
import sys
from collections import deque
from typing import Dict, List
from dotenv import load_dotenv
import os
# Set Variables
load_dotenv()
# Set API Keys
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
assert OPENAI_API_KEY, "OPENAI_API_KE... | ```suggestion
OPENAI_API_MODEL = os.getenv("OPENAI_API_MODEL", "gpt-3.5-turbo")
```
Here as well. | #!/usr/bin/env python3
import os
import openai
import pinecone
import time
import sys
from collections import deque
from typing import Dict, List
from dotenv import load_dotenv
import os
# Set Variables
load_dotenv()
# Set API Keys
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
assert OPENAI_API_KEY, "OPENAI_API_KE... | @@ -9,17 +9,18 @@
from dotenv import load_dotenv
import os
-#Set Variables
+# Set Variables
load_dotenv()
# Set API Keys
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
assert OPENAI_API_KEY, "OPENAI_API_KEY environment variable is missing from .env"
-# Use GPT-3 model
-USE_GPT4 = False
-if USE_GPT4:
- ... | babyagi.py | 19 | Python | 0.714 | suggestion | 100 | 44 | 44 | false | Add support for specifying other gpt models | 41 | yoheinakajima/babyagi | 6,266 | Python | CptCaptain | davidbyttow |
def task_creation_agent(objective: str, result: Dict, task_description: str, task_list: List[str]):
prompt = f"You are an task creation AI that uses the result of an execution agent to create new tasks with the following objective: {objective}, The last completed task has the result: {result}. This result was base... | ```suggestion
def execution_agent(objective: str, task: str) -> str:
```
formatting |
def task_creation_agent(objective: str, result: Dict, task_description: str, task_list: List[str]):
prompt = f"You are an task creation AI that uses the result of an execution agent to create new tasks with the following objective: {objective}, The last completed task has the result: {result}. This result was base... | @@ -117,12 +118,12 @@ def prioritization_agent(this_task_id:int, gpt_version: str = 'gpt-3'):
task_name = task_parts[1].strip()
task_list.append({"task_id": task_id, "task_name": task_name})
-def execution_agent(objective:str,task: str, gpt_version: str = 'gpt-3') -> str:
+def execution_agen... | babyagi.py | 26 | Python | 0.571 | suggestion | 86 | 51 | 51 | false | Add support for specifying other gpt models | 41 | yoheinakajima/babyagi | 6,266 | Python | CptCaptain | davidbyttow |
max_tokens=max_tokens,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
return response.choices[0].text.strip()
else:
# Use chat completion API
messages=[{"role": "user", "content": prompt}]
response = openai.ChatCompletion.cr... | ```suggestion
def prioritization_agent(this_task_id: int):
```
formatting | max_tokens=max_tokens,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
return response.choices[0].text.strip()
else:
# Use chat completion API
messages=[{"role": "user", "content": prompt}]
response = openai.ChatCompletion.cr... | @@ -81,33 +82,33 @@ def openai_call(prompt: str, use_gpt4: bool = False, temperature: float = 0.5, m
)
return response.choices[0].text.strip()
else:
- #Call GPT-4 chat model
+ # Use chat completion API
messages=[{"role": "user", "content": prompt}]
response = opena... | babyagi.py | 26 | Python | 0.571 | suggestion | 76 | 51 | 51 | false | Add support for specifying other gpt models | 41 | yoheinakajima/babyagi | 6,266 | Python | CptCaptain | davidbyttow |
#!/usr/bin/env python3
import os
import openai
import pinecone
import time
import sys
from collections import deque
from typing import Dict, List
from dotenv import load_dotenv
import os
# Set Variables
load_dotenv()
# Set API Keys
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
assert OPENAI_API_KEY, "OPENAI_API_KE... | ```suggestion
assert OPENAI_API_MODEL, "OPENAI_API_MODEL environment variable is missing from .env"
``` | #!/usr/bin/env python3
import os
import openai
import pinecone
import time
import sys
from collections import deque
from typing import Dict, List
from dotenv import load_dotenv
import os
# Set Variables
load_dotenv()
# Set API Keys
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
assert OPENAI_API_KEY, "OPENAI_API_KE... | @@ -9,17 +9,18 @@
from dotenv import load_dotenv
import os
-#Set Variables
+# Set Variables
load_dotenv()
# Set API Keys
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
assert OPENAI_API_KEY, "OPENAI_API_KEY environment variable is missing from .env"
-# Use GPT-3 model
-USE_GPT4 = False
-if USE_GPT4:
- ... | babyagi.py | 20 | Python | 0.714 | suggestion | 105 | 45 | 45 | false | Add support for specifying other gpt models | 41 | yoheinakajima/babyagi | 6,266 | Python | CptCaptain | davidbyttow |
temperature=temperature,
max_tokens=max_tokens,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
return response.choices[0].text.strip()
else:
# Use chat completion API
messages=[{"role": "user", "content": prompt}]
... | do we not want to print the error here? won't this quietly exit on another error, or no? | engine=model,
prompt=prompt,
temperature=temperature,
max_tokens=max_tokens,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
return response.choi... | @@ -69,30 +69,37 @@ def get_ada_embedding(text):
return openai.Embedding.create(input=[text], model="text-embedding-ada-002")["data"][0]["embedding"]
def openai_call(prompt: str, model: str = OPENAI_API_MODEL, temperature: float = 0.5, max_tokens: int = 100):
- if not model.startswith('gpt-'):
- # Use... | babyagi.py | 26 | Python | 0.357 | bug | 88 | 51 | 51 | false | OpenAI API Error managed | 63 | yoheinakajima/babyagi | 6,266 | Python | davidbyttow | Korben00 |
#!/usr/bin/env python3
import argparse
import os
import openai
import pinecone
import time
import sys
from collections import deque
from typing import Dict, List
from dotenv import load_dotenv
import os
# Parse arguments for optional extensions
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--env', narg... | Being a bit nitpicky here, but the logic as structured will load the extension .env first and then the main, which means the extension can't overwrite anything in the main. We should reverse the order - first load the core .env, then load optional extension(s), which can add more env variables or overwrite preloaded. T... | #!/usr/bin/env python3
import argparse
import os
import openai
import pinecone
import time
import sys
from collections import deque
from typing import Dict, List
from dotenv import load_dotenv
import os
# Parse arguments for optional extensions
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--env', narg... | @@ -9,7 +10,18 @@
from dotenv import load_dotenv
import os
-# Set Variables
+# Parse arguments for optional extensions
+parser = argparse.ArgumentParser()
+parser.add_argument('-e', '--env', nargs='+', help='filenames for env')
+args = parser.parse_args()
+
+# Set environment variables for optional extensions
+if a... | babyagi.py | 22 | Python | 0.5 | nitpick | 466 | 47 | 47 | false | Allow an environment argument to support extension configuration | 67 | yoheinakajima/babyagi | 6,266 | Python | francip | fxchen |
# Load default environment variables (.env)
load_dotenv()
# Set environment variables for optional extensions
if args.env:
for env_path in args.env:
load_dotenv(env_path)
print('Using env from file:', env_path)
# Set API Keys
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
assert OPENAI_API_KEY,... | So this is trying to support multiple .env to override env variables? I haven't seen many examples where we need multiple .env files? Is it because each extension might need to override env variables? | OPENAI_API_MODEL = os.getenv("OPENAI_API_MODEL", "gpt-3.5-turbo")
PINECONE_API_KEY = os.getenv("PINECONE_API_KEY", "")
assert PINECONE_API_KEY, "PINECONE_API_KEY environment variable is missing from .env"
PINECONE_ENVIRONMENT = os.getenv("PINECONE_ENVIRONMENT", "us-east1-gcp")
# Table config
YOUR_TABLE_NAME = os.get... | @@ -1,59 +1,59 @@
#!/usr/bin/env python3
-import argparse
import os
+import time
import openai
import pinecone
-import time
-import sys
from collections import deque
from typing import Dict, List
from dotenv import load_dotenv
-import os
-
-# Parse arguments for optional extensions
-parser = argparse.ArgumentPar... | babyagi.py | 26 | Python | 0.5 | question | 200 | 51 | 51 | false | Command line arguments parser and updates to the dotenv | 82 | yoheinakajima/babyagi | 6,266 | Python | tnachen | francip |
from extensions.dotenvext import load_dotenv_extensions
load_dotenv_extensions(DOTENV_EXTENSIONS)
# TODO: There's still work to be done here to enable people to get
# defaults from dotenv extensions # but also provide command line
# arguments to override them
if "gpt-4" in OPENAI_API_MODEL.lower():
print... | OBJECTIVE could also be loaded from command args right?
Seems like it's more correct to say is missing from .env or arg (if enabled) | # Command line arguments extension
# Can override any of the above environment variables
ENABLE_COMMAND_LINE_ARGS = (
os.getenv("ENABLE_COMMAND_LINE_ARGS", "false").lower() == "true"
)
if ENABLE_COMMAND_LINE_ARGS:
if can_import("extensions.argparseext"):
from extensions.argparseext import parse_argument... | @@ -52,20 +64,28 @@
os.getenv("ENABLE_COMMAND_LINE_ARGS", "false").lower() == "true"
)
if ENABLE_COMMAND_LINE_ARGS:
- from extensions.argparseext import parse_arguments
+ if can_import("extensions.argparseext"):
+ from extensions.argparseext import parse_arguments
- OBJECTIVE, INITIAL_TASK, OPE... | babyagi.py | 26 | Python | 0.429 | suggestion | 133 | 51 | 51 | false | Fixing crash if extensions is missing | 112 | yoheinakajima/babyagi | 6,266 | Python | tnachen | francip |
break
parsed_args.append(arg)
env_argv = ['-e'] + parsed_args
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--env', nargs='+', help='''
filenames for additional env variables to load
''', default=os.getenv("DOTENV_EXTENSIONS", "").split(' '))
ret... | No issues found. | break
parsed_args.append(arg)
env_argv = ['-e'] + parsed_args
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--env', nargs='+', help='''
filenames for additional env variables to load
''', default=os.getenv("DOTENV_EXTENSIONS", "").split(' '))
ret... | @@ -0,0 +1,76 @@
+import os
+import sys
+import argparse
+
+# Extract the env filenames in the -e flag only
+# Ignore any other arguments
+def parse_dotenv_extensions(argv):
+ env_argv = []
+ if '-e' in argv:
+ tmp_argv = argv[argv.index('-e') + 1:]
+ parsed_args = []
+ for arg in tmp_argv:
+... | extensions/argparseext.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Command line arguments parser and updates to the dotenv | 82 | yoheinakajima/babyagi | 6,266 | Python | francip | |
def get_ada_embedding(text):
text = text.replace("\n", " ")
return openai.Embedding.create(input=[text], model="text-embedding-ada-002")[
"data"
][0]["embedding"]
def openai_call(
prompt: str,
model: str = OPENAI_API_MODEL,
temperature: float = OPENAI_TEMPERATURE,
max_tokens: int =... | No issues found. | def get_ada_embedding(text):
text = text.replace("\n", " ")
return openai.Embedding.create(input=[text], model="text-embedding-ada-002")[
"data"
][0]["embedding"]
def openai_call(
prompt: str,
model: str = OPENAI_API_MODEL,
temperature: float = OPENAI_TEMPERATURE,
max_tokens: int =... | @@ -20,14 +20,6 @@
assert OPENAI_API_KEY, "OPENAI_API_KEY environment variable is missing from .env"
OPENAI_API_MODEL = os.getenv("OPENAI_API_MODEL", "gpt-3.5-turbo")
-assert OPENAI_API_MODEL, "OPENAI_API_MODEL environment variable is missing from .env"
-
-if "gpt-4" in OPENAI_API_MODEL.lower():
- print(
- ... | babyagi.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Cooperative mode based on Python Ray | 85 | yoheinakajima/babyagi | 6,266 | Python | francip | |
import openai
import pinecone
from dotenv import load_dotenv
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
assert OPENAI_API_KEY, "OPENAI_API_KEY environment variable is missing from .env"
PINECONE_API_KEY = os.getenv("PINECONE_API_KEY", "")
assert PINECONE_API_KEY, "PINECONE_API_KEY environment var... | No issues found. | import openai
import pinecone
from dotenv import load_dotenv
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
assert OPENAI_API_KEY, "OPENAI_API_KEY environment variable is missing from .env"
PINECONE_API_KEY = os.getenv("PINECONE_API_KEY", "")
assert PINECONE_API_KEY, "PINECONE_API_KEY environment var... | @@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+import os
+import argparse
+import openai
+import pinecone
+from dotenv import load_dotenv
+
+load_dotenv()
+
+OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
+assert OPENAI_API_KEY, "OPENAI_API_KEY environment variable is missing from .env"
+
+PINECONE_API_KEY = os.getenv("PI... | tools/results.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Llama.cpp support | 87 | yoheinakajima/babyagi | 6,266 | Python | francip | |
placement: {
type: String,
default: 'bottom',
},
getContainer: {
type: [String, Function],
default: 'body',
},
closeOnClickAction: {
type: Boolean,
default: true,
},
},
watch: {
value: 'updateLocation',
placement: 'updateLocation',
},
mounted... | How about adding a `if (!isServer) {` condition to avoid effecting SSR | placement: {
type: String,
default: 'bottom',
},
getContainer: {
type: [String, Function],
default: 'body',
},
closeOnClickAction: {
type: Boolean,
default: true,
},
},
watch: {
value: 'updateLocation',
placement: 'updateLocation',
},
mounted... | @@ -60,14 +60,16 @@ export default createComponent({
beforeDestroy() {
if (this.popper) {
+ window.removeEventListener('animationend', this.popper.update); | src/popover/index.js | 26 | JavaScript | 0.429 | suggestion | 70 | 51 | 51 | false | fix(popover): location update | 11,558 | youzan/vant | 18,391 | TypeScript | chenjiahan | acyza |
this.popper = null;
}
},
methods: {
createPopper() {
const popper = createPopper(this.$refs.wrapper, this.$refs.popover.$el, {
placement: this.placement,
modifiers: [
{
name: 'computeStyles',
options: {
adaptive: false,
... | If the popper is not showed or deactivated when inside a `<keep-alive>`, should we calling `popper.update()` ? | }
this.popper.destroy();
this.popper = null;
}
},
methods: {
createPopper() {
const popper = createPopper(this.$refs.wrapper, this.$refs.popover.$el, {
placement: this.placement,
modifiers: [
{
name: 'computeStyles',
options: {
... | @@ -85,6 +87,9 @@ export default createComponent({
},
],
});
+ window.addEventListener('animationend', popper.update);
+ window.addEventListener('transitionend', popper.update); | src/popover/index.js | 26 | JavaScript | 0.571 | question | 110 | 51 | 51 | false | fix(popover): location update | 11,558 | youzan/vant | 18,391 | TypeScript | chenjiahan | acyza |
import { raf, cancelRaf } from '@vant/use';
import { ScrollElement, getScrollTop, setScrollTop } from '../utils';
let scrollLeftToRafId: number;
let scrollTopToRafId: number;
export function scrollLeftTo(
scroller: HTMLElement,
to: number,
duration: number
) {
cancelRaf(scrollLeftToRafId);
let count = 0;
... | If we use a global variable to store the id, it may break the scroll animation if there are multiple components. So we should store the id at the component level. | import { raf, cancelRaf } from '@vant/use';
import { ScrollElement, getScrollTop, setScrollTop } from '../utils';
export function scrollLeftTo(
scroller: HTMLElement,
to: number,
duration: number
) {
let rafId: number;
let count = 0;
const from = scroller.scrollLeft;
const frames = duration === 0 ? 1 : M... | @@ -1,11 +1,16 @@
-import { raf } from '@vant/use';
+import { raf, cancelRaf } from '@vant/use';
import { ScrollElement, getScrollTop, setScrollTop } from '../utils';
+let scrollLeftToRafId: number;
+let scrollTopToRafId: number; | packages/vant/src/tabs/utils.ts | 5 | TypeScript | 0.429 | suggestion | 162 | 30 | 30 | false | fix(Tab): should cancel raf before the next scroll | 11,819 | youzan/vant | 18,391 | TypeScript | chenjiahan | inottn |
instance.start();
await later();
expect(wrapper.find(itemWrapperClass).classes()).toContain(animationClass);
instance.reset();
await later();
expect(wrapper.find(itemWrapperClass).classes()).not.toContain(
animationClass
);
});
test('should restart rolling after calling the reset method when auto-s... | 这里应该是 toContain吧,不是 not.toContain |
instance.start();
await later();
expect(wrapper.find(itemWrapperClass).classes()).toContain(animationClass);
instance.reset();
await later();
expect(wrapper.find(itemWrapperClass).classes()).not.toContain(
animationClass
);
});
test('should restart rolling after calling the reset method when auto-s... | @@ -1,13 +1,95 @@
-import { RollingText } from '..';
-import { mount } from '../../../test';
+import { RollingText, type RollingTextInstance } from '..';
+import { later, mount } from '../../../test';
+
+const itemWrapperClass = '.van-roll-single-down__box';
+const animationClass = 'van-roll-single-down__ani';
test(... | packages/vant/src/rolling-text/test/index.spec.ts | 26 | TypeScript | 0.071 | suggestion | 34 | 29 | 31 | false | fix(RollingText): should restart rolling after calling the reset method when auto-start prop is true | 11,991 | youzan/vant | 18,391 | TypeScript | cunzaizhuyi | inottn |
icon: 'Icon',
loading: 'Loading',
shape: 'Shape',
default: 'Default',
primary: 'Primary',
success: 'Success',
danger: 'Danger',
warning: 'Warning',
large: 'Large',
normal: 'Normal',
small: 'Small',
mini: 'Mini',
plain: 'Plain',
square: 'Square',
round: 'Round'... | 用完整的单词哈
animatedButton: 'Animated Button' | icon: 'Icon',
loading: 'Loading',
shape: 'Shape',
default: 'Default',
primary: 'Primary',
success: 'Success',
danger: 'Danger',
warning: 'Warning',
large: 'Large',
normal: 'Normal',
small: 'Small',
mini: 'Mini',
plain: 'Plain',
square: 'Square',
round: 'Round'... | @@ -60,6 +65,9 @@ const t = useTranslate({
pure: 'Pure',
gradient: 'Gradient',
blockElement: 'Block Element',
+ aniButton: 'aniButton', | packages/vant/src/button/demo/index.vue | 26 | Vue | 0.071 | suggestion | 44 | 51 | 51 | false | chore(Button): add animation button demo | 11,995 | youzan/vant | 18,391 | TypeScript | chenjiahan | cunzaizhuyi |
import { join } from 'node:path';
import { SCRIPT_EXTS, STYLE_EXTS } from '../common/constant.js';
import { readFileSync, existsSync } from 'node:fs';
let depsMap: Record<string, string[]> = {};
let existsCache: Record<string, boolean> = {};
// https://regexr.com/47jlq
const IMPORT_RE =
/import\s+?(?:(?:(?:[\w*\s{}... | 试了下这个正则,还是稍微宽松了一些,可能会匹配到一些预期之外的情况,比如:

红框里的部分是为了匹配 magic comments 嘛?可以考虑再调整下

https://regexper.com/#%2Fimport.*%3F%5C%28%5B'... | import { join } from 'node:path';
import { SCRIPT_EXTS, STYLE_EXTS } from '../common/constant.js';
import { readFileSync, existsSync } from 'node:fs';
let depsMap: Record<string, string[]> = {};
let existsCache: Record<string, boolean> = {};
// https://regexr.com/47jlq
const IMPORT_RE =
/import\s+?(?:(?:(?:[\w*\s{}... | @@ -8,6 +8,7 @@ let existsCache: Record<string, boolean> = {};
// https://regexr.com/47jlq
const IMPORT_RE =
/import\s+?(?:(?:(?:[\w*\s{},]*)\s+from(\s+)?)|)(?:(?:".*?")|(?:'.*?'))[\s]*?(?:;|$|)/g;
+const IMPORT_NOF_RE = /import.*?\(['|"].+?['|"]\)/g; | packages/vant-cli/src/compiler/get-deps.ts | 11 | TypeScript | 0.429 | suggestion | 359 | 36 | 36 | false | feat(get-deps): import('../foo.vue') => import('../foo.mjs') 的替换 | 12,046 | youzan/vant | 18,391 | TypeScript | chenjiahan | suncohey |
export const inBrowser = typeof window !== 'undefined';
// Keep forward compatible
// should be removed in next major version
export const supportsPassive = true;
export function raf(fn: FrameRequestCallback): number {
return inBrowser ? requestAnimationFrame(fn) : -1;
}
export function cancelRaf(id: number) {
i... | Can you add a Vant document for this new API? | export const inBrowser = typeof window !== 'undefined';
// Keep forward compatible
// should be removed in next major version
export const supportsPassive = true;
export function raf(fn: FrameRequestCallback): number {
return inBrowser ? requestAnimationFrame(fn) : -1;
}
export function cancelRaf(id: number) {
i... | @@ -14,6 +14,14 @@ export function cancelRaf(id: number) {
}
}
+export function useRaf(fn: FrameRequestCallback): () => void { | packages/vant-use/src/utils.ts | 17 | TypeScript | 0.071 | question | 45 | 29 | 21 | false | feat(vant-use): add useRaf | 12,211 | youzan/vant | 18,391 | TypeScript | chenjiahan | Simon-He95 |
import { inBrowser } from '..';
export function useRaf(fn: FrameRequestCallback, interval = 0): () => void {
if (inBrowser) {
let start: number;
const disposesId: number[] = [];
let isStopped = false;
const frameWrapper = (timestamp: number) => {
if (isStopped) return;
if (start === unde... | The disposesId will only be cleared when cancel is called. Considering the execution frequency of requestAnimationFrame, the length of disposesId should increase rapidly. | import { inBrowser } from '..';
interface UseRafOptions {
interval?: number;
isLoop?: boolean;
}
export function useRaf(
fn: FrameRequestCallback,
options?: UseRafOptions,
): () => void {
if (inBrowser) {
const { interval = 0, isLoop = false } = options || {};
let start: number;
let isStopped = ... | @@ -0,0 +1,28 @@
+import { inBrowser } from '..';
+
+export function useRaf(fn: FrameRequestCallback, interval = 0): () => void {
+ if (inBrowser) {
+ let start: number;
+ const disposesId: number[] = [];
+ let isStopped = false;
+
+ const frameWrapper = (timestamp: number) => {
+ if (isStopped) retur... | packages/vant-use/src/useRaf/index.ts | 17 | TypeScript | 0.429 | suggestion | 170 | 29 | 42 | false | feat(vant-use): add useRaf | 12,211 | youzan/vant | 18,391 | TypeScript | inottn | Simon-He95 |
options?: UseRafOptions,
): () => void {
if (inBrowser) {
const { interval = 0, isLoop = false } = options || {};
let start: number;
let isStopped = false;
let rafId: number;
const stop = () => {
isStopped = true;
cancelAnimationFrame(rafId);
};
const frameWrapper = (timesta... | It seems like `cancelAnimationFrame` here can be removed. | options?: UseRafOptions,
): () => void {
if (inBrowser) {
const { interval = 0, isLoop = false } = options || {};
let start: number;
let isStopped = false;
let rafId: number;
const stop = () => {
isStopped = true;
cancelAnimationFrame(rafId);
};
const frameWrapper = (timesta... | @@ -0,0 +1,42 @@
+import { inBrowser } from '..';
+
+interface UseRafOptions {
+ interval?: number;
+ isLoop?: boolean;
+}
+
+export function useRaf(
+ fn: FrameRequestCallback,
+ options?: UseRafOptions,
+): () => void {
+ if (inBrowser) {
+ const { interval = 0, isLoop = false } = options || {};
+ let star... | packages/vant-use/src/useRaf/index.ts | 26 | TypeScript | 0.429 | suggestion | 57 | 34 | 33 | false | feat(vant-use): add useRaf | 12,211 | youzan/vant | 18,391 | TypeScript | inottn | Simon-He95 |
computed,
defineComponent,
type PropType,
type ExtractPropTypes,
} from 'vue';
// Utils
import { pick, extend, truthProp, createNamespace } from '../utils';
import { CHECKBOX_GROUP_KEY } from '../checkbox-group/CheckboxGroup';
// Composables
import { useParent, useCustomFieldValue } from '@vant/use';
import {... | 这个横线看起来没有完全居中。。

| computed,
defineComponent,
type PropType,
type ExtractPropTypes,
} from 'vue';
// Utils
import { pick, extend, truthProp, createNamespace } from '../utils';
import { CHECKBOX_GROUP_KEY } from '../checkbox-group/CheckboxGroup';
// Composables
import { useParent, useCustomFieldValue } from '@vant/use';
import {... | @@ -25,6 +25,7 @@ const [name, bem] = createNamespace('checkbox');
export const checkboxProps = extend({}, checkerProps, {
shape: String as PropType<CheckerShape>,
bindGroup: truthProp,
+ indeterminate: Boolean, | packages/vant/src/checkbox/Checkbox.tsx | 26 | TypeScript | 0.357 | suggestion | 113 | 51 | 51 | false | feat(Checkbox): add indeterminate status | 12,216 | youzan/vant | 18,391 | TypeScript | chenjiahan | wjw-gavin |
const activeIcon = cdnURL('user-active.png');
const inactiveIcon = cdnURL('user-inactive.png');
const group = ref<CheckboxGroupInstance>();
const isIndeterminate = ref(true);
const [refs, setRefs] = useRefs<CheckboxInstance>();
const toggle = (index: number) => {
refs.value[index].toggle();
};
const checkAll = () ... | 这个 API 不是特别高频,可以放到示例列表的下面,没必要放到第二个
另外可以参考 antd 的示例,能够比较好地说明这个 API 的使用场景:
https://ant-design.antgroup.com/components/checkbox-cn#checkbox

| });
const list = ['a', 'b', 'c', 'd'];
const activeIcon = cdnURL('user-active.png');
const inactiveIcon = cdnURL('user-inactive.png');
const group = ref<CheckboxGroupInstance>();
const [refs, setRefs] = useRefs<CheckboxInstance>();
const toggle = (index: number) => {
refs.value[index].toggle();
};
const checkAll... | @@ -85,6 +89,21 @@ const toggleAll = () => {
<van-checkbox v-model="state.checkbox1">{{ t('checkbox') }}</van-checkbox>
</demo-block>
+ <demo-block :title="t('indeterminate')"> | packages/vant/src/checkbox/demo/index.vue | 26 | Vue | 0.429 | suggestion | 240 | 51 | 51 | false | feat(Checkbox): add indeterminate status | 12,216 | youzan/vant | 18,391 | TypeScript | chenjiahan | wjw-gavin |
const touch = event.touches[0];
const mouseX = (touch.clientX - (canvasRect?.left || 0)) * state.ratio;
const mouseY = (touch.clientY - (canvasRect?.top || 0)) * state.ratio;
state.ctx.lineCap = 'round';
state.ctx.lineJoin = 'round';
state.ctx?.lineTo(mouseX, mouseY);
state.c... | Can we reuse the `setCanvasBgColor` function? The ctx can be a param. |
const touch = event.touches[0];
const mouseX = (touch.clientX - (canvasRect?.left || 0)) * state.ratio;
const mouseY = (touch.clientY - (canvasRect?.top || 0)) * state.ratio;
state.ctx.lineCap = 'round';
state.ctx.lineJoin = 'round';
state.ctx?.lineTo(mouseX, mouseY);
state.c... | @@ -97,6 +97,11 @@ export default defineComponent({
const empty = document.createElement('canvas');
empty.width = canvas.width;
empty.height = canvas.height;
+ if (props.backgroundColor) {
+ const emptyCtx = empty.getContext('2d');
+ emptyCtx!.fillStyle = props.backgroundColor;
+... | packages/vant/src/signature/Signature.tsx | 26 | TypeScript | 0.429 | question | 69 | 51 | 51 | false | fix(Signature): fix checking if canvas is empty when backgoundColor is set | 12,304 | youzan/vant | 18,391 | TypeScript | chenjiahan | sywyyhykkk |
emits: ['click', 'clickDisabledDate'],
setup(props, { emit, slots }) {
const [visible, setVisible] = useToggle();
const daysRef = ref<HTMLElement>();
const monthRef = ref<HTMLElement>();
const height = useHeight(monthRef);
const title = computed(() => formatMonthTitle(props.date));
const r... | Is this a breaking change? The `title` param of `month-show` event is changed.
The previous type was string, but now the type is `Ref<string>` |
setup(props, { emit, slots }) {
const [visible, setVisible] = useToggle();
const daysRef = ref<HTMLElement>();
const monthRef = ref<HTMLElement>();
const height = useHeight(monthRef);
const title = computed(() => formatMonthTitle(props.date));
const rowHeight = computed(() => addUnit(props.r... | @@ -87,7 +88,7 @@ export default defineComponent({
const shouldRender = computed(() => visible.value || !props.lazyRender);
- const getTitle = () => title.value;
+ const getTitle = () => toRef(title, 'value'); | packages/vant/src/calendar/CalendarMonth.tsx | 26 | TypeScript | 0.714 | question | 145 | 51 | 51 | false | fix(canendar): subtitle supports reactive | 12,425 | youzan/vant | 18,391 | TypeScript | chenjiahan | cc-hearts |
y: (touches[0].clientY + touches[1].clientY) / 2,
});
const bem = createNamespace('image-preview')[1];
const longImageRatio = 2.6;
const imagePreviewItemProps = {
src: String,
show: Boolean,
active: Number,
minZoom: makeRequiredProp(numericProp),
maxZoom: makeRequiredProp(numericProp),
rootWidth: makeR... | We can use `imagePreviewItemProps` 😄
```suggestion
props: imagePreviewItemProps
``` | y: (touches[0].clientY + touches[1].clientY) / 2,
});
const bem = createNamespace('image-preview')[1];
const longImageRatio = 2.6;
const imagePreviewItemProps = {
src: String,
show: Boolean,
active: Number,
minZoom: makeRequiredProp(numericProp),
maxZoom: makeRequiredProp(numericProp),
rootWidth: makeR... | @@ -43,6 +45,23 @@ const bem = createNamespace('image-preview')[1];
const longImageRatio = 2.6;
+const imagePreviewItemProps = {
+ src: String,
+ show: Boolean,
+ active: Number,
+ minZoom: makeRequiredProp(numericProp),
+ maxZoom: makeRequiredProp(numericProp),
+ rootWidth: makeRequiredProp(Number),
+ root... | packages/vant/src/image-preview/ImagePreviewItem.tsx | 26 | TypeScript | 0.643 | suggestion | 90 | 51 | 51 | false | feat(ImagePreview): expose resetScale method | 12,426 | youzan/vant | 18,391 | TypeScript | chenjiahan | inottn |
group.forEach((item, index) => {
if (index === 0) {
spaces.push({ right: averagePadding });
} else {
const left = gutter - spaces[item - 1].right;
const right = averagePadding - left;
spaces.push({ left, right });
}
});
... | ```suggestion
spaces.push({ bottom });
``` | group.forEach((item, index) => {
if (index === 0) {
spaces.push({ right: averagePadding });
} else {
const left = gutter - spaces[item - 1].right;
const right = averagePadding - left;
spaces.push({ left, right });
}
});
... | @@ -94,7 +101,26 @@ export default defineComponent({
return spaces;
});
- linkChildren({ spaces });
+ const verticalSpaces = computed(() => {
+ const { gutter } = props;
+ const spaces: VerticalSpaces = [];
+ if (Array.isArray(gutter) && gutter.length > 1) {
+ const bottom = Nu... | packages/vant/src/row/Row.tsx | 26 | TypeScript | 0.571 | suggestion | 58 | 51 | 51 | false | feat(Row): gutter support vertical space | 12,439 | youzan/vant | 18,391 | TypeScript | inottn | cc-hearts |
} else {
const left = gutter - spaces[item - 1].right;
const right = averagePadding - left;
spaces.push({ left, right });
}
});
});
return spaces;
});
const verticalSpaces = computed(() => {
const { gutter } = props;
const... | ```suggestion
groups.value.forEach((group, index) => {
if (index === groups.value.length - 1) return;
group.forEach(() => {
spaces.push({ bottom });
});
});
``` | } else {
const left = gutter - spaces[item - 1].right;
const right = averagePadding - left;
spaces.push({ left, right });
}
});
});
return spaces;
});
const verticalSpaces = computed(() => {
const { gutter } = props;
const... | @@ -94,7 +101,26 @@ export default defineComponent({
return spaces;
});
- linkChildren({ spaces });
+ const verticalSpaces = computed(() => {
+ const { gutter } = props;
+ const spaces: VerticalSpaces = [];
+ if (Array.isArray(gutter) && gutter.length > 1) {
+ const bottom = Nu... | packages/vant/src/row/Row.tsx | 26 | TypeScript | 0.786 | suggestion | 225 | 49 | 48 | false | feat(Row): gutter support vertical space | 12,439 | youzan/vant | 18,391 | TypeScript | inottn | cc-hearts |
props: colProps,
setup(props, { slots }) {
const { parent, index } = useParent(ROW_KEY);
const style = computed(() => {
if (!parent) {
return;
}
const { spaces, verticalSpaces } = parent;
let styles = {};
if (spaces && spaces.value && spaces.value[index.value]) {
... | ```suggestion
const { bottom } = verticalSpaces.value[index.value] || {};
return extend(styles, {
marginBottom: bottom ? `${bottom}px` : null,
});
``` |
props: colProps,
setup(props, { slots }) {
const { parent, index } = useParent(ROW_KEY);
const style = computed(() => {
if (!parent) {
return;
}
const { spaces, verticalSpaces } = parent;
let styles = {};
if (spaces && spaces.value && spaces.value[index.value]) {
... | @@ -31,15 +32,21 @@ export default defineComponent({
return;
}
- const { spaces } = parent;
-
+ const { spaces, verticalSpaces } = parent;
+ let styles = {};
if (spaces && spaces.value && spaces.value[index.value]) {
const { left, right } = spaces.value[index.value];
- ... | packages/vant/src/col/Col.tsx | 26 | TypeScript | 0.857 | suggestion | 183 | 43 | 43 | false | feat(Row): gutter support vertical space | 12,439 | youzan/vant | 18,391 | TypeScript | inottn | cc-hearts |
state.moving = false;
return;
}
isImageMoved = true;
preventDefault(event, true);
state.moveX = clamp(moveX, -maxMoveX.value, maxMoveX.value);
state.moveY = clamp(moveY, -maxMoveY.value, maxMoveY.value);
}
if (state.zooming) {
preventDefa... | When using slots, it's also possible that the image element is not the first element, should we consider that case | ) {
state.moving = false;
return;
}
isImageMoved = true;
preventDefault(event, true);
state.moveX = clamp(moveX, -maxMoveX.value, maxMoveX.value);
state.moveY = clamp(moveY, -maxMoveY.value, maxMoveY.value);
}
if (state.zooming) {
... | @@ -251,8 +252,12 @@ export default defineComponent({
};
const checkClose = (event: TouchEvent) => {
- const isClickOverlay = event.target === swipeItem.value?.$el;
+ const swipeItemEl: HTMLElement = swipeItem.value?.$el;
+ const imageEl = swipeItemEl.firstElementChild; | packages/vant/src/image-preview/ImagePreviewItem.tsx | 26 | TypeScript | 0.429 | suggestion | 114 | 51 | 51 | false | feat(ImagePreview): add close-on-click-image prop | 12,566 | youzan/vant | 18,391 | TypeScript | chenjiahan | inottn |
// useEventListener will set passive to `false` to eliminate the warning of Chrome
useEventListener('touchmove', onTouchMove, {
target: computed(() => swipeItem.value?.$el),
});
useExpose({ resetScale });
return () => {
const imageSlots = {
loading: () => <Loading type="spinne... | ```suggestion
onLoad,
``` |
// useEventListener will set passive to `false` to eliminate the warning of Chrome
useEventListener('touchmove', onTouchMove, {
target: computed(() => swipeItem.value?.$el),
});
useExpose({ resetScale });
return () => {
const imageSlots = {
loading: () => <Loading type="spinne... | @@ -407,7 +407,11 @@ export default defineComponent({
>
{slots.image ? (
<div class={bem('image-wrap')}>
- {slots.image({ src: props.src })}
+ {slots.image({
+ src: props.src,
+ onLoad: onLoad, | packages/vant/src/image-preview/ImagePreviewItem.tsx | 26 | TypeScript | 0.429 | suggestion | 43 | 46 | 46 | false | feat(image-preview): export onLoad and style for image slot | 12,740 | youzan/vant | 18,391 | TypeScript | chenjiahan | chouchouji |
import {
computed,
defineComponent,
ref,
watch,
type ExtractPropTypes,
type PropType,
ComponentPublicInstance,
} from 'vue';
// Utils
import {
formatValueRange,
genOptions,
pickerInheritKeys,
sharedProps,
type TimeFilter,
} from '../date-picker/utils';
import {
createNamespace,
extend,
is... | ```suggestion
type ComponentPublicInstance,
``` | import {
computed,
defineComponent,
ref,
watch,
type ExtractPropTypes,
type PropType,
type ComponentPublicInstance,
} from 'vue';
// Utils
import {
formatValueRange,
genOptions,
pickerInheritKeys,
sharedProps,
type TimeFilter,
} from '../date-picker/utils';
import {
createNamespace,
extend,... | @@ -5,6 +5,7 @@ import {
watch,
type ExtractPropTypes,
type PropType,
+ ComponentPublicInstance, | packages/vant/src/time-picker/TimePicker.tsx | 8 | TypeScript | 0.714 | suggestion | 51 | 33 | 33 | false | feat(TimePicker): support confirm and getSelectedTime methods | 12,761 | youzan/vant | 18,391 | TypeScript | chenjiahan | bluesky335 |
TimePickerExpose
>;
export default defineComponent({
name,
props: timePickerProps,
emits: ['confirm', 'cancel', 'change', 'update:modelValue'],
setup(props, { emit, slots }) {
const currentValues = ref<string[]>(props.modelValue);
const pickerRef = ref<PickerInstance>();
const getValidTime = ... | ```suggestion
const getSelectedTime = (): string[] => {
``` | export type TimePickerInstance = ComponentPublicInstance<
TimePickerProps,
TimePickerExpose
>;
export default defineComponent({
name,
props: timePickerProps,
emits: ['confirm', 'cancel', 'change', 'update:modelValue'],
setup(props, { emit, slots }) {
const currentValues = ref<string[]>(props.modelVa... | @@ -75,6 +88,14 @@ export default defineComponent({
);
};
+ const confirm = () => {
+ return pickerRef.value?.confirm();
+ };
+
+ const getSelectedTime = (): Array<string> => { | packages/vant/src/time-picker/TimePicker.tsx | 26 | TypeScript | 0.571 | suggestion | 65 | 51 | 51 | false | feat(TimePicker): support confirm and getSelectedTime methods | 12,761 | youzan/vant | 18,391 | TypeScript | chenjiahan | bluesky335 |
type ExtractPropTypes,
type PropType,
ComponentPublicInstance,
} from 'vue';
// Utils
import {
formatValueRange,
genOptions,
pickerInheritKeys,
sharedProps,
type TimeFilter,
} from '../date-picker/utils';
import {
createNamespace,
extend,
isSameValue,
makeNumericProp,
pick,
} from '../utils';... | ```suggestion
// Composables
import { useExpose } from '../composables/use-expose';
``` | type ExtractPropTypes,
type PropType,
type ComponentPublicInstance,
} from 'vue';
// Utils
import {
formatValueRange,
genOptions,
pickerInheritKeys,
sharedProps,
type TimeFilter,
} from '../date-picker/utils';
import {
createNamespace,
extend,
isSameValue,
makeNumericProp,
pick,
} from '../ut... | @@ -24,7 +25,8 @@ import {
} from '../utils';
// Components
-import { Picker } from '../picker';
+import { Picker, PickerInstance } from '../picker';
+import { useExpose } from '../composables/use-expose'; | packages/vant/src/time-picker/TimePicker.tsx | 26 | TypeScript | 0.643 | suggestion | 92 | 51 | 51 | false | feat(TimePicker): support confirm and getSelectedTime methods | 12,761 | youzan/vant | 18,391 | TypeScript | chenjiahan | bluesky335 |
minMonth,
maxMonth,
'month',
props.formatter,
props.filter,
);
};
const genDayOptions = () => {
const year = getValue('year');
const month = getValue('month');
const minDate =
isMinYear(year) && isMinMonth(month) ? props.minDate.getDate() ... | The type of **getSelectedDate** can be inferred by ts, maybe no need to declare the return type. | minMonth,
maxMonth,
'month',
props.formatter,
props.filter,
);
};
const genDayOptions = () => {
const year = getValue('year');
const month = getValue('month');
const minDate =
isMinYear(year) && isMinMonth(month) ? props.minDate.getDate() ... | @@ -121,6 +134,14 @@ export default defineComponent({
return genOptions(minDate, maxDate, 'day', props.formatter, props.filter);
};
+ const confirm = () => {
+ return pickerRef.value?.confirm();
+ };
+
+ const getSelectedDate = (): Array<string> => { | packages/vant/src/date-picker/DatePicker.tsx | 26 | TypeScript | 0.357 | suggestion | 96 | 51 | 51 | false | feat(DatePicker): support confirm and getSelectedDate method | 12,762 | youzan/vant | 18,391 | TypeScript | chouchouji | bluesky335 |
minMonth,
maxMonth,
'month',
props.formatter,
props.filter,
);
};
const genDayOptions = () => {
const year = getValue('year');
const month = getValue('month');
const minDate =
isMinYear(year) && isMinMonth(month) ? props.minDate.getDate() ... | ```suggestion
const getSelectedDate = () => {
``` | minMonth,
maxMonth,
'month',
props.formatter,
props.filter,
);
};
const genDayOptions = () => {
const year = getValue('year');
const month = getValue('month');
const minDate =
isMinYear(year) && isMinMonth(month) ? props.minDate.getDate() ... | @@ -121,6 +134,14 @@ export default defineComponent({
return genOptions(minDate, maxDate, 'day', props.formatter, props.filter);
};
+ const confirm = () => {
+ return pickerRef.value?.confirm();
+ };
+
+ const getSelectedDate = (): Array<string> => { | packages/vant/src/date-picker/DatePicker.tsx | 26 | TypeScript | 0.571 | suggestion | 55 | 51 | 51 | false | feat(DatePicker): support confirm and getSelectedDate method | 12,762 | youzan/vant | 18,391 | TypeScript | chenjiahan | bluesky335 |
import {
ref,
watch,
computed,
defineComponent,
ComponentPublicInstance,
type PropType,
type ExtractPropTypes,
} from 'vue';
// Utils
import { pick, extend, isDate, isSameValue, createNamespace } from '../utils';
import {
genOptions,
sharedProps,
getMonthEndDay,
pickerInheritKeys,
formatValueRa... | ```suggestion
type ComponentPublicInstance,
``` | import {
ref,
watch,
computed,
defineComponent,
type ComponentPublicInstance,
type PropType,
type ExtractPropTypes,
} from 'vue';
// Utils
import { pick, extend, isDate, isSameValue, createNamespace } from '../utils';
import {
genOptions,
sharedProps,
getMonthEndDay,
pickerInheritKeys,
formatVa... | @@ -3,6 +3,7 @@ import {
watch,
computed,
defineComponent,
+ ComponentPublicInstance, | packages/vant/src/date-picker/DatePicker.tsx | 6 | TypeScript | 0.714 | suggestion | 51 | 31 | 31 | false | feat(DatePicker): support confirm and getSelectedDate method | 12,762 | youzan/vant | 18,391 | TypeScript | chenjiahan | bluesky335 |
import { Area } from '..';
import { areaList } from '../demo/area-simple';
import { mount, later, triggerDrag } from '../../../test';
import {
PickerCancelEventParams,
PickerChangeEventParams,
PickerConfirmEventParams,
} from '../../picker';
test('should columns placeholder displayed normally', async () => {
c... | Prefer using English in test files:
```suggestion
const columnsPlaceholder = ['Province', 'City', 'County'];
``` | import { Area } from '..';
import { areaList } from '../demo/area-simple';
import { mount, later, triggerDrag } from '../../../test';
import {
PickerCancelEventParams,
PickerChangeEventParams,
PickerConfirmEventParams,
} from '../../picker';
test('should columns placeholder displayed normally', async () => {
c... | @@ -7,6 +7,24 @@ import {
PickerConfirmEventParams,
} from '../../picker';
+test('should columns placeholder displayed normally', async () => {
+ const columnsPlaceholder = ['省份', '省份', '区县']; | packages/vant/src/area/test/index.spec.ts | 11 | TypeScript | 0.786 | suggestion | 119 | 36 | 36 | false | fix(area): columns-placeholder prop rendering error | 12,857 | youzan/vant | 18,391 | TypeScript | chenjiahan | yipl95 |
item.$el.scrollIntoView(options);
return true;
}
return false;
});
};
const getValues = () =>
children.reduce<Record<string, unknown>>((form, field) => {
if (field.name !== undefined) {
form[field.name] = field.formValue.value;
}
... | 默认设置一个 block 可能会引起浏览器兼容性问题:
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

可能默认不设置 block 更好,仅在使用者传入 props.scrollToErrorPosition 的时候设置 scroll options
| return false;
});
};
const getValues = () =>
children.reduce<Record<string, unknown>>((form, field) => {
if (field.name !== undefined) {
form[field.name] = field.formValue.value;
}
return form;
}, {});
const submit = () => {
const values = ... | @@ -179,7 +183,9 @@ export default defineComponent({
emit('failed', { values, errors });
if (props.scrollToError && errors[0].name) {
- scrollToField(errors[0].name);
+ scrollToField(errors[0].name, {
+ block: props.scrollToErrorPosition, | packages/vant/src/form/Form.tsx | 26 | TypeScript | 0.571 | style | 279 | 51 | 51 | false | feat(Form): add prop "scrollToErrorPosition" | 12,937 | youzan/vant | 18,391 | TypeScript | chenjiahan | pany-ang |
state.focused = false;
updateValue(getModelValue(), 'onBlur');
emit('blur', event);
if (getProp('readonly')) {
return;
}
const { value } = event.target as HTMLInputElement;
if (props.type === 'number' || props.type === 'digit') {
const numericValue = value ==... | ```suggestion
if ((props.type === 'number' || props.type === 'digit') && value !== '') {
const adjustedValue = clamp(
+value,
props.min ?? -Infinity,
props.max ?? Infinity,
);
updateValue(adjustedValue.toString(), 'onBlur');
}
``` | state.focused = true;
emit('focus', event);
nextTick(adjustTextareaSize);
// readonly not work in legacy mobile safari
if (getProp('readonly')) {
blur();
}
};
const onBlur = (event: Event) => {
state.focused = false;
updateValue(getModelValue(), 'onBlur'... | @@ -419,6 +421,25 @@ export default defineComponent({
return;
}
+ const { value } = event.target as HTMLInputElement;
+
+ if (props.type === 'number' || props.type === 'digit') {
+ const numericValue = value === '' ? '' : Number(value);
+ const min = props.min !== undefined ? p... | packages/vant/src/field/Field.tsx | 26 | TypeScript | 0.929 | suggestion | 305 | 51 | 51 | false | feat(Field): add min and max props | 13,068 | youzan/vant | 18,391 | TypeScript | inottn | tuskermanshu |
) => {
if (min && compareDay(date, min) === -1) {
return min;
}
if (max && compareDay(date, max) === 1) {
return max;
}
return date;
};
const getInitialDate = (defaultDate = props.defaultDate) => {
const { type, allowSameDay } = props;
if (defaultD... | ```suggestion
// reset invalid default date
if (defaultDate.length === 1 && compareDay(defaultDate[0], now) === 1) {
``` | ) => {
if (min && compareDay(date, min) === -1) {
return min;
}
if (max && compareDay(date, max) === 1) {
return max;
}
return date;
};
const getInitialDate = (defaultDate = props.defaultDate) => {
const { type, allowSameDay } = props;
if (defaultD... | @@ -165,6 +165,10 @@ export default defineComponent({
defaultDate = [];
}
+ if (defaultDate.length === 1 && compareDay(defaultDate[0], now) === 1) { | packages/vant/src/calendar/Calendar.tsx | 26 | TypeScript | 0.714 | suggestion | 139 | 51 | 51 | false | fix(Calendar): fix getInitialDate function error | 13,075 | youzan/vant | 18,391 | TypeScript | chenjiahan | pany-ang |
{slots['top-info'] ? slots['top-info'](props.item) : topInfo}
</div>
);
}
};
const renderBottomInfo = () => {
const { bottomInfo } = props.item;
if (bottomInfo || slots['bottom-info']) {
return (
<div class={bem('bottom-info')}>
{sl... | Do we need a `div` wrapper? It seems unnecessary. | {slots['top-info'] ? slots['top-info'](props.item) : topInfo}
</div>
);
}
};
const renderBottomInfo = () => {
const { bottomInfo } = props.item;
if (bottomInfo || slots['bottom-info']) {
return (
<div class={bem('bottom-info')}>
{sl... | @@ -95,11 +95,22 @@ export default defineComponent({
}
};
+ const renderText = () => {
+ const { item } = props;
+ const { text } = item;
+
+ if (slots['text']) {
+ return <div class={bem('text')}>{slots['text'](props.item)}</div>; | packages/vant/src/calendar/CalendarDay.tsx | 26 | TypeScript | 0.214 | question | 49 | 51 | 51 | false | feat(Calendar): support `text` slot | 13,127 | youzan/vant | 18,391 | TypeScript | chenjiahan | yuyinws |
<div class={bem('top-info')}>
{slots['top-info'] ? slots['top-info'](props.item) : topInfo}
</div>
);
}
};
const renderBottomInfo = () => {
const { bottomInfo } = props.item;
if (bottomInfo || slots['bottom-info']) {
return (
<div cla... | ```suggestion
if (slots.text) {
``` | <div class={bem('top-info')}>
{slots['top-info'] ? slots['top-info'](props.item) : topInfo}
</div>
);
}
};
const renderBottomInfo = () => {
const { bottomInfo } = props.item;
if (bottomInfo || slots['bottom-info']) {
return (
<div cla... | @@ -95,11 +95,22 @@ export default defineComponent({
}
};
+ const renderText = () => {
+ const { item } = props;
+ const { text } = item;
+
+ if (slots['text']) { | packages/vant/src/calendar/CalendarDay.tsx | 26 | TypeScript | 0.429 | suggestion | 43 | 51 | 51 | false | feat(Calendar): support `text` slot | 13,127 | youzan/vant | 18,391 | TypeScript | chenjiahan | yuyinws |
<div class={bem('top-info')}>
{slots['top-info'] ? slots['top-info'](props.item) : topInfo}
</div>
);
}
};
const renderBottomInfo = () => {
const { bottomInfo } = props.item;
if (bottomInfo || slots['bottom-info']) {
return (
<div cla... | ```suggestion
return slots.text ? slots.text(props.item) : props.item.text;
``` | <div class={bem('top-info')}>
{slots['top-info'] ? slots['top-info'](props.item) : topInfo}
</div>
);
}
};
const renderBottomInfo = () => {
const { bottomInfo } = props.item;
if (bottomInfo || slots['bottom-info']) {
return (
<div cla... | @@ -95,11 +95,18 @@ export default defineComponent({
}
};
+ const renderText = () => {
+ const { item } = props;
+ const { text } = item;
+
+ return <>{slots.text ? slots.text(props.item) : text}</>; | packages/vant/src/calendar/CalendarDay.tsx | 26 | TypeScript | 0.571 | suggestion | 87 | 51 | 51 | false | feat(Calendar): support `text` slot | 13,127 | youzan/vant | 18,391 | TypeScript | inottn | yuyinws |
],
Shanghai: [
{ text: 'Huangpu', value: 'Huangpu' },
{ text: 'Xuhui', value: 'Xuhui' },
{ text: 'Changning', value: 'Changning' },
{ text: 'Pudong', value: 'Pudong' },
],
};
const currentValues = ref(['Beijing', 'Dongcheng']);
const wrapper = mount({
setup() {
const ... | ```suggestion
```
Since the comment in the previous line is very clear, we can remove the comment here. | ],
Shanghai: [
{ text: 'Huangpu', value: 'Huangpu' },
{ text: 'Xuhui', value: 'Xuhui' },
{ text: 'Changning', value: 'Changning' },
{ text: 'Pudong', value: 'Pudong' },
],
};
const currentValues = ref(['Beijing', 'Dongcheng']);
const wrapper = mount({
setup() {
const ... | @@ -440,3 +441,53 @@ test('should render empty slot when options is empty', async () => {
await wrapper.setProps({ columns: [{ values: ['foo'] }] });
expect(wrapper.html()).not.toContain('empty content');
});
+
+test('should emit correct values when clicking confirm button during column scrolling', async () => {... | packages/vant/src/picker/test/index.spec.tsx | 26 | TypeScript | 0.786 | suggestion | 105 | 39 | 37 | false | fix(Picker): ensure that the confirm event params are up to date | 13,381 | youzan/vant | 18,391 | TypeScript | inottn | refinist |
if (!isDef(newIndex)) {
return;
}
const newTab = children[newIndex];
const newName = getTabName(newTab, newIndex);
const shouldEmitChange = state.currentIndex !== null;
if (state.currentIndex !== newIndex) {
state.currentIndex = newIndex;
if (!skipScrollInt... | No issues found. | if (!isDef(newIndex)) {
return;
}
const newTab = children[newIndex];
const newName = getTabName(newTab, newIndex);
const shouldEmitChange = state.currentIndex !== null;
if (state.currentIndex !== newIndex) {
state.currentIndex = newIndex;
if (!skipScrollInt... | @@ -97,6 +97,8 @@ export default defineComponent({
let tabHeight: number;
let lockScroll: boolean;
let stickyFixed: boolean;
+ let cancelScrollLeftToRaf: (() => void) | undefined;
+ let cancelScrollTopToRaf: (() => void) | undefined;
const root = ref<HTMLElement>();
const navRef = ref<H... | packages/vant/src/tabs/Tabs.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(Tab): should cancel raf before the next scroll | 11,819 | youzan/vant | 18,391 | TypeScript | inottn | |
setup(props) {
const isCustomType = computed(
() => Array.isArray(props.textArray) && props.textArray.length
);
const getTextArrByIdx = (idx: number) => {
if (!isCustomType.value) return [];
const result = [];
for (let i = 0; i < props.textArray.length; i++) {
result.push... | No issues found. |
setup(props) {
const isCustomType = computed(
() => Array.isArray(props.textArray) && props.textArray.length
);
const getTextArrByIdx = (idx: number) => {
if (!isCustomType.value) return [];
const result = [];
for (let i = 0; i < props.textArray.length; i++) {
result.push... | @@ -1,6 +1,13 @@
-import { ref, defineComponent, computed, type ExtractPropTypes } from 'vue';
+import {
+ ref,
+ defineComponent,
+ computed,
+ watch,
+ type ExtractPropTypes,
+} from 'vue';
// Utils
+import { raf } from '@vant/use';
import {
createNamespace,
makeArrayProp,
@@ -98,16 +105,29 @@ export d... | packages/vant/src/rolling-text/RollingText.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(RollingText): should restart rolling after calling the reset method when auto-start prop is true | 11,991 | youzan/vant | 18,391 | TypeScript | inottn | |
title: 'useClickAway',
},
{
path: 'use-count-down',
title: 'useCountDown',
},
{
path: 'use-custom-field-value',
title: 'useCustomFieldValue',
},
{
... | No issues found. | title: 'useClickAway',
},
{
path: 'use-count-down',
title: 'useCountDown',
},
{
path: 'use-custom-field-value',
title: 'useCustomFieldValue',
},
{
... | @@ -503,6 +503,10 @@ location.href = location.href.replace('youzan.github.io', 'vant-ui.github.io');
path: 'use-window-size',
title: 'useWindowSize',
},
+ {
+ path: 'use-raf',
+ title: 'useRaf',
+ },
],... | packages/vant/vant.config.mjs | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat(vant-use): add useRaf | 12,211 | youzan/vant | 18,391 | TypeScript | Simon-He95 | |
.length;
const max = getParentProp('max');
const overlimit = max && checkedCount >= +max;
return disabled || (overlimit && !props.checked);
}
return disabled;
}
return props.disabled;
});
const direction = computed(() => getParentProp('di... | No issues found. | .length;
const max = getParentProp('max');
const overlimit = max && checkedCount >= +max;
return disabled || (overlimit && !props.checked);
}
return disabled;
}
return props.disabled;
});
const direction = computed(() => getParentProp('di... | @@ -45,6 +45,10 @@ export default defineComponent({
parent: Object as PropType<CheckerParent | null>,
checked: Boolean,
bindGroup: truthProp,
+ indeterminate: {
+ type: Boolean as PropType<boolean | null>,
+ default: null,
+ },
}),
emits: ['click', 'toggle'],
@@ -106,15 +110,15 @@... | packages/vant/src/checkbox/Checker.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(Checkbox): add indeterminate status | 12,216 | youzan/vant | 18,391 | TypeScript | wjw-gavin | |
date: currentMonth.date,
};
}
};
const scrollToDate = (targetDate: Date) => {
raf(() => {
months.value.some((month, index) => {
if (compareMonth(month, targetDate) === 0) {
if (bodyRef.value) {
monthRefs.value[index].scrollToDate(bodyRef... | No issues found. | date: currentMonth.date,
};
}
};
const scrollToDate = (targetDate: Date) => {
raf(() => {
months.value.some((month, index) => {
if (compareMonth(month, targetDate) === 0) {
if (bodyRef.value) {
monthRefs.value[index].scrollToDate(bodyRef... | @@ -176,8 +176,8 @@ export default defineComponent({
const bodyRef = ref<HTMLElement>();
- const subtitle = ref<{ text: string; date?: Date }>({
- text: '',
+ const subtitle = ref<{ textFn: () => string; date?: Date }>({
+ textFn: () => '',
date: undefined,
});
const currentDat... | packages/vant/src/calendar/Calendar.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(canendar): subtitle supports reactive | 12,425 | youzan/vant | 18,391 | TypeScript | cc-hearts | |
});
const swipe = wrapper.find('.van-swipe__track');
// should not emit input or close event when tapped
triggerDrag(swipe, 0, 0);
await later(250);
expect(wrapper.emitted('input')).toBeFalsy();
expect(wrapper.emitted('close')).toBeFalsy();
await wrapper.setProps({ show: false });
expect(wrapper.em... | No issues found. | });
const swipe = wrapper.find('.van-swipe__track');
// should not emit input or close event when tapped
triggerDrag(swipe, 0, 0);
await later(250);
expect(wrapper.emitted('input')).toBeFalsy();
expect(wrapper.emitted('close')).toBeFalsy();
await wrapper.setProps({ show: false });
expect(wrapper.em... | @@ -8,6 +8,7 @@ import {
import { LONG_PRESS_START_TIME } from '../../utils';
import ImagePreview from '../ImagePreview';
import { images, triggerZoom } from './shared';
+import type { ImagePreviewInstance } from '../types';
test('should swipe to current index after calling the swipeTo method', async () => {
c... | packages/vant/src/image-preview/test/index.spec.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(ImagePreview): expose resetScale method | 12,426 | youzan/vant | 18,391 | TypeScript | inottn | |
<Col span="5">5</Col>
<Col span="4">4</Col>
<Col span="3">3</Col>
<Col span="2">2</Col>
</Row>
),
});
expect(wrapper.html()).toMatchSnapshot();
});
test('should render vertical space when gutter is an array and provide the second parameter', async () => {
const wrapper ... | No issues found. | <Col span="5">5</Col>
<Col span="4">4</Col>
<Col span="3">3</Col>
<Col span="2">2</Col>
</Row>
),
});
expect(wrapper.html()).toMatchSnapshot();
});
test('should render vertical space when gutter is an array and provide the second parameter', async () => {
const wrapper ... | @@ -1,6 +1,7 @@
import { Col } from '..';
import { Row } from '../../row';
import { mount } from '../../../test';
+import { nextTick } from 'vue';
test('should render Col correctly', () => {
const wrapper = mount(Col, {
@@ -41,3 +42,77 @@ test('should render gutter correctly', () => {
expect(wrapper.html(... | packages/vant/src/col/test/index.spec.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(Row): gutter support vertical space | 12,439 | youzan/vant | 18,391 | TypeScript | cc-hearts | |
await later(300);
expect(wrapper.emitted('close')).toBeTruthy();
});
test('should close when overlay is clicked', async () => {
const wrapper = mount(ImagePreview, {
props: {
images,
show: true,
'onUpdate:show': (show) => {
wrapper.setProps({ show });
},
},
});
const ... | No issues found. | await later(300);
expect(wrapper.emitted('close')).toBeTruthy();
});
test('should close when overlay is clicked', async () => {
const wrapper = mount(ImagePreview, {
props: {
images,
show: true,
'onUpdate:show': (show) => {
wrapper.setProps({ show });
},
},
});
const ... | @@ -181,6 +181,25 @@ test('before close prop', async () => {
expect(wrapper.emitted('close')![0]).toBeTruthy();
});
+test('should close when image is clicked', async () => {
+ const wrapper = mount(ImagePreview, {
+ props: {
+ images,
+ show: true,
+ 'onUpdate:show': (show) => {
+ wrappe... | packages/vant/src/image-preview/test/index.spec.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(ImagePreview): add close-on-click-image prop | 12,566 | youzan/vant | 18,391 | TypeScript | inottn | |
const iconActions = computed<ActionSheetAction[]>(() => [
{ name: t('option1'), icon: 'cart-o' },
{ name: t('option2'), icon: 'shop-o' },
{ name: t('option3'), icon: 'star-o' },
]);
const statusActions = computed<ActionSheetAction[]>(() => [
{ name: t('coloredOption'), color: '#ee0a24' },
{ name: t('disable... | No issues found. |
const iconActions = computed<ActionSheetAction[]>(() => [
{ name: t('option1'), icon: 'cart-o' },
{ name: t('option2'), icon: 'shop-o' },
{ name: t('option3'), icon: 'star-o' },
]);
const statusActions = computed<ActionSheetAction[]>(() => [
{ name: t('coloredOption'), color: '#ee0a24' },
{ name: t('disable... | @@ -11,6 +11,7 @@ const t = useTranslate({
option2: '选项二',
option3: '选项三',
subname: '描述信息',
+ showIcon: '展示图标',
showCancel: '展示取消按钮',
buttonText: '弹出菜单',
customPanel: '自定义面板',
@@ -25,6 +26,7 @@ const t = useTranslate({
option2: 'Option 2',
option3: 'Option 3',
subname: 'D... | packages/vant/src/action-sheet/demo/index.vue | 0 | Vue | 1 | none | 16 | 51 | 51 | true | feat(ActionSheet): add icon support to the actions data | 12,671 | youzan/vant | 18,391 | TypeScript | wjw-gavin | |
show: true,
'onUpdate:show': (show) => {
wrapper.setProps({ show });
},
},
});
const swipe = wrapper.find('.van-swipe-item');
await triggerDrag(swipe, 0, 0);
await later(300);
expect(wrapper.emitted('close')).toBeTruthy();
});
test('should not close when image is clicked and c... | No issues found. | show: true,
'onUpdate:show': (show) => {
wrapper.setProps({ show });
},
},
});
const swipe = wrapper.find('.van-swipe-item');
await triggerDrag(swipe, 0, 0);
await later(300);
expect(wrapper.emitted('close')).toBeTruthy();
});
test('should not close when image is clicked and c... | @@ -403,6 +403,23 @@ test('should render image slot correctly 2', async () => {
expect(wrapper.html().includes('video')).toBeTruthy();
});
+test('should render image slot correctly 3', async () => {
+ const wrapper = mount(ImagePreview, {
+ props: {
+ show: true,
+ images,
+ },
+ slots: {
+ ... | packages/vant/src/image-preview/test/index.spec.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(image-preview): export onLoad and style for image slot | 12,740 | youzan/vant | 18,391 | TypeScript | chouchouji | |
import { withInstall } from '../utils';
import _TimePicker, { TimePickerProps } from './TimePicker';
export const TimePicker = withInstall(_TimePicker);
export default TimePicker;
export { timePickerProps } from './TimePicker';
export type { TimePickerProps };
export type { TimePickerColumnType, TimePickerInstance } f... | No issues found. | import { withInstall } from '../utils';
import _TimePicker, { TimePickerProps } from './TimePicker';
export const TimePicker = withInstall(_TimePicker);
export default TimePicker;
export { timePickerProps } from './TimePicker';
export type { TimePickerProps };
export type { TimePickerColumnType, TimePickerInstance } f... | @@ -5,7 +5,7 @@ export const TimePicker = withInstall(_TimePicker);
export default TimePicker;
export { timePickerProps } from './TimePicker';
export type { TimePickerProps };
-export type { TimePickerColumnType } from './TimePicker';
+export type { TimePickerColumnType, TimePickerInstance } from './TimePicker';
... | packages/vant/src/time-picker/index.ts | 0 | TypeScript | 1 | none | 16 | 15 | 15 | true | feat(TimePicker): support confirm and getSelectedTime methods | 12,761 | youzan/vant | 18,391 | TypeScript | bluesky335 | |
import { withInstall } from '../utils';
import _DatePicker, { DatePickerProps } from './DatePicker';
export const DatePicker = withInstall(_DatePicker);
export default DatePicker;
export { datePickerProps } from './DatePicker';
export type { DatePickerProps };
export type { DatePickerColumnType, DatePickerInstance } f... | No issues found. | import { withInstall } from '../utils';
import _DatePicker, { DatePickerProps } from './DatePicker';
export const DatePicker = withInstall(_DatePicker);
export default DatePicker;
export { datePickerProps } from './DatePicker';
export type { DatePickerProps };
export type { DatePickerColumnType, DatePickerInstance } f... | @@ -5,7 +5,7 @@ export const DatePicker = withInstall(_DatePicker);
export default DatePicker;
export { datePickerProps } from './DatePicker';
export type { DatePickerProps };
-export type { DatePickerColumnType } from './DatePicker';
+export type { DatePickerColumnType, DatePickerInstance } from './DatePicker';
... | packages/vant/src/date-picker/index.ts | 0 | TypeScript | 1 | none | 16 | 15 | 15 | true | feat(DatePicker): support confirm and getSelectedDate method | 12,762 | youzan/vant | 18,391 | TypeScript | bluesky335 | |
value,
children,
});
export function formatDataForCascade({
areaList,
columnsNum,
columnsPlaceholder: placeholder,
}: AreaProps) {
const {
city_list: city = {},
county_list: county = {},
province_list: province = {},
} = areaList;
const showCity = +columnsNum > 1;
const showCounty = +colu... | No issues found. | value,
children,
});
export function formatDataForCascade({
areaList,
columnsNum,
columnsPlaceholder: placeholder,
}: AreaProps) {
const {
city_list: city = {},
county_list: county = {},
province_list: province = {},
} = areaList;
const showCity = +columnsNum > 1;
const showCounty = +colu... | @@ -47,10 +47,10 @@ export function formatDataForCascade({
const getProvinceChildren = () => {
if (showCity) {
- return placeholder.length
+ return placeholder.length > 1
? [
makeOption(
- placeholder[0],
+ placeholder[1],
AREA_EMPTY_COD... | packages/vant/src/area/utils.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(area): columns-placeholder prop rendering error | 12,857 | youzan/vant | 18,391 | TypeScript | yipl95 | |
expect(wrapper.find('.van-key--delete').html()).toMatchSnapshot();
});
test('should render delete slot correctly when theme is custom', () => {
const wrapper = mount(NumberKeyboard, {
props: {
theme: 'custom',
},
slots: {
delete: () => 'Custom Delete Key',
},
});
expect(wrapper.fi... | No issues found. |
expect(wrapper.find('.van-key--delete').html()).toMatchSnapshot();
});
test('should render delete slot correctly when theme is custom', () => {
const wrapper = mount(NumberKeyboard, {
props: {
theme: 'custom',
},
slots: {
delete: () => 'Custom Delete Key',
},
});
expect(wrapper.fi... | @@ -105,6 +105,16 @@ test('should render extra-key slot correctly', () => {
expect(wrapper.findAll('.van-key')[9].html()).toMatchSnapshot();
});
+test('should render zero key correctly when extra-key prop is an empty array', () => {
+ const wrapper = mount(NumberKeyboard, {
+ props: {
+ theme: 'custom',
... | packages/vant/src/number-keyboard/test/index.spec.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(NumberKeyboard): lose the number 0 key in some configs | 12,972 | youzan/vant | 18,391 | TypeScript | Whbbit1999 | |
},
});
expect(wrapper.find('.van-field__label').html()).toMatchSnapshot();
});
test('should render extra slot correctly', () => {
const wrapper = mount(Field, {
slots: {
extra: () => 'Extra',
},
});
expect(wrapper.html()).toMatchSnapshot();
});
test('should change cell size when using si... | No issues found. | },
});
expect(wrapper.find('.van-field__label').html()).toMatchSnapshot();
});
test('should render extra slot correctly', () => {
const wrapper = mount(Field, {
slots: {
extra: () => 'Extra',
},
});
expect(wrapper.html()).toMatchSnapshot();
});
test('should change cell size when using si... | @@ -95,6 +95,34 @@ test('should format input value when type is digit', () => {
expect(wrapper.emitted('update:modelValue')[2][0]).toEqual('123');
});
+test('should limit input value based on min and max props', async () => {
+ const wrapper = mount(Field, {
+ props: {
+ type: 'number',
+ min: 2,
+ ... | packages/vant/src/field/test/index.spec.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat(Field): add min and max props | 13,068 | youzan/vant | 18,391 | TypeScript | tuskermanshu | |
test('row-height prop', async () => {
const wrapper = mount(Calendar, {
props: {
minDate,
maxDate,
poppable: false,
rowHeight: 50,
defaultDate: minDate,
lazyRender: false,
},
});
await later();
expect(wrapper.find('.van-calendar__day').style.height).toEqual('50px')... | No issues found. |
test('row-height prop', async () => {
const wrapper = mount(Calendar, {
props: {
minDate,
maxDate,
poppable: false,
rowHeight: 50,
defaultDate: minDate,
lazyRender: false,
},
});
await later();
expect(wrapper.find('.van-calendar__day').style.height).toEqual('50px')... | @@ -655,3 +655,19 @@ test('should render confirm-text slot correctly', async () => {
expect(wrapper.find('.van-calendar__confirm').html()).toMatchSnapshot();
});
+
+test('the defaultDate length of 1 should be handled correctly', async () => {
+ const wrapper = mount(Calendar, {
+ props: {
+ poppable: fal... | packages/vant/src/calendar/test/index.spec.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(Calendar): fix getInitialDate function error | 13,075 | youzan/vant | 18,391 | TypeScript | pany-ang | |
index >= visibleRange[0] - 1 && index <= visibleRange[1] + 1;
monthRefs.value[index].setVisible(visible);
});
/* istanbul ignore else */
if (currentMonth) {
currentMonthRef.value = currentMonth;
}
};
const scrollToDate = (targetDate: Date) => {
if (canSw... | No issues found. | index >= visibleRange[0] - 1 && index <= visibleRange[1] + 1;
monthRefs.value[index].setVisible(visible);
});
/* istanbul ignore else */
if (currentMonth) {
currentMonthRef.value = currentMonth;
}
};
const scrollToDate = (targetDate: Date) => {
if (canSw... | @@ -518,7 +518,12 @@ export default defineComponent({
const showMonthTitle = index !== 0 || !props.showSubtitle;
return (
<CalendarMonth
- v-slots={pick(slots, ['top-info', 'bottom-info', 'month-title'])}
+ v-slots={pick(slots, [
+ 'top-info',
+ 'bottom-inf... | packages/vant/src/calendar/Calendar.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(Calendar): support `text` slot | 13,127 | youzan/vant | 18,391 | TypeScript | yuyinws | |
selectedValues.value = newValues;
}
};
const getEventParams = () => ({
selectedValues: selectedValues.value.slice(0),
selectedOptions: selectedOptions.value,
selectedIndexes: selectedIndexes.value,
});
const onChange = (value: Numeric, columnIndex: number) => {
se... | No issues found. | selectedValues.value = newValues;
}
};
const getEventParams = () => ({
selectedValues: selectedValues.value.slice(0),
selectedOptions: selectedOptions.value,
selectedIndexes: selectedIndexes.value,
});
const onChange = (value: Numeric, columnIndex: number) => {
se... | @@ -189,6 +189,7 @@ export default defineComponent({
// wait nextTick to ensure the model value is update to date
// when confirm event is emitted
nextTick(() => {
+ const params = getEventParams();
emit('confirm', params);
});
| packages/vant/src/picker/Picker.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(Picker): ensure that the confirm event params are up to date | 13,381 | youzan/vant | 18,391 | TypeScript | refinist | |
cmd += self._configuration_args()
cmd += ['--', info_dict['url']]
return cmd
class Aria2cFD(ExternalFD):
AVAILABLE_OPT = '-v'
def _make_cmd(self, tmpfilename, info_dict):
cmd = [self.exe, '-c']
# cmd += self._configuration_args([
# '--min-split-size', '1M', ... | Note that if user provides `--external-downloader-args`, these will be overwritten with them. So ensure that these are all non-essential options. You might want to move `--download-result` and `--uri-selector` elsewhere |
# curl writes the progress to stderr so don't capture it.
p = subprocess.Popen(cmd)
process_communicate_or_kill(p)
return p.returncode
class AxelFD(ExternalFD):
AVAILABLE_OPT = '-V'
def _make_cmd(self, tmpfilename, info_dict):
cmd = [self.exe, '-o', tmpfilename]
... | @@ -189,22 +202,85 @@ class Aria2cFD(ExternalFD):
def _make_cmd(self, tmpfilename, info_dict):
cmd = [self.exe, '-c']
- cmd += self._configuration_args([
- '--min-split-size', '1M', '--max-connection-per-server', '4'])
- dn = os.path.dirname(tmpfilename)
- if dn:
- ... | youtube_dlc/downloader/external.py | 26 | Python | 0.643 | suggestion | 219 | 51 | 51 | false | Aria2c support for MPEG-DASH and HLS | 55 | yt-dlp/yt-dlp | 132,642 | Python | pukkandan | shirt-dev |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.