index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
25,359 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/openai_proxy_test.py | 60,61 | 56,109 | test_determine_openai_engine | TestOpenAIProxyDetermineOpenaiEngine | 61,109 | 61,109 | class TestOpenAIProxyDetermineOpenaiEngine(unittest.TestCase):
def setUp(self):
self.openai_proxy = OpenAIProxy()
def test_determine_openai_engine(self):
FILL_FUNC_BODY | class TestOpenAIProxyDetermineOpenaiEngine(unittest.TestCase):
def setUp(self):
self.openai_proxy = OpenAIProxy()
def test_determine_openai_engine(self):
FILL_FUNC_BODY | self.assertEqual(
self.openai_proxy.determine_openai_engine("gpt-3.5-turbo-16k"),
OPENAI_API_ENGINE_GPT35,
)
self.assertEqual(self.openai_proxy.determine_openai_engine("other"), None)
# class TestOpenAIProxy(unittest.TestCase):
# @pytest.mark.skip("Breaks")
# @p... | self.assertEqual(
self.openai_proxy.determine_openai_engine("gpt-3.5-turbo-16k"),
OPENAI_API_ENGINE_GPT35,
)
self.assertEqual(self.openai_proxy.determine_openai_engine("other"), None)
# class TestOpenAIProxy(unittest.TestCase):
# @pytest.mark.skip("Breaks")
# @p... | 152 | 66 | 642 | 708 | import unittest
from unittest.mock import MagicMock, PropertyMock, patch
from sweepai.config.server import OPENAI_API_ENGINE_GPT35
from sweepai.utils.openai_proxy import OpenAIProxy
class TestOpenAIProxyCallOpenai(unittest.TestCase):
@unittest.skip("Breaks")
def setUp(self):
self.proxy = OpenAIProxy... | import unittest
from unittest.mock import MagicMock, PropertyMock, patch
from sweepai.config.server import OPENAI_API_ENGINE_GPT35
from sweepai.utils.openai_proxy import OpenAIProxy
class TestOpenAIProxyCallOpenai(unittest.TestCase):
@unittest.skip("Breaks")
def setUp(self):
self.proxy = OpenAIProxy... |
25,360 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/patch_utils.py | 6,7 | 1,49 | apply_patch | 11,41 | 7,41 | import re
_hdr_pat = re.compile("^@@ -(\d+),?(\d+)? \+(\d+),?(\d+)? @@$")
def apply_patch(s, patch, revert=False):
FILL_FUNC_BODYif __name__ == "__main__":
patch_output = """"""
original_file_path = ""
original_content = open(original_file_path).read()
patched_content = apply_patch(original_content... | import re
_hdr_pat = re.compile("^@@ -(\d+),?(\d+)? \+(\d+),?(\d+)? @@$")
def apply_patch(s, patch, revert=False):
"""
Apply unified diff patch to string s to recover newer string.
If revert is True, treat s as the newer string, recover older string.
"""
FILL_FUNC_BODYif __name__ == "__main__":
p... | s = s.splitlines(True)
p = patch.splitlines(True)
t = ""
i = sl = 0
(midx, sign) = (1, "+") if not revert else (3, "-")
while i < len(p) and p[i].startswith(("---", "+++")):
i += 1 # skip header lines
while i < len(p):
m = _hdr_pat.match(p[i])
if not m:
r... | """
Apply unified diff patch to string s to recover newer string.
If revert is True, treat s as the newer string, recover older string.
"""
s = s.splitlines(True)
p = patch.splitlines(True)
t = ""
i = sl = 0
(midx, sign) = (1, "+") if not revert else (3, "-")
while i < len(p) and... | 135 | 183 | 374 | 557 | import re
_hdr_pat = re.compile("^@@ -(\d+),?(\d+)? \+(\d+),?(\d+)? @@$")
def apply_patch(s, patch, revert=False):
FILL_FUNC_BODYif __name__ == "__main__":
patch_output = """"""
original_file_path = ""
original_content = open(original_file_path).read()
patched_content = apply_patch(original_content... | import re
_hdr_pat = re.compile("^@@ -(\d+),?(\d+)? \+(\d+),?(\d+)? @@$")
def apply_patch(s, patch, revert=False):
"""
Apply unified diff patch to string s to recover newer string.
If revert is True, treat s as the newer string, recover older string.
"""
FILL_FUNC_BODYif __name__ == "__main__":
p... | |
25,362 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/previous_diff_utils.py | 117,119 | 111,121 | xml | Commit | 119,121 | 119,121 | @dataclass
class Commit:
sha: str
message: str
diff: str = field(repr=False)
@property
def xml(self):
FILL_FUNC_BODY | @dataclass
class Commit:
sha: str
message: str
diff: str = field(repr=False)
@property
def xml(self):
FILL_FUNC_BODY | return f"<commit>\n<commit_sha>{self.sha}</commit_sha>\n<commit_message>\n{self.message}\n</commit_message>\n<source>\n{self.diff}\n</source>\n</commit>"
| return f"<commit>\n<commit_sha>{self.sha}</commit_sha>\n<commit_message>\n{self.message}\n</commit_message>\n<source>\n{self.diff}\n</source>\n</commit>"
| 2 | 54 | 74 | 128 | import re
import numpy as np
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
from sweepai.core.vector_db import multi_get_query_texts_similarity
# from sweepai.logn.cache import file_cache
from sweepai.utils.cohere_utils import cohere_rerank_call
from dataclasses import field, dataclass... | import re
import numpy as np
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
from sweepai.core.vector_db import multi_get_query_texts_similarity
# from sweepai.logn.cache import file_cache
from sweepai.utils.cohere_utils import cohere_rerank_call
from dataclasses import field, dataclass... |
25,364 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/progress.py | 53,60 | 44,102 | from_ids | AssistantConversation | 60,85 | 60,85 | class AssistantConversation(BaseModel):
model_config = ConfigDict(use_enum_values=True, validate_default=True)
messages: list[AssistantAPIMessage] = []
is_active: bool = True
status: AssistantStatus = "in_progress"
assistant_id: str = ""
run_id: str = ""
thread_id: str = ""
@classmethod... | class AssistantConversation(BaseModel):
model_config = ConfigDict(use_enum_values=True, validate_default=True)
messages: list[AssistantAPIMessage] = []
is_active: bool = True
status: AssistantStatus = "in_progress"
assistant_id: str = ""
run_id: str = ""
thread_id: str = ""
@classmethod... | client = OpenAI(api_key=OPENAI_API_KEY)
try:
assistant = client.beta.assistants.retrieve(
assistant_id=assistant_id, timeout=1.5
)
run = client.beta.threads.runs.retrieve(
run_id=run_id, thread_id=thread_id, timeout=1.5
)
... | client = OpenAI(api_key=OPENAI_API_KEY)
try:
assistant = client.beta.assistants.retrieve(
assistant_id=assistant_id, timeout=1.5
)
run = client.beta.threads.runs.retrieve(
run_id=run_id, thread_id=thread_id, timeout=1.5
)
... | 43 | 307 | 260 | 567 | from __future__ import annotations
import time
from enum import Enum
from threading import Thread
from loguru import logger
from openai import OpenAI
from pydantic import BaseModel, ConfigDict, Field
from sweepai.config.server import MONGODB_URI, OPENAI_API_KEY
from sweepai.core.entities import FileChangeRequest, Sn... | from __future__ import annotations
import time
from enum import Enum
from threading import Thread
from loguru import logger
from openai import OpenAI
from pydantic import BaseModel, ConfigDict, Field
from sweepai.config.server import MONGODB_URI, OPENAI_API_KEY
from sweepai.core.entities import FileChangeRequest, Sn... |
25,365 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/progress.py | 224,225 | 165,265 | wait | TicketProgress | 225,265 | 225,265 | class TicketProgress(BaseModel):
model_config = ConfigDict(use_enum_values=True, validate_default=True)
tracking_id: str
username: str = ""
context: TicketContext = TicketContext()
status: TicketProgressStatus = TicketProgressStatus.SEARCHING
search_progress: SearchProgress = SearchProgress()
... | class TicketProgress(BaseModel):
model_config = ConfigDict(use_enum_values=True, validate_default=True)
tracking_id: str
username: str = ""
context: TicketContext = TicketContext()
status: TicketProgressStatus = TicketProgressStatus.SEARCHING
search_progress: SearchProgress = SearchProgress()
... | if MONGODB_URI is None:
return
try:
# check if user set breakpoints
current_ticket_progress = TicketProgress.load(self.tracking_id)
current_ticket_progress.user_state = current_ticket_progress.user_state
current_ticket_progress.user_state.state... | if MONGODB_URI is None:
return
try:
# check if user set breakpoints
current_ticket_progress = TicketProgress.load(self.tracking_id)
current_ticket_progress.user_state = current_ticket_progress.user_state
current_ticket_progress.user_state.state... | 119 | 654 | 542 | 1,196 | from __future__ import annotations
import time
from enum import Enum
from threading import Thread
from loguru import logger
from openai import OpenAI
from pydantic import BaseModel, ConfigDict, Field
from sweepai.config.server import MONGODB_URI, OPENAI_API_KEY
from sweepai.core.entities import FileChangeRequest, Sn... | from __future__ import annotations
import time
from enum import Enum
from threading import Thread
from loguru import logger
from openai import OpenAI
from pydantic import BaseModel, ConfigDict, Field
from sweepai.config.server import MONGODB_URI, OPENAI_API_KEY
from sweepai.core.entities import FileChangeRequest, Sn... |
25,366 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/progress_test.py | 6,8 | 1,14 | test_create_index | 8,14 | 8,14 | from unittest.mock import patch
from sweepai.utils.progress import create_index
@patch("sweepai.utils.progress.global_mongo_client")
def test_create_index(mock_mongo_client):
FILL_FUNC_BODY | from unittest.mock import patch
from sweepai.utils.progress import create_index
@patch("sweepai.utils.progress.global_mongo_client")
def test_create_index(mock_mongo_client):
FILL_FUNC_BODY | mock_db = mock_mongo_client.return_value
mock_collection = mock_db.__getitem__.return_value
create_index()
mock_collection.create_index.assert_called_once_with("tracking_id", unique=True)
| mock_db = mock_mongo_client.return_value
mock_collection = mock_db.__getitem__.return_value
create_index()
mock_collection.create_index.assert_called_once_with("tracking_id", unique=True)
| 9 | 68 | 74 | 142 | from unittest.mock import patch
from sweepai.utils.progress import create_index
@patch("sweepai.utils.progress.global_mongo_client")
def test_create_index(mock_mongo_client):
FILL_FUNC_BODY | from unittest.mock import patch
from sweepai.utils.progress import create_index
@patch("sweepai.utils.progress.global_mongo_client")
def test_create_index(mock_mongo_client):
FILL_FUNC_BODY | |
25,368 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/prompt_constructor.py | 201,202 | 154,215 | get_issue_metadata | HumanMessageCommentPrompt | 202,215 | 202,215 | class HumanMessageCommentPrompt(HumanMessagePrompt):
comment: str
diffs: list
relevant_docs: str | None
pr_file_path: str | None
pr_chunk: str | None
original_line: str | None
def format_diffs(self):
formatted_diffs = []
for file_name, file_patch in self.diffs:
f... | class HumanMessageCommentPrompt(HumanMessagePrompt):
comment: str
diffs: list
relevant_docs: str | None
pr_file_path: str | None
pr_chunk: str | None
original_line: str | None
def format_diffs(self):
formatted_diffs = []
for file_name, file_patch in self.diffs:
f... | self.summary = (
self.summary if not self.summary.strip().endswith("_No response_") else ""
)
issue_description = (
f"\nIssue Description: {self.summary}" if self.summary.strip() else ""
)
return f"""# Repo & Issue Metadata
Repo: {self.repo_name}: {self.re... | self.summary = (
self.summary if not self.summary.strip().endswith("_No response_") else ""
)
issue_description = (
f"\nIssue Description: {self.summary}" if self.summary.strip() else ""
)
return f"""# Repo & Issue Metadata
Repo: {self.repo_name}: {self.re... | 47 | 467 | 150 | 617 | from pydantic import BaseModel
from sweepai.core.prompts import (
diff_section_prompt,
final_review_prompt,
human_message_prompt,
human_message_prompt_comment,
)
class HumanMessagePrompt(BaseModel):
repo_name: str
title: str
summary: str
snippets: list
tree: str
repo_descripti... | from pydantic import BaseModel
from sweepai.core.prompts import (
diff_section_prompt,
final_review_prompt,
human_message_prompt,
human_message_prompt_comment,
)
class HumanMessagePrompt(BaseModel):
repo_name: str
title: str
summary: str
snippets: list
tree: str
repo_descripti... |
25,369 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/prompt_constructor.py | 218,219 | 215,223 | construct_prompt | HumanMessageFinalPRComment | 219,223 | 219,223 | class HumanMessageFinalPRComment(BaseModel):
summarization_replies: list
def construct_prompt(self):
FILL_FUNC_BODY | class HumanMessageFinalPRComment(BaseModel):
summarization_replies: list
def construct_prompt(self):
FILL_FUNC_BODY | final_review = final_review_prompt.format(
file_summaries="\n".join(self.summarization_replies)
)
return final_review
| final_review = final_review_prompt.format(
file_summaries="\n".join(self.summarization_replies)
)
return final_review
| 7 | 41 | 51 | 92 | from pydantic import BaseModel
from sweepai.core.prompts import (
diff_section_prompt,
final_review_prompt,
human_message_prompt,
human_message_prompt_comment,
)
class HumanMessagePrompt(BaseModel):
repo_name: str
title: str
summary: str
snippets: list
tree: str
repo_descripti... | from pydantic import BaseModel
from sweepai.core.prompts import (
diff_section_prompt,
final_review_prompt,
human_message_prompt,
human_message_prompt_comment,
)
class HumanMessagePrompt(BaseModel):
repo_name: str
title: str
summary: str
snippets: list
tree: str
repo_descripti... |
25,370 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/prompt_constructor.py | 87,88 | 11,145 | construct_prompt | HumanMessagePrompt | 88,122 | 88,122 | class HumanMessagePrompt(BaseModel):
repo_name: str
title: str
summary: str
snippets: list
tree: str
repo_description: str = ""
snippet_text: str = ""
commit_history: list = []
def delete_file(self, file_path):
# Remove the snippets from the main list
self.snippets =... | class HumanMessagePrompt(BaseModel):
repo_name: str
title: str
summary: str
snippets: list
tree: str
repo_description: str = ""
snippet_text: str = ""
commit_history: list = []
def delete_file(self, file_path):
# Remove the snippets from the main list
self.snippets =... | relevant_snippets = (
self.snippet_text
if self.snippet_text
else self.render_snippet_array(self.snippets, snippet_tag)
)
relevant_directories = (
self.get_relevant_directories(directory_tag)
if self.get_relevant_directories(directory_t... | relevant_snippets = (
self.snippet_text
if self.snippet_text
else self.render_snippet_array(self.snippets, snippet_tag)
)
relevant_directories = (
self.get_relevant_directories(directory_tag)
if self.get_relevant_directories(directory_t... | 57 | 1,085 | 347 | 1,432 | from pydantic import BaseModel
from sweepai.core.prompts import (
diff_section_prompt,
final_review_prompt,
human_message_prompt,
human_message_prompt_comment,
)
class HumanMessagePrompt(BaseModel):
repo_name: str
title: str
summary: str
snippets: list
tree: str
repo_descripti... | from pydantic import BaseModel
from sweepai.core.prompts import (
diff_section_prompt,
final_review_prompt,
human_message_prompt,
human_message_prompt_comment,
)
class HumanMessagePrompt(BaseModel):
repo_name: str
title: str
summary: str
snippets: list
tree: str
repo_descripti... |
25,371 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/regex_utils.py | 4,10 | 1,35 | xml_pattern | 10,21 | 10,21 | import re
def xml_pattern(
tags: str,
name: str | None = None,
add_newlines: bool = True,
**kwargs: dict[str, str],
) -> str:
FILL_FUNC_BODYdef search_xml(content: str, tag: str, **kwargs) -> str:
return re.search(xml_pattern(tag, name=tag, **kwargs), content, re.DOTALL).group(
tag
)
... | import re
def xml_pattern(
tags: str,
name: str | None = None,
add_newlines: bool = True,
**kwargs: dict[str, str],
) -> str:
FILL_FUNC_BODYdef search_xml(content: str, tag: str, **kwargs) -> str:
return re.search(xml_pattern(tag, name=tag, **kwargs), content, re.DOTALL).group(
tag
)
... | name = name or tags
new_lines = "\n" if add_newlines else ""
if kwargs:
kwargs_pattern = "\s+" + r"\s+".join(
rf"{key}=\"(?P<{value}>.*?)\"" for key, value in kwargs.items()
)
else:
kwargs_pattern = ""
return rf"<{tags}{kwargs_pattern}>{new_lines}(?P<{name}>.*?){n... | name = name or tags
new_lines = "\n" if add_newlines else ""
if kwargs:
kwargs_pattern = "\s+" + r"\s+".join(
rf"{key}=\"(?P<{value}>.*?)\"" for key, value in kwargs.items()
)
else:
kwargs_pattern = ""
return rf"<{tags}{kwargs_pattern}>{new_lines}(?P<{name}>.*?){n... | 32 | 209 | 153 | 362 | import re
def xml_pattern(
tags: str,
name: str | None = None,
add_newlines: bool = True,
**kwargs: dict[str, str],
) -> str:
FILL_FUNC_BODYdef search_xml(content: str, tag: str, **kwargs) -> str:
return re.search(xml_pattern(tag, name=tag, **kwargs), content, re.DOTALL).group(
tag
)
... | import re
def xml_pattern(
tags: str,
name: str | None = None,
add_newlines: bool = True,
**kwargs: dict[str, str],
) -> str:
FILL_FUNC_BODYdef search_xml(content: str, tag: str, **kwargs) -> str:
return re.search(xml_pattern(tag, name=tag, **kwargs), content, re.DOTALL).group(
tag
)
... | |
25,372 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/safe_pqueue.py | 22,23 | 5,33 | empty | SafePriorityQueue | 23,26 | 23,26 | class SafePriorityQueue:
def __init__(self):
self.q = queue.PriorityQueue()
self.lock = threading.Lock()
def put(self, priority: int, event):
try:
with self.lock:
self.q.put((priority, event))
self._invalidate_lower_priority(priority)
... | class SafePriorityQueue:
def __init__(self):
self.q = queue.PriorityQueue()
self.lock = threading.Lock()
def put(self, priority: int, event):
try:
with self.lock:
self.q.put((priority, event))
self._invalidate_lower_priority(priority)
... | with self.lock:
return self.q.empty()
| with self.lock:
return self.q.empty()
| 4 | 231 | 20 | 251 | import queue
import threading
class SafePriorityQueue:
def __init__(self):
self.q = queue.PriorityQueue()
self.lock = threading.Lock()
def put(self, priority: int, event):
try:
with self.lock:
self.q.put((priority, event))
self._invalidate_l... | import queue
import threading
class SafePriorityQueue:
def __init__(self):
self.q = queue.PriorityQueue()
self.lock = threading.Lock()
def put(self, priority: int, event):
try:
with self.lock:
self.q.put((priority, event))
self._invalidate_l... |
25,373 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/scorer.py | 41,42 | 1,59 | get_scores | 42,59 | 42,59 | from datetime import datetime
def compute_score(relative_file_path, git_repo):
commits = list(git_repo.iter_commits(paths=relative_file_path))
score_factor = get_factors(commits)
return score_factor
def get_factors(commits):
commit_count = len(commits) + 1
earliest_commit = commits[0].committed_... | from datetime import datetime
def compute_score(relative_file_path, git_repo):
commits = list(git_repo.iter_commits(paths=relative_file_path))
score_factor = get_factors(commits)
return score_factor
def get_factors(commits):
commit_count = len(commits) + 1
earliest_commit = commits[0].committed_... | # add all of the arrays together
line_count_scores = [x[0] for x in score_factors]
commit_count_scores = [x[1] for x in score_factors]
days_since_last_modified_scores = [x[2] for x in score_factors]
line_count_scores = convert_to_percentiles(line_count_scores, 1)
commit_count_scores = convert_to... | # add all of the arrays together
line_count_scores = [x[0] for x in score_factors]
commit_count_scores = [x[1] for x in score_factors]
days_since_last_modified_scores = [x[2] for x in score_factors]
line_count_scores = convert_to_percentiles(line_count_scores, 1)
commit_count_scores = convert_to... | 67 | 412 | 291 | 703 | from datetime import datetime
def compute_score(relative_file_path, git_repo):
commits = list(git_repo.iter_commits(paths=relative_file_path))
score_factor = get_factors(commits)
return score_factor
def get_factors(commits):
commit_count = len(commits) + 1
earliest_commit = commits[0].committed_... | from datetime import datetime
def compute_score(relative_file_path, git_repo):
commits = list(git_repo.iter_commits(paths=relative_file_path))
score_factor = get_factors(commits)
return score_factor
def get_factors(commits):
commit_count = len(commits) + 1
earliest_commit = commits[0].committed_... | |
25,374 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/scorer_test.py | 4,5 | 1,24 | test_days_since_last_modified_scores | 5,15 | 5,15 | from sweepai.utils.scorer import get_scores
def test_days_since_last_modified_scores():
FILL_FUNC_BODYdef test_commit_count_effect_on_scores():
# Given: Two file score factors with different commit counts but same modified days
factors_commit_count = [(1, 10, 1), (1, 20, 1)]
# When: We calculate scores
... | from sweepai.utils.scorer import get_scores
def test_days_since_last_modified_scores():
FILL_FUNC_BODYdef test_commit_count_effect_on_scores():
# Given: Two file score factors with different commit counts but same modified days
factors_commit_count = [(1, 10, 1), (1, 20, 1)]
# When: We calculate scores
... | # Given: Two file score factors
factors_recent_first = [(1, 10, 1), (1, 10, 30)]
# When: We calculate scores
scores_recent_first = get_scores(factors_recent_first)
# Then: Verify the recent modification has a higher score
assert scores_recent_first[0] > scores_recent_first[1]
| # Given: Two file score factors
factors_recent_first = [(1, 10, 1), (1, 10, 30)]
# When: We calculate scores
scores_recent_first = get_scores(factors_recent_first)
# Then: Verify the recent modification has a higher score
assert scores_recent_first[0] > scores_recent_first[1]
| 36 | 168 | 120 | 288 | from sweepai.utils.scorer import get_scores
def test_days_since_last_modified_scores():
FILL_FUNC_BODYdef test_commit_count_effect_on_scores():
# Given: Two file score factors with different commit counts but same modified days
factors_commit_count = [(1, 10, 1), (1, 20, 1)]
# When: We calculate scores
... | from sweepai.utils.scorer import get_scores
def test_days_since_last_modified_scores():
FILL_FUNC_BODYdef test_commit_count_effect_on_scores():
# Given: Two file score factors with different commit counts but same modified days
factors_commit_count = [(1, 10, 1), (1, 20, 1)]
# When: We calculate scores
... | |
25,375 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/search_and_replace_test.py | 31,32 | 15,60 | test_score_multiline | TestSearchAndReplace | 32,38 | 32,38 | class TestSearchAndReplace(unittest.TestCase):
def test_score_line(self):
self.assertEqual(score_line("abc", "abc"), 100)
def test_match_without_whitespace(self):
self.assertTrue(match_without_whitespace("abc", "abc"))
self.assertTrue(match_without_whitespace(" abc", "abc"))
sel... | class TestSearchAndReplace(unittest.TestCase):
def test_score_line(self):
self.assertEqual(score_line("abc", "abc"), 100)
def test_match_without_whitespace(self):
self.assertTrue(match_without_whitespace("abc", "abc"))
self.assertTrue(match_without_whitespace(" abc", "abc"))
sel... | self.assertEqual(score_multiline(["abc"], ["abc"]), 100)
self.assertEqual(score_multiline(["abc", "def"], ["abc", "def"]), 100)
self.assertEqual(
score_multiline(["abc", "...", "def"], ["abc", "ghi", "def"]), 100
)
| self.assertEqual(score_multiline(["abc"], ["abc"]), 100)
self.assertEqual(score_multiline(["abc", "def"], ["abc", "def"]), 100)
self.assertEqual(
score_multiline(["abc", "...", "def"], ["abc", "ghi", "def"]), 100
)
| 17 | 575 | 102 | 677 | import unittest
from sweepai.utils.search_and_replace import (
Match,
find_best_match,
get_max_indent,
line_cost,
match_without_whitespace,
score_line,
score_multiline,
split_ellipses,
)
class TestSearchAndReplace(unittest.TestCase):
def test_score_line(self):
self.assertE... | import unittest
from sweepai.utils.search_and_replace import (
Match,
find_best_match,
get_max_indent,
line_cost,
match_without_whitespace,
score_line,
score_multiline,
split_ellipses,
)
class TestSearchAndReplace(unittest.TestCase):
def test_score_line(self):
self.assertE... |
25,376 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/slack_utils.py | 21,22 | 1,52 | add_slack_context | 22,48 | 22,48 | import re
from loguru import logger
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from sweepai.config.server import SLACK_API_KEY
def get_thread_by_thread_ts(client: WebClient, channel_id: int, thread_ts: int):
response = client.conversations_replies(
channel=channel_id,
... | import re
from loguru import logger
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from sweepai.config.server import SLACK_API_KEY
def get_thread_by_thread_ts(client: WebClient, channel_id: int, thread_ts: int):
response = client.conversations_replies(
channel=channel_id,
... | result = ""
if not SLACK_API_KEY:
return result
slack_link_match = re.search(r'(https://[\w-]+\.slack\.com/archives/\w+/p\d+)', summary)
if not slack_link_match:
return result
slack_link = slack_link_match.group(1)
slack_client = WebClient(token=SLACK_API_KEY)
try:
# ... | result = ""
if not SLACK_API_KEY:
return result
slack_link_match = re.search(r'(https://[\w-]+\.slack\.com/archives/\w+/p\d+)', summary)
if not slack_link_match:
return result
slack_link = slack_link_match.group(1)
slack_client = WebClient(token=SLACK_API_KEY)
try:
# ... | 118 | 212 | 459 | 671 | import re
from loguru import logger
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from sweepai.config.server import SLACK_API_KEY
def get_thread_by_thread_ts(client: WebClient, channel_id: int, thread_ts: int):
response = client.conversations_replies(
channel=channel_id,
... | import re
from loguru import logger
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from sweepai.config.server import SLACK_API_KEY
def get_thread_by_thread_ts(client: WebClient, channel_id: int, thread_ts: int):
response = client.conversations_replies(
channel=channel_id,
... | |
25,377 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/str_utils.py | 127,128 | 1,147 | to_branch_name | 128,133 | 128,133 | import hashlib
import os
import re
import time
from sweepai.config.server import PROGRESS_BASE_URL
UPDATES_MESSAGE = f"""\
<details>
<summary><b>🎉 Latest improvements to Sweep:</b></summary>
<ul>
<li>New <a href="{PROGRESS_BASE_URL}">dashboard</a> launched for real-time tracking of Sweep issues, covering all stages ... | import hashlib
import os
import re
import time
from sweepai.config.server import PROGRESS_BASE_URL
UPDATES_MESSAGE = f"""\
<details>
<summary><b>🎉 Latest improvements to Sweep:</b></summary>
<ul>
<li>New <a href="{PROGRESS_BASE_URL}">dashboard</a> launched for real-time tracking of Sweep issues, covering all stages ... | branch_name = s.strip().lower().replace(" ", "_")
branch_name = re.sub(r"[^a-z0-9_]", "", branch_name)
return branch_name[:max_length]
| branch_name = s.strip().lower().replace(" ", "_")
branch_name = re.sub(r"[^a-z0-9_]", "", branch_name)
return branch_name[:max_length]
| 12 | 1,868 | 63 | 1,931 | import hashlib
import os
import re
import time
from sweepai.config.server import PROGRESS_BASE_URL
UPDATES_MESSAGE = f"""\
<details>
<summary><b>🎉 Latest improvements to Sweep:</b></summary>
<ul>
<li>New <a href="{PROGRESS_BASE_URL}">dashboard</a> launched for real-time tracking of Sweep issues, covering all stages ... | import hashlib
import os
import re
import time
from sweepai.config.server import PROGRESS_BASE_URL
UPDATES_MESSAGE = f"""\
<details>
<summary><b>🎉 Latest improvements to Sweep:</b></summary>
<ul>
<li>New <a href="{PROGRESS_BASE_URL}">dashboard</a> launched for real-time tracking of Sweep issues, covering all stages ... | |
25,379 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/user_settings.py | 27,31 | 22,91 | from_username | UserSettings | 31,65 | 31,65 | class UserSettings(BaseModel):
username: str
email: str = ""
do_email: bool = True
@classmethod
def from_username(
cls, username: str, installation_id: int = None
) -> "UserSettings":
FILL_FUNC_BODY def get_message(self, completed: bool = False) -> str:
# This is a message di... | class UserSettings(BaseModel):
username: str
email: str = ""
do_email: bool = True
@classmethod
def from_username(
cls, username: str, installation_id: int = None
) -> "UserSettings":
FILL_FUNC_BODY def get_message(self, completed: bool = False) -> str:
# This is a message di... | if IS_SELF_HOSTED:
return cls(username=username, email="", do_email=False)
db = global_mongo_client["users"]
collection = db["users"]
doc = collection.find_one({"username": username})
if doc is None:
# Try get email from github
try:
... | if IS_SELF_HOSTED:
return cls(username=username, email="", do_email=False)
db = global_mongo_client["users"]
collection = db["users"]
doc = collection.find_one({"username": username})
if doc is None:
# Try get email from github
try:
... | 75 | 378 | 320 | 698 | import traceback
from loguru import logger
import resend
from github import Github
from github.AppAuthentication import AppAuthentication
from pydantic import BaseModel
from sweepai.config.server import (
GITHUB_APP_ID,
GITHUB_APP_PEM,
IS_SELF_HOSTED,
PROGRESS_BASE_URL,
RESEND_API_KEY,
)
from swee... | import traceback
from loguru import logger
import resend
from github import Github
from github.AppAuthentication import AppAuthentication
from pydantic import BaseModel
from sweepai.config.server import (
GITHUB_APP_ID,
GITHUB_APP_PEM,
IS_SELF_HOSTED,
PROGRESS_BASE_URL,
RESEND_API_KEY,
)
from swee... |
25,381 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/utils.py | 266,267 | 251,291 | is_worse_than_message | CheckResults | 267,291 | 267,291 | @dataclass
class CheckResults:
# Experimental feature, we'll see how this does.
# TODO: smart parsing
parse_error_message: str = ""
pylint: str = ""
eslint: str = ""
def is_worse_than(self, other: CheckResults) -> bool:
if self.parse_error_message:
return True
if oth... | @dataclass
class CheckResults:
# Experimental feature, we'll see how this does.
# TODO: smart parsing
parse_error_message: str = ""
pylint: str = ""
eslint: str = ""
def is_worse_than(self, other: CheckResults) -> bool:
if self.parse_error_message:
return True
if oth... | if other.parse_error_message:
# Previously failing
return ""
if self.parse_error_message:
return self.parse_error_message
if len(self.pylint.splitlines()) > len(other.pylint.splitlines()):
# return f"The code has the following pylint errors:\n\n{se... | if other.parse_error_message:
# Previously failing
return ""
if self.parse_error_message:
return self.parse_error_message
if len(self.pylint.splitlines()) > len(other.pylint.splitlines()):
# return f"The code has the following pylint errors:\n\n{se... | 98 | 199 | 397 | 596 | from __future__ import annotations
import ast
from io import StringIO
import os
import re
import subprocess
from tempfile import TemporaryDirectory
import tempfile
import traceback
from dataclasses import dataclass
from typing import Optional
import uuid
from pylint.lint import Run
from pylint.reporters.text import T... | from __future__ import annotations
import ast
from io import StringIO
import os
import re
import subprocess
from tempfile import TemporaryDirectory
import tempfile
import traceback
from dataclasses import dataclass
from typing import Optional
import uuid
from pylint.lint import Run
from pylint.reporters.text import T... |
25,382 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/utils.py | 67,68 | 52,87 | extract_lines | Span | 68,71 | 68,71 | @dataclass
class Span:
# Represents a slice of a string
start: int = 0
end: int = 0
def __post_init__(self):
# If end is None, set it to start
if self.end is None:
self.end = self.start
def extract(self, s: str) -> str:
# Grab the corresponding substring of stri... | @dataclass
class Span:
# Represents a slice of a string
start: int = 0
end: int = 0
def __post_init__(self):
# If end is None, set it to start
if self.end is None:
self.end = self.start
def extract(self, s: str) -> str:
# Grab the corresponding substring of stri... | # Grab the corresponding substring of string s by lines
return "\n".join(s.splitlines()[self.start : self.end + 1])
| # Grab the corresponding substring of string s by lines
return "\n".join(s.splitlines()[self.start : self.end + 1])
| 16 | 358 | 42 | 400 | from __future__ import annotations
import ast
from io import StringIO
import os
import re
import subprocess
from tempfile import TemporaryDirectory
import tempfile
import traceback
from dataclasses import dataclass
from typing import Optional
import uuid
from pylint.lint import Run
from pylint.reporters.text import T... | from __future__ import annotations
import ast
from io import StringIO
import os
import re
import subprocess
from tempfile import TemporaryDirectory
import tempfile
import traceback
from dataclasses import dataclass
from typing import Optional
import uuid
from pylint.lint import Run
from pylint.reporters.text import T... |
25,383 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/utils.py | 667,668 | 652,677 | count | Tiktoken | 668,670 | 668,670 | class Tiktoken:
def __init__(self):
openai_models = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-1106",
"gpt-4",
"gpt-4-32k",
"gpt-4-32k-0613",
"gpt-4-1106-preview",
"gpt-4-0125-preview",
]
self.openai_models = {
... | class Tiktoken:
def __init__(self):
openai_models = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-1106",
"gpt-4",
"gpt-4-32k",
"gpt-4-32k-0613",
"gpt-4-1106-preview",
"gpt-4-0125-preview",
]
self.openai_models = {
... | return len(self.openai_models[model].encode(text, disallowed_special=()))
| return len(self.openai_models[model].encode(text, disallowed_special=()))
| 3 | 285 | 27 | 312 | from __future__ import annotations
import ast
from io import StringIO
import os
import re
import subprocess
from tempfile import TemporaryDirectory
import tempfile
import traceback
from dataclasses import dataclass
from typing import Optional
import uuid
from pylint.lint import Run
from pylint.reporters.text import T... | from __future__ import annotations
import ast
from io import StringIO
import os
import re
import subprocess
from tempfile import TemporaryDirectory
import tempfile
import traceback
from dataclasses import dataclass
from typing import Optional
import uuid
from pylint.lint import Run
from pylint.reporters.text import T... |
25,384 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/utils_test.py | 6,15 | 1,18 | test_check_syntax | 15,18 | 15,18 | import pytest
from sweepai.utils.utils import check_syntax
@pytest.mark.parametrize(
"file_path, code, expected_validity, expected_message",
[
("file.tsx", "let x = 1;", True, ""),
("file.tsx", "let x = ;", False, "Invalid syntax found within or before the lines 0-0, displayed below:\nlet x =... | import pytest
from sweepai.utils.utils import check_syntax
@pytest.mark.parametrize(
"file_path, code, expected_validity, expected_message",
[
("file.tsx", "let x = 1;", True, ""),
("file.tsx", "let x = ;", False, "Invalid syntax found within or before the lines 0-0, displayed below:\nlet x =... | validity, message = check_syntax(file_path, code)
assert validity == expected_validity
assert message == expected_message
| validity, message = check_syntax(file_path, code)
assert validity == expected_validity
assert message == expected_message
| 13 | 166 | 37 | 203 | import pytest
from sweepai.utils.utils import check_syntax
@pytest.mark.parametrize(
"file_path, code, expected_validity, expected_message",
[
("file.tsx", "let x = 1;", True, ""),
("file.tsx", "let x = ;", False, "Invalid syntax found within or before the lines 0-0, displayed below:\nlet x =... | import pytest
from sweepai.utils.utils import check_syntax
@pytest.mark.parametrize(
"file_path, code, expected_validity, expected_message",
[
("file.tsx", "let x = 1;", True, ""),
("file.tsx", "let x = ;", False, "Invalid syntax found within or before the lines 0-0, displayed below:\nlet x =... | |
25,385 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/validate_license.py | 4,5 | 1,25 | validate_license | 5,23 | 5,23 | import requests
from sweepai.config.server import LICENSE_KEY
def validate_license():
FILL_FUNC_BODYif __name__ == "__main__":
assert validate_license()
| import requests
from sweepai.config.server import LICENSE_KEY
def validate_license():
FILL_FUNC_BODYif __name__ == "__main__":
assert validate_license()
| # Validate the license key
if LICENSE_KEY is None:
raise ValueError("No license key provided, please set the LICENSE_KEY environment variable or get a license key from https://deploy.sweep.dev.")
response = requests.post(
"https://api.keygen.sh/v1/accounts/sweep-dev/licenses/actions/validate... | # Validate the license key
if LICENSE_KEY is None:
raise ValueError("No license key provided, please set the LICENSE_KEY environment variable or get a license key from https://deploy.sweep.dev.")
response = requests.post(
"https://api.keygen.sh/v1/accounts/sweep-dev/licenses/actions/validate... | 91 | 52 | 286 | 338 | import requests
from sweepai.config.server import LICENSE_KEY
def validate_license():
FILL_FUNC_BODYif __name__ == "__main__":
assert validate_license()
| import requests
from sweepai.config.server import LICENSE_KEY
def validate_license():
FILL_FUNC_BODYif __name__ == "__main__":
assert validate_license()
| |
25,386 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/watch.py | 28,29 | 1,117 | pascal_to_snake | 29,32 | 29,32 | # from rich import Console
import datetime
import os
import pickle
import threading
import time
from itertools import chain, islice
from github import Github
from github.Event import Event
from github.IssueEvent import IssueEvent
from github.Repository import Repository
from rich import print
from sweepai.api import ... | # from rich import Console
import datetime
import os
import pickle
import threading
import time
from itertools import chain, islice
from github import Github
from github.Event import Event
from github.IssueEvent import IssueEvent
from github.Repository import Repository
from rich import print
from sweepai.api import ... | return "".join(["_" + i.lower() if i.isupper() else i for i in name]).lstrip("_")
| return "".join(["_" + i.lower() if i.isupper() else i for i in name]).lstrip("_")
| 12 | 1,187 | 38 | 1,225 | # from rich import Console
import datetime
import os
import pickle
import threading
import time
from itertools import chain, islice
from github import Github
from github.Event import Event
from github.IssueEvent import IssueEvent
from github.Repository import Repository
from rich import print
from sweepai.api import ... | # from rich import Console
import datetime
import os
import pickle
import threading
import time
from itertools import chain, islice
from github import Github
from github.Event import Event
from github.IssueEvent import IssueEvent
from github.Repository import Repository
from rich import print
from sweepai.api import ... | |
25,387 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/web/event_utils.py | 7,12 | 1,60 | fetch_issue_request | 12,60 | 12,60 |
from github import Github
from sweepai.utils.github_utils import get_github_client, get_installation_id
from sweepai.web.events import Account, Installation, IssueRequest
def fetch_issue_request(org_name: str,
repo_name: str,
issue_number: str,
... |
from github import Github
from sweepai.utils.github_utils import get_github_client, get_installation_id
from sweepai.web.events import Account, Installation, IssueRequest
def fetch_issue_request(org_name: str,
repo_name: str,
issue_number: str,
... |
print("Fetching installation ID...")
installation_id = get_installation_id(org_name)
print("Fetching access token...")
_token, g = get_github_client(installation_id)
g: Github = g
print("Fetching repo...")
issue = g.get_repo(f"{org_name}/{repo_name}").get_issue(int(issue_number))
i... |
print("Fetching installation ID...")
installation_id = get_installation_id(org_name)
print("Fetching access token...")
_token, g = get_github_client(installation_id)
g: Github = g
print("Fetching repo...")
issue = g.get_repo(f"{org_name}/{repo_name}").get_issue(int(issue_number))
i... | 63 | 111 | 467 | 578 |
from github import Github
from sweepai.utils.github_utils import get_github_client, get_installation_id
from sweepai.web.events import Account, Installation, IssueRequest
def fetch_issue_request(org_name: str,
repo_name: str,
issue_number: str,
... |
from github import Github
from sweepai.utils.github_utils import get_github_client, get_installation_id
from sweepai.web.events import Account, Installation, IssueRequest
def fetch_issue_request(org_name: str,
repo_name: str,
issue_number: str,
... | |
25,388 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/web/events.py | 9,11 | 6,14 | body_from | Changes | 11,14 | 11,14 | class Changes(BaseModel):
body: Dict[str, str]
@property
def body_from(self):
FILL_FUNC_BODY | class Changes(BaseModel):
body: Dict[str, str]
@property
def body_from(self):
FILL_FUNC_BODY | return self.body.get("from")
| return self.body.get("from")
| 2 | 43 | 16 | 59 | from typing import Any, Dict, Literal
from pydantic import BaseModel
class Changes(BaseModel):
body: Dict[str, str]
@property
def body_from(self):
FILL_FUNC_BODYclass Account(BaseModel):
id: int
login: str
type: str
class Installation(BaseModel):
id: Any | None = None
account: Acco... | from typing import Any, Dict, Literal
from pydantic import BaseModel
class Changes(BaseModel):
body: Dict[str, str]
@property
def body_from(self):
FILL_FUNC_BODYclass Account(BaseModel):
id: int
login: str
type: str
class Installation(BaseModel):
id: Any | None = None
account: Acco... |
25,389 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/web/events.py | 200,202 | 186,205 | run_id | CheckRun | 202,205 | 202,205 | class CheckRun(BaseModel):
class PullRequest(BaseModel):
number: int
class CheckSuite(BaseModel):
head_branch: str | None
conclusion: str
html_url: str
pull_requests: list[PullRequest]
completed_at: str
check_suite: CheckSuite
... | class CheckRun(BaseModel):
class PullRequest(BaseModel):
number: int
class CheckSuite(BaseModel):
head_branch: str | None
conclusion: str
html_url: str
pull_requests: list[PullRequest]
completed_at: str
check_suite: CheckSuite
... | # format is like https://github.com/ORG/REPO_NAME/actions/runs/RUN_ID/jobs/JOB_ID
return self.html_url.split("/")[-3]
| # format is like https://github.com/ORG/REPO_NAME/actions/runs/RUN_ID/jobs/JOB_ID
return self.html_url.split("/")[-3]
| 7 | 118 | 55 | 173 | from typing import Any, Dict, Literal
from pydantic import BaseModel
class Changes(BaseModel):
body: Dict[str, str]
@property
def body_from(self):
return self.body.get("from")
class Account(BaseModel):
id: int
login: str
type: str
class Installation(BaseModel):
id: Any | None... | from typing import Any, Dict, Literal
from pydantic import BaseModel
class Changes(BaseModel):
body: Dict[str, str]
@property
def body_from(self):
return self.body.get("from")
class Account(BaseModel):
id: int
login: str
type: str
class Installation(BaseModel):
id: Any | None... |
25,390 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/web/events.py | 200,202 | 185,218 | run_id | CheckRunCompleted | 202,205 | 202,205 | class CheckRunCompleted(BaseModel):
class CheckRun(BaseModel):
class PullRequest(BaseModel):
number: int
class CheckSuite(BaseModel):
head_branch: str | None
conclusion: str
html_url: str
pull_requests: list[PullRequest]
completed_at: str
... | class CheckRunCompleted(BaseModel):
class CheckRun(BaseModel):
class PullRequest(BaseModel):
number: int
class CheckSuite(BaseModel):
head_branch: str | None
conclusion: str
html_url: str
pull_requests: list[PullRequest]
completed_at: str
... | # format is like https://github.com/ORG/REPO_NAME/actions/runs/RUN_ID/jobs/JOB_ID
return self.html_url.split("/")[-3]
| # format is like https://github.com/ORG/REPO_NAME/actions/runs/RUN_ID/jobs/JOB_ID
return self.html_url.split("/")[-3]
| 7 | 195 | 55 | 250 | from typing import Any, Dict, Literal
from pydantic import BaseModel
class Changes(BaseModel):
body: Dict[str, str]
@property
def body_from(self):
return self.body.get("from")
class Account(BaseModel):
id: int
login: str
type: str
class Installation(BaseModel):
id: Any | None... | from typing import Any, Dict, Literal
from pydantic import BaseModel
class Changes(BaseModel):
body: Dict[str, str]
@property
def body_from(self):
return self.body.get("from")
class Account(BaseModel):
id: int
login: str
type: str
class Installation(BaseModel):
id: Any | None... |
25,391 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/web/health.py | 37,39 | 1,73 | health_check | 39,73 | 39,73 | import psutil
import redis
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from loguru import logger
from pymongo import MongoClient
from sweepai.config.server import IS_SELF_HOSTED, MONGODB_URI, REDIS_URL
app = FastAPI()
def check_sandbox_health() -> str:
return "UP"
def check_mongodb_... | import psutil
import redis
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from loguru import logger
from pymongo import MongoClient
from sweepai.config.server import IS_SELF_HOSTED, MONGODB_URI, REDIS_URL
app = FastAPI()
def check_sandbox_health() -> str:
return "UP"
def check_mongodb_... | sandbox_status = check_sandbox_health()
mongo_status = check_mongodb_health() if not IS_SELF_HOSTED else None
redis_status = check_redis_health()
cpu_usage = psutil.cpu_percent(interval=0.1)
memory_info = psutil.virtual_memory()
disk_usage = psutil.disk_usage("/")
network_traffic = psutil.n... | sandbox_status = check_sandbox_health()
mongo_status = check_mongodb_health() if not IS_SELF_HOSTED else None
redis_status = check_redis_health()
cpu_usage = psutil.cpu_percent(interval=0.1)
memory_info = psutil.virtual_memory()
disk_usage = psutil.disk_usage("/")
network_traffic = psutil.n... | 69 | 299 | 355 | 654 | import psutil
import redis
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from loguru import logger
from pymongo import MongoClient
from sweepai.config.server import IS_SELF_HOSTED, MONGODB_URI, REDIS_URL
app = FastAPI()
def check_sandbox_health() -> str:
return "UP"
def check_mongodb_... | import psutil
import redis
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from loguru import logger
from pymongo import MongoClient
from sweepai.config.server import IS_SELF_HOSTED, MONGODB_URI, REDIS_URL
app = FastAPI()
def check_sandbox_health() -> str:
return "UP"
def check_mongodb_... | |
25,392 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/web/health_test.py | 39,41 | 14,54 | test_check_redis_health | TestHealth | 41,49 | 41,49 | @unittest.skip("Fails")
class TestHealth(unittest.TestCase):
def setUp(self):
self.client = TestClient(app)
@patch("sweepai.health.requests.get")
def test_check_sandbox_health(self, mock_get):
mock_get.return_value.status_code = 200
response = check_sandbox_health()
self.ass... | @unittest.skip("Fails")
class TestHealth(unittest.TestCase):
def setUp(self):
self.client = TestClient(app)
@patch("sweepai.health.requests.get")
def test_check_sandbox_health(self, mock_get):
mock_get.return_value.status_code = 200
response = check_sandbox_health()
self.ass... | mock_redis.ping.return_value = True
response = check_redis_health()
self.assertEqual(response, "UP")
mock_redis.ping.side_effect = Exception()
response = check_redis_health()
self.assertEqual(response, "DOWN")
| mock_redis.ping.return_value = True
response = check_redis_health()
self.assertEqual(response, "UP")
mock_redis.ping.side_effect = Exception()
response = check_redis_health()
self.assertEqual(response, "DOWN")
| 16 | 383 | 84 | 467 | import unittest
from unittest.mock import patch
from fastapi.testclient import TestClient
from sweepai.web.health import (
app,
check_mongodb_health,
check_redis_health,
check_sandbox_health,
)
@unittest.skip("Fails")
class TestHealth(unittest.TestCase):
def setUp(self):
self.client = Te... | import unittest
from unittest.mock import patch
from fastapi.testclient import TestClient
from sweepai.web.health import (
app,
check_mongodb_health,
check_redis_health,
check_sandbox_health,
)
@unittest.skip("Fails")
class TestHealth(unittest.TestCase):
def setUp(self):
self.client = Te... |
25,598 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/setup.py | 73,74 | 56,94 | run | UploadCommand | 74,94 | 74,94 | class UploadCommand(Command):
"""Support setup.py upload."""
description = "Build and publish the package."
user_options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print("\033[1m{0}\033[0m".format(s))
def initialize_options(self):
pass
def fina... | class UploadCommand(Command):
"""Support setup.py upload."""
description = "Build and publish the package."
user_options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print("\033[1m{0}\033[0m".format(s))
def initialize_options(self):
pass
def fina... | try:
self.status("Removing previous builds…")
rmtree(os.path.join(here, "dist"))
except OSError:
pass
self.status("Building Source and Wheel (universal) distribution…")
os.system("{0} setup.py sdist bdist_wheel --universal".format(sys.executable))
... | try:
self.status("Removing previous builds…")
rmtree(os.path.join(here, "dist"))
except OSError:
pass
self.status("Building Source and Wheel (universal) distribution…")
os.system("{0} setup.py sdist bdist_wheel --universal".format(sys.executable))
... | 45 | 127 | 204 | 331 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ pipenv install twine --dev
import io
import os
import sys
from shutil import rmtree
from setuptools import Command, setup
# Package meta-data.
NAME = "yyets"
DESCRIPTION = "https://yyets.click/ wrap... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ pipenv install twine --dev
import io
import os
import sys
from shutil import rmtree
from setuptools import Command, setup
# Package meta-data.
NAME = "yyets"
DESCRIPTION = "https://yyets.click/ wrap... |
25,599 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyets/BagAndDrag/bag.py | 48,49 | 1,108 | login | 49,62 | 49,62 | #!/usr/local/bin/python3
# coding: utf-8
# BagAndDrag - bag.py
# 1/10/21 15:29
#
__author__ = "Benny <benny.think@gmail.com>"
import contextlib
import json
import logging
import os
import pickle
import sys
import time
import traceback
import pymysql
import requests
logging.basicConfig(level=logging.INFO, format='%... | #!/usr/local/bin/python3
# coding: utf-8
# BagAndDrag - bag.py
# 1/10/21 15:29
#
__author__ = "Benny <benny.think@gmail.com>"
import contextlib
import json
import logging
import os
import pickle
import sys
import time
import traceback
import pymysql
import requests
logging.basicConfig(level=logging.INFO, format='%... | data = {"account": USERNAME, "password": PASSWORD, "remember": 1}
logging.info("login in as %s", data)
r = requests.post(AJAX_LOGIN, data=data, headers={"User-Agent": ua})
resp = r.json()
if resp.get('status') == 1:
logging.info("Login success! %s", r.cookies)
save_cookies(r.cookies)... | data = {"account": USERNAME, "password": PASSWORD, "remember": 1}
logging.info("login in as %s", data)
r = requests.post(AJAX_LOGIN, data=data, headers={"User-Agent": ua})
resp = r.json()
if resp.get('status') == 1:
logging.info("Login success! %s", r.cookies)
save_cookies(r.cookies)... | 38 | 1,158 | 164 | 1,322 | #!/usr/local/bin/python3
# coding: utf-8
# BagAndDrag - bag.py
# 1/10/21 15:29
#
__author__ = "Benny <benny.think@gmail.com>"
import contextlib
import json
import logging
import os
import pickle
import sys
import time
import traceback
import pymysql
import requests
logging.basicConfig(level=logging.INFO, format='%... | #!/usr/local/bin/python3
# coding: utf-8
# BagAndDrag - bag.py
# 1/10/21 15:29
#
__author__ = "Benny <benny.think@gmail.com>"
import contextlib
import json
import logging
import os
import pickle
import sys
import time
import traceback
import pymysql
import requests
logging.basicConfig(level=logging.INFO, format='%... | |
25,600 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyets/BagAndDrag/cfkv.py | 54,55 | 1,89 | dump_index | 55,73 | 55,73 | #!/usr/local/bin/python3
# coding: utf-8
# BagAndDrag - cfkv.py
# 1/17/21 12:08
#
__author__ = "Benny <benny.think@gmail.com>"
import json
import os
import pymysql
con = pymysql.Connect(host="127.0.0.1", user="root", password="root", charset="utf8mb4", database="yyets",
cursorclass=pymysql.cu... | #!/usr/local/bin/python3
# coding: utf-8
# BagAndDrag - cfkv.py
# 1/17/21 12:08
#
__author__ = "Benny <benny.think@gmail.com>"
import json
import os
import pymysql
con = pymysql.Connect(host="127.0.0.1", user="root", password="root", charset="utf8mb4", database="yyets",
cursorclass=pymysql.cu... | cur = con.cursor()
indexes = {}
cur.execute("select name, id from resource")
data = cur.fetchall()
for datum in data:
name = datum["name"]
rid = datum["id"]
indexes[name] = rid
with open("kv/index.json", "w") as f:
write_data = [
{
"key... | cur = con.cursor()
indexes = {}
cur.execute("select name, id from resource")
data = cur.fetchall()
for datum in data:
name = datum["name"]
rid = datum["id"]
indexes[name] = rid
with open("kv/index.json", "w") as f:
write_data = [
{
"key... | 47 | 688 | 177 | 865 | #!/usr/local/bin/python3
# coding: utf-8
# BagAndDrag - cfkv.py
# 1/17/21 12:08
#
__author__ = "Benny <benny.think@gmail.com>"
import json
import os
import pymysql
con = pymysql.Connect(host="127.0.0.1", user="root", password="root", charset="utf8mb4", database="yyets",
cursorclass=pymysql.cu... | #!/usr/local/bin/python3
# coding: utf-8
# BagAndDrag - cfkv.py
# 1/17/21 12:08
#
__author__ = "Benny <benny.think@gmail.com>"
import json
import os
import pymysql
con = pymysql.Connect(host="127.0.0.1", user="root", password="root", charset="utf8mb4", database="yyets",
cursorclass=pymysql.cu... | |
25,601 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyets/BagAndDrag/convert_db.py | 76,77 | 1,103 | main | 77,98 | 77,98 | #!/usr/local/bin/python3
# coding: utf-8
# BagAndDrag - convert_db.py
# 1/12/21 18:24
#
__author__ = "Benny <benny.think@gmail.com>"
# convert to mongodb and con_sqlite
import json
import sqlite3
from typing import List
import pymongo
import pymysql
import tqdm
con_mysql = pymysql.Connect(host="127.0.0.1", user="... | #!/usr/local/bin/python3
# coding: utf-8
# BagAndDrag - convert_db.py
# 1/12/21 18:24
#
__author__ = "Benny <benny.think@gmail.com>"
# convert to mongodb and con_sqlite
import json
import sqlite3
from typing import List
import pymongo
import pymysql
import tqdm
con_mysql = pymysql.Connect(host="127.0.0.1", user="... | create_sqlite_database()
clear_mongodb()
mysql_cur = con_mysql.cursor()
mysql_cur.execute("select count(id) from resource")
count = mysql_cur.fetchall()[0]["count(id)"]
mysql_cur.execute("SELECT * FROM resource")
with tqdm.tqdm(total=count * 2) as pbar:
while True:
dat... | create_sqlite_database()
clear_mongodb()
mysql_cur = con_mysql.cursor()
mysql_cur.execute("select count(id) from resource")
count = mysql_cur.fetchall()[0]["count(id)"]
mysql_cur.execute("SELECT * FROM resource")
with tqdm.tqdm(total=count * 2) as pbar:
while True:
dat... | 35 | 617 | 191 | 808 | #!/usr/local/bin/python3
# coding: utf-8
# BagAndDrag - convert_db.py
# 1/12/21 18:24
#
__author__ = "Benny <benny.think@gmail.com>"
# convert to mongodb and con_sqlite
import json
import sqlite3
from typing import List
import pymongo
import pymysql
import tqdm
con_mysql = pymysql.Connect(host="127.0.0.1", user="... | #!/usr/local/bin/python3
# coding: utf-8
# BagAndDrag - convert_db.py
# 1/12/21 18:24
#
__author__ = "Benny <benny.think@gmail.com>"
# convert to mongodb and con_sqlite
import json
import sqlite3
from typing import List
import pymongo
import pymysql
import tqdm
con_mysql = pymysql.Connect(host="127.0.0.1", user="... | |
25,602 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyets/BagAndDrag/drag.py | 54,55 | 1,61 | main | 55,59 | 55,59 | #!/usr/local/bin/python3
# coding: utf-8
# BagAndDrag - drag.py
# 1/10/21 15:38
#
__author__ = "Benny <benny.think@gmail.com>"
import argparse
import logging
import time
import traceback
from concurrent.futures import ThreadPoolExecutor
import requests
from tqdm import tqdm
from bag import (API_DATA, SHARE_URL, in... | #!/usr/local/bin/python3
# coding: utf-8
# BagAndDrag - drag.py
# 1/10/21 15:38
#
__author__ = "Benny <benny.think@gmail.com>"
import argparse
import logging
import time
import traceback
from concurrent.futures import ThreadPoolExecutor
import requests
from tqdm import tqdm
from bag import (API_DATA, SHARE_URL, in... | total = args.e + 1 - args.s
list(tqdm(executor.map(get_api_json, range(args.s, args.e + 1)), total=total))
| total = args.e + 1 - args.s
list(tqdm(executor.map(get_api_json, range(args.s, args.e + 1)), total=total))
| 13 | 633 | 54 | 687 | #!/usr/local/bin/python3
# coding: utf-8
# BagAndDrag - drag.py
# 1/10/21 15:38
#
__author__ = "Benny <benny.think@gmail.com>"
import argparse
import logging
import time
import traceback
from concurrent.futures import ThreadPoolExecutor
import requests
from tqdm import tqdm
from bag import (API_DATA, SHARE_URL, in... | #!/usr/local/bin/python3
# coding: utf-8
# BagAndDrag - drag.py
# 1/10/21 15:38
#
__author__ = "Benny <benny.think@gmail.com>"
import argparse
import logging
import time
import traceback
from concurrent.futures import ThreadPoolExecutor
import requests
from tqdm import tqdm
from bag import (API_DATA, SHARE_URL, in... | |
25,603 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyets/BagAndDrag/zimuxia/convert_db.py | 51,52 | 1,65 | main | 52,61 | 52,61 | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - convert_db.py
# 2/5/21 13:46
#
__author__ = "Benny <benny.think@gmail.com>"
# convert to mongodb and con_sqlite
import pymongo
import pymysql
import tqdm
import json
from typing import List
con_mysql = pymysql.Connect(host="127.0.0.1", user="root", password="r... | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - convert_db.py
# 2/5/21 13:46
#
__author__ = "Benny <benny.think@gmail.com>"
# convert to mongodb and con_sqlite
import pymongo
import pymysql
import tqdm
import json
from typing import List
con_mysql = pymysql.Connect(host="127.0.0.1", user="root", password="r... | clear_mongodb()
clear_mysql()
with open("result.json") as f:
data = json.load(f)
# [{"url": "https://www.zimuxia.cn/portfolio/%e6%888b%e5%8f%8b", "name": "我家的女儿交不到男朋友", "data":""}]
mysql_insert(data)
mongodb_insert(data)
| clear_mongodb()
clear_mysql()
with open("result.json") as f:
data = json.load(f)
# [{"url": "https://www.zimuxia.cn/portfolio/%e6%888b%e5%8f%8b", "name": "我家的女儿交不到男朋友", "data":""}]
mysql_insert(data)
mongodb_insert(data)
| 17 | 438 | 120 | 558 | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - convert_db.py
# 2/5/21 13:46
#
__author__ = "Benny <benny.think@gmail.com>"
# convert to mongodb and con_sqlite
import pymongo
import pymysql
import tqdm
import json
from typing import List
con_mysql = pymysql.Connect(host="127.0.0.1", user="root", password="r... | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - convert_db.py
# 2/5/21 13:46
#
__author__ = "Benny <benny.think@gmail.com>"
# convert to mongodb and con_sqlite
import pymongo
import pymysql
import tqdm
import json
from typing import List
con_mysql = pymysql.Connect(host="127.0.0.1", user="root", password="r... | |
25,604 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyets/BagAndDrag/zimuxia/zimuxia.py | 30,31 | 1,58 | get_list | 31,38 | 31,38 | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - zimuxia.py
# 2/5/21 12:44
#
__author__ = "Benny <benny.think@gmail.com>"
import requests
import random
import time
import json
from bs4 import BeautifulSoup
from urllib.parse import quote, unquote
import tqdm
import logging
logging.basicConfig(level=logging.INFO... | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - zimuxia.py
# 2/5/21 12:44
#
__author__ = "Benny <benny.think@gmail.com>"
import requests
import random
import time
import json
from bs4 import BeautifulSoup
from urllib.parse import quote, unquote
import tqdm
import logging
logging.basicConfig(level=logging.INFO... | for index in tqdm.trange(1, 89):
time.sleep(random.random())
url = list_url.format(index)
list_html = s.get(url).text
get_episode(list_html)
| for index in tqdm.trange(1, 89):
time.sleep(random.random())
url = list_url.format(index)
list_html = s.get(url).text
get_episode(list_html)
| 13 | 550 | 73 | 623 | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - zimuxia.py
# 2/5/21 12:44
#
__author__ = "Benny <benny.think@gmail.com>"
import requests
import random
import time
import json
from bs4 import BeautifulSoup
from urllib.parse import quote, unquote
import tqdm
import logging
logging.basicConfig(level=logging.INFO... | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - zimuxia.py
# 2/5/21 12:44
#
__author__ = "Benny <benny.think@gmail.com>"
import requests
import random
import time
import json
from bs4 import BeautifulSoup
from urllib.parse import quote, unquote
import tqdm
import logging
logging.basicConfig(level=logging.INFO... | |
25,605 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsbot/utils.py | 22,23 | 1,63 | get_error_dump | 23,30 | 23,30 | # coding: utf-8
# YYeTsBot - utils.py
# 2019/8/15 20:27
__author__ = 'Benny <benny.think@gmail.com>'
import pathlib
import redis
from config import REDIS
r = redis.StrictRedis(host=REDIS, decode_responses=True)
cookie_file = pathlib.Path(__file__).parent / 'data' / 'cookies.dump'
def save_error_dump(uid, err: s... | # coding: utf-8
# YYeTsBot - utils.py
# 2019/8/15 20:27
__author__ = 'Benny <benny.think@gmail.com>'
import pathlib
import redis
from config import REDIS
r = redis.StrictRedis(host=REDIS, decode_responses=True)
cookie_file = pathlib.Path(__file__).parent / 'data' / 'cookies.dump'
def save_error_dump(uid, err: s... | err = r.get(uid)
r.delete(uid)
if not err:
err = ""
return err
| err = r.get(uid)
r.delete(uid)
if not err:
err = ""
return err
| 12 | 546 | 42 | 588 | # coding: utf-8
# YYeTsBot - utils.py
# 2019/8/15 20:27
__author__ = 'Benny <benny.think@gmail.com>'
import pathlib
import redis
from config import REDIS
r = redis.StrictRedis(host=REDIS, decode_responses=True)
cookie_file = pathlib.Path(__file__).parent / 'data' / 'cookies.dump'
def save_error_dump(uid, err: s... | # coding: utf-8
# YYeTsBot - utils.py
# 2019/8/15 20:27
__author__ = 'Benny <benny.think@gmail.com>'
import pathlib
import redis
from config import REDIS
r = redis.StrictRedis(host=REDIS, decode_responses=True)
cookie_file = pathlib.Path(__file__).parent / 'data' / 'cookies.dump'
def save_error_dump(uid, err: s... | |
25,607 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/commands/grafana_test_data.py | 18,19 | 1,46 | generate_date_series | 19,32 | 19,32 | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - grafana_test_data.py
# 3/14/21 18:25
#
__author__ = "Benny <benny.think@gmail.com>"
import random
from datetime import date, timedelta
from common import Mongo
col = Mongo().client["zimuzu"]["metrics"]
def generate_date_series(start: str, end: str) -> list:
F... | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - grafana_test_data.py
# 3/14/21 18:25
#
__author__ = "Benny <benny.think@gmail.com>"
import random
from datetime import date, timedelta
from common import Mongo
col = Mongo().client["zimuzu"]["metrics"]
def generate_date_series(start: str, end: str) -> list:
F... | start_int = [int(i) for i in start.split("-")]
end_int = [int(i) for i in end.split("-")]
sdate = date(*start_int) # start date
edate = date(*end_int) # end date
delta = edate - sdate # as timedelta
days = []
for i in range(delta.days + 1):
day = sdate + timedelta(days=i)
... | start_int = [int(i) for i in start.split("-")]
end_int = [int(i) for i in end.split("-")]
sdate = date(*start_int) # start date
edate = date(*end_int) # end date
delta = edate - sdate # as timedelta
days = []
for i in range(delta.days + 1):
day = sdate + timedelta(days=i)
... | 51 | 272 | 158 | 430 | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - grafana_test_data.py
# 3/14/21 18:25
#
__author__ = "Benny <benny.think@gmail.com>"
import random
from datetime import date, timedelta
from common import Mongo
col = Mongo().client["zimuzu"]["metrics"]
def generate_date_series(start: str, end: str) -> list:
F... | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - grafana_test_data.py
# 3/14/21 18:25
#
__author__ = "Benny <benny.think@gmail.com>"
import random
from datetime import date, timedelta
from common import Mongo
col = Mongo().client["zimuzu"]["metrics"]
def generate_date_series(start: str, end: str) -> list:
F... | |
25,610 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/common/sync.py | 60,62 | 19,65 | sleep | BaseSync | 62,65 | 62,65 | class BaseSync:
def __init__(self):
self.mongo = Mongo()
self.yyets = self.mongo.db["yyets"]
self.sync = self.mongo.db["sync"]
self.structure = {
"status": 1,
"info": "OK",
"data": {
"info": {
"id": None,
... | class BaseSync:
def __init__(self):
self.mongo = Mongo()
self.yyets = self.mongo.db["yyets"]
self.sync = self.mongo.db["sync"]
self.structure = {
"status": 1,
"info": "OK",
"data": {
"info": {
"id": None,
... | time.sleep(random.random() * times)
| time.sleep(random.random() * times)
| 3 | 373 | 18 | 391 | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import logging
import os
import random
import re
import time
from copy import deepcopy
import requests
from bs4 import BeautifulSoup
from tqdm import tqdm
from databases.base import Mongo
from databases.douban import Douban
class BaseSync:
def __init__(se... | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import logging
import os
import random
import re
import time
from copy import deepcopy
import requests
from bs4 import BeautifulSoup
from tqdm import tqdm
from databases.base import Mongo
from databases.douban import Douban
class BaseSync:
def __init__(se... |
25,611 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/common/sync.py | 195,196 | 180,236 | run | YYSub | 196,231 | 196,231 | class YYSub(BaseSync):
def get_lastest_id(self):
url = "https://www.yysub.net/resourcelist?channel=&area=&category=&year=&tvstation=&sort=pubdate&page=1"
html = self.session.get(url).content.decode("u8")
soup = BeautifulSoup(html, "html.parser")
x = soup.find("div", class_="resource-... | class YYSub(BaseSync):
def get_lastest_id(self):
url = "https://www.yysub.net/resourcelist?channel=&area=&category=&year=&tvstation=&sort=pubdate&page=1"
html = self.session.get(url).content.decode("u8")
soup = BeautifulSoup(html, "html.parser")
x = soup.find("div", class_="resource-... | logging.info("Starting to sync YYSub...")
structure = deepcopy(self.structure)
end = self.get_lastest_id() + 1
# end = 41566
start = (self.sync.find_one({"name": "yysub"}) or {}).get("resource_id", 41557)
api = "https://m.yysub.net/api/resource/{}"
for i in range(... | logging.info("Starting to sync YYSub...")
structure = deepcopy(self.structure)
end = self.get_lastest_id() + 1
# end = 41566
start = (self.sync.find_one({"name": "yysub"}) or {}).get("resource_id", 41557)
api = "https://m.yysub.net/api/resource/{}"
for i in range(... | 101 | 285 | 509 | 794 | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import logging
import os
import random
import re
import time
from copy import deepcopy
import requests
from bs4 import BeautifulSoup
from tqdm import tqdm
from databases.base import Mongo
from databases.douban import Douban
class BaseSync:
def __init__(se... | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import logging
import os
import random
import re
import time
from copy import deepcopy
import requests
from bs4 import BeautifulSoup
from tqdm import tqdm
from databases.base import Mongo
from databases.douban import Douban
class BaseSync:
def __init__(se... |
25,612 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/common/sync.py | 82,83 | 65,180 | build_data | Zhuixinfan | 83,154 | 83,154 | class Zhuixinfan(BaseSync):
def run(self):
zhuixinfan = "http://www.fanxinzhui.com/rr/{}"
start = (self.sync.find_one({"name": "zhuixinfan"}) or {}).get(
"resource_id", os.getenv("ZHUIXINFAN_START", 20)
)
end = os.getenv("ZHUIXINFAN_END", 2500)
for i in range(star... | class Zhuixinfan(BaseSync):
def run(self):
zhuixinfan = "http://www.fanxinzhui.com/rr/{}"
start = (self.sync.find_one({"name": "zhuixinfan"}) or {}).get(
"resource_id", os.getenv("ZHUIXINFAN_START", 20)
)
end = os.getenv("ZHUIXINFAN_END", 2500)
for i in range(star... | structure = deepcopy(self.structure)
if "更新至" in html or re.findall(r"全\d+回", html):
channel, channel_cn = "tv", "日剧"
else:
channel, channel_cn = "movie", "日影"
soup = BeautifulSoup(html, "html.parser")
title = soup.find_all("div", class_="resource_title")[... | structure = deepcopy(self.structure)
if "更新至" in html or re.findall(r"全\d+回", html):
channel, channel_cn = "tv", "日剧"
else:
channel, channel_cn = "movie", "日影"
soup = BeautifulSoup(html, "html.parser")
title = soup.find_all("div", class_="resource_title")[... | 188 | 641 | 862 | 1,503 | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import logging
import os
import random
import re
import time
from copy import deepcopy
import requests
from bs4 import BeautifulSoup
from tqdm import tqdm
from databases.base import Mongo
from databases.douban import Douban
class BaseSync:
def __init__(se... | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import logging
import os
import random
import re
import time
from copy import deepcopy
import requests
from bs4 import BeautifulSoup
from tqdm import tqdm
from databases.base import Mongo
from databases.douban import Douban
class BaseSync:
def __init__(se... |
25,613 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/common/utils.py | 64,65 | 1,170 | generate_body | 65,70 | 65,70 | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - utils.py
# 6/16/21 21:42
#
__author__ = "Benny <benny.think@gmail.com>"
import contextlib
import json
import logging
import os
import pathlib
import re
import smtplib
import time
from datetime import datetime
from email.header import Header
from email.mime.text i... | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - utils.py
# 6/16/21 21:42
#
__author__ = "Benny <benny.think@gmail.com>"
import contextlib
import json
import logging
import os
import pathlib
import re
import smtplib
import time
from datetime import datetime
from email.header import Header
from email.mime.text i... | template = pathlib.Path(__file__).parent.parent.joinpath("templates", "email_template.html")
with open(template) as f:
return Template(f.read()).render(**context)
| template = pathlib.Path(__file__).parent.parent.joinpath("templates", "email_template.html")
with open(template) as f:
return Template(f.read()).render(**context)
| 10 | 1,834 | 60 | 1,894 | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - utils.py
# 6/16/21 21:42
#
__author__ = "Benny <benny.think@gmail.com>"
import contextlib
import json
import logging
import os
import pathlib
import re
import smtplib
import time
from datetime import datetime
from email.header import Header
from email.mime.text i... | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - utils.py
# 6/16/21 21:42
#
__author__ = "Benny <benny.think@gmail.com>"
import contextlib
import json
import logging
import os
import pathlib
import re
import smtplib
import time
from datetime import datetime
from email.header import Header
from email.mime.text i... | |
25,614 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/common/utils.py | 128,129 | 114,167 | get_old_ips | Cloudflare | 129,148 | 129,148 | class Cloudflare(Redis):
key = "cf-blacklist-ip"
expire = "cf-expire"
def __init__(self):
self.account_id = "e8d3ba82fe9e9a41cceb0047c2a2ab4f"
self.item_id = "3740654e0b104053b3e5d0a71fe87b33"
self.endpoint = "https://api.cloudflare.com/client/v4/accounts/{}/rules/lists/{}/items".fo... | class Cloudflare(Redis):
key = "cf-blacklist-ip"
expire = "cf-expire"
def __init__(self):
self.account_id = "e8d3ba82fe9e9a41cceb0047c2a2ab4f"
self.item_id = "3740654e0b104053b3e5d0a71fe87b33"
self.endpoint = "https://api.cloudflare.com/client/v4/accounts/{}/rules/lists/{}/items".fo... | cache = self.r.get(self.key)
if cache:
cache = json.loads(cache)
logging.info("Cache found with %s IPs", len(cache))
if len(cache) > 10000:
return cache[:5000]
return cache
else:
data = self.session.get(self.endpoint).js... | cache = self.r.get(self.key)
if cache:
cache = json.loads(cache)
logging.info("Cache found with %s IPs", len(cache))
if len(cache) > 10000:
return cache[:5000]
return cache
else:
data = self.session.get(self.endpoint).js... | 61 | 514 | 258 | 772 | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - utils.py
# 6/16/21 21:42
#
__author__ = "Benny <benny.think@gmail.com>"
import contextlib
import json
import logging
import os
import pathlib
import re
import smtplib
import time
from datetime import datetime
from email.header import Header
from email.mime.text i... | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - utils.py
# 6/16/21 21:42
#
__author__ = "Benny <benny.think@gmail.com>"
import contextlib
import json
import logging
import os
import pathlib
import re
import smtplib
import time
from datetime import datetime
from email.header import Header
from email.mime.text i... |
25,615 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/base.py | 23,24 | 13,32 | is_user_blocked | Mongo | 24,28 | 24,28 | class Mongo:
def __init__(self):
self.db = db
super().__init__()
def is_admin(self, username: str) -> bool:
data = self.db["users"].find_one({"username": username, "group": {"$in": ["admin"]}})
if data:
return True
def is_user_blocked(self, username: str) -> str... | class Mongo:
def __init__(self):
self.db = db
super().__init__()
def is_admin(self, username: str) -> bool:
data = self.db["users"].find_one({"username": username, "group": {"$in": ["admin"]}})
if data:
return True
def is_user_blocked(self, username: str) -> str... | r = self.db["users"].find_one({"username": username, "status.disable": True})
if r:
return r["status"]["reason"]
| r = self.db["users"].find_one({"username": username, "status.disable": True})
if r:
return r["status"]["reason"]
| 10 | 163 | 46 | 209 | #!/usr/bin/env python3
# coding: utf-8
import json
import logging
import os
import time
import meilisearch
from databases import db, redis_client
class Mongo:
def __init__(self):
self.db = db
super().__init__()
def is_admin(self, username: str) -> bool:
data = self.db["users"].find_... | #!/usr/bin/env python3
# coding: utf-8
import json
import logging
import os
import time
import meilisearch
from databases import db, redis_client
class Mongo:
def __init__(self):
self.db = db
super().__init__()
def is_admin(self, username: str) -> bool:
data = self.db["users"].find_... |
25,616 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/base.py | 39,40 | 32,57 | func | Redis | 40,54 | 40,54 | class Redis:
def __init__(self):
self.r = redis_client
super().__init__()
@classmethod
def cache(cls, timeout: int):
def func(fun):
FILL_FUNC_BODY return func
| class Redis:
def __init__(self):
self.r = redis_client
super().__init__()
@classmethod
def cache(cls, timeout: int):
def func(fun):
FILL_FUNC_BODY return func
| def inner(*args, **kwargs):
func_name = fun.__name__
cache_value = cls().r.get(func_name)
if cache_value:
logging.info("Retrieving %s data from redis", func_name)
return json.loads(cache_value)
else:
... | def inner(*args, **kwargs):
func_name = fun.__name__
cache_value = cls().r.get(func_name)
if cache_value:
logging.info("Retrieving %s data from redis", func_name)
return json.loads(cache_value)
else:
... | 36 | 71 | 158 | 229 | #!/usr/bin/env python3
# coding: utf-8
import json
import logging
import os
import time
import meilisearch
from databases import db, redis_client
class Mongo:
def __init__(self):
self.db = db
super().__init__()
def is_admin(self, username: str) -> bool:
data = self.db["users"].find_... | #!/usr/bin/env python3
# coding: utf-8
import json
import logging
import os
import time
import meilisearch
from databases import db, redis_client
class Mongo:
def __init__(self):
self.db = db
super().__init__()
def is_admin(self, username: str) -> bool:
data = self.db["users"].find_... |
25,617 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/base.py | 210,211 | 57,234 | get_data | SearchEngine | 211,220 | 211,220 | class SearchEngine(Mongo):
yyets_projection = {
"data.info.cnname": 1,
"data.info.enname": 1,
"data.info.aliasname": 1,
"data.info.area": 1,
"data.info.id": 1,
"data.info.channel_cn": 1,
"data.info.channel": 1,
"_id": {"$toString": "$_id"},
"or... | class SearchEngine(Mongo):
yyets_projection = {
"data.info.cnname": 1,
"data.info.enname": 1,
"data.info.aliasname": 1,
"data.info.area": 1,
"data.info.id": 1,
"data.info.channel_cn": 1,
"data.info.channel": 1,
"_id": {"$toString": "$_id"},
"or... | data = self.db.douban.aggregate(
[
{"$match": {"_id": _id}},
{"$lookup": self.douban_lookup},
{"$project": self.douban_projection},
]
)
return list(data)
| data = self.db.douban.aggregate(
[
{"$match": {"_id": _id}},
{"$lookup": self.douban_lookup},
{"$project": self.douban_projection},
]
)
return list(data)
| 15 | 1,737 | 86 | 1,823 | #!/usr/bin/env python3
# coding: utf-8
import json
import logging
import os
import time
import meilisearch
from databases import db, redis_client
class Mongo:
def __init__(self):
self.db = db
super().__init__()
def is_admin(self, username: str) -> bool:
data = self.db["users"].find_... | #!/usr/bin/env python3
# coding: utf-8
import json
import logging
import os
import time
import meilisearch
from databases import db, redis_client
class Mongo:
def __init__(self):
self.db = db
super().__init__()
def is_admin(self, username: str) -> bool:
data = self.db["users"].find_... |
25,619 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/comment.py | 312,313 | 305,336 | get_comment | CommentChild | 313,336 | 313,336 | class CommentChild(Comment, Mongo):
def __init__(self):
super().__init__()
self.page = 1
self.size = 5
self.projection = {"ip": False, "parent_id": False}
def get_comment(self, parent_id: str, page: int, size: int) -> dict:
FILL_FUNC_BODY | class CommentChild(Comment, Mongo):
def __init__(self):
super().__init__()
self.page = 1
self.size = 5
self.projection = {"ip": False, "parent_id": False}
def get_comment(self, parent_id: str, page: int, size: int) -> dict:
FILL_FUNC_BODY | condition = {
"parent_id": ObjectId(parent_id),
"deleted_at": {"$exists": False},
"type": "child",
}
count = self.db["comment"].count_documents(condition)
data = (
self.db["comment"]
.find(condition, self.projection)
... | condition = {
"parent_id": ObjectId(parent_id),
"deleted_at": {"$exists": False},
"type": "child",
}
count = self.db["comment"].count_documents(condition)
data = (
self.db["comment"]
.find(condition, self.projection)
... | 41 | 97 | 204 | 301 | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import os
import re
from http import HTTPStatus
import pymongo
from bson import ObjectId
from common.utils import check_spam, send_mail, ts_date
from databases.base import Mongo
from databases.other import Captcha, SpamProcess
class Comment(Mongo):
def __... | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import os
import re
from http import HTTPStatus
import pymongo
from bson import ObjectId
from common.utils import check_spam, send_mail, ts_date
from databases.base import Mongo
from databases.other import Captcha, SpamProcess
class Comment(Mongo):
def __... |
25,620 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/comment.py | 363,364 | 336,371 | extra_info | CommentNewest | 364,371 | 364,371 | class CommentNewest(Comment, Mongo):
def __init__(self):
super().__init__()
self.page = 1
self.size = 5
self.projection = {"ip": False, "parent_id": False, "children": False}
self.condition: "dict" = {"deleted_at": {"$exists": False}}
def get_comment(self, page: int, siz... | class CommentNewest(Comment, Mongo):
def __init__(self):
super().__init__()
self.page = 1
self.size = 5
self.projection = {"ip": False, "parent_id": False, "children": False}
self.condition: "dict" = {"deleted_at": {"$exists": False}}
def get_comment(self, page: int, siz... | for i in data:
resource_id = i.get("resource_id", 233)
res = self.db["yyets"].find_one({"data.info.id": resource_id})
if res:
i["cnname"] = res["data"]["info"]["cnname"]
| for i in data:
resource_id = i.get("resource_id", 233)
res = self.db["yyets"].find_one({"data.info.id": resource_id})
if res:
i["cnname"] = res["data"]["info"]["cnname"]
| 17 | 301 | 85 | 386 | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import os
import re
from http import HTTPStatus
import pymongo
from bson import ObjectId
from common.utils import check_spam, send_mail, ts_date
from databases.base import Mongo
from databases.other import Captcha, SpamProcess
class Comment(Mongo):
def __... | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import os
import re
from http import HTTPStatus
import pymongo
from bson import ObjectId
from common.utils import check_spam, send_mail, ts_date
from databases.base import Mongo
from databases.other import Captcha, SpamProcess
class Comment(Mongo):
def __... |
25,621 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/comment.py | 282,283 | 281,305 | react_comment | CommentReaction | 283,305 | 283,305 | class CommentReaction(Mongo):
def react_comment(self, username, data):
FILL_FUNC_BODY | class CommentReaction(Mongo):
def react_comment(self, username, data):
FILL_FUNC_BODY | # {"comment_id":"da23","😊":["user1","user2"]}
comment_id = data["comment_id"]
verb = data["verb"]
method = data["method"]
if not self.db["comment"].find_one({"_id": ObjectId(comment_id)}):
return {
"status": False,
"message": "Where is... | # {"comment_id":"da23","😊":["user1","user2"]}
comment_id = data["comment_id"]
verb = data["verb"]
method = data["method"]
if not self.db["comment"].find_one({"_id": ObjectId(comment_id)}):
return {
"status": False,
"message": "Where is... | 63 | 32 | 285 | 317 | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import os
import re
from http import HTTPStatus
import pymongo
from bson import ObjectId
from common.utils import check_spam, send_mail, ts_date
from databases.base import Mongo
from databases.other import Captcha, SpamProcess
class Comment(Mongo):
def __... | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import os
import re
from http import HTTPStatus
import pymongo
from bson import ObjectId
from common.utils import check_spam, send_mail, ts_date
from databases.base import Mongo
from databases.other import Captcha, SpamProcess
class Comment(Mongo):
def __... |
25,622 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/comment.py | 372,373 | 371,405 | get_comment | CommentSearch | 373,393 | 373,393 | class CommentSearch(CommentNewest):
def get_comment(self, page: int, size: int, keyword="") -> dict:
FILL_FUNC_BODY def fill_children(self, data):
for item in data:
child_id: "list" = item.get("children", [])
children = list(
self.db["comment"].find({"_id": {"$in":... | class CommentSearch(CommentNewest):
def get_comment(self, page: int, size: int, keyword="") -> dict:
FILL_FUNC_BODY def fill_children(self, data):
for item in data:
child_id: "list" = item.get("children", [])
children = list(
self.db["comment"].find({"_id": {"$in":... | self.projection.pop("children")
self.condition.update(content={"$regex": f".*{keyword}.*", "$options": "i"})
data = list(
self.db["comment"]
.find(self.condition, self.projection)
.sort("_id", pymongo.DESCENDING)
.limit(size)
.skip((pag... | self.projection.pop("children")
self.condition.update(content={"$regex": f".*{keyword}.*", "$options": "i"})
data = list(
self.db["comment"]
.find(self.condition, self.projection)
.sort("_id", pymongo.DESCENDING)
.limit(size)
.skip((pag... | 41 | 172 | 211 | 383 | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import os
import re
from http import HTTPStatus
import pymongo
from bson import ObjectId
from common.utils import check_spam, send_mail, ts_date
from databases.base import Mongo
from databases.other import Captcha, SpamProcess
class Comment(Mongo):
def __... | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import os
import re
from http import HTTPStatus
import pymongo
from bson import ObjectId
from common.utils import check_spam, send_mail, ts_date
from databases.base import Mongo
from databases.other import Captcha, SpamProcess
class Comment(Mongo):
def __... |
25,623 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/comment.py | 438,439 | 405,468 | get_content | Notification | 439,457 | 439,457 | class Notification(Mongo):
def get_notification(self, username, page, size):
# .sort("_id", pymongo.DESCENDING).limit(size).skip((page - 1) * size)
notify = self.db["notification"].find_one({"username": username}, projection={"_id": False})
if not notify:
return {
... | class Notification(Mongo):
def get_notification(self, username, page, size):
# .sort("_id", pymongo.DESCENDING).limit(size).skip((page - 1) * size)
notify = self.db["notification"].find_one({"username": username}, projection={"_id": False})
if not notify:
return {
... | comments = (
self.db["comment"]
.find({"_id": {"$in": id_list}}, projection={"ip": False, "parent_id": False})
.sort("_id", pymongo.DESCENDING)
)
comments = list(comments)
for comment in comments:
comment["id"] = str(comment["_id"])
... | comments = (
self.db["comment"]
.find({"_id": {"$in": id_list}}, projection={"ip": False, "parent_id": False})
.sort("_id", pymongo.DESCENDING)
)
comments = list(comments)
for comment in comments:
comment["id"] = str(comment["_id"])
... | 46 | 502 | 224 | 726 | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import os
import re
from http import HTTPStatus
import pymongo
from bson import ObjectId
from common.utils import check_spam, send_mail, ts_date
from databases.base import Mongo
from databases.other import Captcha, SpamProcess
class Comment(Mongo):
def __... | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import os
import re
from http import HTTPStatus
import pymongo
from bson import ObjectId
from common.utils import check_spam, send_mail, ts_date
from databases.base import Mongo
from databases.other import Captcha, SpamProcess
class Comment(Mongo):
def __... |
25,624 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/douban.py | 28,30 | 18,138 | find_douban | Douban | 30,71 | 30,71 | class Douban(Mongo):
def get_douban_data(self, rid: int) -> dict:
with contextlib.suppress(Exception):
return self.find_douban(rid)
return {"posterData": None}
def get_douban_image(self, rid: int) -> bytes:
db_data = self.get_douban_data(rid)
return db_data["posterDa... | class Douban(Mongo):
def get_douban_data(self, rid: int) -> dict:
with contextlib.suppress(Exception):
return self.find_douban(rid)
return {"posterData": None}
def get_douban_image(self, rid: int) -> bytes:
db_data = self.get_douban_data(rid)
return db_data["posterDa... | session = requests.Session()
ua = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
session.headers.update({"User-Agent": ua})
douban_col = self.db["douban"]
yyets_col = self.db["yyets"]
data = doub... | session = requests.Session()
ua = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
session.headers.update({"User-Agent": ua})
douban_col = self.db["douban"]
yyets_col = self.db["yyets"]
data = doub... | 120 | 1,022 | 588 | 1,610 | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import logging
import re
from http import HTTPStatus
from urllib.parse import unquote
import requests
from bs4 import BeautifulSoup
from retry import retry
from databases import DOUBAN_DETAIL, DOUBAN_SEARCH
from databases.base import Mongo
from databases.other ... | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import logging
import re
from http import HTTPStatus
from urllib.parse import unquote
import requests
from bs4 import BeautifulSoup
from retry import retry
from databases import DOUBAN_DETAIL, DOUBAN_SEARCH
from databases.base import Mongo
from databases.other ... |
25,625 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/douban.py | 142,145 | 138,162 | report_error | DoubanReport | 145,162 | 145,162 | class DoubanReport(Mongo):
def get_error(self) -> dict:
return dict(data=list(self.db["douban_error"].find(projection={"_id": False})))
def report_error(
self, captcha: str, captcha_id: int, content: str, resource_id: int
) -> dict:
FILL_FUNC_BODY | class DoubanReport(Mongo):
def get_error(self) -> dict:
return dict(data=list(self.db["douban_error"].find(projection={"_id": False})))
def report_error(
self, captcha: str, captcha_id: int, content: str, resource_id: int
) -> dict:
FILL_FUNC_BODY | returned = {"status_code": 0, "message": ""}
verify_result = Captcha().verify_code(captcha, captcha_id)
if not verify_result["status"]:
returned["status_code"] = HTTPStatus.BAD_REQUEST
returned["message"] = verify_result["message"]
return returned
cou... | returned = {"status_code": 0, "message": ""}
verify_result = Captcha().verify_code(captcha, captcha_id)
if not verify_result["status"]:
returned["status_code"] = HTTPStatus.BAD_REQUEST
returned["message"] = verify_result["message"]
return returned
cou... | 37 | 103 | 178 | 281 | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import logging
import re
from http import HTTPStatus
from urllib.parse import unquote
import requests
from bs4 import BeautifulSoup
from retry import retry
from databases import DOUBAN_DETAIL, DOUBAN_SEARCH
from databases.base import Mongo
from databases.other ... | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import logging
import re
from http import HTTPStatus
from urllib.parse import unquote
import requests
from bs4 import BeautifulSoup
from retry import retry
from databases import DOUBAN_DETAIL, DOUBAN_SEARCH
from databases.base import Mongo
from databases.other ... |
25,626 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/grafana.py | 12,13 | 11,18 | get_grafana_data | GrafanaQuery | 13,18 | 13,18 | class GrafanaQuery(Mongo):
def get_grafana_data(self, date_series) -> str:
FILL_FUNC_BODY | class GrafanaQuery(Mongo):
def get_grafana_data(self, date_series) -> str:
FILL_FUNC_BODY | condition = {"date": {"$in": date_series}}
projection = {"_id": False}
return self.db["metrics"].find(condition, projection)
| condition = {"date": {"$in": date_series}}
projection = {"_id": False}
return self.db["metrics"].find(condition, projection)
| 12 | 41 | 48 | 89 | #!/usr/bin/env python3
# coding: utf-8
import time
from datetime import date, timedelta
import pymongo
from databases.base import Mongo
class GrafanaQuery(Mongo):
def get_grafana_data(self, date_series) -> str:
FILL_FUNC_BODYclass Metrics(Mongo):
def set_metrics(self, metrics_type: str):
today = tim... | #!/usr/bin/env python3
# coding: utf-8
import time
from datetime import date, timedelta
import pymongo
from databases.base import Mongo
class GrafanaQuery(Mongo):
def get_grafana_data(self, date_series) -> str:
FILL_FUNC_BODYclass Metrics(Mongo):
def set_metrics(self, metrics_type: str):
today = tim... |
25,627 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/grafana.py | 23,24 | 18,33 | get_metrics | Metrics | 24,33 | 24,33 | class Metrics(Mongo):
def set_metrics(self, metrics_type: str):
today = time.strftime("%Y-%m-%d", time.localtime())
self.db["metrics"].update_one({"date": today}, {"$inc": {metrics_type: 1}}, upsert=True)
def get_metrics(self, from_date: str, to_date: str) -> dict:
FILL_FUNC_BODY | class Metrics(Mongo):
def set_metrics(self, metrics_type: str):
today = time.strftime("%Y-%m-%d", time.localtime())
self.db["metrics"].update_one({"date": today}, {"$inc": {metrics_type: 1}}, upsert=True)
def get_metrics(self, from_date: str, to_date: str) -> dict:
FILL_FUNC_BODY | start_int = [int(i) for i in from_date.split("-")]
end_int = [int(i) for i in to_date.split("-")]
sdate = date(*start_int) # start date
edate = date(*end_int) # end date
date_range = [str(sdate + timedelta(days=x)) for x in range((edate - sdate).days + 1)]
condition = {... | start_int = [int(i) for i in from_date.split("-")]
end_int = [int(i) for i in to_date.split("-")]
sdate = date(*start_int) # start date
edate = date(*end_int) # end date
date_range = [str(sdate + timedelta(days=x)) for x in range((edate - sdate).days + 1)]
condition = {... | 52 | 122 | 180 | 302 | #!/usr/bin/env python3
# coding: utf-8
import time
from datetime import date, timedelta
import pymongo
from databases.base import Mongo
class GrafanaQuery(Mongo):
def get_grafana_data(self, date_series) -> str:
condition = {"date": {"$in": date_series}}
projection = {"_id": False}
return... | #!/usr/bin/env python3
# coding: utf-8
import time
from datetime import date, timedelta
import pymongo
from databases.base import Mongo
class GrafanaQuery(Mongo):
def get_grafana_data(self, date_series) -> str:
condition = {"date": {"$in": date_series}}
projection = {"_id": False}
return... |
25,628 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/oauth.py | 10,11 | 9,42 | add_user | OAuthRegister | 11,42 | 11,42 | class OAuthRegister(Mongo):
def add_user(self, username, ip, browser, uid, source: "str"):
FILL_FUNC_BODY | class OAuthRegister(Mongo):
def add_user(self, username, ip, browser, uid, source: "str"):
FILL_FUNC_BODY | uid = str(uid)
# username = "Benny"
user = self.db["users"].find_one({"uid": uid, "source": source})
if user and user.get("password"):
# 直接注册的用户
return {"status": "fail", "message": "第三方登录失败,用户名已存在"}
elif user:
# 已存在的oauth用户
return ... | uid = str(uid)
# username = "Benny"
user = self.db["users"].find_one({"uid": uid, "source": source})
if user and user.get("password"):
# 直接注册的用户
return {"status": "fail", "message": "第三方登录失败,用户名已存在"}
elif user:
# 已存在的oauth用户
return ... | 71 | 43 | 337 | 380 | #!/usr/bin/env python3
# coding: utf-8
from hashlib import sha256
from common.utils import ts_date
from databases.base import Mongo
class OAuthRegister(Mongo):
def add_user(self, username, ip, browser, uid, source: "str"):
FILL_FUNC_BODYclass GitHubOAuth2Login(OAuthRegister):
pass
class MSOAuth2Login(OAuth... | #!/usr/bin/env python3
# coding: utf-8
from hashlib import sha256
from common.utils import ts_date
from databases.base import Mongo
class OAuthRegister(Mongo):
def add_user(self, username, ip, browser, uid, source: "str"):
FILL_FUNC_BODYclass GitHubOAuth2Login(OAuthRegister):
pass
class MSOAuth2Login(OAuth... |
25,629 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/other.py | 28,29 | 27,58 | get_announcement | Announcement | 29,47 | 29,47 | class Announcement(Mongo):
def get_announcement(self, page: int, size: int) -> dict:
FILL_FUNC_BODY def add_announcement(self, username, content, ip, browser):
construct = {
"username": username,
"ip": ip,
"date": ts_date(),
"browser": browser,
... | class Announcement(Mongo):
def get_announcement(self, page: int, size: int) -> dict:
FILL_FUNC_BODY def add_announcement(self, username, content, ip, browser):
construct = {
"username": username,
"ip": ip,
"date": ts_date(),
"browser": browser,
... | condition = {}
count = self.db["announcement"].count_documents(condition)
data = (
self.db["announcement"]
.find(condition, projection={"_id": True, "ip": False})
.sort("_id", pymongo.DESCENDING)
.limit(size)
.skip((page - 1) * size)
... | condition = {}
count = self.db["announcement"].count_documents(condition)
data = (
self.db["announcement"]
.find(condition, projection={"_id": True, "ip": False})
.sort("_id", pymongo.DESCENDING)
.limit(size)
.skip((page - 1) * size)
... | 42 | 124 | 178 | 302 | #!/usr/bin/env python3
# coding: utf-8
import base64
import json
import logging
import os
import random
import re
import string
import time
from hashlib import sha256
import pymongo
import requests
from bson import ObjectId
from captcha.image import ImageCaptcha
from common.utils import Cloudflare, ts_date
from datab... | #!/usr/bin/env python3
# coding: utf-8
import base64
import json
import logging
import os
import random
import re
import string
import time
from hashlib import sha256
import pymongo
import requests
from bson import ObjectId
from captcha.image import ImageCaptcha
from common.utils import Cloudflare, ts_date
from datab... |
25,630 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/other.py | 59,60 | 58,71 | get_black_list | Blacklist | 60,71 | 60,71 | class Blacklist(Redis):
def get_black_list(self):
FILL_FUNC_BODY | class Blacklist(Redis):
def get_black_list(self):
FILL_FUNC_BODY | keys = self.r.keys("*")
result = {}
for key in keys:
count = self.r.get(key)
ttl = self.r.ttl(key)
if ttl != -1:
result[key] = dict(count=count, ttl=ttl)
return result
| keys = self.r.keys("*")
result = {}
for key in keys:
count = self.r.get(key)
ttl = self.r.ttl(key)
if ttl != -1:
result[key] = dict(count=count, ttl=ttl)
return result
| 26 | 29 | 97 | 126 | #!/usr/bin/env python3
# coding: utf-8
import base64
import json
import logging
import os
import random
import re
import string
import time
from hashlib import sha256
import pymongo
import requests
from bson import ObjectId
from captcha.image import ImageCaptcha
from common.utils import Cloudflare, ts_date
from datab... | #!/usr/bin/env python3
# coding: utf-8
import base64
import json
import logging
import os
import random
import re
import string
import time
from hashlib import sha256
import pymongo
import requests
from bson import ObjectId
from captcha.image import ImageCaptcha
from common.utils import Cloudflare, ts_date
from datab... |
25,631 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/other.py | 178,179 | 177,194 | get_captcha | Captcha | 179,185 | 179,185 | class Captcha(Redis):
def get_captcha(self, captcha_id):
FILL_FUNC_BODY def verify_code(self, user_input, captcha_id) -> dict:
correct_code = self.r.get(captcha_id)
if not correct_code:
return {"status": False, "message": "验证码已过期"}
if user_input.lower() == correct_code.lower()... | class Captcha(Redis):
def get_captcha(self, captcha_id):
FILL_FUNC_BODY def verify_code(self, user_input, captcha_id) -> dict:
correct_code = self.r.get(captcha_id)
if not correct_code:
return {"status": False, "message": "验证码已过期"}
if user_input.lower() == correct_code.lower()... | chars = "".join([random.choice(predefined_str) for _ in range(4)])
image = ImageCaptcha()
data = image.generate(chars)
self.r.set(captcha_id, chars, ex=captcha_ex)
return f"data:image/png;base64,{base64.b64encode(data.getvalue()).decode('ascii')}"
| chars = "".join([random.choice(predefined_str) for _ in range(4)])
image = ImageCaptcha()
data = image.generate(chars)
self.r.set(captcha_id, chars, ex=captcha_ex)
return f"data:image/png;base64,{base64.b64encode(data.getvalue()).decode('ascii')}"
| 18 | 165 | 115 | 280 | #!/usr/bin/env python3
# coding: utf-8
import base64
import json
import logging
import os
import random
import re
import string
import time
from hashlib import sha256
import pymongo
import requests
from bson import ObjectId
from captcha.image import ImageCaptcha
from common.utils import Cloudflare, ts_date
from datab... | #!/usr/bin/env python3
# coding: utf-8
import base64
import json
import logging
import os
import random
import re
import string
import time
from hashlib import sha256
import pymongo
import requests
from bson import ObjectId
from captcha.image import ImageCaptcha
from common.utils import Cloudflare, ts_date
from datab... |
25,632 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/other.py | 72,73 | 71,99 | get_category | Category | 73,99 | 73,99 | class Category(Mongo):
def get_category(self, query: dict):
FILL_FUNC_BODY | class Category(Mongo):
def get_category(self, query: dict):
FILL_FUNC_BODY | page, size, douban = query["page"], query["size"], query["douban"]
query.pop("page")
query.pop("size")
query.pop("douban")
query_dict = {}
for key, value in query.items():
query_dict[f"data.info.{key}"] = value
logging.info("Query dict %s", query_dict)... | page, size, douban = query["page"], query["size"], query["douban"]
query.pop("page")
query.pop("size")
query.pop("douban")
query_dict = {}
for key, value in query.items():
query_dict[f"data.info.{key}"] = value
logging.info("Query dict %s", query_dict)... | 74 | 30 | 373 | 403 | #!/usr/bin/env python3
# coding: utf-8
import base64
import json
import logging
import os
import random
import re
import string
import time
from hashlib import sha256
import pymongo
import requests
from bson import ObjectId
from captcha.image import ImageCaptcha
from common.utils import Cloudflare, ts_date
from datab... | #!/usr/bin/env python3
# coding: utf-8
import base64
import json
import logging
import os
import random
import re
import string
import time
from hashlib import sha256
import pymongo
import requests
from bson import ObjectId
from captcha.image import ImageCaptcha
from common.utils import Cloudflare, ts_date
from datab... |
25,633 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/other.py | 160,161 | 140,177 | import_ban_user | Other | 161,167 | 161,167 | class Other(Mongo, Redis):
def reset_top(self):
# before resetting, save top data to history
json_data = requests.get("http://127.0.0.1:8888/api/top").json()
last_month = time.strftime("%Y-%m", time.localtime(time.time() - 3600 * 24))
json_data["date"] = last_month
json_data[... | class Other(Mongo, Redis):
def reset_top(self):
# before resetting, save top data to history
json_data = requests.get("http://127.0.0.1:8888/api/top").json()
last_month = time.strftime("%Y-%m", time.localtime(time.time() - 3600 * 24))
json_data["date"] = last_month
json_data[... | usernames = self.db["users"].find({"status.disable": True}, projection={"username": True})
self.r.delete("user_blacklist")
logging.info("Importing ban users to redis...%s", usernames)
for username in [u["username"] for u in usernames]:
self.r.hset("user_blacklist", username, ... | usernames = self.db["users"].find({"status.disable": True}, projection={"username": True})
self.r.delete("user_blacklist")
logging.info("Importing ban users to redis...%s", usernames)
for username in [u["username"] for u in usernames]:
self.r.hset("user_blacklist", username, ... | 24 | 476 | 107 | 583 | #!/usr/bin/env python3
# coding: utf-8
import base64
import json
import logging
import os
import random
import re
import string
import time
from hashlib import sha256
import pymongo
import requests
from bson import ObjectId
from captcha.image import ImageCaptcha
from common.utils import Cloudflare, ts_date
from datab... | #!/usr/bin/env python3
# coding: utf-8
import base64
import json
import logging
import os
import random
import re
import string
import time
from hashlib import sha256
import pymongo
import requests
from bson import ObjectId
from captcha.image import ImageCaptcha
from common.utils import Cloudflare, ts_date
from datab... |
25,634 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/other.py | 110,111 | 99,140 | restore_spam | SpamProcess | 111,118 | 111,118 | class SpamProcess(Mongo):
def ban_spam(self, obj_id: "str"):
obj_id = ObjectId(obj_id)
logging.info("Deleting spam %s", obj_id)
spam = self.db["spam"].find_one({"_id": obj_id})
username = spam["username"]
self.db["spam"].delete_many({"username": username})
# self.db["... | class SpamProcess(Mongo):
def ban_spam(self, obj_id: "str"):
obj_id = ObjectId(obj_id)
logging.info("Deleting spam %s", obj_id)
spam = self.db["spam"].find_one({"_id": obj_id})
username = spam["username"]
self.db["spam"].delete_many({"username": username})
# self.db["... | obj_id = ObjectId(obj_id)
spam = self.db["spam"].find_one({"_id": obj_id}, projection={"_id": False})
logging.info("Restoring spam %s", spam)
self.db["comment"].insert_one(spam)
self.db["spam"].delete_one({"_id": obj_id})
return {"status": True}
| obj_id = ObjectId(obj_id)
spam = self.db["spam"].find_one({"_id": obj_id}, projection={"_id": False})
logging.info("Restoring spam %s", spam)
self.db["comment"].insert_one(spam)
self.db["spam"].delete_one({"_id": obj_id})
return {"status": True}
| 19 | 408 | 111 | 519 | #!/usr/bin/env python3
# coding: utf-8
import base64
import json
import logging
import os
import random
import re
import string
import time
from hashlib import sha256
import pymongo
import requests
from bson import ObjectId
from captcha.image import ImageCaptcha
from common.utils import Cloudflare, ts_date
from datab... | #!/usr/bin/env python3
# coding: utf-8
import base64
import json
import logging
import os
import random
import re
import string
import time
from hashlib import sha256
import pymongo
import requests
from bson import ObjectId
from captcha.image import ImageCaptcha
from common.utils import Cloudflare, ts_date
from datab... |
25,635 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/resources.py | 294,295 | 293,331 | get_names | Name | 295,331 | 295,331 | class Name(Mongo):
def get_names(self, is_readable: [str, bool]) -> dict:
FILL_FUNC_BODY | class Name(Mongo):
def get_names(self, is_readable: [str, bool]) -> dict:
FILL_FUNC_BODY | if is_readable:
aggregation = [
{
"$project": {
"name": {
"$concat": [
"$data.info.area",
"$data.info.channel_cn",
"... | if is_readable:
aggregation = [
{
"$project": {
"name": {
"$concat": [
"$data.info.area",
"$data.info.channel_cn",
"... | 62 | 40 | 305 | 345 | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import json
import logging
import os
import random
import pymongo
import requests
import zhconv
from tqdm import tqdm
from common.utils import hide_phone, ts_date
from databases.base import Mongo, Redis, SearchEngine
from databases.comment import CommentSearch
... | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import json
import logging
import os
import random
import pymongo
import requests
import zhconv
from tqdm import tqdm
from common.utils import hide_phone, ts_date
from databases.base import Mongo, Redis, SearchEngine
from databases.comment import CommentSearch
... |
25,637 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/resources.py | 257,258 | 243,293 | query_db | ResourceLatest | 258,286 | 258,286 | class ResourceLatest(Mongo, Redis):
def get_latest_resource(self) -> dict:
key = "latest-resource"
latest = self.r.get(key)
if latest:
logging.info("Cache hit for latest resource")
latest = json.loads(latest)
latest["data"] = latest["data"][:100]
e... | class ResourceLatest(Mongo, Redis):
def get_latest_resource(self) -> dict:
key = "latest-resource"
latest = self.r.get(key)
if latest:
logging.info("Cache hit for latest resource")
latest = json.loads(latest)
latest["data"] = latest["data"][:100]
e... | col = self.db["yyets"]
projection = {"_id": False, "status": False, "info": False}
episode_data = {}
for res in tqdm(col.find(projection=projection), total=col.count_documents({})):
for season in res["data"].get("list", []):
for item in season["items"].values(... | col = self.db["yyets"]
projection = {"_id": False, "status": False, "info": False}
episode_data = {}
for res in tqdm(col.find(projection=projection), total=col.count_documents({})):
for season in res["data"].get("list", []):
for item in season["items"].values(... | 86 | 249 | 355 | 604 | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import json
import logging
import os
import random
import pymongo
import requests
import zhconv
from tqdm import tqdm
from common.utils import hide_phone, ts_date
from databases.base import Mongo, Redis, SearchEngine
from databases.comment import CommentSearch
... | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import json
import logging
import os
import random
import pymongo
import requests
import zhconv
from tqdm import tqdm
from common.utils import hide_phone, ts_date
from databases.base import Mongo, Redis, SearchEngine
from databases.comment import CommentSearch
... |
25,638 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/databases/resources.py | 224,225 | 209,243 | get_top_resource | Top | 225,243 | 225,243 | class Top(Mongo):
projection = {"_id": False, "data.info": True}
def get_most(self) -> list:
projection = {"_id": False, "like": True}
data = self.db["users"].find({}, projection)
most_like = {}
for item in data:
for _id in item.get("like", []):
most_... | class Top(Mongo):
projection = {"_id": False, "data.info": True}
def get_most(self) -> list:
projection = {"_id": False, "like": True}
data = self.db["users"].find({}, projection)
most_like = {}
for item in data:
for _id in item.get("like", []):
most_... | area_dict = dict(ALL={"$regex": ".*"}, US="美国", JP="日本", KR="韩国", UK="英国")
all_data = {"ALL": "全部"}
for abbr, area in area_dict.items():
data = (
self.db["yyets"]
.find(
{"data.info.area": area, "data.info.id": {"$ne": 233}},
... | area_dict = dict(ALL={"$regex": ".*"}, US="美国", JP="日本", KR="韩国", UK="英国")
all_data = {"ALL": "全部"}
for abbr, area in area_dict.items():
data = (
self.db["yyets"]
.find(
{"data.info.area": area, "data.info.id": {"$ne": 233}},
... | 41 | 221 | 205 | 426 | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import json
import logging
import os
import random
import pymongo
import requests
import zhconv
from tqdm import tqdm
from common.utils import hide_phone, ts_date
from databases.base import Mongo, Redis, SearchEngine
from databases.comment import CommentSearch
... | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import json
import logging
import os
import random
import pymongo
import requests
import zhconv
from tqdm import tqdm
from common.utils import hide_phone, ts_date
from databases.base import Mongo, Redis, SearchEngine
from databases.comment import CommentSearch
... |
25,639 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/base.py | 99,100 | 22,109 | write_error | BaseHandler | 100,109 | 100,109 | class BaseHandler(web.RequestHandler):
key = "user_blacklist"
filename = filename
executor = ThreadPoolExecutor(200)
def __init__(self, application, request, **kwargs):
super().__init__(application, request, **kwargs)
self.json = {}
with contextlib.suppress(ValueError):
... | class BaseHandler(web.RequestHandler):
key = "user_blacklist"
filename = filename
executor = ThreadPoolExecutor(200)
def __init__(self, application, request, **kwargs):
super().__init__(application, request, **kwargs)
self.json = {}
with contextlib.suppress(ValueError):
... | if status_code in [
HTTPStatus.FORBIDDEN,
HTTPStatus.UNAUTHORIZED,
HTTPStatus.NOT_FOUND,
HTTPStatus.INTERNAL_SERVER_ERROR,
]:
self.write(str(kwargs.get("exc_info")))
| if status_code in [
HTTPStatus.FORBIDDEN,
HTTPStatus.UNAUTHORIZED,
HTTPStatus.NOT_FOUND,
HTTPStatus.INTERNAL_SERVER_ERROR,
]:
self.write(str(kwargs.get("exc_info")))
| 10 | 799 | 86 | 885 | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import importlib
import json
import logging
import pathlib
from concurrent.futures import ThreadPoolExecutor
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from databases.base imp... | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import importlib
import json
import logging
import pathlib
from concurrent.futures import ThreadPoolExecutor
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from databases.base imp... |
25,640 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/base.py | 110,112 | 109,122 | send_index | IndexHandler | 112,116 | 112,116 | class IndexHandler(BaseHandler):
@run_on_executor()
def send_index(self):
FILL_FUNC_BODY @gen.coroutine
def get(self):
resp = yield self.send_index()
self.write(resp)
| class IndexHandler(BaseHandler):
@run_on_executor()
def send_index(self):
FILL_FUNC_BODY @gen.coroutine
def get(self):
resp = yield self.send_index()
self.write(resp)
| with open(index, encoding="u8") as f:
html = f.read()
return html
| with open(index, encoding="u8") as f:
html = f.read()
return html
| 10 | 73 | 33 | 106 | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import importlib
import json
import logging
import pathlib
from concurrent.futures import ThreadPoolExecutor
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from databases.base imp... | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import importlib
import json
import logging
import pathlib
from concurrent.futures import ThreadPoolExecutor
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from databases.base imp... |
25,641 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/base.py | 123,124 | 122,126 | get | NotFoundHandler | 124,126 | 124,126 | class NotFoundHandler(BaseHandler):
def get(self):
FILL_FUNC_BODY | class NotFoundHandler(BaseHandler):
def get(self):
FILL_FUNC_BODY | # for react app
self.render(index)
| # for react app
self.render(index)
| 5 | 26 | 16 | 42 | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import importlib
import json
import logging
import pathlib
from concurrent.futures import ThreadPoolExecutor
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from databases.base imp... | #!/usr/bin/env python3
# coding: utf-8
import contextlib
import importlib
import json
import logging
import pathlib
from concurrent.futures import ThreadPoolExecutor
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from databases.base imp... |
25,642 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/comment.py | 132,134 | 129,151 | get_comment | CommentChildHandler | 134,145 | 134,145 | class CommentChildHandler(CommentHandler):
filename = filename
@run_on_executor()
def get_comment(self):
FILL_FUNC_BODY @gen.coroutine
def get(self):
resp = yield self.get_comment()
self.write(resp)
| class CommentChildHandler(CommentHandler):
filename = filename
@run_on_executor()
def get_comment(self):
FILL_FUNC_BODY @gen.coroutine
def get(self):
resp = yield self.get_comment()
self.write(resp)
| parent_id = self.get_argument("parent_id", "0")
size = int(self.get_argument("size", "3"))
page = int(self.get_argument("page", "1"))
if not parent_id:
self.set_status(HTTPStatus.BAD_REQUEST)
return {"status": False, "message": "请提供 parent_id"}
comment_da... | parent_id = self.get_argument("parent_id", "0")
size = int(self.get_argument("size", "3"))
page = int(self.get_argument("page", "1"))
if not parent_id:
self.set_status(HTTPStatus.BAD_REQUEST)
return {"status": False, "message": "请提供 parent_id"}
comment_da... | 30 | 80 | 149 | 229 | #!/usr/bin/env python3
# coding: utf-8
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import hide_phone
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class CommentHandler(BaseHan... | #!/usr/bin/env python3
# coding: utf-8
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import hide_phone
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class CommentHandler(BaseHan... |
25,643 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/comment.py | 18,20 | 15,105 | get_comment | CommentHandler | 20,45 | 20,45 | class CommentHandler(BaseHandler):
filename = filename
@run_on_executor()
def get_comment(self):
FILL_FUNC_BODY @run_on_executor()
def add_comment(self):
payload = self.json
captcha = payload["captcha"]
captcha_id = payload["id"]
content = payload["content"]
r... | class CommentHandler(BaseHandler):
filename = filename
@run_on_executor()
def get_comment(self):
FILL_FUNC_BODY @run_on_executor()
def add_comment(self):
payload = self.json
captcha = payload["captcha"]
captcha_id = payload["id"]
content = payload["content"]
r... | query_id = self.get_argument("resource_id", "0")
resource_id = int(query_id) if query_id.isdigit() else 0
size = int(self.get_argument("size", "5"))
page = int(self.get_argument("page", "1"))
inner_size = int(self.get_argument("inner_size", "3"))
inner_page = int(self.ge... | query_id = self.get_argument("resource_id", "0")
resource_id = int(query_id) if query_id.isdigit() else 0
size = int(self.get_argument("size", "5"))
page = int(self.get_argument("page", "1"))
inner_size = int(self.get_argument("inner_size", "3"))
inner_page = int(self.ge... | 59 | 535 | 308 | 843 | #!/usr/bin/env python3
# coding: utf-8
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import hide_phone
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class CommentHandler(BaseHan... | #!/usr/bin/env python3
# coding: utf-8
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import hide_phone
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class CommentHandler(BaseHan... |
25,644 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/comment.py | 154,156 | 151,169 | get_comment | CommentNewestHandler | 156,163 | 156,163 | class CommentNewestHandler(CommentHandler):
filename = filename
@run_on_executor()
def get_comment(self):
FILL_FUNC_BODY @gen.coroutine
def get(self):
resp = yield self.get_comment()
self.write(resp)
| class CommentNewestHandler(CommentHandler):
filename = filename
@run_on_executor()
def get_comment(self):
FILL_FUNC_BODY @gen.coroutine
def get(self):
resp = yield self.get_comment()
self.write(resp)
| size = int(self.get_argument("size", "5"))
page = int(self.get_argument("page", "1"))
comment_data = self.instance.get_comment(page, size)
hide_phone((comment_data["data"]))
return comment_data
| size = int(self.get_argument("size", "5"))
page = int(self.get_argument("page", "1"))
comment_data = self.instance.get_comment(page, size)
hide_phone((comment_data["data"]))
return comment_data
| 15 | 81 | 80 | 161 | #!/usr/bin/env python3
# coding: utf-8
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import hide_phone
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class CommentHandler(BaseHan... | #!/usr/bin/env python3
# coding: utf-8
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import hide_phone
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class CommentHandler(BaseHan... |
25,645 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/comment.py | 108,110 | 105,129 | comment_reaction | CommentReactionHandler | 110,116 | 110,116 | class CommentReactionHandler(BaseHandler):
filename = filename
@run_on_executor()
def comment_reaction(self):
FILL_FUNC_BODY @gen.coroutine
@web.authenticated
def post(self):
resp = yield self.comment_reaction()
self.write(resp)
@gen.coroutine
@web.authenticated
def ... | class CommentReactionHandler(BaseHandler):
filename = filename
@run_on_executor()
def comment_reaction(self):
FILL_FUNC_BODY @gen.coroutine
@web.authenticated
def post(self):
resp = yield self.comment_reaction()
self.write(resp)
@gen.coroutine
@web.authenticated
def ... | self.json.update(method=self.request.method)
username = self.get_current_user()
result = self.instance.react_comment(username, self.json)
self.set_status(result.get("status_code"))
return result
| self.json.update(method=self.request.method)
username = self.get_current_user()
result = self.instance.react_comment(username, self.json)
self.set_status(result.get("status_code"))
return result
| 11 | 135 | 73 | 208 | #!/usr/bin/env python3
# coding: utf-8
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import hide_phone
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class CommentHandler(BaseHan... | #!/usr/bin/env python3
# coding: utf-8
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import hide_phone
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class CommentHandler(BaseHan... |
25,646 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/comment.py | 172,174 | 169,187 | search_comment | CommentSearchHandler | 174,181 | 174,181 | class CommentSearchHandler(CommentHandler):
filename = filename
@run_on_executor()
def search_comment(self):
FILL_FUNC_BODY @gen.coroutine
def get(self):
resp = yield self.search_comment()
self.write(resp)
| class CommentSearchHandler(CommentHandler):
filename = filename
@run_on_executor()
def search_comment(self):
FILL_FUNC_BODY @gen.coroutine
def get(self):
resp = yield self.search_comment()
self.write(resp)
| size = int(self.get_argument("size", "5"))
page = int(self.get_argument("page", "1"))
keyword = self.get_argument("keyword", "")
comment_data = self.instance.get_comment(page, size, keyword)
hide_phone((comment_data["data"]))
return comment_data
| size = int(self.get_argument("size", "5"))
page = int(self.get_argument("page", "1"))
keyword = self.get_argument("keyword", "")
comment_data = self.instance.get_comment(page, size, keyword)
hide_phone((comment_data["data"]))
return comment_data
| 20 | 80 | 95 | 175 | #!/usr/bin/env python3
# coding: utf-8
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import hide_phone
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class CommentHandler(BaseHan... | #!/usr/bin/env python3
# coding: utf-8
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import hide_phone
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class CommentHandler(BaseHan... |
25,647 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/comment.py | 209,212 | 187,220 | get | NotificationHandler | 212,215 | 212,215 | class NotificationHandler(BaseHandler):
filename = filename
@run_on_executor()
def get_notification(self):
username = self.get_current_user()
size = int(self.get_argument("size", "5"))
page = int(self.get_argument("page", "1"))
return self.instance.get_notification(username... | class NotificationHandler(BaseHandler):
filename = filename
@run_on_executor()
def get_notification(self):
username = self.get_current_user()
size = int(self.get_argument("size", "5"))
page = int(self.get_argument("page", "1"))
return self.instance.get_notification(username... | resp = yield self.get_notification()
self.write(resp)
| resp = yield self.get_notification()
self.write(resp)
| 5 | 317 | 24 | 341 | #!/usr/bin/env python3
# coding: utf-8
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import hide_phone
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class CommentHandler(BaseHan... | #!/usr/bin/env python3
# coding: utf-8
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import hide_phone
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class CommentHandler(BaseHan... |
25,648 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/douban.py | 18,20 | 15,43 | douban_data | DoubanHandler | 20,27 | 20,27 | class DoubanHandler(BaseHandler):
filename = filename
@run_on_executor()
def douban_data(self):
FILL_FUNC_BODY def get_image(self) -> bytes:
rid = self.get_query_argument("resource_id")
return self.instance.get_douban_image(int(rid))
@gen.coroutine
def get(self):
_type =... | class DoubanHandler(BaseHandler):
filename = filename
@run_on_executor()
def douban_data(self):
FILL_FUNC_BODY def get_image(self) -> bytes:
rid = self.get_query_argument("resource_id")
return self.instance.get_douban_image(int(rid))
@gen.coroutine
def get(self):
_type =... | rid = self.get_query_argument("resource_id")
data = self.instance.get_douban_data(int(rid))
data.pop("posterData", None)
if not data:
self.set_status(HTTPStatus.NOT_FOUND)
return data
| rid = self.get_query_argument("resource_id")
data = self.instance.get_douban_data(int(rid))
data.pop("posterData", None)
if not data:
self.set_status(HTTPStatus.NOT_FOUND)
return data
| 14 | 203 | 82 | 285 | #!/usr/bin/env python3
# coding: utf-8
from http import HTTPStatus
from pathlib import Path
import filetype
from tornado import gen
from tornado.concurrent import run_on_executor
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class DoubanHandler(BaseHandler):
filename = file... | #!/usr/bin/env python3
# coding: utf-8
from http import HTTPStatus
from pathlib import Path
import filetype
from tornado import gen
from tornado.concurrent import run_on_executor
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class DoubanHandler(BaseHandler):
filename = file... |
25,649 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/douban.py | 67,69 | 43,71 | get | DoubanReportHandler | 69,71 | 69,71 | class DoubanReportHandler(BaseHandler):
class_name = "DoubanReportResource"
@run_on_executor()
def get_error(self):
return self.instance.get_error()
@run_on_executor()
def report_error(self):
data = self.json
user_captcha = data["captcha_id"]
captcha_id = data["id"]... | class DoubanReportHandler(BaseHandler):
class_name = "DoubanReportResource"
@run_on_executor()
def get_error(self):
return self.instance.get_error()
@run_on_executor()
def report_error(self):
data = self.json
user_captcha = data["captcha_id"]
captcha_id = data["id"]... | resp = yield self.get_error()
self.write(resp)
| resp = yield self.get_error()
self.write(resp)
| 5 | 274 | 21 | 295 | #!/usr/bin/env python3
# coding: utf-8
from http import HTTPStatus
from pathlib import Path
import filetype
from tornado import gen
from tornado.concurrent import run_on_executor
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class DoubanHandler(BaseHandler):
filename = file... | #!/usr/bin/env python3
# coding: utf-8
from http import HTTPStatus
from pathlib import Path
import filetype
from tornado import gen
from tornado.concurrent import run_on_executor
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class DoubanHandler(BaseHandler):
filename = file... |
25,650 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/grafana.py | 66,67 | 63,70 | get | GrafanaIndexHandler | 67,70 | 67,70 | class GrafanaIndexHandler(BaseHandler):
filename = filename
def get(self):
FILL_FUNC_BODY | class GrafanaIndexHandler(BaseHandler):
filename = filename
def get(self):
FILL_FUNC_BODY | self.write({})
| self.write({})
| 1 | 34 | 12 | 46 | #!/usr/bin/env python3
# coding: utf-8
import json
import time
from datetime import date, timedelta
from http import HTTPStatus
from pathlib import Path
from tornado import gen
from tornado.concurrent import run_on_executor
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class Me... | #!/usr/bin/env python3
# coding: utf-8
import json
import time
from datetime import date, timedelta
from http import HTTPStatus
from pathlib import Path
from tornado import gen
from tornado.concurrent import run_on_executor
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class Me... |
25,651 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/grafana.py | 117,118 | 96,134 | post | GrafanaQueryHandler | 118,134 | 118,134 | class GrafanaQueryHandler(BaseHandler):
filename = filename
@staticmethod
def generate_date_series(start: str, end: str) -> list:
start_int = [int(i) for i in start.split("-")]
end_int = [int(i) for i in end.split("-")]
sdate = date(*start_int) # start date
edate = date(*en... | class GrafanaQueryHandler(BaseHandler):
filename = filename
@staticmethod
def generate_date_series(start: str, end: str) -> list:
start_int = [int(i) for i in start.split("-")]
end_int = [int(i) for i in end.split("-")]
sdate = date(*start_int) # start date
edate = date(*en... | payload = self.json
start = payload["range"]["from"].split("T")[0]
end = payload["range"]["to"].split("T")[0]
date_series = self.generate_date_series(start, end)
targets = [i["target"] for i in payload["targets"] if i["target"]]
grafana_data = []
for target in tar... | payload = self.json
start = payload["range"]["from"].split("T")[0]
end = payload["range"]["to"].split("T")[0]
date_series = self.generate_date_series(start, end)
targets = [i["target"] for i in payload["targets"] if i["target"]]
grafana_data = []
for target in tar... | 60 | 246 | 253 | 499 | #!/usr/bin/env python3
# coding: utf-8
import json
import time
from datetime import date, timedelta
from http import HTTPStatus
from pathlib import Path
from tornado import gen
from tornado.concurrent import run_on_executor
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class Me... | #!/usr/bin/env python3
# coding: utf-8
import json
import time
from datetime import date, timedelta
from http import HTTPStatus
from pathlib import Path
from tornado import gen
from tornado.concurrent import run_on_executor
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class Me... |
25,652 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/grafana.py | 73,74 | 70,96 | post | GrafanaSearchHandler | 74,96 | 74,96 | class GrafanaSearchHandler(BaseHandler):
filename = filename
def post(self):
FILL_FUNC_BODY | class GrafanaSearchHandler(BaseHandler):
filename = filename
def post(self):
FILL_FUNC_BODY | data = [
"resource",
"top",
"home",
"search",
"extra",
"discuss",
"multiDownload",
"download",
"user",
"share",
"me",
"database",
"help",
"backO... | data = [
"resource",
"top",
"home",
"search",
"extra",
"discuss",
"multiDownload",
"download",
"user",
"share",
"me",
"database",
"help",
"backO... | 22 | 34 | 138 | 172 | #!/usr/bin/env python3
# coding: utf-8
import json
import time
from datetime import date, timedelta
from http import HTTPStatus
from pathlib import Path
from tornado import gen
from tornado.concurrent import run_on_executor
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class Me... | #!/usr/bin/env python3
# coding: utf-8
import json
import time
from datetime import date, timedelta
from http import HTTPStatus
from pathlib import Path
from tornado import gen
from tornado.concurrent import run_on_executor
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class Me... |
25,653 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/grafana.py | 29,31 | 17,63 | get_metrics | MetricsHandler | 31,45 | 31,45 | class MetricsHandler(BaseHandler):
filename = filename
@run_on_executor()
def set_metrics(self):
payload = self.json
metrics_type = payload.get("type", self.get_query_argument("type", "unknown"))
self.instance.set_metrics(metrics_type)
self.set_status(HTTPStatus.CREATED)
... | class MetricsHandler(BaseHandler):
filename = filename
@run_on_executor()
def set_metrics(self):
payload = self.json
metrics_type = payload.get("type", self.get_query_argument("type", "unknown"))
self.instance.set_metrics(metrics_type)
self.set_status(HTTPStatus.CREATED)
... | if not self.instance.is_admin(self.get_current_user()):
self.set_status(HTTPStatus.NOT_FOUND)
return ""
# only return latest 7 days. with days parameter to generate different range
from_date = self.get_query_argument("from", None)
to_date = self.get_query_argumen... | if not self.instance.is_admin(self.get_current_user()):
self.set_status(HTTPStatus.NOT_FOUND)
return ""
# only return latest 7 days. with days parameter to generate different range
from_date = self.get_query_argument("from", None)
to_date = self.get_query_argumen... | 52 | 287 | 219 | 506 | #!/usr/bin/env python3
# coding: utf-8
import json
import time
from datetime import date, timedelta
from http import HTTPStatus
from pathlib import Path
from tornado import gen
from tornado.concurrent import run_on_executor
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class Me... | #!/usr/bin/env python3
# coding: utf-8
import json
import time
from datetime import date, timedelta
from http import HTTPStatus
from pathlib import Path
from tornado import gen
from tornado.concurrent import run_on_executor
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class Me... |
25,654 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/oauth.py | 147,148 | 142,163 | get | FacebookAuth2LoginHandler | 148,163 | 148,163 | class FacebookAuth2LoginHandler(OAuth2Handler):
_OAUTH_AUTHORIZE_URL = "https://www.facebook.com/v16.0/dialog/oauth"
_OAUTH_ACCESS_TOKEN_URL = "https://graph.facebook.com/oauth/access_token"
_OAUTH_API_REQUEST_URL = "https://graph.facebook.com/me"
def get(self):
FILL_FUNC_BODY | class FacebookAuth2LoginHandler(OAuth2Handler):
_OAUTH_AUTHORIZE_URL = "https://www.facebook.com/v16.0/dialog/oauth"
_OAUTH_ACCESS_TOKEN_URL = "https://graph.facebook.com/oauth/access_token"
_OAUTH_API_REQUEST_URL = "https://graph.facebook.com/me"
def get(self):
FILL_FUNC_BODY | client_id, client_secret, redirect_uri = self.get_secret("fb_oauth")
code = self.get_argument("code", None)
if code:
access = self.get_authenticated_user(client_id, client_secret, code, {"redirect_uri": redirect_uri})
resp = self.oauth2_sync_request(access["access_token"]... | client_id, client_secret, redirect_uri = self.get_secret("fb_oauth")
code = self.get_argument("code", None)
if code:
access = self.get_authenticated_user(client_id, client_secret, code, {"redirect_uri": redirect_uri})
resp = self.oauth2_sync_request(access["access_token"]... | 49 | 122 | 223 | 345 | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
from pathlib import Path
from urllib.parse import urlencode
import requests
from tornado.auth import GoogleOAuth2Mixin, OAuth2Mixin, TwitterMixin
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class OAuth2Handler(Ba... | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
from pathlib import Path
from urllib.parse import urlencode
import requests
from tornado.auth import GoogleOAuth2Mixin, OAuth2Mixin, TwitterMixin
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class OAuth2Handler(Ba... |
25,655 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/oauth.py | 61,62 | 56,79 | get | GitHubOAuth2LoginHandler | 62,79 | 62,79 | class GitHubOAuth2LoginHandler(OAuth2Handler):
_OAUTH_AUTHORIZE_URL = "https://github.com/login/oauth/authorize"
_OAUTH_ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token"
_OAUTH_API_REQUEST_URL = "https://api.github.com/user"
def get(self):
FILL_FUNC_BODY | class GitHubOAuth2LoginHandler(OAuth2Handler):
_OAUTH_AUTHORIZE_URL = "https://github.com/login/oauth/authorize"
_OAUTH_ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token"
_OAUTH_API_REQUEST_URL = "https://api.github.com/user"
def get(self):
FILL_FUNC_BODY | client_id, client_secret, redirect_uri = self.get_secret("github_oauth")
code = self.get_argument("code", None)
if code:
access = self.get_authenticated_user(client_id, client_secret, code)
resp = self.oauth2_sync_request(access["access_token"])
username = res... | client_id, client_secret, redirect_uri = self.get_secret("github_oauth")
code = self.get_argument("code", None)
if code:
access = self.get_authenticated_user(client_id, client_secret, code)
resp = self.oauth2_sync_request(access["access_token"])
username = res... | 35 | 119 | 201 | 320 | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
from pathlib import Path
from urllib.parse import urlencode
import requests
from tornado.auth import GoogleOAuth2Mixin, OAuth2Mixin, TwitterMixin
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class OAuth2Handler(Ba... | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
from pathlib import Path
from urllib.parse import urlencode
import requests
from tornado.auth import GoogleOAuth2Mixin, OAuth2Mixin, TwitterMixin
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class OAuth2Handler(Ba... |
25,656 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/oauth.py | 109,110 | 108,131 | get | GoogleOAuth2LoginHandler | 110,131 | 110,131 | class GoogleOAuth2LoginHandler(GoogleOAuth2Mixin, OAuth2Handler):
async def get(self):
FILL_FUNC_BODY | class GoogleOAuth2LoginHandler(GoogleOAuth2Mixin, OAuth2Handler):
async def get(self):
FILL_FUNC_BODY | redirect_uri = os.getenv("DOMAIN") + self.request.path
code = self.get_argument("code", None)
if code:
access = await self.get_authenticated_user(redirect_uri=redirect_uri, code=code)
user = await self.oauth2_request(
"https://www.googleapis.com/oauth2/v1/... | redirect_uri = os.getenv("DOMAIN") + self.request.path
code = self.get_argument("code", None)
if code:
access = await self.get_authenticated_user(redirect_uri=redirect_uri, code=code)
user = await self.oauth2_request(
"https://www.googleapis.com/oauth2/v1/... | 44 | 39 | 256 | 295 | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
from pathlib import Path
from urllib.parse import urlencode
import requests
from tornado.auth import GoogleOAuth2Mixin, OAuth2Mixin, TwitterMixin
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class OAuth2Handler(Ba... | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
from pathlib import Path
from urllib.parse import urlencode
import requests
from tornado.auth import GoogleOAuth2Mixin, OAuth2Mixin, TwitterMixin
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class OAuth2Handler(Ba... |
25,657 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/oauth.py | 84,85 | 79,108 | get | MSOAuth2LoginHandler | 85,108 | 85,108 | class MSOAuth2LoginHandler(OAuth2Handler):
_OAUTH_AUTHORIZE_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
_OAUTH_ACCESS_TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
_OAUTH_API_REQUEST_URL = "https://graph.microsoft.com/v1.0/me"
def get(self):
FILL_FU... | class MSOAuth2LoginHandler(OAuth2Handler):
_OAUTH_AUTHORIZE_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
_OAUTH_ACCESS_TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
_OAUTH_API_REQUEST_URL = "https://graph.microsoft.com/v1.0/me"
def get(self):
FILL_FU... | client_id, client_secret, redirect_uri = self.get_secret("ms_oauth")
code = self.get_argument("code", None)
if code:
access = self.get_authenticated_user(
client_id,
client_secret,
code,
{"grant_type": "authorization_cod... | client_id, client_secret, redirect_uri = self.get_secret("ms_oauth")
code = self.get_argument("code", None)
if code:
access = self.get_authenticated_user(
client_id,
client_secret,
code,
{"grant_type": "authorization_cod... | 41 | 139 | 251 | 390 | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
from pathlib import Path
from urllib.parse import urlencode
import requests
from tornado.auth import GoogleOAuth2Mixin, OAuth2Mixin, TwitterMixin
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class OAuth2Handler(Ba... | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
from pathlib import Path
from urllib.parse import urlencode
import requests
from tornado.auth import GoogleOAuth2Mixin, OAuth2Mixin, TwitterMixin
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class OAuth2Handler(Ba... |
25,658 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/oauth.py | 22,23 | 16,56 | add_oauth_user | OAuth2Handler | 23,31 | 23,31 | class OAuth2Handler(BaseHandler, OAuth2Mixin):
filename = filename
_OAUTH_AUTHORIZE_URL = ""
_OAUTH_ACCESS_TOKEN_URL = ""
_OAUTH_API_REQUEST_URL = ""
def add_oauth_user(self, username, unique, source):
FILL_FUNC_BODY def get_authenticated_user(self, client_id: str, client_secret: str, code: str,... | class OAuth2Handler(BaseHandler, OAuth2Mixin):
filename = filename
_OAUTH_AUTHORIZE_URL = ""
_OAUTH_ACCESS_TOKEN_URL = ""
_OAUTH_API_REQUEST_URL = ""
def add_oauth_user(self, username, unique, source):
FILL_FUNC_BODY def get_authenticated_user(self, client_id: str, client_secret: str, code: str,... | logging.info("User %s login with %s now...", username, source)
ip = self.get_real_ip()
browser = self.request.headers["user-agent"]
result = self.instance.add_user(username, ip, browser, unique, source)
if result["status"] == "success":
self.set_secure_cookie("usernam... | logging.info("User %s login with %s now...", username, source)
ip = self.get_real_ip()
browser = self.request.headers["user-agent"]
result = self.instance.add_user(username, ip, browser, unique, source)
if result["status"] == "success":
self.set_secure_cookie("usernam... | 31 | 389 | 123 | 512 | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
from pathlib import Path
from urllib.parse import urlencode
import requests
from tornado.auth import GoogleOAuth2Mixin, OAuth2Mixin, TwitterMixin
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class OAuth2Handler(Ba... | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
from pathlib import Path
from urllib.parse import urlencode
import requests
from tornado.auth import GoogleOAuth2Mixin, OAuth2Mixin, TwitterMixin
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class OAuth2Handler(Ba... |
25,659 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/oauth.py | 132,133 | 131,142 | get | TwitterOAuth2LoginHandler | 133,142 | 133,142 | class TwitterOAuth2LoginHandler(TwitterMixin, OAuth2Handler):
async def get(self):
FILL_FUNC_BODY | class TwitterOAuth2LoginHandler(TwitterMixin, OAuth2Handler):
async def get(self):
FILL_FUNC_BODY | if self.get_argument("oauth_token", None):
user = await self.get_authenticated_user()
username = user["username"]
id_str = user["id_str"]
self.add_oauth_user(username, id_str, "Twitter")
else:
await self.authorize_redirect(extra_params={"x_auth... | if self.get_argument("oauth_token", None):
user = await self.get_authenticated_user()
username = user["username"]
id_str = user["id_str"]
self.add_oauth_user(username, id_str, "Twitter")
else:
await self.authorize_redirect(extra_params={"x_auth... | 20 | 37 | 115 | 152 | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
from pathlib import Path
from urllib.parse import urlencode
import requests
from tornado.auth import GoogleOAuth2Mixin, OAuth2Mixin, TwitterMixin
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class OAuth2Handler(Ba... | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
from pathlib import Path
from urllib.parse import urlencode
import requests
from tornado.auth import GoogleOAuth2Mixin, OAuth2Mixin, TwitterMixin
from handlers.base import BaseHandler
filename = Path(__file__).name.split(".")[0]
class OAuth2Handler(Ba... |
25,660 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/other.py | 30,32 | 21,58 | add_announcement | AnnouncementHandler | 32,46 | 32,46 | class AnnouncementHandler(BaseHandler):
filename = filename
@run_on_executor()
def get_announcement(self):
size = int(self.get_argument("size", "5"))
page = int(self.get_argument("page", "1"))
return self.instance.get_announcement(page, size)
@run_on_executor()
def add_anno... | class AnnouncementHandler(BaseHandler):
filename = filename
@run_on_executor()
def get_announcement(self):
size = int(self.get_argument("size", "5"))
page = int(self.get_argument("page", "1"))
return self.instance.get_announcement(page, size)
@run_on_executor()
def add_anno... | username = self.get_current_user()
if not self.instance.is_admin(username):
self.set_status(HTTPStatus.FORBIDDEN)
return {"message": "只有管理员可以设置公告"}
payload = self.json
content = payload["content"]
real_ip = self.get_real_ip()
browser = self.reques... | username = self.get_current_user()
if not self.instance.is_admin(username):
self.set_status(HTTPStatus.FORBIDDEN)
return {"message": "只有管理员可以设置公告"}
payload = self.json
content = payload["content"]
real_ip = self.get_real_ip()
browser = self.reques... | 30 | 203 | 163 | 366 | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
import pathlib
import time
from hashlib import sha1
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import ts_date
from databases.base import Redis
from ha... | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
import pathlib
import time
from hashlib import sha1
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import ts_date
from databases.base import Redis
from ha... |
25,661 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/other.py | 167,169 | 160,173 | get | BlacklistHandler | 169,173 | 169,173 | class BlacklistHandler(BaseHandler):
filename = filename
@run_on_executor()
def get_black_list(self):
return self.instance.get_black_list()
@gen.coroutine
def get(self):
FILL_FUNC_BODY | class BlacklistHandler(BaseHandler):
filename = filename
@run_on_executor()
def get_black_list(self):
return self.instance.get_black_list()
@gen.coroutine
def get(self):
FILL_FUNC_BODY | resp = yield self.get_black_list()
self.write(resp)
| resp = yield self.get_black_list()
self.write(resp)
| 5 | 75 | 27 | 102 | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
import pathlib
import time
from hashlib import sha1
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import ts_date
from databases.base import Redis
from ha... | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
import pathlib
import time
from hashlib import sha1
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import ts_date
from databases.base import Redis
from ha... |
25,662 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/other.py | 140,142 | 123,160 | captcha | CaptchaHandler | 142,149 | 142,149 | class CaptchaHandler(BaseHandler):
filename = filename
@run_on_executor()
def verify_captcha(self):
data = self.json
captcha_id = data.get("id", None)
userinput = data.get("captcha", None)
if captcha_id is None or userinput is None:
self.set_status(HTTPStatus.BAD... | class CaptchaHandler(BaseHandler):
filename = filename
@run_on_executor()
def verify_captcha(self):
data = self.json
captcha_id = data.get("id", None)
userinput = data.get("captcha", None)
if captcha_id is None or userinput is None:
self.set_status(HTTPStatus.BAD... | request_id = self.get_argument("id", None)
if request_id is None:
self.set_status(HTTPStatus.BAD_REQUEST)
return "Please supply id parameter."
return self.instance.get_captcha(request_id)
| request_id = self.get_argument("id", None)
if request_id is None:
self.set_status(HTTPStatus.BAD_REQUEST)
return "Please supply id parameter."
return self.instance.get_captcha(request_id)
| 16 | 278 | 75 | 353 | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
import pathlib
import time
from hashlib import sha1
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import ts_date
from databases.base import Redis
from ha... | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
import pathlib
import time
from hashlib import sha1
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import ts_date
from databases.base import Redis
from ha... |
25,663 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/other.py | 109,111 | 106,123 | get_data | CategoryHandler | 111,117 | 111,117 | class CategoryHandler(BaseHandler):
filename = filename
@run_on_executor()
def get_data(self):
FILL_FUNC_BODY @gen.coroutine
def get(self):
resp = yield self.get_data()
self.write(resp)
| class CategoryHandler(BaseHandler):
filename = filename
@run_on_executor()
def get_data(self):
FILL_FUNC_BODY @gen.coroutine
def get(self):
resp = yield self.get_data()
self.write(resp)
| self.json = {k: self.get_argument(k) for k in self.request.arguments}
self.json["size"] = int(self.json.get("size", 15))
self.json["page"] = int(self.json.get("page", 1))
self.json["douban"] = self.json.get("douban", False)
return self.instance.get_category(self.json)
| self.json = {k: self.get_argument(k) for k in self.request.arguments}
self.json["size"] = int(self.json.get("size", 15))
self.json["page"] = int(self.json.get("page", 1))
self.json["douban"] = self.json.get("douban", False)
return self.instance.get_category(self.json)
| 22 | 79 | 116 | 195 | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
import pathlib
import time
from hashlib import sha1
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import ts_date
from databases.base import Redis
from ha... | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
import pathlib
import time
from hashlib import sha1
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import ts_date
from databases.base import Redis
from ha... |
25,664 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/other.py | 79,82 | 58,106 | get_hash | DBDumpHandler | 82,100 | 82,100 | class DBDumpHandler(BaseHandler):
@staticmethod
def sizeof_fmt(num: int, suffix="B"):
for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, "Yi", s... | class DBDumpHandler(BaseHandler):
@staticmethod
def sizeof_fmt(num: int, suffix="B"):
for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, "Yi", s... | file_list = [
"templates/dump/yyets_mongo.gz",
"templates/dump/yyets_mysql.zip",
"templates/dump/yyets_sqlite.zip",
]
result = {}
for fp in file_list:
checksum = self.checksum(fp)
creation = ts_date(os.stat(fp).st_ctime)
... | file_list = [
"templates/dump/yyets_mongo.gz",
"templates/dump/yyets_mysql.zip",
"templates/dump/yyets_sqlite.zip",
]
result = {}
for fp in file_list:
checksum = self.checksum(fp)
creation = ts_date(os.stat(fp).st_ctime)
... | 35 | 304 | 189 | 493 | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
import pathlib
import time
from hashlib import sha1
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import ts_date
from databases.base import Redis
from ha... | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
import pathlib
import time
from hashlib import sha1
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import ts_date
from databases.base import Redis
from ha... |
25,665 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/handlers/other.py | 176,177 | 173,198 | process | SpamProcessHandler | 177,191 | 177,191 | class SpamProcessHandler(BaseHandler):
filename = filename
def process(self, method):
FILL_FUNC_BODY @gen.coroutine
def post(self):
self.write(self.process("restore_spam"))
@gen.coroutine
def delete(self):
self.write(self.process("ban_spam"))
| class SpamProcessHandler(BaseHandler):
filename = filename
def process(self, method):
FILL_FUNC_BODY @gen.coroutine
def post(self):
self.write(self.process("restore_spam"))
@gen.coroutine
def delete(self):
self.write(self.process("ban_spam"))
| obj_id = self.json.get("obj_id")
token = self.json.get("token")
ua = self.request.headers["user-agent"]
ip = self.get_real_ip()
logging.info("Authentication %s(%s) for spam API now...", ua, ip)
if token == os.getenv("TOKEN"):
return getattr(self.instance, meth... | obj_id = self.json.get("obj_id")
token = self.json.get("token")
ua = self.request.headers["user-agent"]
ip = self.get_real_ip()
logging.info("Authentication %s(%s) for spam API now...", ua, ip)
if token == os.getenv("TOKEN"):
return getattr(self.instance, meth... | 44 | 97 | 177 | 274 | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
import pathlib
import time
from hashlib import sha1
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import ts_date
from databases.base import Redis
from ha... | #!/usr/bin/env python3
# coding: utf-8
import logging
import os
import pathlib
import time
from hashlib import sha1
from http import HTTPStatus
from pathlib import Path
from tornado import gen, web
from tornado.concurrent import run_on_executor
from common.utils import ts_date
from databases.base import Redis
from ha... |
25,666 | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot | /home/hieuvd/dung_repo/raw/stars_01/tgbot-collection_YYeTsBot/YYeTsBot/yyetsweb/server.py | 142,144 | 74,160 | run_server | RunServer | 144,160 | 144,160 | class RunServer:
static_path = pathlib.Path(__file__).parent.joinpath("templates")
handlers = [
(r"/", IndexHandler),
(r"/api/resource", ResourceHandler),
(r"/api/resource/latest", ResourceLatestHandler),
(r"/api/top", TopHandler),
(r"/api/like", LikeHandler),
(r"... | class RunServer:
static_path = pathlib.Path(__file__).parent.joinpath("templates")
handlers = [
(r"/", IndexHandler),
(r"/api/resource", ResourceHandler),
(r"/api/resource/latest", ResourceLatestHandler),
(r"/api/top", TopHandler),
(r"/api/like", LikeHandler),
(r"... | tornado_server = httpserver.HTTPServer(RunServer.application, xheaders=True)
tornado_server.bind(port, host)
if os.getenv("PYTHON_DEV"):
tornado_server.start(1)
tornado.autoreload.start()
else:
tornado_server.start(0)
try:
print("S... | tornado_server = httpserver.HTTPServer(RunServer.application, xheaders=True)
tornado_server.bind(port, host)
if os.getenv("PYTHON_DEV"):
tornado_server.start(1)
tornado.autoreload.start()
else:
tornado_server.start(0)
try:
print("S... | 26 | 1,014 | 188 | 1,202 | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - server.py
# 2/5/21 21:02
#
__author__ = "Benny <benny.think@gmail.com>"
import logging
import os
import pathlib
import threading
from zoneinfo import ZoneInfo
import tornado.autoreload
from apscheduler.schedulers.background import BackgroundScheduler
from apsche... | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - server.py
# 2/5/21 21:02
#
__author__ = "Benny <benny.think@gmail.com>"
import logging
import os
import pathlib
import threading
from zoneinfo import ZoneInfo
import tornado.autoreload
from apscheduler.schedulers.background import BackgroundScheduler
from apsche... |
25,736 | /home/hieuvd/dung_repo/raw/stars_01/tiangolo_fastapi/fastapi | /home/hieuvd/dung_repo/raw/stars_01/tiangolo_fastapi/fastapi/docs_src/additional_responses/tutorial001.py | 18,20 | 1,23 | read_item | 20,23 | 20,23 | from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
class Message(BaseModel):
message: str
app = FastAPI()
@app.get("/items/{item_id}", response_model=Item, responses={404: {"model": Message}})
async def read... | from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
class Message(BaseModel):
message: str
app = FastAPI()
@app.get("/items/{item_id}", response_model=Item, responses={404: {"model": Message}})
async def read... | if item_id == "foo":
return {"id": "foo", "value": "there goes my hero"}
return JSONResponse(status_code=404, content={"message": "Item not found"})
| if item_id == "foo":
return {"id": "foo", "value": "there goes my hero"}
return JSONResponse(status_code=404, content={"message": "Item not found"})
| 18 | 122 | 56 | 178 | from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
class Message(BaseModel):
message: str
app = FastAPI()
@app.get("/items/{item_id}", response_model=Item, responses={404: {"model": Message}})
async def read... | from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
class Message(BaseModel):
message: str
app = FastAPI()
@app.get("/items/{item_id}", response_model=Item, responses={404: {"model": Message}})
async def read... | |
25,737 | /home/hieuvd/dung_repo/raw/stars_01/tiangolo_fastapi/fastapi | /home/hieuvd/dung_repo/raw/stars_01/tiangolo_fastapi/fastapi/docs_src/additional_responses/tutorial002.py | 16,27 | 1,31 | read_item | 27,31 | 27,31 | from typing import Union
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
app = FastAPI()
@app.get(
"/items/{item_id}",
response_model=Item,
responses={
200: {
"content": {"image... | from typing import Union
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
app = FastAPI()
@app.get(
"/items/{item_id}",
response_model=Item,
responses={
200: {
"content": {"image... | if img:
return FileResponse("image.png", media_type="image/png")
else:
return {"id": "foo", "value": "there goes my hero"}
| if img:
return FileResponse("image.png", media_type="image/png")
else:
return {"id": "foo", "value": "there goes my hero"}
| 14 | 164 | 50 | 214 | from typing import Union
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
app = FastAPI()
@app.get(
"/items/{item_id}",
response_model=Item,
responses={
200: {
"content": {"image... | from typing import Union
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
app = FastAPI()
@app.get(
"/items/{item_id}",
response_model=Item,
responses={
200: {
"content": {"image... | |
25,738 | /home/hieuvd/dung_repo/raw/stars_01/tiangolo_fastapi/fastapi | /home/hieuvd/dung_repo/raw/stars_01/tiangolo_fastapi/fastapi/docs_src/additional_responses/tutorial003.py | 18,34 | 1,38 | read_item | 34,38 | 34,38 | from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
class Message(BaseModel):
message: str
app = FastAPI()
@app.get(
"/items/{item_id}",
response_model=Item,
responses={
404: {"model": Mes... | from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
class Message(BaseModel):
message: str
app = FastAPI()
@app.get(
"/items/{item_id}",
response_model=Item,
responses={
404: {"model": Mes... | if item_id == "foo":
return {"id": "foo", "value": "there goes my hero"}
else:
return JSONResponse(status_code=404, content={"message": "Item not found"})
| if item_id == "foo":
return {"id": "foo", "value": "there goes my hero"}
else:
return JSONResponse(status_code=404, content={"message": "Item not found"})
| 19 | 207 | 61 | 268 | from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
class Message(BaseModel):
message: str
app = FastAPI()
@app.get(
"/items/{item_id}",
response_model=Item,
responses={
404: {"model": Mes... | from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
class Message(BaseModel):
message: str
app = FastAPI()
@app.get(
"/items/{item_id}",
response_model=Item,
responses={
404: {"model": Mes... | |
25,739 | /home/hieuvd/dung_repo/raw/stars_01/tiangolo_fastapi/fastapi | /home/hieuvd/dung_repo/raw/stars_01/tiangolo_fastapi/fastapi/docs_src/additional_responses/tutorial004.py | 23,29 | 1,33 | read_item | 29,33 | 29,33 | from typing import Union
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
responses = {
404: {"description": "Item not found"},
302: {"description": "The item was moved"},
403: {"description": "Not en... | from typing import Union
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
responses = {
404: {"description": "Item not found"},
302: {"description": "The item was moved"},
403: {"description": "Not en... | if img:
return FileResponse("image.png", media_type="image/png")
else:
return {"id": "foo", "value": "there goes my hero"}
| if img:
return FileResponse("image.png", media_type="image/png")
else:
return {"id": "foo", "value": "there goes my hero"}
| 14 | 197 | 50 | 247 | from typing import Union
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
responses = {
404: {"description": "Item not found"},
302: {"description": "The item was moved"},
403: {"description": "Not en... | from typing import Union
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
responses = {
404: {"description": "Item not found"},
302: {"description": "The item was moved"},
403: {"description": "Not en... | |
25,740 | /home/hieuvd/dung_repo/raw/stars_01/tiangolo_fastapi/fastapi | /home/hieuvd/dung_repo/raw/stars_01/tiangolo_fastapi/fastapi/docs_src/additional_status_codes/tutorial001.py | 11,17 | 1,26 | upsert_item | 17,26 | 17,26 | from typing import Union
from fastapi import Body, FastAPI, status
from fastapi.responses import JSONResponse
app = FastAPI()
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
@app.put("/items/{item_id}")
async def upsert_item(
item_id: str,
name: Union[str, None] = Bo... | from typing import Union
from fastapi import Body, FastAPI, status
from fastapi.responses import JSONResponse
app = FastAPI()
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
@app.put("/items/{item_id}")
async def upsert_item(
item_id: str,
name: Union[str, None] = Bo... | if item_id in items:
item = items[item_id]
item["name"] = name
item["size"] = size
return item
else:
item = {"name": name, "size": size}
items[item_id] = item
return JSONResponse(status_code=status.HTTP_201_CREATED, content=item)
| if item_id in items:
item = items[item_id]
item["name"] = name
item["size"] = size
return item
else:
item = {"name": name, "size": size}
items[item_id] = item
return JSONResponse(status_code=status.HTTP_201_CREATED, content=item)
| 28 | 148 | 101 | 249 | from typing import Union
from fastapi import Body, FastAPI, status
from fastapi.responses import JSONResponse
app = FastAPI()
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
@app.put("/items/{item_id}")
async def upsert_item(
item_id: str,
name: Union[str, None] = Bo... | from typing import Union
from fastapi import Body, FastAPI, status
from fastapi.responses import JSONResponse
app = FastAPI()
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
@app.put("/items/{item_id}")
async def upsert_item(
item_id: str,
name: Union[str, None] = Bo... | |
25,741 | /home/hieuvd/dung_repo/raw/stars_01/tiangolo_fastapi/fastapi | /home/hieuvd/dung_repo/raw/stars_01/tiangolo_fastapi/fastapi/docs_src/additional_status_codes/tutorial001_an.py | 12,18 | 1,27 | upsert_item | 18,27 | 18,27 | from typing import Union
from fastapi import Body, FastAPI, status
from fastapi.responses import JSONResponse
from typing_extensions import Annotated
app = FastAPI()
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
@app.put("/items/{item_id}")
async def upsert_item(
item_... | from typing import Union
from fastapi import Body, FastAPI, status
from fastapi.responses import JSONResponse
from typing_extensions import Annotated
app = FastAPI()
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
@app.put("/items/{item_id}")
async def upsert_item(
item_... | if item_id in items:
item = items[item_id]
item["name"] = name
item["size"] = size
return item
else:
item = {"name": name, "size": size}
items[item_id] = item
return JSONResponse(status_code=status.HTTP_201_CREATED, content=item)
| if item_id in items:
item = items[item_id]
item["name"] = name
item["size"] = size
return item
else:
item = {"name": name, "size": size}
items[item_id] = item
return JSONResponse(status_code=status.HTTP_201_CREATED, content=item)
| 28 | 165 | 101 | 266 | from typing import Union
from fastapi import Body, FastAPI, status
from fastapi.responses import JSONResponse
from typing_extensions import Annotated
app = FastAPI()
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
@app.put("/items/{item_id}")
async def upsert_item(
item_... | from typing import Union
from fastapi import Body, FastAPI, status
from fastapi.responses import JSONResponse
from typing_extensions import Annotated
app = FastAPI()
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
@app.put("/items/{item_id}")
async def upsert_item(
item_... | |
25,742 | /home/hieuvd/dung_repo/raw/stars_01/tiangolo_fastapi/fastapi | /home/hieuvd/dung_repo/raw/stars_01/tiangolo_fastapi/fastapi/docs_src/additional_status_codes/tutorial001_an_py310.py | 11,17 | 1,26 | upsert_item | 17,26 | 17,26 | from typing import Annotated
from fastapi import Body, FastAPI, status
from fastapi.responses import JSONResponse
app = FastAPI()
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
@app.put("/items/{item_id}")
async def upsert_item(
item_id: str,
name: Annotated[str | N... | from typing import Annotated
from fastapi import Body, FastAPI, status
from fastapi.responses import JSONResponse
app = FastAPI()
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
@app.put("/items/{item_id}")
async def upsert_item(
item_id: str,
name: Annotated[str | N... | if item_id in items:
item = items[item_id]
item["name"] = name
item["size"] = size
return item
else:
item = {"name": name, "size": size}
items[item_id] = item
return JSONResponse(status_code=status.HTTP_201_CREATED, content=item)
| if item_id in items:
item = items[item_id]
item["name"] = name
item["size"] = size
return item
else:
item = {"name": name, "size": size}
items[item_id] = item
return JSONResponse(status_code=status.HTTP_201_CREATED, content=item)
| 28 | 152 | 101 | 253 | from typing import Annotated
from fastapi import Body, FastAPI, status
from fastapi.responses import JSONResponse
app = FastAPI()
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
@app.put("/items/{item_id}")
async def upsert_item(
item_id: str,
name: Annotated[str | N... | from typing import Annotated
from fastapi import Body, FastAPI, status
from fastapi.responses import JSONResponse
app = FastAPI()
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
@app.put("/items/{item_id}")
async def upsert_item(
item_id: str,
name: Annotated[str | N... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.