path
stringlengths 9
117
| type
stringclasses 2
values | project
stringclasses 10
values | commit_hash
stringlengths 40
40
| commit_message
stringlengths 1
137
| ground_truth
stringlengths 0
2.74k
| main_code
stringlengths 102
3.37k
| context
stringlengths 0
14.7k
|
---|---|---|---|---|---|---|---|
backend.src.publisher.aggregation.user.commits/get_top_repos
|
Modified
|
avgupta456~github-trends
|
1485ea60f454a3ddbce3bcdb166c32046a560aad
|
Sort Repo Card Bars (#197)
|
# module: backend.src.publisher.aggregation.user.commits
def get_top_repos(
data: UserPackage, loc_metric: str, include_private: bool, group: str
) -> Tuple[List[RepoStats], int]:
<0> repos: List[Any] = [
<1> {
<2> "repo": repo,
<3> "private": repo_stats.private,
<4> "langs": [
<5> {
<6> "lang": x[0],
<7> "color": x[1].color,
<8> "loc": loc_metric_func(loc_metric, x[1].additions, x[1].deletions),
<9> }
<10> for x in list(repo_stats.languages.items())
<11> ],
<12> }
<13> for repo, repo_stats in data.contribs.repo_stats.items()
<14> if include_private or not repo_stats.private
<15> ]
<16>
<17> for repo in repos:
<18> repo["loc"] = sum(x["loc"] for x in repo["langs"]) # first estimate
<19> repos = list(filter(lambda x: x["loc"] > 0, repos))
<20>
<21> for repo in repos:
<22> repo["langs"] = [x for x in repo["langs"] if x["loc"] > 0.05 * repo["loc"]]
<23> repo["loc"] = sum(x["loc"] for x in repo["langs"]) # final estimate
<24> repos = sorted(repos, key=lambda x: x["loc"], reverse=True)
<25>
<26> new_repos = [
<27> RepoStats.parse_obj(x) for x in repos if x["loc"] > 0.01 * repos[0]["loc"]
<28> ]
<29>
<30> commits_excluded = data.contribs.public_stats.other_count
<31> if include_private:
<32> commits_excluded = data.contribs.total_stats.other_count
<33>
<34> # With n bars, group from n onwards into the last bar
<35> bars = 4 # TODO: make this configurable (see issues)
<36>
<37> </s>
|
===========below chunk 0===========
# module: backend.src.publisher.aggregation.user.commits
def get_top_repos(
data: UserPackage, loc_metric: str, include_private: bool, group: str
) -> Tuple[List[RepoStats], int]:
# offset: 1
return new_repos[:bars], commits_excluded
out_repos = []
other_repos = []
if group == "other":
out_repos = new_repos[: bars - 1]
other_repos = new_repos[bars - 1 :]
elif group == "private":
public_repos = [x for x in new_repos if not x.private]
private_repos = [x for x in new_repos if x.private]
if len(public_repos) < 4 and len(private_repos) > 0:
public_repos += private_repos[: bars - len(public_repos) - 1]
private_repos = private_repos[bars - len(public_repos) - 1 :]
out_repos = public_repos[: bars - 1]
other_repos = public_repos[bars - 1 :] + private_repos
else:
raise ValueError("Invalid group value")
other: Dict[str, Tuple[int, Optional[str]]] = {}
for repo in other_repos:
for _lang in repo.langs:
lang = _lang.lang
if lang not in other:
other[lang] = (0, _lang.color)
other[lang] = (other[lang][0] + _lang.loc, other[lang][1])
out_repos.append(
RepoStats(
repo="other/repos",
private=False,
langs=[{"lang": k, "loc": v[0], "color": v[1]} for k, v in other.items()],
loc=sum(v[0] for v in other.values()),
)
)
return out_repos, commits_excluded
===========unchanged ref 0===========
at: backend.src.publisher.aggregation.user.commits
loc_metric_func(loc_metric: str, additions: int, deletions: int) -> int
at: src.models.user.contribs.ContributionStats
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.Language
color: Optional[str]
additions: int
deletions: int
at: src.models.user.contribs.RepoContributionStats
private: bool
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
public_stats: ContributionStats
total: List[ContributionDay]
public: List[ContributionDay]
repo_stats: Dict[str, RepoContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
|
|
backend.src.publisher.processing.user.auth/authenticate
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<8>:<add> "private_access": private_access,
<10>:<del> raw_user["private_access"] = private_access
|
# module: backend.src.publisher.processing.user.auth
def authenticate(code: str, private_access: bool) -> str:
<0> user_id, access_token = await github_authenticate(code)
<1>
<2> curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
<3>
<4> raw_user: Dict[str, Any] = {
<5> "user_id": user_id,
<6> "access_token": access_token,
<7> "user_key": code_key_map.get(code, None),
<8> }
<9>
<10> raw_user["private_access"] = private_access
<11> if curr_user is not None:
<12> curr_private_access = curr_user.private_access
<13> new_private_access = curr_private_access or private_access
<14> raw_user["private_access"] = new_private_access
<15>
<16> if new_private_access != curr_private_access:
<17> await update_user(user_id, access_token, new_private_access)
<18> else:
<19> # first time sign up
<20> await update_user(user_id, access_token, private_access)
<21>
<22> await db_update_user(user_id, raw_user)
<23> return user_id
<24>
|
===========unchanged ref 0===========
at: backend.src.publisher.processing.user.auth
code_key_map: Dict[str, str] = {}
at: src.data.github.auth.main
authenticate(code: str) -> Tuple[str, str]
at: src.data.mongo.user.functions
update_user(user_id: str, raw_user: Dict[str, Any]) -> None
at: src.data.mongo.user.get
Callable(*args: List[Any], **kwargs: Dict[str, Any]) -> Any
at: src.data.mongo.user.models.PublicUserModel
user_id: str
access_token: str
private_access: Optional[bool]
at: src.publisher.processing.user.get_data
Callable(*args: List[Any], **kwargs: Dict[str, Any]) -> Any
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
|
backend.src.subscriber.aggregation.wrapped.timestamps/get_timestamp_data
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<5>:<del> for obj in list:
<6>:<add> out.extend(
<del> out.append(
<7>:<add> {
<del> {
<8>:<add> "type": type,
<del> "type": type,
<9>:<add> "weekday": item.weekday,
<del> "weekday": item.weekday,
<10>:<add> "timestamp": date_to_seconds_since_midnight(obj),
<del> "timestamp": date_to_seconds_since_midnight(obj),
<11>:<del> }
<12>:<add> }
<del> )
<13>:<add> for obj in list
<add> )
|
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
<0> out: List[Any] = []
<1> for item in data.contribs.total:
<2> lists = item.lists
<3> lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
<4> for type, list in zip(["commit", "issue", "pr", "review"], lists):
<5> for obj in list:
<6> out.append(
<7> {
<8> "type": type,
<9> "weekday": item.weekday,
<10> "timestamp": date_to_seconds_since_midnight(obj),
<11> }
<12> )
<13>
<14> shuffle(out)
<15> out = out[:MAX_ITEMS]
<16> out = [TimestampDatum.parse_obj(x) for x in out]
<17>
<18> return TimestampData(contribs=out)
<19>
|
===========unchanged ref 0===========
at: backend.src.subscriber.aggregation.wrapped.timestamps
MAX_ITEMS = 200
date_to_seconds_since_midnight(date: datetime) -> int
at: random
shuffle = _inst.shuffle
at: src.models.user.contribs.ContributionDay
date: str
weekday: int
stats: ContributionStats
lists: ContributionLists
at: src.models.user.contribs.ContributionLists
commits: List[datetime]
issues: List[datetime]
prs: List[datetime]
reviews: List[datetime]
repos: List[datetime]
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
public_stats: ContributionStats
total: List[ContributionDay]
public: List[ContributionDay]
repo_stats: Dict[str, RepoContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.publisher.processing.user.auth
def authenticate(code: str, private_access: bool) -> str:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
+ "private_access": private_access,
}
- raw_user["private_access"] = private_access
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
await update_user(user_id, access_token, new_private_access)
else:
# first time sign up
await update_user(user_id, access_token, private_access)
await db_update_user(user_id, raw_user)
return user_id
|
backend.src.data.github.rest.repo/get_repo_commits
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<14>:<add> query += f"&since={str(since)}"
<del> query += "&since=" + str(since)
<16>:<add> query += f"&until={str(until)}"
<del> query += "&until=" + str(until)
|
# module: backend.src.data.github.rest.repo
def get_repo_commits(
owner: str,
repo: str,
user: Optional[str] = None,
since: Optional[datetime] = None,
until: Optional[datetime] = None,
page: int = 1,
access_token: Optional[str] = None,
) -> List[RawCommit]:
<0> """
<1> Returns most recent commits
<2> :param access_token: GitHub access token
<3> :param owner: repository owner
<4> :param repo: repository name
<5> :param user: optional GitHub user if not owner
<6> :param since: optional datetime to start from
<7> :param until: optional datetime to end at
<8> :param page: optional page number
<9> :return: Up to 100 commits from page
<10> """
<11> user = user if user is not None else owner
<12> query = BASE_URL + owner + "/" + repo + "/commits?author=" + user
<13> if since is not None:
<14> query += "&since=" + str(since)
<15> if until is not None:
<16> query += "&until=" + str(until)
<17> try:
<18> data = get_template_plural(query, access_token, page=page)
<19>
<20> def extract_info(x: Any) -> RawCommit:
<21> dt = x["commit"]["committer"]["date"]
<22> temp = {
<23> "timestamp": datetime.strptime(dt, "%Y-%m-%dT%H:%M:%SZ"),
<24> "node_id": x["node_id"],
<25> }
<26> return RawCommit.parse_obj(temp)
<27>
<28> return list(map(extract_info, data))
<29> except RESTError:
<30> return []
<31> except Exception as e:
<32> logging.exception(e)
<33> return []
<34>
|
===========unchanged ref 0===========
at: backend.src.data.github.rest.repo
BASE_URL = "https://api.github.com/repos/"
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
strptime(date_string: _Text, format: _Text) -> datetime
__radd__ = __add__
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: src.data.github.rest.template
RESTError(*args: object)
get_template_plural(query: str, access_token: Optional[str]=None, per_page: int=100, page: int=1, accept_header: str="application/vnd.github.v3+json") -> List[Dict[str, Any]]
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
===========changed ref 1===========
# module: backend.src.publisher.processing.user.auth
def authenticate(code: str, private_access: bool) -> str:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
+ "private_access": private_access,
}
- raw_user["private_access"] = private_access
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
await update_user(user_id, access_token, new_private_access)
else:
# first time sign up
await update_user(user_id, access_token, private_access)
await db_update_user(user_id, raw_user)
return user_id
|
backend.src.subscriber.aggregation.wrapped.time/get_month_data
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<8>:<add> x.additions + x.deletions for x in item.stats.languages.values()
<del> [x.additions + x.deletions for x in item.stats.languages.values()]
<10>:<add>
<15>:<add> _obj: Dict[str, Union[str, int]] = {
<del> _obj: Dict[str, Union[str, int]] = {"index": k, **v}
<16>:<add> "index": k,
<add> **v,
<add> "formatted_loc_changed": format_number(v["loc_changed"]),
<del> _obj["formatted_loc_changed"] = format_number(v["loc_changed"])
<17>:<add> }
<add>
|
# module: backend.src.subscriber.aggregation.wrapped.time
def get_month_data(data: UserPackage) -> MonthData:
<0> months: Dict[int, Dict[str, int]] = defaultdict(
<1> lambda: {"contribs": 0, "loc_changed": 0}
<2> )
<3>
<4> for item in data.contribs.total:
<5> month = datetime.fromisoformat(item.date).month - 1
<6> months[month]["contribs"] += item.stats.contribs_count
<7> loc_changed = sum(
<8> [x.additions + x.deletions for x in item.stats.languages.values()]
<9> )
<10> months[month]["loc_changed"] += loc_changed
<11>
<12> out: List[TimeDatum] = []
<13> for k in range(12):
<14> v = months[k]
<15> _obj: Dict[str, Union[str, int]] = {"index": k, **v}
<16> _obj["formatted_loc_changed"] = format_number(v["loc_changed"])
<17> out.append(TimeDatum.parse_obj(_obj))
<18>
<19> return MonthData(months=out)
<20>
|
===========unchanged ref 0===========
at: collections
defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]])
defaultdict(default_factory: Optional[Callable[[], _VT]])
defaultdict(**kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT])
at: datetime
datetime()
at: datetime.date
__slots__ = '_year', '_month', '_day', '_hashcode'
__str__ = isoformat
__radd__ = __add__
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
fromisoformat(date_string: str) -> _S
__radd__ = __add__
at: src.models.user.contribs.ContributionDay
date: str
weekday: int
stats: ContributionStats
lists: ContributionLists
at: src.models.user.contribs.ContributionStats
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.Language
color: Optional[str]
additions: int
deletions: int
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
public_stats: ContributionStats
total: List[ContributionDay]
===========unchanged ref 1===========
public: List[ContributionDay]
repo_stats: Dict[str, RepoContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
at: src.utils.utils
format_number(num: int) -> str
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
===========changed ref 1===========
# module: backend.src.publisher.processing.user.auth
def authenticate(code: str, private_access: bool) -> str:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
+ "private_access": private_access,
}
- raw_user["private_access"] = private_access
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
await update_user(user_id, access_token, new_private_access)
else:
# first time sign up
await update_user(user_id, access_token, private_access)
await db_update_user(user_id, raw_user)
return user_id
===========changed ref 2===========
# module: backend.src.data.github.rest.repo
def get_repo_commits(
owner: str,
repo: str,
user: Optional[str] = None,
since: Optional[datetime] = None,
until: Optional[datetime] = None,
page: int = 1,
access_token: Optional[str] = None,
) -> List[RawCommit]:
"""
Returns most recent commits
:param access_token: GitHub access token
:param owner: repository owner
:param repo: repository name
:param user: optional GitHub user if not owner
:param since: optional datetime to start from
:param until: optional datetime to end at
:param page: optional page number
:return: Up to 100 commits from page
"""
user = user if user is not None else owner
query = BASE_URL + owner + "/" + repo + "/commits?author=" + user
if since is not None:
+ query += f"&since={str(since)}"
- query += "&since=" + str(since)
if until is not None:
+ query += f"&until={str(until)}"
- query += "&until=" + str(until)
try:
data = get_template_plural(query, access_token, page=page)
def extract_info(x: Any) -> RawCommit:
dt = x["commit"]["committer"]["date"]
temp = {
"timestamp": datetime.strptime(dt, "%Y-%m-%dT%H:%M:%SZ"),
"node_id": x["node_id"],
}
return RawCommit.parse_obj(temp)
return list(map(extract_info, data))
except RESTError:
return []
except Exception as e:
logging.exception(e)
return []
|
backend.src.subscriber.aggregation.wrapped.time/get_day_data
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<8>:<add> x.additions + x.deletions for x in item.stats.languages.values()
<del> [x.additions + x.deletions for x in item.stats.languages.values()]
<10>:<add>
<15>:<add> _obj: Dict[str, Union[str, int]] = {
<del> _obj: Dict[str, Union[str, int]] = {"index": k, **v}
<16>:<add> "index": k,
<add> **v,
<add> "formatted_loc_changed": format_number(v["loc_changed"]),
<del> _obj["formatted_loc_changed"] = format_number(v["loc_changed"])
<17>:<add> }
<add>
|
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
<0> days: Dict[int, Dict[str, int]] = defaultdict(
<1> lambda: {"contribs": 0, "loc_changed": 0}
<2> )
<3>
<4> for item in data.contribs.total:
<5> day = datetime.fromisoformat(item.date).weekday()
<6> days[day]["contribs"] += item.stats.contribs_count
<7> loc_changed = sum(
<8> [x.additions + x.deletions for x in item.stats.languages.values()]
<9> )
<10> days[day]["loc_changed"] += loc_changed
<11>
<12> out: List[TimeDatum] = []
<13> for k in range(7):
<14> v = days[k]
<15> _obj: Dict[str, Union[str, int]] = {"index": k, **v}
<16> _obj["formatted_loc_changed"] = format_number(v["loc_changed"])
<17> out.append(TimeDatum.parse_obj(_obj))
<18>
<19> return DayData(days=out)
<20>
|
===========unchanged ref 0===========
at: backend.src.subscriber.aggregation.wrapped.time.get_month_data
out: List[TimeDatum] = []
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
at: collections
defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]])
defaultdict(default_factory: Optional[Callable[[], _VT]])
defaultdict(**kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT])
at: datetime
datetime()
at: datetime.date
weekday() -> int
at: datetime.datetime
fromisoformat(date_string: str) -> _S
at: src.models.user.contribs.ContributionDay
date: str
stats: ContributionStats
at: src.models.user.contribs.ContributionStats
contribs_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.Language
additions: int
deletions: int
at: src.models.user.contribs.UserContributions
total: List[ContributionDay]
at: src.models.user.main.UserPackage
contribs: UserContributions
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_month_data(data: UserPackage) -> MonthData:
months: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
month = datetime.fromisoformat(item.date).month - 1
months[month]["contribs"] += item.stats.contribs_count
loc_changed = sum(
+ x.additions + x.deletions for x in item.stats.languages.values()
- [x.additions + x.deletions for x in item.stats.languages.values()]
)
+
months[month]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(12):
v = months[k]
+ _obj: Dict[str, Union[str, int]] = {
- _obj: Dict[str, Union[str, int]] = {"index": k, **v}
+ "index": k,
+ **v,
+ "formatted_loc_changed": format_number(v["loc_changed"]),
- _obj["formatted_loc_changed"] = format_number(v["loc_changed"])
+ }
+
out.append(TimeDatum.parse_obj(_obj))
return MonthData(months=out)
===========changed ref 1===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
===========changed ref 2===========
# module: backend.src.publisher.processing.user.auth
def authenticate(code: str, private_access: bool) -> str:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
+ "private_access": private_access,
}
- raw_user["private_access"] = private_access
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
await update_user(user_id, access_token, new_private_access)
else:
# first time sign up
await update_user(user_id, access_token, private_access)
await db_update_user(user_id, raw_user)
return user_id
===========changed ref 3===========
# module: backend.src.data.github.rest.repo
def get_repo_commits(
owner: str,
repo: str,
user: Optional[str] = None,
since: Optional[datetime] = None,
until: Optional[datetime] = None,
page: int = 1,
access_token: Optional[str] = None,
) -> List[RawCommit]:
"""
Returns most recent commits
:param access_token: GitHub access token
:param owner: repository owner
:param repo: repository name
:param user: optional GitHub user if not owner
:param since: optional datetime to start from
:param until: optional datetime to end at
:param page: optional page number
:return: Up to 100 commits from page
"""
user = user if user is not None else owner
query = BASE_URL + owner + "/" + repo + "/commits?author=" + user
if since is not None:
+ query += f"&since={str(since)}"
- query += "&since=" + str(since)
if until is not None:
+ query += f"&until={str(until)}"
- query += "&until=" + str(until)
try:
data = get_template_plural(query, access_token, page=page)
def extract_info(x: Any) -> RawCommit:
dt = x["commit"]["committer"]["date"]
temp = {
"timestamp": datetime.strptime(dt, "%Y-%m-%dT%H:%M:%SZ"),
"node_id": x["node_id"],
}
return RawCommit.parse_obj(temp)
return list(map(extract_info, data))
except RESTError:
return []
except Exception as e:
logging.exception(e)
return []
|
backend.src.publisher.render.style/get_style
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
# module: backend.src.publisher.render.style
def get_style(theme: str = "classic", use_animation: bool = True) -> str:
<0> # List[Tuple["selector", List[Tuple["property", "is_animation"]], "is_animation"]]
<1> _style: List[Tuple[str, List[Tuple[str, bool]], bool]] = [
<2> (
<3> ".header",
<4> [
<5> ("font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;", False),
<6> ("fill: " + themes[theme]["header_color"] + ";", False),
<7> ("animation: fadeInAnimation 0.8s ease-in-out forwards;", True),
<8> ],
<9> False,
<10> ),
<11> (
<12> ".subheader",
<13> [
<14> ("font: 500 10px 'Segoe UI', Ubuntu, Sans-Serif;", False),
<15> ("fill: " + themes[theme]["subheader_color"] + ";", False),
<16> ("animation: fadeInAnimation 0.8s ease-in-out forwards;", True),
<17> ],
<18> False,
<19> ),
<20> (
<21> ".lang-name",
<22> [
<23> ("font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;", False),
<24> ("fill: " + themes[theme]["text_color"] + ";", False),
<25> ],
<26> False,
<27> ),
<28> (
<29> ".image-text",
<30> [
<31> ("font: 500 20px 'Segoe UI', Ubuntu, Sans-Serif;", False),
<32> ("fill: " + themes[theme]["text_color"] + ";", False),
<33> ("opacity: 50%;", False),
<34> ],
<35> False,
<36> ),
<37> (
<38> "@keyframes fadeInAnimation",
<39> [("from { opacity: 0; } to { opacity: 1; }", True)],
<40> True,
<41> </s>
|
===========below chunk 0===========
# module: backend.src.publisher.render.style
def get_style(theme: str = "classic", use_animation: bool = True) -> str:
# offset: 1
]
return "\n".join(
[
rule[0].replace(".", "." + theme + "-")
+ " {"
+ "\n".join(item[0] for item in rule[1] if (use_animation or not item[1]))
+ "}"
for rule in _style
if use_animation or not rule[2]
]
)
===========unchanged ref 0===========
at: backend.src.publisher.render.style
themes = {
"classic": {
"header_color": "#2f80ed",
"subheader_color": "#666",
"text_color": "#333",
"bg_color": "#fffefe",
"border_color": "#e4e2e2",
"bar_color": "#ddd",
},
"dark": {
"header_color": "#fff",
"subheader_color": "#9f9f9f",
"text_color": "#9f9f9f",
"bg_color": "#151515",
"border_color": "#e4e2e2",
"bar_color": "#333",
},
"bright_lights": {
"header_color": "#fff",
"subheader_color": "#0e86d4",
"text_color": "#b1d4e0",
"bg_color": "#003060",
"border_color": "#0e86d4",
"bar_color": "#ddd",
},
"rosettes": {
"header_color": "#fff",
"subheader_color": "#b6e2d3",
"text_color": "#fae8e0",
"bg_color": "#ef7c8e",
"border_color": "#b6e2d3",
"bar_color": "#ddd",
},
"ferns": {
"header_color": "#116530",
"subheader_color": "#18a558",
"text_color": "#116530",
"bg_color": "#a3ebb1",
"border_color": "#21b6a8",
"bar_color": "#ddd",
},
"synthwaves": {
"header_color": "#e2e9ec",
"subheader_color": "#e5289e",
"text_color": "#ef8539",
"bg_color":</s>
===========unchanged ref 1===========
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
===========changed ref 1===========
# module: backend.src.publisher.processing.user.auth
def authenticate(code: str, private_access: bool) -> str:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
+ "private_access": private_access,
}
- raw_user["private_access"] = private_access
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
await update_user(user_id, access_token, new_private_access)
else:
# first time sign up
await update_user(user_id, access_token, private_access)
await db_update_user(user_id, raw_user)
return user_id
===========changed ref 2===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
days: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
day = datetime.fromisoformat(item.date).weekday()
days[day]["contribs"] += item.stats.contribs_count
loc_changed = sum(
+ x.additions + x.deletions for x in item.stats.languages.values()
- [x.additions + x.deletions for x in item.stats.languages.values()]
)
+
days[day]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(7):
v = days[k]
+ _obj: Dict[str, Union[str, int]] = {
- _obj: Dict[str, Union[str, int]] = {"index": k, **v}
+ "index": k,
+ **v,
+ "formatted_loc_changed": format_number(v["loc_changed"]),
- _obj["formatted_loc_changed"] = format_number(v["loc_changed"])
+ }
+
out.append(TimeDatum.parse_obj(_obj))
return DayData(days=out)
|
|
backend.src.subscriber.aggregation.user.languages/get_commit_languages
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<19>:<add> total_changed = sum(x.additions + x.deletions for x in pr_files)
<del> total_changed = sum([x.additions + x.deletions for x in pr_files])
<26>:<add> lang = EXTENSIONS.get(f".{extension}", None)
<del> lang = EXTENSIONS.get("." + extension, None)
<32>:<del> pr = commit.prs.nodes[0]
<33>:<del> total_additions, total_deletions = 0, 0
<34>:<del> for file in pr.files.nodes:
<35>:<del> filename = file.path.split(".")
<36>:<del> extension = "" if len(filename) <= 1 else filename[-1]
|
# module: backend.src.subscriber.aggregation.user.languages
def get_commit_languages(
commit: Optional[RawCommit],
files: Optional[List[RawCommitFile]],
repo: RawRepo,
) -> CommitLanguages:
<0> out = CommitLanguages()
<1>
<2> if commit is None:
<3> return out
<4>
<5> if max(commit.additions, commit.deletions) == 0:
<6> return out
<7>
<8> # assummed to be auto-generated or copied
<9> if max(commit.additions, commit.deletions) > 10 * CUTOFF or (
<10> max(commit.additions, commit.deletions) > CUTOFF
<11> and min(commit.additions, commit.deletions) == 0
<12> ):
<13> return out
<14>
<15> pr_coverage = 0
<16> if len(commit.prs.nodes) > 0:
<17> pr_obj = commit.prs.nodes[0]
<18> pr_files = pr_obj.files.nodes
<19> total_changed = sum([x.additions + x.deletions for x in pr_files])
<20> pr_coverage = total_changed / max(1, (pr_obj.additions + pr_obj.deletions))
<21>
<22> if files is not None:
<23> for file in files:
<24> filename = file.filename.split(".")
<25> extension = "" if len(filename) <= 1 else filename[-1]
<26> lang = EXTENSIONS.get("." + extension, None)
<27> if lang is not None:
<28> out.add_lines(
<29> lang["name"], lang["color"], file.additions, file.deletions
<30> )
<31> elif len(commit.prs.nodes) > 0 and pr_coverage > 0.25:
<32> pr = commit.prs.nodes[0]
<33> total_additions, total_deletions = 0, 0
<34> for file in pr.files.nodes:
<35> filename = file.path.split(".")
<36> extension = "" if len(filename) <= 1 else filename[-1]
</s>
|
===========below chunk 0===========
# module: backend.src.subscriber.aggregation.user.languages
def get_commit_languages(
commit: Optional[RawCommit],
files: Optional[List[RawCommitFile]],
repo: RawRepo,
) -> CommitLanguages:
# offset: 1
if lang is not None:
out.add_lines(
lang["name"], lang["color"], file.additions, file.deletions
)
total_additions += file.additions
total_deletions += file.deletions
add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
out.normalize(add_ratio, del_ratio)
elif commit.additions + commit.deletions > 2 * CUTOFF:
# assummed to be auto generated
return out
else:
repo_info = repo.languages.edges
languages = [x for x in repo_info if x.node.name not in BLACKLIST]
total_repo_size = sum([language.size for language in languages])
for language in languages:
lang_name = language.node.name
lang_color = language.node.color
lang_size = language.size
additions = round(commit.additions * lang_size / total_repo_size)
deletions = round(commit.deletions * lang_size / total_repo_size)
out.add_lines(lang_name, lang_color, additions, deletions)
return out
===========unchanged ref 0===========
at: backend.src.subscriber.aggregation.user.languages
EXTENSIONS: Dict[str, Dict[str, str]] = load(open("./src/data/github/extensions.json"))
CommitLanguages()
at: backend.src.subscriber.aggregation.user.languages.CommitLanguages
add_lines(name: str, color: Optional[str], additions: int, deletions: int)
at: src.constants
CUTOFF = 1000 # if additions or deletions > CUTOFF, or sum > 2 * CUTOFF, ignore LOC
BLACKLIST = ["Jupyter Notebook", "HTML"] # languages to ignore
at: src.data.github.graphql.models.RawCommit
additions: int
deletions: int
changed_files: int = Field(alias="changedFiles")
url: str
prs: RawCommitPR = Field(alias="associatedPullRequests")
at: src.data.github.graphql.models.RawCommitPR
nodes: List[RawCommitPRNode]
at: src.data.github.graphql.models.RawCommitPRFile
nodes: List[RawCommitPRFileNode]
at: src.data.github.graphql.models.RawCommitPRFileNode
path: str
additions: int
deletions: int
at: src.data.github.graphql.models.RawCommitPRNode
changed_files: int = Field(alias="changedFiles")
additions: int
deletions: int
files: RawCommitPRFile
at: src.data.github.graphql.models.RawRepo
is_private: bool = Field(alias="isPrivate")
fork_count: int = Field(alias="forkCount")
stargazer_count: int = Field(alias="stargazerCount")
languages: RawRepoLanguage
at: src.data.github.graphql.models.RawRepoLanguage
total_count: int = Field(alias="totalCount")
total_size: int = Field(alias="totalSize")
===========unchanged ref 1===========
edges: List[RawRepoLanguageEdge]
at: src.data.github.graphql.models.RawRepoLanguageEdge
node: RawRepoLanguageNode
size: int
at: src.data.github.graphql.models.RawRepoLanguageNode
name: str
color: Optional[str]
at: src.data.github.rest.models.RawCommitFile
filename: str
additions: int
deletions: int
at: typing
List = _alias(list, 1, inst=False, name='List')
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
===========changed ref 1===========
# module: backend.src.publisher.processing.user.auth
def authenticate(code: str, private_access: bool) -> str:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
+ "private_access": private_access,
}
- raw_user["private_access"] = private_access
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
await update_user(user_id, access_token, new_private_access)
else:
# first time sign up
await update_user(user_id, access_token, private_access)
await db_update_user(user_id, raw_user)
return user_id
|
backend.src.data.github.auth.main/get_unknown_user
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<6>:<add> "Accept": "application/vnd.github.v3+json",
<del> "Accept": str("application/vnd.github.v3+json"),
<7>:<add> "Authorization": f"bearer {access_token}",
<del> "Authorization": "bearer " + access_token,
|
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
<0> """
<1> Accepts access_token and returns user_id of associated user
<2> :param access_token: GitHub access token
<3> :return: user_id or None if invalid access_token
<4> """
<5> headers: Dict[str, str] = {
<6> "Accept": str("application/vnd.github.v3+json"),
<7> "Authorization": "bearer " + access_token,
<8> }
<9>
<10> r = s.get("https://api.github.com/user", params={}, headers=headers)
<11> return r.json().get("login", None) # type: ignore
<12>
|
===========unchanged ref 0===========
at: backend.src.data.github.auth.main
s = requests.session()
at: requests.models.Response
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
json(**kwargs) -> Any
at: requests.sessions.Session
__attrs__ = [
"headers",
"cookies",
"auth",
"proxies",
"hooks",
"params",
"verify",
"cert",
"adapters",
"stream",
"trust_env",
"max_redirects",
]
get(url: Union[Text, bytes], **kwargs) -> Response
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.subscriber.aggregation.user.languages
+ # TODO Rename this here and in `get_commit_languages`
+ def _extracted_from_get_commit_languages_38(commit, out):
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
+ if lang is not None:
+ out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
+ total_additions += file.additions
+ total_deletions += file.deletions
+ add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
+ del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
+ out.normalize(add_ratio, del_ratio)
+
===========changed ref 1===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
===========changed ref 2===========
# module: backend.src.publisher.processing.user.auth
def authenticate(code: str, private_access: bool) -> str:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
+ "private_access": private_access,
}
- raw_user["private_access"] = private_access
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
await update_user(user_id, access_token, new_private_access)
else:
# first time sign up
await update_user(user_id, access_token, private_access)
await db_update_user(user_id, raw_user)
return user_id
===========changed ref 3===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
days: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
day = datetime.fromisoformat(item.date).weekday()
days[day]["contribs"] += item.stats.contribs_count
loc_changed = sum(
+ x.additions + x.deletions for x in item.stats.languages.values()
- [x.additions + x.deletions for x in item.stats.languages.values()]
)
+
days[day]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(7):
v = days[k]
+ _obj: Dict[str, Union[str, int]] = {
- _obj: Dict[str, Union[str, int]] = {"index": k, **v}
+ "index": k,
+ **v,
+ "formatted_loc_changed": format_number(v["loc_changed"]),
- _obj["formatted_loc_changed"] = format_number(v["loc_changed"])
+ }
+
out.append(TimeDatum.parse_obj(_obj))
return DayData(days=out)
===========changed ref 4===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_month_data(data: UserPackage) -> MonthData:
months: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
month = datetime.fromisoformat(item.date).month - 1
months[month]["contribs"] += item.stats.contribs_count
loc_changed = sum(
+ x.additions + x.deletions for x in item.stats.languages.values()
- [x.additions + x.deletions for x in item.stats.languages.values()]
)
+
months[month]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(12):
v = months[k]
+ _obj: Dict[str, Union[str, int]] = {
- _obj: Dict[str, Union[str, int]] = {"index": k, **v}
+ "index": k,
+ **v,
+ "formatted_loc_changed": format_number(v["loc_changed"]),
- _obj["formatted_loc_changed"] = format_number(v["loc_changed"])
+ }
+
out.append(TimeDatum.parse_obj(_obj))
return MonthData(months=out)
|
backend.src.data.github.auth.main/authenticate
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<17>:<add> raise OAuthError(f"OAuth Error: {str(r.status_code)}")
<del> raise OAuthError("OAuth Error: " + str(r.status_code))
|
# module: backend.src.data.github.auth.main
def authenticate(code: str) -> Tuple[str, str]:
<0> """
<1> Takes a authentication code, verifies, and returns user_id/access_token
<2> :param code: GitHub authentication code from OAuth process
<3> :return: user_id, access_token of authenticated user
<4> """
<5> start = datetime.now()
<6>
<7> params = {
<8> "client_id": OAUTH_CLIENT_ID,
<9> "client_secret": OAUTH_CLIENT_SECRET,
<10> "code": code,
<11> "redirect_uri": OAUTH_REDIRECT_URI,
<12> }
<13>
<14> r = s.post("https://github.com/login/oauth/access_token", params=params)
<15>
<16> if r.status_code != 200:
<17> raise OAuthError("OAuth Error: " + str(r.status_code))
<18>
<19> access_token = r.text.split("&")[0].split("=")[1]
<20> user_id = get_unknown_user(access_token)
<21>
<22> if user_id is None:
<23> raise OAuthError("OAuth Error: Invalid user_id/access_token")
<24>
<25> print("OAuth SignUp", datetime.now() - start)
<26> return user_id, access_token
<27>
|
===========unchanged ref 0===========
at: backend.src.data.github.auth.main
s = requests.session()
get_unknown_user(access_token: str) -> Optional[str]
OAuthError(*args: object)
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: requests.models.Response.__init__
self.status_code = None
at: requests.sessions.Session
post(url: Union[Text, bytes], data: _Data=..., json: Optional[Any]=..., **kwargs) -> Response
at: src.constants
OAUTH_CLIENT_ID = os.getenv("OAUTH_CLIENT_ID", "") # client ID for GitHub OAuth App
OAUTH_CLIENT_SECRET = os.getenv("OAUTH_CLIENT_SECRET", "") # client secret for App
OAUTH_REDIRECT_URI = os.getenv("OAUTH_REDIRECT_URI", "") # redirect uri for App
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
===========changed ref 0===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 1===========
# module: backend.src.subscriber.aggregation.user.languages
+ # TODO Rename this here and in `get_commit_languages`
+ def _extracted_from_get_commit_languages_38(commit, out):
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
+ if lang is not None:
+ out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
+ total_additions += file.additions
+ total_deletions += file.deletions
+ add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
+ del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
+ out.normalize(add_ratio, del_ratio)
+
===========changed ref 2===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
===========changed ref 3===========
# module: backend.src.publisher.processing.user.auth
def authenticate(code: str, private_access: bool) -> str:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
+ "private_access": private_access,
}
- raw_user["private_access"] = private_access
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
await update_user(user_id, access_token, new_private_access)
else:
# first time sign up
await update_user(user_id, access_token, private_access)
await db_update_user(user_id, raw_user)
return user_id
===========changed ref 4===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
days: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
day = datetime.fromisoformat(item.date).weekday()
days[day]["contribs"] += item.stats.contribs_count
loc_changed = sum(
+ x.additions + x.deletions for x in item.stats.languages.values()
- [x.additions + x.deletions for x in item.stats.languages.values()]
)
+
days[day]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(7):
v = days[k]
+ _obj: Dict[str, Union[str, int]] = {
- _obj: Dict[str, Union[str, int]] = {"index": k, **v}
+ "index": k,
+ **v,
+ "formatted_loc_changed": format_number(v["loc_changed"]),
- _obj["formatted_loc_changed"] = format_number(v["loc_changed"])
+ }
+
out.append(TimeDatum.parse_obj(_obj))
return DayData(days=out)
|
backend.src.subscriber.aggregation.wrapped.langs/get_lang_data
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<19>:<del> total_count = 0
<20>:<del> for (k, v) in list(langs)[5:]:
<21>:<del> total_count += _count_loc(v, m)
<22>:<add> total_count = sum(_count_loc(v, m) for _, v in list(langs)[5:])
<32>:<add> out[f"langs_{m}"] = lang_objs
<del> out["langs_" + m] = lang_objs
|
# module: backend.src.subscriber.aggregation.wrapped.langs
def get_lang_data(data: UserPackage) -> LangData:
<0> out = {}
<1> for m in ["changed", "added"]:
<2> langs = sorted(
<3> data.contribs.total_stats.languages.items(),
<4> key=lambda x: _count_loc(x[1], m),
<5> reverse=True,
<6> )
<7> lang_objs: List[LangDatum] = []
<8> for k, v in list(langs)[:5]:
<9> lang_data = {
<10> "id": k,
<11> "label": k,
<12> "value": _count_loc(v, m),
<13> "formatted_value": format_number(_count_loc(v, m)),
<14> "color": v.color,
<15> }
<16> lang_objs.append(LangDatum.parse_obj(lang_data))
<17>
<18> # remaining languages
<19> total_count = 0
<20> for (k, v) in list(langs)[5:]:
<21> total_count += _count_loc(v, m)
<22> lang_data = {
<23> "id": -1,
<24> "label": "other",
<25> "value": total_count,
<26> "formatted_value": format_number(total_count),
<27> "color": DEFAULT_COLOR,
<28> }
<29> if total_count > 100:
<30> lang_objs.append(LangDatum.parse_obj(lang_data))
<31>
<32> out["langs_" + m] = lang_objs
<33>
<34> return LangData.parse_obj(out)
<35>
|
===========unchanged ref 0===========
at: backend.src.subscriber.aggregation.wrapped.langs
_count_loc(x: Language, metric: str) -> int
at: src.constants
DEFAULT_COLOR = "#858585"
at: src.models.user.contribs.ContributionStats
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.Language
color: Optional[str]
additions: int
deletions: int
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
public_stats: ContributionStats
total: List[ContributionDay]
public: List[ContributionDay]
repo_stats: Dict[str, RepoContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
at: src.utils.utils
format_number(num: int) -> str
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 1===========
# module: backend.src.subscriber.aggregation.user.languages
+ # TODO Rename this here and in `get_commit_languages`
+ def _extracted_from_get_commit_languages_38(commit, out):
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
+ if lang is not None:
+ out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
+ total_additions += file.additions
+ total_deletions += file.deletions
+ add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
+ del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
+ out.normalize(add_ratio, del_ratio)
+
===========changed ref 2===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
===========changed ref 3===========
# module: backend.src.publisher.processing.user.auth
def authenticate(code: str, private_access: bool) -> str:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
+ "private_access": private_access,
}
- raw_user["private_access"] = private_access
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
await update_user(user_id, access_token, new_private_access)
else:
# first time sign up
await update_user(user_id, access_token, private_access)
await db_update_user(user_id, raw_user)
return user_id
===========changed ref 4===========
# module: backend.src.data.github.auth.main
def authenticate(code: str) -> Tuple[str, str]:
"""
Takes a authentication code, verifies, and returns user_id/access_token
:param code: GitHub authentication code from OAuth process
:return: user_id, access_token of authenticated user
"""
start = datetime.now()
params = {
"client_id": OAUTH_CLIENT_ID,
"client_secret": OAUTH_CLIENT_SECRET,
"code": code,
"redirect_uri": OAUTH_REDIRECT_URI,
}
r = s.post("https://github.com/login/oauth/access_token", params=params)
if r.status_code != 200:
+ raise OAuthError(f"OAuth Error: {str(r.status_code)}")
- raise OAuthError("OAuth Error: " + str(r.status_code))
access_token = r.text.split("&")[0].split("=")[1]
user_id = get_unknown_user(access_token)
if user_id is None:
raise OAuthError("OAuth Error: Invalid user_id/access_token")
print("OAuth SignUp", datetime.now() - start)
return user_id, access_token
|
backend.src.utils.utils/use_time_range
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<11>:<add> time_str = f"{start_str} - {end_str}"
<del> time_str = start_str + " - " + end_str
|
# module: backend.src.utils.utils
# returns start date, end date, string representing time range
def use_time_range(
time_range: str, start_date: date, end_date: date
) -> Tuple[date, date, str]:
<0> duration_options = {
<1> "one_month": (30, "Past 1 Month"),
<2> "three_months": (90, "Past 3 Months"),
<3> "six_months": (180, "Past 6 Months"),
<4> "one_year": (365, "Past 1 Year"),
<5> }
<6>
<7> start_str = start_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
<8> end_str = end_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
<9> if end_date == date.today():
<10> end_str = "Present"
<11> time_str = start_str + " - " + end_str
<12>
<13> if time_range in duration_options:
<14> days, time_str = duration_options[time_range]
<15> end_date = date.today()
<16> start_date = date.today() - timedelta(days)
<17>
<18> return start_date, end_date, time_str
<19>
|
===========unchanged ref 0===========
at: datetime
timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...)
date()
at: datetime.date
__slots__ = '_year', '_month', '_day', '_hashcode'
today() -> _S
strftime(fmt: _Text) -> str
__str__ = isoformat
__radd__ = __add__
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
===========changed ref 0===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 1===========
# module: backend.src.subscriber.aggregation.user.languages
+ # TODO Rename this here and in `get_commit_languages`
+ def _extracted_from_get_commit_languages_38(commit, out):
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
+ if lang is not None:
+ out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
+ total_additions += file.additions
+ total_deletions += file.deletions
+ add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
+ del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
+ out.normalize(add_ratio, del_ratio)
+
===========changed ref 2===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
===========changed ref 3===========
# module: backend.src.publisher.processing.user.auth
def authenticate(code: str, private_access: bool) -> str:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
+ "private_access": private_access,
}
- raw_user["private_access"] = private_access
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
await update_user(user_id, access_token, new_private_access)
else:
# first time sign up
await update_user(user_id, access_token, private_access)
await db_update_user(user_id, raw_user)
return user_id
===========changed ref 4===========
# module: backend.src.data.github.auth.main
def authenticate(code: str) -> Tuple[str, str]:
"""
Takes a authentication code, verifies, and returns user_id/access_token
:param code: GitHub authentication code from OAuth process
:return: user_id, access_token of authenticated user
"""
start = datetime.now()
params = {
"client_id": OAUTH_CLIENT_ID,
"client_secret": OAUTH_CLIENT_SECRET,
"code": code,
"redirect_uri": OAUTH_REDIRECT_URI,
}
r = s.post("https://github.com/login/oauth/access_token", params=params)
if r.status_code != 200:
+ raise OAuthError(f"OAuth Error: {str(r.status_code)}")
- raise OAuthError("OAuth Error: " + str(r.status_code))
access_token = r.text.split("&")[0].split("=")[1]
user_id = get_unknown_user(access_token)
if user_id is None:
raise OAuthError("OAuth Error: Invalid user_id/access_token")
print("OAuth SignUp", datetime.now() - start)
return user_id, access_token
===========changed ref 5===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
days: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
day = datetime.fromisoformat(item.date).weekday()
days[day]["contribs"] += item.stats.contribs_count
loc_changed = sum(
+ x.additions + x.deletions for x in item.stats.languages.values()
- [x.additions + x.deletions for x in item.stats.languages.values()]
)
+
days[day]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(7):
v = days[k]
+ _obj: Dict[str, Union[str, int]] = {
- _obj: Dict[str, Union[str, int]] = {"index": k, **v}
+ "index": k,
+ **v,
+ "formatted_loc_changed": format_number(v["loc_changed"]),
- _obj["formatted_loc_changed"] = format_number(v["loc_changed"])
+ }
+
out.append(TimeDatum.parse_obj(_obj))
return DayData(days=out)
|
backend.src.utils.utils/format_number
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<1>:<add> return f"~{str(num // 1000)}k lines"
<del> return "~" + str(int(num / 1000)) + "k lines"
<3>:<add> return f"~{str(num // 100 / 10)}k lines"
<del> return "~" + str(int(num / 100) / 10) + "k lines"
<5>:<add> return f"~{str(num // 100 * 100)} lines"
<del> return "~" + str(int(num / 100) * 100) + " lines"
|
# module: backend.src.utils.utils
def format_number(num: int) -> str:
<0> if num > 10000:
<1> return "~" + str(int(num / 1000)) + "k lines"
<2> elif num > 1000:
<3> return "~" + str(int(num / 100) / 10) + "k lines"
<4> elif num > 100:
<5> return "~" + str(int(num / 100) * 100) + " lines"
<6> else:
<7> return "<100 lines"
<8>
|
===========changed ref 0===========
# module: backend.src.utils.utils
# returns start date, end date, string representing time range
def use_time_range(
time_range: str, start_date: date, end_date: date
) -> Tuple[date, date, str]:
duration_options = {
"one_month": (30, "Past 1 Month"),
"three_months": (90, "Past 3 Months"),
"six_months": (180, "Past 6 Months"),
"one_year": (365, "Past 1 Year"),
}
start_str = start_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
end_str = end_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
if end_date == date.today():
end_str = "Present"
+ time_str = f"{start_str} - {end_str}"
- time_str = start_str + " - " + end_str
if time_range in duration_options:
days, time_str = duration_options[time_range]
end_date = date.today()
start_date = date.today() - timedelta(days)
return start_date, end_date, time_str
===========changed ref 1===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 2===========
# module: backend.src.subscriber.aggregation.user.languages
+ # TODO Rename this here and in `get_commit_languages`
+ def _extracted_from_get_commit_languages_38(commit, out):
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
+ if lang is not None:
+ out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
+ total_additions += file.additions
+ total_deletions += file.deletions
+ add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
+ del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
+ out.normalize(add_ratio, del_ratio)
+
===========changed ref 3===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
===========changed ref 4===========
# module: backend.src.publisher.processing.user.auth
def authenticate(code: str, private_access: bool) -> str:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
+ "private_access": private_access,
}
- raw_user["private_access"] = private_access
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
await update_user(user_id, access_token, new_private_access)
else:
# first time sign up
await update_user(user_id, access_token, private_access)
await db_update_user(user_id, raw_user)
return user_id
===========changed ref 5===========
# module: backend.src.data.github.auth.main
def authenticate(code: str) -> Tuple[str, str]:
"""
Takes a authentication code, verifies, and returns user_id/access_token
:param code: GitHub authentication code from OAuth process
:return: user_id, access_token of authenticated user
"""
start = datetime.now()
params = {
"client_id": OAUTH_CLIENT_ID,
"client_secret": OAUTH_CLIENT_SECRET,
"code": code,
"redirect_uri": OAUTH_REDIRECT_URI,
}
r = s.post("https://github.com/login/oauth/access_token", params=params)
if r.status_code != 200:
+ raise OAuthError(f"OAuth Error: {str(r.status_code)}")
- raise OAuthError("OAuth Error: " + str(r.status_code))
access_token = r.text.split("&")[0].split("=")[1]
user_id = get_unknown_user(access_token)
if user_id is None:
raise OAuthError("OAuth Error: Invalid user_id/access_token")
print("OAuth SignUp", datetime.now() - start)
return user_id, access_token
|
backend.src.subscriber.routers.dev/get_user_raw
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<2>:<add> return await get_user_data(
<del> data = await get_user_data(
<5>:<del> return data
|
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
<0> await update_keys()
<1> start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
<2> data = await get_user_data(
<3> user_id, start_date, end_date, timezone_str, access_token
<4> )
<5> return data
<6>
|
===========unchanged ref 0===========
at: backend.src.subscriber.routers.dev
router = APIRouter()
at: datetime
timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...)
date()
at: datetime.date
__slots__ = '_year', '_month', '_day', '_hashcode'
today() -> _S
__str__ = isoformat
__radd__ = __add__
at: src.data.mongo.secret.functions
update_keys() -> None
at: src.subscriber.aggregation.user.package
get_user_data(user_id: str, start_date: date, end_date: date, timezone_str: str, access_token: Optional[str], catch_errors: bool=False) -> UserPackage
at: src.utils.decorators
async_fail_gracefully(func: Callable[..., Any])
at: src.utils.utils
use_time_range(time_range: str, start_date: date, end_date: date) -> Tuple[date, date, str]
===========changed ref 0===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
===========changed ref 1===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 2===========
# module: backend.src.subscriber.aggregation.user.languages
+ # TODO Rename this here and in `get_commit_languages`
+ def _extracted_from_get_commit_languages_38(commit, out):
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
+ if lang is not None:
+ out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
+ total_additions += file.additions
+ total_deletions += file.deletions
+ add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
+ del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
+ out.normalize(add_ratio, del_ratio)
+
===========changed ref 3===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
===========changed ref 4===========
# module: backend.src.publisher.processing.user.auth
def authenticate(code: str, private_access: bool) -> str:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
+ "private_access": private_access,
}
- raw_user["private_access"] = private_access
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
await update_user(user_id, access_token, new_private_access)
else:
# first time sign up
await update_user(user_id, access_token, private_access)
await db_update_user(user_id, raw_user)
return user_id
===========changed ref 5===========
# module: backend.src.utils.utils
# returns start date, end date, string representing time range
def use_time_range(
time_range: str, start_date: date, end_date: date
) -> Tuple[date, date, str]:
duration_options = {
"one_month": (30, "Past 1 Month"),
"three_months": (90, "Past 3 Months"),
"six_months": (180, "Past 6 Months"),
"one_year": (365, "Past 1 Year"),
}
start_str = start_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
end_str = end_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
if end_date == date.today():
end_str = "Present"
+ time_str = f"{start_str} - {end_str}"
- time_str = start_str + " - " + end_str
if time_range in duration_options:
days, time_str = duration_options[time_range]
end_date = date.today()
start_date = date.today() - timedelta(days)
return start_date, end_date, time_str
|
backend.src.subscriber.routers.dev/get_wrapped_user_raw
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<4>:<add> return get_wrapped_data(user_data, year)
<del> wrapped_data = get_wrapped_data(user_data, year)
<5>:<del> return wrapped_data
|
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
<0> await update_keys()
<1> user_data = await get_user_data(
<2> user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
<3> )
<4> wrapped_data = get_wrapped_data(user_data, year)
<5> return wrapped_data
<6>
|
===========unchanged ref 0===========
at: datetime
date()
at: src.data.mongo.secret.functions
update_keys() -> None
at: src.subscriber.aggregation.user.package
get_user_data(user_id: str, start_date: date, end_date: date, timezone_str: str, access_token: Optional[str], catch_errors: bool=False) -> UserPackage
at: src.subscriber.aggregation.wrapped.package
main(user_package: UserPackage, year: int) -> WrappedPackage
at: src.utils.decorators
async_fail_gracefully(func: Callable[..., Any])
===========changed ref 0===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 1===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
===========changed ref 2===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 3===========
# module: backend.src.subscriber.aggregation.user.languages
+ # TODO Rename this here and in `get_commit_languages`
+ def _extracted_from_get_commit_languages_38(commit, out):
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
+ if lang is not None:
+ out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
+ total_additions += file.additions
+ total_deletions += file.deletions
+ add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
+ del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
+ out.normalize(add_ratio, del_ratio)
+
===========changed ref 4===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
===========changed ref 5===========
# module: backend.src.publisher.processing.user.auth
def authenticate(code: str, private_access: bool) -> str:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
+ "private_access": private_access,
}
- raw_user["private_access"] = private_access
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
await update_user(user_id, access_token, new_private_access)
else:
# first time sign up
await update_user(user_id, access_token, private_access)
await db_update_user(user_id, raw_user)
return user_id
===========changed ref 6===========
# module: backend.src.utils.utils
# returns start date, end date, string representing time range
def use_time_range(
time_range: str, start_date: date, end_date: date
) -> Tuple[date, date, str]:
duration_options = {
"one_month": (30, "Past 1 Month"),
"three_months": (90, "Past 3 Months"),
"six_months": (180, "Past 6 Months"),
"one_year": (365, "Past 1 Year"),
}
start_str = start_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
end_str = end_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
if end_date == date.today():
end_str = "Present"
+ time_str = f"{start_str} - {end_str}"
- time_str = start_str + " - " + end_str
if time_range in duration_options:
days, time_str = duration_options[time_range]
end_date = date.today()
start_date = date.today() - timedelta(days)
return start_date, end_date, time_str
|
backend.src.data.github.rest.template/_get_template
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<12>:<add> "Accept": accept_header,
<del> "Accept": str(accept_header),
<13>:<add> "Authorization": f"bearer {new_access_token}",
<del> "Authorization": "bearer " + new_access_token,
<37>:<add> raise RESTError(f"REST Error: {str(r.status_code)}")
<del> raise RESTError("REST Error: " + str(r.status_code))
|
# module: backend.src.data.github.rest.template
def _get_template(
query: str,
params: Dict[str, Any],
accept_header: str,
access_token: Optional[str] = None,
retries: int = 0,
) -> Any:
<0> """
<1> Internal template for interacting with the GitHub REST API
<2> :param query: The query to be sent to the GitHub API
<3> :param params: The parameters to be sent to the GitHub API
<4> :param access_token: The access token to be sent to the GitHub API
<5> :param accept_header: The accept header to be sent to the GitHub API
<6> :return: The response from the GitHub API
<7> """
<8> start = datetime.now()
<9>
<10> new_access_token = get_access_token(access_token)
<11> headers: Dict[str, str] = {
<12> "Accept": str(accept_header),
<13> "Authorization": "bearer " + new_access_token,
<14> }
<15>
<16> try:
<17> r = s.get(query, params=params, headers=headers, timeout=TIMEOUT)
<18> except ReadTimeout:
<19> raise RESTErrorTimeout("REST Error: Request Timeout")
<20>
<21> if r.status_code == 200:
<22> print("REST API", new_access_token, datetime.now() - start)
<23> return r.json() # type: ignore
<24>
<25> if r.status_code == 401:
<26> raise RESTErrorUnauthorized("REST Error: Unauthorized")
<27>
<28> if r.status_code == 404:
<29> raise RESTErrorNotFound("REST Error: Not Found")
<30>
<31> if r.status_code == 409:
<32> raise RESTErrorEmptyRepo("REST Error: Empty Repository")
<33>
<34> if retries < 3:
<35> print("REST Error, Retrying:", new_access_token)
<36> return _get_template(query, params, accept_header, access_token, retries + 1)
<37> raise RESTError("REST Error: " + str(r.status_code))
<38>
|
===========unchanged ref 0===========
at: backend.src.data.github.rest.template
s = requests.session()
RESTError(*args: object)
RESTErrorUnauthorized(*args: object)
RESTErrorNotFound(*args: object)
RESTErrorEmptyRepo(*args: object)
RESTErrorTimeout(*args: object)
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: requests.exceptions
ReadTimeout(*args, **kwargs)
at: requests.models.Response
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
json(**kwargs) -> Any
at: requests.models.Response.__init__
self.status_code = None
at: requests.sessions.Session
__attrs__ = [
"headers",
"cookies",
"auth",
"proxies",
"hooks",
"params",
"verify",
"cert",
"adapters",
"stream",
"trust_env",
"max_redirects",
]
get(url: Union[Text, bytes], **kwargs) -> Response
at: src.constants
TIMEOUT = 15 # max seconds to wait for api response
at: src.data.github.utils
get_access_token(access_token: Optional[str]=None) -> str
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 1===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 2===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
===========changed ref 3===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 4===========
# module: backend.src.subscriber.aggregation.user.languages
+ # TODO Rename this here and in `get_commit_languages`
+ def _extracted_from_get_commit_languages_38(commit, out):
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
+ if lang is not None:
+ out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
+ total_additions += file.additions
+ total_deletions += file.deletions
+ add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
+ del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
+ out.normalize(add_ratio, del_ratio)
+
===========changed ref 5===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
|
backend.src.data.github.graphql.template/get_template
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<9>:<add> headers: Dict[str, str] = {"Authorization": f"bearer {new_access_token}"}
<del> headers: Dict[str, str] = {"Authorization": "bearer " + new_access_token}
|
# module: backend.src.data.github.graphql.template
def get_template(
query: Dict[str, Any], access_token: Optional[str] = None, retries: int = 0
) -> Dict[str, Any]:
<0> """
<1> Template for interacting with the GitHub GraphQL API
<2> :param query: The query to be sent to the GitHub GraphQL API
<3> :param access_token: The access token to be used for the query
<4> :param retries: The number of retries to be made for Auth Exceptions
<5> :return: The response from the GitHub GraphQL API
<6> """
<7> start = datetime.now()
<8> new_access_token = get_access_token(access_token)
<9> headers: Dict[str, str] = {"Authorization": "bearer " + new_access_token}
<10>
<11> try:
<12> r = s.post( # type: ignore
<13> "https://api.github.com/graphql",
<14> json=query,
<15> headers=headers,
<16> timeout=TIMEOUT,
<17> )
<18> except ReadTimeout:
<19> raise GraphQLErrorTimeout("GraphQL Error: Request Timeout")
<20>
<21> print("GraphQL", new_access_token, datetime.now() - start)
<22> if r.status_code == 200:
<23> data = r.json() # type: ignore
<24> if "errors" in data:
<25> if (
<26> "type" in data["errors"][0]
<27> and data["errors"][0]["type"] in ["SERVICE_UNAVAILABLE", "NOT_FOUND"]
<28> and "path" in data["errors"][0]
<29> and isinstance(data["errors"][0]["path"], list)
<30> and data["errors"][0]["path"][0] == "nodes"
<31> ):
<32> raise GraphQLErrorMissingNode(node=int(data["errors"][0]["path"][1])) # type: ignore
<33>
<34> if retries < 2:
<35> print("GraphQL Error, Retrying:", new_access_token)
<36> return get_template(query</s>
|
===========below chunk 0===========
# module: backend.src.data.github.graphql.template
def get_template(
query: Dict[str, Any], access_token: Optional[str] = None, retries: int = 0
) -> Dict[str, Any]:
# offset: 1
raise GraphQLError("GraphQL Error: " + str(data["errors"]))
return data
if r.status_code in [401, 403]:
if retries < 2:
print("GraphQL Error, Retrying:", new_access_token)
return get_template(query, access_token, retries + 1)
raise GraphQLErrorRateLimit("GraphQL Error: Unauthorized")
if r.status_code == 502:
raise GraphQLErrorTimeout("GraphQL Error: Request Timeout")
raise GraphQLError("GraphQL Error: " + str(r.status_code))
===========unchanged ref 0===========
at: backend.src.data.github.graphql.template
s = requests.session()
GraphQLError(*args: object)
GraphQLErrorMissingNode(node: int)
GraphQLErrorRateLimit(*args: object)
GraphQLErrorTimeout(*args: object)
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: requests.exceptions
ReadTimeout(*args, **kwargs)
at: requests.models.Response
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
json(**kwargs) -> Any
at: requests.models.Response.__init__
self.status_code = None
at: requests.sessions.Session
__attrs__ = [
"headers",
"cookies",
"auth",
"proxies",
"hooks",
"params",
"verify",
"cert",
"adapters",
"stream",
"trust_env",
"max_redirects",
]
post(url: Union[Text, bytes], data: _Data=..., json: Optional[Any]=..., **kwargs) -> Response
at: src.constants
TIMEOUT = 15 # max seconds to wait for api response
at: src.data.github.utils
get_access_token(access_token: Optional[str]=None) -> str
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 1===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 2===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
===========changed ref 3===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 4===========
# module: backend.src.subscriber.aggregation.user.languages
+ # TODO Rename this here and in `get_commit_languages`
+ def _extracted_from_get_commit_languages_38(commit, out):
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
+ if lang is not None:
+ out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
+ total_additions += file.additions
+ total_deletions += file.deletions
+ add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
+ del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
+ out.normalize(add_ratio, del_ratio)
+
|
backend.src.publisher.routers.auth.standalone/redirect_return
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<2>:<add> return f"You ({user_id}) are now authenticated!"
<del> return "You (" + user_id + ") are now authenticated!"
|
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
<0> try:
<1> user_id = await authenticate(code=code, private_access=private_access) # type: ignore
<2> return "You (" + user_id + ") are now authenticated!"
<3> except Exception as e:
<4> logging.exception(e)
<5> return "Unknown Error. Please try again later."
<6>
|
===========unchanged ref 0===========
at: backend.src.publisher.routers.auth.standalone
router = APIRouter()
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: src.publisher.processing.user.auth
authenticate(code: str, private_access: bool) -> str
===========changed ref 0===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 1===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 2===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
===========changed ref 3===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 4===========
# module: backend.src.subscriber.aggregation.user.languages
+ # TODO Rename this here and in `get_commit_languages`
+ def _extracted_from_get_commit_languages_38(commit, out):
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
+ if lang is not None:
+ out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
+ total_additions += file.additions
+ total_deletions += file.deletions
+ add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
+ del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
+ out.normalize(add_ratio, del_ratio)
+
===========changed ref 5===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
===========changed ref 6===========
# module: backend.src.publisher.processing.user.auth
def authenticate(code: str, private_access: bool) -> str:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
+ "private_access": private_access,
}
- raw_user["private_access"] = private_access
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
await update_user(user_id, access_token, new_private_access)
else:
# first time sign up
await update_user(user_id, access_token, private_access)
await db_update_user(user_id, raw_user)
return user_id
|
backend.src.publisher.routers.auth.standalone/delete_account_auth
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<1>:<add> get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
<del> get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
|
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
<0> return RedirectResponse(
<1> get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
<2> )
<3>
|
===========unchanged ref 0===========
at: backend.src.publisher.routers.auth.standalone
router = APIRouter()
at: src.publisher.routers.decorators
get_redirect_url(prefix: str="", private: bool=False, user_id: Optional[str]=None) -> str
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 1===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 2===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 3===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
===========changed ref 4===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 5===========
# module: backend.src.subscriber.aggregation.user.languages
+ # TODO Rename this here and in `get_commit_languages`
+ def _extracted_from_get_commit_languages_38(commit, out):
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
+ if lang is not None:
+ out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
+ total_additions += file.additions
+ total_deletions += file.deletions
+ add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
+ del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
+ out.normalize(add_ratio, del_ratio)
+
===========changed ref 6===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
===========changed ref 7===========
# module: backend.src.publisher.processing.user.auth
def authenticate(code: str, private_access: bool) -> str:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
+ "private_access": private_access,
}
- raw_user["private_access"] = private_access
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
await update_user(user_id, access_token, new_private_access)
else:
# first time sign up
await update_user(user_id, access_token, private_access)
await db_update_user(user_id, raw_user)
return user_id
|
backend.src.publisher.routers.auth.standalone/delete_account
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<2>:<add> f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
<del> "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
|
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
<0> await delete_user(user_id, user_key="", use_user_key=False)
<1> return RedirectResponse(
<2> "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
<3> )
<4>
|
===========unchanged ref 0===========
at: backend.src.publisher.routers.auth.standalone
router = APIRouter()
at: src.constants
OAUTH_CLIENT_ID = os.getenv("OAUTH_CLIENT_ID", "") # client ID for GitHub OAuth App
at: src.publisher.processing.user.auth
delete_user(user_id: str, user_key: str, use_user_key: bool=True) -> bool
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 4===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
===========changed ref 5===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 6===========
# module: backend.src.subscriber.aggregation.user.languages
+ # TODO Rename this here and in `get_commit_languages`
+ def _extracted_from_get_commit_languages_38(commit, out):
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
+ if lang is not None:
+ out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
+ total_additions += file.additions
+ total_deletions += file.deletions
+ add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
+ del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
+ out.normalize(add_ratio, del_ratio)
+
===========changed ref 7===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
|
backend.src.subscriber.processing.auth/check_user_starred_repo
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<7>:<add> return f"{owner}/{repo}" in user_stars
<del> if f"{owner}/{repo}" in user_stars:
<8>:<del> return True
<10>:<del> return False
<11>:<del>
|
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
<0> # Checks the repo's starred users (with cache)
<1> repo_stargazers = await get_repo_stargazers(owner, repo)
<2> if user_id in repo_stargazers:
<3> return True
<4>
<5> # Checks the user's 30 most recent starred repos (no cache)
<6> user_stars = await get_user_stars(user_id)
<7> if f"{owner}/{repo}" in user_stars:
<8> return True
<9>
<10> return False
<11>
|
===========unchanged ref 0===========
at: datetime
timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...)
at: src.constants
OWNER = "avgupta456"
REPO = "github-trends"
at: src.subscriber.aggregation.auth.auth
Callable(*args: List[Any], **kwargs: Dict[str, Any]) -> Any
get_user_stars(user_id: str) -> List[str]
at: src.utils.alru_cache
alru_cache(max_size: int=128, ttl: timedelta=timedelta(minutes=1))
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
===========changed ref 6===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 7===========
# module: backend.src.subscriber.aggregation.user.languages
+ # TODO Rename this here and in `get_commit_languages`
+ def _extracted_from_get_commit_languages_38(commit, out):
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
+ if lang is not None:
+ out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
+ total_additions += file.additions
+ total_deletions += file.deletions
+ add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
+ del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
+ out.normalize(add_ratio, del_ratio)
+
===========changed ref 8===========
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
out: List[Any] = []
for item in data.contribs.total:
lists = item.lists
lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
for type, list in zip(["commit", "issue", "pr", "review"], lists):
- for obj in list:
+ out.extend(
- out.append(
+ {
- {
+ "type": type,
- "type": type,
+ "weekday": item.weekday,
- "weekday": item.weekday,
+ "timestamp": date_to_seconds_since_midnight(obj),
- "timestamp": date_to_seconds_since_midnight(obj),
- }
+ }
- )
+ for obj in list
+ )
shuffle(out)
out = out[:MAX_ITEMS]
out = [TimestampDatum.parse_obj(x) for x in out]
return TimestampData(contribs=out)
|
backend.src.subscriber.aggregation.user.follows/get_user_follows
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<28>:<add> return UserFollows(followers=followers, following=following)
<del> output = UserFollows(followers=followers, following=following)
<29>:<del> return output
|
# module: backend.src.subscriber.aggregation.user.follows
def get_user_follows(user_id: str, access_token: Optional[str]) -> UserFollows:
<0> """get user followers and users following for given user"""
<1>
<2> followers: List[User] = []
<3> following: List[User] = []
<4>
<5> for user_list, get_func in zip(
<6> [followers, following], [_get_user_followers, _get_user_following]
<7> ):
<8> after: Optional[str] = ""
<9> index, cont = 0, True # initialize variables
<10> while cont and index < 10:
<11> after_str: str = after if isinstance(after, str) else ""
<12> data = get_func(user_id, after=after_str, access_token=access_token)
<13>
<14> cont = False
<15>
<16> user_list.extend(
<17> map(
<18> lambda x: User(name=x.name, login=x.login, url=x.url),
<19> data.nodes,
<20> )
<21> )
<22> if data.page_info.has_next_page:
<23> after = data.page_info.end_cursor
<24> cont = True
<25>
<26> index += 1
<27>
<28> output = UserFollows(followers=followers, following=following)
<29> return output
<30>
|
===========unchanged ref 0===========
at: src.data.github.graphql.user.follows.follows
get_user_followers(user_id: str, first: int=100, after: str="", access_token: Optional[str]=None) -> RawFollows
get_user_following(user_id: str, first: int=10, after: str="", access_token: Optional[str]=None) -> RawFollows
at: src.data.github.graphql.user.follows.models.PageInfo
has_next_page: bool = Field(alias="hasNextPage")
end_cursor: Optional[str] = Field(alias="endCursor")
at: src.data.github.graphql.user.follows.models.RawFollows
nodes: List[User]
page_info: PageInfo = Field(alias="pageInfo")
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
# Checks the repo's starred users (with cache)
repo_stargazers = await get_repo_stargazers(owner, repo)
if user_id in repo_stargazers:
return True
# Checks the user's 30 most recent starred repos (no cache)
user_stars = await get_user_stars(user_id)
+ return f"{owner}/{repo}" in user_stars
- if f"{owner}/{repo}" in user_stars:
- return True
- return False
-
===========changed ref 6===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
===========changed ref 7===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 8===========
# module: backend.src.subscriber.aggregation.user.languages
+ # TODO Rename this here and in `get_commit_languages`
+ def _extracted_from_get_commit_languages_38(commit, out):
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
+ if lang is not None:
+ out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
+ total_additions += file.additions
+ total_deletions += file.deletions
+ add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
+ del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
+ out.normalize(add_ratio, del_ratio)
+
|
backend.src.subscriber.aggregation.auth.auth/get_user_stars
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<10>:<add> return [f"{OWNER}/{REPO}"]
<del> return [OWNER + "/" + REPO]
|
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
<0> access_token = get_access_token()
<1> try:
<2> data = github_get_user_starred_repos(user_id, access_token)
<3> data = [x["repo"]["full_name"] for x in data]
<4> return data
<5> except RESTErrorNotFound:
<6> # User does not exist (and rate limited previously)
<7> return []
<8> except RESTError:
<9> # Rate limited, so assume user starred repo
<10> return [OWNER + "/" + REPO]
<11>
|
===========unchanged ref 0===========
at: src.constants
OWNER = "avgupta456"
REPO = "github-trends"
at: src.data.github.rest.template
RESTError(*args: object)
RESTErrorNotFound(*args: object)
at: src.data.github.rest.user
get_user_starred_repos(user_id: str, access_token: str, per_page: int=100, page: int=1) -> List[Dict[str, Any]]
at: src.data.github.utils
get_access_token(access_token: Optional[str]=None) -> str
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
# Checks the repo's starred users (with cache)
repo_stargazers = await get_repo_stargazers(owner, repo)
if user_id in repo_stargazers:
return True
# Checks the user's 30 most recent starred repos (no cache)
user_stars = await get_user_stars(user_id)
+ return f"{owner}/{repo}" in user_stars
- if f"{owner}/{repo}" in user_stars:
- return True
- return False
-
===========changed ref 6===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
===========changed ref 7===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 8===========
# module: backend.src.subscriber.aggregation.user.languages
+ # TODO Rename this here and in `get_commit_languages`
+ def _extracted_from_get_commit_languages_38(commit, out):
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
+ if lang is not None:
+ out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
+ total_additions += file.additions
+ total_deletions += file.deletions
+ add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
+ del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
+ out.normalize(add_ratio, del_ratio)
+
|
backend.src.publisher.render.template/get_template
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<24>:<add> dp = Group(transform=f"translate({padding}, {padding})")
<del> dp = Group(transform="translate(" + str(padding) + ", " + str(padding) + ")")
<26>:<add> dp.add(d.text(header_text, insert=(0, 13), class_=f"{theme}-header"))
<del> dp.add(d.text(header_text, insert=(0, 13), class_=theme + "-header"))
<27>:<add> dp.add(d.text(subheader_text, insert=(0, 31), class_=f"{theme}-subheader"))
<del> dp.add(d.text(subheader_text, insert=(0, 31), class_=theme + "-subheader"))
|
# module: backend.src.publisher.render.template
def get_template(
width: int,
height: int,
padding: int,
header_text: str,
subheader_text: str,
theme: str,
use_animation: bool = True,
debug: bool = False,
) -> Tuple[Drawing, Group]:
<0> d = Drawing(size=(width, height))
<1>
<2> style = styles[theme]
<3> style_no_animation = styles_no_animation[theme]
<4> d.defs.add(d.style(style if use_animation else style_no_animation))
<5>
<6> d.add(
<7> d.rect(
<8> size=(width - 1, height - 1),
<9> insert=(0.5, 0.5),
<10> rx=4.5,
<11> stroke=themes[theme]["border_color"],
<12> fill=themes[theme]["bg_color"],
<13> )
<14> )
<15>
<16> d.add(
<17> d.rect(
<18> size=(width - 2 * padding, height - 2 * padding),
<19> insert=(padding, padding),
<20> fill="#eee" if debug else themes[theme]["bg_color"],
<21> )
<22> )
<23>
<24> dp = Group(transform="translate(" + str(padding) + ", " + str(padding) + ")")
<25>
<26> dp.add(d.text(header_text, insert=(0, 13), class_=theme + "-header"))
<27> dp.add(d.text(subheader_text, insert=(0, 31), class_=theme + "-subheader"))
<28>
<29> return d, dp
<30>
|
===========unchanged ref 0===========
at: src.publisher.render.style
themes = {
"classic": {
"header_color": "#2f80ed",
"subheader_color": "#666",
"text_color": "#333",
"bg_color": "#fffefe",
"border_color": "#e4e2e2",
"bar_color": "#ddd",
},
"dark": {
"header_color": "#fff",
"subheader_color": "#9f9f9f",
"text_color": "#9f9f9f",
"bg_color": "#151515",
"border_color": "#e4e2e2",
"bar_color": "#333",
},
"bright_lights": {
"header_color": "#fff",
"subheader_color": "#0e86d4",
"text_color": "#b1d4e0",
"bg_color": "#003060",
"border_color": "#0e86d4",
"bar_color": "#ddd",
},
"rosettes": {
"header_color": "#fff",
"subheader_color": "#b6e2d3",
"text_color": "#fae8e0",
"bg_color": "#ef7c8e",
"border_color": "#b6e2d3",
"bar_color": "#ddd",
},
"ferns": {
"header_color": "#116530",
"subheader_color": "#18a558",
"text_color": "#116530",
"bg_color": "#a3ebb1",
"border_color": "#21b6a8",
"bar_color": "#ddd",
},
"synthwaves": {
"header_color": "#e2e9ec",
"subheader_color": "#e5289e",
"text_color": "#ef8539",
"bg_color": "#2</s>
===========unchanged ref 1===========
styles = {k: get_style(k) for k in themes.keys()}
styles_no_animation = {k: get_style(k, False) for k in themes.keys()}
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
access_token = get_access_token()
try:
data = github_get_user_starred_repos(user_id, access_token)
data = [x["repo"]["full_name"] for x in data]
return data
except RESTErrorNotFound:
# User does not exist (and rate limited previously)
return []
except RESTError:
# Rate limited, so assume user starred repo
+ return [f"{OWNER}/{REPO}"]
- return [OWNER + "/" + REPO]
===========changed ref 6===========
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
# Checks the repo's starred users (with cache)
repo_stargazers = await get_repo_stargazers(owner, repo)
if user_id in repo_stargazers:
return True
# Checks the user's 30 most recent starred repos (no cache)
user_stars = await get_user_stars(user_id)
+ return f"{owner}/{repo}" in user_stars
- if f"{owner}/{repo}" in user_stars:
- return True
- return False
-
===========changed ref 7===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
|
backend.src.publisher.render.template/get_bar_section
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<0>:<add> section = Group(transform=f"translate(0, {padding})")
<del> section = Group(transform="translate(0, " + str(padding) + ")")
<2>:<add> translate = f"translate(0, {str(40 * i)})"
<del> translate = "translate(0, " + str(40 * i) + ")"
<4>:<add> row.add(d.text(top_text, insert=(2, 15), class_=f"{theme}-lang-name"))
<del> row.add(d.text(top_text, insert=(2, 15), class_=theme + "-lang-name"))
<6>:<add> d.text(right_text, insert=(bar_width + 10, 33), class_=f"{theme}-lang-name")
<del> d.text(right_text, insert=(bar_width + 10, 33), class_=theme + "-lang-name")
<8>:<add>
|
# module: backend.src.publisher.render.template
def get_bar_section(
d: Drawing,
dataset: List[Tuple[str, str, List[Tuple[float, str]]]],
theme: str,
padding: int = 45,
bar_width: int = 210,
) -> Group:
<0> section = Group(transform="translate(0, " + str(padding) + ")")
<1> for i, (top_text, right_text, data_row) in enumerate(dataset):
<2> translate = "translate(0, " + str(40 * i) + ")"
<3> row = Group(transform=translate)
<4> row.add(d.text(top_text, insert=(2, 15), class_=theme + "-lang-name"))
<5> row.add(
<6> d.text(right_text, insert=(bar_width + 10, 33), class_=theme + "-lang-name")
<7> )
<8> progress = Drawing(width=str(bar_width), x="0", y="25")
<9> progress.add(
<10> d.rect(
<11> size=(bar_width, 8),
<12> insert=(0, 0),
<13> rx=5,
<14> ry=5,
<15> fill=themes[theme]["bar_color"],
<16> )
<17> )
<18> total_percent, total_items = 0, len(data_row)
<19> for j, (percent, color) in enumerate(data_row):
<20> color = color or DEFAULT_COLOR
<21> percent = max(300 / bar_width, percent)
<22> bar_percent = bar_width * percent / 100
<23> bar_total = bar_width * total_percent / 100
<24> box_size, insert = (bar_percent, 8), (bar_total, 0)
<25> progress.add(d.rect(size=box_size, insert=insert, rx=5, ry=5, fill=color))
<26>
<27> width = min(bar_percent / 2, 5)
<28> if total_items > 1:
<29> box_left, box_right =</s>
|
===========below chunk 0===========
# module: backend.src.publisher.render.template
def get_bar_section(
d: Drawing,
dataset: List[Tuple[str, str, List[Tuple[float, str]]]],
theme: str,
padding: int = 45,
bar_width: int = 210,
) -> Group:
# offset: 1
box_size, insert = bar_percent - 2 * width, bar_total + width
if box_left:
box_size += width
insert -= width
if box_right:
box_size += width
progress.add(d.rect(size=(box_size, 8), insert=(insert, 0), fill=color))
total_percent += percent
row.add(progress)
section.add(row)
return section
===========unchanged ref 0===========
at: src.constants
DEFAULT_COLOR = "#858585"
===========unchanged ref 1===========
at: src.publisher.render.style
themes = {
"classic": {
"header_color": "#2f80ed",
"subheader_color": "#666",
"text_color": "#333",
"bg_color": "#fffefe",
"border_color": "#e4e2e2",
"bar_color": "#ddd",
},
"dark": {
"header_color": "#fff",
"subheader_color": "#9f9f9f",
"text_color": "#9f9f9f",
"bg_color": "#151515",
"border_color": "#e4e2e2",
"bar_color": "#333",
},
"bright_lights": {
"header_color": "#fff",
"subheader_color": "#0e86d4",
"text_color": "#b1d4e0",
"bg_color": "#003060",
"border_color": "#0e86d4",
"bar_color": "#ddd",
},
"rosettes": {
"header_color": "#fff",
"subheader_color": "#b6e2d3",
"text_color": "#fae8e0",
"bg_color": "#ef7c8e",
"border_color": "#b6e2d3",
"bar_color": "#ddd",
},
"ferns": {
"header_color": "#116530",
"subheader_color": "#18a558",
"text_color": "#116530",
"bg_color": "#a3ebb1",
"border_color": "#21b6a8",
"bar_color": "#ddd",
},
"synthwaves": {
"header_color": "#e2e9ec",
"subheader_color": "#e5289e",
"text_color": "#ef8539",
"bg_color": "#2</s>
===========unchanged ref 2===========
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.publisher.render.template
def get_template(
width: int,
height: int,
padding: int,
header_text: str,
subheader_text: str,
theme: str,
use_animation: bool = True,
debug: bool = False,
) -> Tuple[Drawing, Group]:
d = Drawing(size=(width, height))
style = styles[theme]
style_no_animation = styles_no_animation[theme]
d.defs.add(d.style(style if use_animation else style_no_animation))
d.add(
d.rect(
size=(width - 1, height - 1),
insert=(0.5, 0.5),
rx=4.5,
stroke=themes[theme]["border_color"],
fill=themes[theme]["bg_color"],
)
)
d.add(
d.rect(
size=(width - 2 * padding, height - 2 * padding),
insert=(padding, padding),
fill="#eee" if debug else themes[theme]["bg_color"],
)
)
+ dp = Group(transform=f"translate({padding}, {padding})")
- dp = Group(transform="translate(" + str(padding) + ", " + str(padding) + ")")
+ dp.add(d.text(header_text, insert=(0, 13), class_=f"{theme}-header"))
- dp.add(d.text(header_text, insert=(0, 13), class_=theme + "-header"))
+ dp.add(d.text(subheader_text, insert=(0, 31), class_=f"{theme}-subheader"))
- dp.add(d.text(subheader_text, insert=(0, 31), class_=theme + "-subheader"))
return d, dp
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 2===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 3===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 4===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
|
backend.src.publisher.render.template/get_lang_name_section
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<0>:<add> section = Group(transform=f"translate(0, {padding})")
<del> section = Group(transform="translate(0, " + str(padding) + ")")
<4>:<add> lang = Group(transform=f"translate({x_translate}, {y_translate})")
<del> lang = Group(transform="translate(" + x_translate + ", " + y_translate + ")")
<6>:<add> lang.add(d.text(data[i][0], insert=(14, 9), class_=f"{theme}-lang-name"))
<del> lang.add(d.text(data[i][0], insert=(14, 9), class_=theme + "-lang-name"))
|
# module: backend.src.publisher.render.template
def get_lang_name_section(
d: Drawing,
data: List[Tuple[str, str]],
theme: str,
columns: int = 2,
padding: int = 80,
) -> Group:
<0> section = Group(transform="translate(0, " + str(padding) + ")")
<1> for i, x in enumerate(data):
<2> x_translate = str((260 / columns) * (i % columns))
<3> y_translate = str(20 * (i // columns))
<4> lang = Group(transform="translate(" + x_translate + ", " + y_translate + ")")
<5> lang.add(Circle(center=(5, 5), r=5, fill=(data[i][1] or DEFAULT_COLOR)))
<6> lang.add(d.text(data[i][0], insert=(14, 9), class_=theme + "-lang-name"))
<7> section.add(lang)
<8> return section
<9>
|
===========unchanged ref 0===========
at: src.constants
DEFAULT_COLOR = "#858585"
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.publisher.render.template
def get_template(
width: int,
height: int,
padding: int,
header_text: str,
subheader_text: str,
theme: str,
use_animation: bool = True,
debug: bool = False,
) -> Tuple[Drawing, Group]:
d = Drawing(size=(width, height))
style = styles[theme]
style_no_animation = styles_no_animation[theme]
d.defs.add(d.style(style if use_animation else style_no_animation))
d.add(
d.rect(
size=(width - 1, height - 1),
insert=(0.5, 0.5),
rx=4.5,
stroke=themes[theme]["border_color"],
fill=themes[theme]["bg_color"],
)
)
d.add(
d.rect(
size=(width - 2 * padding, height - 2 * padding),
insert=(padding, padding),
fill="#eee" if debug else themes[theme]["bg_color"],
)
)
+ dp = Group(transform=f"translate({padding}, {padding})")
- dp = Group(transform="translate(" + str(padding) + ", " + str(padding) + ")")
+ dp.add(d.text(header_text, insert=(0, 13), class_=f"{theme}-header"))
- dp.add(d.text(header_text, insert=(0, 13), class_=theme + "-header"))
+ dp.add(d.text(subheader_text, insert=(0, 31), class_=f"{theme}-subheader"))
- dp.add(d.text(subheader_text, insert=(0, 31), class_=theme + "-subheader"))
return d, dp
===========changed ref 1===========
# module: backend.src.publisher.render.template
def get_bar_section(
d: Drawing,
dataset: List[Tuple[str, str, List[Tuple[float, str]]]],
theme: str,
padding: int = 45,
bar_width: int = 210,
) -> Group:
+ section = Group(transform=f"translate(0, {padding})")
- section = Group(transform="translate(0, " + str(padding) + ")")
for i, (top_text, right_text, data_row) in enumerate(dataset):
+ translate = f"translate(0, {str(40 * i)})"
- translate = "translate(0, " + str(40 * i) + ")"
row = Group(transform=translate)
+ row.add(d.text(top_text, insert=(2, 15), class_=f"{theme}-lang-name"))
- row.add(d.text(top_text, insert=(2, 15), class_=theme + "-lang-name"))
row.add(
+ d.text(right_text, insert=(bar_width + 10, 33), class_=f"{theme}-lang-name")
- d.text(right_text, insert=(bar_width + 10, 33), class_=theme + "-lang-name")
)
+
progress = Drawing(width=str(bar_width), x="0", y="25")
progress.add(
d.rect(
size=(bar_width, 8),
insert=(0, 0),
rx=5,
ry=5,
fill=themes[theme]["bar_color"],
)
)
total_percent, total_items = 0, len(data_row)
for j, (percent, color) in enumerate(data_row):
color = color or DEFAULT_COLOR
percent = max(300 / bar_width, percent)
bar_percent = bar_width * percent / 100
bar_total = bar_width * total_percent / 100
box_size, insert = (</s>
===========changed ref 2===========
# module: backend.src.publisher.render.template
def get_bar_section(
d: Drawing,
dataset: List[Tuple[str, str, List[Tuple[float, str]]]],
theme: str,
padding: int = 45,
bar_width: int = 210,
) -> Group:
# offset: 1
<s>_width * percent / 100
bar_total = bar_width * total_percent / 100
box_size, insert = (bar_percent, 8), (bar_total, 0)
progress.add(d.rect(size=box_size, insert=insert, rx=5, ry=5, fill=color))
width = min(bar_percent / 2, 5)
if total_items > 1:
box_left, box_right = j > 0, j < total_items - 1
box_size, insert = bar_percent - 2 * width, bar_total + width
if box_left:
box_size += width
insert -= width
if box_right:
box_size += width
progress.add(d.rect(size=(box_size, 8), insert=(insert, 0), fill=color))
total_percent += percent
row.add(progress)
section.add(row)
return section
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 4===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 5===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 6===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
|
backend.src.publisher.routers.decorators/get_redirect_url
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<9>:<add> if prefix != "":
<del> if len(prefix) > 0:
<10>:<add> url += f"/{prefix}"
<del> url += "/" + prefix
<20>:<add> url += f"&login={user_id}"
<del> url += "&login=" + user_id
|
# module: backend.src.publisher.routers.decorators
# for standalone auth routes
def get_redirect_url(
prefix: str = "", private: bool = False, user_id: Optional[str] = None
) -> str:
<0> url = (
<1> "https://github.com/login/oauth/authorize?client_id="
<2> + OAUTH_CLIENT_ID
<3> + "&redirect_uri="
<4> + OAUTH_REDIRECT_URI
<5> + "/redirect"
<6> )
<7>
<8> # add prefix to redirect to different backend routes
<9> if len(prefix) > 0:
<10> url += "/" + prefix
<11>
<12> # add private flag to request correct permissions
<13> if private:
<14> url += "?private_access=True&scope=user,repo"
<15> else:
<16> url += "?private_access=False"
<17>
<18> # add user_id to hint if provided
<19> if user_id is not None:
<20> url += "&login=" + user_id
<21>
<22> return url
<23>
|
===========unchanged ref 0===========
at: src.constants
OAUTH_CLIENT_ID = os.getenv("OAUTH_CLIENT_ID", "") # client ID for GitHub OAuth App
OAUTH_REDIRECT_URI = os.getenv("OAUTH_REDIRECT_URI", "") # redirect uri for App
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
access_token = get_access_token()
try:
data = github_get_user_starred_repos(user_id, access_token)
data = [x["repo"]["full_name"] for x in data]
return data
except RESTErrorNotFound:
# User does not exist (and rate limited previously)
return []
except RESTError:
# Rate limited, so assume user starred repo
+ return [f"{OWNER}/{REPO}"]
- return [OWNER + "/" + REPO]
===========changed ref 6===========
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
# Checks the repo's starred users (with cache)
repo_stargazers = await get_repo_stargazers(owner, repo)
if user_id in repo_stargazers:
return True
# Checks the user's 30 most recent starred repos (no cache)
user_stars = await get_user_stars(user_id)
+ return f"{owner}/{repo}" in user_stars
- if f"{owner}/{repo}" in user_stars:
- return True
- return False
-
===========changed ref 7===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
===========changed ref 8===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 9===========
# module: backend.src.subscriber.aggregation.user.languages
+ # TODO Rename this here and in `get_commit_languages`
+ def _extracted_from_get_commit_languages_38(commit, out):
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
+ if lang is not None:
+ out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
+ total_additions += file.additions
+ total_deletions += file.deletions
+ add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
+ del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
+ out.normalize(add_ratio, del_ratio)
+
|
backend.src.publisher.routers.decorators/svg_fail_gracefully
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<31>:<add> headers={"Cache-Control": f"public, max-age={cache_max_age}"},
<del> headers={"Cache-Control": "public, max-age=" + str(cache_max_age)},
|
# module: backend.src.publisher.routers.decorators
# NOTE: implied async, sync not implemented yet
def svg_fail_gracefully(func: Callable[..., Any]):
<0> @wraps(func) # needed to play nice with FastAPI decorator
<1> async def wrapper(
<2> response: Response, *args: List[Any], **kwargs: Dict[str, Any]
<3> ) -> Any:
<4> d: Drawing
<5> start = datetime.now()
<6> cache_max_age = 3600
<7> try:
<8> d = await func(response, *args, **kwargs)
<9> except LookupError as e:
<10> if "user_id" in kwargs:
<11> user_id: str = kwargs["user_id"] # type: ignore
<12> url = get_redirect_url(private=False, user_id=user_id)
<13> return RedirectResponse(url)
<14> logging.exception(e)
<15> d = get_error_svg()
<16> cache_max_age = 0
<17> except Exception as e:
<18> logging.exception(e)
<19> d = get_error_svg()
<20> cache_max_age = 0
<21>
<22> sio = io.StringIO()
<23> d.write(sio) # type: ignore
<24>
<25> print("SVG", datetime.now() - start)
<26>
<27> return Response(
<28> sio.getvalue(),
<29> media_type="image/svg+xml",
<30> status_code=status.HTTP_200_OK,
<31> headers={"Cache-Control": "public, max-age=" + str(cache_max_age)},
<32> )
<33>
<34> return wrapper
<35>
|
===========unchanged ref 0===========
at: backend.src.publisher.routers.decorators
get_redirect_url(prefix: str="", private: bool=False, user_id: Optional[str]=None) -> str
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: functools
wraps(wrapped: _AnyCallable, assigned: Sequence[str]=..., updated: Sequence[str]=...) -> Callable[[_T], _T]
at: io
StringIO(initial_value: Optional[str]=..., newline: Optional[str]=...)
at: io.StringIO
getvalue(self) -> str
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: src.publisher.render.error
get_error_svg() -> Drawing
at: typing
Callable = _CallableType(collections.abc.Callable, 2)
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.publisher.routers.decorators
# for standalone auth routes
def get_redirect_url(
prefix: str = "", private: bool = False, user_id: Optional[str] = None
) -> str:
url = (
"https://github.com/login/oauth/authorize?client_id="
+ OAUTH_CLIENT_ID
+ "&redirect_uri="
+ OAUTH_REDIRECT_URI
+ "/redirect"
)
# add prefix to redirect to different backend routes
+ if prefix != "":
- if len(prefix) > 0:
+ url += f"/{prefix}"
- url += "/" + prefix
# add private flag to request correct permissions
if private:
url += "?private_access=True&scope=user,repo"
else:
url += "?private_access=False"
# add user_id to hint if provided
if user_id is not None:
+ url += f"&login={user_id}"
- url += "&login=" + user_id
return url
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 2===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 3===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 4===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 5===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 6===========
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
access_token = get_access_token()
try:
data = github_get_user_starred_repos(user_id, access_token)
data = [x["repo"]["full_name"] for x in data]
return data
except RESTErrorNotFound:
# User does not exist (and rate limited previously)
return []
except RESTError:
# Rate limited, so assume user starred repo
+ return [f"{OWNER}/{REPO}"]
- return [OWNER + "/" + REPO]
===========changed ref 7===========
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
# Checks the repo's starred users (with cache)
repo_stargazers = await get_repo_stargazers(owner, repo)
if user_id in repo_stargazers:
return True
# Checks the user's 30 most recent starred repos (no cache)
user_stars = await get_user_stars(user_id)
+ return f"{owner}/{repo}" in user_stars
- if f"{owner}/{repo}" in user_stars:
- return True
- return False
-
===========changed ref 8===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
|
backend.src.subscriber.processing.user/query_user
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<s>src.subscriber.processing.user
# NOTE: can only be called once every 1-2 minutes from publisher due to separate alru_cache
@alru_cache(ttl=timedelta(hours=6))
async def query_user(
user_id: str,
access_token: Optional[str],
private_access: bool = False,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
no_cache: bool = False,
) -> UserPackage:
<0> # Return (possibly incomplete) within 45 seconds
<1> start_time = datetime.now()
<2> incomplete = False
<3>
<4> await update_keys()
<5>
<6> curr_data: List[UserMonth] = await get_user_months(
<7> user_id, private_access, start_date, end_date
<8> )
<9> curr_months = [x.month for x in curr_data if x.complete]
<10>
<11> month, year = start_date.month, start_date.year
<12> months: List[date] = []
<13> while date(year, month, 1) <= end_date:
<14> start = date(year, month, 1)
<15> if date_to_datetime(start) not in curr_months:
<16> months.append(start)
<17> month = month % 12 + 1
<18> year = year + (month == 1)
<19>
<20> # Start with complete months and add any incomplete months
<21> all_user_packages: List[UserPackage] = [x.data for x in curr_data if x.complete]
<22> for month in months:
<23> if datetime.now() - start_time < timedelta(seconds=40):
<24> temp = await query_user_month(user_id, access_token, private_access, month)
<25> if temp is not None:
<26> all_user_packages.append(temp.data)
<27> else:
<28> incomplete = True
<29> else:
<30> incomplete = True
<31>
<32> out: UserPackage = UserPackage.empty()
<33> if len(all_user</s>
|
===========below chunk 0===========
<s>.user
# NOTE: can only be called once every 1-2 minutes from publisher due to separate alru_cache
@alru_cache(ttl=timedelta(hours=6))
async def query_user(
user_id: str,
access_token: Optional[str],
private_access: bool = False,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
no_cache: bool = False,
) -> UserPackage:
# offset: 1
out = all_user_packages[0]
for user_package in all_user_packages[1:]:
out += user_package
out.incomplete = incomplete
if incomplete or len(months) > 1:
# cache buster for publisher
if PROD:
s.get(BACKEND_URL + "/user/" + user_id + "?no_cache=True")
elif DOCKER:
s.get(LOCAL_PUBLISHER + "/user/" + user_id + "?no_cache=True")
return (False, out) # type: ignore
# only cache if just the current month updated
return (True, out) # type: ignore
===========unchanged ref 0===========
at: backend.src.subscriber.processing.user
s = requests.Session()
query_user_month(user_id: str, access_token: Optional[str], private_access: bool, start_date: date, retries: int=0) -> Optional[UserMonth]
at: datetime
timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...)
date()
datetime()
at: datetime.date
__slots__ = '_year', '_month', '_day', '_hashcode'
today() -> _S
__str__ = isoformat
__radd__ = __add__
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: datetime.timedelta
__slots__ = '_days', '_seconds', '_microseconds', '_hashcode'
__radd__ = __add__
__rmul__ = __mul__
at: requests.sessions.Session
__attrs__ = [
"headers",
"cookies",
"auth",
"proxies",
"hooks",
"params",
"verify",
"cert",
"adapters",
"stream",
"trust_env",
"max_redirects",
]
get(url: Union[Text, bytes], **kwargs) -> Response
at: src.constants
PROD = os.getenv("PROD", "False") == "True"
DOCKER = os.getenv("DOCKER", "False") == "True"
BACKEND_URL = "https://api.githubtrends.io" if PROD else "http://localhost:8000"
LOCAL_PUBLISHER = "http://backend:8000" if DOCKER else BACKEND_URL
===========unchanged ref 1===========
at: src.data.mongo.secret.functions
update_keys() -> None
at: src.data.mongo.user_months.get
get_user_months(user_id: str, private_access: bool, start_month: date, end_month: date) -> List[UserMonth]
at: src.data.mongo.user_months.models.UserMonth
user_id: str
month: datetime
version: float
private: bool
complete: bool
data: UserPackage
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
empty() -> "UserPackage"
at: src.utils.alru_cache
alru_cache(max_size: int=128, ttl: timedelta=timedelta(minutes=1))
at: src.utils.utils
date_to_datetime(dt: date, hour: int=0, minute: int=0, second: int=0) -> datetime
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
|
|
backend.src.models.user.contribs/ContributionStats.compress
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<10>:<add> *[[name] + stats.compress() for name, stats in self.languages.items()],
<11>:<del>
<12>:<del> out.extend(
<13>:<del> [[name] + stats.compress() for name, stats in self.languages.items()]
<14>:<del> )
|
# module: backend.src.models.user.contribs
class ContributionStats(BaseModel):
def compress(self) -> List[Any]:
<0> out: List[Any] = [
<1> [
<2> self.contribs_count,
<3> self.commits_count,
<4> self.issues_count,
<5> self.prs_count,
<6> self.reviews_count,
<7> self.repos_count,
<8> self.other_count,
<9> ],
<10> ]
<11>
<12> out.extend(
<13> [[name] + stats.compress() for name, stats in self.languages.items()]
<14> )
<15>
<16> return out
<17>
|
===========unchanged ref 0===========
at: backend.src.models.user.contribs.ContributionStats
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
at: backend.src.models.user.contribs.Language
color: Optional[str]
additions: int
deletions: int
compress() -> List[Any]
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
access_token = get_access_token()
try:
data = github_get_user_starred_repos(user_id, access_token)
data = [x["repo"]["full_name"] for x in data]
return data
except RESTErrorNotFound:
# User does not exist (and rate limited previously)
return []
except RESTError:
# Rate limited, so assume user starred repo
+ return [f"{OWNER}/{REPO}"]
- return [OWNER + "/" + REPO]
===========changed ref 6===========
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
# Checks the repo's starred users (with cache)
repo_stargazers = await get_repo_stargazers(owner, repo)
if user_id in repo_stargazers:
return True
# Checks the user's 30 most recent starred repos (no cache)
user_stars = await get_user_stars(user_id)
+ return f"{owner}/{repo}" in user_stars
- if f"{owner}/{repo}" in user_stars:
- return True
- return False
-
===========changed ref 7===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
===========changed ref 8===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 9===========
# module: backend.src.publisher.routers.decorators
# for standalone auth routes
def get_redirect_url(
prefix: str = "", private: bool = False, user_id: Optional[str] = None
) -> str:
url = (
"https://github.com/login/oauth/authorize?client_id="
+ OAUTH_CLIENT_ID
+ "&redirect_uri="
+ OAUTH_REDIRECT_URI
+ "/redirect"
)
# add prefix to redirect to different backend routes
+ if prefix != "":
- if len(prefix) > 0:
+ url += f"/{prefix}"
- url += "/" + prefix
# add private flag to request correct permissions
if private:
url += "?private_access=True&scope=user,repo"
else:
url += "?private_access=False"
# add user_id to hint if provided
if user_id is not None:
+ url += f"&login={user_id}"
- url += "&login=" + user_id
return url
|
backend.src.subscriber.aggregation.wrapped.numeric/format_loc_number
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<3>:<add> return f"{str(round(number / 1000.0))},000"
<del> return str(round(number / 1e3)) + ",000"
<4>:<add> return f"{str(round(number / 1000000.0))},000,000"
<del> return str(round(number / 1e6)) + ",000,000"
|
# module: backend.src.subscriber.aggregation.wrapped.numeric
def format_loc_number(number: int) -> str:
<0> if number < 1e3:
<1> return str(100 * round(number / 100))
<2> if number < 1e6:
<3> return str(round(number / 1e3)) + ",000"
<4> return str(round(number / 1e6)) + ",000,000"
<5>
|
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
access_token = get_access_token()
try:
data = github_get_user_starred_repos(user_id, access_token)
data = [x["repo"]["full_name"] for x in data]
return data
except RESTErrorNotFound:
# User does not exist (and rate limited previously)
return []
except RESTError:
# Rate limited, so assume user starred repo
+ return [f"{OWNER}/{REPO}"]
- return [OWNER + "/" + REPO]
===========changed ref 6===========
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
# Checks the repo's starred users (with cache)
repo_stargazers = await get_repo_stargazers(owner, repo)
if user_id in repo_stargazers:
return True
# Checks the user's 30 most recent starred repos (no cache)
user_stars = await get_user_stars(user_id)
+ return f"{owner}/{repo}" in user_stars
- if f"{owner}/{repo}" in user_stars:
- return True
- return False
-
===========changed ref 7===========
# module: backend.src.models.user.contribs
class ContributionStats(BaseModel):
def compress(self) -> List[Any]:
out: List[Any] = [
[
self.contribs_count,
self.commits_count,
self.issues_count,
self.prs_count,
self.reviews_count,
self.repos_count,
self.other_count,
],
+ *[[name] + stats.compress() for name, stats in self.languages.items()],
]
-
- out.extend(
- [[name] + stats.compress() for name, stats in self.languages.items()]
- )
return out
===========changed ref 8===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
===========changed ref 9===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
===========changed ref 10===========
# module: backend.src.publisher.routers.decorators
# for standalone auth routes
def get_redirect_url(
prefix: str = "", private: bool = False, user_id: Optional[str] = None
) -> str:
url = (
"https://github.com/login/oauth/authorize?client_id="
+ OAUTH_CLIENT_ID
+ "&redirect_uri="
+ OAUTH_REDIRECT_URI
+ "/redirect"
)
# add prefix to redirect to different backend routes
+ if prefix != "":
- if len(prefix) > 0:
+ url += f"/{prefix}"
- url += "/" + prefix
# add private flag to request correct permissions
if private:
url += "?private_access=True&scope=user,repo"
else:
url += "?private_access=False"
# add user_id to hint if provided
if user_id is not None:
+ url += f"&login={user_id}"
- url += "&login=" + user_id
return url
|
backend.src.subscriber.aggregation.wrapped.numeric/get_loc_stats
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<3>:<add> "loc_additions": format_loc_number(sum(x.additions for x in dataset)),
<del> "loc_additions": format_loc_number(sum([x.additions for x in dataset])),
<4>:<add> "loc_deletions": format_loc_number(sum(x.deletions for x in dataset)),
<del> "loc_deletions": format_loc_number(sum([x.deletions for x in dataset])),
<6>:<add> sum(x.additions + x.deletions for x in dataset)
<del> sum([x.additions + x.deletions for x in dataset])
<9>:<add> sum(x.additions - x.deletions for x in dataset)
<del> sum([x.additions - x.deletions for x in dataset])
<12>:<add> (
<add> sum(x.additions for x in dataset)
<del> sum([x.additions for x in dataset])
<13>:<add> / max(1, data.contribs.total_stats.commits_count)
<del> / max(1, data.contribs.total_stats.commits_count)
<14>:<add> )
<16>:<add> (
<add> sum(x.deletions for x in dataset)
<del> sum([x.deletions for x in dataset])
<17>:<add> / max(1, data.contribs.total_stats.commits_count)
<del> / max(1, data.contribs.total_stats.commits_count)
<18>:<add> )
<20>:<add> sum(x.additions + x.deletions for x in dataset) / 365
<del> sum([x.additions + x.deletions for x in dataset]) / 365
|
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_loc_stats(data: UserPackage) -> LOCStats:
<0> dataset = data.contribs.total_stats.languages.values()
<1> return LOCStats.parse_obj(
<2> {
<3> "loc_additions": format_loc_number(sum([x.additions for x in dataset])),
<4> "loc_deletions": format_loc_number(sum([x.deletions for x in dataset])),
<5> "loc_changed": format_loc_number(
<6> sum([x.additions + x.deletions for x in dataset])
<7> ),
<8> "loc_added": format_loc_number(
<9> sum([x.additions - x.deletions for x in dataset])
<10> ),
<11> "loc_additions_per_commit": round(
<12> sum([x.additions for x in dataset])
<13> / max(1, data.contribs.total_stats.commits_count)
<14> ),
<15> "loc_deletions_per_commit": round(
<16> sum([x.deletions for x in dataset])
<17> / max(1, data.contribs.total_stats.commits_count)
<18> ),
<19> "loc_changed_per_day": round(
<20> sum([x.additions + x.deletions for x in dataset]) / 365
<21> ),
<22> }
<23> )
<24>
|
===========unchanged ref 0===========
at: backend.src.subscriber.aggregation.wrapped.numeric
format_loc_number(number: int) -> str
at: src.models.user.contribs.ContributionStats
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.Language
color: Optional[str]
additions: int
deletions: int
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
public_stats: ContributionStats
total: List[ContributionDay]
public: List[ContributionDay]
repo_stats: Dict[str, RepoContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
===========changed ref 0===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def format_loc_number(number: int) -> str:
if number < 1e3:
return str(100 * round(number / 100))
if number < 1e6:
+ return f"{str(round(number / 1000.0))},000"
- return str(round(number / 1e3)) + ",000"
+ return f"{str(round(number / 1000000.0))},000,000"
- return str(round(number / 1e6)) + ",000,000"
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 2===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 3===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 4===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 5===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 6===========
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
access_token = get_access_token()
try:
data = github_get_user_starred_repos(user_id, access_token)
data = [x["repo"]["full_name"] for x in data]
return data
except RESTErrorNotFound:
# User does not exist (and rate limited previously)
return []
except RESTError:
# Rate limited, so assume user starred repo
+ return [f"{OWNER}/{REPO}"]
- return [OWNER + "/" + REPO]
===========changed ref 7===========
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
# Checks the repo's starred users (with cache)
repo_stargazers = await get_repo_stargazers(owner, repo)
if user_id in repo_stargazers:
return True
# Checks the user's 30 most recent starred repos (no cache)
user_stars = await get_user_stars(user_id)
+ return f"{owner}/{repo}" in user_stars
- if f"{owner}/{repo}" in user_stars:
- return True
- return False
-
===========changed ref 8===========
# module: backend.src.models.user.contribs
class ContributionStats(BaseModel):
def compress(self) -> List[Any]:
out: List[Any] = [
[
self.contribs_count,
self.commits_count,
self.issues_count,
self.prs_count,
self.reviews_count,
self.repos_count,
self.other_count,
],
+ *[[name] + stats.compress() for name, stats in self.languages.items()],
]
-
- out.extend(
- [[name] + stats.compress() for name, stats in self.languages.items()]
- )
return out
===========changed ref 9===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
|
backend.src.subscriber.aggregation.wrapped.repos/get_repo_data
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<20>:<del> total_count = 0
<21>:<del> for (k, v) in list(repos)[5:]:
<22>:<del> total_count += _count_repo_loc(v, m)
<23>:<add> total_count = sum(_count_repo_loc(v, m) for _, v in list(repos)[5:])
<32>:<add> out[f"repos_{m}"] = repo_objs
<del> out["repos_" + m] = repo_objs
|
# module: backend.src.subscriber.aggregation.wrapped.repos
def get_repo_data(data: UserPackage) -> RepoData:
<0> out = {}
<1> for m in ["changed", "added"]:
<2> repos = sorted(
<3> data.contribs.repo_stats.items(),
<4> key=lambda x: _count_repo_loc(x[1], m),
<5> reverse=True,
<6> )
<7> repo_objs: List[RepoDatum] = []
<8>
<9> # first five repositories
<10> for i, (k, v) in enumerate(list(repos)[:5]):
<11> repo_data = {
<12> "id": i,
<13> "label": "private/repository" if v.private else k,
<14> "value": _count_repo_loc(v, m),
<15> "formatted_value": format_number(_count_repo_loc(v, m)),
<16> }
<17> repo_objs.append(RepoDatum.parse_obj(repo_data))
<18>
<19> # remaining repositories
<20> total_count = 0
<21> for (k, v) in list(repos)[5:]:
<22> total_count += _count_repo_loc(v, m)
<23> repo_data = {
<24> "id": -1,
<25> "label": "other",
<26> "value": total_count,
<27> "formatted_value": format_number(total_count),
<28> }
<29> if total_count > 100:
<30> repo_objs.append(RepoDatum.parse_obj(repo_data))
<31>
<32> out["repos_" + m] = repo_objs
<33>
<34> return RepoData.parse_obj(out)
<35>
|
===========unchanged ref 0===========
at: backend.src.subscriber.aggregation.wrapped.repos
_count_repo_loc(x: RepoContributionStats, metric: str) -> int
at: src.models.user.contribs.RepoContributionStats
private: bool
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
public_stats: ContributionStats
total: List[ContributionDay]
public: List[ContributionDay]
repo_stats: Dict[str, RepoContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
at: src.utils.utils
format_number(num: int) -> str
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def format_loc_number(number: int) -> str:
if number < 1e3:
return str(100 * round(number / 100))
if number < 1e6:
+ return f"{str(round(number / 1000.0))},000"
- return str(round(number / 1e3)) + ",000"
+ return f"{str(round(number / 1000000.0))},000,000"
- return str(round(number / 1e6)) + ",000,000"
===========changed ref 6===========
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
access_token = get_access_token()
try:
data = github_get_user_starred_repos(user_id, access_token)
data = [x["repo"]["full_name"] for x in data]
return data
except RESTErrorNotFound:
# User does not exist (and rate limited previously)
return []
except RESTError:
# Rate limited, so assume user starred repo
+ return [f"{OWNER}/{REPO}"]
- return [OWNER + "/" + REPO]
===========changed ref 7===========
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
# Checks the repo's starred users (with cache)
repo_stargazers = await get_repo_stargazers(owner, repo)
if user_id in repo_stargazers:
return True
# Checks the user's 30 most recent starred repos (no cache)
user_stars = await get_user_stars(user_id)
+ return f"{owner}/{repo}" in user_stars
- if f"{owner}/{repo}" in user_stars:
- return True
- return False
-
===========changed ref 8===========
# module: backend.src.models.user.contribs
class ContributionStats(BaseModel):
def compress(self) -> List[Any]:
out: List[Any] = [
[
self.contribs_count,
self.commits_count,
self.issues_count,
self.prs_count,
self.reviews_count,
self.repos_count,
self.other_count,
],
+ *[[name] + stats.compress() for name, stats in self.languages.items()],
]
-
- out.extend(
- [[name] + stats.compress() for name, stats in self.languages.items()]
- )
return out
===========changed ref 9===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
|
backend.src.subscriber.aggregation.user.contributions/get_all_commit_languages
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<12>:<add> node_id_chunks: List[List[str]] = [
<del> node_id_chunks: List[List[str]] = []
<13>:<del> for i in range(0, len(all_node_ids), GRAPHQL_NODE_CHUNK_SIZE):
<14>:<del> node_id_chunks.append(
<15>:<add> all_node_ids[i : min(len(all_node_ids), i + GRAPHQL_NODE_CHUNK_SIZE)]
<del> all_node_ids[i : min(len(all_node_ids), i + GRAPHQL_NODE_CHUNK_SIZE)]
<16>:<add> for i in range(0, len(all_node_ids), GRAPHQL_NODE_CHUNK_SIZE)
<add> ]
<del> )
|
# module: backend.src.subscriber.aggregation.user.contributions
def get_all_commit_languages(
commit_infos: List[List[RESTRawCommit]],
repos: List[str],
repo_infos: Dict[str, RawRepo],
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> Tuple[Dict[str, List[datetime]], Dict[str, List[CommitLanguages]]]:
<0> commit_node_ids = [[x.node_id for x in repo] for repo in commit_infos]
<1> commit_times = [[x.timestamp for x in repo] for repo in commit_infos]
<2>
<3> id_mapping: Dict[str, Tuple[int, int]] = {}
<4> repo_mapping: Dict[str, str] = {}
<5> all_node_ids: List[str] = []
<6> for i, repo_node_ids in enumerate(commit_node_ids):
<7> for j, node_id in enumerate(repo_node_ids):
<8> id_mapping[node_id] = (i, j)
<9> repo_mapping[node_id] = repos[i]
<10> all_node_ids.append(node_id)
<11>
<12> node_id_chunks: List[List[str]] = []
<13> for i in range(0, len(all_node_ids), GRAPHQL_NODE_CHUNK_SIZE):
<14> node_id_chunks.append(
<15> all_node_ids[i : min(len(all_node_ids), i + GRAPHQL_NODE_CHUNK_SIZE)]
<16> )
<17>
<18> commit_language_chunks: List[List[Optional[GraphQLRawCommit]]] = await gather(
<19> funcs=[get_commits for _ in node_id_chunks],
<20> args_dicts=[
<21> {
<22> "node_ids": node_id_chunk,
<23> "access_token": access_token,
<24> "catch_errors": catch_errors,
<25> }
<26> for node_id_chunk in node_id_chunks
<27> ],
<28> </s>
|
===========below chunk 0===========
# module: backend.src.subscriber.aggregation.user.contributions
def get_all_commit_languages(
commit_infos: List[List[RESTRawCommit]],
repos: List[str],
repo_infos: Dict[str, RawRepo],
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> Tuple[Dict[str, List[datetime]], Dict[str, List[CommitLanguages]]]:
# offset: 1
)
temp_commit_languages: List[Optional[GraphQLRawCommit]] = []
for commit_language_chunk in commit_language_chunks:
temp_commit_languages.extend(commit_language_chunk)
# returns commits with no associated PR or incomplete PR
filtered_commits: List[GraphQLRawCommit] = filter(
lambda x: x is not None
and (len(x.prs.nodes) == 0 or x.prs.nodes[0].changed_files > PR_FILES)
and (x.additions + x.deletions > 100),
temp_commit_languages,
) # type: ignore
# get NODE_QUERIES largest commits with no associated PR or incomplete PR
sorted_commits = sorted(
filtered_commits, key=lambda x: x.additions + x.deletions, reverse=True
)[:NODE_QUERIES]
sorted_commit_urls = [commit.url.split("/") for commit in sorted_commits]
commit_files: List[List[RawCommitFile]] = await gather(
funcs=[get_commit_files for _ in sorted_commit_urls],
args_dicts=[
{
"owner": url[3],
"repo": url[4],
"sha": url[6],
"access_token": access_token,
}
for url in sorted_commit_urls
],
max_threads=REST_NODE_THREADS,
)
commit_files_dict: Dict[str, List[RawCommitFile]] = {}
for commit, commit_file in zip(sorted_commits, commit_</s>
===========below chunk 1===========
# module: backend.src.subscriber.aggregation.user.contributions
def get_all_commit_languages(
commit_infos: List[List[RESTRawCommit]],
repos: List[str],
repo_infos: Dict[str, RawRepo],
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> Tuple[Dict[str, List[datetime]], Dict[str, List[CommitLanguages]]]:
# offset: 2
<s>: Dict[str, List[RawCommitFile]] = {}
for commit, commit_file in zip(sorted_commits, commit_files):
commit_files_dict[commit.url] = commit_file
commit_languages: List[List[CommitLanguages]] = [
[CommitLanguages() for _ in repo] for repo in commit_infos
]
for raw_commits, node_ids in zip(commit_language_chunks, node_id_chunks):
for raw_commit, node_id in zip(raw_commits, node_ids):
curr_commit_files: Optional[List[RawCommitFile]] = None
if raw_commit is not None and raw_commit.url in commit_files_dict:
curr_commit_files = commit_files_dict[raw_commit.url]
lang_breakdown = get_commit_languages(
raw_commit, curr_commit_files, repo_infos[repo_mapping[node_id]]
)
i, j = id_mapping[node_id]
commit_languages[i][j] = lang_breakdown
commit_times_dict: Dict[str, List[datetime]] = {}
commit_languages_dict: Dict[str, List[CommitLanguages]] = {}
for repo, times, languages in zip(repos, commit_times, commit_languages):
commit_times_dict[repo] = times
commit_languages_dict[repo] = languages
return commit_times_dict, commit_languages_dict
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def format_loc_number(number: int) -> str:
if number < 1e3:
return str(100 * round(number / 100))
if number < 1e6:
+ return f"{str(round(number / 1000.0))},000"
- return str(round(number / 1e3)) + ",000"
+ return f"{str(round(number / 1000000.0))},000,000"
- return str(round(number / 1e6)) + ",000,000"
|
backend.src.subscriber.aggregation.user.contributions/get_contributions
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
# module: backend.src.subscriber.aggregation.user.contributions
def get_contributions(
user_id: str,
start_date: date,
end_date: date,
timezone_str: str = "US/Eastern",
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> UserContributions:
<0> tz = pytz.timezone(timezone_str)
<1>
<2> start_month = date_to_datetime(start_date)
<3> end_month = date_to_datetime(end_date, hour=23, minute=59, second=59)
<4> (
<5> calendar,
<6> contrib_events,
<7> repo_infos,
<8> commit_times_dict,
<9> commit_languages_dict,
<10> ) = await get_cleaned_contributions(
<11> user_id, start_month, end_month, access_token, catch_errors
<12> )
<13>
<14> total_stats = StatsContainer()
<15> public_stats = StatsContainer()
<16> total: Dict[str, DateContainer] = defaultdict(DateContainer)
<17> public: Dict[str, DateContainer] = defaultdict(DateContainer)
<18> repo_stats: Dict[str, StatsContainer] = defaultdict(StatsContainer)
<19> repositories: Dict[str, Dict[str, DateContainer]] = defaultdict(
<20> lambda: defaultdict(DateContainer)
<21> )
<22>
<23> for week in calendar.weeks:
<24> for day in week.contribution_days:
<25> day_str = str(day.date)
<26> for (obj, stats_obj) in [(total, total_stats), (public, public_stats)]:
<27> obj[day_str].date = day.date.isoformat()
<28> obj[day_str].weekday = day.weekday
<29> obj[day_str].stats.contribs = day.count
<30> obj[day_str].stats.other = day.count
<31> stats_obj.contribs += day.count
<32> stats_obj.other += day.count
<33>
<34> def update_</s>
|
===========below chunk 0===========
# module: backend.src.subscriber.aggregation.user.contributions
def get_contributions(
user_id: str,
start_date: date,
end_date: date,
timezone_str: str = "US/Eastern",
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> UserContributions:
# offset: 1
date_str: str, repo: str, event: str, count: int, times: List[datetime]
):
# update global counts for this event
total[date_str].add_stat(event, count, times)
total_stats.add_stat(event, count)
if not repo_infos[repo].is_private:
public[date_str].add_stat(event, count, times)
public_stats.add_stat(event, count)
repositories[repo][date_str].add_stat(event, count, times, add=True)
repo_stats[repo].add_stat(event, count, add=True)
def update_langs(date_str: str, repo: str, langs: CommitLanguages):
stores = [
total[date_str].stats.languages,
total_stats.languages,
repositories[repo][date_str].stats.languages,
repo_stats[repo].languages,
]
if not repo_infos[repo].is_private:
stores.append(public[date_str].stats.languages)
stores.append(public_stats.languages)
for store in stores:
store += langs
for repo, repo_events in contrib_events.items():
for (label, events) in [
("commit", repo_events.commits),
("issue", repo_events.issues),
("pr", repo_events.prs),
("review", repo_events.reviews),
("repo", repo_events.repos),
]:
events = sorted(events, key=lambda x: x.occurred_at)
for event in events:
datetime_obj = event.occur</s>
===========below chunk 1===========
# module: backend.src.subscriber.aggregation.user.contributions
def get_contributions(
user_id: str,
start_date: date,
end_date: date,
timezone_str: str = "US/Eastern",
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> UserContributions:
# offset: 2
<s>events, key=lambda x: x.occurred_at)
for event in events:
datetime_obj = event.occurred_at.astimezone(tz)
date_str = datetime_obj.date().isoformat()
repositories[repo][date_str].date = date_str
if isinstance(event, RawEventsCommit):
count = 0
commit_times: List[datetime] = []
while len(commit_languages_dict[repo]) > 0 and count < event.count:
commit_times.append(commit_times_dict[repo].pop(0))
langs = commit_languages_dict[repo].pop(0)
update_langs(date_str, repo, langs)
count += 1
update_stats(date_str, repo, "commit", event.count, commit_times)
else:
update_stats(date_str, repo, label, 1, [datetime_obj])
total_stats_dict = total_stats.to_dict()
public_stats_dict = public_stats.to_dict()
repo_stats_dict = {name: stats.to_dict() for name, stats in repo_stats.items()}
for repo in repo_stats:
repo_stats_dict[repo]["private"] = repo_infos[repo].is_private
total_list = [v.to_dict() for v in total.values() if v.stats.contribs > 0]
public_list = [v.to_dict() for v in public.values() if v.stats.contribs > 0]
</s>
===========below chunk 2===========
# module: backend.src.subscriber.aggregation.user.contributions
def get_contributions(
user_id: str,
start_date: date,
end_date: date,
timezone_str: str = "US/Eastern",
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> UserContributions:
# offset: 3
<s>list = {
name: list([v.to_dict() for v in repo.values()])
for name, repo in repositories.items()
}
output = UserContributions.parse_obj(
{
"total_stats": total_stats_dict,
"public_stats": public_stats_dict,
"total": total_list,
"public": public_list,
"repo_stats": repo_stats_dict,
"repos": repositories_list,
}
)
return output
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
|
|
backend.src.publisher.render.error/get_error_svg
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<13>:<add> d.add(d.text("Unknown Error", insert=(25, 35), class_=f"{THEME}-header"))
<del> d.add(d.text("Unknown Error", insert=(25, 35), class_=THEME + "-header"))
<19>:<add> class_=f"{THEME}-lang-name",
<del> class_=THEME + "-lang-name",
<24>:<add> d.image(f"{BACKEND_URL}/assets/error", insert=(85, 100), style="opacity: 50%")
<del> d.image(BACKEND_URL + "/assets/error", insert=(85, 100), style="opacity: 50%")
|
# module: backend.src.publisher.render.error
def get_error_svg() -> Drawing:
<0> d = Drawing(size=(300, 285))
<1> d.defs.add(d.style(styles_no_animation[THEME]))
<2>
<3> d.add(
<4> d.rect(
<5> size=(299, 284),
<6> insert=(0.5, 0.5),
<7> rx=4.5,
<8> stroke=themes[THEME]["border_color"],
<9> fill=themes[THEME]["bg_color"],
<10> )
<11> )
<12>
<13> d.add(d.text("Unknown Error", insert=(25, 35), class_=THEME + "-header"))
<14>
<15> d.add(
<16> d.text(
<17> "Please try again later or raise a ticket on GitHub",
<18> insert=(25, 60),
<19> class_=THEME + "-lang-name",
<20> )
<21> )
<22>
<23> d.add(
<24> d.image(BACKEND_URL + "/assets/error", insert=(85, 100), style="opacity: 50%")
<25> )
<26>
<27> return d
<28>
|
===========unchanged ref 0===========
at: backend.src.publisher.render.error
THEME = "classic"
at: src.constants
BACKEND_URL = "https://api.githubtrends.io" if PROD else "http://localhost:8000"
===========unchanged ref 1===========
at: src.publisher.render.style
themes = {
"classic": {
"header_color": "#2f80ed",
"subheader_color": "#666",
"text_color": "#333",
"bg_color": "#fffefe",
"border_color": "#e4e2e2",
"bar_color": "#ddd",
},
"dark": {
"header_color": "#fff",
"subheader_color": "#9f9f9f",
"text_color": "#9f9f9f",
"bg_color": "#151515",
"border_color": "#e4e2e2",
"bar_color": "#333",
},
"bright_lights": {
"header_color": "#fff",
"subheader_color": "#0e86d4",
"text_color": "#b1d4e0",
"bg_color": "#003060",
"border_color": "#0e86d4",
"bar_color": "#ddd",
},
"rosettes": {
"header_color": "#fff",
"subheader_color": "#b6e2d3",
"text_color": "#fae8e0",
"bg_color": "#ef7c8e",
"border_color": "#b6e2d3",
"bar_color": "#ddd",
},
"ferns": {
"header_color": "#116530",
"subheader_color": "#18a558",
"text_color": "#116530",
"bg_color": "#a3ebb1",
"border_color": "#21b6a8",
"bar_color": "#ddd",
},
"synthwaves": {
"header_color": "#e2e9ec",
"subheader_color": "#e5289e",
"text_color": "#ef8539",
"bg_color": "#2</s>
===========unchanged ref 2===========
styles_no_animation = {k: get_style(k, False) for k in themes.keys()}
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def format_loc_number(number: int) -> str:
if number < 1e3:
return str(100 * round(number / 100))
if number < 1e6:
+ return f"{str(round(number / 1000.0))},000"
- return str(round(number / 1e3)) + ",000"
+ return f"{str(round(number / 1000000.0))},000,000"
- return str(round(number / 1e6)) + ",000,000"
===========changed ref 6===========
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
access_token = get_access_token()
try:
data = github_get_user_starred_repos(user_id, access_token)
data = [x["repo"]["full_name"] for x in data]
return data
except RESTErrorNotFound:
# User does not exist (and rate limited previously)
return []
except RESTError:
# Rate limited, so assume user starred repo
+ return [f"{OWNER}/{REPO}"]
- return [OWNER + "/" + REPO]
===========changed ref 7===========
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
# Checks the repo's starred users (with cache)
repo_stargazers = await get_repo_stargazers(owner, repo)
if user_id in repo_stargazers:
return True
# Checks the user's 30 most recent starred repos (no cache)
user_stars = await get_user_stars(user_id)
+ return f"{owner}/{repo}" in user_stars
- if f"{owner}/{repo}" in user_stars:
- return True
- return False
-
|
backend.src.publisher.render.error/get_empty_demo_svg
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<13>:<add> d.add(d.text(header, insert=(25, 35), class_=f"{THEME}-header"))
<del> d.add(d.text(header, insert=(25, 35), class_=THEME + "-header"))
<19>:<add> class_=f"{THEME}-lang-name",
<del> class_=THEME + "-lang-name",
<25>:<add> f"{BACKEND_URL}/assets/stopwatch", insert=(85, 100), style="opacity: 50%"
<del> BACKEND_URL + "/assets/stopwatch", insert=(85, 100), style="opacity: 50%"
|
# module: backend.src.publisher.render.error
def get_empty_demo_svg(header: str) -> Drawing:
<0> d = Drawing(size=(300, 285))
<1> d.defs.add(d.style(styles_no_animation[THEME]))
<2>
<3> d.add(
<4> d.rect(
<5> size=(299, 284),
<6> insert=(0.5, 0.5),
<7> rx=4.5,
<8> stroke=themes[THEME]["border_color"],
<9> fill=themes[THEME]["bg_color"],
<10> )
<11> )
<12>
<13> d.add(d.text(header, insert=(25, 35), class_=THEME + "-header"))
<14>
<15> d.add(
<16> d.text(
<17> "Enter your username to start!",
<18> insert=(25, 60),
<19> class_=THEME + "-lang-name",
<20> )
<21> )
<22>
<23> d.add(
<24> d.image(
<25> BACKEND_URL + "/assets/stopwatch", insert=(85, 100), style="opacity: 50%"
<26> )
<27> )
<28>
<29> return d
<30>
|
===========unchanged ref 0===========
at: backend.src.publisher.render.error
THEME = "classic"
at: src.constants
BACKEND_URL = "https://api.githubtrends.io" if PROD else "http://localhost:8000"
===========unchanged ref 1===========
at: src.publisher.render.style
themes = {
"classic": {
"header_color": "#2f80ed",
"subheader_color": "#666",
"text_color": "#333",
"bg_color": "#fffefe",
"border_color": "#e4e2e2",
"bar_color": "#ddd",
},
"dark": {
"header_color": "#fff",
"subheader_color": "#9f9f9f",
"text_color": "#9f9f9f",
"bg_color": "#151515",
"border_color": "#e4e2e2",
"bar_color": "#333",
},
"bright_lights": {
"header_color": "#fff",
"subheader_color": "#0e86d4",
"text_color": "#b1d4e0",
"bg_color": "#003060",
"border_color": "#0e86d4",
"bar_color": "#ddd",
},
"rosettes": {
"header_color": "#fff",
"subheader_color": "#b6e2d3",
"text_color": "#fae8e0",
"bg_color": "#ef7c8e",
"border_color": "#b6e2d3",
"bar_color": "#ddd",
},
"ferns": {
"header_color": "#116530",
"subheader_color": "#18a558",
"text_color": "#116530",
"bg_color": "#a3ebb1",
"border_color": "#21b6a8",
"bar_color": "#ddd",
},
"synthwaves": {
"header_color": "#e2e9ec",
"subheader_color": "#e5289e",
"text_color": "#ef8539",
"bg_color": "#2</s>
===========unchanged ref 2===========
styles_no_animation = {k: get_style(k, False) for k in themes.keys()}
===========changed ref 0===========
# module: backend.src.publisher.render.error
def get_error_svg() -> Drawing:
d = Drawing(size=(300, 285))
d.defs.add(d.style(styles_no_animation[THEME]))
d.add(
d.rect(
size=(299, 284),
insert=(0.5, 0.5),
rx=4.5,
stroke=themes[THEME]["border_color"],
fill=themes[THEME]["bg_color"],
)
)
+ d.add(d.text("Unknown Error", insert=(25, 35), class_=f"{THEME}-header"))
- d.add(d.text("Unknown Error", insert=(25, 35), class_=THEME + "-header"))
d.add(
d.text(
"Please try again later or raise a ticket on GitHub",
insert=(25, 60),
+ class_=f"{THEME}-lang-name",
- class_=THEME + "-lang-name",
)
)
d.add(
+ d.image(f"{BACKEND_URL}/assets/error", insert=(85, 100), style="opacity: 50%")
- d.image(BACKEND_URL + "/assets/error", insert=(85, 100), style="opacity: 50%")
)
return d
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 2===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 3===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 4===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 5===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 6===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def format_loc_number(number: int) -> str:
if number < 1e3:
return str(100 * round(number / 100))
if number < 1e6:
+ return f"{str(round(number / 1000.0))},000"
- return str(round(number / 1e3)) + ",000"
+ return f"{str(round(number / 1000000.0))},000,000"
- return str(round(number / 1e6)) + ",000,000"
|
backend.src.publisher.render.error/get_loading_svg
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<14>:<add> d.text("Loading data, hang tight!", insert=(25, 35), class_=f"{THEME}-header")
<del> d.text("Loading data, hang tight!", insert=(25, 35), class_=THEME + "-header")
<21>:<add> class_=f"{THEME}-lang-name",
<del> class_=THEME + "-lang-name",
<27>:<add> f"{BACKEND_URL}/assets/stopwatch", insert=(85, 100), style="opacity: 50%"
<del> BACKEND_URL + "/assets/stopwatch", insert=(85, 100), style="opacity: 50%"
|
# module: backend.src.publisher.render.error
def get_loading_svg() -> Drawing:
<0> d = Drawing(size=(300, 285))
<1> d.defs.add(d.style(styles_no_animation[THEME]))
<2>
<3> d.add(
<4> d.rect(
<5> size=(299, 284),
<6> insert=(0.5, 0.5),
<7> rx=4.5,
<8> stroke=themes[THEME]["border_color"],
<9> fill=themes[THEME]["bg_color"],
<10> )
<11> )
<12>
<13> d.add(
<14> d.text("Loading data, hang tight!", insert=(25, 35), class_=THEME + "-header")
<15> )
<16>
<17> d.add(
<18> d.text(
<19> "Please wait a couple seconds and refresh the page.",
<20> insert=(25, 60),
<21> class_=THEME + "-lang-name",
<22> )
<23> )
<24>
<25> d.add(
<26> d.image(
<27> BACKEND_URL + "/assets/stopwatch", insert=(85, 100), style="opacity: 50%"
<28> )
<29> )
<30>
<31> return d
<32>
|
===========unchanged ref 0===========
at: backend.src.publisher.render.error
THEME = "classic"
at: src.constants
BACKEND_URL = "https://api.githubtrends.io" if PROD else "http://localhost:8000"
===========unchanged ref 1===========
at: src.publisher.render.style
themes = {
"classic": {
"header_color": "#2f80ed",
"subheader_color": "#666",
"text_color": "#333",
"bg_color": "#fffefe",
"border_color": "#e4e2e2",
"bar_color": "#ddd",
},
"dark": {
"header_color": "#fff",
"subheader_color": "#9f9f9f",
"text_color": "#9f9f9f",
"bg_color": "#151515",
"border_color": "#e4e2e2",
"bar_color": "#333",
},
"bright_lights": {
"header_color": "#fff",
"subheader_color": "#0e86d4",
"text_color": "#b1d4e0",
"bg_color": "#003060",
"border_color": "#0e86d4",
"bar_color": "#ddd",
},
"rosettes": {
"header_color": "#fff",
"subheader_color": "#b6e2d3",
"text_color": "#fae8e0",
"bg_color": "#ef7c8e",
"border_color": "#b6e2d3",
"bar_color": "#ddd",
},
"ferns": {
"header_color": "#116530",
"subheader_color": "#18a558",
"text_color": "#116530",
"bg_color": "#a3ebb1",
"border_color": "#21b6a8",
"bar_color": "#ddd",
},
"synthwaves": {
"header_color": "#e2e9ec",
"subheader_color": "#e5289e",
"text_color": "#ef8539",
"bg_color": "#2</s>
===========unchanged ref 2===========
styles_no_animation = {k: get_style(k, False) for k in themes.keys()}
===========changed ref 0===========
# module: backend.src.publisher.render.error
def get_empty_demo_svg(header: str) -> Drawing:
d = Drawing(size=(300, 285))
d.defs.add(d.style(styles_no_animation[THEME]))
d.add(
d.rect(
size=(299, 284),
insert=(0.5, 0.5),
rx=4.5,
stroke=themes[THEME]["border_color"],
fill=themes[THEME]["bg_color"],
)
)
+ d.add(d.text(header, insert=(25, 35), class_=f"{THEME}-header"))
- d.add(d.text(header, insert=(25, 35), class_=THEME + "-header"))
d.add(
d.text(
"Enter your username to start!",
insert=(25, 60),
+ class_=f"{THEME}-lang-name",
- class_=THEME + "-lang-name",
)
)
d.add(
d.image(
+ f"{BACKEND_URL}/assets/stopwatch", insert=(85, 100), style="opacity: 50%"
- BACKEND_URL + "/assets/stopwatch", insert=(85, 100), style="opacity: 50%"
)
)
return d
===========changed ref 1===========
# module: backend.src.publisher.render.error
def get_error_svg() -> Drawing:
d = Drawing(size=(300, 285))
d.defs.add(d.style(styles_no_animation[THEME]))
d.add(
d.rect(
size=(299, 284),
insert=(0.5, 0.5),
rx=4.5,
stroke=themes[THEME]["border_color"],
fill=themes[THEME]["bg_color"],
)
)
+ d.add(d.text("Unknown Error", insert=(25, 35), class_=f"{THEME}-header"))
- d.add(d.text("Unknown Error", insert=(25, 35), class_=THEME + "-header"))
d.add(
d.text(
"Please try again later or raise a ticket on GitHub",
insert=(25, 60),
+ class_=f"{THEME}-lang-name",
- class_=THEME + "-lang-name",
)
)
d.add(
+ d.image(f"{BACKEND_URL}/assets/error", insert=(85, 100), style="opacity: 50%")
- d.image(BACKEND_URL + "/assets/error", insert=(85, 100), style="opacity: 50%")
)
return d
===========changed ref 2===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 4===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 5===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
|
backend.src.publisher.render.error/get_no_data_svg
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<10>:<add> d.add(d.image(f"{BACKEND_URL}/assets/error", insert=(85, 80), style="opacity: 50%"))
<del> d.add(d.image(BACKEND_URL + "/assets/error", insert=(85, 80), style="opacity: 50%"))
<11>:<add>
<add> dp.add(d.text("No data to show", insert=(55, 220), class_=f"{THEME}-image-text"))
<del> dp.add(d.text("No data to show", insert=(55, 220), class_=THEME + "-image-text"))
|
# module: backend.src.publisher.render.error
def get_no_data_svg(header: str, subheader: str) -> Drawing:
<0> d, dp = get_template(
<1> width=300,
<2> height=285,
<3> padding=20,
<4> header_text=header,
<5> subheader_text=subheader,
<6> debug=False,
<7> theme=THEME,
<8> )
<9>
<10> d.add(d.image(BACKEND_URL + "/assets/error", insert=(85, 80), style="opacity: 50%"))
<11> dp.add(d.text("No data to show", insert=(55, 220), class_=THEME + "-image-text"))
<12>
<13> d.add(dp)
<14> return d
<15>
|
===========unchanged ref 0===========
at: backend.src.publisher.render.error
THEME = "classic"
at: src.constants
BACKEND_URL = "https://api.githubtrends.io" if PROD else "http://localhost:8000"
at: src.publisher.render.template
get_template(width: int, height: int, padding: int, header_text: str, subheader_text: str, theme: str, use_animation: bool=True, debug: bool=False) -> Tuple[Drawing, Group]
===========changed ref 0===========
# module: backend.src.publisher.render.error
def get_loading_svg() -> Drawing:
d = Drawing(size=(300, 285))
d.defs.add(d.style(styles_no_animation[THEME]))
d.add(
d.rect(
size=(299, 284),
insert=(0.5, 0.5),
rx=4.5,
stroke=themes[THEME]["border_color"],
fill=themes[THEME]["bg_color"],
)
)
d.add(
+ d.text("Loading data, hang tight!", insert=(25, 35), class_=f"{THEME}-header")
- d.text("Loading data, hang tight!", insert=(25, 35), class_=THEME + "-header")
)
d.add(
d.text(
"Please wait a couple seconds and refresh the page.",
insert=(25, 60),
+ class_=f"{THEME}-lang-name",
- class_=THEME + "-lang-name",
)
)
d.add(
d.image(
+ f"{BACKEND_URL}/assets/stopwatch", insert=(85, 100), style="opacity: 50%"
- BACKEND_URL + "/assets/stopwatch", insert=(85, 100), style="opacity: 50%"
)
)
return d
===========changed ref 1===========
# module: backend.src.publisher.render.error
def get_empty_demo_svg(header: str) -> Drawing:
d = Drawing(size=(300, 285))
d.defs.add(d.style(styles_no_animation[THEME]))
d.add(
d.rect(
size=(299, 284),
insert=(0.5, 0.5),
rx=4.5,
stroke=themes[THEME]["border_color"],
fill=themes[THEME]["bg_color"],
)
)
+ d.add(d.text(header, insert=(25, 35), class_=f"{THEME}-header"))
- d.add(d.text(header, insert=(25, 35), class_=THEME + "-header"))
d.add(
d.text(
"Enter your username to start!",
insert=(25, 60),
+ class_=f"{THEME}-lang-name",
- class_=THEME + "-lang-name",
)
)
d.add(
d.image(
+ f"{BACKEND_URL}/assets/stopwatch", insert=(85, 100), style="opacity: 50%"
- BACKEND_URL + "/assets/stopwatch", insert=(85, 100), style="opacity: 50%"
)
)
return d
===========changed ref 2===========
# module: backend.src.publisher.render.error
def get_error_svg() -> Drawing:
d = Drawing(size=(300, 285))
d.defs.add(d.style(styles_no_animation[THEME]))
d.add(
d.rect(
size=(299, 284),
insert=(0.5, 0.5),
rx=4.5,
stroke=themes[THEME]["border_color"],
fill=themes[THEME]["bg_color"],
)
)
+ d.add(d.text("Unknown Error", insert=(25, 35), class_=f"{THEME}-header"))
- d.add(d.text("Unknown Error", insert=(25, 35), class_=THEME + "-header"))
d.add(
d.text(
"Please try again later or raise a ticket on GitHub",
insert=(25, 60),
+ class_=f"{THEME}-lang-name",
- class_=THEME + "-lang-name",
)
)
d.add(
+ d.image(f"{BACKEND_URL}/assets/error", insert=(85, 100), style="opacity: 50%")
- d.image(BACKEND_URL + "/assets/error", insert=(85, 100), style="opacity: 50%")
)
return d
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 4===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 5===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 6===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 7===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
|
backend.src.utils.decorators/fail_gracefully
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<11>:<add> "message": f"Error {str(e)}",
<del> "message": "Error " + str(e),
|
# module: backend.src.utils.decorators
def fail_gracefully(func: Callable[..., Any]):
<0> @wraps(func) # needed to play nice with FastAPI decorator
<1> def wrapper(response: Response, *args: List[Any], **kwargs: Dict[str, Any]) -> Any:
<2> start = datetime.now()
<3> try:
<4> data = func(response, *args, **kwargs)
<5> return {"data": data, "message": "200 OK", "time": datetime.now() - start}
<6> except Exception as e:
<7> logging.exception(e)
<8> response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
<9> return {
<10> "data": [],
<11> "message": "Error " + str(e),
<12> "time": datetime.now() - start,
<13> }
<14>
<15> return wrapper
<16>
|
===========unchanged ref 0===========
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: functools
wraps(wrapped: _AnyCallable, assigned: Sequence[str]=..., updated: Sequence[str]=...) -> Callable[[_T], _T]
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: typing
Callable = _CallableType(collections.abc.Callable, 2)
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def format_loc_number(number: int) -> str:
if number < 1e3:
return str(100 * round(number / 100))
if number < 1e6:
+ return f"{str(round(number / 1000.0))},000"
- return str(round(number / 1e3)) + ",000"
+ return f"{str(round(number / 1000000.0))},000,000"
- return str(round(number / 1e6)) + ",000,000"
===========changed ref 6===========
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
access_token = get_access_token()
try:
data = github_get_user_starred_repos(user_id, access_token)
data = [x["repo"]["full_name"] for x in data]
return data
except RESTErrorNotFound:
# User does not exist (and rate limited previously)
return []
except RESTError:
# Rate limited, so assume user starred repo
+ return [f"{OWNER}/{REPO}"]
- return [OWNER + "/" + REPO]
===========changed ref 7===========
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
# Checks the repo's starred users (with cache)
repo_stargazers = await get_repo_stargazers(owner, repo)
if user_id in repo_stargazers:
return True
# Checks the user's 30 most recent starred repos (no cache)
user_stars = await get_user_stars(user_id)
+ return f"{owner}/{repo}" in user_stars
- if f"{owner}/{repo}" in user_stars:
- return True
- return False
-
===========changed ref 8===========
# module: backend.src.models.user.contribs
class ContributionStats(BaseModel):
def compress(self) -> List[Any]:
out: List[Any] = [
[
self.contribs_count,
self.commits_count,
self.issues_count,
self.prs_count,
self.reviews_count,
self.repos_count,
self.other_count,
],
+ *[[name] + stats.compress() for name, stats in self.languages.items()],
]
-
- out.extend(
- [[name] + stats.compress() for name, stats in self.languages.items()]
- )
return out
===========changed ref 9===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
|
backend.src.utils.decorators/async_fail_gracefully
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<13>:<add> "message": f"Error {str(e)}",
<del> "message": "Error " + str(e),
|
# module: backend.src.utils.decorators
def async_fail_gracefully(func: Callable[..., Any]):
<0> @wraps(func) # needed to play nice with FastAPI decorator
<1> async def wrapper(
<2> response: Response, *args: List[Any], **kwargs: Dict[str, Any]
<3> ) -> Any:
<4> start = datetime.now()
<5> try:
<6> data = await func(response, *args, **kwargs)
<7> return {"data": data, "message": "200 OK", "time": datetime.now() - start}
<8> except Exception as e:
<9> logging.exception(e)
<10> response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
<11> return {
<12> "data": [],
<13> "message": "Error " + str(e),
<14> "time": datetime.now() - start,
<15> }
<16>
<17> return wrapper
<18>
|
===========unchanged ref 0===========
at: datetime
datetime()
at: datetime.datetime
now(tz: Optional[_tzinfo]=...) -> _S
at: functools
wraps(wrapped: _AnyCallable, assigned: Sequence[str]=..., updated: Sequence[str]=...) -> Callable[[_T], _T]
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: typing
Callable = _CallableType(collections.abc.Callable, 2)
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.utils.decorators
def fail_gracefully(func: Callable[..., Any]):
@wraps(func) # needed to play nice with FastAPI decorator
def wrapper(response: Response, *args: List[Any], **kwargs: Dict[str, Any]) -> Any:
start = datetime.now()
try:
data = func(response, *args, **kwargs)
return {"data": data, "message": "200 OK", "time": datetime.now() - start}
except Exception as e:
logging.exception(e)
response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
return {
"data": [],
+ "message": f"Error {str(e)}",
- "message": "Error " + str(e),
"time": datetime.now() - start,
}
return wrapper
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 2===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 3===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 4===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 5===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 6===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def format_loc_number(number: int) -> str:
if number < 1e3:
return str(100 * round(number / 100))
if number < 1e6:
+ return f"{str(round(number / 1000.0))},000"
- return str(round(number / 1e3)) + ",000"
+ return f"{str(round(number / 1000000.0))},000,000"
- return str(round(number / 1e6)) + ",000,000"
===========changed ref 7===========
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
access_token = get_access_token()
try:
data = github_get_user_starred_repos(user_id, access_token)
data = [x["repo"]["full_name"] for x in data]
return data
except RESTErrorNotFound:
# User does not exist (and rate limited previously)
return []
except RESTError:
# Rate limited, so assume user starred repo
+ return [f"{OWNER}/{REPO}"]
- return [OWNER + "/" + REPO]
===========changed ref 8===========
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
# Checks the repo's starred users (with cache)
repo_stargazers = await get_repo_stargazers(owner, repo)
if user_id in repo_stargazers:
return True
# Checks the user's 30 most recent starred repos (no cache)
user_stars = await get_user_stars(user_id)
+ return f"{owner}/{repo}" in user_stars
- if f"{owner}/{repo}" in user_stars:
- return True
- return False
-
===========changed ref 9===========
# module: backend.src.models.user.contribs
class ContributionStats(BaseModel):
def compress(self) -> List[Any]:
out: List[Any] = [
[
self.contribs_count,
self.commits_count,
self.issues_count,
self.prs_count,
self.reviews_count,
self.repos_count,
self.other_count,
],
+ *[[name] + stats.compress() for name, stats in self.languages.items()],
]
-
- out.extend(
- [[name] + stats.compress() for name, stats in self.languages.items()]
- )
return out
|
backend.tests.data.github.graphql.test_user_contribs/TestTemplate.test_get_user_contribution_calendar
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<3>:<add> start_date=datetime.now() - timedelta(days=30),
<del> start_date=datetime.today() - timedelta(days=30),
<4>:<add> end_date=datetime.now(),
<del> end_date=datetime.today(),
<6>:<add>
|
# module: backend.tests.data.github.graphql.test_user_contribs
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_calendar(self):
<0> response = get_user_contribution_calendar(
<1> user_id=USER_ID,
<2> access_token=TOKEN,
<3> start_date=datetime.today() - timedelta(days=30),
<4> end_date=datetime.today(),
<5> )
<6> self.assertIsInstance(response, RawCalendar)
<7>
|
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def format_loc_number(number: int) -> str:
if number < 1e3:
return str(100 * round(number / 100))
if number < 1e6:
+ return f"{str(round(number / 1000.0))},000"
- return str(round(number / 1e3)) + ",000"
+ return f"{str(round(number / 1000000.0))},000,000"
- return str(round(number / 1e6)) + ",000,000"
===========changed ref 6===========
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
access_token = get_access_token()
try:
data = github_get_user_starred_repos(user_id, access_token)
data = [x["repo"]["full_name"] for x in data]
return data
except RESTErrorNotFound:
# User does not exist (and rate limited previously)
return []
except RESTError:
# Rate limited, so assume user starred repo
+ return [f"{OWNER}/{REPO}"]
- return [OWNER + "/" + REPO]
===========changed ref 7===========
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
# Checks the repo's starred users (with cache)
repo_stargazers = await get_repo_stargazers(owner, repo)
if user_id in repo_stargazers:
return True
# Checks the user's 30 most recent starred repos (no cache)
user_stars = await get_user_stars(user_id)
+ return f"{owner}/{repo}" in user_stars
- if f"{owner}/{repo}" in user_stars:
- return True
- return False
-
===========changed ref 8===========
# module: backend.src.models.user.contribs
class ContributionStats(BaseModel):
def compress(self) -> List[Any]:
out: List[Any] = [
[
self.contribs_count,
self.commits_count,
self.issues_count,
self.prs_count,
self.reviews_count,
self.repos_count,
self.other_count,
],
+ *[[name] + stats.compress() for name, stats in self.languages.items()],
]
-
- out.extend(
- [[name] + stats.compress() for name, stats in self.languages.items()]
- )
return out
===========changed ref 9===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
===========changed ref 10===========
# module: backend.src.data.github.auth.main
def get_unknown_user(access_token: str) -> Optional[str]:
"""
Accepts access_token and returns user_id of associated user
:param access_token: GitHub access token
:return: user_id or None if invalid access_token
"""
headers: Dict[str, str] = {
+ "Accept": "application/vnd.github.v3+json",
- "Accept": str("application/vnd.github.v3+json"),
+ "Authorization": f"bearer {access_token}",
- "Authorization": "bearer " + access_token,
}
r = s.get("https://api.github.com/user", params={}, headers=headers)
return r.json().get("login", None) # type: ignore
|
backend.tests.data.github.graphql.test_user_contribs/TestTemplate.test_get_user_contribution_events
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<3>:<add> start_date=datetime.now() - timedelta(days=30),
<del> start_date=datetime.today() - timedelta(days=30),
<4>:<add> end_date=datetime.now(),
<del> end_date=datetime.today(),
<6>:<add>
|
# module: backend.tests.data.github.graphql.test_user_contribs
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_events(self):
<0> response = get_user_contribution_events(
<1> user_id=USER_ID,
<2> access_token=TOKEN,
<3> start_date=datetime.today() - timedelta(days=30),
<4> end_date=datetime.today(),
<5> )
<6> self.assertIsInstance(response, RawEvents)
<7>
|
===========changed ref 0===========
# module: backend.tests.data.github.graphql.test_user_contribs
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_calendar(self):
response = get_user_contribution_calendar(
user_id=USER_ID,
access_token=TOKEN,
+ start_date=datetime.now() - timedelta(days=30),
- start_date=datetime.today() - timedelta(days=30),
+ end_date=datetime.now(),
- end_date=datetime.today(),
)
+
self.assertIsInstance(response, RawCalendar)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 2===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 3===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 4===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 5===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 6===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def format_loc_number(number: int) -> str:
if number < 1e3:
return str(100 * round(number / 100))
if number < 1e6:
+ return f"{str(round(number / 1000.0))},000"
- return str(round(number / 1e3)) + ",000"
+ return f"{str(round(number / 1000000.0))},000,000"
- return str(round(number / 1e6)) + ",000,000"
===========changed ref 7===========
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
access_token = get_access_token()
try:
data = github_get_user_starred_repos(user_id, access_token)
data = [x["repo"]["full_name"] for x in data]
return data
except RESTErrorNotFound:
# User does not exist (and rate limited previously)
return []
except RESTError:
# Rate limited, so assume user starred repo
+ return [f"{OWNER}/{REPO}"]
- return [OWNER + "/" + REPO]
===========changed ref 8===========
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
# Checks the repo's starred users (with cache)
repo_stargazers = await get_repo_stargazers(owner, repo)
if user_id in repo_stargazers:
return True
# Checks the user's 30 most recent starred repos (no cache)
user_stars = await get_user_stars(user_id)
+ return f"{owner}/{repo}" in user_stars
- if f"{owner}/{repo}" in user_stars:
- return True
- return False
-
===========changed ref 9===========
# module: backend.src.models.user.contribs
class ContributionStats(BaseModel):
def compress(self) -> List[Any]:
out: List[Any] = [
[
self.contribs_count,
self.commits_count,
self.issues_count,
self.prs_count,
self.reviews_count,
self.repos_count,
self.other_count,
],
+ *[[name] + stats.compress() for name, stats in self.languages.items()],
]
-
- out.extend(
- [[name] + stats.compress() for name, stats in self.languages.items()]
- )
return out
===========changed ref 10===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
|
backend.src.subscriber.aggregation.wrapped.calendar/get_calendar_data
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<13>:<add> item = items_dict.get(date)
<del> item = items_dict.get(date, None)
|
# module: backend.src.subscriber.aggregation.wrapped.calendar
def get_calendar_data(data: UserPackage, year: int) -> CalendarData:
<0> top_langs = [
<1> x[0]
<2> for x in sorted(
<3> data.contribs.total_stats.languages.items(),
<4> key=lambda x: x[1].additions + x[1].deletions,
<5> reverse=True,
<6> )[:5]
<7> ]
<8>
<9> total_out: List[CalendarDayDatum] = []
<10> items_dict = {item.date: item for item in data.contribs.total}
<11> for i in range(365):
<12> date = (datetime(year, 1, 1) + timedelta(days=i - 1)).strftime("%Y-%m-%d")
<13> item = items_dict.get(date, None)
<14> out: Dict[str, Any] = {
<15> "day": date,
<16> "contribs": 0,
<17> "commits": 0,
<18> "issues": 0,
<19> "prs": 0,
<20> "reviews": 0,
<21> "loc_added": 0,
<22> "loc_changed": 0,
<23> "top_langs": {k: {"loc_added": 0, "loc_changed": 0} for k in top_langs},
<24> }
<25>
<26> if item is not None:
<27> out["contribs"] = item.stats.contribs_count
<28> out["commits"] = item.stats.commits_count
<29> out["issues"] = item.stats.issues_count
<30> out["prs"] = item.stats.prs_count
<31> out["reviews"] = item.stats.reviews_count
<32>
<33> for k, v in item.stats.languages.items():
<34> if k in top_langs:
<35> out["top_langs"][k]["loc_added"] = v.additions - v.deletions # type: ignore
<36> out["top_langs"][k]["loc_changed"] = v.</s>
|
===========below chunk 0===========
# module: backend.src.subscriber.aggregation.wrapped.calendar
def get_calendar_data(data: UserPackage, year: int) -> CalendarData:
# offset: 1
out["loc_added"] += v.additions - v.deletions # type: ignore
out["loc_changed"] += v.additions + v.deletions # type: ignore
out_obj = CalendarDayDatum.parse_obj(out)
total_out.append(out_obj)
return CalendarData.parse_obj({"days": total_out})
===========unchanged ref 0===========
at: datetime
timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...)
datetime()
at: datetime.date
__slots__ = '_year', '_month', '_day', '_hashcode'
strftime(fmt: _Text) -> str
__str__ = isoformat
__radd__ = __add__
at: datetime.timedelta
__slots__ = '_days', '_seconds', '_microseconds', '_hashcode'
__radd__ = __add__
__rmul__ = __mul__
at: src.models.user.contribs.ContributionDay
date: str
weekday: int
stats: ContributionStats
lists: ContributionLists
at: src.models.user.contribs.ContributionStats
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
public_stats: ContributionStats
total: List[ContributionDay]
public: List[ContributionDay]
repo_stats: Dict[str, RepoContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========unchanged ref 1===========
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.tests.data.github.graphql.test_user_contribs
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_events(self):
response = get_user_contribution_events(
user_id=USER_ID,
access_token=TOKEN,
+ start_date=datetime.now() - timedelta(days=30),
- start_date=datetime.today() - timedelta(days=30),
+ end_date=datetime.now(),
- end_date=datetime.today(),
)
+
self.assertIsInstance(response, RawEvents)
===========changed ref 6===========
# module: backend.tests.data.github.graphql.test_user_contribs
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_calendar(self):
response = get_user_contribution_calendar(
user_id=USER_ID,
access_token=TOKEN,
+ start_date=datetime.now() - timedelta(days=30),
- start_date=datetime.today() - timedelta(days=30),
+ end_date=datetime.now(),
- end_date=datetime.today(),
)
+
self.assertIsInstance(response, RawCalendar)
===========changed ref 7===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def format_loc_number(number: int) -> str:
if number < 1e3:
return str(100 * round(number / 100))
if number < 1e6:
+ return f"{str(round(number / 1000.0))},000"
- return str(round(number / 1e3)) + ",000"
+ return f"{str(round(number / 1000000.0))},000,000"
- return str(round(number / 1e6)) + ",000,000"
|
backend.src.publisher.render.top_repos/get_top_repos_svg
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<0>:<add> # sourcery skip: simplify-len-comparison
<4>:<add> subheader += f" | {commits_excluded} commits excluded"
<del> subheader += " | " + str(commits_excluded) + " commits excluded"
<23>:<add> data_row = [
<del> data_row = []
<24>:<add> (100 * lang.loc / total, lang.color)
<add> for lang in sorted(x.langs, key=lambda x: x.loc, reverse=True)
<del> for lang in sorted(x.langs, key=lambda x: x.loc, reverse=True):
<25>:<add> ]
<add>
<del> data_row.append((100 * lang.loc / total, lang.color))
|
# module: backend.src.publisher.render.top_repos
def get_top_repos_svg(
data: List[RepoStats],
time_str: str,
loc_metric: str,
commits_excluded: int,
use_animation: bool,
theme: str,
) -> Drawing:
<0> header = "Most Contributed Repositories"
<1> subheader = time_str
<2> subheader += " | " + ("LOC Changed" if loc_metric == "changed" else "LOC Added")
<3> if commits_excluded > 50:
<4> subheader += " | " + str(commits_excluded) + " commits excluded"
<5>
<6> if len(data) == 0:
<7> return get_no_data_svg(header, subheader)
<8>
<9> d, dp = get_template(
<10> width=300,
<11> height=285,
<12> padding=20,
<13> header_text=header,
<14> subheader_text=subheader,
<15> use_animation=use_animation,
<16> debug=False,
<17> theme=theme,
<18> )
<19>
<20> dataset: List[Tuple[str, str, List[Tuple[float, str]]]] = []
<21> total = max(x.loc for x in data)
<22> for x in data[:4]:
<23> data_row = []
<24> for lang in sorted(x.langs, key=lambda x: x.loc, reverse=True):
<25> data_row.append((100 * lang.loc / total, lang.color))
<26> name = "private/repository" if x.private else x.repo
<27> dataset.append((name, format_number(x.loc), data_row))
<28>
<29> dp.add(
<30> get_bar_section(d=d, dataset=dataset, theme=theme, padding=45, bar_width=195)
<31> )
<32>
<33> langs = {}
<34> for x in data[:4]:
<35> for lang in x.langs:
<36> langs[lang.lang] = lang.color
<37> langs = list(langs.items</s>
|
===========below chunk 0===========
# module: backend.src.publisher.render.top_repos
def get_top_repos_svg(
data: List[RepoStats],
time_str: str,
loc_metric: str,
commits_excluded: int,
use_animation: bool,
theme: str,
) -> Drawing:
# offset: 1
columns = {1: 1, 2: 2, 3: 3, 4: 2, 5: 3, 6: 3}[len(langs)]
padding = 215 + (10 if columns == len(langs) else 0)
dp.add(
get_lang_name_section(
d=d, data=langs, theme=theme, columns=columns, padding=padding
)
)
d.add(dp)
return d
===========unchanged ref 0===========
at: src.publisher.aggregation.user.models.RepoLanguage
lang: str
color: Optional[str]
loc: int
at: src.publisher.aggregation.user.models.RepoStats
repo: str
private: bool
langs: List[RepoLanguage]
loc: int
at: src.publisher.render.error
get_no_data_svg(header: str, subheader: str) -> Drawing
at: src.publisher.render.template
get_template(width: int, height: int, padding: int, header_text: str, subheader_text: str, theme: str, use_animation: bool=True, debug: bool=False) -> Tuple[Drawing, Group]
get_bar_section(d: Drawing, dataset: List[Tuple[str, str, List[Tuple[float, str]]]], theme: str, padding: int=45, bar_width: int=210) -> Group
get_lang_name_section(d: Drawing, data: List[Tuple[str, str]], theme: str, columns: int=2, padding: int=80) -> Group
at: src.utils.utils
format_number(num: int) -> str
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.tests.data.github.graphql.test_user_contribs
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_events(self):
response = get_user_contribution_events(
user_id=USER_ID,
access_token=TOKEN,
+ start_date=datetime.now() - timedelta(days=30),
- start_date=datetime.today() - timedelta(days=30),
+ end_date=datetime.now(),
- end_date=datetime.today(),
)
+
self.assertIsInstance(response, RawEvents)
===========changed ref 6===========
# module: backend.tests.data.github.graphql.test_user_contribs
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_calendar(self):
response = get_user_contribution_calendar(
user_id=USER_ID,
access_token=TOKEN,
+ start_date=datetime.now() - timedelta(days=30),
- start_date=datetime.today() - timedelta(days=30),
+ end_date=datetime.now(),
- end_date=datetime.today(),
)
+
self.assertIsInstance(response, RawCalendar)
===========changed ref 7===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def format_loc_number(number: int) -> str:
if number < 1e3:
return str(100 * round(number / 100))
if number < 1e6:
+ return f"{str(round(number / 1000.0))},000"
- return str(round(number / 1e3)) + ",000"
+ return f"{str(round(number / 1000000.0))},000,000"
- return str(round(number / 1e6)) + ",000,000"
===========changed ref 8===========
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
access_token = get_access_token()
try:
data = github_get_user_starred_repos(user_id, access_token)
data = [x["repo"]["full_name"] for x in data]
return data
except RESTErrorNotFound:
# User does not exist (and rate limited previously)
return []
except RESTError:
# Rate limited, so assume user starred repo
+ return [f"{OWNER}/{REPO}"]
- return [OWNER + "/" + REPO]
|
backend.src.subscriber.routers.decorators/pubsub_fail_gracefully
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<13>:<add> "message": f"Error {str(e)}",
<del> "message": "Error " + str(e),
|
# module: backend.src.subscriber.routers.decorators
# NOTE: returns HTTP_200_OK regardless to avoid retrying PubSub API
def pubsub_fail_gracefully(func: Callable[..., Any]):
<0> @wraps(func) # needed to play nice with FastAPI decorator
<1> async def wrapper(
<2> response: Response, *args: List[Any], **kwargs: Dict[str, Any]
<3> ) -> Any:
<4> start = datetime.now()
<5> try:
<6> data = await func(response, *args, **kwargs)
<7> return {"data": data, "message": "200 OK", "time": datetime.now() - start}
<8> except Exception as e:
<9> logging.exception(e)
<10> response.status_code = status.HTTP_200_OK
<11> return {
<12> "data": [],
<13> "message": "Error " + str(e),
<14> "time": datetime.now() - start,
<15> }
<16>
<17> return wrapper
<18>
|
===========unchanged ref 0===========
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: functools
wraps(wrapped: _AnyCallable, assigned: Sequence[str]=..., updated: Sequence[str]=...) -> Callable[[_T], _T]
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: typing
Callable = _CallableType(collections.abc.Callable, 2)
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.tests.data.github.graphql.test_user_contribs
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_events(self):
response = get_user_contribution_events(
user_id=USER_ID,
access_token=TOKEN,
+ start_date=datetime.now() - timedelta(days=30),
- start_date=datetime.today() - timedelta(days=30),
+ end_date=datetime.now(),
- end_date=datetime.today(),
)
+
self.assertIsInstance(response, RawEvents)
===========changed ref 6===========
# module: backend.tests.data.github.graphql.test_user_contribs
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_calendar(self):
response = get_user_contribution_calendar(
user_id=USER_ID,
access_token=TOKEN,
+ start_date=datetime.now() - timedelta(days=30),
- start_date=datetime.today() - timedelta(days=30),
+ end_date=datetime.now(),
- end_date=datetime.today(),
)
+
self.assertIsInstance(response, RawCalendar)
===========changed ref 7===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def format_loc_number(number: int) -> str:
if number < 1e3:
return str(100 * round(number / 100))
if number < 1e6:
+ return f"{str(round(number / 1000.0))},000"
- return str(round(number / 1e3)) + ",000"
+ return f"{str(round(number / 1000000.0))},000,000"
- return str(round(number / 1e6)) + ",000,000"
===========changed ref 8===========
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
access_token = get_access_token()
try:
data = github_get_user_starred_repos(user_id, access_token)
data = [x["repo"]["full_name"] for x in data]
return data
except RESTErrorNotFound:
# User does not exist (and rate limited previously)
return []
except RESTError:
# Rate limited, so assume user starred repo
+ return [f"{OWNER}/{REPO}"]
- return [OWNER + "/" + REPO]
===========changed ref 9===========
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
# Checks the repo's starred users (with cache)
repo_stargazers = await get_repo_stargazers(owner, repo)
if user_id in repo_stargazers:
return True
# Checks the user's 30 most recent starred repos (no cache)
user_stars = await get_user_stars(user_id)
+ return f"{owner}/{repo}" in user_stars
- if f"{owner}/{repo}" in user_stars:
- return True
- return False
-
|
backend.src.publisher.render.top_langs/get_top_langs_svg
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<5>:<add> subheader += f" | {commits_excluded} commits excluded"
<del> subheader += " | " + str(commits_excluded) + " commits excluded"
<24>:<del> data_row = []
<25>:<del> for x in data[1:6]:
<26>:<del> data_row.append((x.percent, x.color))
<27>:<add> data_row = [(x.percent, x.color) for x in data[1:6]]
<33>:<add> dataset.append((x.lang, f"{str(x.percent)}%", [(x.percent, x.color)]))
<del> dataset.append((x.lang, str(x.percent) + "%", [(x.percent, x.color)]))
|
# module: backend.src.publisher.render.top_langs
def get_top_langs_svg(
data: List[LanguageStats],
time_str: str,
use_percent: bool,
loc_metric: str,
commits_excluded: int,
compact: bool,
use_animation: bool,
theme: str,
) -> Drawing:
<0> header = "Most Used Languages"
<1> subheader = time_str
<2> if not use_percent:
<3> subheader += " | " + ("LOC Changed" if loc_metric == "changed" else "LOC Added")
<4> if commits_excluded > 50:
<5> subheader += " | " + str(commits_excluded) + " commits excluded"
<6>
<7> if len(data) <= 1:
<8> return get_no_data_svg(header, subheader)
<9>
<10> d, dp = get_template(
<11> width=300,
<12> height=175 if compact else 285,
<13> padding=20,
<14> header_text=header,
<15> subheader_text=subheader,
<16> use_animation=use_animation,
<17> debug=False,
<18> theme=theme,
<19> )
<20>
<21> dataset: List[Tuple[str, str, List[Tuple[float, str]]]] = []
<22> padding, width = 0, 0
<23> if compact:
<24> data_row = []
<25> for x in data[1:6]:
<26> data_row.append((x.percent, x.color))
<27> dataset.append(("", "", data_row))
<28> padding, width = 30, 260
<29> else:
<30> max_length = max(data[i].loc for i in range(1, len(data)))
<31> for x in data[1:6]:
<32> if use_percent:
<33> dataset.append((x.lang, str(x.percent) + "%", [(x.percent, x.color)]))
<34> else:
<35> percent = 100 * x.loc / max_length
<36> dataset.append((x</s>
|
===========below chunk 0===========
# module: backend.src.publisher.render.top_langs
def get_top_langs_svg(
data: List[LanguageStats],
time_str: str,
use_percent: bool,
loc_metric: str,
commits_excluded: int,
compact: bool,
use_animation: bool,
theme: str,
) -> Drawing:
# offset: 1
padding, width = 45, 210 if use_percent else 195
dp.add(
get_bar_section(
d=d, dataset=dataset, theme=theme, padding=padding, bar_width=width
)
)
langs = [(x.lang + " " + str(x.percent) + "%", x.color) for x in data[1:6]]
if compact:
dp.add(get_lang_name_section(d=d, data=langs, theme=theme))
d.add(dp)
return d
===========unchanged ref 0===========
at: src.publisher.aggregation.user.models.LanguageStats
lang: str
loc: int
percent: float
color: Optional[str]
at: src.publisher.render.error
get_no_data_svg(header: str, subheader: str) -> Drawing
at: src.publisher.render.template
get_template(width: int, height: int, padding: int, header_text: str, subheader_text: str, theme: str, use_animation: bool=True, debug: bool=False) -> Tuple[Drawing, Group]
get_bar_section(d: Drawing, dataset: List[Tuple[str, str, List[Tuple[float, str]]]], theme: str, padding: int=45, bar_width: int=210) -> Group
get_lang_name_section(d: Drawing, data: List[Tuple[str, str]], theme: str, columns: int=2, padding: int=80) -> Group
at: src.utils.utils
format_number(num: int) -> str
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.tests.data.github.graphql.test_user_contribs
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_events(self):
response = get_user_contribution_events(
user_id=USER_ID,
access_token=TOKEN,
+ start_date=datetime.now() - timedelta(days=30),
- start_date=datetime.today() - timedelta(days=30),
+ end_date=datetime.now(),
- end_date=datetime.today(),
)
+
self.assertIsInstance(response, RawEvents)
===========changed ref 6===========
# module: backend.tests.data.github.graphql.test_user_contribs
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_calendar(self):
response = get_user_contribution_calendar(
user_id=USER_ID,
access_token=TOKEN,
+ start_date=datetime.now() - timedelta(days=30),
- start_date=datetime.today() - timedelta(days=30),
+ end_date=datetime.now(),
- end_date=datetime.today(),
)
+
self.assertIsInstance(response, RawCalendar)
===========changed ref 7===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def format_loc_number(number: int) -> str:
if number < 1e3:
return str(100 * round(number / 100))
if number < 1e6:
+ return f"{str(round(number / 1000.0))},000"
- return str(round(number / 1e3)) + ",000"
+ return f"{str(round(number / 1000000.0))},000,000"
- return str(round(number / 1e6)) + ",000,000"
===========changed ref 8===========
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
access_token = get_access_token()
try:
data = github_get_user_starred_repos(user_id, access_token)
data = [x["repo"]["full_name"] for x in data]
return data
except RESTErrorNotFound:
# User does not exist (and rate limited previously)
return []
except RESTError:
# Rate limited, so assume user starred repo
+ return [f"{OWNER}/{REPO}"]
- return [OWNER + "/" + REPO]
|
backend.src.data.github.utils/get_access_token
|
Modified
|
avgupta456~github-trends
|
e0e284def2c731d11dcc2143a3c8419d40cd8c4f
|
Lint Backend (#201)
|
<0>:<del> if access_token is not None:
<1>:<del> return access_token
<2>:<del> return get_random_key()
<3>:<add> return access_token if access_token is not None else get_random_key()
|
# module: backend.src.data.github.utils
def get_access_token(access_token: Optional[str] = None) -> str:
<0> if access_token is not None:
<1> return access_token
<2> return get_random_key()
<3>
|
===========unchanged ref 0===========
at: src.data.mongo.secret.functions
get_random_key() -> str
===========changed ref 0===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/delete/{user_id}")
async def delete_account_auth(user_id: str) -> RedirectResponse:
return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
- get_redirect_url(prefix="delete/" + user_id, private=False, user_id=user_id)
)
===========changed ref 1===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect/delete/{user_id}", include_in_schema=False)
async def delete_account(user_id: str) -> RedirectResponse:
await delete_user(user_id, user_key="", use_user_key=False)
return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
- "https://github.com/settings/connections/applications/" + OAUTH_CLIENT_ID
)
===========changed ref 2===========
<s>=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_raw(
response: Response,
user_id: str,
access_token: Optional[str] = None,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
time_range: str = "one_month",
timezone_str: str = "US/Eastern",
full: bool = False,
) -> UserPackage:
await update_keys()
start_date, end_date, _ = use_time_range(time_range, start_date, end_date)
+ return await get_user_data(
- data = await get_user_data(
user_id, start_date, end_date, timezone_str, access_token
)
- return data
===========changed ref 3===========
# module: backend.src.publisher.routers.auth.standalone
@router.get("/redirect", include_in_schema=False)
async def redirect_return(code: str = "", private_access: bool = False) -> str:
try:
user_id = await authenticate(code=code, private_access=private_access) # type: ignore
+ return f"You ({user_id}) are now authenticated!"
- return "You (" + user_id + ") are now authenticated!"
except Exception as e:
logging.exception(e)
return "Unknown Error. Please try again later."
===========changed ref 4===========
# module: backend.src.subscriber.routers.dev
@router.get("/wrapped/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_wrapped_user_raw(
response: Response,
user_id: str,
year: int = 2022,
access_token: Optional[str] = None,
) -> WrappedPackage:
await update_keys()
user_data = await get_user_data(
user_id, date(year, 1, 1), date(year, 12, 31), "US/Eastern", access_token
)
+ return get_wrapped_data(user_data, year)
- wrapped_data = get_wrapped_data(user_data, year)
- return wrapped_data
===========changed ref 5===========
# module: backend.tests.data.github.graphql.test_user_contribs
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_events(self):
response = get_user_contribution_events(
user_id=USER_ID,
access_token=TOKEN,
+ start_date=datetime.now() - timedelta(days=30),
- start_date=datetime.today() - timedelta(days=30),
+ end_date=datetime.now(),
- end_date=datetime.today(),
)
+
self.assertIsInstance(response, RawEvents)
===========changed ref 6===========
# module: backend.tests.data.github.graphql.test_user_contribs
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_calendar(self):
response = get_user_contribution_calendar(
user_id=USER_ID,
access_token=TOKEN,
+ start_date=datetime.now() - timedelta(days=30),
- start_date=datetime.today() - timedelta(days=30),
+ end_date=datetime.now(),
- end_date=datetime.today(),
)
+
self.assertIsInstance(response, RawCalendar)
===========changed ref 7===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def format_loc_number(number: int) -> str:
if number < 1e3:
return str(100 * round(number / 100))
if number < 1e6:
+ return f"{str(round(number / 1000.0))},000"
- return str(round(number / 1e3)) + ",000"
+ return f"{str(round(number / 1000000.0))},000,000"
- return str(round(number / 1e6)) + ",000,000"
===========changed ref 8===========
# module: backend.src.subscriber.aggregation.auth.auth
def get_user_stars(user_id: str) -> List[str]:
access_token = get_access_token()
try:
data = github_get_user_starred_repos(user_id, access_token)
data = [x["repo"]["full_name"] for x in data]
return data
except RESTErrorNotFound:
# User does not exist (and rate limited previously)
return []
except RESTError:
# Rate limited, so assume user starred repo
+ return [f"{OWNER}/{REPO}"]
- return [OWNER + "/" + REPO]
===========changed ref 9===========
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
# Checks the repo's starred users (with cache)
repo_stargazers = await get_repo_stargazers(owner, repo)
if user_id in repo_stargazers:
return True
# Checks the user's 30 most recent starred repos (no cache)
user_stars = await get_user_stars(user_id)
+ return f"{owner}/{repo}" in user_stars
- if f"{owner}/{repo}" in user_stars:
- return True
- return False
-
===========changed ref 10===========
# module: backend.src.models.user.contribs
class ContributionStats(BaseModel):
def compress(self) -> List[Any]:
out: List[Any] = [
[
self.contribs_count,
self.commits_count,
self.issues_count,
self.prs_count,
self.reviews_count,
self.repos_count,
self.other_count,
],
+ *[[name] + stats.compress() for name, stats in self.languages.items()],
]
-
- out.extend(
- [[name] + stats.compress() for name, stats in self.languages.items()]
- )
return out
===========changed ref 11===========
# module: backend.src.utils.utils
def format_number(num: int) -> str:
if num > 10000:
+ return f"~{str(num // 1000)}k lines"
- return "~" + str(int(num / 1000)) + "k lines"
elif num > 1000:
+ return f"~{str(num // 100 / 10)}k lines"
- return "~" + str(int(num / 100) / 10) + "k lines"
elif num > 100:
+ return f"~{str(num // 100 * 100)} lines"
- return "~" + str(int(num / 100) * 100) + " lines"
else:
return "<100 lines"
|
backend.src.subscriber.aggregation.user.languages/get_commit_languages
|
Modified
|
avgupta456~github-trends
|
8ee3078ab0d22c712b3566bc61d49df3542cbdea
|
Code Freeze (#203)
|
<0>:<add> # sourcery skip: extract-method
<32>:<add> pr = commit.prs.nodes[0]
<add> total_additions, total_deletions = 0, 0
<add> for file in pr.files.nodes:
<add> filename = file.path.split(".")
<add> extension = "" if len(filename) <= 1 else filename[-1]
<add> lang = EXTENSIONS.get(f".{extension}", None)
<add> if lang is not None:
<add> out.add_lines(
<add> lang["name"], lang["color"], file.additions, file.deletions
<add> )
<add> total_additions += file.additions
<add> total_deletions += file.deletions
<add> add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
<add> del_ratio = min(pr.deletions, commit.deletions) / max(1,
|
# module: backend.src.subscriber.aggregation.user.languages
def get_commit_languages(
commit: Optional[RawCommit],
files: Optional[List[RawCommitFile]],
repo: RawRepo,
) -> CommitLanguages:
<0> out = CommitLanguages()
<1>
<2> if commit is None:
<3> return out
<4>
<5> if max(commit.additions, commit.deletions) == 0:
<6> return out
<7>
<8> # assummed to be auto-generated or copied
<9> if max(commit.additions, commit.deletions) > 10 * CUTOFF or (
<10> max(commit.additions, commit.deletions) > CUTOFF
<11> and min(commit.additions, commit.deletions) == 0
<12> ):
<13> return out
<14>
<15> pr_coverage = 0
<16> if len(commit.prs.nodes) > 0:
<17> pr_obj = commit.prs.nodes[0]
<18> pr_files = pr_obj.files.nodes
<19> total_changed = sum(x.additions + x.deletions for x in pr_files)
<20> pr_coverage = total_changed / max(1, (pr_obj.additions + pr_obj.deletions))
<21>
<22> if files is not None:
<23> for file in files:
<24> filename = file.filename.split(".")
<25> extension = "" if len(filename) <= 1 else filename[-1]
<26> lang = EXTENSIONS.get(f".{extension}", None)
<27> if lang is not None:
<28> out.add_lines(
<29> lang["name"], lang["color"], file.additions, file.deletions
<30> )
<31> elif len(commit.prs.nodes) > 0 and pr_coverage > 0.25:
<32> _extracted_from_get_commit_languages_38(commit, out)
<33> elif commit.additions + commit.deletions > 2 * CUTOFF:
<34> # assummed to be auto generated
<35> return out
<36> else:
<37> repo_info = repo.languages.</s>
|
===========below chunk 0===========
# module: backend.src.subscriber.aggregation.user.languages
def get_commit_languages(
commit: Optional[RawCommit],
files: Optional[List[RawCommitFile]],
repo: RawRepo,
) -> CommitLanguages:
# offset: 1
languages = [x for x in repo_info if x.node.name not in BLACKLIST]
total_repo_size = sum(language.size for language in languages)
for language in languages:
lang_name = language.node.name
lang_color = language.node.color
lang_size = language.size
additions = round(commit.additions * lang_size / total_repo_size)
deletions = round(commit.deletions * lang_size / total_repo_size)
out.add_lines(lang_name, lang_color, additions, deletions)
return out
===========unchanged ref 0===========
at: backend.src.subscriber.aggregation.user.languages
EXTENSIONS: Dict[str, Dict[str, str]] = load(open("./src/data/github/extensions.json"))
CommitLanguages()
at: backend.src.subscriber.aggregation.user.languages.CommitLanguages
add_lines(name: str, color: Optional[str], additions: int, deletions: int)
normalize(add_ratio: float, del_ratio: float)
at: src.constants
CUTOFF = 1000 # if additions or deletions > CUTOFF, or sum > 2 * CUTOFF, ignore LOC
at: src.data.github.graphql.models.RawCommit
additions: int
deletions: int
changed_files: int = Field(alias="changedFiles")
url: str
prs: RawCommitPR = Field(alias="associatedPullRequests")
at: src.data.github.graphql.models.RawCommitPR
nodes: List[RawCommitPRNode]
at: src.data.github.graphql.models.RawCommitPRFile
nodes: List[RawCommitPRFileNode]
at: src.data.github.graphql.models.RawCommitPRFileNode
path: str
additions: int
deletions: int
at: src.data.github.graphql.models.RawCommitPRNode
changed_files: int = Field(alias="changedFiles")
additions: int
deletions: int
files: RawCommitPRFile
at: src.data.github.rest.models.RawCommitFile
filename: str
additions: int
deletions: int
at: typing
List = _alias(list, 1, inst=False, name='List')
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
|
backend.src.subscriber.aggregation.user.contributions/get_user_all_contribution_events
|
Modified
|
avgupta456~github-trends
|
8ee3078ab0d22c712b3566bc61d49df3542cbdea
|
Code Freeze (#203)
|
<31>:<add> node = RawEventsEvent(occurredAt=repo.occurred_at)
<del> node = RawEventsEvent(occurredAt=str(repo.occurred_at))
|
# module: backend.src.subscriber.aggregation.user.contributions
def get_user_all_contribution_events(
user_id: str,
start_date: datetime,
end_date: datetime,
access_token: Optional[str] = None,
) -> Dict[str, ContribsList]:
<0> repo_contribs: Dict[str, ContribsList] = defaultdict(lambda: ContribsList())
<1> after: Optional[str] = ""
<2> cont = True
<3> while cont:
<4> after_str = after if isinstance(after, str) else ""
<5> response = get_user_contribution_events(
<6> user_id=user_id,
<7> start_date=start_date,
<8> end_date=end_date,
<9> after=after_str,
<10> access_token=access_token,
<11> )
<12>
<13> cont = False
<14> node_lists = [
<15> ("commit", response.commit_contribs_by_repo),
<16> ("issue", response.issue_contribs_by_repo),
<17> ("pr", response.pr_contribs_by_repo),
<18> ("review", response.review_contribs_by_repo),
<19> ]
<20> for event_type, event_list in node_lists:
<21> for repo in event_list:
<22> name = repo.repo.name
<23> for event in repo.contribs.nodes:
<24> repo_contribs[name].add(event_type, event)
<25> if repo.contribs.page_info.has_next_page:
<26> after = repo.contribs.page_info.end_cursor
<27> cont = True
<28>
<29> for repo in response.repo_contribs.nodes:
<30> name = repo.repo.name
<31> node = RawEventsEvent(occurredAt=str(repo.occurred_at))
<32> repo_contribs[name].add("repo", node)
<33>
<34> return repo_contribs
<35>
|
===========unchanged ref 0===========
at: backend.src.subscriber.aggregation.user.contributions
ContribsList()
at: backend.src.subscriber.aggregation.user.contributions.ContribsList
add(label: str, event: Union[RawEventsCommit, RawEventsEvent])
at: collections
defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]])
defaultdict(default_factory: Optional[Callable[[], _VT]])
defaultdict(**kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT])
at: datetime
datetime()
at: src.data.github.graphql.user.contribs.contribs
get_user_contribution_events(user_id: str, start_date: datetime, end_date: datetime, max_repos: int=100, first: int=100, after: str="", access_token: Optional[str]=None) -> RawEvents
at: src.data.github.graphql.user.contribs.models.RawEvents
commit_contribs_by_repo: List[RawEventsRepoCommits] = Field(
alias="commitContributionsByRepository"
)
issue_contribs_by_repo: List[RawEventsRepo] = Field(
alias="issueContributionsByRepository"
)
pr_contribs_by_repo: List[RawEventsRepo] = Field(
alias="pullRequestContributionsByRepository"
)
===========unchanged ref 1===========
review_contribs_by_repo: List[RawEventsRepo] = Field(
alias="pullRequestReviewContributionsByRepository"
)
repo_contribs: RawEventsRepoContribs = Field(alias="repositoryContributions")
at: src.data.github.graphql.user.contribs.models.RawEventsCommits
nodes: List[RawEventsCommit]
page_info: RawEventsPageInfo = Field(alias="pageInfo")
at: src.data.github.graphql.user.contribs.models.RawEventsContribs
nodes: List[RawEventsEvent]
page_info: RawEventsPageInfo = Field(alias="pageInfo")
at: src.data.github.graphql.user.contribs.models.RawEventsPageInfo
has_next_page: bool = Field(alias="hasNextPage")
end_cursor: Optional[str] = Field(alias="endCursor")
at: src.data.github.graphql.user.contribs.models.RawEventsRepo
repo: RawEventsRepoName = Field(alias="repository")
count: RawEventsCount = Field(alias="totalCount")
contribs: RawEventsContribs = Field(alias="contributions")
at: src.data.github.graphql.user.contribs.models.RawEventsRepoCommits
repo: RawEventsRepoName = Field(alias="repository")
count: RawEventsCount = Field(alias="totalCount")
contribs: RawEventsCommits = Field(alias="contributions")
at: src.data.github.graphql.user.contribs.models.RawEventsRepoContribs
count: int = Field(alias="totalCount")
nodes: List[RawEventsRepoEvent]
at: src.data.github.graphql.user.contribs.models.RawEventsRepoEvent
repo: RawEventsRepoName = Field(alias="repository")
occurred_at: datetime = Field(alias="occurredAt")
===========unchanged ref 2===========
at: src.data.github.graphql.user.contribs.models.RawEventsRepoName
name: str = Field(alias="nameWithOwner")
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.subscriber.aggregation.user.languages
- # TODO Rename this here and in `get_commit_languages`
- def _extracted_from_get_commit_languages_38(commit, out):
- pr = commit.prs.nodes[0]
- total_additions, total_deletions = 0, 0
- for file in pr.files.nodes:
- filename = file.path.split(".")
- extension = "" if len(filename) <= 1 else filename[-1]
- lang = EXTENSIONS.get(f".{extension}", None)
- if lang is not None:
- out.add_lines(lang["name"], lang["color"], file.additions, file.deletions)
- total_additions += file.additions
- total_deletions += file.deletions
- add_ratio = min(pr.additions, commit.additions) / max(1, total_additions)
- del_ratio = min(pr.deletions, commit.deletions) / max(1, total_deletions)
- out.normalize(add_ratio, del_ratio)
-
===========changed ref 1===========
# module: backend.src.subscriber.aggregation.user.languages
def get_commit_languages(
commit: Optional[RawCommit],
files: Optional[List[RawCommitFile]],
repo: RawRepo,
) -> CommitLanguages:
+ # sourcery skip: extract-method
out = CommitLanguages()
if commit is None:
return out
if max(commit.additions, commit.deletions) == 0:
return out
# assummed to be auto-generated or copied
if max(commit.additions, commit.deletions) > 10 * CUTOFF or (
max(commit.additions, commit.deletions) > CUTOFF
and min(commit.additions, commit.deletions) == 0
):
return out
pr_coverage = 0
if len(commit.prs.nodes) > 0:
pr_obj = commit.prs.nodes[0]
pr_files = pr_obj.files.nodes
total_changed = sum(x.additions + x.deletions for x in pr_files)
pr_coverage = total_changed / max(1, (pr_obj.additions + pr_obj.deletions))
if files is not None:
for file in files:
filename = file.filename.split(".")
extension = "" if len(filename) <= 1 else filename[-1]
lang = EXTENSIONS.get(f".{extension}", None)
if lang is not None:
out.add_lines(
lang["name"], lang["color"], file.additions, file.deletions
)
elif len(commit.prs.nodes) > 0 and pr_coverage > 0.25:
+ pr = commit.prs.nodes[0]
+ total_additions, total_deletions = 0, 0
+ for file in pr.files.nodes:
+ filename = file.path.split(".")
+ extension = "" if len(filename) <= 1 else filename[-1]
+ lang = EXTENSIONS.get(f".{extension}", None)
</s>
|
backend.src.subscriber.processing.auth/check_user_starred_repo
|
Modified
|
avgupta456~github-trends
|
6a10c5749e0973ae212cf42cc07df19b550d83e4
|
Update auth.py (#210)
|
<1>:<add> try:
<add> repo_stargazers = await get_repo_stargazers(owner, repo)
<del> repo_stargazers = await get_repo_stargazers(owner, repo)
<2>:<add> if user_id in repo_stargazers:
<del> if user_id in repo_stargazers:
<3>:<add> return True
<del> return True
<4>:<add> except RESTError:
<add> return True # Assume the user has starred the repo
|
# module: backend.src.subscriber.processing.auth
def check_user_starred_repo(
user_id: str, owner: str = OWNER, repo: str = REPO
) -> bool:
<0> # Checks the repo's starred users (with cache)
<1> repo_stargazers = await get_repo_stargazers(owner, repo)
<2> if user_id in repo_stargazers:
<3> return True
<4>
<5> # Checks the user's 30 most recent starred repos (no cache)
<6> user_stars = await get_user_stars(user_id)
<7> return f"{owner}/{repo}" in user_stars
<8>
|
===========unchanged ref 0===========
at: src.constants
OWNER = "avgupta456"
REPO = "github-trends"
at: src.data.github.rest.template
RESTError(*args: object)
at: src.subscriber.aggregation.auth.auth
Callable(*args: List[Any], **kwargs: Dict[str, Any]) -> Any
|
backend.src.subscriber.processing.wrapped/query_wrapped_user
|
Modified
|
avgupta456~github-trends
|
6901f9efe96b204706645545b2e9d65c1346532f
|
Don't query December
|
<0>:<add> start_date, end_date = date(year, 1, 1), date(year, 11, 31)
<del> start_date, end_date = date(year, 1, 1), date(year, 12, 31)
|
# module: backend.src.subscriber.processing.wrapped
@alru_cache(ttl=timedelta(hours=12))
async def query_wrapped_user(
user_id: str, year: int, no_cache: bool = False
) -> Optional[WrappedPackage]:
<0> start_date, end_date = date(year, 1, 1), date(year, 12, 31)
<1> user: Optional[PublicUserModel] = await db_get_public_user(user_id)
<2> access_token = None if user is None else user.access_token
<3> private_access = False if user is None else user.private_access or False
<4> user_package: UserPackage = await query_user(
<5> user_id, access_token, private_access, start_date, end_date, no_cache=True
<6> )
<7> wrapped_package = get_wrapped_data(user_package, year)
<8>
<9> # Don't cache if incomplete
<10> return (not wrapped_package.incomplete, wrapped_package) # type: ignore
<11>
|
===========unchanged ref 0===========
at: datetime
timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...)
date()
at: src.data.mongo.user.get
Callable(*args: List[Any], **kwargs: Dict[str, Any]) -> Any
at: src.data.mongo.user.models.PublicUserModel
user_id: str
access_token: str
private_access: Optional[bool]
at: src.models.wrapped.main.WrappedPackage
month_data: MonthData
day_data: DayData
calendar_data: CalendarData
numeric_data: NumericData
repo_data: RepoData
lang_data: LangData
timestamp_data: TimestampData
incomplete: bool = False
at: src.subscriber.aggregation.wrapped.package
main(user_package: UserPackage, year: int) -> WrappedPackage
at: src.subscriber.processing.user
Callable(*args: List[Any], **kwargs: Dict[str, Any]) -> Any
at: src.utils.alru_cache
alru_cache(max_size: int=128, ttl: timedelta=timedelta(minutes=1))
|
backend.src.subscriber.processing.wrapped/query_wrapped_user
|
Modified
|
avgupta456~github-trends
|
1039e27ec140b22c61e85a4e392e1fb68a8eb99a
|
Update wrapped.py
|
<0>:<add> start_date, end_date = date(year, 1, 1), date(year, 11, 30)
<del> start_date, end_date = date(year, 1, 1), date(year, 11, 31)
|
# module: backend.src.subscriber.processing.wrapped
@alru_cache(ttl=timedelta(hours=12))
async def query_wrapped_user(
user_id: str, year: int, no_cache: bool = False
) -> Optional[WrappedPackage]:
<0> start_date, end_date = date(year, 1, 1), date(year, 11, 31)
<1> user: Optional[PublicUserModel] = await db_get_public_user(user_id)
<2> access_token = None if user is None else user.access_token
<3> private_access = False if user is None else user.private_access or False
<4> user_package: UserPackage = await query_user(
<5> user_id, access_token, private_access, start_date, end_date, no_cache=True
<6> )
<7> wrapped_package = get_wrapped_data(user_package, year)
<8>
<9> # Don't cache if incomplete
<10> return (not wrapped_package.incomplete, wrapped_package) # type: ignore
<11>
|
===========unchanged ref 0===========
at: datetime
timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...)
date()
at: src.data.mongo.user.get
Callable(*args: List[Any], **kwargs: Dict[str, Any]) -> Any
at: src.data.mongo.user.models.PublicUserModel
user_id: str
access_token: str
private_access: Optional[bool]
at: src.models.wrapped.main.WrappedPackage
month_data: MonthData
day_data: DayData
calendar_data: CalendarData
numeric_data: NumericData
repo_data: RepoData
lang_data: LangData
timestamp_data: TimestampData
incomplete: bool = False
at: src.subscriber.aggregation.wrapped.package
main(user_package: UserPackage, year: int) -> WrappedPackage
at: src.subscriber.processing.user
Callable(*args: List[Any], **kwargs: Dict[str, Any]) -> Any
at: src.utils.alru_cache
alru_cache(max_size: int=128, ttl: timedelta=timedelta(minutes=1))
|
backend.src.subscriber.processing.wrapped/query_wrapped_user
|
Modified
|
avgupta456~github-trends
|
d80e0825b634a615173e03e363e481d80b625cf3
|
Include December (#224)
|
<0>:<add> start_date, end_date = date(year, 1, 1), date(year, 12, 31)
<del> start_date, end_date = date(year, 1, 1), date(year, 11, 30)
|
# module: backend.src.subscriber.processing.wrapped
@alru_cache(ttl=timedelta(hours=12))
async def query_wrapped_user(
user_id: str, year: int, no_cache: bool = False
) -> Optional[WrappedPackage]:
<0> start_date, end_date = date(year, 1, 1), date(year, 11, 30)
<1> user: Optional[PublicUserModel] = await db_get_public_user(user_id)
<2> access_token = None if user is None else user.access_token
<3> private_access = False if user is None else user.private_access or False
<4> user_package: UserPackage = await query_user(
<5> user_id, access_token, private_access, start_date, end_date, no_cache=True
<6> )
<7> wrapped_package = get_wrapped_data(user_package, year)
<8>
<9> # Don't cache if incomplete
<10> return (not wrapped_package.incomplete, wrapped_package) # type: ignore
<11>
|
===========unchanged ref 0===========
at: datetime
timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...)
date()
at: src.data.mongo.user.get
Callable(*args: List[Any], **kwargs: Dict[str, Any]) -> Any
at: src.data.mongo.user.models.PublicUserModel
user_id: str
access_token: str
private_access: Optional[bool]
at: src.models.wrapped.main.WrappedPackage
month_data: MonthData
day_data: DayData
calendar_data: CalendarData
numeric_data: NumericData
repo_data: RepoData
lang_data: LangData
timestamp_data: TimestampData
incomplete: bool = False
at: src.subscriber.aggregation.wrapped.package
main(user_package: UserPackage, year: int) -> WrappedPackage
at: src.subscriber.processing.user
Callable(*args: List[Any], **kwargs: Dict[str, Any]) -> Any
at: src.utils.alru_cache
alru_cache(max_size: int=128, ttl: timedelta=timedelta(minutes=1))
|
backend.src.data.mongo.user_months.get/get_user_months
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<22>:<add> UserMonth.model_validate(
<del> UserMonth.parse_obj(
<29>:<add> "data": data.model_dump(),
<del> "data": data.dict(),
|
# module: backend.src.data.mongo.user_months.get
def get_user_months(
user_id: str, private_access: bool, start_month: date, end_month: date
) -> List[UserMonth]:
<0> start = datetime(start_month.year, start_month.month, 1)
<1> end = datetime(end_month.year, end_month.month, 28)
<2> today = datetime.now()
<3>
<4> filters = {
<5> "user_id": user_id,
<6> "month": {"$gte": start, "$lte": end},
<7> "version": API_VERSION,
<8> }
<9>
<10> if private_access:
<11> filters["private"] = True
<12>
<13> months: List[Dict[str, Any]] = await USER_MONTHS.find(filters).to_list(length=None) # type: ignore
<14>
<15> months_data: List[UserMonth] = []
<16> for month in months:
<17> date_obj: datetime = month["month"]
<18> complete = not (date_obj.year == today.year and date_obj.month == today.month)
<19> try:
<20> data = UserPackage.decompress(month["data"])
<21> months_data.append(
<22> UserMonth.parse_obj(
<23> {
<24> "user_id": user_id,
<25> "month": month["month"],
<26> "version": API_VERSION,
<27> "private": month["private"],
<28> "complete": complete,
<29> "data": data.dict(),
<30> }
<31> )
<32> )
<33> except Exception:
<34> pass
<35>
<36> return months_data
<37>
|
===========unchanged ref 0===========
at: datetime
date()
datetime()
at: datetime.date
__slots__ = '_year', '_month', '_day', '_hashcode'
__str__ = isoformat
__radd__ = __add__
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: src.constants
API_VERSION = 0.02 # determines when to overwrite MongoDB data
at: src.data.mongo.main
USER_MONTHS = DB.user_months
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
decompress(data: Dict[str, Any]) -> "UserPackage"
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.src.data.github.rest.repo/get_repo_commits
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<26>:<add> return RawCommit.model_validate(temp)
<del> return RawCommit.parse_obj(temp)
|
# module: backend.src.data.github.rest.repo
def get_repo_commits(
owner: str,
repo: str,
user: Optional[str] = None,
since: Optional[datetime] = None,
until: Optional[datetime] = None,
page: int = 1,
access_token: Optional[str] = None,
) -> List[RawCommit]:
<0> """
<1> Returns most recent commits
<2> :param access_token: GitHub access token
<3> :param owner: repository owner
<4> :param repo: repository name
<5> :param user: optional GitHub user if not owner
<6> :param since: optional datetime to start from
<7> :param until: optional datetime to end at
<8> :param page: optional page number
<9> :return: Up to 100 commits from page
<10> """
<11> user = user if user is not None else owner
<12> query = BASE_URL + owner + "/" + repo + "/commits?author=" + user
<13> if since is not None:
<14> query += f"&since={str(since)}"
<15> if until is not None:
<16> query += f"&until={str(until)}"
<17> try:
<18> data = get_template_plural(query, access_token, page=page)
<19>
<20> def extract_info(x: Any) -> RawCommit:
<21> dt = x["commit"]["committer"]["date"]
<22> temp = {
<23> "timestamp": datetime.strptime(dt, "%Y-%m-%dT%H:%M:%SZ"),
<24> "node_id": x["node_id"],
<25> }
<26> return RawCommit.parse_obj(temp)
<27>
<28> return list(map(extract_info, data))
<29> except RESTError:
<30> return []
<31> except Exception as e:
<32> logging.exception(e)
<33> return []
<34>
|
===========unchanged ref 0===========
at: backend.src.data.github.rest.repo
BASE_URL = "https://api.github.com/repos/"
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
strptime(date_string: _Text, format: _Text) -> datetime
__radd__ = __add__
at: logging
exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: src.data.github.rest.template
RESTError(*args: object)
get_template_plural(query: str, access_token: Optional[str]=None, per_page: int=100, page: int=1, accept_header: str="application/vnd.github.v3+json") -> List[Dict[str, Any]]
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.data.mongo.user_months.get
def get_user_months(
user_id: str, private_access: bool, start_month: date, end_month: date
) -> List[UserMonth]:
start = datetime(start_month.year, start_month.month, 1)
end = datetime(end_month.year, end_month.month, 28)
today = datetime.now()
filters = {
"user_id": user_id,
"month": {"$gte": start, "$lte": end},
"version": API_VERSION,
}
if private_access:
filters["private"] = True
months: List[Dict[str, Any]] = await USER_MONTHS.find(filters).to_list(length=None) # type: ignore
months_data: List[UserMonth] = []
for month in months:
date_obj: datetime = month["month"]
complete = not (date_obj.year == today.year and date_obj.month == today.month)
try:
data = UserPackage.decompress(month["data"])
months_data.append(
+ UserMonth.model_validate(
- UserMonth.parse_obj(
{
"user_id": user_id,
"month": month["month"],
"version": API_VERSION,
"private": month["private"],
"complete": complete,
+ "data": data.model_dump(),
- "data": data.dict(),
}
)
)
except Exception:
pass
return months_data
|
backend.src.data.github.graphql.repo/get_repo
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<33>:<add> return RawRepo.model_validate(raw_repo)
<del> return RawRepo.parse_obj(raw_repo)
|
# module: backend.src.data.github.graphql.repo
def get_repo(
owner: str,
repo: str,
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> Optional[RawRepo]:
<0> """
<1> Gets all repository data from graphql
<2> :param access_token: GitHub access token
<3> :param owner: GitHub owner
<4> :param repo: GitHub repository
<5> :return: RawRepo object or None if repo not present
<6> """
<7> query = {
<8> "variables": {"owner": owner, "repo": repo},
<9> "query": """
<10> query getRepo($owner: String!, $repo: String!) {
<11> repository(owner: $owner, name: $repo) {
<12> isPrivate,
<13> forkCount,
<14> stargazerCount,
<15> languages(first: 10){
<16> totalCount,
<17> totalSize,
<18> edges{
<19> node {
<20> name,
<21> color,
<22> },
<23> size,
<24> },
<25> },
<26> }
<27> }
<28> """,
<29> }
<30>
<31> try:
<32> raw_repo = get_template(query, access_token)["data"]["repository"]
<33> return RawRepo.parse_obj(raw_repo)
<34> except Exception as e:
<35> if catch_errors:
<36> return None
<37> raise e
<38>
|
===========unchanged ref 0===========
at: src.data.github.graphql.template
get_template(query: Dict[str, Any], access_token: Optional[str]=None, retries: int=0) -> Dict[str, Any]
===========changed ref 0===========
# module: backend.src.data.github.rest.repo
def get_repo_commits(
owner: str,
repo: str,
user: Optional[str] = None,
since: Optional[datetime] = None,
until: Optional[datetime] = None,
page: int = 1,
access_token: Optional[str] = None,
) -> List[RawCommit]:
"""
Returns most recent commits
:param access_token: GitHub access token
:param owner: repository owner
:param repo: repository name
:param user: optional GitHub user if not owner
:param since: optional datetime to start from
:param until: optional datetime to end at
:param page: optional page number
:return: Up to 100 commits from page
"""
user = user if user is not None else owner
query = BASE_URL + owner + "/" + repo + "/commits?author=" + user
if since is not None:
query += f"&since={str(since)}"
if until is not None:
query += f"&until={str(until)}"
try:
data = get_template_plural(query, access_token, page=page)
def extract_info(x: Any) -> RawCommit:
dt = x["commit"]["committer"]["date"]
temp = {
"timestamp": datetime.strptime(dt, "%Y-%m-%dT%H:%M:%SZ"),
"node_id": x["node_id"],
}
+ return RawCommit.model_validate(temp)
- return RawCommit.parse_obj(temp)
return list(map(extract_info, data))
except RESTError:
return []
except Exception as e:
logging.exception(e)
return []
===========changed ref 1===========
# module: backend.src.data.mongo.user_months.get
def get_user_months(
user_id: str, private_access: bool, start_month: date, end_month: date
) -> List[UserMonth]:
start = datetime(start_month.year, start_month.month, 1)
end = datetime(end_month.year, end_month.month, 28)
today = datetime.now()
filters = {
"user_id": user_id,
"month": {"$gte": start, "$lte": end},
"version": API_VERSION,
}
if private_access:
filters["private"] = True
months: List[Dict[str, Any]] = await USER_MONTHS.find(filters).to_list(length=None) # type: ignore
months_data: List[UserMonth] = []
for month in months:
date_obj: datetime = month["month"]
complete = not (date_obj.year == today.year and date_obj.month == today.month)
try:
data = UserPackage.decompress(month["data"])
months_data.append(
+ UserMonth.model_validate(
- UserMonth.parse_obj(
{
"user_id": user_id,
"month": month["month"],
"version": API_VERSION,
"private": month["private"],
"complete": complete,
+ "data": data.model_dump(),
- "data": data.dict(),
}
)
)
except Exception:
pass
return months_data
|
backend.src.data.github.graphql.user.follows.follows/get_user_followers
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<52>:<add> return RawFollows.model_validate(output_dict)
<del> return RawFollows.parse_obj(output_dict)
|
# module: backend.src.data.github.graphql.user.follows.follows
def get_user_followers(
user_id: str, first: int = 100, after: str = "", access_token: Optional[str] = None
) -> RawFollows:
<0> """gets user's followers and users following'"""
<1>
<2> variables: Dict[str, Union[str, int]] = (
<3> {"login": user_id, "first": first, "after": after}
<4> if after != ""
<5> else {"login": user_id, "first": first}
<6> )
<7>
<8> query_str: str = (
<9> """
<10> query getUser($login: String!, $first: Int!, $after: String!) {
<11> user(login: $login){
<12> followers(first: $first, after: $after){
<13> nodes{
<14> name,
<15> login,
<16> url
<17> }
<18> pageInfo{
<19> hasNextPage,
<20> endCursor
<21> }
<22> }
<23> }
<24> }
<25> """
<26> if after != ""
<27> else """
<28> query getUser($login: String!, $first: Int!) {
<29> user(login: $login){
<30> followers(first: $first){
<31> nodes{
<32> name,
<33> login,
<34> url
<35> }
<36> pageInfo{
<37> hasNextPage,
<38> endCursor
<39> }
<40> }
<41> }
<42> }
<43> """
<44> )
<45>
<46> query = {
<47> "variables": variables,
<48> "query": query_str,
<49> }
<50>
<51> output_dict = get_template(query, access_token)["data"]["user"]["followers"]
<52> return RawFollows.parse_obj(output_dict)
<53>
|
===========unchanged ref 0===========
at: src.data.github.graphql.template
get_template(query: Dict[str, Any], access_token: Optional[str]=None, retries: int=0) -> Dict[str, Any]
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.data.github.graphql.repo
def get_repo(
owner: str,
repo: str,
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> Optional[RawRepo]:
"""
Gets all repository data from graphql
:param access_token: GitHub access token
:param owner: GitHub owner
:param repo: GitHub repository
:return: RawRepo object or None if repo not present
"""
query = {
"variables": {"owner": owner, "repo": repo},
"query": """
query getRepo($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
isPrivate,
forkCount,
stargazerCount,
languages(first: 10){
totalCount,
totalSize,
edges{
node {
name,
color,
},
size,
},
},
}
}
""",
}
try:
raw_repo = get_template(query, access_token)["data"]["repository"]
+ return RawRepo.model_validate(raw_repo)
- return RawRepo.parse_obj(raw_repo)
except Exception as e:
if catch_errors:
return None
raise e
===========changed ref 1===========
# module: backend.src.data.github.rest.repo
def get_repo_commits(
owner: str,
repo: str,
user: Optional[str] = None,
since: Optional[datetime] = None,
until: Optional[datetime] = None,
page: int = 1,
access_token: Optional[str] = None,
) -> List[RawCommit]:
"""
Returns most recent commits
:param access_token: GitHub access token
:param owner: repository owner
:param repo: repository name
:param user: optional GitHub user if not owner
:param since: optional datetime to start from
:param until: optional datetime to end at
:param page: optional page number
:return: Up to 100 commits from page
"""
user = user if user is not None else owner
query = BASE_URL + owner + "/" + repo + "/commits?author=" + user
if since is not None:
query += f"&since={str(since)}"
if until is not None:
query += f"&until={str(until)}"
try:
data = get_template_plural(query, access_token, page=page)
def extract_info(x: Any) -> RawCommit:
dt = x["commit"]["committer"]["date"]
temp = {
"timestamp": datetime.strptime(dt, "%Y-%m-%dT%H:%M:%SZ"),
"node_id": x["node_id"],
}
+ return RawCommit.model_validate(temp)
- return RawCommit.parse_obj(temp)
return list(map(extract_info, data))
except RESTError:
return []
except Exception as e:
logging.exception(e)
return []
===========changed ref 2===========
# module: backend.src.data.mongo.user_months.get
def get_user_months(
user_id: str, private_access: bool, start_month: date, end_month: date
) -> List[UserMonth]:
start = datetime(start_month.year, start_month.month, 1)
end = datetime(end_month.year, end_month.month, 28)
today = datetime.now()
filters = {
"user_id": user_id,
"month": {"$gte": start, "$lte": end},
"version": API_VERSION,
}
if private_access:
filters["private"] = True
months: List[Dict[str, Any]] = await USER_MONTHS.find(filters).to_list(length=None) # type: ignore
months_data: List[UserMonth] = []
for month in months:
date_obj: datetime = month["month"]
complete = not (date_obj.year == today.year and date_obj.month == today.month)
try:
data = UserPackage.decompress(month["data"])
months_data.append(
+ UserMonth.model_validate(
- UserMonth.parse_obj(
{
"user_id": user_id,
"month": month["month"],
"version": API_VERSION,
"private": month["private"],
"complete": complete,
+ "data": data.model_dump(),
- "data": data.dict(),
}
)
)
except Exception:
pass
return months_data
|
backend.src.data.github.graphql.user.follows.follows/get_user_following
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<52>:<add> return RawFollows.model_validate(output_dict)
<del> return RawFollows.parse_obj(output_dict)
|
# module: backend.src.data.github.graphql.user.follows.follows
def get_user_following(
user_id: str, first: int = 10, after: str = "", access_token: Optional[str] = None
) -> RawFollows:
<0> """gets user's followers and users following'"""
<1>
<2> variables: Dict[str, Union[str, int]] = (
<3> {"login": user_id, "first": first, "after": after}
<4> if after != ""
<5> else {"login": user_id, "first": first}
<6> )
<7>
<8> query_str: str = (
<9> """
<10> query getUser($login: String!, $first: Int!, $after: String!) {
<11> user(login: $login){
<12> following(first: $first, after: $after){
<13> nodes{
<14> name,
<15> login,
<16> url
<17> }
<18> pageInfo{
<19> hasNextPage,
<20> endCursor
<21> }
<22> }
<23> }
<24> }
<25> """
<26> if after != ""
<27> else """
<28> query getUser($login: String!, $first: Int!) {
<29> user(login: $login){
<30> following(first: $first){
<31> nodes{
<32> name,
<33> login,
<34> url
<35> }
<36> pageInfo{
<37> hasNextPage,
<38> endCursor
<39> }
<40> }
<41> }
<42> }
<43> """
<44> )
<45>
<46> query = {
<47> "variables": variables,
<48> "query": query_str,
<49> }
<50>
<51> output_dict = get_template(query, access_token)["data"]["user"]["following"]
<52> return RawFollows.parse_obj(output_dict)
<53>
|
===========unchanged ref 0===========
at: src.data.github.graphql.template
get_template(query: Dict[str, Any], access_token: Optional[str]=None, retries: int=0) -> Dict[str, Any]
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.data.github.graphql.user.follows.follows
def get_user_followers(
user_id: str, first: int = 100, after: str = "", access_token: Optional[str] = None
) -> RawFollows:
"""gets user's followers and users following'"""
variables: Dict[str, Union[str, int]] = (
{"login": user_id, "first": first, "after": after}
if after != ""
else {"login": user_id, "first": first}
)
query_str: str = (
"""
query getUser($login: String!, $first: Int!, $after: String!) {
user(login: $login){
followers(first: $first, after: $after){
nodes{
name,
login,
url
}
pageInfo{
hasNextPage,
endCursor
}
}
}
}
"""
if after != ""
else """
query getUser($login: String!, $first: Int!) {
user(login: $login){
followers(first: $first){
nodes{
name,
login,
url
}
pageInfo{
hasNextPage,
endCursor
}
}
}
}
"""
)
query = {
"variables": variables,
"query": query_str,
}
output_dict = get_template(query, access_token)["data"]["user"]["followers"]
+ return RawFollows.model_validate(output_dict)
- return RawFollows.parse_obj(output_dict)
===========changed ref 1===========
# module: backend.src.data.github.graphql.repo
def get_repo(
owner: str,
repo: str,
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> Optional[RawRepo]:
"""
Gets all repository data from graphql
:param access_token: GitHub access token
:param owner: GitHub owner
:param repo: GitHub repository
:return: RawRepo object or None if repo not present
"""
query = {
"variables": {"owner": owner, "repo": repo},
"query": """
query getRepo($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
isPrivate,
forkCount,
stargazerCount,
languages(first: 10){
totalCount,
totalSize,
edges{
node {
name,
color,
},
size,
},
},
}
}
""",
}
try:
raw_repo = get_template(query, access_token)["data"]["repository"]
+ return RawRepo.model_validate(raw_repo)
- return RawRepo.parse_obj(raw_repo)
except Exception as e:
if catch_errors:
return None
raise e
===========changed ref 2===========
# module: backend.src.data.github.rest.repo
def get_repo_commits(
owner: str,
repo: str,
user: Optional[str] = None,
since: Optional[datetime] = None,
until: Optional[datetime] = None,
page: int = 1,
access_token: Optional[str] = None,
) -> List[RawCommit]:
"""
Returns most recent commits
:param access_token: GitHub access token
:param owner: repository owner
:param repo: repository name
:param user: optional GitHub user if not owner
:param since: optional datetime to start from
:param until: optional datetime to end at
:param page: optional page number
:return: Up to 100 commits from page
"""
user = user if user is not None else owner
query = BASE_URL + owner + "/" + repo + "/commits?author=" + user
if since is not None:
query += f"&since={str(since)}"
if until is not None:
query += f"&until={str(until)}"
try:
data = get_template_plural(query, access_token, page=page)
def extract_info(x: Any) -> RawCommit:
dt = x["commit"]["committer"]["date"]
temp = {
"timestamp": datetime.strptime(dt, "%Y-%m-%dT%H:%M:%SZ"),
"node_id": x["node_id"],
}
+ return RawCommit.model_validate(temp)
- return RawCommit.parse_obj(temp)
return list(map(extract_info, data))
except RESTError:
return []
except Exception as e:
logging.exception(e)
return []
===========changed ref 3===========
# module: backend.src.data.mongo.user_months.get
def get_user_months(
user_id: str, private_access: bool, start_month: date, end_month: date
) -> List[UserMonth]:
start = datetime(start_month.year, start_month.month, 1)
end = datetime(end_month.year, end_month.month, 28)
today = datetime.now()
filters = {
"user_id": user_id,
"month": {"$gte": start, "$lte": end},
"version": API_VERSION,
}
if private_access:
filters["private"] = True
months: List[Dict[str, Any]] = await USER_MONTHS.find(filters).to_list(length=None) # type: ignore
months_data: List[UserMonth] = []
for month in months:
date_obj: datetime = month["month"]
complete = not (date_obj.year == today.year and date_obj.month == today.month)
try:
data = UserPackage.decompress(month["data"])
months_data.append(
+ UserMonth.model_validate(
- UserMonth.parse_obj(
{
"user_id": user_id,
"month": month["month"],
"version": API_VERSION,
"private": month["private"],
"complete": complete,
+ "data": data.model_dump(),
- "data": data.dict(),
}
)
)
except Exception:
pass
return months_data
|
backend.src.data.github.graphql.commit/get_commits
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
# module: backend.src.data.github.graphql.commit
def get_commits(
node_ids: List[str], access_token: Optional[str] = None, catch_errors: bool = False
) -> List[Optional[RawCommit]]:
<0> """
<1> Gets all repository data from graphql
<2> :param access_token: GitHub access token
<3> :param node_ids: List of node ids
<4> :return: List of commits
<5> """
<6>
<7> if PR_FILES == 0: # type: ignore
<8> query = {
<9> "variables": {"ids": node_ids},
<10> "query": """
<11> query getCommits($ids: [ID!]!) {
<12> nodes(ids: $ids) {
<13> ... on Commit {
<14> additions
<15> deletions
<16> changedFiles
<17> url
<18> }
<19> }
<20> }
<21> """,
<22> }
<23> else:
<24> query = {
<25> "variables": {"ids": node_ids, "first": PR_FILES},
<26> "query": """
<27> query getCommits($ids: [ID!]!, $first: Int!) {
<28> nodes(ids: $ids) {
<29> ... on Commit {
<30> additions
<31> deletions
<32> changedFiles
<33> url
<34> associatedPullRequests(first: 1) {
<35> nodes {
<36> changedFiles
<37> additions
<38> deletions
<39> files(first: $first) {
<40> nodes {
<41> path
<42> additions
<43> deletions
<44> }
<45> }
<46> }
<47> }
<48> }
<49> }
<50> }
<51> """,
<52> }
<53>
<54> try:
<55> raw_commits = get_template(query, access_token)["data"]["nodes"]
<56> except GraphQLErrorMissingNode as e:
<57> return (
<58> get_commits(node_ids[: e.node], access_token)
<59> + [None]
<60> + get_commits(node_ids[e.node + 1 :],</s>
|
===========below chunk 0===========
# module: backend.src.data.github.graphql.commit
def get_commits(
node_ids: List[str], access_token: Optional[str] = None, catch_errors: bool = False
) -> List[Optional[RawCommit]]:
# offset: 1
)
except (GraphQLErrorRateLimit, GraphQLErrorTimeout, GraphQLError) as e:
if catch_errors:
return [None for _ in node_ids]
raise e
out: List[Optional[RawCommit]] = []
for raw_commit in raw_commits:
try:
if "associatedPullRequests" not in raw_commit:
raw_commit["associatedPullRequests"] = {"nodes": []}
out.append(RawCommit.parse_obj(raw_commit))
except Exception as e:
if catch_errors:
out.append(None)
else:
raise e
return out
===========unchanged ref 0===========
at: src.constants
PR_FILES = 5 # max number of files to query for PRs
at: src.data.github.graphql.template
GraphQLError(*args: object)
GraphQLErrorMissingNode(node: int)
GraphQLErrorRateLimit(*args: object)
GraphQLErrorTimeout(*args: object)
get_template(query: Dict[str, Any], access_token: Optional[str]=None, retries: int=0) -> Dict[str, Any]
at: src.data.github.graphql.template.GraphQLErrorMissingNode.__init__
self.node = node
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.data.github.graphql.repo
def get_repo(
owner: str,
repo: str,
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> Optional[RawRepo]:
"""
Gets all repository data from graphql
:param access_token: GitHub access token
:param owner: GitHub owner
:param repo: GitHub repository
:return: RawRepo object or None if repo not present
"""
query = {
"variables": {"owner": owner, "repo": repo},
"query": """
query getRepo($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
isPrivate,
forkCount,
stargazerCount,
languages(first: 10){
totalCount,
totalSize,
edges{
node {
name,
color,
},
size,
},
},
}
}
""",
}
try:
raw_repo = get_template(query, access_token)["data"]["repository"]
+ return RawRepo.model_validate(raw_repo)
- return RawRepo.parse_obj(raw_repo)
except Exception as e:
if catch_errors:
return None
raise e
===========changed ref 1===========
# module: backend.src.data.github.rest.repo
def get_repo_commits(
owner: str,
repo: str,
user: Optional[str] = None,
since: Optional[datetime] = None,
until: Optional[datetime] = None,
page: int = 1,
access_token: Optional[str] = None,
) -> List[RawCommit]:
"""
Returns most recent commits
:param access_token: GitHub access token
:param owner: repository owner
:param repo: repository name
:param user: optional GitHub user if not owner
:param since: optional datetime to start from
:param until: optional datetime to end at
:param page: optional page number
:return: Up to 100 commits from page
"""
user = user if user is not None else owner
query = BASE_URL + owner + "/" + repo + "/commits?author=" + user
if since is not None:
query += f"&since={str(since)}"
if until is not None:
query += f"&until={str(until)}"
try:
data = get_template_plural(query, access_token, page=page)
def extract_info(x: Any) -> RawCommit:
dt = x["commit"]["committer"]["date"]
temp = {
"timestamp": datetime.strptime(dt, "%Y-%m-%dT%H:%M:%SZ"),
"node_id": x["node_id"],
}
+ return RawCommit.model_validate(temp)
- return RawCommit.parse_obj(temp)
return list(map(extract_info, data))
except RESTError:
return []
except Exception as e:
logging.exception(e)
return []
===========changed ref 2===========
# module: backend.src.data.mongo.user_months.get
def get_user_months(
user_id: str, private_access: bool, start_month: date, end_month: date
) -> List[UserMonth]:
start = datetime(start_month.year, start_month.month, 1)
end = datetime(end_month.year, end_month.month, 28)
today = datetime.now()
filters = {
"user_id": user_id,
"month": {"$gte": start, "$lte": end},
"version": API_VERSION,
}
if private_access:
filters["private"] = True
months: List[Dict[str, Any]] = await USER_MONTHS.find(filters).to_list(length=None) # type: ignore
months_data: List[UserMonth] = []
for month in months:
date_obj: datetime = month["month"]
complete = not (date_obj.year == today.year and date_obj.month == today.month)
try:
data = UserPackage.decompress(month["data"])
months_data.append(
+ UserMonth.model_validate(
- UserMonth.parse_obj(
{
"user_id": user_id,
"month": month["month"],
"version": API_VERSION,
"private": month["private"],
"complete": complete,
+ "data": data.model_dump(),
- "data": data.dict(),
}
)
)
except Exception:
pass
return months_data
===========changed ref 3===========
# module: backend.src.data.github.graphql.user.follows.follows
def get_user_following(
user_id: str, first: int = 10, after: str = "", access_token: Optional[str] = None
) -> RawFollows:
"""gets user's followers and users following'"""
variables: Dict[str, Union[str, int]] = (
{"login": user_id, "first": first, "after": after}
if after != ""
else {"login": user_id, "first": first}
)
query_str: str = (
"""
query getUser($login: String!, $first: Int!, $after: String!) {
user(login: $login){
following(first: $first, after: $after){
nodes{
name,
login,
url
}
pageInfo{
hasNextPage,
endCursor
}
}
}
}
"""
if after != ""
else """
query getUser($login: String!, $first: Int!) {
user(login: $login){
following(first: $first){
nodes{
name,
login,
url
}
pageInfo{
hasNextPage,
endCursor
}
}
}
}
"""
)
query = {
"variables": variables,
"query": query_str,
}
output_dict = get_template(query, access_token)["data"]["user"]["following"]
+ return RawFollows.model_validate(output_dict)
- return RawFollows.parse_obj(output_dict)
|
|
backend.src.subscriber.aggregation.wrapped.time/get_month_data
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<22>:<add> out.append(TimeDatum.model_validate(_obj))
<del> out.append(TimeDatum.parse_obj(_obj))
|
# module: backend.src.subscriber.aggregation.wrapped.time
def get_month_data(data: UserPackage) -> MonthData:
<0> months: Dict[int, Dict[str, int]] = defaultdict(
<1> lambda: {"contribs": 0, "loc_changed": 0}
<2> )
<3>
<4> for item in data.contribs.total:
<5> month = datetime.fromisoformat(item.date).month - 1
<6> months[month]["contribs"] += item.stats.contribs_count
<7> loc_changed = sum(
<8> x.additions + x.deletions for x in item.stats.languages.values()
<9> )
<10>
<11> months[month]["loc_changed"] += loc_changed
<12>
<13> out: List[TimeDatum] = []
<14> for k in range(12):
<15> v = months[k]
<16> _obj: Dict[str, Union[str, int]] = {
<17> "index": k,
<18> **v,
<19> "formatted_loc_changed": format_number(v["loc_changed"]),
<20> }
<21>
<22> out.append(TimeDatum.parse_obj(_obj))
<23>
<24> return MonthData(months=out)
<25>
|
===========unchanged ref 0===========
at: collections
defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]])
defaultdict(default_factory: Optional[Callable[[], _VT]])
defaultdict(**kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT])
at: datetime
datetime()
at: datetime.date
__slots__ = '_year', '_month', '_day', '_hashcode'
__str__ = isoformat
__radd__ = __add__
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
fromisoformat(date_string: str) -> _S
__radd__ = __add__
at: src.models.user.contribs.ContributionDay
date: str
weekday: int
stats: ContributionStats
lists: ContributionLists
at: src.models.user.contribs.ContributionStats
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.Language
color: Optional[str]
additions: int
deletions: int
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
public_stats: ContributionStats
total: List[ContributionDay]
===========unchanged ref 1===========
public: List[ContributionDay]
repo_stats: Dict[str, RepoContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
at: src.utils.utils
format_number(num: int) -> str
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.data.github.graphql.repo
def get_repo(
owner: str,
repo: str,
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> Optional[RawRepo]:
"""
Gets all repository data from graphql
:param access_token: GitHub access token
:param owner: GitHub owner
:param repo: GitHub repository
:return: RawRepo object or None if repo not present
"""
query = {
"variables": {"owner": owner, "repo": repo},
"query": """
query getRepo($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
isPrivate,
forkCount,
stargazerCount,
languages(first: 10){
totalCount,
totalSize,
edges{
node {
name,
color,
},
size,
},
},
}
}
""",
}
try:
raw_repo = get_template(query, access_token)["data"]["repository"]
+ return RawRepo.model_validate(raw_repo)
- return RawRepo.parse_obj(raw_repo)
except Exception as e:
if catch_errors:
return None
raise e
===========changed ref 1===========
# module: backend.src.data.github.rest.repo
def get_repo_commits(
owner: str,
repo: str,
user: Optional[str] = None,
since: Optional[datetime] = None,
until: Optional[datetime] = None,
page: int = 1,
access_token: Optional[str] = None,
) -> List[RawCommit]:
"""
Returns most recent commits
:param access_token: GitHub access token
:param owner: repository owner
:param repo: repository name
:param user: optional GitHub user if not owner
:param since: optional datetime to start from
:param until: optional datetime to end at
:param page: optional page number
:return: Up to 100 commits from page
"""
user = user if user is not None else owner
query = BASE_URL + owner + "/" + repo + "/commits?author=" + user
if since is not None:
query += f"&since={str(since)}"
if until is not None:
query += f"&until={str(until)}"
try:
data = get_template_plural(query, access_token, page=page)
def extract_info(x: Any) -> RawCommit:
dt = x["commit"]["committer"]["date"]
temp = {
"timestamp": datetime.strptime(dt, "%Y-%m-%dT%H:%M:%SZ"),
"node_id": x["node_id"],
}
+ return RawCommit.model_validate(temp)
- return RawCommit.parse_obj(temp)
return list(map(extract_info, data))
except RESTError:
return []
except Exception as e:
logging.exception(e)
return []
===========changed ref 2===========
# module: backend.src.data.mongo.user_months.get
def get_user_months(
user_id: str, private_access: bool, start_month: date, end_month: date
) -> List[UserMonth]:
start = datetime(start_month.year, start_month.month, 1)
end = datetime(end_month.year, end_month.month, 28)
today = datetime.now()
filters = {
"user_id": user_id,
"month": {"$gte": start, "$lte": end},
"version": API_VERSION,
}
if private_access:
filters["private"] = True
months: List[Dict[str, Any]] = await USER_MONTHS.find(filters).to_list(length=None) # type: ignore
months_data: List[UserMonth] = []
for month in months:
date_obj: datetime = month["month"]
complete = not (date_obj.year == today.year and date_obj.month == today.month)
try:
data = UserPackage.decompress(month["data"])
months_data.append(
+ UserMonth.model_validate(
- UserMonth.parse_obj(
{
"user_id": user_id,
"month": month["month"],
"version": API_VERSION,
"private": month["private"],
"complete": complete,
+ "data": data.model_dump(),
- "data": data.dict(),
}
)
)
except Exception:
pass
return months_data
|
backend.src.subscriber.aggregation.wrapped.time/get_day_data
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<22>:<add> out.append(TimeDatum.model_validate(_obj))
<del> out.append(TimeDatum.parse_obj(_obj))
|
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
<0> days: Dict[int, Dict[str, int]] = defaultdict(
<1> lambda: {"contribs": 0, "loc_changed": 0}
<2> )
<3>
<4> for item in data.contribs.total:
<5> day = datetime.fromisoformat(item.date).weekday()
<6> days[day]["contribs"] += item.stats.contribs_count
<7> loc_changed = sum(
<8> x.additions + x.deletions for x in item.stats.languages.values()
<9> )
<10>
<11> days[day]["loc_changed"] += loc_changed
<12>
<13> out: List[TimeDatum] = []
<14> for k in range(7):
<15> v = days[k]
<16> _obj: Dict[str, Union[str, int]] = {
<17> "index": k,
<18> **v,
<19> "formatted_loc_changed": format_number(v["loc_changed"]),
<20> }
<21>
<22> out.append(TimeDatum.parse_obj(_obj))
<23>
<24> return DayData(days=out)
<25>
|
===========unchanged ref 0===========
at: collections
defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]])
defaultdict(default_factory: Optional[Callable[[], _VT]])
defaultdict(**kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT])
at: datetime
datetime()
at: datetime.date
weekday() -> int
at: datetime.datetime
fromisoformat(date_string: str) -> _S
at: src.models.user.contribs.ContributionDay
date: str
stats: ContributionStats
at: src.models.user.contribs.ContributionStats
contribs_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.Language
additions: int
deletions: int
at: src.models.user.contribs.UserContributions
total: List[ContributionDay]
at: src.models.user.main.UserPackage
contribs: UserContributions
at: src.utils.utils
format_number(num: int) -> str
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_month_data(data: UserPackage) -> MonthData:
months: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
month = datetime.fromisoformat(item.date).month - 1
months[month]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
months[month]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(12):
v = months[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return MonthData(months=out)
===========changed ref 1===========
# module: backend.src.data.github.graphql.repo
def get_repo(
owner: str,
repo: str,
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> Optional[RawRepo]:
"""
Gets all repository data from graphql
:param access_token: GitHub access token
:param owner: GitHub owner
:param repo: GitHub repository
:return: RawRepo object or None if repo not present
"""
query = {
"variables": {"owner": owner, "repo": repo},
"query": """
query getRepo($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
isPrivate,
forkCount,
stargazerCount,
languages(first: 10){
totalCount,
totalSize,
edges{
node {
name,
color,
},
size,
},
},
}
}
""",
}
try:
raw_repo = get_template(query, access_token)["data"]["repository"]
+ return RawRepo.model_validate(raw_repo)
- return RawRepo.parse_obj(raw_repo)
except Exception as e:
if catch_errors:
return None
raise e
===========changed ref 2===========
# module: backend.src.data.github.rest.repo
def get_repo_commits(
owner: str,
repo: str,
user: Optional[str] = None,
since: Optional[datetime] = None,
until: Optional[datetime] = None,
page: int = 1,
access_token: Optional[str] = None,
) -> List[RawCommit]:
"""
Returns most recent commits
:param access_token: GitHub access token
:param owner: repository owner
:param repo: repository name
:param user: optional GitHub user if not owner
:param since: optional datetime to start from
:param until: optional datetime to end at
:param page: optional page number
:return: Up to 100 commits from page
"""
user = user if user is not None else owner
query = BASE_URL + owner + "/" + repo + "/commits?author=" + user
if since is not None:
query += f"&since={str(since)}"
if until is not None:
query += f"&until={str(until)}"
try:
data = get_template_plural(query, access_token, page=page)
def extract_info(x: Any) -> RawCommit:
dt = x["commit"]["committer"]["date"]
temp = {
"timestamp": datetime.strptime(dt, "%Y-%m-%dT%H:%M:%SZ"),
"node_id": x["node_id"],
}
+ return RawCommit.model_validate(temp)
- return RawCommit.parse_obj(temp)
return list(map(extract_info, data))
except RESTError:
return []
except Exception as e:
logging.exception(e)
return []
===========changed ref 3===========
# module: backend.src.data.mongo.user_months.get
def get_user_months(
user_id: str, private_access: bool, start_month: date, end_month: date
) -> List[UserMonth]:
start = datetime(start_month.year, start_month.month, 1)
end = datetime(end_month.year, end_month.month, 28)
today = datetime.now()
filters = {
"user_id": user_id,
"month": {"$gte": start, "$lte": end},
"version": API_VERSION,
}
if private_access:
filters["private"] = True
months: List[Dict[str, Any]] = await USER_MONTHS.find(filters).to_list(length=None) # type: ignore
months_data: List[UserMonth] = []
for month in months:
date_obj: datetime = month["month"]
complete = not (date_obj.year == today.year and date_obj.month == today.month)
try:
data = UserPackage.decompress(month["data"])
months_data.append(
+ UserMonth.model_validate(
- UserMonth.parse_obj(
{
"user_id": user_id,
"month": month["month"],
"version": API_VERSION,
"private": month["private"],
"complete": complete,
+ "data": data.model_dump(),
- "data": data.dict(),
}
)
)
except Exception:
pass
return months_data
|
backend.src.subscriber.routers.wrapped/check_valid_user
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<0>:<add> print("Checking valid user")
<add> out = await get_is_valid_user(user_id)
<del> return await get_is_valid_user(user_id)
<1>:<add> print(out)
<add> return out
|
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
<0> return await get_is_valid_user(user_id)
<1>
|
===========unchanged ref 0===========
at: backend.src.subscriber.routers.wrapped
router = APIRouter()
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 1===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 2===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 3===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 5===========
+ # module: backend.delete_old_data
+ def main():
+ # Replace 'your_date_field' with the actual name of your date field
+ cutoff_date = datetime(2022, 12, 31)
+
+ count = await count_old_rows(cutoff_date)
+ if count == 0:
+ print("No rows to delete.")
+ return
+
+ print(f"Found {count} rows to delete.")
+ print()
+
+ confirmation = input("Are you sure you want to delete these rows? (yes/no): ")
+ if confirmation.lower() != "yes":
+ print("Operation canceled.")
+ return
+
+ print()
+ await delete_old_rows(cutoff_date)
+
===========changed ref 6===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
days: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
day = datetime.fromisoformat(item.date).weekday()
days[day]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
days[day]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(7):
v = days[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return DayData(days=out)
===========changed ref 7===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_month_data(data: UserPackage) -> MonthData:
months: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
month = datetime.fromisoformat(item.date).month - 1
months[month]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
months[month]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(12):
v = months[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return MonthData(months=out)
===========changed ref 8===========
# module: backend.src.data.github.graphql.repo
def get_repo(
owner: str,
repo: str,
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> Optional[RawRepo]:
"""
Gets all repository data from graphql
:param access_token: GitHub access token
:param owner: GitHub owner
:param repo: GitHub repository
:return: RawRepo object or None if repo not present
"""
query = {
"variables": {"owner": owner, "repo": repo},
"query": """
query getRepo($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
isPrivate,
forkCount,
stargazerCount,
languages(first: 10){
totalCount,
totalSize,
edges{
node {
name,
color,
},
size,
},
},
}
}
""",
}
try:
raw_repo = get_template(query, access_token)["data"]["repository"]
+ return RawRepo.model_validate(raw_repo)
- return RawRepo.parse_obj(raw_repo)
except Exception as e:
if catch_errors:
return None
raise e
===========changed ref 9===========
# module: backend.src.data.github.rest.repo
def get_repo_commits(
owner: str,
repo: str,
user: Optional[str] = None,
since: Optional[datetime] = None,
until: Optional[datetime] = None,
page: int = 1,
access_token: Optional[str] = None,
) -> List[RawCommit]:
"""
Returns most recent commits
:param access_token: GitHub access token
:param owner: repository owner
:param repo: repository name
:param user: optional GitHub user if not owner
:param since: optional datetime to start from
:param until: optional datetime to end at
:param page: optional page number
:return: Up to 100 commits from page
"""
user = user if user is not None else owner
query = BASE_URL + owner + "/" + repo + "/commits?author=" + user
if since is not None:
query += f"&since={str(since)}"
if until is not None:
query += f"&until={str(until)}"
try:
data = get_template_plural(query, access_token, page=page)
def extract_info(x: Any) -> RawCommit:
dt = x["commit"]["committer"]["date"]
temp = {
"timestamp": datetime.strptime(dt, "%Y-%m-%dT%H:%M:%SZ"),
"node_id": x["node_id"],
}
+ return RawCommit.model_validate(temp)
- return RawCommit.parse_obj(temp)
return list(map(extract_info, data))
except RESTError:
return []
except Exception as e:
logging.exception(e)
return []
|
backend.src.data.mongo.secret.functions/get_keys
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<4>:<add> tokens = SecretModel.model_validate(secrets).access_tokens
<del> tokens = SecretModel.parse_obj(secrets).access_tokens
|
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
<0> secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
<1> if secrets is None:
<2> return (False, []) # type: ignore
<3>
<4> tokens = SecretModel.parse_obj(secrets).access_tokens
<5> return (True, tokens) # type: ignore
<6>
|
===========unchanged ref 0===========
at: datetime
timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...)
at: src.data.mongo.main
SECRETS = DB.secrets
at: src.utils.alru_cache
alru_cache(max_size: int=128, ttl: timedelta=timedelta(minutes=1))
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 1===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 2===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 3===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 5===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 6===========
+ # module: backend.delete_old_data
+ def main():
+ # Replace 'your_date_field' with the actual name of your date field
+ cutoff_date = datetime(2022, 12, 31)
+
+ count = await count_old_rows(cutoff_date)
+ if count == 0:
+ print("No rows to delete.")
+ return
+
+ print(f"Found {count} rows to delete.")
+ print()
+
+ confirmation = input("Are you sure you want to delete these rows? (yes/no): ")
+ if confirmation.lower() != "yes":
+ print("Operation canceled.")
+ return
+
+ print()
+ await delete_old_rows(cutoff_date)
+
===========changed ref 7===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
days: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
day = datetime.fromisoformat(item.date).weekday()
days[day]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
days[day]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(7):
v = days[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return DayData(days=out)
===========changed ref 8===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_month_data(data: UserPackage) -> MonthData:
months: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
month = datetime.fromisoformat(item.date).month - 1
months[month]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
months[month]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(12):
v = months[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return MonthData(months=out)
===========changed ref 9===========
# module: backend.src.data.github.graphql.repo
def get_repo(
owner: str,
repo: str,
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> Optional[RawRepo]:
"""
Gets all repository data from graphql
:param access_token: GitHub access token
:param owner: GitHub owner
:param repo: GitHub repository
:return: RawRepo object or None if repo not present
"""
query = {
"variables": {"owner": owner, "repo": repo},
"query": """
query getRepo($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
isPrivate,
forkCount,
stargazerCount,
languages(first: 10){
totalCount,
totalSize,
edges{
node {
name,
color,
},
size,
},
},
}
}
""",
}
try:
raw_repo = get_template(query, access_token)["data"]["repository"]
+ return RawRepo.model_validate(raw_repo)
- return RawRepo.parse_obj(raw_repo)
except Exception as e:
if catch_errors:
return None
raise e
|
backend.src.data.github.graphql.user.contribs.contribs/get_user_contribution_calendar
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<30>:<add> return RawCalendar.model_validate(output)
<del> return RawCalendar.parse_obj(output)
|
# module: backend.src.data.github.graphql.user.contribs.contribs
def get_user_contribution_calendar(
user_id: str,
start_date: datetime,
end_date: datetime,
access_token: Optional[str] = None,
) -> RawCalendar:
<0> """Gets contribution calendar for a given time period (max one year)"""
<1> if (end_date - start_date).days > 365:
<2> raise ValueError("date range can be at most 1 year")
<3> query = {
<4> "variables": {
<5> "login": user_id,
<6> "startDate": start_date.strftime("%Y-%m-%dT%H:%M:%SZ"),
<7> "endDate": end_date.strftime("%Y-%m-%dT%H:%M:%SZ"),
<8> },
<9> "query": """
<10> query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!){
<11> user(login: $login){
<12> contributionsCollection(from: $startDate, to: $endDate){
<13> contributionCalendar{
<14> weeks{
<15> contributionDays{
<16> date
<17> weekday
<18> contributionCount
<19> }
<20> }
<21> }
<22> }
<23> }
<24> }
<25> """,
<26> }
<27>
<28> raw_data = get_template(query, access_token)
<29> output = raw_data["data"]["user"]["contributionsCollection"]["contributionCalendar"]
<30> return RawCalendar.parse_obj(output)
<31>
|
===========unchanged ref 0===========
at: datetime
datetime()
at: datetime.date
__slots__ = '_year', '_month', '_day', '_hashcode'
strftime(fmt: _Text) -> str
__str__ = isoformat
__radd__ = __add__
at: datetime.timedelta
__slots__ = '_days', '_seconds', '_microseconds', '_hashcode'
__radd__ = __add__
__rmul__ = __mul__
at: src.data.github.graphql.template
get_template(query: Dict[str, Any], access_token: Optional[str]=None, retries: int=0) -> Dict[str, Any]
===========changed ref 0===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 1===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 2===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 3===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 5===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 6===========
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
if secrets is None:
return (False, []) # type: ignore
+ tokens = SecretModel.model_validate(secrets).access_tokens
- tokens = SecretModel.parse_obj(secrets).access_tokens
return (True, tokens) # type: ignore
===========changed ref 7===========
+ # module: backend.delete_old_data
+ def main():
+ # Replace 'your_date_field' with the actual name of your date field
+ cutoff_date = datetime(2022, 12, 31)
+
+ count = await count_old_rows(cutoff_date)
+ if count == 0:
+ print("No rows to delete.")
+ return
+
+ print(f"Found {count} rows to delete.")
+ print()
+
+ confirmation = input("Are you sure you want to delete these rows? (yes/no): ")
+ if confirmation.lower() != "yes":
+ print("Operation canceled.")
+ return
+
+ print()
+ await delete_old_rows(cutoff_date)
+
===========changed ref 8===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
days: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
day = datetime.fromisoformat(item.date).weekday()
days[day]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
days[day]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(7):
v = days[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return DayData(days=out)
===========changed ref 9===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_month_data(data: UserPackage) -> MonthData:
months: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
month = datetime.fromisoformat(item.date).month - 1
months[month]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
months[month]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(12):
v = months[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return MonthData(months=out)
===========changed ref 10===========
# module: backend.src.data.github.graphql.repo
def get_repo(
owner: str,
repo: str,
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> Optional[RawRepo]:
"""
Gets all repository data from graphql
:param access_token: GitHub access token
:param owner: GitHub owner
:param repo: GitHub repository
:return: RawRepo object or None if repo not present
"""
query = {
"variables": {"owner": owner, "repo": repo},
"query": """
query getRepo($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
isPrivate,
forkCount,
stargazerCount,
languages(first: 10){
totalCount,
totalSize,
edges{
node {
name,
color,
},
size,
},
},
}
}
""",
}
try:
raw_repo = get_template(query, access_token)["data"]["repository"]
+ return RawRepo.model_validate(raw_repo)
- return RawRepo.parse_obj(raw_repo)
except Exception as e:
if catch_errors:
return None
raise e
|
backend.src.data.github.graphql.user.contribs.contribs/get_user_contribution_events
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
# module: backend.src.data.github.graphql.user.contribs.contribs
def get_user_contribution_events(
user_id: str,
start_date: datetime,
end_date: datetime,
max_repos: int = 100,
first: int = 100,
after: str = "",
access_token: Optional[str] = None,
) -> RawEvents:
<0> """Fetches user contributions (commits, issues, prs, reviews)"""
<1> if (end_date - start_date).days > 365:
<2> raise ValueError("date range can be at most 1 year")
<3> query = {
<4> "variables": {
<5> "login": user_id,
<6> "startDate": start_date.strftime("%Y-%m-%dT%H:%M:%SZ"),
<7> "endDate": end_date.strftime("%Y-%m-%dT%H:%M:%SZ"),
<8> "maxRepos": max_repos,
<9> "first": first,
<10> "after": after,
<11> },
<12> "query": """
<13> query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!, $maxRepos: Int!, $first: Int!, $after: String!) {
<14> user(login: $login){
<15> contributionsCollection(from: $startDate, to: $endDate){
<16> commitContributionsByRepository(maxRepositories: $maxRepos){
<17> repository{
<18> nameWithOwner,
<19> },
<20> totalCount:contributions(first: 1){
<21> totalCount
<22> }
<23> contributions(first: $first, after: $after){
<24> nodes{
<25> commitCount,
<26> occurredAt,
<27> }
<28> pageInfo{
<29> hasNextPage,
<30> endCursor
<31> }
<32> }
<33> }
<34> issueContributionsByRepository(maxRepositories: $maxRepos){
<35> repository{
<36> nameWithOwner
<37> },
<38> totalCount:contributions(first: 1){
<39> totalCount
<40> }
<41> </s>
|
===========below chunk 0===========
# module: backend.src.data.github.graphql.user.contribs.contribs
def get_user_contribution_events(
user_id: str,
start_date: datetime,
end_date: datetime,
max_repos: int = 100,
first: int = 100,
after: str = "",
access_token: Optional[str] = None,
) -> RawEvents:
# offset: 1
nodes{
occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
pullRequestContributionsByRepository(maxRepositories: $maxRepos){
repository{
nameWithOwner
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: $first, after: $after){
nodes{
occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
}
pullRequestReviewContributionsByRepository(maxRepositories: $maxRepos){
repository{
nameWithOwner
},
totalCount:contributions(first: 1){
totalCount
}
contributions(first: $first, after: $after){
nodes{
occurredAt,
}
pageInfo{
hasNextPage,
endCursor
}
}
},
repositoryContributions(first: $maxRepos){
totalCount
nodes{
repository{
nameWithOwner,
}
occurredAt,
}
},
},
}
}
""",
}
raw_data = get_template(query, access_token)
output = raw_data["data"]["user"]["contributionsCollection"]
return RawEvents.parse_obj(output)
===========unchanged ref 0===========
at: datetime
datetime()
at: datetime.date
strftime(fmt: _Text) -> str
at: src.data.github.graphql.template
get_template(query: Dict[str, Any], access_token: Optional[str]=None, retries: int=0) -> Dict[str, Any]
===========changed ref 0===========
# module: backend.src.data.github.graphql.user.contribs.contribs
def get_user_contribution_calendar(
user_id: str,
start_date: datetime,
end_date: datetime,
access_token: Optional[str] = None,
) -> RawCalendar:
"""Gets contribution calendar for a given time period (max one year)"""
if (end_date - start_date).days > 365:
raise ValueError("date range can be at most 1 year")
query = {
"variables": {
"login": user_id,
"startDate": start_date.strftime("%Y-%m-%dT%H:%M:%SZ"),
"endDate": end_date.strftime("%Y-%m-%dT%H:%M:%SZ"),
},
"query": """
query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!){
user(login: $login){
contributionsCollection(from: $startDate, to: $endDate){
contributionCalendar{
weeks{
contributionDays{
date
weekday
contributionCount
}
}
}
}
}
}
""",
}
raw_data = get_template(query, access_token)
output = raw_data["data"]["user"]["contributionsCollection"]["contributionCalendar"]
+ return RawCalendar.model_validate(output)
- return RawCalendar.parse_obj(output)
===========changed ref 1===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 2===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 3===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 5===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 6===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 7===========
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
if secrets is None:
return (False, []) # type: ignore
+ tokens = SecretModel.model_validate(secrets).access_tokens
- tokens = SecretModel.parse_obj(secrets).access_tokens
return (True, tokens) # type: ignore
===========changed ref 8===========
+ # module: backend.delete_old_data
+ def main():
+ # Replace 'your_date_field' with the actual name of your date field
+ cutoff_date = datetime(2022, 12, 31)
+
+ count = await count_old_rows(cutoff_date)
+ if count == 0:
+ print("No rows to delete.")
+ return
+
+ print(f"Found {count} rows to delete.")
+ print()
+
+ confirmation = input("Are you sure you want to delete these rows? (yes/no): ")
+ if confirmation.lower() != "yes":
+ print("Operation canceled.")
+ return
+
+ print()
+ await delete_old_rows(cutoff_date)
+
|
|
backend.src.subscriber.aggregation.wrapped.langs/get_lang_data
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<16>:<add> lang_objs.append(LangDatum.model_validate(lang_data))
<del> lang_objs.append(LangDatum.parse_obj(lang_data))
<21>:<add> "id": "other",
<del> "id": -1,
<28>:<add> lang_objs.append(LangDatum.model_validate(lang_data))
<del> lang_objs.append(LangDatum.parse_obj(lang_data))
<32>:<add> return LangData.model_validate(out)
<del> return LangData.parse_obj(out)
|
# module: backend.src.subscriber.aggregation.wrapped.langs
def get_lang_data(data: UserPackage) -> LangData:
<0> out = {}
<1> for m in ["changed", "added"]:
<2> langs = sorted(
<3> data.contribs.total_stats.languages.items(),
<4> key=lambda x: _count_loc(x[1], m),
<5> reverse=True,
<6> )
<7> lang_objs: List[LangDatum] = []
<8> for k, v in list(langs)[:5]:
<9> lang_data = {
<10> "id": k,
<11> "label": k,
<12> "value": _count_loc(v, m),
<13> "formatted_value": format_number(_count_loc(v, m)),
<14> "color": v.color,
<15> }
<16> lang_objs.append(LangDatum.parse_obj(lang_data))
<17>
<18> # remaining languages
<19> total_count = sum(_count_loc(v, m) for _, v in list(langs)[5:])
<20> lang_data = {
<21> "id": -1,
<22> "label": "other",
<23> "value": total_count,
<24> "formatted_value": format_number(total_count),
<25> "color": DEFAULT_COLOR,
<26> }
<27> if total_count > 100:
<28> lang_objs.append(LangDatum.parse_obj(lang_data))
<29>
<30> out[f"langs_{m}"] = lang_objs
<31>
<32> return LangData.parse_obj(out)
<33>
|
===========unchanged ref 0===========
at: backend.src.subscriber.aggregation.wrapped.langs
_count_loc(x: Language, metric: str) -> int
at: src.constants
DEFAULT_COLOR = "#858585"
at: src.models.user.contribs.ContributionStats
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.Language
color: Optional[str]
additions: int
deletions: int
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
public_stats: ContributionStats
total: List[ContributionDay]
public: List[ContributionDay]
repo_stats: Dict[str, RepoContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
at: src.utils.utils
format_number(num: int) -> str
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 1===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 2===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 3===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 5===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 6===========
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
if secrets is None:
return (False, []) # type: ignore
+ tokens = SecretModel.model_validate(secrets).access_tokens
- tokens = SecretModel.parse_obj(secrets).access_tokens
return (True, tokens) # type: ignore
===========changed ref 7===========
+ # module: backend.delete_old_data
+ def main():
+ # Replace 'your_date_field' with the actual name of your date field
+ cutoff_date = datetime(2022, 12, 31)
+
+ count = await count_old_rows(cutoff_date)
+ if count == 0:
+ print("No rows to delete.")
+ return
+
+ print(f"Found {count} rows to delete.")
+ print()
+
+ confirmation = input("Are you sure you want to delete these rows? (yes/no): ")
+ if confirmation.lower() != "yes":
+ print("Operation canceled.")
+ return
+
+ print()
+ await delete_old_rows(cutoff_date)
+
===========changed ref 8===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
days: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
day = datetime.fromisoformat(item.date).weekday()
days[day]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
days[day]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(7):
v = days[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return DayData(days=out)
===========changed ref 9===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_month_data(data: UserPackage) -> MonthData:
months: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
month = datetime.fromisoformat(item.date).month - 1
months[month]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
months[month]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(12):
v = months[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return MonthData(months=out)
|
backend.src.publisher.aggregation.user.commits/get_top_languages
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<6>:<add> languages_list = [
<add> LanguageStats(
<del> languages_list: List[dict_type] = [
<7>:<del> {
<8>:<add> lang=lang,
<del> "lang": lang,
<9>:<add> color=stats.color or DEFAULT_COLOR,
<del> "color": stats.color or DEFAULT_COLOR,
<10>:<add> loc=loc_metric_func(loc_metric, stats.additions, stats.deletions),
<del> "loc": loc_metric_func(loc_metric, stats.additions, stats.deletions),
<11>:<add> percent=-1,
<add> )
<del> }
<15>:<add> languages_list = list(filter(lambda x: x.loc > 0, languages_list))
<del> languages_list = list(filter(lambda x: x["loc"] > 0, languages_list)) # type: ignore
<17>:<add> total_loc = sum(x.loc for x in languages_list) + 1
<del> total_loc: int = sum(x["loc"] for x in languages_list) + 1 # type: ignore
<18>:<add> total = LanguageStats(lang="Total", color=None, loc=total_loc, percent=100)
<del> total: dict_type = {"lang": "Total", "loc": total_loc}
<20>:<add> languages_list = sorted(languages_list, key=lambda x: x.loc, reverse=True)
<del> languages_list = sorted(languages_list, key=lambda x: x["loc"], reverse=True)
<21>:<add> other = LanguageStats(lang="Other", color="#ededed", loc=0, percent=-1)
<del> other: dict_type = {"lang": "Other", "loc": 0, "color": "#ededed"}
<23>:<add> other.loc = other.loc + language.loc
<del> other["loc"] = int(other["loc"]) + int(language["loc"])
<29>:<add> lang.percent =
|
# module: backend.src.publisher.aggregation.user.commits
def get_top_languages(
data: UserPackage, loc_metric: str, include_private: bool
) -> Tuple[List[LanguageStats], int]:
<0> raw_languages = (
<1> data.contribs.total_stats.languages
<2> if include_private
<3> else data.contribs.public_stats.languages
<4> )
<5>
<6> languages_list: List[dict_type] = [
<7> {
<8> "lang": lang,
<9> "color": stats.color or DEFAULT_COLOR,
<10> "loc": loc_metric_func(loc_metric, stats.additions, stats.deletions),
<11> }
<12> for lang, stats in raw_languages.items()
<13> ]
<14>
<15> languages_list = list(filter(lambda x: x["loc"] > 0, languages_list)) # type: ignore
<16>
<17> total_loc: int = sum(x["loc"] for x in languages_list) + 1 # type: ignore
<18> total: dict_type = {"lang": "Total", "loc": total_loc}
<19>
<20> languages_list = sorted(languages_list, key=lambda x: x["loc"], reverse=True)
<21> other: dict_type = {"lang": "Other", "loc": 0, "color": "#ededed"}
<22> for language in languages_list[4:]:
<23> other["loc"] = int(other["loc"]) + int(language["loc"])
<24>
<25> languages_list = [total] + languages_list[:4] + [other]
<26>
<27> new_languages_list: List[LanguageStats] = []
<28> for lang in languages_list:
<29> lang["percent"] = float(round(100 * int(lang["loc"]) / total_loc, 2))
<30> if lang["percent"] > 1: # 1% minimum to show
<31> new_languages_list.append(LanguageStats.parse_obj(lang))
<32>
<33> commits_excluded = data.contribs.public_stats.other_count
<34> if include</s>
|
===========below chunk 0===========
# module: backend.src.publisher.aggregation.user.commits
def get_top_languages(
data: UserPackage, loc_metric: str, include_private: bool
) -> Tuple[List[LanguageStats], int]:
# offset: 1
commits_excluded = data.contribs.total_stats.other_count
return new_languages_list, commits_excluded
===========unchanged ref 0===========
at: backend.src.publisher.aggregation.user.commits
loc_metric_func(loc_metric: str, additions: int, deletions: int) -> int
at: src.constants
DEFAULT_COLOR = "#858585"
at: src.models.user.contribs.ContributionStats
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.Language
color: Optional[str]
additions: int
deletions: int
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
public_stats: ContributionStats
total: List[ContributionDay]
public: List[ContributionDay]
repo_stats: Dict[str, RepoContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
at: src.publisher.aggregation.user.models.LanguageStats
lang: str
loc: int
percent: float
color: Optional[str]
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 1===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 2===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 3===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 5===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 6===========
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
if secrets is None:
return (False, []) # type: ignore
+ tokens = SecretModel.model_validate(secrets).access_tokens
- tokens = SecretModel.parse_obj(secrets).access_tokens
return (True, tokens) # type: ignore
===========changed ref 7===========
+ # module: backend.delete_old_data
+ def main():
+ # Replace 'your_date_field' with the actual name of your date field
+ cutoff_date = datetime(2022, 12, 31)
+
+ count = await count_old_rows(cutoff_date)
+ if count == 0:
+ print("No rows to delete.")
+ return
+
+ print(f"Found {count} rows to delete.")
+ print()
+
+ confirmation = input("Are you sure you want to delete these rows? (yes/no): ")
+ if confirmation.lower() != "yes":
+ print("Operation canceled.")
+ return
+
+ print()
+ await delete_old_rows(cutoff_date)
+
===========changed ref 8===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
days: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
day = datetime.fromisoformat(item.date).weekday()
days[day]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
days[day]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(7):
v = days[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return DayData(days=out)
===========changed ref 9===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_month_data(data: UserPackage) -> MonthData:
months: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
month = datetime.fromisoformat(item.date).month - 1
months[month]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
months[month]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(12):
v = months[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return MonthData(months=out)
|
backend.src.publisher.aggregation.user.commits/get_top_repos
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<0>:<del> # sourcery skip: switch
<28>:<add> RepoStats.model_validate(x) for x in repos if x["loc"] > 0.01 * repos[0]["loc"]
<del> RepoStats.parse_obj(x) for x in repos if x["loc"] > 0.01 * repos[0]["loc"]
|
# module: backend.src.publisher.aggregation.user.commits
def get_top_repos(
data: UserPackage, loc_metric: str, include_private: bool, group: str
) -> Tuple[List[RepoStats], int]:
<0> # sourcery skip: switch
<1> repos: List[Any] = [
<2> {
<3> "repo": repo,
<4> "private": repo_stats.private,
<5> "langs": [
<6> {
<7> "lang": x[0],
<8> "color": x[1].color,
<9> "loc": loc_metric_func(loc_metric, x[1].additions, x[1].deletions),
<10> }
<11> for x in list(repo_stats.languages.items())
<12> ],
<13> }
<14> for repo, repo_stats in data.contribs.repo_stats.items()
<15> if include_private or not repo_stats.private
<16> ]
<17>
<18> for repo in repos:
<19> repo["loc"] = sum(x["loc"] for x in repo["langs"]) # first estimate
<20> repos = list(filter(lambda x: x["loc"] > 0, repos))
<21>
<22> for repo in repos:
<23> repo["langs"] = [x for x in repo["langs"] if x["loc"] > 0.05 * repo["loc"]]
<24> repo["loc"] = sum(x["loc"] for x in repo["langs"]) # final estimate
<25> repos = sorted(repos, key=lambda x: x["loc"], reverse=True)
<26>
<27> new_repos = [
<28> RepoStats.parse_obj(x) for x in repos if x["loc"] > 0.01 * repos[0]["loc"]
<29> ]
<30>
<31> commits_excluded = data.contribs.public_stats.other_count
<32> if include_private:
<33> commits_excluded = data.contribs.total_stats.other_count
<34>
<35> # With n bars, group from n onwards into the last bar
<36> bars = 4 # TODO: make this</s>
|
===========below chunk 0===========
# module: backend.src.publisher.aggregation.user.commits
def get_top_repos(
data: UserPackage, loc_metric: str, include_private: bool, group: str
) -> Tuple[List[RepoStats], int]:
# offset: 1
if group == "none" or len(new_repos) <= bars:
return new_repos[:bars], commits_excluded
out_repos = []
other_repos = []
if group == "other":
out_repos = new_repos[: bars - 1]
other_repos = new_repos[bars - 1 :]
elif group == "private":
public_repos = [x for x in new_repos if not x.private]
private_repos = [x for x in new_repos if x.private]
if len(public_repos) < 4 and len(private_repos) > 0:
public_repos += private_repos[: bars - len(public_repos) - 1]
private_repos = private_repos[bars - len(public_repos) - 1 :]
out_repos = sorted(public_repos[: bars - 1], key=lambda x: x.loc, reverse=True)
other_repos = public_repos[bars - 1 :] + private_repos
else:
raise ValueError("Invalid group value")
other: Dict[str, Tuple[int, Optional[str]]] = {}
for repo in other_repos:
for _lang in repo.langs:
lang = _lang.lang
if lang not in other:
other[lang] = (0, _lang.color)
other[lang] = (other[lang][0] + _lang.loc, other[lang][1])
out_repos.append(
RepoStats(
repo="other/repos",
private=False,
langs=[{"lang": k, "loc": v[0], "color": v[1]} for k, v in other.items()], # type: ignore
loc=sum(v[0] for v in other.values()),
)
)
return out_repos,</s>
===========below chunk 1===========
# module: backend.src.publisher.aggregation.user.commits
def get_top_repos(
data: UserPackage, loc_metric: str, include_private: bool, group: str
) -> Tuple[List[RepoStats], int]:
# offset: 2
<s> loc=sum(v[0] for v in other.values()),
)
)
return out_repos, commits_excluded
===========unchanged ref 0===========
at: backend.src.publisher.aggregation.user.commits
loc_metric_func(loc_metric: str, additions: int, deletions: int) -> int
at: src.models.user.contribs.ContributionStats
other_count: int
at: src.models.user.contribs.Language
color: Optional[str]
additions: int
deletions: int
at: src.models.user.contribs.RepoContributionStats
private: bool
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
public_stats: ContributionStats
repo_stats: Dict[str, RepoContributionStats]
at: src.models.user.main.UserPackage
contribs: UserContributions
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.publisher.aggregation.user.commits
def get_top_languages(
data: UserPackage, loc_metric: str, include_private: bool
) -> Tuple[List[LanguageStats], int]:
raw_languages = (
data.contribs.total_stats.languages
if include_private
else data.contribs.public_stats.languages
)
+ languages_list = [
+ LanguageStats(
- languages_list: List[dict_type] = [
- {
+ lang=lang,
- "lang": lang,
+ color=stats.color or DEFAULT_COLOR,
- "color": stats.color or DEFAULT_COLOR,
+ loc=loc_metric_func(loc_metric, stats.additions, stats.deletions),
- "loc": loc_metric_func(loc_metric, stats.additions, stats.deletions),
+ percent=-1,
+ )
- }
for lang, stats in raw_languages.items()
]
+ languages_list = list(filter(lambda x: x.loc > 0, languages_list))
- languages_list = list(filter(lambda x: x["loc"] > 0, languages_list)) # type: ignore
+ total_loc = sum(x.loc for x in languages_list) + 1
- total_loc: int = sum(x["loc"] for x in languages_list) + 1 # type: ignore
+ total = LanguageStats(lang="Total", color=None, loc=total_loc, percent=100)
- total: dict_type = {"lang": "Total", "loc": total_loc}
+ languages_list = sorted(languages_list, key=lambda x: x.loc, reverse=True)
- languages_list = sorted(languages_list, key=lambda x: x["loc"], reverse=True)
+ other = LanguageStats(lang="Other", color="#ededed", loc=0, percent=-1)
- other: dict_type = {"lang": "Other", "loc": 0, "color": "#e</s>
===========changed ref 1===========
# module: backend.src.publisher.aggregation.user.commits
def get_top_languages(
data: UserPackage, loc_metric: str, include_private: bool
) -> Tuple[List[LanguageStats], int]:
# offset: 1
<s>, percent=-1)
- other: dict_type = {"lang": "Other", "loc": 0, "color": "#ededed"}
for language in languages_list[4:]:
+ other.loc = other.loc + language.loc
- other["loc"] = int(other["loc"]) + int(language["loc"])
languages_list = [total] + languages_list[:4] + [other]
new_languages_list: List[LanguageStats] = []
for lang in languages_list:
+ lang.percent = float(round(100 * lang.loc / total_loc, 2))
- lang["percent"] = float(round(100 * int(lang["loc"]) / total_loc, 2))
+ if lang.percent > 1: # 1% minimum to show
- if lang["percent"] > 1: # 1% minimum to show
+ new_languages_list.append(LanguageStats.model_validate(lang))
- new_languages_list.append(LanguageStats.parse_obj(lang))
commits_excluded = data.contribs.public_stats.other_count
if include_private:
commits_excluded = data.contribs.total_stats.other_count
return new_languages_list, commits_excluded
===========changed ref 2===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 3===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
|
backend.src.utils.alru_cache/alru_cache
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<0>:<del> # sourcery skip: assign-if-exp, boolean-if-exp-identity, reintroduce-else, remove-unnecessary-cast
<1>:<add> def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
<del> def decorator(func: Callable[..., Any]) -> Any:
<29>:<add> try:
<add> # Should not raise KeyError, but just in case
<add> del cache[keys.pop(0)]
<del> del cache[keys.pop(0)]
<30>:<add> except KeyError:
<add> # Already deleted by another thread
<add> pass
<32>:<add> return value # equal to cache[key][1]
<del> return cache[key][1]
<37>:<add> [(k, v) for k, v in kwargs.items() if k not in ["no_cache"]]
<del> {k: v for k, v in kwargs.items() if k not in ["no_cache"]}
|
# module: backend.src.utils.alru_cache
- # NOTE: return flag = False to avoid caching
- # considers one optional parameter, no_cache
- # if true, bypass cache system, otherwise use normally
def alru_cache(max_size: int = 128, ttl: timedelta = timedelta(minutes=1)):
<0> # sourcery skip: assign-if-exp, boolean-if-exp-identity, reintroduce-else, remove-unnecessary-cast
<1> def decorator(func: Callable[..., Any]) -> Any:
<2> cache: Dict[Any, Tuple[datetime, Any]] = {}
<3> keys: List[Any] = []
<4>
<5> def in_cache(key: Any) -> bool:
<6> # key not in cache
<7> if key not in cache:
<8> return False
<9>
<10> # key in cache but expired
<11> if datetime.now() - cache[key][0] > ttl:
<12> return False
<13>
<14> # key in cache and not expired
<15> return True
<16>
<17> def update_cache_and_return(key: Any, flag: bool, value: Any) -> Any:
<18> # if flag = False, do not update cache and return value
<19> if not flag:
<20> return value
<21>
<22> # if flag = True, update cache
<23> now = datetime.now()
<24> cache[key] = (now, value)
<25> keys.append(key)
<26>
<27> # remove oldest key if cache is full
<28> if len(keys) > max_size:
<29> del cache[keys.pop(0)]
<30>
<31> # return value from cache
<32> return cache[key][1]
<33>
<34> @wraps(func)
<35> async def wrapper(*args: List[Any], **kwargs: Dict[str, Any]) -> Any:
<36> key = tuple(args), frozenset(
<37> {k: v for k, v in kwargs.items() if k not in ["no_cache"]}
<38> )
<39> if "no_cache" in kwargs and kwargs["no_cache"]:
<40> (flag, value)</s>
|
===========below chunk 0===========
# module: backend.src.utils.alru_cache
- # NOTE: return flag = False to avoid caching
- # considers one optional parameter, no_cache
- # if true, bypass cache system, otherwise use normally
def alru_cache(max_size: int = 128, ttl: timedelta = timedelta(minutes=1)):
# offset: 1
return update_cache_and_return(key, flag, value)
if in_cache(key):
return cache[key][1]
(flag, value) = await func(*args, **kwargs)
return update_cache_and_return(key, flag, value)
return wrapper
return decorator
===========unchanged ref 0===========
at: datetime
timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...)
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: functools
wraps(wrapped: _AnyCallable, assigned: Sequence[str]=..., updated: Sequence[str]=...) -> Callable[[_T], _T]
at: typing
Callable = _CallableType(collections.abc.Callable, 2)
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 1===========
# module: backend.tests
+ load_dotenv(find_dotenv(), verbose=True)
- load_dotenv(dotenv_path="")
===========changed ref 2===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 3===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 5===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 6===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 7===========
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
if secrets is None:
return (False, []) # type: ignore
+ tokens = SecretModel.model_validate(secrets).access_tokens
- tokens = SecretModel.parse_obj(secrets).access_tokens
return (True, tokens) # type: ignore
===========changed ref 8===========
+ # module: backend.delete_old_data
+ def main():
+ # Replace 'your_date_field' with the actual name of your date field
+ cutoff_date = datetime(2022, 12, 31)
+
+ count = await count_old_rows(cutoff_date)
+ if count == 0:
+ print("No rows to delete.")
+ return
+
+ print(f"Found {count} rows to delete.")
+ print()
+
+ confirmation = input("Are you sure you want to delete these rows? (yes/no): ")
+ if confirmation.lower() != "yes":
+ print("Operation canceled.")
+ return
+
+ print()
+ await delete_old_rows(cutoff_date)
+
===========changed ref 9===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
days: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
day = datetime.fromisoformat(item.date).weekday()
days[day]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
days[day]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(7):
v = days[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return DayData(days=out)
===========changed ref 10===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_month_data(data: UserPackage) -> MonthData:
months: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
month = datetime.fromisoformat(item.date).month - 1
months[month]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
months[month]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(12):
v = months[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return MonthData(months=out)
|
backend.src.subscriber.processing.user/query_user_month
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<24>:<add> user_month = UserMonth.model_validate(
<del> user_month = UserMonth.parse_obj(
|
# module: backend.src.subscriber.processing.user
def query_user_month(
user_id: str,
access_token: Optional[str],
private_access: bool,
start_date: date,
retries: int = 0,
) -> Optional[UserMonth]:
<0> year, month = start_date.year, start_date.month
<1> end_day = monthrange(year, month)[1]
<2> end_date = date(year, month, end_day)
<3>
<4> try:
<5> data = await get_user_data(
<6> user_id=user_id,
<7> start_date=start_date,
<8> end_date=end_date,
<9> timezone_str="US/Eastern",
<10> access_token=access_token,
<11> catch_errors=retries > 0,
<12> )
<13> except GraphQLErrorRateLimit:
<14> return None
<15> except Exception:
<16> # Retry, catching exceptions and marking incomplete this time
<17> if retries < 1:
<18> await query_user_month(
<19> user_id, access_token, private_access, start_date, retries + 1
<20> )
<21> return None
<22>
<23> month_completed = datetime.now() > date_to_datetime(end_date) + timedelta(days=1)
<24> user_month = UserMonth.parse_obj(
<25> {
<26> "user_id": user_id,
<27> "month": date_to_datetime(start_date),
<28> "version": API_VERSION,
<29> "private": private_access,
<30> "complete": retries == 0 and month_completed,
<31> "data": data,
<32> }
<33> )
<34>
<35> await set_user_month(user_month)
<36> return user_month
<37>
|
===========changed ref 0===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 1===========
# module: backend.tests
+ load_dotenv(find_dotenv(), verbose=True)
- load_dotenv(dotenv_path="")
===========changed ref 2===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 3===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 5===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 6===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 7===========
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
if secrets is None:
return (False, []) # type: ignore
+ tokens = SecretModel.model_validate(secrets).access_tokens
- tokens = SecretModel.parse_obj(secrets).access_tokens
return (True, tokens) # type: ignore
===========changed ref 8===========
+ # module: backend.delete_old_data
+ def main():
+ # Replace 'your_date_field' with the actual name of your date field
+ cutoff_date = datetime(2022, 12, 31)
+
+ count = await count_old_rows(cutoff_date)
+ if count == 0:
+ print("No rows to delete.")
+ return
+
+ print(f"Found {count} rows to delete.")
+ print()
+
+ confirmation = input("Are you sure you want to delete these rows? (yes/no): ")
+ if confirmation.lower() != "yes":
+ print("Operation canceled.")
+ return
+
+ print()
+ await delete_old_rows(cutoff_date)
+
===========changed ref 9===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
days: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
day = datetime.fromisoformat(item.date).weekday()
days[day]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
days[day]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(7):
v = days[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return DayData(days=out)
===========changed ref 10===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_month_data(data: UserPackage) -> MonthData:
months: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
month = datetime.fromisoformat(item.date).month - 1
months[month]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
months[month]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(12):
v = months[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return MonthData(months=out)
===========changed ref 11===========
# module: backend.src.data.github.graphql.repo
def get_repo(
owner: str,
repo: str,
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> Optional[RawRepo]:
"""
Gets all repository data from graphql
:param access_token: GitHub access token
:param owner: GitHub owner
:param repo: GitHub repository
:return: RawRepo object or None if repo not present
"""
query = {
"variables": {"owner": owner, "repo": repo},
"query": """
query getRepo($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
isPrivate,
forkCount,
stargazerCount,
languages(first: 10){
totalCount,
totalSize,
edges{
node {
name,
color,
},
size,
},
},
}
}
""",
}
try:
raw_repo = get_template(query, access_token)["data"]["repository"]
+ return RawRepo.model_validate(raw_repo)
- return RawRepo.parse_obj(raw_repo)
except Exception as e:
if catch_errors:
return None
raise e
|
backend.src.models.user.contribs/RepoContributionStats.decompress
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<0>:<add> contribs = super().decompress(data).model_dump()
<del> contribs = super().decompress(data).dict()
|
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
@classmethod
def decompress(cls, data: List[Any]) -> "RepoContributionStats":
<0> contribs = super().decompress(data).dict()
<1> contribs["private"] = data[0][7]
<2> return RepoContributionStats(**contribs)
<3>
|
===========unchanged ref 0===========
at: backend.src.models.user.contribs.ContributionStats
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
decompress(data: List[Any]) -> "ContributionStats"
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 1===========
# module: backend.src.main
+ load_dotenv(find_dotenv())
- load_dotenv()
===========changed ref 2===========
# module: backend.tests
+ load_dotenv(find_dotenv(), verbose=True)
- load_dotenv(dotenv_path="")
===========changed ref 3===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 5===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 6===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 7===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 8===========
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
if secrets is None:
return (False, []) # type: ignore
+ tokens = SecretModel.model_validate(secrets).access_tokens
- tokens = SecretModel.parse_obj(secrets).access_tokens
return (True, tokens) # type: ignore
===========changed ref 9===========
+ # module: backend.delete_old_data
+ def main():
+ # Replace 'your_date_field' with the actual name of your date field
+ cutoff_date = datetime(2022, 12, 31)
+
+ count = await count_old_rows(cutoff_date)
+ if count == 0:
+ print("No rows to delete.")
+ return
+
+ print(f"Found {count} rows to delete.")
+ print()
+
+ confirmation = input("Are you sure you want to delete these rows? (yes/no): ")
+ if confirmation.lower() != "yes":
+ print("Operation canceled.")
+ return
+
+ print()
+ await delete_old_rows(cutoff_date)
+
===========changed ref 10===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
days: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
day = datetime.fromisoformat(item.date).weekday()
days[day]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
days[day]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(7):
v = days[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return DayData(days=out)
===========changed ref 11===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_month_data(data: UserPackage) -> MonthData:
months: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
month = datetime.fromisoformat(item.date).month - 1
months[month]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
months[month]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(12):
v = months[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return MonthData(months=out)
===========changed ref 12===========
# module: backend.src.data.github.graphql.repo
def get_repo(
owner: str,
repo: str,
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> Optional[RawRepo]:
"""
Gets all repository data from graphql
:param access_token: GitHub access token
:param owner: GitHub owner
:param repo: GitHub repository
:return: RawRepo object or None if repo not present
"""
query = {
"variables": {"owner": owner, "repo": repo},
"query": """
query getRepo($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
isPrivate,
forkCount,
stargazerCount,
languages(first: 10){
totalCount,
totalSize,
edges{
node {
name,
color,
},
size,
},
},
}
}
""",
}
try:
raw_repo = get_template(query, access_token)["data"]["repository"]
+ return RawRepo.model_validate(raw_repo)
- return RawRepo.parse_obj(raw_repo)
except Exception as e:
if catch_errors:
return None
raise e
|
backend.src.models.user.contribs/RepoContributionStats.__add__
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<0>:<add> new_self = ContributionStats(**self.model_dump())
<del> new_self = ContributionStats(**self.dict())
<1>:<add> new_other = ContributionStats(**other.model_dump())
<del> new_other = ContributionStats(**other.dict())
<2>:<add> combined = (new_self + new_other).model_dump()
<del> combined = (new_self + new_other).dict()
|
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
def __add__( # type: ignore
self, other: "RepoContributionStats"
) -> "RepoContributionStats":
<0> new_self = ContributionStats(**self.dict())
<1> new_other = ContributionStats(**other.dict())
<2> combined = (new_self + new_other).dict()
<3> combined["private"] = self.private
<4> return RepoContributionStats(**combined)
<5>
|
===========unchanged ref 0===========
at: backend.src.models.user.contribs.ContributionStats
__add__(self, other: "ContributionStats") -> "ContributionStats"
at: backend.src.models.user.contribs.RepoContributionStats
private: bool
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
===========changed ref 0===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
@classmethod
def decompress(cls, data: List[Any]) -> "RepoContributionStats":
+ contribs = super().decompress(data).model_dump()
- contribs = super().decompress(data).dict()
contribs["private"] = data[0][7]
return RepoContributionStats(**contribs)
===========changed ref 1===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 2===========
# module: backend.src.main
+ load_dotenv(find_dotenv())
- load_dotenv()
===========changed ref 3===========
# module: backend.tests
+ load_dotenv(find_dotenv(), verbose=True)
- load_dotenv(dotenv_path="")
===========changed ref 4===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 5===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 6===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 7===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 8===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 9===========
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
if secrets is None:
return (False, []) # type: ignore
+ tokens = SecretModel.model_validate(secrets).access_tokens
- tokens = SecretModel.parse_obj(secrets).access_tokens
return (True, tokens) # type: ignore
===========changed ref 10===========
+ # module: backend.delete_old_data
+ def main():
+ # Replace 'your_date_field' with the actual name of your date field
+ cutoff_date = datetime(2022, 12, 31)
+
+ count = await count_old_rows(cutoff_date)
+ if count == 0:
+ print("No rows to delete.")
+ return
+
+ print(f"Found {count} rows to delete.")
+ print()
+
+ confirmation = input("Are you sure you want to delete these rows? (yes/no): ")
+ if confirmation.lower() != "yes":
+ print("Operation canceled.")
+ return
+
+ print()
+ await delete_old_rows(cutoff_date)
+
===========changed ref 11===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
days: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
day = datetime.fromisoformat(item.date).weekday()
days[day]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
days[day]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(7):
v = days[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return DayData(days=out)
===========changed ref 12===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_month_data(data: UserPackage) -> MonthData:
months: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
month = datetime.fromisoformat(item.date).month - 1
months[month]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
months[month]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(12):
v = months[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return MonthData(months=out)
|
backend.src.models.user.contribs/UserContributions.trim
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<9>:<add> raw_new_repo_stats = _new_repo_stats.model_dump()
<del> raw_new_repo_stats = _new_repo_stats.dict()
|
# module: backend.src.models.user.contribs
class UserContributions(BaseModel):
def trim(self, start: date, end: date) -> "UserContributions":
<0> new_total, new_total_stats = self.trim_contribs(self.total, start, end)
<1> new_public, new_public_stats = self.trim_contribs(self.public, start, end)
<2>
<3> new_repos_dict: Dict[str, List[ContributionDay]] = {}
<4> new_repo_stats_dict: Dict[str, RepoContributionStats] = {}
<5> for repo_name, repo in self.repos.items():
<6> new_repo_total, _new_repo_stats = self.trim_contribs(repo, start, end)
<7> if len(new_repo_total) > 0:
<8> new_repos_dict[repo_name] = new_repo_total
<9> raw_new_repo_stats = _new_repo_stats.dict()
<10> raw_new_repo_stats["private"] = self.repo_stats[repo_name].private
<11> new_repo_stats = RepoContributionStats(**raw_new_repo_stats)
<12> new_repo_stats_dict[repo_name] = new_repo_stats
<13>
<14> return UserContributions(
<15> total_stats=new_total_stats,
<16> public_stats=new_public_stats,
<17> total=new_total,
<18> public=new_public,
<19> repo_stats=new_repo_stats_dict,
<20> repos=new_repos_dict,
<21> )
<22>
|
===========unchanged ref 0===========
at: backend.src.models.user.contribs.RepoContributionStats
private: bool
at: backend.src.models.user.contribs.UserContributions
total_stats: ContributionStats
public_stats: ContributionStats
total: List[ContributionDay]
public: List[ContributionDay]
repo_stats: Dict[str, RepoContributionStats]
repos: Dict[str, List[ContributionDay]]
trim_contribs(contribs: List[ContributionDay], start_date: date, end_date: date) -> Tuple[List[ContributionDay], ContributionStats]
at: datetime
date()
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
@classmethod
def decompress(cls, data: List[Any]) -> "RepoContributionStats":
+ contribs = super().decompress(data).model_dump()
- contribs = super().decompress(data).dict()
contribs["private"] = data[0][7]
return RepoContributionStats(**contribs)
===========changed ref 1===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
def __add__( # type: ignore
self, other: "RepoContributionStats"
) -> "RepoContributionStats":
+ new_self = ContributionStats(**self.model_dump())
- new_self = ContributionStats(**self.dict())
+ new_other = ContributionStats(**other.model_dump())
- new_other = ContributionStats(**other.dict())
+ combined = (new_self + new_other).model_dump()
- combined = (new_self + new_other).dict()
combined["private"] = self.private
return RepoContributionStats(**combined)
===========changed ref 2===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 3===========
# module: backend.src.main
+ load_dotenv(find_dotenv())
- load_dotenv()
===========changed ref 4===========
# module: backend.tests
+ load_dotenv(find_dotenv(), verbose=True)
- load_dotenv(dotenv_path="")
===========changed ref 5===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 6===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 7===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 8===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 9===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 10===========
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
if secrets is None:
return (False, []) # type: ignore
+ tokens = SecretModel.model_validate(secrets).access_tokens
- tokens = SecretModel.parse_obj(secrets).access_tokens
return (True, tokens) # type: ignore
===========changed ref 11===========
+ # module: backend.delete_old_data
+ def main():
+ # Replace 'your_date_field' with the actual name of your date field
+ cutoff_date = datetime(2022, 12, 31)
+
+ count = await count_old_rows(cutoff_date)
+ if count == 0:
+ print("No rows to delete.")
+ return
+
+ print(f"Found {count} rows to delete.")
+ print()
+
+ confirmation = input("Are you sure you want to delete these rows? (yes/no): ")
+ if confirmation.lower() != "yes":
+ print("Operation canceled.")
+ return
+
+ print()
+ await delete_old_rows(cutoff_date)
+
===========changed ref 12===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
days: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
day = datetime.fromisoformat(item.date).weekday()
days[day]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
days[day]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(7):
v = days[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return DayData(days=out)
===========changed ref 13===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_month_data(data: UserPackage) -> MonthData:
months: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
month = datetime.fromisoformat(item.date).month - 1
months[month]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
months[month]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(12):
v = months[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return MonthData(months=out)
|
backend.src.subscriber.aggregation.wrapped.numeric/get_contrib_stats
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<0>:<add> return ContribStats.model_validate(
<del> return ContribStats.parse_obj(
|
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_contrib_stats(data: UserPackage) -> ContribStats:
<0> return ContribStats.parse_obj(
<1> {
<2> "contribs": data.contribs.total_stats.contribs_count,
<3> "commits": data.contribs.total_stats.commits_count,
<4> "issues": data.contribs.total_stats.issues_count,
<5> "prs": data.contribs.total_stats.prs_count,
<6> "reviews": data.contribs.total_stats.reviews_count,
<7> "other": data.contribs.total_stats.other_count,
<8> }
<9> )
<10>
|
===========unchanged ref 0===========
at: src.models.user.contribs.ContributionStats
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
public_stats: ContributionStats
total: List[ContributionDay]
public: List[ContributionDay]
repo_stats: Dict[str, RepoContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
===========changed ref 0===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 1===========
# module: backend.src.main
+ load_dotenv(find_dotenv())
- load_dotenv()
===========changed ref 2===========
# module: backend.tests
+ load_dotenv(find_dotenv(), verbose=True)
- load_dotenv(dotenv_path="")
===========changed ref 3===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 5===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 6===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 7===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 8===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
@classmethod
def decompress(cls, data: List[Any]) -> "RepoContributionStats":
+ contribs = super().decompress(data).model_dump()
- contribs = super().decompress(data).dict()
contribs["private"] = data[0][7]
return RepoContributionStats(**contribs)
===========changed ref 9===========
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
if secrets is None:
return (False, []) # type: ignore
+ tokens = SecretModel.model_validate(secrets).access_tokens
- tokens = SecretModel.parse_obj(secrets).access_tokens
return (True, tokens) # type: ignore
===========changed ref 10===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
def __add__( # type: ignore
self, other: "RepoContributionStats"
) -> "RepoContributionStats":
+ new_self = ContributionStats(**self.model_dump())
- new_self = ContributionStats(**self.dict())
+ new_other = ContributionStats(**other.model_dump())
- new_other = ContributionStats(**other.dict())
+ combined = (new_self + new_other).model_dump()
- combined = (new_self + new_other).dict()
combined["private"] = self.private
return RepoContributionStats(**combined)
===========changed ref 11===========
+ # module: backend.delete_old_data
+ def main():
+ # Replace 'your_date_field' with the actual name of your date field
+ cutoff_date = datetime(2022, 12, 31)
+
+ count = await count_old_rows(cutoff_date)
+ if count == 0:
+ print("No rows to delete.")
+ return
+
+ print(f"Found {count} rows to delete.")
+ print()
+
+ confirmation = input("Are you sure you want to delete these rows? (yes/no): ")
+ if confirmation.lower() != "yes":
+ print("Operation canceled.")
+ return
+
+ print()
+ await delete_old_rows(cutoff_date)
+
===========changed ref 12===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
days: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
day = datetime.fromisoformat(item.date).weekday()
days[day]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
days[day]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(7):
v = days[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return DayData(days=out)
===========changed ref 13===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_month_data(data: UserPackage) -> MonthData:
months: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
month = datetime.fromisoformat(item.date).month - 1
months[month]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
months[month]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(12):
v = months[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return MonthData(months=out)
|
backend.src.subscriber.aggregation.wrapped.numeric/get_misc_stats
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_misc_stats(data: UserPackage, year: int) -> MiscStats:
<0> weekdays: Dict[int, int] = defaultdict(int)
<1> yeardays, distinct_days, total_contribs = {}, 0, 0
<2> for item in data.contribs.total:
<3> count = item.stats.contribs_count
<4> weekdays[item.weekday] += count
<5> total_contribs += item.stats.contribs_count
<6> if count > 0:
<7> date = datetime.fromisoformat(item.date)
<8> yeardays[date.timetuple().tm_yday - 1] = 1
<9> distinct_days += 1
<10> curr, best, best_dates = 0, 0, (1, 1)
<11> for i in range(366):
<12> curr = curr + 1 if i in yeardays else 0
<13> if curr > best:
<14> best = curr
<15> best_dates = (i - curr + 2, i + 1)
<16> longest_streak = max(best, curr)
<17> longest_streak_days = (
<18> best_dates[0],
<19> best_dates[1],
<20> datetime.fromordinal(max(1, best_dates[0])).strftime("%b %d"),
<21> datetime.fromordinal(max(1, best_dates[1])).strftime("%b %d"),
<22> )
<23> curr, best, best_dates = 0, 0, (1, 1)
<24> days = (datetime.now() - datetime(year, 1, 1)).days
<25> for i in range(min(days, 365)):
<26> curr = 0 if i in yeardays else curr + 1
<27> if curr > best:
<28> best = curr
<29> best_dates = (i - curr + 2, i + 1)
<30> longest_gap = max(best, curr)
<31> longest_gap_days = (
<32> best_dates[0],
<33> best_dates[1</s>
|
===========below chunk 0===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_misc_stats(data: UserPackage, year: int) -> MiscStats:
# offset: 1
datetime.fromordinal(max(1, best_dates[0])).strftime("%b %d"),
datetime.fromordinal(max(1, best_dates[1])).strftime("%b %d"),
)
weekend_percent = (weekdays[0] + weekdays[6]) / max(1, total_contribs)
best_day_count, best_day_date, best_day_index = 0, None, None
if len(data.contribs.total) > 0:
best_day = max(data.contribs.total, key=lambda x: x.stats.contribs_count)
best_day_index = datetime.fromisoformat(best_day.date).timetuple().tm_yday
best_day_count = best_day.stats.contribs_count
best_day_date = best_day.date
return MiscStats.parse_obj(
{
"total_days": distinct_days,
"longest_streak": longest_streak,
"longest_streak_days": longest_streak_days,
"longest_gap": longest_gap,
"longest_gap_days": longest_gap_days,
"weekend_percent": round(100 * weekend_percent),
"best_day_count": best_day_count,
"best_day_date": best_day_date,
"best_day_index": best_day_index,
}
)
===========unchanged ref 0===========
at: collections
defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]])
defaultdict(default_factory: Optional[Callable[[], _VT]])
defaultdict(**kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT])
at: datetime
datetime()
at: datetime.date
__slots__ = '_year', '_month', '_day', '_hashcode'
fromordinal(n: int) -> _S
strftime(fmt: _Text) -> str
__str__ = isoformat
__radd__ = __add__
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
fromisoformat(date_string: str) -> _S
timetuple() -> struct_time
__radd__ = __add__
at: datetime.timedelta
__slots__ = '_days', '_seconds', '_microseconds', '_hashcode'
__radd__ = __add__
__rmul__ = __mul__
at: src.models.user.contribs.ContributionDay
date: str
weekday: int
stats: ContributionStats
lists: ContributionLists
at: src.models.user.contribs.ContributionStats
contribs_count: int
at: src.models.user.contribs.UserContributions
total: List[ContributionDay]
===========unchanged ref 1===========
at: src.models.user.main.UserPackage
contribs: UserContributions
at: time._struct_time
tm_year: int
tm_mon: int
tm_mday: int
tm_hour: int
tm_min: int
tm_sec: int
tm_wday: int
tm_yday: int
tm_isdst: int
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_contrib_stats(data: UserPackage) -> ContribStats:
+ return ContribStats.model_validate(
- return ContribStats.parse_obj(
{
"contribs": data.contribs.total_stats.contribs_count,
"commits": data.contribs.total_stats.commits_count,
"issues": data.contribs.total_stats.issues_count,
"prs": data.contribs.total_stats.prs_count,
"reviews": data.contribs.total_stats.reviews_count,
"other": data.contribs.total_stats.other_count,
}
)
===========changed ref 1===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 2===========
# module: backend.src.main
+ load_dotenv(find_dotenv())
- load_dotenv()
===========changed ref 3===========
# module: backend.tests
+ load_dotenv(find_dotenv(), verbose=True)
- load_dotenv(dotenv_path="")
===========changed ref 4===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 5===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 6===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 7===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 8===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 9===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
@classmethod
def decompress(cls, data: List[Any]) -> "RepoContributionStats":
+ contribs = super().decompress(data).model_dump()
- contribs = super().decompress(data).dict()
contribs["private"] = data[0][7]
return RepoContributionStats(**contribs)
|
|
backend.src.subscriber.aggregation.wrapped.numeric/get_loc_stats
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<1>:<add> return LOCStats.model_validate(
<del> return LOCStats.parse_obj(
|
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_loc_stats(data: UserPackage) -> LOCStats:
<0> dataset = data.contribs.total_stats.languages.values()
<1> return LOCStats.parse_obj(
<2> {
<3> "loc_additions": format_loc_number(sum(x.additions for x in dataset)),
<4> "loc_deletions": format_loc_number(sum(x.deletions for x in dataset)),
<5> "loc_changed": format_loc_number(
<6> sum(x.additions + x.deletions for x in dataset)
<7> ),
<8> "loc_added": format_loc_number(
<9> sum(x.additions - x.deletions for x in dataset)
<10> ),
<11> "loc_additions_per_commit": round(
<12> (
<13> sum(x.additions for x in dataset)
<14> / max(1, data.contribs.total_stats.commits_count)
<15> )
<16> ),
<17> "loc_deletions_per_commit": round(
<18> (
<19> sum(x.deletions for x in dataset)
<20> / max(1, data.contribs.total_stats.commits_count)
<21> )
<22> ),
<23> "loc_changed_per_day": round(
<24> sum(x.additions + x.deletions for x in dataset) / 365
<25> ),
<26> }
<27> )
<28>
|
===========unchanged ref 0===========
at: backend.src.subscriber.aggregation.wrapped.numeric
format_loc_number(number: int) -> str
at: src.models.user.contribs.ContributionStats
commits_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.Language
color: Optional[str]
additions: int
deletions: int
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
at: src.models.user.main.UserPackage
contribs: UserContributions
===========changed ref 0===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_contrib_stats(data: UserPackage) -> ContribStats:
+ return ContribStats.model_validate(
- return ContribStats.parse_obj(
{
"contribs": data.contribs.total_stats.contribs_count,
"commits": data.contribs.total_stats.commits_count,
"issues": data.contribs.total_stats.issues_count,
"prs": data.contribs.total_stats.prs_count,
"reviews": data.contribs.total_stats.reviews_count,
"other": data.contribs.total_stats.other_count,
}
)
===========changed ref 1===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_misc_stats(data: UserPackage, year: int) -> MiscStats:
weekdays: Dict[int, int] = defaultdict(int)
yeardays, distinct_days, total_contribs = {}, 0, 0
for item in data.contribs.total:
count = item.stats.contribs_count
weekdays[item.weekday] += count
total_contribs += item.stats.contribs_count
if count > 0:
date = datetime.fromisoformat(item.date)
yeardays[date.timetuple().tm_yday - 1] = 1
distinct_days += 1
curr, best, best_dates = 0, 0, (1, 1)
for i in range(366):
curr = curr + 1 if i in yeardays else 0
if curr > best:
best = curr
best_dates = (i - curr + 2, i + 1)
longest_streak = max(best, curr)
longest_streak_days = (
best_dates[0],
best_dates[1],
datetime.fromordinal(max(1, best_dates[0])).strftime("%b %d"),
datetime.fromordinal(max(1, best_dates[1])).strftime("%b %d"),
)
curr, best, best_dates = 0, 0, (1, 1)
days = (datetime.now() - datetime(year, 1, 1)).days
for i in range(min(days, 365)):
curr = 0 if i in yeardays else curr + 1
if curr > best:
best = curr
best_dates = (i - curr + 2, i + 1)
longest_gap = max(best, curr)
longest_gap_days = (
best_dates[0],
best_dates[1],
datetime.fromordinal(max(1, best_dates[0])).strftime("%b %d"),
datetime.fromord</s>
===========changed ref 2===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_misc_stats(data: UserPackage, year: int) -> MiscStats:
# offset: 1
<s>.fromordinal(max(1, best_dates[0])).strftime("%b %d"),
datetime.fromordinal(max(1, best_dates[1])).strftime("%b %d"),
)
weekend_percent = (weekdays[0] + weekdays[6]) / max(1, total_contribs)
best_day_count, best_day_date, best_day_index = 0, None, None
if len(data.contribs.total) > 0:
best_day = max(data.contribs.total, key=lambda x: x.stats.contribs_count)
best_day_index = datetime.fromisoformat(best_day.date).timetuple().tm_yday
best_day_count = best_day.stats.contribs_count
best_day_date = best_day.date
+ return MiscStats.model_validate(
- return MiscStats.parse_obj(
{
"total_days": distinct_days,
"longest_streak": longest_streak,
"longest_streak_days": longest_streak_days,
"longest_gap": longest_gap,
"longest_gap_days": longest_gap_days,
"weekend_percent": round(100 * weekend_percent),
"best_day_count": best_day_count,
"best_day_date": best_day_date,
"best_day_index": best_day_index,
}
)
===========changed ref 3===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 4===========
# module: backend.src.main
+ load_dotenv(find_dotenv())
- load_dotenv()
===========changed ref 5===========
# module: backend.tests
+ load_dotenv(find_dotenv(), verbose=True)
- load_dotenv(dotenv_path="")
===========changed ref 6===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 7===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 8===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 9===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 10===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 11===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
@classmethod
def decompress(cls, data: List[Any]) -> "RepoContributionStats":
+ contribs = super().decompress(data).model_dump()
- contribs = super().decompress(data).dict()
contribs["private"] = data[0][7]
return RepoContributionStats(**contribs)
|
backend.src.subscriber.aggregation.wrapped.numeric/get_numeric_data
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<0>:<add> return NumericData.model_validate(
<del> return NumericData.parse_obj(
|
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_numeric_data(data: UserPackage, year: int) -> NumericData:
<0> return NumericData.parse_obj(
<1> {
<2> "contribs": get_contrib_stats(data),
<3> "misc": get_misc_stats(data, year),
<4> "loc": get_loc_stats(data),
<5> }
<6> )
<7>
|
===========unchanged ref 0===========
at: backend.src.subscriber.aggregation.wrapped.numeric
get_contrib_stats(data: UserPackage) -> ContribStats
get_misc_stats(data: UserPackage, year: int) -> MiscStats
get_loc_stats(data: UserPackage) -> LOCStats
===========changed ref 0===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_contrib_stats(data: UserPackage) -> ContribStats:
+ return ContribStats.model_validate(
- return ContribStats.parse_obj(
{
"contribs": data.contribs.total_stats.contribs_count,
"commits": data.contribs.total_stats.commits_count,
"issues": data.contribs.total_stats.issues_count,
"prs": data.contribs.total_stats.prs_count,
"reviews": data.contribs.total_stats.reviews_count,
"other": data.contribs.total_stats.other_count,
}
)
===========changed ref 1===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_loc_stats(data: UserPackage) -> LOCStats:
dataset = data.contribs.total_stats.languages.values()
+ return LOCStats.model_validate(
- return LOCStats.parse_obj(
{
"loc_additions": format_loc_number(sum(x.additions for x in dataset)),
"loc_deletions": format_loc_number(sum(x.deletions for x in dataset)),
"loc_changed": format_loc_number(
sum(x.additions + x.deletions for x in dataset)
),
"loc_added": format_loc_number(
sum(x.additions - x.deletions for x in dataset)
),
"loc_additions_per_commit": round(
(
sum(x.additions for x in dataset)
/ max(1, data.contribs.total_stats.commits_count)
)
),
"loc_deletions_per_commit": round(
(
sum(x.deletions for x in dataset)
/ max(1, data.contribs.total_stats.commits_count)
)
),
"loc_changed_per_day": round(
sum(x.additions + x.deletions for x in dataset) / 365
),
}
)
===========changed ref 2===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_misc_stats(data: UserPackage, year: int) -> MiscStats:
weekdays: Dict[int, int] = defaultdict(int)
yeardays, distinct_days, total_contribs = {}, 0, 0
for item in data.contribs.total:
count = item.stats.contribs_count
weekdays[item.weekday] += count
total_contribs += item.stats.contribs_count
if count > 0:
date = datetime.fromisoformat(item.date)
yeardays[date.timetuple().tm_yday - 1] = 1
distinct_days += 1
curr, best, best_dates = 0, 0, (1, 1)
for i in range(366):
curr = curr + 1 if i in yeardays else 0
if curr > best:
best = curr
best_dates = (i - curr + 2, i + 1)
longest_streak = max(best, curr)
longest_streak_days = (
best_dates[0],
best_dates[1],
datetime.fromordinal(max(1, best_dates[0])).strftime("%b %d"),
datetime.fromordinal(max(1, best_dates[1])).strftime("%b %d"),
)
curr, best, best_dates = 0, 0, (1, 1)
days = (datetime.now() - datetime(year, 1, 1)).days
for i in range(min(days, 365)):
curr = 0 if i in yeardays else curr + 1
if curr > best:
best = curr
best_dates = (i - curr + 2, i + 1)
longest_gap = max(best, curr)
longest_gap_days = (
best_dates[0],
best_dates[1],
datetime.fromordinal(max(1, best_dates[0])).strftime("%b %d"),
datetime.fromord</s>
===========changed ref 3===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_misc_stats(data: UserPackage, year: int) -> MiscStats:
# offset: 1
<s>.fromordinal(max(1, best_dates[0])).strftime("%b %d"),
datetime.fromordinal(max(1, best_dates[1])).strftime("%b %d"),
)
weekend_percent = (weekdays[0] + weekdays[6]) / max(1, total_contribs)
best_day_count, best_day_date, best_day_index = 0, None, None
if len(data.contribs.total) > 0:
best_day = max(data.contribs.total, key=lambda x: x.stats.contribs_count)
best_day_index = datetime.fromisoformat(best_day.date).timetuple().tm_yday
best_day_count = best_day.stats.contribs_count
best_day_date = best_day.date
+ return MiscStats.model_validate(
- return MiscStats.parse_obj(
{
"total_days": distinct_days,
"longest_streak": longest_streak,
"longest_streak_days": longest_streak_days,
"longest_gap": longest_gap,
"longest_gap_days": longest_gap_days,
"weekend_percent": round(100 * weekend_percent),
"best_day_count": best_day_count,
"best_day_date": best_day_date,
"best_day_index": best_day_index,
}
)
===========changed ref 4===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 5===========
# module: backend.src.main
+ load_dotenv(find_dotenv())
- load_dotenv()
===========changed ref 6===========
# module: backend.tests
+ load_dotenv(find_dotenv(), verbose=True)
- load_dotenv(dotenv_path="")
===========changed ref 7===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 8===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 9===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 10===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
|
backend.src.subscriber.aggregation.wrapped.repos/get_repo_data
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<17>:<add> repo_objs.append(RepoDatum.model_validate(repo_data))
<del> repo_objs.append(RepoDatum.parse_obj(repo_data))
<28>:<add> repo_objs.append(RepoDatum.model_validate(repo_data))
<del> repo_objs.append(RepoDatum.parse_obj(repo_data))
<32>:<add> return RepoData.model_validate(out)
<del> return RepoData.parse_obj(out)
|
# module: backend.src.subscriber.aggregation.wrapped.repos
def get_repo_data(data: UserPackage) -> RepoData:
<0> out = {}
<1> for m in ["changed", "added"]:
<2> repos = sorted(
<3> data.contribs.repo_stats.items(),
<4> key=lambda x: _count_repo_loc(x[1], m),
<5> reverse=True,
<6> )
<7> repo_objs: List[RepoDatum] = []
<8>
<9> # first five repositories
<10> for i, (k, v) in enumerate(list(repos)[:5]):
<11> repo_data = {
<12> "id": i,
<13> "label": "private/repository" if v.private else k,
<14> "value": _count_repo_loc(v, m),
<15> "formatted_value": format_number(_count_repo_loc(v, m)),
<16> }
<17> repo_objs.append(RepoDatum.parse_obj(repo_data))
<18>
<19> # remaining repositories
<20> total_count = sum(_count_repo_loc(v, m) for _, v in list(repos)[5:])
<21> repo_data = {
<22> "id": -1,
<23> "label": "other",
<24> "value": total_count,
<25> "formatted_value": format_number(total_count),
<26> }
<27> if total_count > 100:
<28> repo_objs.append(RepoDatum.parse_obj(repo_data))
<29>
<30> out[f"repos_{m}"] = repo_objs
<31>
<32> return RepoData.parse_obj(out)
<33>
|
===========unchanged ref 0===========
at: backend.src.subscriber.aggregation.wrapped.repos
_count_repo_loc(x: RepoContributionStats, metric: str) -> int
at: src.models.user.contribs.RepoContributionStats
private: bool
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
public_stats: ContributionStats
total: List[ContributionDay]
public: List[ContributionDay]
repo_stats: Dict[str, RepoContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
at: src.utils.utils
format_number(num: int) -> str
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 1===========
# module: backend.src.main
+ load_dotenv(find_dotenv())
- load_dotenv()
===========changed ref 2===========
# module: backend.tests
+ load_dotenv(find_dotenv(), verbose=True)
- load_dotenv(dotenv_path="")
===========changed ref 3===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 5===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 6===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 7===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 8===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
@classmethod
def decompress(cls, data: List[Any]) -> "RepoContributionStats":
+ contribs = super().decompress(data).model_dump()
- contribs = super().decompress(data).dict()
contribs["private"] = data[0][7]
return RepoContributionStats(**contribs)
===========changed ref 9===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_numeric_data(data: UserPackage, year: int) -> NumericData:
+ return NumericData.model_validate(
- return NumericData.parse_obj(
{
"contribs": get_contrib_stats(data),
"misc": get_misc_stats(data, year),
"loc": get_loc_stats(data),
}
)
===========changed ref 10===========
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
if secrets is None:
return (False, []) # type: ignore
+ tokens = SecretModel.model_validate(secrets).access_tokens
- tokens = SecretModel.parse_obj(secrets).access_tokens
return (True, tokens) # type: ignore
===========changed ref 11===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
def __add__( # type: ignore
self, other: "RepoContributionStats"
) -> "RepoContributionStats":
+ new_self = ContributionStats(**self.model_dump())
- new_self = ContributionStats(**self.dict())
+ new_other = ContributionStats(**other.model_dump())
- new_other = ContributionStats(**other.dict())
+ combined = (new_self + new_other).model_dump()
- combined = (new_self + new_other).dict()
combined["private"] = self.private
return RepoContributionStats(**combined)
===========changed ref 12===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_contrib_stats(data: UserPackage) -> ContribStats:
+ return ContribStats.model_validate(
- return ContribStats.parse_obj(
{
"contribs": data.contribs.total_stats.contribs_count,
"commits": data.contribs.total_stats.commits_count,
"issues": data.contribs.total_stats.issues_count,
"prs": data.contribs.total_stats.prs_count,
"reviews": data.contribs.total_stats.reviews_count,
"other": data.contribs.total_stats.other_count,
}
)
===========changed ref 13===========
+ # module: backend.delete_old_data
+ def main():
+ # Replace 'your_date_field' with the actual name of your date field
+ cutoff_date = datetime(2022, 12, 31)
+
+ count = await count_old_rows(cutoff_date)
+ if count == 0:
+ print("No rows to delete.")
+ return
+
+ print(f"Found {count} rows to delete.")
+ print()
+
+ confirmation = input("Are you sure you want to delete these rows? (yes/no): ")
+ if confirmation.lower() != "yes":
+ print("Operation canceled.")
+ return
+
+ print()
+ await delete_old_rows(cutoff_date)
+
|
backend.src.subscriber.aggregation.user.contributions/get_contributions
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<26>:<add> for obj, stats_obj in [(total, total_stats), (public, public_stats)]:
<del> for (obj, stats_obj) in [(total, total_stats), (public, public_stats)]:
|
# module: backend.src.subscriber.aggregation.user.contributions
def get_contributions(
user_id: str,
start_date: date,
end_date: date,
timezone_str: str = "US/Eastern",
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> UserContributions:
<0> tz = pytz.timezone(timezone_str)
<1>
<2> start_month = date_to_datetime(start_date)
<3> end_month = date_to_datetime(end_date, hour=23, minute=59, second=59)
<4> (
<5> calendar,
<6> contrib_events,
<7> repo_infos,
<8> commit_times_dict,
<9> commit_languages_dict,
<10> ) = await get_cleaned_contributions(
<11> user_id, start_month, end_month, access_token, catch_errors
<12> )
<13>
<14> total_stats = StatsContainer()
<15> public_stats = StatsContainer()
<16> total: Dict[str, DateContainer] = defaultdict(DateContainer)
<17> public: Dict[str, DateContainer] = defaultdict(DateContainer)
<18> repo_stats: Dict[str, StatsContainer] = defaultdict(StatsContainer)
<19> repositories: Dict[str, Dict[str, DateContainer]] = defaultdict(
<20> lambda: defaultdict(DateContainer)
<21> )
<22>
<23> for week in calendar.weeks:
<24> for day in week.contribution_days:
<25> day_str = str(day.date)
<26> for (obj, stats_obj) in [(total, total_stats), (public, public_stats)]:
<27> obj[day_str].date = day.date.isoformat()
<28> obj[day_str].weekday = day.weekday
<29> obj[day_str].stats.contribs = day.count
<30> obj[day_str].stats.other = day.count
<31> stats_obj.contribs += day.count
<32> stats_obj.other += day.count
<33>
<34> def update_</s>
|
===========below chunk 0===========
# module: backend.src.subscriber.aggregation.user.contributions
def get_contributions(
user_id: str,
start_date: date,
end_date: date,
timezone_str: str = "US/Eastern",
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> UserContributions:
# offset: 1
date_str: str, repo: str, event: str, count: int, times: List[datetime]
):
# update global counts for this event
total[date_str].add_stat(event, count, times)
total_stats.add_stat(event, count)
if not repo_infos[repo].is_private:
public[date_str].add_stat(event, count, times)
public_stats.add_stat(event, count)
repositories[repo][date_str].add_stat(event, count, times, add=True)
repo_stats[repo].add_stat(event, count, add=True)
def update_langs(date_str: str, repo: str, langs: CommitLanguages):
stores = [
total[date_str].stats.languages,
total_stats.languages,
repositories[repo][date_str].stats.languages,
repo_stats[repo].languages,
]
if not repo_infos[repo].is_private:
stores.append(public[date_str].stats.languages)
stores.append(public_stats.languages)
for store in stores:
store += langs
for repo, repo_events in contrib_events.items():
for (label, events) in [
("commit", repo_events.commits),
("issue", repo_events.issues),
("pr", repo_events.prs),
("review", repo_events.reviews),
("repo", repo_events.repos),
]:
events = sorted(events, key=lambda x: x.occurred_at)
for event in events:
datetime_obj = event.occur</s>
===========below chunk 1===========
# module: backend.src.subscriber.aggregation.user.contributions
def get_contributions(
user_id: str,
start_date: date,
end_date: date,
timezone_str: str = "US/Eastern",
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> UserContributions:
# offset: 2
<s>events, key=lambda x: x.occurred_at)
for event in events:
datetime_obj = event.occurred_at.astimezone(tz)
date_str = datetime_obj.date().isoformat()
repositories[repo][date_str].date = date_str
if isinstance(event, RawEventsCommit):
count = 0
commit_times: List[datetime] = []
while len(commit_languages_dict[repo]) > 0 and count < event.count:
commit_times.append(commit_times_dict[repo].pop(0))
langs = commit_languages_dict[repo].pop(0)
update_langs(date_str, repo, langs)
count += 1
update_stats(date_str, repo, "commit", event.count, commit_times)
else:
update_stats(date_str, repo, label, 1, [datetime_obj])
total_stats_dict = total_stats.to_dict()
public_stats_dict = public_stats.to_dict()
repo_stats_dict = {name: stats.to_dict() for name, stats in repo_stats.items()}
for repo in repo_stats:
repo_stats_dict[repo]["private"] = repo_infos[repo].is_private
total_list = [v.to_dict() for v in total.values() if v.stats.contribs > 0]
public_list = [v.to_dict() for v in public.values() if v.stats.contribs > 0]
</s>
===========below chunk 2===========
# module: backend.src.subscriber.aggregation.user.contributions
def get_contributions(
user_id: str,
start_date: date,
end_date: date,
timezone_str: str = "US/Eastern",
access_token: Optional[str] = None,
catch_errors: bool = False,
) -> UserContributions:
# offset: 3
<s>list = {
name: [v.to_dict() for v in repo.values()]
for name, repo in repositories.items()
}
output = UserContributions.parse_obj(
{
"total_stats": total_stats_dict,
"public_stats": public_stats_dict,
"total": total_list,
"public": public_list,
"repo_stats": repo_stats_dict,
"repos": repositories_list,
}
)
return output
===========changed ref 0===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 1===========
# module: backend.src.main
+ load_dotenv(find_dotenv())
- load_dotenv()
===========changed ref 2===========
# module: backend.tests
+ load_dotenv(find_dotenv(), verbose=True)
- load_dotenv(dotenv_path="")
===========changed ref 3===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 5===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 6===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 7===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 8===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
@classmethod
def decompress(cls, data: List[Any]) -> "RepoContributionStats":
+ contribs = super().decompress(data).model_dump()
- contribs = super().decompress(data).dict()
contribs["private"] = data[0][7]
return RepoContributionStats(**contribs)
===========changed ref 9===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_numeric_data(data: UserPackage, year: int) -> NumericData:
+ return NumericData.model_validate(
- return NumericData.parse_obj(
{
"contribs": get_contrib_stats(data),
"misc": get_misc_stats(data, year),
"loc": get_loc_stats(data),
}
)
|
backend.src.subscriber.aggregation.wrapped.calendar/get_calendar_data
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
# module: backend.src.subscriber.aggregation.wrapped.calendar
def get_calendar_data(data: UserPackage, year: int) -> CalendarData:
<0> top_langs = [
<1> x[0]
<2> for x in sorted(
<3> data.contribs.total_stats.languages.items(),
<4> key=lambda x: x[1].additions + x[1].deletions,
<5> reverse=True,
<6> )[:5]
<7> ]
<8>
<9> total_out: List[CalendarDayDatum] = []
<10> items_dict = {item.date: item for item in data.contribs.total}
<11> for i in range(365):
<12> date = (datetime(year, 1, 1) + timedelta(days=i - 1)).strftime("%Y-%m-%d")
<13> item = items_dict.get(date)
<14> out: Dict[str, Any] = {
<15> "day": date,
<16> "contribs": 0,
<17> "commits": 0,
<18> "issues": 0,
<19> "prs": 0,
<20> "reviews": 0,
<21> "loc_added": 0,
<22> "loc_changed": 0,
<23> "top_langs": {k: {"loc_added": 0, "loc_changed": 0} for k in top_langs},
<24> }
<25>
<26> if item is not None:
<27> out["contribs"] = item.stats.contribs_count
<28> out["commits"] = item.stats.commits_count
<29> out["issues"] = item.stats.issues_count
<30> out["prs"] = item.stats.prs_count
<31> out["reviews"] = item.stats.reviews_count
<32>
<33> for k, v in item.stats.languages.items():
<34> if k in top_langs:
<35> out["top_langs"][k]["loc_added"] = v.additions - v.deletions # type: ignore
<36> out["top_langs"][k]["loc_changed"] = v.additions</s>
|
===========below chunk 0===========
# module: backend.src.subscriber.aggregation.wrapped.calendar
def get_calendar_data(data: UserPackage, year: int) -> CalendarData:
# offset: 1
out["loc_added"] += v.additions - v.deletions # type: ignore
out["loc_changed"] += v.additions + v.deletions # type: ignore
out_obj = CalendarDayDatum.parse_obj(out)
total_out.append(out_obj)
return CalendarData.parse_obj({"days": total_out})
===========unchanged ref 0===========
at: datetime
timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...)
datetime()
at: datetime.date
__slots__ = '_year', '_month', '_day', '_hashcode'
strftime(fmt: _Text) -> str
__str__ = isoformat
__radd__ = __add__
at: datetime.timedelta
__slots__ = '_days', '_seconds', '_microseconds', '_hashcode'
__radd__ = __add__
__rmul__ = __mul__
at: src.models.user.contribs.ContributionDay
date: str
weekday: int
stats: ContributionStats
lists: ContributionLists
at: src.models.user.contribs.ContributionStats
contribs_count: int
commits_count: int
issues_count: int
prs_count: int
reviews_count: int
repos_count: int
other_count: int
languages: Dict[str, Language]
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
public_stats: ContributionStats
total: List[ContributionDay]
public: List[ContributionDay]
repo_stats: Dict[str, RepoContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========unchanged ref 1===========
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 1===========
# module: backend.src.main
+ load_dotenv(find_dotenv())
- load_dotenv()
===========changed ref 2===========
# module: backend.tests
+ load_dotenv(find_dotenv(), verbose=True)
- load_dotenv(dotenv_path="")
===========changed ref 3===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 5===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 6===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 7===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 8===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
@classmethod
def decompress(cls, data: List[Any]) -> "RepoContributionStats":
+ contribs = super().decompress(data).model_dump()
- contribs = super().decompress(data).dict()
contribs["private"] = data[0][7]
return RepoContributionStats(**contribs)
===========changed ref 9===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_numeric_data(data: UserPackage, year: int) -> NumericData:
+ return NumericData.model_validate(
- return NumericData.parse_obj(
{
"contribs": get_contrib_stats(data),
"misc": get_misc_stats(data, year),
"loc": get_loc_stats(data),
}
)
===========changed ref 10===========
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
if secrets is None:
return (False, []) # type: ignore
+ tokens = SecretModel.model_validate(secrets).access_tokens
- tokens = SecretModel.parse_obj(secrets).access_tokens
return (True, tokens) # type: ignore
===========changed ref 11===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
def __add__( # type: ignore
self, other: "RepoContributionStats"
) -> "RepoContributionStats":
+ new_self = ContributionStats(**self.model_dump())
- new_self = ContributionStats(**self.dict())
+ new_other = ContributionStats(**other.model_dump())
- new_other = ContributionStats(**other.dict())
+ combined = (new_self + new_other).model_dump()
- combined = (new_self + new_other).dict()
combined["private"] = self.private
return RepoContributionStats(**combined)
===========changed ref 12===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_contrib_stats(data: UserPackage) -> ContribStats:
+ return ContribStats.model_validate(
- return ContribStats.parse_obj(
{
"contribs": data.contribs.total_stats.contribs_count,
"commits": data.contribs.total_stats.commits_count,
"issues": data.contribs.total_stats.issues_count,
"prs": data.contribs.total_stats.prs_count,
"reviews": data.contribs.total_stats.reviews_count,
"other": data.contribs.total_stats.other_count,
}
)
|
|
backend.src.data.github.rest.commit/get_commit_files
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<14>:<add> return [RawCommitFile.model_validate(f) for f in files]
<del> return [RawCommitFile.parse_obj(f) for f in files]
|
# module: backend.src.data.github.rest.commit
def get_commit_files(
owner: str, repo: str, sha: str, access_token: Optional[str] = None
) -> Optional[List[RawCommitFile]]:
<0> """
<1> Returns raw repository data
<2> :param owner: repository owner
<3> :param repo: repository name
<4> :param sha: commit sha
<5> :param access_token: GitHub access token
<6> :return: repository data
<7> """
<8>
<9> try:
<10> output = get_template(
<11> BASE_URL + owner + "/" + repo + "/commits/" + sha, access_token
<12> )
<13> files = output["files"]
<14> return [RawCommitFile.parse_obj(f) for f in files]
<15> except Exception:
<16> return None
<17>
|
===========unchanged ref 0===========
at: backend.src.data.github.rest.commit
BASE_URL = "https://api.github.com/repos/"
at: src.data.github.rest.template
get_template(query: str, access_token: Optional[str]=None, accept_header: str="application/vnd.github.v3+json") -> Dict[str, Any]
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 1===========
# module: backend.src.main
+ load_dotenv(find_dotenv())
- load_dotenv()
===========changed ref 2===========
# module: backend.tests
+ load_dotenv(find_dotenv(), verbose=True)
- load_dotenv(dotenv_path="")
===========changed ref 3===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 5===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 6===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 7===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 8===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
@classmethod
def decompress(cls, data: List[Any]) -> "RepoContributionStats":
+ contribs = super().decompress(data).model_dump()
- contribs = super().decompress(data).dict()
contribs["private"] = data[0][7]
return RepoContributionStats(**contribs)
===========changed ref 9===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_numeric_data(data: UserPackage, year: int) -> NumericData:
+ return NumericData.model_validate(
- return NumericData.parse_obj(
{
"contribs": get_contrib_stats(data),
"misc": get_misc_stats(data, year),
"loc": get_loc_stats(data),
}
)
===========changed ref 10===========
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
if secrets is None:
return (False, []) # type: ignore
+ tokens = SecretModel.model_validate(secrets).access_tokens
- tokens = SecretModel.parse_obj(secrets).access_tokens
return (True, tokens) # type: ignore
===========changed ref 11===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
def __add__( # type: ignore
self, other: "RepoContributionStats"
) -> "RepoContributionStats":
+ new_self = ContributionStats(**self.model_dump())
- new_self = ContributionStats(**self.dict())
+ new_other = ContributionStats(**other.model_dump())
- new_other = ContributionStats(**other.dict())
+ combined = (new_self + new_other).model_dump()
- combined = (new_self + new_other).dict()
combined["private"] = self.private
return RepoContributionStats(**combined)
===========changed ref 12===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_contrib_stats(data: UserPackage) -> ContribStats:
+ return ContribStats.model_validate(
- return ContribStats.parse_obj(
{
"contribs": data.contribs.total_stats.contribs_count,
"commits": data.contribs.total_stats.commits_count,
"issues": data.contribs.total_stats.issues_count,
"prs": data.contribs.total_stats.prs_count,
"reviews": data.contribs.total_stats.reviews_count,
"other": data.contribs.total_stats.other_count,
}
)
===========changed ref 13===========
+ # module: backend.delete_old_data
+ def main():
+ # Replace 'your_date_field' with the actual name of your date field
+ cutoff_date = datetime(2022, 12, 31)
+
+ count = await count_old_rows(cutoff_date)
+ if count == 0:
+ print("No rows to delete.")
+ return
+
+ print(f"Found {count} rows to delete.")
+ print()
+
+ confirmation = input("Are you sure you want to delete these rows? (yes/no): ")
+ if confirmation.lower() != "yes":
+ print("Operation canceled.")
+ return
+
+ print()
+ await delete_old_rows(cutoff_date)
+
===========changed ref 14===========
# module: backend.src.subscriber.aggregation.wrapped.time
def get_day_data(data: UserPackage) -> DayData:
days: Dict[int, Dict[str, int]] = defaultdict(
lambda: {"contribs": 0, "loc_changed": 0}
)
for item in data.contribs.total:
day = datetime.fromisoformat(item.date).weekday()
days[day]["contribs"] += item.stats.contribs_count
loc_changed = sum(
x.additions + x.deletions for x in item.stats.languages.values()
)
days[day]["loc_changed"] += loc_changed
out: List[TimeDatum] = []
for k in range(7):
v = days[k]
_obj: Dict[str, Union[str, int]] = {
"index": k,
**v,
"formatted_loc_changed": format_number(v["loc_changed"]),
}
+ out.append(TimeDatum.model_validate(_obj))
- out.append(TimeDatum.parse_obj(_obj))
return DayData(days=out)
|
backend.src.data.mongo.user_months.functions/set_user_month
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<0>:<add> compressed_user_month = user_month.model_dump()
<del> compressed_user_month = user_month.dict()
|
# module: backend.src.data.mongo.user_months.functions
def set_user_month(user_month: UserMonth):
<0> compressed_user_month = user_month.dict()
<1> compressed_user_month["data"] = user_month.data.compress()
<2>
<3> await USER_MONTHS.update_one( # type: ignore
<4> {"user_id": user_month.user_id, "month": user_month.month},
<5> {"$set": compressed_user_month},
<6> upsert=True,
<7> )
<8>
|
===========unchanged ref 0===========
at: src.data.mongo.main
USER_MONTHS = DB.user_months
at: src.data.mongo.user_months.models.UserMonth
user_id: str
month: datetime
version: float
private: bool
complete: bool
data: UserPackage
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
compress()
===========changed ref 0===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 1===========
# module: backend.src.main
+ load_dotenv(find_dotenv())
- load_dotenv()
===========changed ref 2===========
# module: backend.tests
+ load_dotenv(find_dotenv(), verbose=True)
- load_dotenv(dotenv_path="")
===========changed ref 3===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 5===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 6===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 7===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 8===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
@classmethod
def decompress(cls, data: List[Any]) -> "RepoContributionStats":
+ contribs = super().decompress(data).model_dump()
- contribs = super().decompress(data).dict()
contribs["private"] = data[0][7]
return RepoContributionStats(**contribs)
===========changed ref 9===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_numeric_data(data: UserPackage, year: int) -> NumericData:
+ return NumericData.model_validate(
- return NumericData.parse_obj(
{
"contribs": get_contrib_stats(data),
"misc": get_misc_stats(data, year),
"loc": get_loc_stats(data),
}
)
===========changed ref 10===========
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
if secrets is None:
return (False, []) # type: ignore
+ tokens = SecretModel.model_validate(secrets).access_tokens
- tokens = SecretModel.parse_obj(secrets).access_tokens
return (True, tokens) # type: ignore
===========changed ref 11===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
def __add__( # type: ignore
self, other: "RepoContributionStats"
) -> "RepoContributionStats":
+ new_self = ContributionStats(**self.model_dump())
- new_self = ContributionStats(**self.dict())
+ new_other = ContributionStats(**other.model_dump())
- new_other = ContributionStats(**other.dict())
+ combined = (new_self + new_other).model_dump()
- combined = (new_self + new_other).dict()
combined["private"] = self.private
return RepoContributionStats(**combined)
===========changed ref 12===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_contrib_stats(data: UserPackage) -> ContribStats:
+ return ContribStats.model_validate(
- return ContribStats.parse_obj(
{
"contribs": data.contribs.total_stats.contribs_count,
"commits": data.contribs.total_stats.commits_count,
"issues": data.contribs.total_stats.issues_count,
"prs": data.contribs.total_stats.prs_count,
"reviews": data.contribs.total_stats.reviews_count,
"other": data.contribs.total_stats.other_count,
}
)
===========changed ref 13===========
# module: backend.src.data.github.rest.commit
def get_commit_files(
owner: str, repo: str, sha: str, access_token: Optional[str] = None
) -> Optional[List[RawCommitFile]]:
"""
Returns raw repository data
:param owner: repository owner
:param repo: repository name
:param sha: commit sha
:param access_token: GitHub access token
:return: repository data
"""
try:
output = get_template(
BASE_URL + owner + "/" + repo + "/commits/" + sha, access_token
)
files = output["files"]
+ return [RawCommitFile.model_validate(f) for f in files]
- return [RawCommitFile.parse_obj(f) for f in files]
except Exception:
return None
===========changed ref 14===========
+ # module: backend.delete_old_data
+ def main():
+ # Replace 'your_date_field' with the actual name of your date field
+ cutoff_date = datetime(2022, 12, 31)
+
+ count = await count_old_rows(cutoff_date)
+ if count == 0:
+ print("No rows to delete.")
+ return
+
+ print(f"Found {count} rows to delete.")
+ print()
+
+ confirmation = input("Are you sure you want to delete these rows? (yes/no): ")
+ if confirmation.lower() != "yes":
+ print("Operation canceled.")
+ return
+
+ print()
+ await delete_old_rows(cutoff_date)
+
|
backend.src.data.mongo.user.functions/delete_user
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<0>:<add> if use_user_key:
<add> is_key = await is_user_key(user_id, user_key)
<del> if use_user_key and not is_user_key(user_id, user_key):
<1>:<add> if not is_key:
<add> return False
<del> return False
<2>:<add>
|
# module: backend.src.data.mongo.user.functions
def delete_user(user_id: str, user_key: str, use_user_key: bool = True) -> bool:
<0> if use_user_key and not is_user_key(user_id, user_key):
<1> return False
<2> await USERS.delete_one({"user_id": user_id}) # type: ignore
<3> return True
<4>
|
===========unchanged ref 0===========
at: backend.src.data.mongo.user.functions
is_user_key(user_id: str, user_key: str) -> bool
===========changed ref 0===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 1===========
# module: backend.src.main
+ load_dotenv(find_dotenv())
- load_dotenv()
===========changed ref 2===========
# module: backend.tests
+ load_dotenv(find_dotenv(), verbose=True)
- load_dotenv(dotenv_path="")
===========changed ref 3===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 4===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 5===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 6===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 7===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 8===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
@classmethod
def decompress(cls, data: List[Any]) -> "RepoContributionStats":
+ contribs = super().decompress(data).model_dump()
- contribs = super().decompress(data).dict()
contribs["private"] = data[0][7]
return RepoContributionStats(**contribs)
===========changed ref 9===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_numeric_data(data: UserPackage, year: int) -> NumericData:
+ return NumericData.model_validate(
- return NumericData.parse_obj(
{
"contribs": get_contrib_stats(data),
"misc": get_misc_stats(data, year),
"loc": get_loc_stats(data),
}
)
===========changed ref 10===========
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
if secrets is None:
return (False, []) # type: ignore
+ tokens = SecretModel.model_validate(secrets).access_tokens
- tokens = SecretModel.parse_obj(secrets).access_tokens
return (True, tokens) # type: ignore
===========changed ref 11===========
# module: backend.src.data.mongo.user_months.functions
def set_user_month(user_month: UserMonth):
+ compressed_user_month = user_month.model_dump()
- compressed_user_month = user_month.dict()
compressed_user_month["data"] = user_month.data.compress()
await USER_MONTHS.update_one( # type: ignore
{"user_id": user_month.user_id, "month": user_month.month},
{"$set": compressed_user_month},
upsert=True,
)
===========changed ref 12===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
def __add__( # type: ignore
self, other: "RepoContributionStats"
) -> "RepoContributionStats":
+ new_self = ContributionStats(**self.model_dump())
- new_self = ContributionStats(**self.dict())
+ new_other = ContributionStats(**other.model_dump())
- new_other = ContributionStats(**other.dict())
+ combined = (new_self + new_other).model_dump()
- combined = (new_self + new_other).dict()
combined["private"] = self.private
return RepoContributionStats(**combined)
===========changed ref 13===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_contrib_stats(data: UserPackage) -> ContribStats:
+ return ContribStats.model_validate(
- return ContribStats.parse_obj(
{
"contribs": data.contribs.total_stats.contribs_count,
"commits": data.contribs.total_stats.commits_count,
"issues": data.contribs.total_stats.issues_count,
"prs": data.contribs.total_stats.prs_count,
"reviews": data.contribs.total_stats.reviews_count,
"other": data.contribs.total_stats.other_count,
}
)
===========changed ref 14===========
# module: backend.src.data.github.rest.commit
def get_commit_files(
owner: str, repo: str, sha: str, access_token: Optional[str] = None
) -> Optional[List[RawCommitFile]]:
"""
Returns raw repository data
:param owner: repository owner
:param repo: repository name
:param sha: commit sha
:param access_token: GitHub access token
:return: repository data
"""
try:
output = get_template(
BASE_URL + owner + "/" + repo + "/commits/" + sha, access_token
)
files = output["files"]
+ return [RawCommitFile.model_validate(f) for f in files]
- return [RawCommitFile.parse_obj(f) for f in files]
except Exception:
return None
===========changed ref 15===========
+ # module: backend.delete_old_data
+ def main():
+ # Replace 'your_date_field' with the actual name of your date field
+ cutoff_date = datetime(2022, 12, 31)
+
+ count = await count_old_rows(cutoff_date)
+ if count == 0:
+ print("No rows to delete.")
+ return
+
+ print(f"Found {count} rows to delete.")
+ print()
+
+ confirmation = input("Are you sure you want to delete these rows? (yes/no): ")
+ if confirmation.lower() != "yes":
+ print("Operation canceled.")
+ return
+
+ print()
+ await delete_old_rows(cutoff_date)
+
|
backend.src.subscriber.aggregation.wrapped.timestamps/get_timestamp_data
|
Modified
|
avgupta456~github-trends
|
97df594eed9a9452bf15b3cd1bd68f8302f3b000
|
Start 2023 Wrapped (#231)
|
<16>:<add> out = [TimestampDatum.model_validate(x) for x in out]
<del> out = [TimestampDatum.parse_obj(x) for x in out]
|
# module: backend.src.subscriber.aggregation.wrapped.timestamps
def get_timestamp_data(data: UserPackage) -> TimestampData:
<0> out: List[Any] = []
<1> for item in data.contribs.total:
<2> lists = item.lists
<3> lists = [lists.commits, lists.issues, lists.prs, lists.reviews]
<4> for type, list in zip(["commit", "issue", "pr", "review"], lists):
<5> out.extend(
<6> {
<7> "type": type,
<8> "weekday": item.weekday,
<9> "timestamp": date_to_seconds_since_midnight(obj),
<10> }
<11> for obj in list
<12> )
<13>
<14> shuffle(out)
<15> out = out[:MAX_ITEMS]
<16> out = [TimestampDatum.parse_obj(x) for x in out]
<17>
<18> return TimestampData(contribs=out)
<19>
|
===========unchanged ref 0===========
at: backend.src.subscriber.aggregation.wrapped.timestamps
MAX_ITEMS = 200
date_to_seconds_since_midnight(date: datetime) -> int
at: random
shuffle = _inst.shuffle
at: src.models.user.contribs.ContributionDay
date: str
weekday: int
stats: ContributionStats
lists: ContributionLists
at: src.models.user.contribs.ContributionLists
commits: List[datetime]
issues: List[datetime]
prs: List[datetime]
reviews: List[datetime]
repos: List[datetime]
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
public_stats: ContributionStats
total: List[ContributionDay]
public: List[ContributionDay]
repo_stats: Dict[str, RepoContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
+ # module: backend.delete_old_data
+ load_dotenv(find_dotenv())
+
===========changed ref 1===========
# module: backend.src.main
+ load_dotenv(find_dotenv())
- load_dotenv()
===========changed ref 2===========
# module: backend.src.models.wrapped.repos
class RepoDatum(BaseModel):
+ id: int
- id: str
label: str
value: int
formatted_value: str
===========changed ref 3===========
# module: backend.tests
+ load_dotenv(find_dotenv(), verbose=True)
- load_dotenv(dotenv_path="")
===========changed ref 4===========
+ # module: backend.delete_old_data
+ if __name__ == "__main__":
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main())
+
===========changed ref 5===========
+ # module: backend.delete_old_data
+ def get_filters(cutoff_date: datetime) -> Any:
+ return {
+ "$or": [
+ {"month": {"$lte": cutoff_date}},
+ {"version": {"$ne": API_VERSION}},
+ ],
+ }
+
===========changed ref 6===========
+ # module: backend.delete_old_data
+ def delete_old_rows(cutoff_date: datetime):
+ filters = get_filters(cutoff_date)
+ result = await USER_MONTHS.delete_many(filters) # type: ignore
+ print(f"Deleted {result.deleted_count} rows")
+
===========changed ref 7===========
+ # module: backend.delete_old_data
+ def count_old_rows(cutoff_date: datetime) -> int:
+ filters = get_filters(cutoff_date)
+ num_rows = len(await USER_MONTHS.find(filters).to_list(length=None)) # type: ignore
+ return num_rows
+
===========changed ref 8===========
# module: backend.src.subscriber.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
- @router.get("/valid/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def check_valid_user(response: Response, user_id: str) -> str:
+ print("Checking valid user")
+ out = await get_is_valid_user(user_id)
- return await get_is_valid_user(user_id)
+ print(out)
+ return out
===========changed ref 9===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
@classmethod
def decompress(cls, data: List[Any]) -> "RepoContributionStats":
+ contribs = super().decompress(data).model_dump()
- contribs = super().decompress(data).dict()
contribs["private"] = data[0][7]
return RepoContributionStats(**contribs)
===========changed ref 10===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_numeric_data(data: UserPackage, year: int) -> NumericData:
+ return NumericData.model_validate(
- return NumericData.parse_obj(
{
"contribs": get_contrib_stats(data),
"misc": get_misc_stats(data, year),
"loc": get_loc_stats(data),
}
)
===========changed ref 11===========
# module: backend.src.data.mongo.user.functions
def delete_user(user_id: str, user_key: str, use_user_key: bool = True) -> bool:
+ if use_user_key:
+ is_key = await is_user_key(user_id, user_key)
- if use_user_key and not is_user_key(user_id, user_key):
+ if not is_key:
+ return False
- return False
+
await USERS.delete_one({"user_id": user_id}) # type: ignore
return True
===========changed ref 12===========
# module: backend.src.data.mongo.secret.functions
@alru_cache(ttl=timedelta(minutes=15))
async def get_keys(no_cache: bool = False) -> List[str]:
secrets: Optional[Dict[str, Any]] = await SECRETS.find_one({"project": "main"}) # type: ignore
if secrets is None:
return (False, []) # type: ignore
+ tokens = SecretModel.model_validate(secrets).access_tokens
- tokens = SecretModel.parse_obj(secrets).access_tokens
return (True, tokens) # type: ignore
===========changed ref 13===========
# module: backend.src.data.mongo.user_months.functions
def set_user_month(user_month: UserMonth):
+ compressed_user_month = user_month.model_dump()
- compressed_user_month = user_month.dict()
compressed_user_month["data"] = user_month.data.compress()
await USER_MONTHS.update_one( # type: ignore
{"user_id": user_month.user_id, "month": user_month.month},
{"$set": compressed_user_month},
upsert=True,
)
===========changed ref 14===========
# module: backend.src.models.user.contribs
class RepoContributionStats(ContributionStats, BaseModel):
def __add__( # type: ignore
self, other: "RepoContributionStats"
) -> "RepoContributionStats":
+ new_self = ContributionStats(**self.model_dump())
- new_self = ContributionStats(**self.dict())
+ new_other = ContributionStats(**other.model_dump())
- new_other = ContributionStats(**other.dict())
+ combined = (new_self + new_other).model_dump()
- combined = (new_self + new_other).dict()
combined["private"] = self.private
return RepoContributionStats(**combined)
===========changed ref 15===========
# module: backend.src.subscriber.aggregation.wrapped.numeric
def get_contrib_stats(data: UserPackage) -> ContribStats:
+ return ContribStats.model_validate(
- return ContribStats.parse_obj(
{
"contribs": data.contribs.total_stats.contribs_count,
"commits": data.contribs.total_stats.commits_count,
"issues": data.contribs.total_stats.issues_count,
"prs": data.contribs.total_stats.prs_count,
"reviews": data.contribs.total_stats.reviews_count,
"other": data.contribs.total_stats.other_count,
}
)
|
backend.src.utils.alru_cache/alru_cache
|
Modified
|
avgupta456~github-trends
|
608321cbf41f097ab7fa5650114585efa6f85d29
|
Remove PubSub (#233)
|
<0>:<add> def decorator(
<add> func: Callable[Param, Awaitable[Tuple[bool, TOutput]]]
<add> ) -> Callable[Param, Awaitable[TOutput]]:
<del> def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
<1>:<add> cache: Dict[TKey, Tuple[datetime, TOutput]] = {}
<del> cache: Dict[Any, Tuple[datetime, Any]] = {}
<2>:<add> keys: List[TKey] = []
<del> keys: List[Any] = []
<4>:<add> def in_cache(key: TKey) -> bool:
<del> def in_cache(key: Any) -> bool:
<16>:<add> def update_cache_and_return(key: TKey, flag: bool, value: TOutput) -> TOutput:
<del> def update_cache_and_return(key: Any, flag: bool, value: Any) -> Any:
<39>:<add> async def wrapper(*args: Param.args, **kwargs: Param.kwargs) -> TOutput:
<del> async def wrapper(*args: List[Any], **kwargs: Dict[str, Any]) -> Any:
<40>:<add> key: TKey = tuple(args), frozenset(
<del> key = tuple(args), frozenset(
|
# module: backend.src.utils.alru_cache
def alru_cache(max_size: int = 128, ttl: timedelta = timedelta(minutes=1)):
<0> def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
<1> cache: Dict[Any, Tuple[datetime, Any]] = {}
<2> keys: List[Any] = []
<3>
<4> def in_cache(key: Any) -> bool:
<5> # key not in cache
<6> if key not in cache:
<7> return False
<8>
<9> # key in cache but expired
<10> if datetime.now() - cache[key][0] > ttl:
<11> return False
<12>
<13> # key in cache and not expired
<14> return True
<15>
<16> def update_cache_and_return(key: Any, flag: bool, value: Any) -> Any:
<17> # if flag = False, do not update cache and return value
<18> if not flag:
<19> return value
<20>
<21> # if flag = True, update cache
<22> now = datetime.now()
<23> cache[key] = (now, value)
<24> keys.append(key)
<25>
<26> # remove oldest key if cache is full
<27> if len(keys) > max_size:
<28> try:
<29> # Should not raise KeyError, but just in case
<30> del cache[keys.pop(0)]
<31> except KeyError:
<32> # Already deleted by another thread
<33> pass
<34>
<35> # return value from cache
<36> return value # equal to cache[key][1]
<37>
<38> @wraps(func)
<39> async def wrapper(*args: List[Any], **kwargs: Dict[str, Any]) -> Any:
<40> key = tuple(args), frozenset(
<41> [(k, v) for k, v in kwargs.items() if k not in ["no_cache"]]
<42> )
<43> if "no_cache" in kwargs and kwargs["no_cache"]:
<44> (flag, value) = await func(*args, **kwargs)
<45> return update_cache_and_return(key, flag, value</s>
|
===========below chunk 0===========
# module: backend.src.utils.alru_cache
def alru_cache(max_size: int = 128, ttl: timedelta = timedelta(minutes=1)):
# offset: 1
if in_cache(key):
return cache[key][1]
(flag, value) = await func(*args, **kwargs)
return update_cache_and_return(key, flag, value)
return wrapper
return decorator
===========unchanged ref 0===========
at: datetime
timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...)
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: functools
wraps(wrapped: _AnyCallable, assigned: Sequence[str]=..., updated: Sequence[str]=...) -> Callable[[_T], _T]
at: typing
TypeVar(name: str, *constraints: Type[Any], bound: Union[None, Type[Any], str]=..., covariant: bool=..., contravariant: bool=...)
ParamSpec(name: str)
Awaitable = _alias(collections.abc.Awaitable, 1)
Callable = _CallableType(collections.abc.Callable, 2)
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
List = _alias(list, 1, inst=False, name='List')
FrozenSet = _alias(frozenset, 1, inst=False, name='FrozenSet')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
+ # module: backend.tests.aggregation
+
+
===========changed ref 1===========
+ # module: backend.src.routers.auth
+
+
===========changed ref 2===========
+ # module: backend.src.processing.wrapped.repos
+
+
===========changed ref 3===========
+ # module: backend.src.render.error
+
+
===========changed ref 4===========
+ # module: backend.src.processing.wrapped.langs
+
+
===========changed ref 5===========
+ # module: backend.src.render.error
+ THEME = "classic"
+
===========changed ref 6===========
+ # module: backend.src.processing.wrapped.repos
+ def _count_repo_loc(x: RepoContributionStats, metric: str) -> int:
+ return sum(_count_loc(lang, metric) for lang in x.languages.values())
+
===========changed ref 7===========
+ # module: backend.src.routers
+ __all__ = ["asset_router", "auth_router", "dev_router", "user_router", "wrapped_router"]
+
===========changed ref 8===========
+ # module: backend.src.processing.wrapped.repos
+ def _count_loc(x: Language, metric: str) -> int:
+ if metric == "changed":
+ return x.additions + x.deletions
+ return x.additions - x.deletions
+
===========changed ref 9===========
+ # module: backend.src.processing.wrapped.langs
+ def _count_loc(x: Language, metric: str) -> int:
+ if metric == "changed":
+ return x.additions + x.deletions
+ return x.additions - x.deletions
+
===========changed ref 10===========
+ # module: backend.src.render.error
+ def get_no_data_svg(header: str, subheader: str) -> Drawing:
+ d, dp = get_template(
+ width=300,
+ height=285,
+ padding=20,
+ header_text=header,
+ subheader_text=subheader,
+ debug=False,
+ theme=THEME,
+ )
+
+ d.add(d.image(f"{BACKEND_URL}/assets/error", insert=(85, 80), style="opacity: 50%"))
+
+ dp.add(d.text("No data to show", insert=(55, 220), class_=f"{THEME}-image-text"))
+
+ d.add(dp)
+ return d
+
===========changed ref 11===========
+ # module: backend.src.render.error
+ def get_empty_demo_svg(header: str) -> Drawing:
+ d = Drawing(size=(300, 285))
+ d.defs.add(d.style(styles_no_animation[THEME]))
+
+ d.add(
+ d.rect(
+ size=(299, 284),
+ insert=(0.5, 0.5),
+ rx=4.5,
+ stroke=themes[THEME]["border_color"],
+ fill=themes[THEME]["bg_color"],
+ )
+ )
+
+ d.add(d.text(header, insert=(25, 35), class_=f"{THEME}-header"))
+
+ d.add(
+ d.text(
+ "Enter your username to start!",
+ insert=(25, 60),
+ class_=f"{THEME}-lang-name",
+ )
+ )
+
+ d.add(
+ d.image(
+ f"{BACKEND_URL}/assets/stopwatch", insert=(85, 100), style="opacity: 50%"
+ )
+ )
+
+ return d
+
===========changed ref 12===========
+ # module: backend.src.render.error
+ def get_error_svg() -> Drawing:
+ d = Drawing(size=(300, 285))
+ d.defs.add(d.style(styles_no_animation[THEME]))
+
+ d.add(
+ d.rect(
+ size=(299, 284),
+ insert=(0.5, 0.5),
+ rx=4.5,
+ stroke=themes[THEME]["border_color"],
+ fill=themes[THEME]["bg_color"],
+ )
+ )
+
+ d.add(d.text("Unknown Error", insert=(25, 35), class_=f"{THEME}-header"))
+
+ d.add(
+ d.text(
+ "Please try again later or raise a ticket on GitHub",
+ insert=(25, 60),
+ class_=f"{THEME}-lang-name",
+ )
+ )
+
+ d.add(
+ d.image(f"{BACKEND_URL}/assets/error", insert=(85, 100), style="opacity: 50%")
+ )
+
+ return d
+
===========changed ref 13===========
+ # module: backend.src.render.error
+ def get_loading_svg() -> Drawing:
+ d = Drawing(size=(300, 285))
+ d.defs.add(d.style(styles_no_animation[THEME]))
+
+ d.add(
+ d.rect(
+ size=(299, 284),
+ insert=(0.5, 0.5),
+ rx=4.5,
+ stroke=themes[THEME]["border_color"],
+ fill=themes[THEME]["bg_color"],
+ )
+ )
+
+ d.add(
+ d.text("Loading data, hang tight!", insert=(25, 35), class_=f"{THEME}-header")
+ )
+
+ d.add(
+ d.text(
+ "Please wait a couple seconds and refresh the page.",
+ insert=(25, 60),
+ class_=f"{THEME}-lang-name",
+ )
+ )
+
+ d.add(
+ d.image(
+ f"{BACKEND_URL}/assets/stopwatch", insert=(85, 100), style="opacity: 50%"
+ )
+ )
+
+ return d
+
|
backend.tests.utils.test_alru_cache/TestTemplate.test_basic_alru_cache
|
Modified
|
avgupta456~github-trends
|
608321cbf41f097ab7fa5650114585efa6f85d29
|
Remove PubSub (#233)
|
<3>:<add> async def f(x: int) -> Tuple[bool, int]:
<del> async def f(x: int) -> int:
<6>:<add> return (True, x)
<del> return (True, x) # type: ignore
|
# module: backend.tests.utils.test_alru_cache
class TestTemplate(AsyncTestCase):
def test_basic_alru_cache(self):
<0> count = 0
<1>
<2> @alru_cache()
<3> async def f(x: int) -> int:
<4> nonlocal count
<5> count += 1
<6> return (True, x) # type: ignore
<7>
<8> assert count == 0
<9> assert await f(1) == 1
<10> assert count == 1
<11> assert await f(1) == 1
<12> assert count == 1
<13> assert await f(2) == 2
<14> assert count == 2
<15> assert await f(2) == 2
<16> assert count == 2
<17> assert await f(1) == 1
<18> assert count == 2
<19>
|
===========changed ref 0===========
+ # module: backend.src.routers.auth.standalone
+
+
===========changed ref 1===========
+ # module: backend.src.processing.wrapped.calendar
+
+
===========changed ref 2===========
+ # module: backend.src.aggregation.layer0.follows
+
+
===========changed ref 3===========
+ # module: backend.src.routers.wrapped
+
+
===========changed ref 4===========
+ # module: backend.tests.aggregation.layer0
+
+
===========changed ref 5===========
+ # module: backend.src.routers.assets
+
+
===========changed ref 6===========
+ # module: backend.src.processing.user.commits
+
+
===========changed ref 7===========
+ # module: backend.src.processing.wrapped.timestamps
+
+
===========changed ref 8===========
+ # module: backend.src.processing.auth
+
+
===========changed ref 9===========
+ # module: backend.src.aggregation.layer1.user
+
+
===========changed ref 10===========
+ # module: backend.src.processing.wrapped.package
+
+
===========changed ref 11===========
+ # module: backend.src.routers.background
+
+
===========changed ref 12===========
+ # module: backend.src.aggregation.layer2.user
+
+
===========changed ref 13===========
+ # module: backend.tests.aggregation
+
+
===========changed ref 14===========
+ # module: backend.src.routers.auth
+
+
===========changed ref 15===========
+ # module: backend.src.processing.wrapped.repos
+
+
===========changed ref 16===========
+ # module: backend.src.render.error
+
+
===========changed ref 17===========
+ # module: backend.src.processing.wrapped.langs
+
+
===========changed ref 18===========
+ # module: backend.src.routers.auth.standalone
+ router = APIRouter()
+
===========changed ref 19===========
+ # module: backend.src.routers.wrapped
+ router = APIRouter()
+
===========changed ref 20===========
+ # module: backend.src.processing.wrapped.timestamps
+ MAX_ITEMS = 200
+
===========changed ref 21===========
+ # module: backend.src.routers.users.db
+ router = APIRouter()
+
===========changed ref 22===========
+ # module: backend.src.aggregation.layer1.user
+ s = requests.Session()
+
===========changed ref 23===========
+ # module: backend.src.render.error
+ THEME = "classic"
+
===========changed ref 24===========
+ # module: backend.src.aggregation.layer1
+ __all__ = ["query_user"]
+
===========changed ref 25===========
+ # module: backend.src.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
+ @async_fail_gracefully
+ async def check_valid_user(response: Response, user_id: str) -> str:
+ return await get_is_valid_user(user_id)
+
===========changed ref 26===========
+ # module: backend.src.processing.user.commits
+ dict_type = Dict[str, Union[str, int, float]]
+
===========changed ref 27===========
+ # module: backend.src.processing.auth
+ def set_user_key(code: str, user_key: str) -> str:
+ code_key_map[code] = user_key
+ return user_key
+
===========changed ref 28===========
+ # module: backend.src.processing.user.commits
+ def loc_metric_func(loc_metric: str, additions: int, deletions: int) -> int:
+ if loc_metric == "changed":
+ return additions + deletions
+ return additions - deletions
+
===========changed ref 29===========
+ # module: backend.src.processing.wrapped.repos
+ def _count_repo_loc(x: RepoContributionStats, metric: str) -> int:
+ return sum(_count_loc(lang, metric) for lang in x.languages.values())
+
===========changed ref 30===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/signup/private")
+ def redirect_private(user_id: Optional[str] = None) -> RedirectResponse:
+ return RedirectResponse(get_redirect_url(private=True, user_id=user_id))
+
===========changed ref 31===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/signup/public")
+ def redirect_public(user_id: Optional[str] = None) -> RedirectResponse:
+ return RedirectResponse(get_redirect_url(private=False, user_id=user_id))
+
===========changed ref 32===========
+ # module: backend.src.processing.wrapped.timestamps
+ def date_to_seconds_since_midnight(date: datetime) -> int:
+ return (date.hour * 60 * 60) + (date.minute * 60) + date.second
+
===========changed ref 33===========
+ # module: backend.src.processing.auth
+ def delete_user(user_id: str, user_key: str, use_user_key: bool = True) -> bool:
+ return await db_delete_user(user_id, user_key, use_user_key)
+
===========changed ref 34===========
<s> module: backend.src.routers.users.db
+ @router.get(
+ "/get/metadata/{user_id}",
+ status_code=status.HTTP_200_OK,
+ include_in_schema=False,
+ response_model=Dict[str, Any],
+ )
+ @async_fail_gracefully
+ async def get_db_public_user(
+ response: Response, user_id: str, no_cache: bool = False
+ ) -> Optional[PublicUserModel]:
+ return await db_get_public_user(user_id, no_cache=no_cache)
+
===========changed ref 35===========
+ # module: backend.src.routers
+ __all__ = ["asset_router", "auth_router", "dev_router", "user_router", "wrapped_router"]
+
===========changed ref 36===========
+ # module: backend.src.processing.wrapped.repos
+ def _count_loc(x: Language, metric: str) -> int:
+ if metric == "changed":
+ return x.additions + x.deletions
+ return x.additions - x.deletions
+
===========changed ref 37===========
+ # module: backend.src.processing.wrapped.langs
+ def _count_loc(x: Language, metric: str) -> int:
+ if metric == "changed":
+ return x.additions + x.deletions
+ return x.additions - x.deletions
+
===========changed ref 38===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/delete/{user_id}")
+ async def delete_account_auth(user_id: str) -> RedirectResponse:
+ return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
+ )
+
===========changed ref 39===========
+ # module: backend.src.routers.background
+ def run_in_background(task: UpdateUserBackgroundTask):
+ if isinstance(task, UpdateUserBackgroundTask): # type: ignore
+ await query_user(task.user_id, task.access_token, task.private_access)
+
===========changed ref 40===========
# module: backend.src.utils.alru_cache
+ Param = ParamSpec("Param")
+ TOutput = TypeVar("TOutput")
+
+ TKey = Tuple[Tuple[Any, ...], FrozenSet[Tuple[str, Any]]]
===========changed ref 41===========
# module: backend.src.data.mongo.user_months
+ __all__ = ["set_user_month", "get_user_months", "UserMonth"]
- __all__ = ["get_user_months", "set_user_month", "UserMonth"]
===========changed ref 42===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/redirect/delete/{user_id}", include_in_schema=False)
+ async def delete_account(user_id: str) -> RedirectResponse:
+ await delete_user(user_id, user_key="", use_user_key=False)
+ return RedirectResponse(
+ f"https://github.com/settings/connections/applications/{OAUTH_CLIENT_ID}"
+ )
+
===========changed ref 43===========
+ # module: backend.src.routers.wrapped
+ @router.get("/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any])
+ @async_fail_gracefully
+ async def get_wrapped_user(
+ response: Response, user_id: str, year: int = 2022, no_cache: bool = False
+ ) -> Optional[WrappedPackage]:
+ valid_user = await get_is_valid_user(user_id)
+ if valid_user != "Valid user":
+ return WrappedPackage.empty()
+
+ return await query_wrapped_user(user_id, year, no_cache=no_cache)
+
|
backend.tests.utils.test_alru_cache/TestTemplate.test_alru_cache_with_flag
|
Modified
|
avgupta456~github-trends
|
608321cbf41f097ab7fa5650114585efa6f85d29
|
Remove PubSub (#233)
|
<3>:<add> async def f(x: int) -> Tuple[bool, int]:
<del> async def f(x: int) -> int:
<6>:<add> return (count % 2 == 0, x)
<del> return (count % 2 == 0, x) # type: ignore
|
# module: backend.tests.utils.test_alru_cache
class TestTemplate(AsyncTestCase):
def test_alru_cache_with_flag(self):
<0> count = 0
<1>
<2> @alru_cache()
<3> async def f(x: int) -> int:
<4> nonlocal count
<5> count += 1
<6> return (count % 2 == 0, x) # type: ignore
<7>
<8> assert count == 0
<9> assert await f(1) == 1
<10> assert count == 1
<11> assert await f(1) == 1
<12> assert count == 2
<13> assert await f(2) == 2
<14> assert count == 3
<15> assert await f(3) == 3
<16> assert count == 4
<17> assert await f(3) == 3
<18> assert count == 4
<19>
|
===========changed ref 0===========
# module: backend.tests.utils.test_alru_cache
class TestTemplate(AsyncTestCase):
def test_basic_alru_cache(self):
count = 0
@alru_cache()
+ async def f(x: int) -> Tuple[bool, int]:
- async def f(x: int) -> int:
nonlocal count
count += 1
+ return (True, x)
- return (True, x) # type: ignore
assert count == 0
assert await f(1) == 1
assert count == 1
assert await f(1) == 1
assert count == 1
assert await f(2) == 2
assert count == 2
assert await f(2) == 2
assert count == 2
assert await f(1) == 1
assert count == 2
===========changed ref 1===========
+ # module: backend.src.routers.auth.standalone
+
+
===========changed ref 2===========
+ # module: backend.src.processing.wrapped.calendar
+
+
===========changed ref 3===========
+ # module: backend.src.aggregation.layer0.follows
+
+
===========changed ref 4===========
+ # module: backend.src.routers.wrapped
+
+
===========changed ref 5===========
+ # module: backend.tests.aggregation.layer0
+
+
===========changed ref 6===========
+ # module: backend.src.routers.assets
+
+
===========changed ref 7===========
+ # module: backend.src.processing.user.commits
+
+
===========changed ref 8===========
+ # module: backend.src.processing.wrapped.timestamps
+
+
===========changed ref 9===========
+ # module: backend.src.processing.auth
+
+
===========changed ref 10===========
+ # module: backend.src.aggregation.layer1.user
+
+
===========changed ref 11===========
+ # module: backend.src.processing.wrapped.package
+
+
===========changed ref 12===========
+ # module: backend.src.routers.background
+
+
===========changed ref 13===========
+ # module: backend.src.aggregation.layer2.user
+
+
===========changed ref 14===========
+ # module: backend.tests.aggregation
+
+
===========changed ref 15===========
+ # module: backend.src.routers.auth
+
+
===========changed ref 16===========
+ # module: backend.src.processing.wrapped.repos
+
+
===========changed ref 17===========
+ # module: backend.src.render.error
+
+
===========changed ref 18===========
+ # module: backend.src.processing.wrapped.langs
+
+
===========changed ref 19===========
+ # module: backend.src.routers.auth.standalone
+ router = APIRouter()
+
===========changed ref 20===========
+ # module: backend.src.routers.wrapped
+ router = APIRouter()
+
===========changed ref 21===========
+ # module: backend.src.processing.wrapped.timestamps
+ MAX_ITEMS = 200
+
===========changed ref 22===========
+ # module: backend.src.routers.users.db
+ router = APIRouter()
+
===========changed ref 23===========
+ # module: backend.src.aggregation.layer1.user
+ s = requests.Session()
+
===========changed ref 24===========
+ # module: backend.src.render.error
+ THEME = "classic"
+
===========changed ref 25===========
+ # module: backend.src.aggregation.layer1
+ __all__ = ["query_user"]
+
===========changed ref 26===========
+ # module: backend.src.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
+ @async_fail_gracefully
+ async def check_valid_user(response: Response, user_id: str) -> str:
+ return await get_is_valid_user(user_id)
+
===========changed ref 27===========
+ # module: backend.src.processing.user.commits
+ dict_type = Dict[str, Union[str, int, float]]
+
===========changed ref 28===========
+ # module: backend.src.processing.auth
+ def set_user_key(code: str, user_key: str) -> str:
+ code_key_map[code] = user_key
+ return user_key
+
===========changed ref 29===========
+ # module: backend.src.processing.user.commits
+ def loc_metric_func(loc_metric: str, additions: int, deletions: int) -> int:
+ if loc_metric == "changed":
+ return additions + deletions
+ return additions - deletions
+
===========changed ref 30===========
+ # module: backend.src.processing.wrapped.repos
+ def _count_repo_loc(x: RepoContributionStats, metric: str) -> int:
+ return sum(_count_loc(lang, metric) for lang in x.languages.values())
+
===========changed ref 31===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/signup/private")
+ def redirect_private(user_id: Optional[str] = None) -> RedirectResponse:
+ return RedirectResponse(get_redirect_url(private=True, user_id=user_id))
+
===========changed ref 32===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/signup/public")
+ def redirect_public(user_id: Optional[str] = None) -> RedirectResponse:
+ return RedirectResponse(get_redirect_url(private=False, user_id=user_id))
+
===========changed ref 33===========
+ # module: backend.src.processing.wrapped.timestamps
+ def date_to_seconds_since_midnight(date: datetime) -> int:
+ return (date.hour * 60 * 60) + (date.minute * 60) + date.second
+
===========changed ref 34===========
+ # module: backend.src.processing.auth
+ def delete_user(user_id: str, user_key: str, use_user_key: bool = True) -> bool:
+ return await db_delete_user(user_id, user_key, use_user_key)
+
===========changed ref 35===========
<s> module: backend.src.routers.users.db
+ @router.get(
+ "/get/metadata/{user_id}",
+ status_code=status.HTTP_200_OK,
+ include_in_schema=False,
+ response_model=Dict[str, Any],
+ )
+ @async_fail_gracefully
+ async def get_db_public_user(
+ response: Response, user_id: str, no_cache: bool = False
+ ) -> Optional[PublicUserModel]:
+ return await db_get_public_user(user_id, no_cache=no_cache)
+
===========changed ref 36===========
+ # module: backend.src.routers
+ __all__ = ["asset_router", "auth_router", "dev_router", "user_router", "wrapped_router"]
+
===========changed ref 37===========
+ # module: backend.src.processing.wrapped.repos
+ def _count_loc(x: Language, metric: str) -> int:
+ if metric == "changed":
+ return x.additions + x.deletions
+ return x.additions - x.deletions
+
===========changed ref 38===========
+ # module: backend.src.processing.wrapped.langs
+ def _count_loc(x: Language, metric: str) -> int:
+ if metric == "changed":
+ return x.additions + x.deletions
+ return x.additions - x.deletions
+
===========changed ref 39===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/delete/{user_id}")
+ async def delete_account_auth(user_id: str) -> RedirectResponse:
+ return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
+ )
+
===========changed ref 40===========
+ # module: backend.src.routers.background
+ def run_in_background(task: UpdateUserBackgroundTask):
+ if isinstance(task, UpdateUserBackgroundTask): # type: ignore
+ await query_user(task.user_id, task.access_token, task.private_access)
+
===========changed ref 41===========
# module: backend.src.utils.alru_cache
+ Param = ParamSpec("Param")
+ TOutput = TypeVar("TOutput")
+
+ TKey = Tuple[Tuple[Any, ...], FrozenSet[Tuple[str, Any]]]
===========changed ref 42===========
# module: backend.src.data.mongo.user_months
+ __all__ = ["set_user_month", "get_user_months", "UserMonth"]
- __all__ = ["get_user_months", "set_user_month", "UserMonth"]
|
backend.tests.utils.test_alru_cache/TestTemplate.test_alru_cache_with_maxsize
|
Modified
|
avgupta456~github-trends
|
608321cbf41f097ab7fa5650114585efa6f85d29
|
Remove PubSub (#233)
|
<3>:<add> async def f(x: int) -> Tuple[bool, int]:
<del> async def f(x: int) -> int:
<6>:<add> return (True, x)
<del> return (True, x) # type: ignore
|
# module: backend.tests.utils.test_alru_cache
class TestTemplate(AsyncTestCase):
def test_alru_cache_with_maxsize(self):
<0> count = 0
<1>
<2> @alru_cache(max_size=2)
<3> async def f(x: int) -> int:
<4> nonlocal count
<5> count += 1
<6> return (True, x) # type: ignore
<7>
<8> assert count == 0
<9> assert await f(1) == 1
<10> assert count == 1
<11> assert await f(2) == 2
<12> assert count == 2
<13> assert await f(3) == 3
<14> assert count == 3
<15> assert await f(1) == 1
<16> assert count == 4
<17>
|
===========changed ref 0===========
# module: backend.tests.utils.test_alru_cache
class TestTemplate(AsyncTestCase):
def test_alru_cache_with_flag(self):
count = 0
@alru_cache()
+ async def f(x: int) -> Tuple[bool, int]:
- async def f(x: int) -> int:
nonlocal count
count += 1
+ return (count % 2 == 0, x)
- return (count % 2 == 0, x) # type: ignore
assert count == 0
assert await f(1) == 1
assert count == 1
assert await f(1) == 1
assert count == 2
assert await f(2) == 2
assert count == 3
assert await f(3) == 3
assert count == 4
assert await f(3) == 3
assert count == 4
===========changed ref 1===========
# module: backend.tests.utils.test_alru_cache
class TestTemplate(AsyncTestCase):
def test_basic_alru_cache(self):
count = 0
@alru_cache()
+ async def f(x: int) -> Tuple[bool, int]:
- async def f(x: int) -> int:
nonlocal count
count += 1
+ return (True, x)
- return (True, x) # type: ignore
assert count == 0
assert await f(1) == 1
assert count == 1
assert await f(1) == 1
assert count == 1
assert await f(2) == 2
assert count == 2
assert await f(2) == 2
assert count == 2
assert await f(1) == 1
assert count == 2
===========changed ref 2===========
+ # module: backend.src.routers.auth.standalone
+
+
===========changed ref 3===========
+ # module: backend.src.processing.wrapped.calendar
+
+
===========changed ref 4===========
+ # module: backend.src.aggregation.layer0.follows
+
+
===========changed ref 5===========
+ # module: backend.src.routers.wrapped
+
+
===========changed ref 6===========
+ # module: backend.tests.aggregation.layer0
+
+
===========changed ref 7===========
+ # module: backend.src.routers.assets
+
+
===========changed ref 8===========
+ # module: backend.src.processing.user.commits
+
+
===========changed ref 9===========
+ # module: backend.src.processing.wrapped.timestamps
+
+
===========changed ref 10===========
+ # module: backend.src.processing.auth
+
+
===========changed ref 11===========
+ # module: backend.src.aggregation.layer1.user
+
+
===========changed ref 12===========
+ # module: backend.src.processing.wrapped.package
+
+
===========changed ref 13===========
+ # module: backend.src.routers.background
+
+
===========changed ref 14===========
+ # module: backend.src.aggregation.layer2.user
+
+
===========changed ref 15===========
+ # module: backend.tests.aggregation
+
+
===========changed ref 16===========
+ # module: backend.src.routers.auth
+
+
===========changed ref 17===========
+ # module: backend.src.processing.wrapped.repos
+
+
===========changed ref 18===========
+ # module: backend.src.render.error
+
+
===========changed ref 19===========
+ # module: backend.src.processing.wrapped.langs
+
+
===========changed ref 20===========
+ # module: backend.src.routers.auth.standalone
+ router = APIRouter()
+
===========changed ref 21===========
+ # module: backend.src.routers.wrapped
+ router = APIRouter()
+
===========changed ref 22===========
+ # module: backend.src.processing.wrapped.timestamps
+ MAX_ITEMS = 200
+
===========changed ref 23===========
+ # module: backend.src.routers.users.db
+ router = APIRouter()
+
===========changed ref 24===========
+ # module: backend.src.aggregation.layer1.user
+ s = requests.Session()
+
===========changed ref 25===========
+ # module: backend.src.render.error
+ THEME = "classic"
+
===========changed ref 26===========
+ # module: backend.src.aggregation.layer1
+ __all__ = ["query_user"]
+
===========changed ref 27===========
+ # module: backend.src.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
+ @async_fail_gracefully
+ async def check_valid_user(response: Response, user_id: str) -> str:
+ return await get_is_valid_user(user_id)
+
===========changed ref 28===========
+ # module: backend.src.processing.user.commits
+ dict_type = Dict[str, Union[str, int, float]]
+
===========changed ref 29===========
+ # module: backend.src.processing.auth
+ def set_user_key(code: str, user_key: str) -> str:
+ code_key_map[code] = user_key
+ return user_key
+
===========changed ref 30===========
+ # module: backend.src.processing.user.commits
+ def loc_metric_func(loc_metric: str, additions: int, deletions: int) -> int:
+ if loc_metric == "changed":
+ return additions + deletions
+ return additions - deletions
+
===========changed ref 31===========
+ # module: backend.src.processing.wrapped.repos
+ def _count_repo_loc(x: RepoContributionStats, metric: str) -> int:
+ return sum(_count_loc(lang, metric) for lang in x.languages.values())
+
===========changed ref 32===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/signup/private")
+ def redirect_private(user_id: Optional[str] = None) -> RedirectResponse:
+ return RedirectResponse(get_redirect_url(private=True, user_id=user_id))
+
===========changed ref 33===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/signup/public")
+ def redirect_public(user_id: Optional[str] = None) -> RedirectResponse:
+ return RedirectResponse(get_redirect_url(private=False, user_id=user_id))
+
===========changed ref 34===========
+ # module: backend.src.processing.wrapped.timestamps
+ def date_to_seconds_since_midnight(date: datetime) -> int:
+ return (date.hour * 60 * 60) + (date.minute * 60) + date.second
+
===========changed ref 35===========
+ # module: backend.src.processing.auth
+ def delete_user(user_id: str, user_key: str, use_user_key: bool = True) -> bool:
+ return await db_delete_user(user_id, user_key, use_user_key)
+
===========changed ref 36===========
<s> module: backend.src.routers.users.db
+ @router.get(
+ "/get/metadata/{user_id}",
+ status_code=status.HTTP_200_OK,
+ include_in_schema=False,
+ response_model=Dict[str, Any],
+ )
+ @async_fail_gracefully
+ async def get_db_public_user(
+ response: Response, user_id: str, no_cache: bool = False
+ ) -> Optional[PublicUserModel]:
+ return await db_get_public_user(user_id, no_cache=no_cache)
+
===========changed ref 37===========
+ # module: backend.src.routers
+ __all__ = ["asset_router", "auth_router", "dev_router", "user_router", "wrapped_router"]
+
===========changed ref 38===========
+ # module: backend.src.processing.wrapped.repos
+ def _count_loc(x: Language, metric: str) -> int:
+ if metric == "changed":
+ return x.additions + x.deletions
+ return x.additions - x.deletions
+
===========changed ref 39===========
+ # module: backend.src.processing.wrapped.langs
+ def _count_loc(x: Language, metric: str) -> int:
+ if metric == "changed":
+ return x.additions + x.deletions
+ return x.additions - x.deletions
+
===========changed ref 40===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/delete/{user_id}")
+ async def delete_account_auth(user_id: str) -> RedirectResponse:
+ return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
+ )
+
===========changed ref 41===========
+ # module: backend.src.routers.background
+ def run_in_background(task: UpdateUserBackgroundTask):
+ if isinstance(task, UpdateUserBackgroundTask): # type: ignore
+ await query_user(task.user_id, task.access_token, task.private_access)
+
|
backend.tests.utils.test_alru_cache/TestTemplate.test_alru_cache_with_ttl
|
Modified
|
avgupta456~github-trends
|
608321cbf41f097ab7fa5650114585efa6f85d29
|
Remove PubSub (#233)
|
<3>:<add> async def f(x: int) -> Tuple[bool, int]:
<del> async def f(x: int) -> int:
<6>:<add> return (True, x)
<del> return (True, x) # type: ignore
|
# module: backend.tests.utils.test_alru_cache
class TestTemplate(AsyncTestCase):
def test_alru_cache_with_ttl(self):
<0> count = 0
<1>
<2> @alru_cache(ttl=timedelta(milliseconds=1))
<3> async def f(x: int) -> int:
<4> nonlocal count
<5> count += 1
<6> return (True, x) # type: ignore
<7>
<8> assert count == 0
<9> assert await f(1) == 1
<10> assert count == 1
<11> assert await f(1) == 1
<12> assert count == 1
<13> await sleep(0.01)
<14> assert await f(1) == 1
<15> assert count == 2
<16>
|
===========changed ref 0===========
# module: backend.tests.utils.test_alru_cache
class TestTemplate(AsyncTestCase):
def test_alru_cache_with_maxsize(self):
count = 0
@alru_cache(max_size=2)
+ async def f(x: int) -> Tuple[bool, int]:
- async def f(x: int) -> int:
nonlocal count
count += 1
+ return (True, x)
- return (True, x) # type: ignore
assert count == 0
assert await f(1) == 1
assert count == 1
assert await f(2) == 2
assert count == 2
assert await f(3) == 3
assert count == 3
assert await f(1) == 1
assert count == 4
===========changed ref 1===========
# module: backend.tests.utils.test_alru_cache
class TestTemplate(AsyncTestCase):
def test_alru_cache_with_flag(self):
count = 0
@alru_cache()
+ async def f(x: int) -> Tuple[bool, int]:
- async def f(x: int) -> int:
nonlocal count
count += 1
+ return (count % 2 == 0, x)
- return (count % 2 == 0, x) # type: ignore
assert count == 0
assert await f(1) == 1
assert count == 1
assert await f(1) == 1
assert count == 2
assert await f(2) == 2
assert count == 3
assert await f(3) == 3
assert count == 4
assert await f(3) == 3
assert count == 4
===========changed ref 2===========
# module: backend.tests.utils.test_alru_cache
class TestTemplate(AsyncTestCase):
def test_basic_alru_cache(self):
count = 0
@alru_cache()
+ async def f(x: int) -> Tuple[bool, int]:
- async def f(x: int) -> int:
nonlocal count
count += 1
+ return (True, x)
- return (True, x) # type: ignore
assert count == 0
assert await f(1) == 1
assert count == 1
assert await f(1) == 1
assert count == 1
assert await f(2) == 2
assert count == 2
assert await f(2) == 2
assert count == 2
assert await f(1) == 1
assert count == 2
===========changed ref 3===========
+ # module: backend.src.routers.auth.standalone
+
+
===========changed ref 4===========
+ # module: backend.src.processing.wrapped.calendar
+
+
===========changed ref 5===========
+ # module: backend.src.aggregation.layer0.follows
+
+
===========changed ref 6===========
+ # module: backend.src.routers.wrapped
+
+
===========changed ref 7===========
+ # module: backend.tests.aggregation.layer0
+
+
===========changed ref 8===========
+ # module: backend.src.routers.assets
+
+
===========changed ref 9===========
+ # module: backend.src.processing.user.commits
+
+
===========changed ref 10===========
+ # module: backend.src.processing.wrapped.timestamps
+
+
===========changed ref 11===========
+ # module: backend.src.processing.auth
+
+
===========changed ref 12===========
+ # module: backend.src.aggregation.layer1.user
+
+
===========changed ref 13===========
+ # module: backend.src.processing.wrapped.package
+
+
===========changed ref 14===========
+ # module: backend.src.routers.background
+
+
===========changed ref 15===========
+ # module: backend.src.aggregation.layer2.user
+
+
===========changed ref 16===========
+ # module: backend.tests.aggregation
+
+
===========changed ref 17===========
+ # module: backend.src.routers.auth
+
+
===========changed ref 18===========
+ # module: backend.src.processing.wrapped.repos
+
+
===========changed ref 19===========
+ # module: backend.src.render.error
+
+
===========changed ref 20===========
+ # module: backend.src.processing.wrapped.langs
+
+
===========changed ref 21===========
+ # module: backend.src.routers.auth.standalone
+ router = APIRouter()
+
===========changed ref 22===========
+ # module: backend.src.routers.wrapped
+ router = APIRouter()
+
===========changed ref 23===========
+ # module: backend.src.processing.wrapped.timestamps
+ MAX_ITEMS = 200
+
===========changed ref 24===========
+ # module: backend.src.routers.users.db
+ router = APIRouter()
+
===========changed ref 25===========
+ # module: backend.src.aggregation.layer1.user
+ s = requests.Session()
+
===========changed ref 26===========
+ # module: backend.src.render.error
+ THEME = "classic"
+
===========changed ref 27===========
+ # module: backend.src.aggregation.layer1
+ __all__ = ["query_user"]
+
===========changed ref 28===========
+ # module: backend.src.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
+ @async_fail_gracefully
+ async def check_valid_user(response: Response, user_id: str) -> str:
+ return await get_is_valid_user(user_id)
+
===========changed ref 29===========
+ # module: backend.src.processing.user.commits
+ dict_type = Dict[str, Union[str, int, float]]
+
===========changed ref 30===========
+ # module: backend.src.processing.auth
+ def set_user_key(code: str, user_key: str) -> str:
+ code_key_map[code] = user_key
+ return user_key
+
===========changed ref 31===========
+ # module: backend.src.processing.user.commits
+ def loc_metric_func(loc_metric: str, additions: int, deletions: int) -> int:
+ if loc_metric == "changed":
+ return additions + deletions
+ return additions - deletions
+
===========changed ref 32===========
+ # module: backend.src.processing.wrapped.repos
+ def _count_repo_loc(x: RepoContributionStats, metric: str) -> int:
+ return sum(_count_loc(lang, metric) for lang in x.languages.values())
+
===========changed ref 33===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/signup/private")
+ def redirect_private(user_id: Optional[str] = None) -> RedirectResponse:
+ return RedirectResponse(get_redirect_url(private=True, user_id=user_id))
+
===========changed ref 34===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/signup/public")
+ def redirect_public(user_id: Optional[str] = None) -> RedirectResponse:
+ return RedirectResponse(get_redirect_url(private=False, user_id=user_id))
+
===========changed ref 35===========
+ # module: backend.src.processing.wrapped.timestamps
+ def date_to_seconds_since_midnight(date: datetime) -> int:
+ return (date.hour * 60 * 60) + (date.minute * 60) + date.second
+
===========changed ref 36===========
+ # module: backend.src.processing.auth
+ def delete_user(user_id: str, user_key: str, use_user_key: bool = True) -> bool:
+ return await db_delete_user(user_id, user_key, use_user_key)
+
===========changed ref 37===========
<s> module: backend.src.routers.users.db
+ @router.get(
+ "/get/metadata/{user_id}",
+ status_code=status.HTTP_200_OK,
+ include_in_schema=False,
+ response_model=Dict[str, Any],
+ )
+ @async_fail_gracefully
+ async def get_db_public_user(
+ response: Response, user_id: str, no_cache: bool = False
+ ) -> Optional[PublicUserModel]:
+ return await db_get_public_user(user_id, no_cache=no_cache)
+
===========changed ref 38===========
+ # module: backend.src.routers
+ __all__ = ["asset_router", "auth_router", "dev_router", "user_router", "wrapped_router"]
+
===========changed ref 39===========
+ # module: backend.src.processing.wrapped.repos
+ def _count_loc(x: Language, metric: str) -> int:
+ if metric == "changed":
+ return x.additions + x.deletions
+ return x.additions - x.deletions
+
|
backend.tests.utils.test_alru_cache/TestTemplate.test_alru_cache_with_no_cache
|
Modified
|
avgupta456~github-trends
|
608321cbf41f097ab7fa5650114585efa6f85d29
|
Remove PubSub (#233)
|
<3>:<add> async def f(x: int, no_cache: bool = False) -> Tuple[bool, int]:
<del> async def f(x: int, no_cache: bool = False) -> int:
<6>:<add> return (True, x)
<del> return (True, x) # type: ignore
|
# module: backend.tests.utils.test_alru_cache
class TestTemplate(AsyncTestCase):
def test_alru_cache_with_no_cache(self):
<0> count = 0
<1>
<2> @alru_cache()
<3> async def f(x: int, no_cache: bool = False) -> int:
<4> nonlocal count
<5> count += 1
<6> return (True, x) # type: ignore
<7>
<8> assert count == 0
<9> assert await f(1) == 1
<10> assert count == 1
<11> assert await f(1) == 1
<12> assert count == 1
<13> assert await f(2) == 2
<14> assert count == 2
<15> assert await f(2, no_cache=True) == 2
<16> assert count == 3
<17> assert await f(3) == 3
<18> assert count == 4
<19> assert await f(3, no_cache=False) == 3
<20> assert count == 4
<21>
|
===========changed ref 0===========
# module: backend.tests.utils.test_alru_cache
class TestTemplate(AsyncTestCase):
def test_alru_cache_with_ttl(self):
count = 0
@alru_cache(ttl=timedelta(milliseconds=1))
+ async def f(x: int) -> Tuple[bool, int]:
- async def f(x: int) -> int:
nonlocal count
count += 1
+ return (True, x)
- return (True, x) # type: ignore
assert count == 0
assert await f(1) == 1
assert count == 1
assert await f(1) == 1
assert count == 1
await sleep(0.01)
assert await f(1) == 1
assert count == 2
===========changed ref 1===========
# module: backend.tests.utils.test_alru_cache
class TestTemplate(AsyncTestCase):
def test_alru_cache_with_maxsize(self):
count = 0
@alru_cache(max_size=2)
+ async def f(x: int) -> Tuple[bool, int]:
- async def f(x: int) -> int:
nonlocal count
count += 1
+ return (True, x)
- return (True, x) # type: ignore
assert count == 0
assert await f(1) == 1
assert count == 1
assert await f(2) == 2
assert count == 2
assert await f(3) == 3
assert count == 3
assert await f(1) == 1
assert count == 4
===========changed ref 2===========
# module: backend.tests.utils.test_alru_cache
class TestTemplate(AsyncTestCase):
def test_alru_cache_with_flag(self):
count = 0
@alru_cache()
+ async def f(x: int) -> Tuple[bool, int]:
- async def f(x: int) -> int:
nonlocal count
count += 1
+ return (count % 2 == 0, x)
- return (count % 2 == 0, x) # type: ignore
assert count == 0
assert await f(1) == 1
assert count == 1
assert await f(1) == 1
assert count == 2
assert await f(2) == 2
assert count == 3
assert await f(3) == 3
assert count == 4
assert await f(3) == 3
assert count == 4
===========changed ref 3===========
# module: backend.tests.utils.test_alru_cache
class TestTemplate(AsyncTestCase):
def test_basic_alru_cache(self):
count = 0
@alru_cache()
+ async def f(x: int) -> Tuple[bool, int]:
- async def f(x: int) -> int:
nonlocal count
count += 1
+ return (True, x)
- return (True, x) # type: ignore
assert count == 0
assert await f(1) == 1
assert count == 1
assert await f(1) == 1
assert count == 1
assert await f(2) == 2
assert count == 2
assert await f(2) == 2
assert count == 2
assert await f(1) == 1
assert count == 2
===========changed ref 4===========
+ # module: backend.src.routers.auth.standalone
+
+
===========changed ref 5===========
+ # module: backend.src.processing.wrapped.calendar
+
+
===========changed ref 6===========
+ # module: backend.src.aggregation.layer0.follows
+
+
===========changed ref 7===========
+ # module: backend.src.routers.wrapped
+
+
===========changed ref 8===========
+ # module: backend.tests.aggregation.layer0
+
+
===========changed ref 9===========
+ # module: backend.src.routers.assets
+
+
===========changed ref 10===========
+ # module: backend.src.processing.user.commits
+
+
===========changed ref 11===========
+ # module: backend.src.processing.wrapped.timestamps
+
+
===========changed ref 12===========
+ # module: backend.src.processing.auth
+
+
===========changed ref 13===========
+ # module: backend.src.aggregation.layer1.user
+
+
===========changed ref 14===========
+ # module: backend.src.processing.wrapped.package
+
+
===========changed ref 15===========
+ # module: backend.src.routers.background
+
+
===========changed ref 16===========
+ # module: backend.src.aggregation.layer2.user
+
+
===========changed ref 17===========
+ # module: backend.tests.aggregation
+
+
===========changed ref 18===========
+ # module: backend.src.routers.auth
+
+
===========changed ref 19===========
+ # module: backend.src.processing.wrapped.repos
+
+
===========changed ref 20===========
+ # module: backend.src.render.error
+
+
===========changed ref 21===========
+ # module: backend.src.processing.wrapped.langs
+
+
===========changed ref 22===========
+ # module: backend.src.routers.auth.standalone
+ router = APIRouter()
+
===========changed ref 23===========
+ # module: backend.src.routers.wrapped
+ router = APIRouter()
+
===========changed ref 24===========
+ # module: backend.src.processing.wrapped.timestamps
+ MAX_ITEMS = 200
+
===========changed ref 25===========
+ # module: backend.src.routers.users.db
+ router = APIRouter()
+
===========changed ref 26===========
+ # module: backend.src.aggregation.layer1.user
+ s = requests.Session()
+
===========changed ref 27===========
+ # module: backend.src.render.error
+ THEME = "classic"
+
===========changed ref 28===========
+ # module: backend.src.aggregation.layer1
+ __all__ = ["query_user"]
+
===========changed ref 29===========
+ # module: backend.src.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
+ @async_fail_gracefully
+ async def check_valid_user(response: Response, user_id: str) -> str:
+ return await get_is_valid_user(user_id)
+
===========changed ref 30===========
+ # module: backend.src.processing.user.commits
+ dict_type = Dict[str, Union[str, int, float]]
+
===========changed ref 31===========
+ # module: backend.src.processing.auth
+ def set_user_key(code: str, user_key: str) -> str:
+ code_key_map[code] = user_key
+ return user_key
+
===========changed ref 32===========
+ # module: backend.src.processing.user.commits
+ def loc_metric_func(loc_metric: str, additions: int, deletions: int) -> int:
+ if loc_metric == "changed":
+ return additions + deletions
+ return additions - deletions
+
===========changed ref 33===========
+ # module: backend.src.processing.wrapped.repos
+ def _count_repo_loc(x: RepoContributionStats, metric: str) -> int:
+ return sum(_count_loc(lang, metric) for lang in x.languages.values())
+
===========changed ref 34===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/signup/private")
+ def redirect_private(user_id: Optional[str] = None) -> RedirectResponse:
+ return RedirectResponse(get_redirect_url(private=True, user_id=user_id))
+
===========changed ref 35===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/signup/public")
+ def redirect_public(user_id: Optional[str] = None) -> RedirectResponse:
+ return RedirectResponse(get_redirect_url(private=False, user_id=user_id))
+
===========changed ref 36===========
+ # module: backend.src.processing.wrapped.timestamps
+ def date_to_seconds_since_midnight(date: datetime) -> int:
+ return (date.hour * 60 * 60) + (date.minute * 60) + date.second
+
===========changed ref 37===========
+ # module: backend.src.processing.auth
+ def delete_user(user_id: str, user_key: str, use_user_key: bool = True) -> bool:
+ return await db_delete_user(user_id, user_key, use_user_key)
+
|
backend.src.data.mongo.user.get/get_public_user
|
Modified
|
avgupta456~github-trends
|
608321cbf41f097ab7fa5650114585efa6f85d29
|
Remove PubSub (#233)
|
<0>:<add> user: Optional[Dict[str, Any]] = await USERS.find_one({"user_id": user_id})
<del> user: Optional[Dict[str, Any]] = await USERS.find_one({"user_id": user_id}) # type: ignore
<1>:<del>
<4>:<add> return (False, None)
<del> return (False, None) # type: ignore
<5>:<add> try:
<add> return (True, PublicUserModel.model_validate(user))
<add> except (TypeError, KeyError, ValidationError):
<add> return (False, None)
<6>:<del> try:
<7>:<del> return (True, PublicUserModel.parse_obj(user)) # type: ignore
<8>:<del> except (TypeError, KeyError, ValidationError):
<9>:<del> return (False, None) # type: ignore
<10>:<del>
|
# module: backend.src.data.mongo.user.get
@alru_cache()
async def get_public_user(
user_id: str, no_cache: bool = False
+ ) -> Tuple[bool, Optional[PublicUserModel]]:
- ) -> Optional[PublicUserModel]:
<0> user: Optional[Dict[str, Any]] = await USERS.find_one({"user_id": user_id}) # type: ignore
<1>
<2> if user is None:
<3> # flag is false, don't cache
<4> return (False, None) # type: ignore
<5>
<6> try:
<7> return (True, PublicUserModel.parse_obj(user)) # type: ignore
<8> except (TypeError, KeyError, ValidationError):
<9> return (False, None) # type: ignore
<10>
|
===========unchanged ref 0===========
at: src.data.mongo.main
USERS = DB.users
at: src.utils.alru_cache
alru_cache(max_size: int=128, ttl: timedelta=timedelta(minutes=1))
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
+ # module: backend.src.processing.wrapped.time
+
+
===========changed ref 1===========
+ # module: backend.src.models.svg
+
+
===========changed ref 2===========
+ # module: backend.src.processing.wrapped.numeric
+
+
===========changed ref 3===========
+ # module: backend.src.routers.auth.standalone
+
+
===========changed ref 4===========
+ # module: backend.src.processing.wrapped.calendar
+
+
===========changed ref 5===========
+ # module: backend.src.aggregation.layer0.follows
+
+
===========changed ref 6===========
+ # module: backend.src.routers.wrapped
+
+
===========changed ref 7===========
+ # module: backend.tests.aggregation.layer0
+
+
===========changed ref 8===========
+ # module: backend.src.routers.assets
+
+
===========changed ref 9===========
+ # module: backend.src.processing.user.commits
+
+
===========changed ref 10===========
+ # module: backend.src.processing.wrapped.timestamps
+
+
===========changed ref 11===========
+ # module: backend.src.processing.auth
+
+
===========changed ref 12===========
+ # module: backend.src.aggregation.layer1.user
+
+
===========changed ref 13===========
+ # module: backend.src.processing.wrapped.package
+
+
===========changed ref 14===========
+ # module: backend.src.routers.background
+
+
===========changed ref 15===========
+ # module: backend.src.aggregation.layer2.user
+
+
===========changed ref 16===========
+ # module: backend.tests.aggregation
+
+
===========changed ref 17===========
+ # module: backend.src.routers.auth
+
+
===========changed ref 18===========
+ # module: backend.src.processing.wrapped.repos
+
+
===========changed ref 19===========
+ # module: backend.src.render.error
+
+
===========changed ref 20===========
+ # module: backend.src.processing.wrapped.langs
+
+
===========changed ref 21===========
+ # module: backend.src.routers.auth.standalone
+ router = APIRouter()
+
===========changed ref 22===========
+ # module: backend.src.routers.wrapped
+ router = APIRouter()
+
===========changed ref 23===========
+ # module: backend.src.processing.wrapped.timestamps
+ MAX_ITEMS = 200
+
===========changed ref 24===========
+ # module: backend.src.routers.users.db
+ router = APIRouter()
+
===========changed ref 25===========
+ # module: backend.src.aggregation.layer1.user
+ s = requests.Session()
+
===========changed ref 26===========
+ # module: backend.tests.aggregation.layer0.test_contributions
+ # TODO: Add further validation
+
===========changed ref 27===========
+ # module: backend.src.render.error
+ THEME = "classic"
+
===========changed ref 28===========
+ # module: backend.src.aggregation.layer1
+ __all__ = ["query_user"]
+
===========changed ref 29===========
+ # module: backend.src.aggregation.layer0
+ __all__ = ["get_user_data"]
+
===========changed ref 30===========
+ # module: backend.src.processing.wrapped
+ __all__ = ["query_wrapped_user"]
+
===========changed ref 31===========
+ # module: backend.src.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
+ @async_fail_gracefully
+ async def check_valid_user(response: Response, user_id: str) -> str:
+ return await get_is_valid_user(user_id)
+
===========changed ref 32===========
+ # module: backend.src.processing.user.commits
+ dict_type = Dict[str, Union[str, int, float]]
+
===========changed ref 33===========
+ # module: backend.src.models.svg
+ class RepoLanguage(BaseModel):
+ lang: str
+ color: Optional[str]
+ loc: int
+
===========changed ref 34===========
+ # module: backend.src.processing.auth
+ def set_user_key(code: str, user_key: str) -> str:
+ code_key_map[code] = user_key
+ return user_key
+
===========changed ref 35===========
+ # module: backend.src.processing.user.commits
+ def loc_metric_func(loc_metric: str, additions: int, deletions: int) -> int:
+ if loc_metric == "changed":
+ return additions + deletions
+ return additions - deletions
+
===========changed ref 36===========
+ # module: backend.src.processing.wrapped.repos
+ def _count_repo_loc(x: RepoContributionStats, metric: str) -> int:
+ return sum(_count_loc(lang, metric) for lang in x.languages.values())
+
===========changed ref 37===========
+ # module: backend.src.models.svg
+ class LanguageStats(BaseModel):
+ lang: str
+ loc: int
+ percent: float
+ color: Optional[str]
+
===========changed ref 38===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/signup/private")
+ def redirect_private(user_id: Optional[str] = None) -> RedirectResponse:
+ return RedirectResponse(get_redirect_url(private=True, user_id=user_id))
+
===========changed ref 39===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/signup/public")
+ def redirect_public(user_id: Optional[str] = None) -> RedirectResponse:
+ return RedirectResponse(get_redirect_url(private=False, user_id=user_id))
+
===========changed ref 40===========
+ # module: backend.src.processing.user
+ __all__ = ["get_top_languages", "get_top_repos", "svg_base"]
+
===========changed ref 41===========
+ # module: backend.src.models.svg
+ class RepoStats(BaseModel):
+ repo: str
+ private: bool
+ langs: List[RepoLanguage]
+ loc: int
+
===========changed ref 42===========
+ # module: backend.src.processing.wrapped.timestamps
+ def date_to_seconds_since_midnight(date: datetime) -> int:
+ return (date.hour * 60 * 60) + (date.minute * 60) + date.second
+
===========changed ref 43===========
+ # module: backend.src.processing.auth
+ def delete_user(user_id: str, user_key: str, use_user_key: bool = True) -> bool:
+ return await db_delete_user(user_id, user_key, use_user_key)
+
===========changed ref 44===========
<s> module: backend.src.routers.users.db
+ @router.get(
+ "/get/metadata/{user_id}",
+ status_code=status.HTTP_200_OK,
+ include_in_schema=False,
+ response_model=Dict[str, Any],
+ )
+ @async_fail_gracefully
+ async def get_db_public_user(
+ response: Response, user_id: str, no_cache: bool = False
+ ) -> Optional[PublicUserModel]:
+ return await db_get_public_user(user_id, no_cache=no_cache)
+
===========changed ref 45===========
+ # module: backend.src.routers
+ __all__ = ["asset_router", "auth_router", "dev_router", "user_router", "wrapped_router"]
+
===========changed ref 46===========
+ # module: backend.src.processing.wrapped.repos
+ def _count_loc(x: Language, metric: str) -> int:
+ if metric == "changed":
+ return x.additions + x.deletions
+ return x.additions - x.deletions
+
===========changed ref 47===========
+ # module: backend.src.processing.wrapped.langs
+ def _count_loc(x: Language, metric: str) -> int:
+ if metric == "changed":
+ return x.additions + x.deletions
+ return x.additions - x.deletions
+
===========changed ref 48===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/delete/{user_id}")
+ async def delete_account_auth(user_id: str) -> RedirectResponse:
+ return RedirectResponse(
+ get_redirect_url(prefix=f"delete/{user_id}", private=False, user_id=user_id)
+ )
+
===========changed ref 49===========
+ # module: backend.src.routers.background
+ def run_in_background(task: UpdateUserBackgroundTask):
+ if isinstance(task, UpdateUserBackgroundTask): # type: ignore
+ await query_user(task.user_id, task.access_token, task.private_access)
+
|
backend.src.data.mongo.user.get/get_full_user
|
Modified
|
avgupta456~github-trends
|
608321cbf41f097ab7fa5650114585efa6f85d29
|
Remove PubSub (#233)
|
<0>:<add> user: Optional[Dict[str, Any]] = await USERS.find_one({"user_id": user_id})
<del> user: Optional[Dict[str, Any]] = await USERS.find_one({"user_id": user_id}) # type: ignore
<4>:<add> return (False, None)
<del> return (False, None) # type: ignore
<7>:<add> return (True, FullUserModel.model_validate(user))
<del> return (True, FullUserModel.parse_obj(user)) # type: ignore
<9>:<add> return (False, None)
<del> return (False, None) # type: ignore
|
# module: backend.src.data.mongo.user.get
@alru_cache()
async def get_full_user(
user_id: str, no_cache: bool = False
+ ) -> Tuple[bool, Optional[FullUserModel]]:
- ) -> Optional[FullUserModel]:
<0> user: Optional[Dict[str, Any]] = await USERS.find_one({"user_id": user_id}) # type: ignore
<1>
<2> if user is None:
<3> # flag is false, don't cache
<4> return (False, None) # type: ignore
<5>
<6> try:
<7> return (True, FullUserModel.parse_obj(user)) # type: ignore
<8> except (TypeError, KeyError, ValidationError):
<9> return (False, None) # type: ignore
<10>
|
===========unchanged ref 0===========
at: src.data.mongo.main
USERS = DB.users
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.data.mongo.user.get
@alru_cache()
async def get_public_user(
user_id: str, no_cache: bool = False
+ ) -> Tuple[bool, Optional[PublicUserModel]]:
- ) -> Optional[PublicUserModel]:
+ user: Optional[Dict[str, Any]] = await USERS.find_one({"user_id": user_id})
- user: Optional[Dict[str, Any]] = await USERS.find_one({"user_id": user_id}) # type: ignore
-
if user is None:
# flag is false, don't cache
+ return (False, None)
- return (False, None) # type: ignore
+ try:
+ return (True, PublicUserModel.model_validate(user))
+ except (TypeError, KeyError, ValidationError):
+ return (False, None)
- try:
- return (True, PublicUserModel.parse_obj(user)) # type: ignore
- except (TypeError, KeyError, ValidationError):
- return (False, None) # type: ignore
-
===========changed ref 1===========
+ # module: backend.src.processing.wrapped.time
+
+
===========changed ref 2===========
+ # module: backend.src.models.svg
+
+
===========changed ref 3===========
+ # module: backend.src.processing.wrapped.numeric
+
+
===========changed ref 4===========
+ # module: backend.src.routers.auth.standalone
+
+
===========changed ref 5===========
+ # module: backend.src.processing.wrapped.calendar
+
+
===========changed ref 6===========
+ # module: backend.src.aggregation.layer0.follows
+
+
===========changed ref 7===========
+ # module: backend.src.routers.wrapped
+
+
===========changed ref 8===========
+ # module: backend.tests.aggregation.layer0
+
+
===========changed ref 9===========
+ # module: backend.src.routers.assets
+
+
===========changed ref 10===========
+ # module: backend.src.processing.user.commits
+
+
===========changed ref 11===========
+ # module: backend.src.processing.wrapped.timestamps
+
+
===========changed ref 12===========
+ # module: backend.src.processing.auth
+
+
===========changed ref 13===========
+ # module: backend.src.aggregation.layer1.user
+
+
===========changed ref 14===========
+ # module: backend.src.processing.wrapped.package
+
+
===========changed ref 15===========
+ # module: backend.src.routers.background
+
+
===========changed ref 16===========
+ # module: backend.src.aggregation.layer2.user
+
+
===========changed ref 17===========
+ # module: backend.tests.aggregation
+
+
===========changed ref 18===========
+ # module: backend.src.routers.auth
+
+
===========changed ref 19===========
+ # module: backend.src.processing.wrapped.repos
+
+
===========changed ref 20===========
+ # module: backend.src.render.error
+
+
===========changed ref 21===========
+ # module: backend.src.processing.wrapped.langs
+
+
===========changed ref 22===========
+ # module: backend.src.routers.auth.standalone
+ router = APIRouter()
+
===========changed ref 23===========
+ # module: backend.src.routers.wrapped
+ router = APIRouter()
+
===========changed ref 24===========
+ # module: backend.src.processing.wrapped.timestamps
+ MAX_ITEMS = 200
+
===========changed ref 25===========
+ # module: backend.src.routers.users.db
+ router = APIRouter()
+
===========changed ref 26===========
+ # module: backend.src.aggregation.layer1.user
+ s = requests.Session()
+
===========changed ref 27===========
+ # module: backend.tests.aggregation.layer0.test_contributions
+ # TODO: Add further validation
+
===========changed ref 28===========
+ # module: backend.src.render.error
+ THEME = "classic"
+
===========changed ref 29===========
+ # module: backend.src.aggregation.layer1
+ __all__ = ["query_user"]
+
===========changed ref 30===========
+ # module: backend.src.aggregation.layer0
+ __all__ = ["get_user_data"]
+
===========changed ref 31===========
+ # module: backend.src.processing.wrapped
+ __all__ = ["query_wrapped_user"]
+
===========changed ref 32===========
+ # module: backend.src.routers.wrapped
+ @router.get(
+ "/valid/{user_id}", status_code=status.HTTP_200_OK, response_model=Dict[str, Any]
+ )
+ @async_fail_gracefully
+ async def check_valid_user(response: Response, user_id: str) -> str:
+ return await get_is_valid_user(user_id)
+
===========changed ref 33===========
+ # module: backend.src.processing.user.commits
+ dict_type = Dict[str, Union[str, int, float]]
+
===========changed ref 34===========
+ # module: backend.src.models.svg
+ class RepoLanguage(BaseModel):
+ lang: str
+ color: Optional[str]
+ loc: int
+
===========changed ref 35===========
+ # module: backend.src.processing.auth
+ def set_user_key(code: str, user_key: str) -> str:
+ code_key_map[code] = user_key
+ return user_key
+
===========changed ref 36===========
+ # module: backend.src.processing.user.commits
+ def loc_metric_func(loc_metric: str, additions: int, deletions: int) -> int:
+ if loc_metric == "changed":
+ return additions + deletions
+ return additions - deletions
+
===========changed ref 37===========
+ # module: backend.src.processing.wrapped.repos
+ def _count_repo_loc(x: RepoContributionStats, metric: str) -> int:
+ return sum(_count_loc(lang, metric) for lang in x.languages.values())
+
===========changed ref 38===========
+ # module: backend.src.models.svg
+ class LanguageStats(BaseModel):
+ lang: str
+ loc: int
+ percent: float
+ color: Optional[str]
+
===========changed ref 39===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/signup/private")
+ def redirect_private(user_id: Optional[str] = None) -> RedirectResponse:
+ return RedirectResponse(get_redirect_url(private=True, user_id=user_id))
+
===========changed ref 40===========
+ # module: backend.src.routers.auth.standalone
+ @router.get("/signup/public")
+ def redirect_public(user_id: Optional[str] = None) -> RedirectResponse:
+ return RedirectResponse(get_redirect_url(private=False, user_id=user_id))
+
===========changed ref 41===========
+ # module: backend.src.processing.user
+ __all__ = ["get_top_languages", "get_top_repos", "svg_base"]
+
===========changed ref 42===========
+ # module: backend.src.models.svg
+ class RepoStats(BaseModel):
+ repo: str
+ private: bool
+ langs: List[RepoLanguage]
+ loc: int
+
===========changed ref 43===========
+ # module: backend.src.processing.wrapped.timestamps
+ def date_to_seconds_since_midnight(date: datetime) -> int:
+ return (date.hour * 60 * 60) + (date.minute * 60) + date.second
+
===========changed ref 44===========
+ # module: backend.src.processing.auth
+ def delete_user(user_id: str, user_key: str, use_user_key: bool = True) -> bool:
+ return await db_delete_user(user_id, user_key, use_user_key)
+
===========changed ref 45===========
<s> module: backend.src.routers.users.db
+ @router.get(
+ "/get/metadata/{user_id}",
+ status_code=status.HTTP_200_OK,
+ include_in_schema=False,
+ response_model=Dict[str, Any],
+ )
+ @async_fail_gracefully
+ async def get_db_public_user(
+ response: Response, user_id: str, no_cache: bool = False
+ ) -> Optional[PublicUserModel]:
+ return await db_get_public_user(user_id, no_cache=no_cache)
+
===========changed ref 46===========
+ # module: backend.src.routers
+ __all__ = ["asset_router", "auth_router", "dev_router", "user_router", "wrapped_router"]
+
===========changed ref 47===========
+ # module: backend.src.processing.wrapped.repos
+ def _count_loc(x: Language, metric: str) -> int:
+ if metric == "changed":
+ return x.additions + x.deletions
+ return x.additions - x.deletions
+
|
backend.src.utils.utils/use_time_range
|
Modified
|
avgupta456~github-trends
|
6083f7c9945a8bb61073e67ac255fc0fffce7357
|
All Time Cards (#238)
|
<5>:<add> "all_time": (365 * 10, "All Time"),
|
# module: backend.src.utils.utils
# returns start date, end date, string representing time range
def use_time_range(
time_range: str, start_date: date, end_date: date
) -> Tuple[date, date, str]:
<0> duration_options = {
<1> "one_month": (30, "Past 1 Month"),
<2> "three_months": (90, "Past 3 Months"),
<3> "six_months": (180, "Past 6 Months"),
<4> "one_year": (365, "Past 1 Year"),
<5> }
<6>
<7> start_str = start_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
<8> end_str = end_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
<9> if end_date == date.today():
<10> end_str = "Present"
<11> time_str = f"{start_str} - {end_str}"
<12>
<13> if time_range in duration_options:
<14> days, time_str = duration_options[time_range]
<15> end_date = date.today()
<16> start_date = date.today() - timedelta(days)
<17>
<18> return start_date, end_date, time_str
<19>
|
===========unchanged ref 0===========
at: datetime
timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...)
date()
at: datetime.date
__slots__ = '_year', '_month', '_day', '_hashcode'
today() -> _S
strftime(fmt: _Text) -> str
__str__ = isoformat
__radd__ = __add__
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
|
backend.src.render.top_repos/get_top_repos_svg
|
Modified
|
avgupta456~github-trends
|
6083f7c9945a8bb61073e67ac255fc0fffce7357
|
All Time Cards (#238)
|
<3>:<add> if not complete:
<add> subheader += " | Incomplete (refresh to update)"
<add> elif commits_excluded > 50:
<del> if commits_excluded > 50:
<35>:<add> langs = defaultdict(int)
<del> langs = {}
<38>:<add> langs[(lang.lang, lang.color)] += lang.loc
<del> langs[lang.lang] = lang.color
<39>:<add> langs = sorted(langs.items(), key=lambda x: x[1], reverse=True)
<add> langs = [lang[0] for lang in langs[:6]]
<del> langs = list(langs
|
# module: backend.src.render.top_repos
def get_top_repos_svg(
data: List[RepoStats],
time_str: str,
loc_metric: str,
+ complete: bool,
commits_excluded: int,
use_animation: bool,
theme: str,
) -> Drawing:
<0> header = "Most Contributed Repositories"
<1> subheader = time_str
<2> subheader += " | " + ("LOC Changed" if loc_metric == "changed" else "LOC Added")
<3> if commits_excluded > 50:
<4> subheader += f" | {commits_excluded} commits excluded"
<5>
<6> if len(data) == 0:
<7> return get_no_data_svg(header, subheader)
<8>
<9> d, dp = get_template(
<10> width=300,
<11> height=285,
<12> padding=20,
<13> header_text=header,
<14> subheader_text=subheader,
<15> use_animation=use_animation,
<16> debug=False,
<17> theme=theme,
<18> )
<19>
<20> dataset: List[Tuple[str, str, List[Tuple[float, str]]]] = []
<21> total = max(x.loc for x in data)
<22> for x in data[:4]:
<23> data_row = [
<24> (100 * lang.loc / total, lang.color)
<25> for lang in sorted(x.langs, key=lambda x: x.loc, reverse=True)
<26> ]
<27>
<28> name = "private/repository" if x.private else x.repo
<29> dataset.append((name, format_number(x.loc), data_row))
<30>
<31> dp.add(
<32> get_bar_section(d=d, dataset=dataset, theme=theme, padding=45, bar_width=195)
<33> )
<34>
<35> langs = {}
<36> for x in data[:4]:
<37> for lang in x.langs:
<38> langs[lang.lang] = lang.color
<39> langs = list(langs</s>
|
===========below chunk 0===========
# module: backend.src.render.top_repos
def get_top_repos_svg(
data: List[RepoStats],
time_str: str,
loc_metric: str,
+ complete: bool,
commits_excluded: int,
use_animation: bool,
theme: str,
) -> Drawing:
# offset: 1
columns = {1: 1, 2: 2, 3: 3, 4: 2, 5: 3, 6: 3}[len(langs)]
padding = 215 + (10 if columns == len(langs) else 0)
dp.add(
get_lang_name_section(
d=d, data=langs, theme=theme, columns=columns, padding=padding
)
)
d.add(dp)
return d
===========unchanged ref 0===========
at: collections
defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]])
defaultdict(default_factory: Optional[Callable[[], _VT]])
defaultdict(**kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT)
defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT])
at: src.models.svg.RepoLanguage
lang: str
color: Optional[str]
loc: int
at: src.models.svg.RepoStats
repo: str
private: bool
langs: List[RepoLanguage]
loc: int
at: src.render.error
get_no_data_svg(header: str, subheader: str) -> Drawing
at: src.render.template
get_template(width: int, height: int, padding: int, header_text: str, subheader_text: str, theme: str, use_animation: bool=True, debug: bool=False) -> Tuple[Drawing, Group]
get_bar_section(d: Drawing, dataset: List[Tuple[str, str, List[Tuple[float, str]]]], theme: str, padding: int=45, bar_width: int=210) -> Group
get_lang_name_section(d: Drawing, data: List[Tuple[str, str]], theme: str, columns: int=2, padding: int=80) -> Group
at: src.utils.utils
format_number(num: int) -> str
===========unchanged ref 1===========
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.utils.utils
# returns start date, end date, string representing time range
def use_time_range(
time_range: str, start_date: date, end_date: date
) -> Tuple[date, date, str]:
duration_options = {
"one_month": (30, "Past 1 Month"),
"three_months": (90, "Past 3 Months"),
"six_months": (180, "Past 6 Months"),
"one_year": (365, "Past 1 Year"),
+ "all_time": (365 * 10, "All Time"),
}
start_str = start_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
end_str = end_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
if end_date == date.today():
end_str = "Present"
time_str = f"{start_str} - {end_str}"
if time_range in duration_options:
days, time_str = duration_options[time_range]
end_date = date.today()
start_date = date.today() - timedelta(days)
return start_date, end_date, time_str
|
backend.src.processing.auth/authenticate
|
Modified
|
avgupta456~github-trends
|
6083f7c9945a8bb61073e67ac255fc0fffce7357
|
All Time Cards (#238)
|
<23>:<add> start_date=None,
<add> end_date=None,
<30>:<add> start_date=None,
<add> end_date=None,
|
# module: backend.src.processing.auth
def authenticate(
code: str, private_access: bool
) -> Tuple[str, Optional[UpdateUserBackgroundTask]]:
<0> user_id, access_token = await github_authenticate(code)
<1>
<2> curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
<3>
<4> raw_user: Dict[str, Any] = {
<5> "user_id": user_id,
<6> "access_token": access_token,
<7> "user_key": code_key_map.get(code, None),
<8> "private_access": private_access,
<9> }
<10>
<11> background_task = None
<12> if curr_user is not None:
<13> curr_private_access = curr_user.private_access
<14> new_private_access = curr_private_access or private_access
<15> raw_user["private_access"] = new_private_access
<16>
<17> if new_private_access != curr_private_access:
<18> # new private access status
<19> background_task = UpdateUserBackgroundTask(
<20> user_id=user_id,
<21> access_token=access_token,
<22> private_access=new_private_access,
<23> )
<24> else:
<25> # first time sign up
<26> background_task = UpdateUserBackgroundTask(
<27> user_id=user_id,
<28> access_token=access_token,
<29> private_access=private_access,
<30> )
<31>
<32> await db_update_user(user_id, raw_user)
<33> return user_id, background_task
<34>
|
===========unchanged ref 0===========
at: backend.src.processing.auth
code_key_map: Dict[str, str] = {}
at: src.data.github.auth.main
authenticate(code: str) -> Tuple[str, str]
at: src.data.mongo.user.get
get_public_user(user_id: str, no_cache: bool=False) -> Tuple[bool, Optional[PublicUserModel]]
at: src.data.mongo.user.models.PublicUserModel
user_id: str
access_token: str
private_access: Optional[bool]
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
Dict = _alias(dict, 2, inst=False, name='Dict')
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
# module: backend.src.utils.utils
# returns start date, end date, string representing time range
def use_time_range(
time_range: str, start_date: date, end_date: date
) -> Tuple[date, date, str]:
duration_options = {
"one_month": (30, "Past 1 Month"),
"three_months": (90, "Past 3 Months"),
"six_months": (180, "Past 6 Months"),
"one_year": (365, "Past 1 Year"),
+ "all_time": (365 * 10, "All Time"),
}
start_str = start_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
end_str = end_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
if end_date == date.today():
end_str = "Present"
time_str = f"{start_str} - {end_str}"
if time_range in duration_options:
days, time_str = duration_options[time_range]
end_date = date.today()
start_date = date.today() - timedelta(days)
return start_date, end_date, time_str
===========changed ref 1===========
# module: backend.src.render.top_repos
def get_top_repos_svg(
data: List[RepoStats],
time_str: str,
loc_metric: str,
+ complete: bool,
commits_excluded: int,
use_animation: bool,
theme: str,
) -> Drawing:
header = "Most Contributed Repositories"
subheader = time_str
subheader += " | " + ("LOC Changed" if loc_metric == "changed" else "LOC Added")
+ if not complete:
+ subheader += " | Incomplete (refresh to update)"
+ elif commits_excluded > 50:
- if commits_excluded > 50:
subheader += f" | {commits_excluded} commits excluded"
if len(data) == 0:
return get_no_data_svg(header, subheader)
d, dp = get_template(
width=300,
height=285,
padding=20,
header_text=header,
subheader_text=subheader,
use_animation=use_animation,
debug=False,
theme=theme,
)
dataset: List[Tuple[str, str, List[Tuple[float, str]]]] = []
total = max(x.loc for x in data)
for x in data[:4]:
data_row = [
(100 * lang.loc / total, lang.color)
for lang in sorted(x.langs, key=lambda x: x.loc, reverse=True)
]
name = "private/repository" if x.private else x.repo
dataset.append((name, format_number(x.loc), data_row))
dp.add(
get_bar_section(d=d, dataset=dataset, theme=theme, padding=45, bar_width=195)
)
+ langs = defaultdict(int)
- langs = {}
for x in data[:4]:
for lang in x.langs:
+ langs[(lang.lang, lang.color)] += lang.</s>
===========changed ref 2===========
# module: backend.src.render.top_repos
def get_top_repos_svg(
data: List[RepoStats],
time_str: str,
loc_metric: str,
+ complete: bool,
commits_excluded: int,
use_animation: bool,
theme: str,
) -> Drawing:
# offset: 1
<s>[:4]:
for lang in x.langs:
+ langs[(lang.lang, lang.color)] += lang.loc
- langs[lang.lang] = lang.color
+ langs = sorted(langs.items(), key=lambda x: x[1], reverse=True)
+ langs = [lang[0] for lang in langs[:6]]
- langs = list(langs.items())[:6]
columns = {1: 1, 2: 2, 3: 3, 4: 2, 5: 3, 6: 3}[len(langs)]
padding = 215 + (10 if columns == len(langs) else 0)
dp.add(
get_lang_name_section(
d=d, data=langs, theme=theme, columns=columns, padding=padding
)
)
d.add(dp)
return d
|
backend.src.render.template/get_bar_section
|
Modified
|
avgupta456~github-trends
|
6083f7c9945a8bb61073e67ac255fc0fffce7357
|
All Time Cards (#238)
|
<20>:<add> diff = max(0, 300 / bar_width - data_row[-1][0])
<22>:<add> if j == 0:
<add> percent -= diff
<add> elif j == total_items - 1:
<add> percent += diff
<del> percent = max(300 / bar_width, percent)
|
# module: backend.src.render.template
def get_bar_section(
d: Drawing,
dataset: List[Tuple[str, str, List[Tuple[float, str]]]],
theme: str,
padding: int = 45,
bar_width: int = 210,
) -> Group:
<0> section = Group(transform=f"translate(0, {padding})")
<1> for i, (top_text, right_text, data_row) in enumerate(dataset):
<2> translate = f"translate(0, {str(40 * i)})"
<3> row = Group(transform=translate)
<4> row.add(d.text(top_text, insert=(2, 15), class_=f"{theme}-lang-name"))
<5> row.add(
<6> d.text(right_text, insert=(bar_width + 10, 33), class_=f"{theme}-lang-name")
<7> )
<8>
<9> progress = Drawing(width=str(bar_width), x="0", y="25")
<10> progress.add(
<11> d.rect(
<12> size=(bar_width, 8),
<13> insert=(0, 0),
<14> rx=5,
<15> ry=5,
<16> fill=themes[theme]["bar_color"],
<17> )
<18> )
<19> total_percent, total_items = 0, len(data_row)
<20> for j, (percent, color) in enumerate(data_row):
<21> color = color or DEFAULT_COLOR
<22> percent = max(300 / bar_width, percent)
<23> bar_percent = bar_width * percent / 100
<24> bar_total = bar_width * total_percent / 100
<25> box_size, insert = (bar_percent, 8), (bar_total, 0)
<26> progress.add(d.rect(size=box_size, insert=insert, rx=5, ry=5, fill=color))
<27>
<28> width = min(bar_percent / 2, 5)
<29> if total_items > 1:
<30> box_left, box_right = j ></s>
|
===========below chunk 0===========
# module: backend.src.render.template
def get_bar_section(
d: Drawing,
dataset: List[Tuple[str, str, List[Tuple[float, str]]]],
theme: str,
padding: int = 45,
bar_width: int = 210,
) -> Group:
# offset: 1
box_size, insert = bar_percent - 2 * width, bar_total + width
if box_left:
box_size += width
insert -= width
if box_right:
box_size += width
progress.add(d.rect(size=(box_size, 8), insert=(insert, 0), fill=color))
total_percent += percent
row.add(progress)
section.add(row)
return section
===========unchanged ref 0===========
at: src.constants
DEFAULT_COLOR = "#858585"
===========unchanged ref 1===========
at: src.render.style
themes = {
"classic": {
"header_color": "#2f80ed",
"subheader_color": "#666",
"text_color": "#333",
"bg_color": "#fffefe",
"border_color": "#e4e2e2",
"bar_color": "#ddd",
},
"dark": {
"header_color": "#fff",
"subheader_color": "#9f9f9f",
"text_color": "#9f9f9f",
"bg_color": "#151515",
"border_color": "#e4e2e2",
"bar_color": "#333",
},
"bright_lights": {
"header_color": "#fff",
"subheader_color": "#0e86d4",
"text_color": "#b1d4e0",
"bg_color": "#003060",
"border_color": "#0e86d4",
"bar_color": "#ddd",
},
"rosettes": {
"header_color": "#fff",
"subheader_color": "#b6e2d3",
"text_color": "#fae8e0",
"bg_color": "#ef7c8e",
"border_color": "#b6e2d3",
"bar_color": "#ddd",
},
"ferns": {
"header_color": "#116530",
"subheader_color": "#18a558",
"text_color": "#116530",
"bg_color": "#a3ebb1",
"border_color": "#21b6a8",
"bar_color": "#ddd",
},
"synthwaves": {
"header_color": "#e2e9ec",
"subheader_color": "#e5289e",
"text_color": "#ef8539",
"bg_color": "#2b2</s>
===========unchanged ref 2===========
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.models.background
class UpdateUserBackgroundTask(BaseModel):
user_id: str
access_token: Optional[str]
private_access: bool
+ start_date: Optional[date]
+ end_date: Optional[date]
===========changed ref 1===========
# module: backend.src.utils.utils
# returns start date, end date, string representing time range
def use_time_range(
time_range: str, start_date: date, end_date: date
) -> Tuple[date, date, str]:
duration_options = {
"one_month": (30, "Past 1 Month"),
"three_months": (90, "Past 3 Months"),
"six_months": (180, "Past 6 Months"),
"one_year": (365, "Past 1 Year"),
+ "all_time": (365 * 10, "All Time"),
}
start_str = start_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
end_str = end_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
if end_date == date.today():
end_str = "Present"
time_str = f"{start_str} - {end_str}"
if time_range in duration_options:
days, time_str = duration_options[time_range]
end_date = date.today()
start_date = date.today() - timedelta(days)
return start_date, end_date, time_str
===========changed ref 2===========
# module: backend.src.processing.auth
def authenticate(
code: str, private_access: bool
) -> Tuple[str, Optional[UpdateUserBackgroundTask]]:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
"private_access": private_access,
}
background_task = None
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
# new private access status
background_task = UpdateUserBackgroundTask(
user_id=user_id,
access_token=access_token,
private_access=new_private_access,
+ start_date=None,
+ end_date=None,
)
else:
# first time sign up
background_task = UpdateUserBackgroundTask(
user_id=user_id,
access_token=access_token,
private_access=private_access,
+ start_date=None,
+ end_date=None,
)
await db_update_user(user_id, raw_user)
return user_id, background_task
|
backend.src.routers.background/run_in_background
|
Modified
|
avgupta456~github-trends
|
6083f7c9945a8bb61073e67ac255fc0fffce7357
|
All Time Cards (#238)
|
<1>:<add> inputs = {
<add> "user_id": task.user_id,
<add> "access_token": task.access_token,
<add> "private_access": task.private_access,
<add> "start_date": task.start_date,
<add> "end_date": task.end_date,
<add> }
<del> await query_user(task.user_id, task.access_token, task.private_access)
|
# module: backend.src.routers.background
def run_in_background(task: UpdateUserBackgroundTask):
<0> if isinstance(task, UpdateUserBackgroundTask): # type: ignore
<1> await query_user(task.user_id, task.access_token, task.private_access)
<2>
|
===========unchanged ref 0===========
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.models.background
class UpdateUserBackgroundTask(BaseModel):
user_id: str
access_token: Optional[str]
private_access: bool
+ start_date: Optional[date]
+ end_date: Optional[date]
===========changed ref 1===========
# module: backend.src.utils.utils
# returns start date, end date, string representing time range
def use_time_range(
time_range: str, start_date: date, end_date: date
) -> Tuple[date, date, str]:
duration_options = {
"one_month": (30, "Past 1 Month"),
"three_months": (90, "Past 3 Months"),
"six_months": (180, "Past 6 Months"),
"one_year": (365, "Past 1 Year"),
+ "all_time": (365 * 10, "All Time"),
}
start_str = start_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
end_str = end_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
if end_date == date.today():
end_str = "Present"
time_str = f"{start_str} - {end_str}"
if time_range in duration_options:
days, time_str = duration_options[time_range]
end_date = date.today()
start_date = date.today() - timedelta(days)
return start_date, end_date, time_str
===========changed ref 2===========
# module: backend.src.processing.auth
def authenticate(
code: str, private_access: bool
) -> Tuple[str, Optional[UpdateUserBackgroundTask]]:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
"private_access": private_access,
}
background_task = None
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
# new private access status
background_task = UpdateUserBackgroundTask(
user_id=user_id,
access_token=access_token,
private_access=new_private_access,
+ start_date=None,
+ end_date=None,
)
else:
# first time sign up
background_task = UpdateUserBackgroundTask(
user_id=user_id,
access_token=access_token,
private_access=private_access,
+ start_date=None,
+ end_date=None,
)
await db_update_user(user_id, raw_user)
return user_id, background_task
===========changed ref 3===========
# module: backend.src.render.template
def get_bar_section(
d: Drawing,
dataset: List[Tuple[str, str, List[Tuple[float, str]]]],
theme: str,
padding: int = 45,
bar_width: int = 210,
) -> Group:
section = Group(transform=f"translate(0, {padding})")
for i, (top_text, right_text, data_row) in enumerate(dataset):
translate = f"translate(0, {str(40 * i)})"
row = Group(transform=translate)
row.add(d.text(top_text, insert=(2, 15), class_=f"{theme}-lang-name"))
row.add(
d.text(right_text, insert=(bar_width + 10, 33), class_=f"{theme}-lang-name")
)
progress = Drawing(width=str(bar_width), x="0", y="25")
progress.add(
d.rect(
size=(bar_width, 8),
insert=(0, 0),
rx=5,
ry=5,
fill=themes[theme]["bar_color"],
)
)
total_percent, total_items = 0, len(data_row)
+ diff = max(0, 300 / bar_width - data_row[-1][0])
for j, (percent, color) in enumerate(data_row):
color = color or DEFAULT_COLOR
+ if j == 0:
+ percent -= diff
+ elif j == total_items - 1:
+ percent += diff
- percent = max(300 / bar_width, percent)
bar_percent = bar_width * percent / 100
bar_total = bar_width * total_percent / 100
box_size, insert = (bar_percent, 8), (bar_total, 0)
progress.add(d.rect(size=box_size, insert=insert, rx=5, ry=5, fill=color))
width = min(bar_percent /</s>
===========changed ref 4===========
# module: backend.src.render.template
def get_bar_section(
d: Drawing,
dataset: List[Tuple[str, str, List[Tuple[float, str]]]],
theme: str,
padding: int = 45,
bar_width: int = 210,
) -> Group:
# offset: 1
<s>_size, insert=insert, rx=5, ry=5, fill=color))
width = min(bar_percent / 2, 5)
if total_items > 1:
box_left, box_right = j > 0, j < total_items - 1
box_size, insert = bar_percent - 2 * width, bar_total + width
if box_left:
box_size += width
insert -= width
if box_right:
box_size += width
progress.add(d.rect(size=(box_size, 8), insert=(insert, 0), fill=color))
total_percent += percent
row.add(progress)
section.add(row)
return section
|
backend.src.aggregation.layer2.user/_get_user
|
Modified
|
avgupta456~github-trends
|
6083f7c9945a8bb61073e67ac255fc0fffce7357
|
All Time Cards (#238)
|
<2>:<add> return None, False
<del> return None
<3>:<add>
<add> expected_num_months = (
<add> (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month) + 1
<add> )
<add> complete = len(user_months) == expected_num_months
<9>:<add> return user_data.trim(start_date, end_date), complete
<del> return user_data.trim(start_date, end_date)
|
# module: backend.src.aggregation.layer2.user
def _get_user(
user_id: str, private_access: bool, start_date: date, end_date: date
+ ) -> Tuple[Optional[UserPackage], bool]:
- ) -> Optional[UserPackage]:
<0> user_months = await get_user_months(user_id, private_access, start_date, end_date)
<1> if len(user_months) == 0:
<2> return None
<3>
<4> user_data = user_months[0].data
<5> for user_month in user_months[1:]:
<6> user_data += user_month.data
<7>
<8> # TODO: handle timezone_str here
<9> return user_data.trim(start_date, end_date)
<10>
|
===========unchanged ref 0===========
at: datetime
date()
at: datetime.date
__slots__ = '_year', '_month', '_day', '_hashcode'
__str__ = isoformat
__radd__ = __add__
at: src.data.mongo.user_months.get
get_user_months(user_id: str, private_access: bool, start_month: date, end_month: date) -> List[UserMonth]
at: src.data.mongo.user_months.models.UserMonth
user_id: str
month: datetime
version: float
private: bool
complete: bool
data: UserPackage
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
===========changed ref 0===========
# module: backend.src.routers.background
+ # create a cache for the function
+ cache: Dict[str, Dict[str, bool]] = {"update_user": {}}
===========changed ref 1===========
# module: backend.src.models.background
class UpdateUserBackgroundTask(BaseModel):
user_id: str
access_token: Optional[str]
private_access: bool
+ start_date: Optional[date]
+ end_date: Optional[date]
===========changed ref 2===========
# module: backend.src.routers.background
def run_in_background(task: UpdateUserBackgroundTask):
if isinstance(task, UpdateUserBackgroundTask): # type: ignore
+ inputs = {
+ "user_id": task.user_id,
+ "access_token": task.access_token,
+ "private_access": task.private_access,
+ "start_date": task.start_date,
+ "end_date": task.end_date,
+ }
- await query_user(task.user_id, task.access_token, task.private_access)
===========changed ref 3===========
# module: backend.src.utils.utils
# returns start date, end date, string representing time range
def use_time_range(
time_range: str, start_date: date, end_date: date
) -> Tuple[date, date, str]:
duration_options = {
"one_month": (30, "Past 1 Month"),
"three_months": (90, "Past 3 Months"),
"six_months": (180, "Past 6 Months"),
"one_year": (365, "Past 1 Year"),
+ "all_time": (365 * 10, "All Time"),
}
start_str = start_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
end_str = end_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
if end_date == date.today():
end_str = "Present"
time_str = f"{start_str} - {end_str}"
if time_range in duration_options:
days, time_str = duration_options[time_range]
end_date = date.today()
start_date = date.today() - timedelta(days)
return start_date, end_date, time_str
===========changed ref 4===========
# module: backend.src.processing.auth
def authenticate(
code: str, private_access: bool
) -> Tuple[str, Optional[UpdateUserBackgroundTask]]:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
"private_access": private_access,
}
background_task = None
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
# new private access status
background_task = UpdateUserBackgroundTask(
user_id=user_id,
access_token=access_token,
private_access=new_private_access,
+ start_date=None,
+ end_date=None,
)
else:
# first time sign up
background_task = UpdateUserBackgroundTask(
user_id=user_id,
access_token=access_token,
private_access=private_access,
+ start_date=None,
+ end_date=None,
)
await db_update_user(user_id, raw_user)
return user_id, background_task
===========changed ref 5===========
# module: backend.src.render.template
def get_bar_section(
d: Drawing,
dataset: List[Tuple[str, str, List[Tuple[float, str]]]],
theme: str,
padding: int = 45,
bar_width: int = 210,
) -> Group:
section = Group(transform=f"translate(0, {padding})")
for i, (top_text, right_text, data_row) in enumerate(dataset):
translate = f"translate(0, {str(40 * i)})"
row = Group(transform=translate)
row.add(d.text(top_text, insert=(2, 15), class_=f"{theme}-lang-name"))
row.add(
d.text(right_text, insert=(bar_width + 10, 33), class_=f"{theme}-lang-name")
)
progress = Drawing(width=str(bar_width), x="0", y="25")
progress.add(
d.rect(
size=(bar_width, 8),
insert=(0, 0),
rx=5,
ry=5,
fill=themes[theme]["bar_color"],
)
)
total_percent, total_items = 0, len(data_row)
+ diff = max(0, 300 / bar_width - data_row[-1][0])
for j, (percent, color) in enumerate(data_row):
color = color or DEFAULT_COLOR
+ if j == 0:
+ percent -= diff
+ elif j == total_items - 1:
+ percent += diff
- percent = max(300 / bar_width, percent)
bar_percent = bar_width * percent / 100
bar_total = bar_width * total_percent / 100
box_size, insert = (bar_percent, 8), (bar_total, 0)
progress.add(d.rect(size=box_size, insert=insert, rx=5, ry=5, fill=color))
width = min(bar_percent /</s>
===========changed ref 6===========
# module: backend.src.render.template
def get_bar_section(
d: Drawing,
dataset: List[Tuple[str, str, List[Tuple[float, str]]]],
theme: str,
padding: int = 45,
bar_width: int = 210,
) -> Group:
# offset: 1
<s>_size, insert=insert, rx=5, ry=5, fill=color))
width = min(bar_percent / 2, 5)
if total_items > 1:
box_left, box_right = j > 0, j < total_items - 1
box_size, insert = bar_percent - 2 * width, bar_total + width
if box_left:
box_size += width
insert -= width
if box_right:
box_size += width
progress.add(d.rect(size=(box_size, 8), insert=(insert, 0), fill=color))
total_percent += percent
row.add(progress)
section.add(row)
return section
|
backend.src.aggregation.layer2.user/get_user
|
Modified
|
avgupta456~github-trends
|
6083f7c9945a8bb61073e67ac255fc0fffce7357
|
All Time Cards (#238)
|
<2>:<add> return (False, (None, False, None))
<del> return (False, (None, None))
<5>:<add> user_data, complete = await _get_user(user_id, private_access, start_date, end_date)
<del> user_data = await _get_user(user_id, private_access, start_date, end_date)
<7>:<add> user_id=user_id,
<add> access_token=user.access_token,
<add> private_access=private_access,
<add> start_date=start_date,
<add> end_date=end_date,
<del> user_id=user_id, access_token=user.access_token, private_access=private_access
<9>:<add> return (complete, (user_data, complete, background_task))
<del> return (user_data is not None, (user_data, background_task))
|
# module: backend.src.aggregation.layer2.user
@alru_cache()
async def get_user(
user_id: str,
start_date: date,
end_date: date,
no_cache: bool = False,
+ ) -> Tuple[
+ bool, Tuple[Optional[UserPackage], bool, Optional[UpdateUserBackgroundTask]]
- ) -> Tuple[bool, Tuple[Optional[UserPackage], Optional[UpdateUserBackgroundTask]]]:
+ ]:
<0> user: Optional[PublicUserModel] = await db_get_public_user(user_id)
<1> if user is None:
<2> return (False, (None, None))
<3>
<4> private_access = user.private_access or False
<5> user_data = await _get_user(user_id, private_access, start_date, end_date)
<6> background_task = UpdateUserBackgroundTask(
<7> user_id=user_id, access_token=user.access_token, private_access=private_access
<8> )
<9> return (user_data is not None, (user_data, background_task))
<10>
|
===========unchanged ref 0===========
at: backend.src.aggregation.layer2.user._get_user
complete = len(user_months) == expected_num_months
user_data = user_months[0].data
user_data += user_month.data
at: datetime
date()
at: src.data.mongo.user.get
get_public_user(user_id: str, no_cache: bool=False) -> Tuple[bool, Optional[PublicUserModel]]
at: src.models.user.main.UserPackage
contribs: UserContributions
incomplete: bool = False
trim(start: date, end: date) -> "UserPackage"
at: src.utils.alru_cache
alru_cache(max_size: int=128, ttl: timedelta=timedelta(minutes=1))
at: typing
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
===========changed ref 0===========
# module: backend.src.aggregation.layer2.user
def _get_user(
user_id: str, private_access: bool, start_date: date, end_date: date
+ ) -> Tuple[Optional[UserPackage], bool]:
- ) -> Optional[UserPackage]:
user_months = await get_user_months(user_id, private_access, start_date, end_date)
if len(user_months) == 0:
+ return None, False
- return None
+
+ expected_num_months = (
+ (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month) + 1
+ )
+ complete = len(user_months) == expected_num_months
user_data = user_months[0].data
for user_month in user_months[1:]:
user_data += user_month.data
# TODO: handle timezone_str here
+ return user_data.trim(start_date, end_date), complete
- return user_data.trim(start_date, end_date)
===========changed ref 1===========
# module: backend.src.routers.background
+ # create a cache for the function
+ cache: Dict[str, Dict[str, bool]] = {"update_user": {}}
===========changed ref 2===========
# module: backend.src.models.background
class UpdateUserBackgroundTask(BaseModel):
user_id: str
access_token: Optional[str]
private_access: bool
+ start_date: Optional[date]
+ end_date: Optional[date]
===========changed ref 3===========
# module: backend.src.routers.background
def run_in_background(task: UpdateUserBackgroundTask):
if isinstance(task, UpdateUserBackgroundTask): # type: ignore
+ inputs = {
+ "user_id": task.user_id,
+ "access_token": task.access_token,
+ "private_access": task.private_access,
+ "start_date": task.start_date,
+ "end_date": task.end_date,
+ }
- await query_user(task.user_id, task.access_token, task.private_access)
===========changed ref 4===========
# module: backend.src.utils.utils
# returns start date, end date, string representing time range
def use_time_range(
time_range: str, start_date: date, end_date: date
) -> Tuple[date, date, str]:
duration_options = {
"one_month": (30, "Past 1 Month"),
"three_months": (90, "Past 3 Months"),
"six_months": (180, "Past 6 Months"),
"one_year": (365, "Past 1 Year"),
+ "all_time": (365 * 10, "All Time"),
}
start_str = start_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
end_str = end_date.strftime("X%m/X%d/%Y").replace("X0", "X").replace("X", "")
if end_date == date.today():
end_str = "Present"
time_str = f"{start_str} - {end_str}"
if time_range in duration_options:
days, time_str = duration_options[time_range]
end_date = date.today()
start_date = date.today() - timedelta(days)
return start_date, end_date, time_str
===========changed ref 5===========
# module: backend.src.processing.auth
def authenticate(
code: str, private_access: bool
) -> Tuple[str, Optional[UpdateUserBackgroundTask]]:
user_id, access_token = await github_authenticate(code)
curr_user: Optional[PublicUserModel] = await db_get_public_user(user_id)
raw_user: Dict[str, Any] = {
"user_id": user_id,
"access_token": access_token,
"user_key": code_key_map.get(code, None),
"private_access": private_access,
}
background_task = None
if curr_user is not None:
curr_private_access = curr_user.private_access
new_private_access = curr_private_access or private_access
raw_user["private_access"] = new_private_access
if new_private_access != curr_private_access:
# new private access status
background_task = UpdateUserBackgroundTask(
user_id=user_id,
access_token=access_token,
private_access=new_private_access,
+ start_date=None,
+ end_date=None,
)
else:
# first time sign up
background_task = UpdateUserBackgroundTask(
user_id=user_id,
access_token=access_token,
private_access=private_access,
+ start_date=None,
+ end_date=None,
)
await db_update_user(user_id, raw_user)
return user_id, background_task
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.