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.external.github_api.rest.repo/get_repo_commits
|
Modified
|
avgupta456~github-trends
|
b720f9b077adb8a7457621406db08b85792414fa
|
propagate access_token
|
<8>:<add> return get_template_plural(query, access_token, page=page)
<del> return get_template_plural(query, page=page)
|
# module: backend.external.github_api.rest.repo
def get_repo_commits(
+ access_token: str,
owner: str,
repo: str,
user: Optional[str] = None,
since: Optional[datetime] = None,
until: Optional[datetime] = None,
page: int = 1,
) -> List[Dict[str, Any]]:
<0> """Returns most recent commits including commit message"""
<1> user = user if user is not None else owner
<2> query = BASE_URL + owner + "/" + repo + "/commits?author=" + user
<3> if since is not None:
<4> query += "&since=" + str(since)
<5> if until is not None:
<6> query += "&until=" + str(until)
<7> try:
<8> return get_template_plural(query, page=page)
<9> except RESTErrorEmptyRepo:
<10> return []
<11>
|
===========unchanged ref 0===========
at: backend.external.github_api.rest.repo
BASE_URL = "https://api.github.com/repos/"
at: external.github_api.rest.template
get_template(query: str, access_token: str, accept_header: str="application/vnd.github.v3+json") -> Dict[str, Any]
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.external.github_api.rest.repo
+ def get_repo_hourly_commits(access_token: str, owner: str, repo: str) -> Dict[str, Any]:
- def get_repo_hourly_commits(owner: str, repo: str) -> Dict[str, Any]:
"""Returns contributions by day, hour for repository"""
+ return get_template(
+ BASE_URL + owner + "/" + repo + "/stats/punch_card", access_token
- return get_template(BASE_URL + owner + "/" + repo + "/stats/punch_card")
+ )
===========changed ref 1===========
# module: backend.external.github_api.rest.repo
+ def get_repo_contributors(access_token: str, owner: str, repo: str) -> Dict[str, Any]:
- def get_repo_contributors(owner: str, repo: str) -> Dict[str, Any]:
"""Returns contributors for a repository"""
+ return get_template(
+ BASE_URL + owner + "/" + repo + "/stats/contributors", access_token
- return get_template(BASE_URL + owner + "/" + repo + "/stats/contributors")
+ )
===========changed ref 2===========
# module: backend.external.github_api.rest.repo
+ def get_repo_weekly_commits(access_token: str, owner: str, repo: str) -> Dict[str, Any]:
- def get_repo_weekly_commits(owner: str, repo: str) -> Dict[str, Any]:
"""Returns contributions by week, owner/non-owner"""
+ return get_template(
+ BASE_URL + owner + "/" + repo + "/stats/participation", access_token
- return get_template(BASE_URL + owner + "/" + repo + "/stats/participation")
+ )
===========changed ref 3===========
# module: backend.external.github_api.rest.repo
+ def get_repo_commit_activity(
+ access_token: str, owner: str, repo: str
+ ) -> Dict[str, Any]:
- def get_repo_commit_activity(owner: str, repo: str) -> Dict[str, Any]:
"""Returns commit activity for past year, broken by week"""
+ return get_template(
+ BASE_URL + owner + "/" + repo + "/stats/commit_activity", access_token
- return get_template(BASE_URL + owner + "/" + repo + "/stats/commit_activity")
+ )
===========changed ref 4===========
# module: backend.external.github_api.rest.repo
# does not accept per page, exceeds if necessary
+ def get_repo_code_frequency(access_token: str, owner: str, repo: str) -> Dict[str, Any]:
- def get_repo_code_frequency(owner: str, repo: str) -> Dict[str, Any]:
"""Returns code frequency for repository"""
+ return get_template(
+ BASE_URL + owner + "/" + repo + "/stats/code_frequency", access_token
- return get_template(BASE_URL + owner + "/" + repo + "/stats/code_frequency")
+ )
===========changed ref 5===========
# module: backend.external.github_api.rest.repo
+ def get_repo(access_token: str, owner: str, repo: str) -> Dict[str, Any]:
- def get_repo(owner: str, repo: str) -> Dict[str, Any]:
"""Returns raw repository data"""
+ return get_template(BASE_URL + owner + "/" + repo, access_token)
- return get_template(BASE_URL + owner + "/" + repo)
===========changed ref 6===========
# module: backend.external.github_api.rest.repo
+ def get_repo_languages(
+ access_token: str, owner: str, repo: str
+ ) -> List[Dict[str, Any]]:
- def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]:
"""Returns repository language breakdown"""
+ return get_template_plural(
+ BASE_URL + owner + "/" + repo + "/languages", access_token
+ )
- return get_template_plural(BASE_URL + owner + "/" + repo + "/languages")
===========changed ref 7===========
# module: backend.external.github_api.rest.repo
def get_repo_stargazers(
+ access_token: str, owner: str, repo: str, per_page: int = 100
- owner: str, repo: str, per_page: int = 100
) -> List[Dict[str, Any]]:
"""Returns stargazers with timestamp for repository"""
return get_template_plural(
BASE_URL + owner + "/" + repo + "/stargazers",
+ access_token,
per_page=per_page,
accept_header="applicaiton/vnd.github.v3.star+json",
)
===========changed ref 8===========
# module: backend.external.github_api.rest.user
+ def get_user(user_id: str, access_token: str) -> Dict[str, Any]:
- def get_user(user_id: str) -> Dict[str, Any]:
"""Returns raw user data"""
+ return get_template(BASE_URL + user_id, access_token)
- return get_template(BASE_URL + user_id)
===========changed ref 9===========
# module: backend.tests.processing.user.test_contributions
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
+ response = get_contributions("avgupta456", TOKEN)
- response = get_contributions("avgupta456")
self.assertIsInstance(response, UserContributions)
===========changed ref 10===========
# module: backend.tests.processing.user.test_follows
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
+ response = get_user_follows("avgupta456", TOKEN)
- response = get_user_follows("avgupta456")
self.assertIsInstance(response, UserFollows)
===========changed ref 11===========
# module: backend.external.github_api.rest.template
def get_template(
query: str,
+ access_token: str,
accept_header: str = "application/vnd.github.v3+json",
) -> Dict[str, Any]:
"""Template for interacting with the GitHub REST API (singular)"""
try:
+ return _get_template(query, {}, access_token, accept_header)
- return _get_template(query, {}, accept_header)
except Exception as e:
raise e
===========changed ref 12===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_events(self):
+ response = get_user_contribution_events(
- response = get_user_contribution_events(user_id="avgupta456")
+ user_id="avgupta456", access_token=TOKEN
+ )
self.assertIsInstance(response, RawEvents)
===========changed ref 13===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_calendar(self):
+ response = get_user_contribution_calendar(
- response = get_user_contribution_calendar(user_id="avgupta456")
+ user_id="avgupta456", access_token=TOKEN
+ )
self.assertIsInstance(response, RawCalendar)
|
backend.external.github_api.graphql.template/get_template
|
Modified
|
avgupta456~github-trends
|
b720f9b077adb8a7457621406db08b85792414fa
|
propagate access_token
|
<2>:<add> headers: Dict[str, str] = {"Authorization": "bearer " + access_token}
<del> headers: Dict[str, str] = {"Authorization": "bearer " + TOKEN}
|
# module: backend.external.github_api.graphql.template
+ def get_template(query: Dict[str, Any], access_token: str) -> Dict[str, Any]:
- def get_template(query: Dict[str, Any]) -> Dict[str, Any]:
<0> """Template for interacting with the GitHub GraphQL API"""
<1> start = datetime.now()
<2> headers: Dict[str, str] = {"Authorization": "bearer " + TOKEN}
<3>
<4> try:
<5> r = s.post( # type: ignore
<6> "https://api.github.com/graphql",
<7> json=query,
<8> headers=headers,
<9> timeout=TIMEOUT,
<10> )
<11> except ReadTimeout:
<12> raise GraphQLErrorTimeout("GraphQL Error: Request Timeout")
<13>
<14> print("GraphQL", datetime.now() - start)
<15> if r.status_code == 200:
<16> data = r.json() # type: ignore
<17> if "errors" in data:
<18> if (
<19> "type" in data["errors"][0]
<20> and data["errors"][0]["type"] == "SERVICE_UNAVAILABLE"
<21> and "path" in data["errors"][0]
<22> and isinstance(data["errors"][0]["path"], list)
<23> and len(data["errors"][0]["path"]) == 3 # type: ignore
<24> and data["errors"][0]["path"][0] == "nodes"
<25> ):
<26> raise GraphQLErrorMissingNode(node=int(data["errors"][0]["path"][1])) # type: ignore
<27> raise GraphQLError("GraphQL Error: " + str(data["errors"]))
<28> return data
<29>
<30> if r.status_code == 403:
<31> raise GraphQLErrorAuth("GraphQL Error: Unauthorized")
<32>
<33> if r.status_code == 502:
<34> raise GraphQLErrorTimeout("GraphQL Error: Request Timeout")
<35>
<36> raise GraphQLError("GraphQL Error: " + str(r.status_code))
<37>
|
===========unchanged ref 0===========
at: backend.external.github_api.graphql.template
s = requests.session()
GraphQLError(*args: object)
GraphQLErrorMissingNode(node: int)
GraphQLErrorAuth(*args: object)
GraphQLErrorTimeout(*args: object)
at: constants
TIMEOUT = 3 # max seconds to wait for api response
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: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.external.github_api.rest.user
+ def get_user(user_id: str, access_token: str) -> Dict[str, Any]:
- def get_user(user_id: str) -> Dict[str, Any]:
"""Returns raw user data"""
+ return get_template(BASE_URL + user_id, access_token)
- return get_template(BASE_URL + user_id)
===========changed ref 1===========
# module: backend.external.github_api.rest.repo
+ def get_repo(access_token: str, owner: str, repo: str) -> Dict[str, Any]:
- def get_repo(owner: str, repo: str) -> Dict[str, Any]:
"""Returns raw repository data"""
+ return get_template(BASE_URL + owner + "/" + repo, access_token)
- return get_template(BASE_URL + owner + "/" + repo)
===========changed ref 2===========
# module: backend.tests.processing.user.test_contributions
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
+ response = get_contributions("avgupta456", TOKEN)
- response = get_contributions("avgupta456")
self.assertIsInstance(response, UserContributions)
===========changed ref 3===========
# module: backend.tests.processing.user.test_follows
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
+ response = get_user_follows("avgupta456", TOKEN)
- response = get_user_follows("avgupta456")
self.assertIsInstance(response, UserFollows)
===========changed ref 4===========
# module: backend.external.github_api.rest.repo
+ def get_repo_languages(
+ access_token: str, owner: str, repo: str
+ ) -> List[Dict[str, Any]]:
- def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]:
"""Returns repository language breakdown"""
+ return get_template_plural(
+ BASE_URL + owner + "/" + repo + "/languages", access_token
+ )
- return get_template_plural(BASE_URL + owner + "/" + repo + "/languages")
===========changed ref 5===========
# module: backend.external.github_api.rest.repo
+ def get_repo_contributors(access_token: str, owner: str, repo: str) -> Dict[str, Any]:
- def get_repo_contributors(owner: str, repo: str) -> Dict[str, Any]:
"""Returns contributors for a repository"""
+ return get_template(
+ BASE_URL + owner + "/" + repo + "/stats/contributors", access_token
- return get_template(BASE_URL + owner + "/" + repo + "/stats/contributors")
+ )
===========changed ref 6===========
# module: backend.external.github_api.rest.repo
# does not accept per page, exceeds if necessary
+ def get_repo_code_frequency(access_token: str, owner: str, repo: str) -> Dict[str, Any]:
- def get_repo_code_frequency(owner: str, repo: str) -> Dict[str, Any]:
"""Returns code frequency for repository"""
+ return get_template(
+ BASE_URL + owner + "/" + repo + "/stats/code_frequency", access_token
- return get_template(BASE_URL + owner + "/" + repo + "/stats/code_frequency")
+ )
===========changed ref 7===========
# module: backend.external.github_api.rest.template
def get_template(
query: str,
+ access_token: str,
accept_header: str = "application/vnd.github.v3+json",
) -> Dict[str, Any]:
"""Template for interacting with the GitHub REST API (singular)"""
try:
+ return _get_template(query, {}, access_token, accept_header)
- return _get_template(query, {}, accept_header)
except Exception as e:
raise e
===========changed ref 8===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_events(self):
+ response = get_user_contribution_events(
- response = get_user_contribution_events(user_id="avgupta456")
+ user_id="avgupta456", access_token=TOKEN
+ )
self.assertIsInstance(response, RawEvents)
===========changed ref 9===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_calendar(self):
+ response = get_user_contribution_calendar(
- response = get_user_contribution_calendar(user_id="avgupta456")
+ user_id="avgupta456", access_token=TOKEN
+ )
self.assertIsInstance(response, RawCalendar)
===========changed ref 10===========
# module: backend.external.github_api.rest.repo
+ def get_repo_commit_activity(
+ access_token: str, owner: str, repo: str
+ ) -> Dict[str, Any]:
- def get_repo_commit_activity(owner: str, repo: str) -> Dict[str, Any]:
"""Returns commit activity for past year, broken by week"""
+ return get_template(
+ BASE_URL + owner + "/" + repo + "/stats/commit_activity", access_token
- return get_template(BASE_URL + owner + "/" + repo + "/stats/commit_activity")
+ )
===========changed ref 11===========
# module: backend.external.github_api.rest.user
+ def get_user_starred_repos(
+ user_id: str, access_token: str, per_page: int = 100
+ ) -> List[Dict[str, Any]]:
- def get_user_starred_repos(user_id: str, per_page: int = 100) -> List[Dict[str, Any]]:
"""Returns list of starred repos"""
return get_template_plural(
BASE_URL + user_id + "/starred",
+ access_token,
per_page=per_page,
accept_header="application/vnd.github.v3.star+json",
)
|
backend.external.github_api.graphql.commit/get_commits
|
Modified
|
avgupta456~github-trends
|
b720f9b077adb8a7457621406db08b85792414fa
|
propagate access_token
|
<26>:<add> return get_template(query, access_token)
<del> return get_template(query)
|
# module: backend.external.github_api.graphql.commit
+ def get_commits(
+ access_token: str, node_ids: List[str]
+ ) -> Union[Dict[str, Any], List[Any]]:
- def get_commits(node_ids: List[str]) -> Union[Dict[str, Any], List[Any]]:
<0> """gets all repository data from graphql"""
<1> query = {
<2> "variables": {"ids": node_ids},
<3> "query": """
<4> query getCommits($ids: [ID!]!) {
<5> nodes(ids: $ids) {
<6> ... on Commit {
<7> additions
<8> deletions
<9> changedFiles
<10> repository{
<11> languages(first: 5, orderBy: {field:SIZE, direction:DESC}){
<12> edges{
<13> size
<14> node{
<15> name
<16> }
<17> }
<18> }
<19> }
<20> }
<21> }
<22> }
<23> """,
<24> }
<25>
<26> return get_template(query)
<27>
|
===========unchanged ref 0===========
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.external.github_api.rest.user
+ def get_user(user_id: str, access_token: str) -> Dict[str, Any]:
- def get_user(user_id: str) -> Dict[str, Any]:
"""Returns raw user data"""
+ return get_template(BASE_URL + user_id, access_token)
- return get_template(BASE_URL + user_id)
===========changed ref 1===========
# module: backend.external.github_api.rest.repo
+ def get_repo(access_token: str, owner: str, repo: str) -> Dict[str, Any]:
- def get_repo(owner: str, repo: str) -> Dict[str, Any]:
"""Returns raw repository data"""
+ return get_template(BASE_URL + owner + "/" + repo, access_token)
- return get_template(BASE_URL + owner + "/" + repo)
===========changed ref 2===========
# module: backend.tests.processing.user.test_contributions
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
+ response = get_contributions("avgupta456", TOKEN)
- response = get_contributions("avgupta456")
self.assertIsInstance(response, UserContributions)
===========changed ref 3===========
# module: backend.tests.processing.user.test_follows
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
+ response = get_user_follows("avgupta456", TOKEN)
- response = get_user_follows("avgupta456")
self.assertIsInstance(response, UserFollows)
===========changed ref 4===========
# module: backend.external.github_api.rest.repo
+ def get_repo_languages(
+ access_token: str, owner: str, repo: str
+ ) -> List[Dict[str, Any]]:
- def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]:
"""Returns repository language breakdown"""
+ return get_template_plural(
+ BASE_URL + owner + "/" + repo + "/languages", access_token
+ )
- return get_template_plural(BASE_URL + owner + "/" + repo + "/languages")
===========changed ref 5===========
# module: backend.external.github_api.rest.repo
+ def get_repo_contributors(access_token: str, owner: str, repo: str) -> Dict[str, Any]:
- def get_repo_contributors(owner: str, repo: str) -> Dict[str, Any]:
"""Returns contributors for a repository"""
+ return get_template(
+ BASE_URL + owner + "/" + repo + "/stats/contributors", access_token
- return get_template(BASE_URL + owner + "/" + repo + "/stats/contributors")
+ )
===========changed ref 6===========
# module: backend.external.github_api.rest.repo
# does not accept per page, exceeds if necessary
+ def get_repo_code_frequency(access_token: str, owner: str, repo: str) -> Dict[str, Any]:
- def get_repo_code_frequency(owner: str, repo: str) -> Dict[str, Any]:
"""Returns code frequency for repository"""
+ return get_template(
+ BASE_URL + owner + "/" + repo + "/stats/code_frequency", access_token
- return get_template(BASE_URL + owner + "/" + repo + "/stats/code_frequency")
+ )
===========changed ref 7===========
# module: backend.external.github_api.rest.template
def get_template(
query: str,
+ access_token: str,
accept_header: str = "application/vnd.github.v3+json",
) -> Dict[str, Any]:
"""Template for interacting with the GitHub REST API (singular)"""
try:
+ return _get_template(query, {}, access_token, accept_header)
- return _get_template(query, {}, accept_header)
except Exception as e:
raise e
===========changed ref 8===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_events(self):
+ response = get_user_contribution_events(
- response = get_user_contribution_events(user_id="avgupta456")
+ user_id="avgupta456", access_token=TOKEN
+ )
self.assertIsInstance(response, RawEvents)
===========changed ref 9===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_calendar(self):
+ response = get_user_contribution_calendar(
- response = get_user_contribution_calendar(user_id="avgupta456")
+ user_id="avgupta456", access_token=TOKEN
+ )
self.assertIsInstance(response, RawCalendar)
===========changed ref 10===========
# module: backend.external.github_api.rest.repo
+ def get_repo_commit_activity(
+ access_token: str, owner: str, repo: str
+ ) -> Dict[str, Any]:
- def get_repo_commit_activity(owner: str, repo: str) -> Dict[str, Any]:
"""Returns commit activity for past year, broken by week"""
+ return get_template(
+ BASE_URL + owner + "/" + repo + "/stats/commit_activity", access_token
- return get_template(BASE_URL + owner + "/" + repo + "/stats/commit_activity")
+ )
===========changed ref 11===========
# module: backend.external.github_api.rest.user
+ def get_user_starred_repos(
+ user_id: str, access_token: str, per_page: int = 100
+ ) -> List[Dict[str, Any]]:
- def get_user_starred_repos(user_id: str, per_page: int = 100) -> List[Dict[str, Any]]:
"""Returns list of starred repos"""
return get_template_plural(
BASE_URL + user_id + "/starred",
+ access_token,
per_page=per_page,
accept_header="application/vnd.github.v3.star+json",
)
===========changed ref 12===========
# module: backend.external.github_api.rest.repo
+ def get_repo_hourly_commits(access_token: str, owner: str, repo: str) -> Dict[str, Any]:
- def get_repo_hourly_commits(owner: str, repo: str) -> Dict[str, Any]:
"""Returns contributions by day, hour for repository"""
+ return get_template(
+ BASE_URL + owner + "/" + repo + "/stats/punch_card", access_token
- return get_template(BASE_URL + owner + "/" + repo + "/stats/punch_card")
+ )
===========changed ref 13===========
# module: backend.external.github_api.rest.repo
+ def get_repo_weekly_commits(access_token: str, owner: str, repo: str) -> Dict[str, Any]:
- def get_repo_weekly_commits(owner: str, repo: str) -> Dict[str, Any]:
"""Returns contributions by week, owner/non-owner"""
+ return get_template(
+ BASE_URL + owner + "/" + repo + "/stats/participation", access_token
- return get_template(BASE_URL + owner + "/" + repo + "/stats/participation")
+ )
|
backend.processing.user.contributions/get_user_all_contribution_events
|
Modified
|
avgupta456~github-trends
|
b720f9b077adb8a7457621406db08b85792414fa
|
propagate access_token
|
<8>:<add> user_id=user_id,
<add> access_token=access_token,
<add> start_date=start_date,
<add> end_date=end_date,
<add> after=after_str,
<del> user_id=user_id, start_date=start_date, end_date=end_date, after=after_str
|
# module: backend.processing.user.contributions
def get_user_all_contribution_events(
user_id: str,
+ access_token: str,
start_date: datetime = datetime.now() - timedelta(365),
end_date: datetime = datetime.now(),
) -> t_stats:
<0> repo_contribs: t_stats = defaultdict(
<1> lambda: {"commits": [], "issues": [], "prs": [], "reviews": [], "repos": []}
<2> )
<3> after: Optional[str] = ""
<4> index, cont = 0, True
<5> while index < 10 and cont:
<6> after_str = after if isinstance(after, str) else ""
<7> response = get_user_contribution_events(
<8> user_id=user_id, start_date=start_date, end_date=end_date, after=after_str
<9> )
<10>
<11> cont = False
<12> for event_type, event_list in zip(
<13> ["commits", "issues", "prs", "reviews"],
<14> [
<15> response.commit_contribs_by_repo,
<16> response.issue_contribs_by_repo,
<17> response.pr_contribs_by_repo,
<18> response.review_contribs_by_repo,
<19> ],
<20> ):
<21> for repo in event_list:
<22> name = repo.repo.name
<23> for event in repo.contribs.nodes:
<24> repo_contribs[name][event_type].append(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> repo_contribs[name]["repos"].append(
<32> RawEventsEvent(occurredAt=str(repo.occurred_at))
<33> )
<34>
<35> index += 1
<36>
<37> return repo</s>
|
===========below chunk 0===========
# module: backend.processing.user.contributions
def get_user_all_contribution_events(
user_id: str,
+ access_token: str,
start_date: datetime = datetime.now() - timedelta(365),
end_date: datetime = datetime.now(),
) -> t_stats:
# offset: 1
===========unchanged ref 0===========
at: backend.processing.user.contributions
t_stats = DefaultDict[str, Dict[str, List[Union[RawEventsEvent, RawEventsCommit]]]]
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
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: external.github_api.graphql.user
get_user_contribution_events(user_id: str, access_token: str, start_date: datetime=datetime.now() - timedelta(365), end_date: datetime=datetime.now(), max_repos: int=100, first: int=100, after: str="") -> RawEvents
at: models.user.contribs.RawEvents
commit_contribs_by_repo: List[RawEventsRepoCommits] = Field(
alias="commitContributionsByRepository"
)
===========unchanged ref 1===========
issue_contribs_by_repo: List[RawEventsRepo] = Field(
alias="issueContributionsByRepository"
)
pr_contribs_by_repo: List[RawEventsRepo] = Field(
alias="pullRequestContributionsByRepository"
)
review_contribs_by_repo: List[RawEventsRepo] = Field(
alias="pullRequestReviewContributionsByRepository"
)
repo_contribs: RawEventsRepoContribs = Field(alias="repositoryContributions")
at: models.user.contribs.RawEventsCommits
nodes: List[RawEventsCommit]
page_info: RawEventsPageInfo = Field(alias="pageInfo")
at: models.user.contribs.RawEventsContribs
nodes: List[RawEventsEvent]
page_info: RawEventsPageInfo = Field(alias="pageInfo")
at: models.user.contribs.RawEventsPageInfo
has_next_page: bool = Field(alias="hasNextPage")
end_cursor: Optional[str] = Field(alias="endCursor")
at: models.user.contribs.RawEventsRepo
repo: RawEventsRepoName = Field(alias="repository")
count: RawEventsCount = Field(alias="totalCount")
contribs: RawEventsContribs = Field(alias="contributions")
at: models.user.contribs.RawEventsRepoCommits
repo: RawEventsRepoName = Field(alias="repository")
count: RawEventsCount = Field(alias="totalCount")
contribs: RawEventsCommits = Field(alias="contributions")
at: models.user.contribs.RawEventsRepoContribs
count: int = Field(alias="totalCount")
nodes: List[RawEventsRepoEvent]
at: models.user.contribs.RawEventsRepoEvent
repo: RawEventsRepoName = Field(alias="repository")
occurred_at: datetime = Field(alias="occurredAt")
at: models.user.contribs.RawEventsRepoName
name: str = Field(alias="nameWithOwner")
===========changed ref 0===========
# module: backend.external.github_api.rest.user
+ def get_user(user_id: str, access_token: str) -> Dict[str, Any]:
- def get_user(user_id: str) -> Dict[str, Any]:
"""Returns raw user data"""
+ return get_template(BASE_URL + user_id, access_token)
- return get_template(BASE_URL + user_id)
===========changed ref 1===========
# module: backend.external.github_api.rest.repo
+ def get_repo(access_token: str, owner: str, repo: str) -> Dict[str, Any]:
- def get_repo(owner: str, repo: str) -> Dict[str, Any]:
"""Returns raw repository data"""
+ return get_template(BASE_URL + owner + "/" + repo, access_token)
- return get_template(BASE_URL + owner + "/" + repo)
===========changed ref 2===========
# module: backend.tests.processing.user.test_contributions
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
+ response = get_contributions("avgupta456", TOKEN)
- response = get_contributions("avgupta456")
self.assertIsInstance(response, UserContributions)
===========changed ref 3===========
# module: backend.tests.processing.user.test_follows
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
+ response = get_user_follows("avgupta456", TOKEN)
- response = get_user_follows("avgupta456")
self.assertIsInstance(response, UserFollows)
===========changed ref 4===========
# module: backend.external.github_api.rest.repo
+ def get_repo_languages(
+ access_token: str, owner: str, repo: str
+ ) -> List[Dict[str, Any]]:
- def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]:
"""Returns repository language breakdown"""
+ return get_template_plural(
+ BASE_URL + owner + "/" + repo + "/languages", access_token
+ )
- return get_template_plural(BASE_URL + owner + "/" + repo + "/languages")
===========changed ref 5===========
# module: backend.external.github_api.rest.repo
+ def get_repo_contributors(access_token: str, owner: str, repo: str) -> Dict[str, Any]:
- def get_repo_contributors(owner: str, repo: str) -> Dict[str, Any]:
"""Returns contributors for a repository"""
+ return get_template(
+ BASE_URL + owner + "/" + repo + "/stats/contributors", access_token
- return get_template(BASE_URL + owner + "/" + repo + "/stats/contributors")
+ )
===========changed ref 6===========
# module: backend.external.github_api.rest.repo
# does not accept per page, exceeds if necessary
+ def get_repo_code_frequency(access_token: str, owner: str, repo: str) -> Dict[str, Any]:
- def get_repo_code_frequency(owner: str, repo: str) -> Dict[str, Any]:
"""Returns code frequency for repository"""
+ return get_template(
+ BASE_URL + owner + "/" + repo + "/stats/code_frequency", access_token
- return get_template(BASE_URL + owner + "/" + repo + "/stats/code_frequency")
+ )
|
backend.tests.processing.user.test_contributions/TestTemplate.test_get_contributions
|
Modified
|
avgupta456~github-trends
|
abdd9300be1b4d3792f472ed83597881e09a3736
|
change testing user
|
<0>:<add> response = get_contributions(USER_ID, TOKEN)
<del> response = get_contributions("avgupta456", TOKEN)
|
# module: backend.tests.processing.user.test_contributions
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
<0> response = get_contributions("avgupta456", TOKEN)
<1> self.assertIsInstance(response, UserContributions)
<2>
| |
backend.tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_contribution_years
|
Modified
|
avgupta456~github-trends
|
abdd9300be1b4d3792f472ed83597881e09a3736
|
change testing user
|
<0>:<add> response = get_user_contribution_years(user_id=USER_ID, access_token=TOKEN)
<del> response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN)
|
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_years(self):
<0> response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN)
<1>
<2> # aside from validating APIResponse class, pydantic will validate tree
<3> self.assertIsInstance(response, list)
<4>
|
===========changed ref 0===========
# module: backend.tests.processing.user.test_contributions
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
+ response = get_contributions(USER_ID, TOKEN)
- response = get_contributions("avgupta456", TOKEN)
self.assertIsInstance(response, UserContributions)
|
backend.tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_contribution_calendar
|
Modified
|
avgupta456~github-trends
|
abdd9300be1b4d3792f472ed83597881e09a3736
|
change testing user
|
<0>:<del> response = get_user_contribution_calendar(
<1>:<del> user_id="avgupta456", access_token=TOKEN
<2>:<del> )
<3>:<add> response = get_user_contribution_calendar(user_id=USER_ID, access_token=TOKEN)
|
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_calendar(self):
<0> response = get_user_contribution_calendar(
<1> user_id="avgupta456", access_token=TOKEN
<2> )
<3> self.assertIsInstance(response, RawCalendar)
<4>
|
===========changed ref 0===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_years(self):
+ response = get_user_contribution_years(user_id=USER_ID, access_token=TOKEN)
- response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN)
# aside from validating APIResponse class, pydantic will validate tree
self.assertIsInstance(response, list)
===========changed ref 1===========
# module: backend.tests.processing.user.test_contributions
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
+ response = get_contributions(USER_ID, TOKEN)
- response = get_contributions("avgupta456", TOKEN)
self.assertIsInstance(response, UserContributions)
|
backend.tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_contribution_events
|
Modified
|
avgupta456~github-trends
|
abdd9300be1b4d3792f472ed83597881e09a3736
|
change testing user
|
<0>:<del> response = get_user_contribution_events(
<1>:<del> user_id="avgupta456", access_token=TOKEN
<2>:<del> )
<3>:<add> response = get_user_contribution_events(user_id=USER_ID, access_token=TOKEN)
|
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_events(self):
<0> response = get_user_contribution_events(
<1> user_id="avgupta456", access_token=TOKEN
<2> )
<3> self.assertIsInstance(response, RawEvents)
<4>
|
===========changed ref 0===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_calendar(self):
- response = get_user_contribution_calendar(
- user_id="avgupta456", access_token=TOKEN
- )
+ response = get_user_contribution_calendar(user_id=USER_ID, access_token=TOKEN)
self.assertIsInstance(response, RawCalendar)
===========changed ref 1===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_years(self):
+ response = get_user_contribution_years(user_id=USER_ID, access_token=TOKEN)
- response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN)
# aside from validating APIResponse class, pydantic will validate tree
self.assertIsInstance(response, list)
===========changed ref 2===========
# module: backend.tests.processing.user.test_contributions
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
+ response = get_contributions(USER_ID, TOKEN)
- response = get_contributions("avgupta456", TOKEN)
self.assertIsInstance(response, UserContributions)
|
backend.tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_followers
|
Modified
|
avgupta456~github-trends
|
abdd9300be1b4d3792f472ed83597881e09a3736
|
change testing user
|
<0>:<add> response = get_user_followers(user_id=USER_ID, access_token=TOKEN)
<del> response = get_user_followers(user_id="avgupta456", access_token=TOKEN)
<3>:<add> response = get_user_followers(user_id=USER_ID, access_token=TOKEN, first=1)
<del> response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1)
|
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
# TODO: Add more validation here
def test_get_user_followers(self):
<0> response = get_user_followers(user_id="avgupta456", access_token=TOKEN)
<1> self.assertIsInstance(response, RawFollows)
<2>
<3> response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1)
<4> self.assertLessEqual(len(response.nodes), 1)
<5>
|
===========changed ref 0===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_events(self):
- response = get_user_contribution_events(
- user_id="avgupta456", access_token=TOKEN
- )
+ response = get_user_contribution_events(user_id=USER_ID, access_token=TOKEN)
self.assertIsInstance(response, RawEvents)
===========changed ref 1===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_calendar(self):
- response = get_user_contribution_calendar(
- user_id="avgupta456", access_token=TOKEN
- )
+ response = get_user_contribution_calendar(user_id=USER_ID, access_token=TOKEN)
self.assertIsInstance(response, RawCalendar)
===========changed ref 2===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_years(self):
+ response = get_user_contribution_years(user_id=USER_ID, access_token=TOKEN)
- response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN)
# aside from validating APIResponse class, pydantic will validate tree
self.assertIsInstance(response, list)
===========changed ref 3===========
# module: backend.tests.processing.user.test_contributions
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
+ response = get_contributions(USER_ID, TOKEN)
- response = get_contributions("avgupta456", TOKEN)
self.assertIsInstance(response, UserContributions)
|
backend.tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_following
|
Modified
|
avgupta456~github-trends
|
abdd9300be1b4d3792f472ed83597881e09a3736
|
change testing user
|
<0>:<add> response = get_user_following(user_id=USER_ID, access_token=TOKEN)
<del> response = get_user_following(user_id="avgupta456", access_token=TOKEN)
<3>:<add> response = get_user_following(user_id=USER_ID, access_token=TOKEN, first=1)
<del> response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1)
|
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_following(self):
<0> response = get_user_following(user_id="avgupta456", access_token=TOKEN)
<1> self.assertIsInstance(response, RawFollows)
<2>
<3> response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1)
<4> self.assertLessEqual(len(response.nodes), 1)
<5>
|
===========changed ref 0===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_events(self):
- response = get_user_contribution_events(
- user_id="avgupta456", access_token=TOKEN
- )
+ response = get_user_contribution_events(user_id=USER_ID, access_token=TOKEN)
self.assertIsInstance(response, RawEvents)
===========changed ref 1===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_calendar(self):
- response = get_user_contribution_calendar(
- user_id="avgupta456", access_token=TOKEN
- )
+ response = get_user_contribution_calendar(user_id=USER_ID, access_token=TOKEN)
self.assertIsInstance(response, RawCalendar)
===========changed ref 2===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_years(self):
+ response = get_user_contribution_years(user_id=USER_ID, access_token=TOKEN)
- response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN)
# aside from validating APIResponse class, pydantic will validate tree
self.assertIsInstance(response, list)
===========changed ref 3===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
# TODO: Add more validation here
def test_get_user_followers(self):
+ response = get_user_followers(user_id=USER_ID, access_token=TOKEN)
- response = get_user_followers(user_id="avgupta456", access_token=TOKEN)
self.assertIsInstance(response, RawFollows)
+ response = get_user_followers(user_id=USER_ID, access_token=TOKEN, first=1)
- response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1)
self.assertLessEqual(len(response.nodes), 1)
===========changed ref 4===========
# module: backend.tests.processing.user.test_contributions
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
+ response = get_contributions(USER_ID, TOKEN)
- response = get_contributions("avgupta456", TOKEN)
self.assertIsInstance(response, UserContributions)
|
backend.tests.external.github_api.graphql.test_template/TestTemplate.test_get_template
|
Modified
|
avgupta456~github-trends
|
abdd9300be1b4d3792f472ed83597881e09a3736
|
change testing user
|
<1>:<add> "variables": {"login": USER_ID},
<del> "variables": {"login": "avgupta456"},
|
# module: backend.tests.external.github_api.graphql.test_template
class TestTemplate(unittest.TestCase):
def test_get_template(self):
<0> query = {
<1> "variables": {"login": "avgupta456"},
<2> "query": """
<3> query getUser($login: String!) {
<4> user(login: $login){
<5> contributionsCollection{
<6> contributionCalendar{
<7> totalContributions
<8> }
<9> }
<10> }
<11> }
<12> """,
<13> }
<14> response = get_template(query, TOKEN)
<15>
<16> self.assertIn("data", response)
<17> data = response["data"]
<18> self.assertIn("user", data)
<19> user = data["user"]
<20> self.assertIn("contributionsCollection", user)
<21> contributionsCollection = user["contributionsCollection"]
<22> self.assertIn("contributionCalendar", contributionsCollection)
<23> contributionCalendar = contributionsCollection["contributionCalendar"]
<24> self.assertIn("totalContributions", contributionCalendar)
<25> totalContributions = contributionCalendar["totalContributions"]
<26> self.assertGreater(totalContributions, 0)
<27>
|
===========changed ref 0===========
# module: backend.tests.processing.user.test_contributions
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
+ response = get_contributions(USER_ID, TOKEN)
- response = get_contributions("avgupta456", TOKEN)
self.assertIsInstance(response, UserContributions)
===========changed ref 1===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_events(self):
- response = get_user_contribution_events(
- user_id="avgupta456", access_token=TOKEN
- )
+ response = get_user_contribution_events(user_id=USER_ID, access_token=TOKEN)
self.assertIsInstance(response, RawEvents)
===========changed ref 2===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_calendar(self):
- response = get_user_contribution_calendar(
- user_id="avgupta456", access_token=TOKEN
- )
+ response = get_user_contribution_calendar(user_id=USER_ID, access_token=TOKEN)
self.assertIsInstance(response, RawCalendar)
===========changed ref 3===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_years(self):
+ response = get_user_contribution_years(user_id=USER_ID, access_token=TOKEN)
- response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN)
# aside from validating APIResponse class, pydantic will validate tree
self.assertIsInstance(response, list)
===========changed ref 4===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_following(self):
+ response = get_user_following(user_id=USER_ID, access_token=TOKEN)
- response = get_user_following(user_id="avgupta456", access_token=TOKEN)
self.assertIsInstance(response, RawFollows)
+ response = get_user_following(user_id=USER_ID, access_token=TOKEN, first=1)
- response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1)
self.assertLessEqual(len(response.nodes), 1)
===========changed ref 5===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
# TODO: Add more validation here
def test_get_user_followers(self):
+ response = get_user_followers(user_id=USER_ID, access_token=TOKEN)
- response = get_user_followers(user_id="avgupta456", access_token=TOKEN)
self.assertIsInstance(response, RawFollows)
+ response = get_user_followers(user_id=USER_ID, access_token=TOKEN, first=1)
- response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1)
self.assertLessEqual(len(response.nodes), 1)
===========changed ref 6===========
# module: backend.constants
+ USER_ID = "AshishGupta938" # for testing, previously "avgupta456"
TOKEN = os.getenv("AUTH_TOKEN", "") # for authentication
TIMEOUT = 3 # max seconds to wait for api response
NODE_CHUNK_SIZE = 50 # number of nodes (commits) to query (max 100)
NODE_THREADS = 30 # number of node queries simultaneously (avoid blacklisting)
BLACKLIST = ["Jupyter Notebook", "HTML"] # languages to ignore
CUTOFF = 1000 # if > cutoff lines, assume imported, don't count
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
|
backend.tests.processing.user.test_follows/TestTemplate.test_get_contributions
|
Modified
|
avgupta456~github-trends
|
abdd9300be1b4d3792f472ed83597881e09a3736
|
change testing user
|
<0>:<add> response = get_user_follows(USER_ID, TOKEN)
<del> response = get_user_follows("avgupta456", TOKEN)
|
# module: backend.tests.processing.user.test_follows
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
<0> response = get_user_follows("avgupta456", TOKEN)
<1> self.assertIsInstance(response, UserFollows)
<2>
|
===========changed ref 0===========
# module: backend.tests.processing.user.test_contributions
class TestTemplate(unittest.TestCase):
def test_get_contributions(self):
+ response = get_contributions(USER_ID, TOKEN)
- response = get_contributions("avgupta456", TOKEN)
self.assertIsInstance(response, UserContributions)
===========changed ref 1===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_events(self):
- response = get_user_contribution_events(
- user_id="avgupta456", access_token=TOKEN
- )
+ response = get_user_contribution_events(user_id=USER_ID, access_token=TOKEN)
self.assertIsInstance(response, RawEvents)
===========changed ref 2===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_calendar(self):
- response = get_user_contribution_calendar(
- user_id="avgupta456", access_token=TOKEN
- )
+ response = get_user_contribution_calendar(user_id=USER_ID, access_token=TOKEN)
self.assertIsInstance(response, RawCalendar)
===========changed ref 3===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_contribution_years(self):
+ response = get_user_contribution_years(user_id=USER_ID, access_token=TOKEN)
- response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN)
# aside from validating APIResponse class, pydantic will validate tree
self.assertIsInstance(response, list)
===========changed ref 4===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
def test_get_user_following(self):
+ response = get_user_following(user_id=USER_ID, access_token=TOKEN)
- response = get_user_following(user_id="avgupta456", access_token=TOKEN)
self.assertIsInstance(response, RawFollows)
+ response = get_user_following(user_id=USER_ID, access_token=TOKEN, first=1)
- response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1)
self.assertLessEqual(len(response.nodes), 1)
===========changed ref 5===========
# module: backend.tests.external.github_api.graphql.test_user
class TestTemplate(unittest.TestCase):
# TODO: Add more validation here
def test_get_user_followers(self):
+ response = get_user_followers(user_id=USER_ID, access_token=TOKEN)
- response = get_user_followers(user_id="avgupta456", access_token=TOKEN)
self.assertIsInstance(response, RawFollows)
+ response = get_user_followers(user_id=USER_ID, access_token=TOKEN, first=1)
- response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1)
self.assertLessEqual(len(response.nodes), 1)
===========changed ref 6===========
# module: backend.constants
+ USER_ID = "AshishGupta938" # for testing, previously "avgupta456"
TOKEN = os.getenv("AUTH_TOKEN", "") # for authentication
TIMEOUT = 3 # max seconds to wait for api response
NODE_CHUNK_SIZE = 50 # number of nodes (commits) to query (max 100)
NODE_THREADS = 30 # number of node queries simultaneously (avoid blacklisting)
BLACKLIST = ["Jupyter Notebook", "HTML"] # languages to ignore
CUTOFF = 1000 # if > cutoff lines, assume imported, don't count
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
===========changed ref 7===========
# module: backend.tests.external.github_api.graphql.test_template
class TestTemplate(unittest.TestCase):
def test_get_template(self):
query = {
+ "variables": {"login": USER_ID},
- "variables": {"login": "avgupta456"},
"query": """
query getUser($login: String!) {
user(login: $login){
contributionsCollection{
contributionCalendar{
totalContributions
}
}
}
}
""",
}
response = get_template(query, TOKEN)
self.assertIn("data", response)
data = response["data"]
self.assertIn("user", data)
user = data["user"]
self.assertIn("contributionsCollection", user)
contributionsCollection = user["contributionsCollection"]
self.assertIn("contributionCalendar", contributionsCollection)
contributionCalendar = contributionsCollection["contributionCalendar"]
self.assertIn("totalContributions", contributionCalendar)
totalContributions = contributionCalendar["totalContributions"]
self.assertGreater(totalContributions, 0)
|
backend.packaging.user/main
|
Modified
|
avgupta456~github-trends
|
629c1a9375e931e1ee1a131999d7f2a172a9cdd9
|
make async
|
<1>:<del> data = gather(
<2>:<del> funcs=[get_contributions, get_user_follows],
<3>:<del> args_dicts=[
<4>:<del> {
<5>:<del> "user_id": user_id,
<6>:<del> "access_token": access_token,
<7>:<del> "start_date": start_date,
<8>:<del> "end_date": end_date,
<9>:<del> "timezone_str": timezone_str,
<10>:<del> },
<11>:<del> {"user_id": user_id, "access_token": access_token},
<12>:<del> ],
<13>:<add>
<add> contribs = await get_contributions(
<add> user_id, access_token, start_date, end_date, timezone_str
<14>:<add> follows = get_user_follows(user_id, access_token)
<add> return UserPackage(contribs=contribs, follows=follows)
<15>:<del> return UserPackage(contribs=data[0], follows=data[1])
<16>:<del>
|
# module: backend.packaging.user
+ def main(
- def main(
user_id: str,
access_token: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> UserPackage:
<0> """packages all processing steps for the user query"""
<1> data = gather(
<2> funcs=[get_contributions, get_user_follows],
<3> args_dicts=[
<4> {
<5> "user_id": user_id,
<6> "access_token": access_token,
<7> "start_date": start_date,
<8> "end_date": end_date,
<9> "timezone_str": timezone_str,
<10> },
<11> {"user_id": user_id, "access_token": access_token},
<12> ],
<13> )
<14>
<15> return UserPackage(contribs=data[0], follows=data[1])
<16>
|
===========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
__str__ = isoformat
__radd__ = __add__
at: processing.user.contributions
get_contributions(user_id: str, access_token: str, start_date: date=date.today() - timedelta(365), end_date: date=date.today(), timezone_str: str="US/Eastern") -> UserContributions
at: processing.user.follows
get_user_follows(user_id: str, access_token: str) -> UserFollows
|
backend.main/fail_gracefully
|
Modified
|
avgupta456~github-trends
|
629c1a9375e931e1ee1a131999d7f2a172a9cdd9
|
make async
|
<1>:<add> async def wrapper(
<add> response: Response, *args: List[Any], **kwargs: Dict[str, Any]
<del> def wrapper(response: Response, *args: List[Any], **kwargs: Dict[str, Any]) -> Any:
<2>:<add> ) -> Any:
<4>:<add> data = await func(response, *args, **kwargs)
<del> data = func(response, *args, **kwargs)
|
# module: backend.main
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.packaging.user
+ def main(
- def main(
user_id: str,
access_token: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> UserPackage:
"""packages all processing steps for the user query"""
- data = gather(
- funcs=[get_contributions, get_user_follows],
- args_dicts=[
- {
- "user_id": user_id,
- "access_token": access_token,
- "start_date": start_date,
- "end_date": end_date,
- "timezone_str": timezone_str,
- },
- {"user_id": user_id, "access_token": access_token},
- ],
+
+ contribs = await get_contributions(
+ user_id, access_token, start_date, end_date, timezone_str
)
+ follows = get_user_follows(user_id, access_token)
+ return UserPackage(contribs=contribs, follows=follows)
- return UserPackage(contribs=data[0], follows=data[1])
-
|
backend.main/get_user
|
Modified
|
avgupta456~github-trends
|
629c1a9375e931e1ee1a131999d7f2a172a9cdd9
|
make async
|
<0>:<add> return await _get_user(user_id)
<del> return _get_user(user_id)
|
# module: backend.main
@app.get("/user/{user_id}", status_code=status.HTTP_200_OK)
@fail_gracefully
+ async def get_user(response: Response, user_id: str) -> Any:
- def get_user(response: Response, user_id: str) -> Any:
<0> return _get_user(user_id)
<1>
|
===========unchanged ref 0===========
at: backend.main
app = FastAPI()
fail_gracefully(func: Callable[..., Any])
===========changed ref 0===========
# module: backend.main
def fail_gracefully(func: Callable[..., Any]):
@wraps(func) # needed to play nice with FastAPI decorator
+ async def wrapper(
+ response: Response, *args: List[Any], **kwargs: Dict[str, Any]
- def wrapper(response: Response, *args: List[Any], **kwargs: Dict[str, Any]) -> Any:
+ ) -> Any:
start = datetime.now()
try:
+ data = await func(response, *args, **kwargs)
- 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": "Error " + str(e),
"time": datetime.now() - start,
}
return wrapper
===========changed ref 1===========
# module: backend.packaging.user
+ def main(
- def main(
user_id: str,
access_token: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> UserPackage:
"""packages all processing steps for the user query"""
- data = gather(
- funcs=[get_contributions, get_user_follows],
- args_dicts=[
- {
- "user_id": user_id,
- "access_token": access_token,
- "start_date": start_date,
- "end_date": end_date,
- "timezone_str": timezone_str,
- },
- {"user_id": user_id, "access_token": access_token},
- ],
+
+ contribs = await get_contributions(
+ user_id, access_token, start_date, end_date, timezone_str
)
+ follows = get_user_follows(user_id, access_token)
+ return UserPackage(contribs=contribs, follows=follows)
- return UserPackage(contribs=data[0], follows=data[1])
-
|
backend.helper.gather/gather
|
Modified
|
avgupta456~github-trends
|
629c1a9375e931e1ee1a131999d7f2a172a9cdd9
|
make async
|
<2>:<add> output: List[Any] = list(
<add> await gather_with_concurrency(
<add> max_threads,
<add> *(async_function(func)(**kwargs) for func, kwargs in zip(funcs, args_dicts))
<add> )
<del> return asyncio.run(
<3>:<del> _gather(funcs=funcs, args_dicts=args_dicts, max_threads=max_threads)
|
# module: backend.helper.gather
+ def gather(
- def gather(
funcs: List[Callable[..., Any]],
args_dicts: List[Dict[str, Any]],
max_threads: int = 5,
) -> List[Any]:
<0> """runs the given functions asynchronously"""
<1>
<2> return asyncio.run(
<3> _gather(funcs=funcs, args_dicts=args_dicts, max_threads=max_threads)
<4> )
<5>
|
===========changed ref 0===========
# module: backend.helper.gather
- def _gather(
- funcs: List[Callable[..., Any]],
- args_dicts: List[Dict[str, Any]],
- max_threads: int = 5,
- ) -> List[Any]:
- """runs the given functions asynchronously"""
-
- async_funcs = [async_function(func) for func in funcs]
-
- output: List[Any] = list(
- await gather_with_concurrency(
- max_threads,
- *(
- async_func(**kwargs)
- for async_func, kwargs in zip(async_funcs, args_dicts)
- )
- )
- )
-
- return output
-
===========changed ref 1===========
# module: backend.main
@app.get("/user/{user_id}", status_code=status.HTTP_200_OK)
@fail_gracefully
+ async def get_user(response: Response, user_id: str) -> Any:
- def get_user(response: Response, user_id: str) -> Any:
+ return await _get_user(user_id)
- return _get_user(user_id)
===========changed ref 2===========
# module: backend.main
def fail_gracefully(func: Callable[..., Any]):
@wraps(func) # needed to play nice with FastAPI decorator
+ async def wrapper(
+ response: Response, *args: List[Any], **kwargs: Dict[str, Any]
- def wrapper(response: Response, *args: List[Any], **kwargs: Dict[str, Any]) -> Any:
+ ) -> Any:
start = datetime.now()
try:
+ data = await func(response, *args, **kwargs)
- 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": "Error " + str(e),
"time": datetime.now() - start,
}
return wrapper
===========changed ref 3===========
# module: backend.packaging.user
+ def main(
- def main(
user_id: str,
access_token: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> UserPackage:
"""packages all processing steps for the user query"""
- data = gather(
- funcs=[get_contributions, get_user_follows],
- args_dicts=[
- {
- "user_id": user_id,
- "access_token": access_token,
- "start_date": start_date,
- "end_date": end_date,
- "timezone_str": timezone_str,
- },
- {"user_id": user_id, "access_token": access_token},
- ],
+
+ contribs = await get_contributions(
+ user_id, access_token, start_date, end_date, timezone_str
)
+ follows = get_user_follows(user_id, access_token)
+ return UserPackage(contribs=contribs, follows=follows)
- return UserPackage(contribs=data[0], follows=data[1])
-
|
backend.endpoints.user/main
|
Modified
|
avgupta456~github-trends
|
629c1a9375e931e1ee1a131999d7f2a172a9cdd9
|
make async
|
<4>:<add> if use_cache:
<add> output = get_user_endpoint(user_id)
<del> output = get_user_endpoint(user_id)
<5>:<add> if output is not None:
<del> if output is not None:
<6>:<add> return output
<del> return output
<8>:<add> data = await get_data(user_id, access_token, start_date, end_date, timezone_str)
<del> data = get_data(user_id, access_token, start_date, end_date, timezone_str)
<10>:<del> funcs = [
<11>:<del> get_top_languages,
<12>:<del> get_top_repos,
<13>:<del> get_contribs_per_day,
<14>:<del> get_contribs_per_repo_per_day,
<15>:<del> ]
<16>:<del> [top_languages, top_repos, contribs_per_day, contribs_per_repo_per_day] = gather(
<17>:<del> funcs=funcs, args_dicts=[{"data": data} for _ in range(len(funcs))]
<18>:<del> )
<19>:<add> top_languages = get_top_languages(data)
<add> top_repos = get_top_repos(data)
<add> contribs_per_day = get_contribs_per_day(data)
<add> contribs_per_repo_per_day = get_contribs_per_repo_per_day(data)
|
# module: backend.endpoints.user
@lru_cache(maxsize=1024)
+ async def main(
- def main(
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
+ use_cache: bool = True,
) -> Dict[str, Any]:
<0> access_token = get_access_token(user_id)
<1> if access_token == "":
<2> raise LookupError("Invalid UserId")
<3>
<4> output = get_user_endpoint(user_id)
<5> if output is not None:
<6> return output
<7>
<8> data = get_data(user_id, access_token, start_date, end_date, timezone_str)
<9>
<10> funcs = [
<11> get_top_languages,
<12> get_top_repos,
<13> get_contribs_per_day,
<14> get_contribs_per_repo_per_day,
<15> ]
<16> [top_languages, top_repos, contribs_per_day, contribs_per_repo_per_day] = gather(
<17> funcs=funcs, args_dicts=[{"data": data} for _ in range(len(funcs))]
<18> )
<19>
<20> output = {
<21> "top_languages": top_languages,
<22> "top_repos": top_repos,
<23> "contribs_per_day": contribs_per_day,
<24> "contribs_per_repo_per_day": contribs_per_repo_per_day,
<25> }
<26>
<27> set_user_endpoint(user_id, output)
<28>
<29> return output
<30>
|
===========unchanged ref 0===========
at: analytics.user.commits
get_top_languages(data: UserPackage) -> List[dict_type]
get_top_repos(data: UserPackage) -> List[Any]
at: analytics.user.contribs_per_day
get_contribs_per_day(data: UserPackage) -> Dict[str, int]
get_contribs_per_repo_per_day(data: UserPackage) -> Dict[str, Dict[str, int]]
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: external.google_datastore.datastore
get_access_token(user_id: str) -> str
set_user_endpoint(user_id: str, data: Dict[str, Any]) -> None
get_user_endpoint(user_id: str) -> Any
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.main
@app.get("/user/{user_id}", status_code=status.HTTP_200_OK)
@fail_gracefully
+ async def get_user(response: Response, user_id: str) -> Any:
- def get_user(response: Response, user_id: str) -> Any:
+ return await _get_user(user_id)
- return _get_user(user_id)
===========changed ref 1===========
# module: backend.helper.gather
+ def gather(
- def gather(
funcs: List[Callable[..., Any]],
args_dicts: List[Dict[str, Any]],
max_threads: int = 5,
) -> List[Any]:
"""runs the given functions asynchronously"""
+ output: List[Any] = list(
+ await gather_with_concurrency(
+ max_threads,
+ *(async_function(func)(**kwargs) for func, kwargs in zip(funcs, args_dicts))
+ )
- return asyncio.run(
- _gather(funcs=funcs, args_dicts=args_dicts, max_threads=max_threads)
)
===========changed ref 2===========
# module: backend.helper.gather
- def _gather(
- funcs: List[Callable[..., Any]],
- args_dicts: List[Dict[str, Any]],
- max_threads: int = 5,
- ) -> List[Any]:
- """runs the given functions asynchronously"""
-
- async_funcs = [async_function(func) for func in funcs]
-
- output: List[Any] = list(
- await gather_with_concurrency(
- max_threads,
- *(
- async_func(**kwargs)
- for async_func, kwargs in zip(async_funcs, args_dicts)
- )
- )
- )
-
- return output
-
===========changed ref 3===========
# module: backend.main
def fail_gracefully(func: Callable[..., Any]):
@wraps(func) # needed to play nice with FastAPI decorator
+ async def wrapper(
+ response: Response, *args: List[Any], **kwargs: Dict[str, Any]
- def wrapper(response: Response, *args: List[Any], **kwargs: Dict[str, Any]) -> Any:
+ ) -> Any:
start = datetime.now()
try:
+ data = await func(response, *args, **kwargs)
- 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": "Error " + str(e),
"time": datetime.now() - start,
}
return wrapper
===========changed ref 4===========
# module: backend.packaging.user
+ def main(
- def main(
user_id: str,
access_token: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> UserPackage:
"""packages all processing steps for the user query"""
- data = gather(
- funcs=[get_contributions, get_user_follows],
- args_dicts=[
- {
- "user_id": user_id,
- "access_token": access_token,
- "start_date": start_date,
- "end_date": end_date,
- "timezone_str": timezone_str,
- },
- {"user_id": user_id, "access_token": access_token},
- ],
+
+ contribs = await get_contributions(
+ user_id, access_token, start_date, end_date, timezone_str
)
+ follows = get_user_follows(user_id, access_token)
+ return UserPackage(contribs=contribs, follows=follows)
- return UserPackage(contribs=data[0], follows=data[1])
-
|
backend.main/fail_gracefully
|
Modified
|
avgupta456~github-trends
|
7c6b80451993aa262700ace7b642f4650f4dc799
|
bug fixes
|
<1>:<del> async def wrapper(
<2>:<add> def wrapper(response: Response, *args: List[Any], **kwargs: Dict[str, Any]) -> Any:
<del> response: Response, *args: List[Any], **kwargs: Dict[str, Any]
<3>:<del> ) -> Any:
<6>:<add> data = func(response, *args, **kwargs)
<del> data = await func(response, *args, **kwargs)
|
# module: backend.main
def 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
__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')
|
backend.external.google_datastore.datastore/set_access_token
|
Modified
|
avgupta456~github-trends
|
a60c023b01c05da537881bf5ded17ac471bc950e
|
add user refresh functionality
|
<0>:<add> obj_key = datastore_client.key("ID_AT", user_id)
<del> obj_key_1 = datastore_client.key("ID_AT", user_id)
<1>:<add> obj = datastore.Entity(key=obj_key)
<del> obj_1 = datastore.Entity(key=obj_key_1)
<2>:<add> obj["user_id"] = user_id
<add> obj["access_token"] = access_token
<del> obj_1["access_token"] = access_token
<3>:<add> datastore_client.put(obj)
<del> datastore_client.put(obj_1)
<4>:<del> obj_key_2 = datastore_client.key("AT_ID", access_token)
<5>:<del> obj_2 = datastore.Entity(key=obj_key_2)
<6>:<del> obj_2["user_id"] = user_id
<7>:<del> datastore_client.put(obj_2)
|
# module: backend.external.google_datastore.datastore
def set_access_token(user_id: str, access_token: str) -> None:
<0> obj_key_1 = datastore_client.key("ID_AT", user_id)
<1> obj_1 = datastore.Entity(key=obj_key_1)
<2> obj_1["access_token"] = access_token
<3> datastore_client.put(obj_1)
<4> obj_key_2 = datastore_client.key("AT_ID", access_token)
<5> obj_2 = datastore.Entity(key=obj_key_2)
<6> obj_2["user_id"] = user_id
<7> datastore_client.put(obj_2)
<8>
|
===========unchanged ref 0===========
at: backend.external.google_datastore.datastore
datastore_client = datastore.Client()
|
backend.main/read_root
|
Modified
|
avgupta456~github-trends
|
2773b72e66e5a3b9563db3066848e67b55b77d4b
|
test cloudbuild
|
<0>:<add> return {"Hello": "World!"}
<del> return {"Hello": "World"}
|
# module: backend.main
@app.get("/")
async def read_root():
<0> return {"Hello": "World"}
<1>
|
===========unchanged ref 0===========
at: backend.main
app = FastAPI()
|
backend.main/read_root
|
Modified
|
avgupta456~github-trends
|
79017a4e3d8bb29f47e7ec86ca128b40048679d4
|
Update main.py
|
<0>:<add> return {"Hello": "World"}
<del> return {"Hello": "World!"}
|
# module: backend.main
@app.get("/")
async def read_root():
<0> return {"Hello": "World!"}
<1>
|
===========unchanged ref 0===========
at: backend.main
app = FastAPI()
|
backend.tests.processing.user.test_contributions/TestTemplate.test_get_contributions
|
Modified
|
avgupta456~github-trends
|
afc9b381805ccf152d21c43e520cbe5d3efb89aa
|
async unittest
|
<0>:<add> response = await get_contributions(USER_ID, TOKEN)
<del> response = get_contributions(USER_ID, TOKEN)
|
# module: backend.tests.processing.user.test_contributions
+ class TestTemplate(aiounittest.AsyncTestCase):
- class TestTemplate(unittest.TestCase):
+ def test_get_contributions(self):
- def test_get_contributions(self):
<0> response = get_contributions(USER_ID, TOKEN)
<1> self.assertIsInstance(response, UserContributions)
<2>
|
===========unchanged ref 0===========
at: constants
USER_ID = "AshishGupta938" # for testing, previously "avgupta456"
TOKEN = os.getenv("AUTH_TOKEN", "") # for authentication
at: processing.user.contributions
get_contributions(user_id: str, access_token: str, start_date: date=date.today() - timedelta(365), end_date: date=date.today(), timezone_str: str="US/Eastern") -> UserContributions
|
backend.analytics.user.commits/get_top_repos
|
Modified
|
avgupta456~github-trends
|
0fea178c495e03d2268994d4d7445713e0a88292
|
remove deepsource
|
<3>:<add> "languages": list(repo_stats.languages.keys()),
<del> "languages": [lang for lang in repo_stats.languages],
|
# module: backend.analytics.user.commits
def get_top_repos(data: UserPackage) -> List[Any]:
<0> repos: List[Any] = [
<1> {
<2> repo: repo,
<3> "languages": [lang for lang in repo_stats.languages],
<4> "additions": sum([x.additions for x in repo_stats.languages.values()]),
<5> "deletions": sum([x.deletions for x in repo_stats.languages.values()]),
<6> }
<7> for repo, repo_stats in data.contribs.repo_stats.items()
<8> ]
<9>
<10> for repo in repos:
<11> repo["added"] = int(repo["additions"]) - int(repo["deletions"])
<12> repo["changed"] = int(repo["additions"]) + int(repo["deletions"])
<13>
<14> repos = sorted(repos, key=lambda x: x["changed"], reverse=True)
<15>
<16> return repos[:5]
<17>
|
===========unchanged ref 0===========
at: 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: models.user.contribs.Language
additions: int
deletions: int
at: models.user.contribs.UserContributions
total_stats: ContributionStats
total: List[ContributionDay]
repo_stats: Dict[str, ContributionStats]
repos: Dict[str, List[ContributionDay]]
at: models.user.package.UserPackage
contribs: UserContributions
follows: UserFollows
at: typing
List = _alias(list, 1, inst=False, name='List')
|
backend.main/login
|
Modified
|
avgupta456~github-trends
|
e376d5d23167866354c12c3c4a1d00b560f1cc6b
|
access env vars
|
<0>:<add> if not PUBSUB_PUB:
<add> raise HTTPException(500, "Login using PUB Server, not SUB Server")
|
# module: backend.main
@app.post("/login/{code}", status_code=status.HTTP_200_OK)
@fail_gracefully
def login(response: Response, code: str) -> Any:
<0> return get_access_token(code)
<1>
|
===========unchanged ref 0===========
at: backend.main
app = FastAPI()
fail_gracefully(func: Callable[..., Any])
|
backend.src.main/test_post
|
Modified
|
avgupta456~github-trends
|
3824736881715a82d02cf5aed3756438af4cb31c
|
Update main.py
|
<2>:<add> data = json.dumps(int(update)).encode("utf-8")
<del> data = int(update)
|
# module: backend.src.main
@app.get("/pubsub/{update}", status_code=status.HTTP_200_OK)
@fail_gracefully
def test_post(response: Response, update: str) -> Any:
<0> topic_path = publisher.topic_path("github-298920", "test") # type: ignore
<1>
<2> data = int(update)
<3>
<4> publisher.publish(topic_path, data=data) # type: ignore
<5>
|
===========unchanged ref 0===========
at: backend.src.main
app = FastAPI()
fail_gracefully(func: Callable[..., Any])
publisher = pubsub_v1.PublisherClient()
at: json
dumps(obj: Any, *, skipkeys: bool=..., ensure_ascii: bool=..., check_circular: bool=..., allow_nan: bool=..., cls: Optional[Type[JSONEncoder]]=..., indent: Union[None, int, str]=..., separators: Optional[Tuple[str, str]]=..., default: Optional[Callable[[Any], Any]]=..., sort_keys: bool=..., **kwds: Any) -> str
|
backend.src.main/test_post
|
Modified
|
avgupta456~github-trends
|
08bf18bbabd38a42966799b8196b0c035f53c43e
|
Update main.py
|
<2>:<add> data = json.dumps({"num": int(update)}).encode("utf-8")
<del> data = json.dumps(int(update)).encode("utf-8")
|
# module: backend.src.main
@app.get("/pubsub/{update}", status_code=status.HTTP_200_OK)
@fail_gracefully
def test_post(response: Response, update: str) -> Any:
<0> topic_path = publisher.topic_path("github-298920", "test") # type: ignore
<1>
<2> data = json.dumps(int(update)).encode("utf-8")
<3>
<4> publisher.publish(topic_path, data=data) # type: ignore
<5>
<6> return update
<7>
|
===========unchanged ref 0===========
at: backend.src.main
app = FastAPI()
fail_gracefully(func: Callable[..., Any])
publisher = pubsub_v1.PublisherClient()
at: json
dumps(obj: Any, *, skipkeys: bool=..., ensure_ascii: bool=..., check_circular: bool=..., allow_nan: bool=..., cls: Optional[Type[JSONEncoder]]=..., indent: Union[None, int, str]=..., separators: Optional[Tuple[str, str]]=..., default: Optional[Callable[[Any], Any]]=..., sort_keys: bool=..., **kwds: Any) -> str
|
backend.src.main/test_pubsub
|
Modified
|
avgupta456~github-trends
|
08bf18bbabd38a42966799b8196b0c035f53c43e
|
Update main.py
|
<0>:<add> print(PUBSUB_TOKEN)
<1>:<add> raise HTTPException(400, "Incorrect Token")
<del> return HTTPException(400, "Incorrect Token")
<8>:<add> count += data["num"]
<del> count += data
|
# module: backend.src.main
@app.post("/pubsub/push/{token}", status_code=status.HTTP_200_OK)
+ @async_fail_gracefully
- @fail_gracefully
async def test_pubsub(response: Response, token: str, request: Request) -> Any:
<0> if token != PUBSUB_TOKEN:
<1> return HTTPException(400, "Incorrect Token")
<2>
<3> data = await request.json()
<4>
<5> print(data)
<6>
<7> global count
<8> count += data
<9>
|
===========unchanged ref 0===========
at: backend.src.main
app = FastAPI()
async_fail_gracefully(func: Callable[..., Any])
at: src.constants
PUBSUB_TOKEN = os.getenv("PUBSUB_TOKEN", "")
===========changed ref 0===========
# module: backend.src.main
@app.get("/pubsub/{update}", status_code=status.HTTP_200_OK)
@fail_gracefully
def test_post(response: Response, update: str) -> Any:
topic_path = publisher.topic_path("github-298920", "test") # type: ignore
+ data = json.dumps({"num": int(update)}).encode("utf-8")
- data = json.dumps(int(update)).encode("utf-8")
publisher.publish(topic_path, data=data) # type: ignore
return update
|
backend.src.main/read_root
|
Modified
|
avgupta456~github-trends
|
d410bf066a54f99c942145cdfbfab9d9c5326385
|
Update main.py
|
<0>:<add> return {"Hello World": PUBSUB_TOKEN}
<del> return {"Hello": "World"}
|
# module: backend.src.main
@app.get("/")
async def read_root():
<0> return {"Hello": "World"}
<1>
|
===========unchanged ref 0===========
at: backend.src.main
app = FastAPI()
at: src.constants
PUBSUB_TOKEN = os.getenv("PUBSUB_TOKEN", "")
|
backend.src.main/read_root
|
Modified
|
avgupta456~github-trends
|
4470d895bec5c91fea154bf665938e5da52ca95e
|
Update main.py
|
<0>:<add> return {"Hello World": [PUBSUB_TOKEN, OAUTH_CLIENT_SECRET]}
<del> return {"Hello World": PUBSUB_TOKEN}
|
# module: backend.src.main
@app.get("/")
async def read_root():
<0> return {"Hello World": PUBSUB_TOKEN}
<1>
|
===========unchanged ref 0===========
at: backend.src.main
app = FastAPI()
at: src.constants
OAUTH_CLIENT_SECRET = os.getenv("OAUTH_CLIENT_SECRET", "") # client secret for App
PUBSUB_TOKEN = os.getenv("PUBSUB_TOKEN", "")
|
backend.src.main/test_pubsub
|
Modified
|
avgupta456~github-trends
|
7073250e952ce5758c8d9eaa784bce7140ff3f50
|
Update main.py
|
<5>:<add> data = data["message"]["data"].decode("utf-8")
|
# module: backend.src.main
@app.post("/push/{token}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def test_pubsub(response: Response, token: str, request: Request) -> Any:
<0> print(PUBSUB_TOKEN)
<1> if token != PUBSUB_TOKEN:
<2> raise HTTPException(400, "Incorrect Token")
<3>
<4> data = await request.json()
<5>
<6> print(data)
<7>
<8> global count
<9> count += data["num"]
<10>
|
===========unchanged ref 0===========
at: backend.src.main
app = FastAPI()
async_fail_gracefully(func: Callable[..., Any])
at: src.constants
PUBSUB_TOKEN = os.getenv("PUBSUB_TOKEN", "")
|
backend.src.main/test_pubsub
|
Modified
|
avgupta456~github-trends
|
f9686f2b63a17c4dd91ba1ffa6fc5ce8e64c73a1
|
Update main.py
|
<5>:<add> data = json.loads(base64.b64decode(data["message"]["data"]))
<del> data = data["message"]["data"].decode("utf-8")
|
# module: backend.src.main
@app.post("/push/{token}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def test_pubsub(response: Response, token: str, request: Request) -> Any:
<0> print(PUBSUB_TOKEN)
<1> if token != PUBSUB_TOKEN:
<2> raise HTTPException(400, "Incorrect Token")
<3>
<4> data = await request.json()
<5> data = data["message"]["data"].decode("utf-8")
<6>
<7> print(data)
<8>
<9> global count
<10> count += data["num"]
<11>
|
===========unchanged ref 0===========
at: backend.src.main
app = FastAPI()
async_fail_gracefully(func: Callable[..., Any])
at: base64
b64decode(s: _decodable, altchars: Optional[bytes]=..., validate: bool=...) -> bytes
at: json
loads(s: Union[str, bytes], *, cls: Optional[Type[JSONDecoder]]=..., object_hook: Optional[Callable[[Dict[Any, Any]], Any]]=..., parse_float: Optional[Callable[[str], Any]]=..., parse_int: Optional[Callable[[str], Any]]=..., parse_constant: Optional[Callable[[str], Any]]=..., object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]]=..., **kwds: Any) -> Any
at: src.constants
PUBSUB_TOKEN = os.getenv("PUBSUB_TOKEN", "")
===========changed ref 0===========
# module: backend.src.main
+ count: int = 0
- count = 0
publisher = pubsub_v1.PublisherClient()
|
backend.src.main/read_root
|
Modified
|
avgupta456~github-trends
|
a05dff5f2449b59ae25edae2fd2d402df558bb10
|
wrap up secrets work
|
<0>:<add> return {"Hello": "World"}
<del> return {"Hello World": [PUBSUB_TOKEN, OAUTH_CLIENT_SECRET]}
|
# module: backend.src.main
@app.get("/")
async def read_root():
<0> return {"Hello World": [PUBSUB_TOKEN, OAUTH_CLIENT_SECRET]}
<1>
|
===========unchanged ref 0===========
at: backend.src.main
app = FastAPI()
|
backend.src.main/login
|
Modified
|
avgupta456~github-trends
|
0ee964a03c5beccb8bf25488672172fcc2516a17
|
reorganization
|
<0>:<del> if not PUBSUB_PUB:
<1>:<del> raise HTTPException(500, "Login using PUB Server, not SUB Server")
|
# module: backend.src.main
@app.post("/login/{code}", status_code=status.HTTP_200_OK)
@fail_gracefully
def login(response: Response, code: str) -> Any:
<0> if not PUBSUB_PUB:
<1> raise HTTPException(500, "Login using PUB Server, not SUB Server")
<2> return get_access_token(code)
<3>
|
===========changed ref 0===========
# module: backend.src.main
- @app.get("/test", status_code=status.HTTP_200_OK)
- @fail_gracefully
- def test(response: Response) -> Any:
- return {"test": count}
-
===========changed ref 1===========
# module: backend.src.main
- @app.get("/user/get/{user_id}", status_code=status.HTTP_200_OK)
- @async_fail_gracefully
- async def get_user_endpoint(response: Response, user_id: str) -> DBUserModel:
- return await get_user(user_id)
-
===========changed ref 2===========
# module: backend.src.main
- @app.get("/user/create/{user_id}/{access_token}", status_code=status.HTTP_200_OK)
- @async_fail_gracefully
- async def create_user_endpoint(
- response: Response, user_id: str, access_token: str
- ) -> str:
- return await create_user(user_id, access_token)
-
===========changed ref 3===========
# module: backend.src.main
+ @app.get("/user/{user_id}", status_code=status.HTTP_200_OK)
+ @async_fail_gracefully
+ async def get_user(response: Response, user_id: str) -> Any:
+ return await _get_user(user_id)
+
===========changed ref 4===========
# module: backend.src.main
- @app.post("/push/{token}", status_code=status.HTTP_200_OK)
- @async_fail_gracefully
- async def test_pubsub(response: Response, token: str, request: Request) -> Any:
- print(PUBSUB_TOKEN)
- if token != PUBSUB_TOKEN:
- raise HTTPException(400, "Incorrect Token")
-
- data = await request.json()
- data = json.loads(base64.b64decode(data["message"]["data"]))
-
- print(data)
-
- global count
- count += data["num"]
-
===========changed ref 5===========
# module: backend.src.main
- @app.get("/pubsub/{update}", status_code=status.HTTP_200_OK)
- @fail_gracefully
- def test_post(response: Response, update: str) -> Any:
- topic_path = publisher.topic_path("github-298920", "test") # type: ignore
-
- data = json.dumps({"num": int(update)}).encode("utf-8")
-
- publisher.publish(topic_path, data=data) # type: ignore
-
- return update
-
===========changed ref 6===========
# module: backend.src.main
+ app.include_router(user_router, prefix="/user", tags=["Users"])
+ app.include_router(pubsub_router, prefix="/pubsub", tags=["PubSub"])
- count: int = 0
- publisher = pubsub_v1.PublisherClient()
-
===========changed ref 7===========
# module: backend.src.main
- def async_fail_gracefully(func: Callable[..., Any]):
- @wraps(func) # needed to play nice with FastAPI decorator
- async def wrapper(
- response: Response, *args: List[Any], **kwargs: Dict[str, Any]
- ) -> Any:
- start = datetime.now()
- try:
- data = await 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": "Error " + str(e),
- "time": datetime.now() - start,
- }
-
- return wrapper
-
===========changed ref 8===========
# module: backend.src.main
- 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": "Error " + str(e),
- "time": datetime.now() - start,
- }
-
- return wrapper
-
===========changed ref 9===========
+ # module: backend.src.external.pubsub.templates
+
+
===========changed ref 10===========
+ # module: backend.src.routers.users
+
+
===========changed ref 11===========
+ # module: backend.src.routers.users
+ router = APIRouter()
+
===========changed ref 12===========
+ # module: backend.src.external.pubsub.templates
+ publisher = pubsub_v1.PublisherClient()
+
===========changed ref 13===========
+ # module: backend.src.routers.users
+ @router.get("/user/get/{user_id}", status_code=status.HTTP_200_OK)
+ @async_fail_gracefully
+ async def get_user_endpoint(response: Response, user_id: str) -> Optional[DBUserModel]:
+ return await get_user(user_id)
+
===========changed ref 14===========
+ # module: backend.src.routers.users
+ @router.get("/create/{user_id}/{access_token}", status_code=status.HTTP_200_OK)
+ @async_fail_gracefully
+ async def create_user_endpoint(
+ response: Response, user_id: str, access_token: str
+ ) -> str:
+ return await create_user(user_id, access_token)
+
===========changed ref 15===========
+ # module: backend.src.external.pubsub.templates
+ def publish_to_topic(topic: str, message: Dict[str, Any]) -> None:
+ topic_path = publisher.topic_path(PROJECT_ID, topic) # type: ignore
+ data = json.dumps(message).encode("utf-8")
+ publisher.publish(topic_path, data=data) # type: ignore
+
===========changed ref 16===========
+ # module: backend.src.external.pubsub.templates
+ def parse_request(token: str, request: Request) -> Dict[str, Any]:
+ if token != PUBSUB_TOKEN:
+ raise HTTPException(400, "Invalid token")
+
+ data = await request.json()
+ data = json.loads(base64.b64decode(data["message"]["data"]))
+
+ return data
+
===========changed ref 17===========
# module: backend.src.utils
+ 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": "Error " + str(e),
+ "time": datetime.now() - start,
+ }
+
+ return wrapper
+
|
backend.src.db.functions.users/create_user
|
Modified
|
avgupta456~github-trends
|
7cb0bc4f3caff4a75f75e9bb81ef6f9ad04479f0
|
remove datastore
|
<0>:<del> user = UserModel.parse_obj({"user_id": user_id, "access_token": access_token})
<1>:<add> await USERS.update_one( # type: ignore
<del> await USERS.insert_one(user.dict()) # type: ignore
<2>:<add> {"user_id": user_id},
<add> {"$set": {"user_id": user_id, "access_token": access_token}},
<add> upsert=True,
<add> )
|
# module: backend.src.db.functions.users
def create_user(user_id: str, access_token: str) -> str:
<0> user = UserModel.parse_obj({"user_id": user_id, "access_token": access_token})
<1> await USERS.insert_one(user.dict()) # type: ignore
<2> return user_id
<3>
|
===========changed ref 0===========
# module: backend.src.db.functions.get
+ def get_user_by_access_token(access_token: str) -> UserModel:
+ user: Dict[str, Any] = await USERS.find_one({"access_token": access_token}) # type: ignore
+ return UserModel.parse_obj(user)
+
===========changed ref 1===========
# module: backend.src.db.functions.get
- def get_user(user_id: str) -> UserModel:
- user: Dict[str, Any] = await USERS.find_one({"user_id": user_id}) # type: ignore
- return UserModel.parse_obj(user)
-
===========changed ref 2===========
# module: backend.src.db.functions.get
- def get_user(user_id: str) -> UserModel:
- user: Dict[str, Any] = await USERS.find_one({"user_id": user_id}) # type: ignore
- return UserModel.parse_obj(user)
-
|
backend.src.endpoints.user/main
|
Modified
|
avgupta456~github-trends
|
7cb0bc4f3caff4a75f75e9bb81ef6f9ad04479f0
|
remove datastore
|
<0>:<add> access_token = (await get_user_by_user_id(user_id)).access_token
<del> access_token = get_access_token(user_id)
<3>:<del>
<4>:<del> if use_cache:
<5>:<del> output = get_user_endpoint(user_id)
<6>:<del> if output is not None:
<7>:<del> return output
<23>:<del> set_user_endpoint(user_id, output)
<24>:<del>
|
# module: backend.src.endpoints.user
def main(
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
use_cache: bool = True,
) -> Dict[str, Any]:
<0> access_token = get_access_token(user_id)
<1> if access_token == "":
<2> raise LookupError("Invalid UserId")
<3>
<4> if use_cache:
<5> output = get_user_endpoint(user_id)
<6> if output is not None:
<7> return output
<8>
<9> data = await get_data(user_id, access_token, start_date, end_date, timezone_str)
<10>
<11> top_languages = get_top_languages(data)
<12> top_repos = get_top_repos(data)
<13> contribs_per_day = get_contribs_per_day(data)
<14> contribs_per_repo_per_day = get_contribs_per_repo_per_day(data)
<15>
<16> output = {
<17> "top_languages": top_languages,
<18> "top_repos": top_repos,
<19> "contribs_per_day": contribs_per_day,
<20> "contribs_per_repo_per_day": contribs_per_repo_per_day,
<21> }
<22>
<23> set_user_endpoint(user_id, output)
<24>
<25> return output
<26>
|
===========unchanged ref 0===========
at: src.analytics.user.commits
get_top_languages(data: UserPackage) -> List[dict_type]
get_top_repos(data: UserPackage) -> List[Any]
at: src.analytics.user.contribs_per_day
get_contribs_per_day(data: UserPackage) -> Dict[str, int]
get_contribs_per_repo_per_day(data: UserPackage) -> Dict[str, Dict[str, int]]
at: src.db.functions.get
get_user_by_user_id(user_id: str) -> UserModel
at: src.db.models.users.UserModel
user_id: str
access_token: str
at: src.packaging.user
main(user_id: str, access_token: str, start_date: date=date.today() - timedelta(365), end_date: date=date.today(), timezone_str: str="US/Eastern") -> UserPackage
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.db.functions.get
+ def get_user_by_access_token(access_token: str) -> UserModel:
+ user: Dict[str, Any] = await USERS.find_one({"access_token": access_token}) # type: ignore
+ return UserModel.parse_obj(user)
+
===========changed ref 1===========
# module: backend.src.db.functions.get
- def get_user(user_id: str) -> UserModel:
- user: Dict[str, Any] = await USERS.find_one({"user_id": user_id}) # type: ignore
- return UserModel.parse_obj(user)
-
===========changed ref 2===========
# module: backend.src.db.functions.get
- def get_user(user_id: str) -> UserModel:
- user: Dict[str, Any] = await USERS.find_one({"user_id": user_id}) # type: ignore
- return UserModel.parse_obj(user)
-
===========changed ref 3===========
# module: backend.src.db.functions.users
def create_user(user_id: str, access_token: str) -> str:
- user = UserModel.parse_obj({"user_id": user_id, "access_token": access_token})
+ await USERS.update_one( # type: ignore
- await USERS.insert_one(user.dict()) # type: ignore
+ {"user_id": user_id},
+ {"$set": {"user_id": user_id, "access_token": access_token}},
+ upsert=True,
+ )
return user_id
|
backend.src.main/login
|
Modified
|
avgupta456~github-trends
|
7cb0bc4f3caff4a75f75e9bb81ef6f9ad04479f0
|
remove datastore
|
<0>:<add> return await get_access_token(code)
<del> return get_access_token(code)
|
# module: backend.src.main
@app.post("/login/{code}", status_code=status.HTTP_200_OK)
+ @async_fail_gracefully
- @fail_gracefully
+ async def login(response: Response, code: str) -> Any:
- def login(response: Response, code: str) -> Any:
<0> return get_access_token(code)
<1>
|
===========unchanged ref 0===========
at: src.endpoints.github_auth
get_access_token(code: str) -> Any
===========changed ref 0===========
# module: backend.src.db.functions.get
+ def get_user_by_access_token(access_token: str) -> UserModel:
+ user: Dict[str, Any] = await USERS.find_one({"access_token": access_token}) # type: ignore
+ return UserModel.parse_obj(user)
+
===========changed ref 1===========
# module: backend.src.db.functions.get
- def get_user(user_id: str) -> UserModel:
- user: Dict[str, Any] = await USERS.find_one({"user_id": user_id}) # type: ignore
- return UserModel.parse_obj(user)
-
===========changed ref 2===========
# module: backend.src.db.functions.get
- def get_user(user_id: str) -> UserModel:
- user: Dict[str, Any] = await USERS.find_one({"user_id": user_id}) # type: ignore
- return UserModel.parse_obj(user)
-
===========changed ref 3===========
# module: backend.src.db.functions.users
def create_user(user_id: str, access_token: str) -> str:
- user = UserModel.parse_obj({"user_id": user_id, "access_token": access_token})
+ await USERS.update_one( # type: ignore
- await USERS.insert_one(user.dict()) # type: ignore
+ {"user_id": user_id},
+ {"$set": {"user_id": user_id, "access_token": access_token}},
+ upsert=True,
+ )
return user_id
===========changed ref 4===========
# module: backend.src.endpoints.user
def main(
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
use_cache: bool = True,
) -> Dict[str, Any]:
+ access_token = (await get_user_by_user_id(user_id)).access_token
- access_token = get_access_token(user_id)
if access_token == "":
raise LookupError("Invalid UserId")
-
- if use_cache:
- output = get_user_endpoint(user_id)
- if output is not None:
- return output
data = await get_data(user_id, access_token, start_date, end_date, timezone_str)
top_languages = get_top_languages(data)
top_repos = get_top_repos(data)
contribs_per_day = get_contribs_per_day(data)
contribs_per_repo_per_day = get_contribs_per_repo_per_day(data)
output = {
"top_languages": top_languages,
"top_repos": top_repos,
"contribs_per_day": contribs_per_day,
"contribs_per_repo_per_day": contribs_per_repo_per_day,
}
- set_user_endpoint(user_id, output)
-
return output
|
backend.src.routers.users/get_user_endpoint
|
Modified
|
avgupta456~github-trends
|
7cb0bc4f3caff4a75f75e9bb81ef6f9ad04479f0
|
remove datastore
|
<0>:<add> return await get_user_by_user_id(user_id)
<del> return await get_user(user_id)
|
# module: backend.src.routers.users
@router.get("/user/get/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_endpoint(response: Response, user_id: str) -> Optional[DBUserModel]:
<0> return await get_user(user_id)
<1>
|
===========unchanged ref 0===========
at: backend.src.routers.users
router = APIRouter()
at: src.db.functions.get
get_user_by_user_id(user_id: str) -> UserModel
at: src.utils
async_fail_gracefully(func: Callable[..., Any])
===========changed ref 0===========
# module: backend.src.main
@app.post("/login/{code}", status_code=status.HTTP_200_OK)
+ @async_fail_gracefully
- @fail_gracefully
+ async def login(response: Response, code: str) -> Any:
- def login(response: Response, code: str) -> Any:
+ return await get_access_token(code)
- return get_access_token(code)
===========changed ref 1===========
# module: backend.src.db.functions.get
+ def get_user_by_access_token(access_token: str) -> UserModel:
+ user: Dict[str, Any] = await USERS.find_one({"access_token": access_token}) # type: ignore
+ return UserModel.parse_obj(user)
+
===========changed ref 2===========
# module: backend.src.db.functions.get
- def get_user(user_id: str) -> UserModel:
- user: Dict[str, Any] = await USERS.find_one({"user_id": user_id}) # type: ignore
- return UserModel.parse_obj(user)
-
===========changed ref 3===========
# module: backend.src.db.functions.get
- def get_user(user_id: str) -> UserModel:
- user: Dict[str, Any] = await USERS.find_one({"user_id": user_id}) # type: ignore
- return UserModel.parse_obj(user)
-
===========changed ref 4===========
# module: backend.src.main
- @app.get("/user_refresh", status_code=status.HTTP_200_OK)
- @async_fail_gracefully
- async def get_user_refresh(response: Response) -> Any:
- data = get_all_user_ids()
- for user_id in data:
- try:
- await _get_user(user_id, use_cache=False)
- except Exception as e:
- print(e)
- return "Successfully Updated"
-
===========changed ref 5===========
# module: backend.src.db.functions.users
def create_user(user_id: str, access_token: str) -> str:
- user = UserModel.parse_obj({"user_id": user_id, "access_token": access_token})
+ await USERS.update_one( # type: ignore
- await USERS.insert_one(user.dict()) # type: ignore
+ {"user_id": user_id},
+ {"$set": {"user_id": user_id, "access_token": access_token}},
+ upsert=True,
+ )
return user_id
===========changed ref 6===========
# module: backend.src.endpoints.user
def main(
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
use_cache: bool = True,
) -> Dict[str, Any]:
+ access_token = (await get_user_by_user_id(user_id)).access_token
- access_token = get_access_token(user_id)
if access_token == "":
raise LookupError("Invalid UserId")
-
- if use_cache:
- output = get_user_endpoint(user_id)
- if output is not None:
- return output
data = await get_data(user_id, access_token, start_date, end_date, timezone_str)
top_languages = get_top_languages(data)
top_repos = get_top_repos(data)
contribs_per_day = get_contribs_per_day(data)
contribs_per_repo_per_day = get_contribs_per_repo_per_day(data)
output = {
"top_languages": top_languages,
"top_repos": top_repos,
"contribs_per_day": contribs_per_day,
"contribs_per_repo_per_day": contribs_per_repo_per_day,
}
- set_user_endpoint(user_id, output)
-
return output
|
backend.src.endpoints.github_auth/get_access_token
|
Modified
|
avgupta456~github-trends
|
7cb0bc4f3caff4a75f75e9bb81ef6f9ad04479f0
|
remove datastore
|
<1>:<del>
<16>:<add> await create_user(user_id, access_token)
<del> set_access_token(user_id, access_token)
|
# module: backend.src.endpoints.github_auth
+ def get_access_token(code: str) -> Any:
- def get_access_token(code: str) -> Any:
<0> """Request a user's access token using code"""
<1>
<2> start = datetime.now()
<3>
<4> params = {
<5> "client_id": OAUTH_CLIENT_ID,
<6> "client_secret": OAUTH_CLIENT_SECRET,
<7> "code": code,
<8> "redirect_uri": OAUTH_REDIRECT_URI,
<9> }
<10>
<11> r = s.post("https://github.com/login/oauth/access_token", params=params) # type: ignore
<12>
<13> if r.status_code == 200:
<14> access_token = r.text.split("&")[0].split("=")[1]
<15> user_id = get_unknown_user(access_token)
<16> set_access_token(user_id, access_token)
<17> print("OAuth API", datetime.now() - start)
<18> return user_id
<19>
<20> raise OAuthError("OAuth Error: " + str(r.status_code))
<21>
|
===========unchanged ref 0===========
at: backend.src.endpoints.github_auth
s = requests.session()
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
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
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
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: src.db.functions.users
create_user(user_id: str, access_token: str) -> str
at: src.external.github_auth.auth
get_unknown_user(access_token: str) -> str
===========changed ref 0===========
# module: backend.src.main
@app.post("/login/{code}", status_code=status.HTTP_200_OK)
+ @async_fail_gracefully
- @fail_gracefully
+ async def login(response: Response, code: str) -> Any:
- def login(response: Response, code: str) -> Any:
+ return await get_access_token(code)
- return get_access_token(code)
===========changed ref 1===========
# module: backend.src.routers.users
@router.get("/user/get/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user_endpoint(response: Response, user_id: str) -> Optional[DBUserModel]:
+ return await get_user_by_user_id(user_id)
- return await get_user(user_id)
===========changed ref 2===========
# module: backend.src.db.functions.get
+ def get_user_by_access_token(access_token: str) -> UserModel:
+ user: Dict[str, Any] = await USERS.find_one({"access_token": access_token}) # type: ignore
+ return UserModel.parse_obj(user)
+
===========changed ref 3===========
# module: backend.src.db.functions.get
- def get_user(user_id: str) -> UserModel:
- user: Dict[str, Any] = await USERS.find_one({"user_id": user_id}) # type: ignore
- return UserModel.parse_obj(user)
-
===========changed ref 4===========
# module: backend.src.db.functions.get
- def get_user(user_id: str) -> UserModel:
- user: Dict[str, Any] = await USERS.find_one({"user_id": user_id}) # type: ignore
- return UserModel.parse_obj(user)
-
===========changed ref 5===========
# module: backend.src.main
- @app.get("/user_refresh", status_code=status.HTTP_200_OK)
- @async_fail_gracefully
- async def get_user_refresh(response: Response) -> Any:
- data = get_all_user_ids()
- for user_id in data:
- try:
- await _get_user(user_id, use_cache=False)
- except Exception as e:
- print(e)
- return "Successfully Updated"
-
===========changed ref 6===========
# module: backend.src.db.functions.users
def create_user(user_id: str, access_token: str) -> str:
- user = UserModel.parse_obj({"user_id": user_id, "access_token": access_token})
+ await USERS.update_one( # type: ignore
- await USERS.insert_one(user.dict()) # type: ignore
+ {"user_id": user_id},
+ {"$set": {"user_id": user_id, "access_token": access_token}},
+ upsert=True,
+ )
return user_id
===========changed ref 7===========
# module: backend.src.endpoints.user
def main(
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
use_cache: bool = True,
) -> Dict[str, Any]:
+ access_token = (await get_user_by_user_id(user_id)).access_token
- access_token = get_access_token(user_id)
if access_token == "":
raise LookupError("Invalid UserId")
-
- if use_cache:
- output = get_user_endpoint(user_id)
- if output is not None:
- return output
data = await get_data(user_id, access_token, start_date, end_date, timezone_str)
top_languages = get_top_languages(data)
top_repos = get_top_repos(data)
contribs_per_day = get_contribs_per_day(data)
contribs_per_repo_per_day = get_contribs_per_repo_per_day(data)
output = {
"top_languages": top_languages,
"top_repos": top_repos,
"contribs_per_day": contribs_per_day,
"contribs_per_repo_per_day": contribs_per_repo_per_day,
}
- set_user_endpoint(user_id, output)
-
return output
|
backend.src.routers.users/get_user
|
Modified
|
avgupta456~github-trends
|
b3efb75579b95e8e93cc28fbd6c7e6fa89e57f4e
|
store raw_data in mongodb
|
<3>:<add>
<add> db_user = await get_user_by_user_id(user_id)
<add> if db_user.raw_data is not None and (
<add> datetime.now() - db_user.last_updated
<add> ) < timedelta(hours=6):
<add> return db_user.raw_data
<18>:<add> await update_user(user_id, output)
<add>
|
# module: backend.src.routers.users
@router.get("/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Dict[str, Any]:
<0> access_token = (await get_user_by_user_id(user_id)).access_token
<1> if access_token == "":
<2> raise LookupError("Invalid UserId")
<3>
<4> data = await get_data(user_id, access_token, start_date, end_date, timezone_str)
<5>
<6> top_languages = get_top_languages(data)
<7> top_repos = get_top_repos(data)
<8> contribs_per_day = get_contribs_per_day(data)
<9> contribs_per_repo_per_day = get_contribs_per_repo_per_day(data)
<10>
<11> output = {
<12> "top_languages": top_languages,
<13> "top_repos": top_repos,
<14> "contribs_per_day": contribs_per_day,
<15> "contribs_per_repo_per_day": contribs_per_repo_per_day,
<16> }
<17>
<18> return output
<19>
|
===========unchanged ref 0===========
at: backend.src.routers.users
router = APIRouter()
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: src.analytics.user.commits
get_top_languages(data: UserPackage) -> List[dict_type]
get_top_repos(data: UserPackage) -> List[Any]
at: src.analytics.user.contribs_per_day
get_contribs_per_day(data: UserPackage) -> Dict[str, int]
get_contribs_per_repo_per_day(data: UserPackage) -> Dict[str, Dict[str, int]]
at: src.db.functions.get
get_user_by_user_id(user_id: str) -> UserModel
at: src.db.models.users.UserModel
user_id: str
access_token: str
last_updated: datetime
raw_data: Optional[Dict[str, Any]]
at: src.packaging.user
main(user_id: str, access_token: str, start_date: date=date.today() - timedelta(365), end_date: date=date.today(), timezone_str: str="US/Eastern") -> UserPackage
at: src.utils
async_fail_gracefully(func: Callable[..., Any])
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.src.db.functions.users/create_user
|
Modified
|
avgupta456~github-trends
|
b3efb75579b95e8e93cc28fbd6c7e6fa89e57f4e
|
store raw_data in mongodb
|
<0>:<add> user = UserModel.parse_obj(
<add> {
<add> "user_id": user_id,
<add> "access_token": access_token,
<add> "last_updated": datetime.now(),
<add> "raw_data": None,
<add> }
<add> )
<2>:<add> {"$set": user.dict()},
<del> {"$set": {"user_id": user_id, "access_token": access_token}},
|
# module: backend.src.db.functions.users
def create_user(user_id: str, access_token: str) -> str:
<0> await USERS.update_one( # type: ignore
<1> {"user_id": user_id},
<2> {"$set": {"user_id": user_id, "access_token": access_token}},
<3> upsert=True,
<4> )
<5> return user_id
<6>
|
===========unchanged ref 0===========
at: src.db.mongodb
USERS = DB.users # type: ignore
===========changed ref 0===========
# module: backend.src.routers.users
@router.get("/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Dict[str, Any]:
access_token = (await get_user_by_user_id(user_id)).access_token
if access_token == "":
raise LookupError("Invalid UserId")
+
+ db_user = await get_user_by_user_id(user_id)
+ if db_user.raw_data is not None and (
+ datetime.now() - db_user.last_updated
+ ) < timedelta(hours=6):
+ return db_user.raw_data
data = await get_data(user_id, access_token, start_date, end_date, timezone_str)
top_languages = get_top_languages(data)
top_repos = get_top_repos(data)
contribs_per_day = get_contribs_per_day(data)
contribs_per_repo_per_day = get_contribs_per_repo_per_day(data)
output = {
"top_languages": top_languages,
"top_repos": top_repos,
"contribs_per_day": contribs_per_day,
"contribs_per_repo_per_day": contribs_per_repo_per_day,
}
+ await update_user(user_id, output)
+
return output
|
backend.src.db.functions.get/get_user_by_user_id
|
Modified
|
avgupta456~github-trends
|
795e128b34b38383646122edcaafacc9b8d7b8cd
|
fix login
|
<0>:<add> user: Optional[Dict[str, Any]] = await USERS.find_one({"user_id": user_id}) # type: ignore
<del> user: Dict[str, Any] = await USERS.find_one({"user_id": user_id}) # type: ignore
<1>:<add> if user is None:
<add> return None
|
# module: backend.src.db.functions.get
+ def get_user_by_user_id(user_id: str) -> Optional[UserModel]:
- def get_user_by_user_id(user_id: str) -> UserModel:
<0> user: Dict[str, Any] = await USERS.find_one({"user_id": user_id}) # type: ignore
<1> return UserModel.parse_obj(user)
<2>
|
===========unchanged ref 0===========
at: src.db.mongodb
USERS = DB.users # type: ignore
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.src.db.functions.get/get_user_by_access_token
|
Modified
|
avgupta456~github-trends
|
795e128b34b38383646122edcaafacc9b8d7b8cd
|
fix login
|
<0>:<add> user: Optional[Dict[str, Any]] = await USERS.find_one( # type: ignore
<del> user: Dict[str, Any] = await USERS.find_one({"access_token": access_token}) # type: ignore
<1>:<add> {"access_token": access_token}
<add> )
<add> if user is None:
<add> return None
|
# module: backend.src.db.functions.get
+ def get_user_by_access_token(access_token: str) -> Optional[UserModel]:
- def get_user_by_access_token(access_token: str) -> UserModel:
<0> user: Dict[str, Any] = await USERS.find_one({"access_token": access_token}) # type: ignore
<1> return UserModel.parse_obj(user)
<2>
|
===========changed ref 0===========
# module: backend.src.db.functions.get
+ def get_user_by_user_id(user_id: str) -> Optional[UserModel]:
- def get_user_by_user_id(user_id: str) -> UserModel:
+ user: Optional[Dict[str, Any]] = await USERS.find_one({"user_id": user_id}) # type: ignore
- user: Dict[str, Any] = await USERS.find_one({"user_id": user_id}) # type: ignore
+ if user is None:
+ return None
return UserModel.parse_obj(user)
|
backend.src.routers.auth/login
|
Modified
|
avgupta456~github-trends
|
795e128b34b38383646122edcaafacc9b8d7b8cd
|
fix login
|
<14>:<add> await login_user(user_id, access_token)
<del> await create_user(user_id, access_token)
|
# module: backend.src.routers.auth
@router.post("/login/{code}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def login(response: Response, code: str) -> Any:
<0> start = datetime.now()
<1>
<2> params = {
<3> "client_id": OAUTH_CLIENT_ID,
<4> "client_secret": OAUTH_CLIENT_SECRET,
<5> "code": code,
<6> "redirect_uri": OAUTH_REDIRECT_URI,
<7> }
<8>
<9> r = s.post("https://github.com/login/oauth/access_token", params=params) # type: ignore
<10>
<11> if r.status_code == 200:
<12> access_token = r.text.split("&")[0].split("=")[1]
<13> user_id = get_unknown_user(access_token)
<14> await create_user(user_id, access_token)
<15> print("OAuth API", datetime.now() - start)
<16> return user_id
<17>
<18> raise OAuthError("OAuth Error: " + str(r.status_code))
<19>
|
===========unchanged ref 0===========
at: backend.src.routers.auth
router = APIRouter()
s = requests.session()
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
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
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
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: src.db.functions.users
login_user(user_id: str, access_token: str) -> str
at: src.external.github_auth.auth
get_unknown_user(access_token: str) -> str
at: src.utils
async_fail_gracefully(func: Callable[..., Any])
===========changed ref 0===========
# module: backend.src.db.functions.get
+ def get_user_by_user_id(user_id: str) -> Optional[UserModel]:
- def get_user_by_user_id(user_id: str) -> UserModel:
+ user: Optional[Dict[str, Any]] = await USERS.find_one({"user_id": user_id}) # type: ignore
- user: Dict[str, Any] = await USERS.find_one({"user_id": user_id}) # type: ignore
+ if user is None:
+ return None
return UserModel.parse_obj(user)
===========changed ref 1===========
# module: backend.src.db.functions.get
+ def get_user_by_access_token(access_token: str) -> Optional[UserModel]:
- def get_user_by_access_token(access_token: str) -> UserModel:
+ user: Optional[Dict[str, Any]] = await USERS.find_one( # type: ignore
- user: Dict[str, Any] = await USERS.find_one({"access_token": access_token}) # type: ignore
+ {"access_token": access_token}
+ )
+ if user is None:
+ return None
return UserModel.parse_obj(user)
|
backend.src.routers.users/create_user_endpoint
|
Modified
|
avgupta456~github-trends
|
795e128b34b38383646122edcaafacc9b8d7b8cd
|
fix login
|
<0>:<add> return await login_user(user_id, access_token)
<del> return await create_user(user_id, access_token)
|
# module: backend.src.routers.users
@router.get("/db/create/{user_id}/{access_token}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def create_user_endpoint(
response: Response, user_id: str, access_token: str
) -> str:
<0> return await create_user(user_id, access_token)
<1>
|
===========unchanged ref 0===========
at: backend.src.routers.users
router = APIRouter()
at: src.db.functions.users
login_user(user_id: str, access_token: str) -> str
at: src.utils
async_fail_gracefully(func: Callable[..., Any])
===========changed ref 0===========
# module: backend.src.db.functions.get
+ def get_user_by_user_id(user_id: str) -> Optional[UserModel]:
- def get_user_by_user_id(user_id: str) -> UserModel:
+ user: Optional[Dict[str, Any]] = await USERS.find_one({"user_id": user_id}) # type: ignore
- user: Dict[str, Any] = await USERS.find_one({"user_id": user_id}) # type: ignore
+ if user is None:
+ return None
return UserModel.parse_obj(user)
===========changed ref 1===========
# module: backend.src.db.functions.get
+ def get_user_by_access_token(access_token: str) -> Optional[UserModel]:
- def get_user_by_access_token(access_token: str) -> UserModel:
+ user: Optional[Dict[str, Any]] = await USERS.find_one( # type: ignore
- user: Dict[str, Any] = await USERS.find_one({"access_token": access_token}) # type: ignore
+ {"access_token": access_token}
+ )
+ if user is None:
+ return None
return UserModel.parse_obj(user)
===========changed ref 2===========
# module: backend.src.routers.auth
@router.post("/login/{code}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def login(response: Response, code: str) -> Any:
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) # type: ignore
if r.status_code == 200:
access_token = r.text.split("&")[0].split("=")[1]
user_id = get_unknown_user(access_token)
+ await login_user(user_id, access_token)
- await create_user(user_id, access_token)
print("OAuth API", datetime.now() - start)
return user_id
raise OAuthError("OAuth Error: " + str(r.status_code))
|
backend.src.routers.users/get_user
|
Modified
|
avgupta456~github-trends
|
795e128b34b38383646122edcaafacc9b8d7b8cd
|
fix login
|
<0>:<add> db_user = await get_user_by_user_id(user_id)
<add> if db_user is None or db_user.access_token == "":
<del> access_token = (await get_user_by_user_id(user_id)).access_token
<1>:<del> if access_token == "":
<4>:<del> db_user = await get_user_by_user_id(user_id)
<10>:<add> data = await get_data(
<add> user_id, db_user.access_token, start_date, end_date, timezone_str
<del> data = await get_data(user_id, access_token, start_date, end_date, timezone_str)
<11>:<add> )
|
# module: backend.src.routers.users
@router.get("/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Dict[str, Any]:
<0> access_token = (await get_user_by_user_id(user_id)).access_token
<1> if access_token == "":
<2> raise LookupError("Invalid UserId")
<3>
<4> db_user = await get_user_by_user_id(user_id)
<5> if db_user.raw_data is not None and (
<6> datetime.now() - db_user.last_updated
<7> ) < timedelta(hours=6):
<8> return db_user.raw_data
<9>
<10> data = await get_data(user_id, access_token, start_date, end_date, timezone_str)
<11>
<12> top_languages = get_top_languages(data)
<13> top_repos = get_top_repos(data)
<14> contribs_per_day = get_contribs_per_day(data)
<15> contribs_per_repo_per_day = get_contribs_per_repo_per_day(data)
<16>
<17> output = {
<18> "top_languages": top_languages,
<19> "top_repos": top_repos,
<20> "contribs_per_day": contribs_per_day,
<21> "contribs_per_repo_per_day": contribs_per_repo_per_day,
<22> }
<23>
<24> await update_user(user_id, output)
<25>
<26> return output
<27>
|
===========unchanged ref 0===========
at: backend.src.routers.users
router = APIRouter()
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: src.analytics.user.commits
get_top_languages(data: UserPackage) -> List[dict_type]
get_top_repos(data: UserPackage) -> List[Any]
at: src.analytics.user.contribs_per_day
get_contribs_per_day(data: UserPackage) -> Dict[str, int]
get_contribs_per_repo_per_day(data: UserPackage) -> Dict[str, Dict[str, int]]
at: src.db.functions.get
get_user_by_user_id(user_id: str) -> Optional[UserModel]
at: src.db.functions.users
update_user(user_id: str, raw_data: Optional[Dict[str, Any]]=None) -> None
at: src.db.models.users.UserModel
user_id: str
access_token: str
last_updated: datetime
raw_data: Optional[Dict[str, Any]]
at: src.packaging.user
main(user_id: str, access_token: str, start_date: date=date.today() - timedelta(365), end_date: date=date.today(), timezone_str: str="US/Eastern") -> UserPackage
===========unchanged ref 1===========
at: src.utils
async_fail_gracefully(func: Callable[..., Any])
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.routers.users
@router.get("/db/create/{user_id}/{access_token}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def create_user_endpoint(
response: Response, user_id: str, access_token: str
) -> str:
+ return await login_user(user_id, access_token)
- return await create_user(user_id, access_token)
===========changed ref 1===========
# module: backend.src.db.functions.get
+ def get_user_by_user_id(user_id: str) -> Optional[UserModel]:
- def get_user_by_user_id(user_id: str) -> UserModel:
+ user: Optional[Dict[str, Any]] = await USERS.find_one({"user_id": user_id}) # type: ignore
- user: Dict[str, Any] = await USERS.find_one({"user_id": user_id}) # type: ignore
+ if user is None:
+ return None
return UserModel.parse_obj(user)
===========changed ref 2===========
# module: backend.src.db.functions.get
+ def get_user_by_access_token(access_token: str) -> Optional[UserModel]:
- def get_user_by_access_token(access_token: str) -> UserModel:
+ user: Optional[Dict[str, Any]] = await USERS.find_one( # type: ignore
- user: Dict[str, Any] = await USERS.find_one({"access_token": access_token}) # type: ignore
+ {"access_token": access_token}
+ )
+ if user is None:
+ return None
return UserModel.parse_obj(user)
===========changed ref 3===========
# module: backend.src.routers.auth
@router.post("/login/{code}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def login(response: Response, code: str) -> Any:
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) # type: ignore
if r.status_code == 200:
access_token = r.text.split("&")[0].split("=")[1]
user_id = get_unknown_user(access_token)
+ await login_user(user_id, access_token)
- await create_user(user_id, access_token)
print("OAuth API", datetime.now() - start)
return user_id
raise OAuthError("OAuth Error: " + str(r.status_code))
|
backend.src.routers.pubsub/test
|
Modified
|
avgupta456~github-trends
|
8be48fa7b57d449f37637aa58c1c4b478e7312e4
|
start local pubsub
|
<0>:<del> if PUBSUB_PUB:
<1>:<del> raise HTTPException(400, "Incorrect server, only Subscriber can access")
|
# module: backend.src.routers.pubsub
+ @router.get("/pub/test", status_code=status.HTTP_200_OK)
- @router.get("/test", status_code=status.HTTP_200_OK)
@fail_gracefully
def test(response: Response) -> Any:
<0> if PUBSUB_PUB:
<1> raise HTTPException(400, "Incorrect server, only Subscriber can access")
<2> return {"test": count}
<3>
|
===========unchanged ref 0===========
at: backend.src.routers.pubsub
router = APIRouter()
global count
count: int = 0
at: src.utils
fail_gracefully(func: Callable[..., Any])
|
backend.src.external.pubsub.templates/publish_to_topic
|
Modified
|
avgupta456~github-trends
|
8be48fa7b57d449f37637aa58c1c4b478e7312e4
|
start local pubsub
|
<0>:<add> if PROD and not PUBSUB_PUB:
<add> raise HTTPException(400, "Publishing is disabled")
<2>:<del> publisher.publish(topic_path, data=data) # type: ignore
|
# module: backend.src.external.pubsub.templates
def publish_to_topic(topic: str, message: Dict[str, Any]) -> None:
<0> topic_path = publisher.topic_path(PROJECT_ID, topic) # type: ignore
<1> data = json.dumps(message).encode("utf-8")
<2> publisher.publish(topic_path, data=data) # type: ignore
<3>
|
===========changed ref 0===========
# module: backend.src.routers.pubsub
+ @router.get("/pub/test", status_code=status.HTTP_200_OK)
- @router.get("/test", status_code=status.HTTP_200_OK)
@fail_gracefully
def test(response: Response) -> Any:
- if PUBSUB_PUB:
- raise HTTPException(400, "Incorrect server, only Subscriber can access")
return {"test": count}
|
backend.src.external.pubsub.templates/parse_request
|
Modified
|
avgupta456~github-trends
|
8be48fa7b57d449f37637aa58c1c4b478e7312e4
|
start local pubsub
|
<0>:<add> if PROD and PUBSUB_PUB:
<add> raise HTTPException(400, "Subscribing is disabled")
<4>:<add> if PROD:
<add> data = json.loads(base64.b64decode(data["message"]["data"]))
<del> data = json.loads(base64.b64decode(data["message"]["data"]))
|
# module: backend.src.external.pubsub.templates
def parse_request(token: str, request: Request) -> Dict[str, Any]:
<0> if token != PUBSUB_TOKEN:
<1> raise HTTPException(400, "Invalid token")
<2>
<3> data = await request.json()
<4> data = json.loads(base64.b64decode(data["message"]["data"]))
<5>
<6> return data
<7>
|
===========changed ref 0===========
# module: backend.src.external.pubsub.templates
def publish_to_topic(topic: str, message: Dict[str, Any]) -> None:
+ if PROD and not PUBSUB_PUB:
+ raise HTTPException(400, "Publishing is disabled")
topic_path = publisher.topic_path(PROJECT_ID, topic) # type: ignore
data = json.dumps(message).encode("utf-8")
- publisher.publish(topic_path, data=data) # type: ignore
===========changed ref 1===========
# module: backend.src.routers.pubsub
+ @router.get("/pub/test", status_code=status.HTTP_200_OK)
- @router.get("/test", status_code=status.HTTP_200_OK)
@fail_gracefully
def test(response: Response) -> Any:
- if PUBSUB_PUB:
- raise HTTPException(400, "Incorrect server, only Subscriber can access")
return {"test": count}
|
backend.src.routers.pubsub/test_post
|
Modified
|
avgupta456~github-trends
|
3f6d2b4e9ad356542b186e087cb1fd349a79df69
|
cleanup
|
<0>:<del> if not PUBSUB_PUB:
<1>:<del> raise HTTPException(400, "Incorrect server, only Publisher can access")
|
# module: backend.src.routers.pubsub
@router.get("/pub/test/{update}", status_code=status.HTTP_200_OK)
@fail_gracefully
def test_post(response: Response, update: str) -> Any:
<0> if not PUBSUB_PUB:
<1> raise HTTPException(400, "Incorrect server, only Publisher can access")
<2> publish_to_topic("test", {"num": int(update)})
<3> return update
<4>
|
===========unchanged ref 0===========
at: backend.src.routers.pubsub
router = APIRouter()
at: src.external.pubsub.templates
publish_to_topic(topic: str, message: Dict[str, Any]) -> None
at: src.utils
async_fail_gracefully(func: Callable[..., Any])
===========changed ref 0===========
# module: backend.src.constants
# GLOBAL
PROD = os.getenv("PROD", "False") == "True"
PROJECT_ID = "github-298920"
# API
TIMEOUT = 3 # max seconds to wait for api response
NODE_CHUNK_SIZE = 50 # number of nodes (commits) to query (max 100)
NODE_THREADS = 30 # number of node queries simultaneously (avoid blacklisting)
CUTOFF = 1000 # if > cutoff lines, assume imported, don't count
# CUSTOMIZATION
BLACKLIST = ["Jupyter Notebook", "HTML"] # languages to ignore
# OAUTH
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
# PUBSUB
PUBSUB_PUB = os.getenv("PUBSUB_PUB", "False") == "True"
PUBSUB_TOKEN = os.getenv("PUBSUB_TOKEN", "")
+ LOCAL_SUBSCRIBER = "http://localhost:8001/pubsub/sub/"
- LOCAL_SUBSCRIBER = "localhost:8001/pubsub/"
# MONGODB
MONGODB_PASSWORD = os.getenv("MONGODB_PASSWORD", "")
# TESTING
TEST_USER_ID = "AshishGupta938" # for testing, previously "avgupta456"
TEST_TOKEN = os.getenv("AUTH_TOKEN", "") # for authentication
|
backend.src.routers.pubsub/test_pubsub
|
Modified
|
avgupta456~github-trends
|
3f6d2b4e9ad356542b186e087cb1fd349a79df69
|
cleanup
|
<0>:<del> if PUBSUB_PUB:
<1>:<del> raise HTTPException(400, "Incorrect server, only Subscriber can access")
|
# module: backend.src.routers.pubsub
@router.post("/sub/test/{token}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def test_pubsub(response: Response, token: str, request: Request) -> Any:
<0> if PUBSUB_PUB:
<1> raise HTTPException(400, "Incorrect server, only Subscriber can access")
<2> data = await parse_request(token, request)
<3>
<4> global count
<5> count += data["num"]
<6>
|
===========unchanged ref 0===========
at: backend.src.routers.pubsub.test_pubsub
data = await parse_request(token, request)
===========changed ref 0===========
# module: backend.src.routers.pubsub
@router.get("/pub/test/{update}", status_code=status.HTTP_200_OK)
@fail_gracefully
def test_post(response: Response, update: str) -> Any:
- if not PUBSUB_PUB:
- raise HTTPException(400, "Incorrect server, only Publisher can access")
publish_to_topic("test", {"num": int(update)})
return update
===========changed ref 1===========
# module: backend.src.constants
# GLOBAL
PROD = os.getenv("PROD", "False") == "True"
PROJECT_ID = "github-298920"
# API
TIMEOUT = 3 # max seconds to wait for api response
NODE_CHUNK_SIZE = 50 # number of nodes (commits) to query (max 100)
NODE_THREADS = 30 # number of node queries simultaneously (avoid blacklisting)
CUTOFF = 1000 # if > cutoff lines, assume imported, don't count
# CUSTOMIZATION
BLACKLIST = ["Jupyter Notebook", "HTML"] # languages to ignore
# OAUTH
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
# PUBSUB
PUBSUB_PUB = os.getenv("PUBSUB_PUB", "False") == "True"
PUBSUB_TOKEN = os.getenv("PUBSUB_TOKEN", "")
+ LOCAL_SUBSCRIBER = "http://localhost:8001/pubsub/sub/"
- LOCAL_SUBSCRIBER = "localhost:8001/pubsub/"
# MONGODB
MONGODB_PASSWORD = os.getenv("MONGODB_PASSWORD", "")
# TESTING
TEST_USER_ID = "AshishGupta938" # for testing, previously "avgupta456"
TEST_TOKEN = os.getenv("AUTH_TOKEN", "") # for authentication
|
backend.src.external.pubsub.templates/publish_to_topic
|
Modified
|
avgupta456~github-trends
|
3f6d2b4e9ad356542b186e087cb1fd349a79df69
|
cleanup
|
<2>:<add>
<del> topic_path = publisher.topic_path(PROJECT_ID, topic) # type: ignore
<4>:<del>
<6>:<add> topic_path = publisher.topic_path(PROJECT_ID, topic) # type: ignore
|
# module: backend.src.external.pubsub.templates
def publish_to_topic(topic: str, message: Dict[str, Any]) -> None:
<0> if PROD and not PUBSUB_PUB:
<1> raise HTTPException(400, "Publishing is disabled")
<2> topic_path = publisher.topic_path(PROJECT_ID, topic) # type: ignore
<3> data = json.dumps(message).encode("utf-8")
<4>
<5> if PROD:
<6> publisher.publish(topic_path, data=data) # type: ignore
<7> else:
<8> requests.post(LOCAL_SUBSCRIBER + topic + "/" + PUBSUB_TOKEN, data=data)
<9>
|
===========changed ref 0===========
# module: backend.src.routers.pubsub
@router.get("/pub/test/{update}", status_code=status.HTTP_200_OK)
@fail_gracefully
def test_post(response: Response, update: str) -> Any:
- if not PUBSUB_PUB:
- raise HTTPException(400, "Incorrect server, only Publisher can access")
publish_to_topic("test", {"num": int(update)})
return update
===========changed ref 1===========
# module: backend.src.routers.pubsub
@router.post("/sub/test/{token}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def test_pubsub(response: Response, token: str, request: Request) -> Any:
- if PUBSUB_PUB:
- raise HTTPException(400, "Incorrect server, only Subscriber can access")
data = await parse_request(token, request)
global count
count += data["num"]
===========changed ref 2===========
# module: backend.src.constants
# GLOBAL
PROD = os.getenv("PROD", "False") == "True"
PROJECT_ID = "github-298920"
# API
TIMEOUT = 3 # max seconds to wait for api response
NODE_CHUNK_SIZE = 50 # number of nodes (commits) to query (max 100)
NODE_THREADS = 30 # number of node queries simultaneously (avoid blacklisting)
CUTOFF = 1000 # if > cutoff lines, assume imported, don't count
# CUSTOMIZATION
BLACKLIST = ["Jupyter Notebook", "HTML"] # languages to ignore
# OAUTH
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
# PUBSUB
PUBSUB_PUB = os.getenv("PUBSUB_PUB", "False") == "True"
PUBSUB_TOKEN = os.getenv("PUBSUB_TOKEN", "")
+ LOCAL_SUBSCRIBER = "http://localhost:8001/pubsub/sub/"
- LOCAL_SUBSCRIBER = "localhost:8001/pubsub/"
# MONGODB
MONGODB_PASSWORD = os.getenv("MONGODB_PASSWORD", "")
# TESTING
TEST_USER_ID = "AshishGupta938" # for testing, previously "avgupta456"
TEST_TOKEN = os.getenv("AUTH_TOKEN", "") # for authentication
|
backend.src.db.functions.users/update_user
|
Modified
|
avgupta456~github-trends
|
91f423e1d8898bd8c79089426b933b0f5c9e305e
|
pubsub user
|
<3>:<add> {"$set": {"last_updated": datetime.now(), "raw_data": raw_data}},
<del> {"$set": {"raw_data": raw_data}},
|
# module: backend.src.db.functions.users
def update_user(user_id: str, raw_data: Optional[Dict[str, Any]] = None) -> None:
<0> if raw_data is not None:
<1> await USERS.update_one( # type: ignore
<2> {"user_id": user_id},
<3> {"$set": {"raw_data": raw_data}},
<4> )
<5>
|
===========unchanged ref 0===========
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: src.db.mongodb
USERS = DB.users # type: ignore
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.routers.pubsub
- @router.get("/test", status_code=status.HTTP_200_OK)
- @fail_gracefully
- def test(response: Response) -> Any:
- return {"test": count}
-
===========changed ref 1===========
# module: backend.src.routers.pubsub
router = APIRouter()
+ """
+ USER PUBSUB
+ """
- count: int = 0
===========changed ref 2===========
# module: backend.src.routers.pubsub
- @router.get("/pub/test/{update}", status_code=status.HTTP_200_OK)
- @fail_gracefully
- def test_post(response: Response, update: str) -> Any:
- publish_to_topic("test", {"num": int(update)})
- return update
-
===========changed ref 3===========
# module: backend.src.routers.pubsub
- @router.post("/sub/test/{token}", status_code=status.HTTP_200_OK)
- @async_fail_gracefully
- async def test_pubsub(response: Response, token: str, request: Request) -> Any:
- data = await parse_request(token, request)
-
- global count
- count += data["num"]
-
===========changed ref 4===========
# module: backend.src.routers.pubsub
+ @router.get("/pub/user/{user_id}/{access_token}", status_code=status.HTTP_200_OK)
+ @fail_gracefully
+ def pub_user(response: Response, user_id: str, access_token: str) -> str:
+ publish_to_topic(
+ "user",
+ {
+ "user_id": user_id,
+ "access_token": access_token,
+ "start_date": str(date.today() - timedelta(365)),
+ "end_date": str(date.today()),
+ "timezone_str": "US/Eastern",
+ },
+ )
+
+ return user_id
+
===========changed ref 5===========
# module: backend.src.routers.pubsub
+ @router.post("/sub/user/{token}", status_code=status.HTTP_200_OK)
+ @async_fail_gracefully
+ async def sub_user(response: Response, token: str, request: Request) -> Any:
+ data: Dict[str, Any] = await parse_request(token, request)
+
+ print(data)
+
+ output = await analytics_get_user(
+ data["user_id"],
+ data["access_token"],
+ datetime.strptime(data["start_date"], "%Y-%m-%d").date(),
+ datetime.strptime(data["end_date"], "%Y-%m-%d").date(),
+ data["timezone_str"],
+ )
+
+ await update_user(data["user_id"], output)
+
+ return output
+
|
backend.src.routers.users/get_user
|
Modified
|
avgupta456~github-trends
|
91f423e1d8898bd8c79089426b933b0f5c9e305e
|
pubsub user
|
<0>:<add> if not PUBSUB_PUB:
<add> raise HTTPException(400, "")
<add>
<9>:<add> publish_to_topic(
<add> "user",
<add> {
<add> "user_id": user_id,
<add> "access_token": db_user.access_token,
<add> "start_date": str(start_date),
<add> "end_date": str(end_date),
<add> "timezone_str": timezone_str,
<add> },
<del> data = await get_data(
<10>:<del> user_id, db_user.access_token, start_date, end_date, timezone_str
<13>:<del> top_languages = get_top_languages(data)
<14>:<del> top_repos = get_top_repos(data)
<15>:<del> contribs_per_day = get_contribs_per_day(data)
<16>:<del> contribs_per_repo_per_day = get_contribs_per_repo_per_day(data)
<17>:<add> return {}
<18>:<del> output = {
<19>:<del> "top_languages": top_languages,
<20>:<del> "top_repos": top_repos,
<21>:<del> "contribs_per_day": contribs_per_day,
<22>:<del> "contribs_per_repo_per_day": contribs_per_repo_per_day,
<23>:<del> }
<24>:<del>
<25>:<del> await update_user(user_id, output)
<26>:<del>
<27>:<del> return output
<28>:<del>
|
# module: backend.src.routers.users
@router.get("/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Dict[str, Any]:
<0> db_user = await get_user_by_user_id(user_id)
<1> if db_user is None or db_user.access_token == "":
<2> raise LookupError("Invalid UserId")
<3>
<4> if db_user.raw_data is not None and (
<5> datetime.now() - db_user.last_updated
<6> ) < timedelta(hours=6):
<7> return db_user.raw_data
<8>
<9> data = await get_data(
<10> user_id, db_user.access_token, start_date, end_date, timezone_str
<11> )
<12>
<13> top_languages = get_top_languages(data)
<14> top_repos = get_top_repos(data)
<15> contribs_per_day = get_contribs_per_day(data)
<16> contribs_per_repo_per_day = get_contribs_per_repo_per_day(data)
<17>
<18> output = {
<19> "top_languages": top_languages,
<20> "top_repos": top_repos,
<21> "contribs_per_day": contribs_per_day,
<22> "contribs_per_repo_per_day": contribs_per_repo_per_day,
<23> }
<24>
<25> await update_user(user_id, output)
<26>
<27> return output
<28>
|
===========unchanged ref 0===========
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: src.constants
PUBSUB_PUB = os.getenv("PUBSUB_PUB", "False") == "True"
at: src.db.functions.get
get_user_by_user_id(user_id: str) -> Optional[UserModel]
at: src.db.models.users.UserModel
user_id: str
access_token: str
last_updated: datetime
raw_data: Optional[Dict[str, Any]]
at: src.external.pubsub.templates
publish_to_topic(topic: str, message: Dict[str, Any]) -> None
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.routers.pubsub
- @router.get("/test", status_code=status.HTTP_200_OK)
- @fail_gracefully
- def test(response: Response) -> Any:
- return {"test": count}
-
===========changed ref 1===========
# module: backend.src.routers.pubsub
router = APIRouter()
+ """
+ USER PUBSUB
+ """
- count: int = 0
===========changed ref 2===========
# module: backend.src.routers.pubsub
- @router.get("/pub/test/{update}", status_code=status.HTTP_200_OK)
- @fail_gracefully
- def test_post(response: Response, update: str) -> Any:
- publish_to_topic("test", {"num": int(update)})
- return update
-
===========changed ref 3===========
# module: backend.src.routers.pubsub
- @router.post("/sub/test/{token}", status_code=status.HTTP_200_OK)
- @async_fail_gracefully
- async def test_pubsub(response: Response, token: str, request: Request) -> Any:
- data = await parse_request(token, request)
-
- global count
- count += data["num"]
-
===========changed ref 4===========
# module: backend.src.db.functions.users
def update_user(user_id: str, raw_data: Optional[Dict[str, Any]] = None) -> None:
if raw_data is not None:
await USERS.update_one( # type: ignore
{"user_id": user_id},
+ {"$set": {"last_updated": datetime.now(), "raw_data": raw_data}},
- {"$set": {"raw_data": raw_data}},
)
===========changed ref 5===========
# module: backend.src.routers.pubsub
+ @router.get("/pub/user/{user_id}/{access_token}", status_code=status.HTTP_200_OK)
+ @fail_gracefully
+ def pub_user(response: Response, user_id: str, access_token: str) -> str:
+ publish_to_topic(
+ "user",
+ {
+ "user_id": user_id,
+ "access_token": access_token,
+ "start_date": str(date.today() - timedelta(365)),
+ "end_date": str(date.today()),
+ "timezone_str": "US/Eastern",
+ },
+ )
+
+ return user_id
+
===========changed ref 6===========
# module: backend.src.routers.pubsub
+ @router.post("/sub/user/{token}", status_code=status.HTTP_200_OK)
+ @async_fail_gracefully
+ async def sub_user(response: Response, token: str, request: Request) -> Any:
+ data: Dict[str, Any] = await parse_request(token, request)
+
+ print(data)
+
+ output = await analytics_get_user(
+ data["user_id"],
+ data["access_token"],
+ datetime.strptime(data["start_date"], "%Y-%m-%d").date(),
+ datetime.strptime(data["end_date"], "%Y-%m-%d").date(),
+ data["timezone_str"],
+ )
+
+ await update_user(data["user_id"], output)
+
+ return output
+
|
backend.src.routers.auth/login
|
Modified
|
avgupta456~github-trends
|
91f423e1d8898bd8c79089426b933b0f5c9e305e
|
pubsub user
|
<0>:<add> if not PUBSUB_PUB:
<add> raise HTTPException(400, "Incorrect Server, must use Publisher")
<add>
|
# module: backend.src.routers.auth
@router.post("/login/{code}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def login(response: Response, code: str) -> Any:
<0> start = datetime.now()
<1>
<2> params = {
<3> "client_id": OAUTH_CLIENT_ID,
<4> "client_secret": OAUTH_CLIENT_SECRET,
<5> "code": code,
<6> "redirect_uri": OAUTH_REDIRECT_URI,
<7> }
<8>
<9> r = s.post("https://github.com/login/oauth/access_token", params=params) # type: ignore
<10>
<11> if r.status_code == 200:
<12> access_token = r.text.split("&")[0].split("=")[1]
<13> user_id = get_unknown_user(access_token)
<14> await login_user(user_id, access_token)
<15> print("OAuth API", datetime.now() - start)
<16> return user_id
<17>
<18> raise OAuthError("OAuth Error: " + str(r.status_code))
<19>
|
===========unchanged ref 0===========
at: backend.src.routers.auth
router = APIRouter()
s = requests.session()
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
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
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
PUBSUB_PUB = os.getenv("PUBSUB_PUB", "False") == "True"
at: src.utils
async_fail_gracefully(func: Callable[..., Any])
===========changed ref 0===========
+ # module: backend.src.analytics.user.main
+
+
===========changed ref 1===========
# module: backend.src.routers.pubsub
- @router.get("/test", status_code=status.HTTP_200_OK)
- @fail_gracefully
- def test(response: Response) -> Any:
- return {"test": count}
-
===========changed ref 2===========
# module: backend.src.routers.pubsub
router = APIRouter()
+ """
+ USER PUBSUB
+ """
- count: int = 0
===========changed ref 3===========
# module: backend.src.routers.pubsub
- @router.get("/pub/test/{update}", status_code=status.HTTP_200_OK)
- @fail_gracefully
- def test_post(response: Response, update: str) -> Any:
- publish_to_topic("test", {"num": int(update)})
- return update
-
===========changed ref 4===========
# module: backend.src.routers.pubsub
- @router.post("/sub/test/{token}", status_code=status.HTTP_200_OK)
- @async_fail_gracefully
- async def test_pubsub(response: Response, token: str, request: Request) -> Any:
- data = await parse_request(token, request)
-
- global count
- count += data["num"]
-
===========changed ref 5===========
# module: backend.src.db.functions.users
def update_user(user_id: str, raw_data: Optional[Dict[str, Any]] = None) -> None:
if raw_data is not None:
await USERS.update_one( # type: ignore
{"user_id": user_id},
+ {"$set": {"last_updated": datetime.now(), "raw_data": raw_data}},
- {"$set": {"raw_data": raw_data}},
)
===========changed ref 6===========
# module: backend.src.routers.pubsub
+ @router.get("/pub/user/{user_id}/{access_token}", status_code=status.HTTP_200_OK)
+ @fail_gracefully
+ def pub_user(response: Response, user_id: str, access_token: str) -> str:
+ publish_to_topic(
+ "user",
+ {
+ "user_id": user_id,
+ "access_token": access_token,
+ "start_date": str(date.today() - timedelta(365)),
+ "end_date": str(date.today()),
+ "timezone_str": "US/Eastern",
+ },
+ )
+
+ return user_id
+
===========changed ref 7===========
# module: backend.src.routers.pubsub
+ @router.post("/sub/user/{token}", status_code=status.HTTP_200_OK)
+ @async_fail_gracefully
+ async def sub_user(response: Response, token: str, request: Request) -> Any:
+ data: Dict[str, Any] = await parse_request(token, request)
+
+ print(data)
+
+ output = await analytics_get_user(
+ data["user_id"],
+ data["access_token"],
+ datetime.strptime(data["start_date"], "%Y-%m-%d").date(),
+ datetime.strptime(data["end_date"], "%Y-%m-%d").date(),
+ data["timezone_str"],
+ )
+
+ await update_user(data["user_id"], output)
+
+ return output
+
===========changed ref 8===========
+ # module: backend.src.analytics.user.main
+ def get_user(
+ user_id: str,
+ access_token: str,
+ start_date: date = date.today() - timedelta(365),
+ end_date: date = date.today(),
+ timezone_str: str = "US/Eastern",
+ ):
+ data = await get_data(user_id, access_token, start_date, end_date, timezone_str)
+
+ top_languages = get_top_languages(data)
+ top_repos = get_top_repos(data)
+ contribs_per_day = get_contribs_per_day(data)
+ contribs_per_repo_per_day = get_contribs_per_repo_per_day(data)
+
+ output = {
+ "top_languages": top_languages,
+ "top_repos": top_repos,
+ "contribs_per_day": contribs_per_day,
+ "contribs_per_repo_per_day": contribs_per_repo_per_day,
+ }
+
+ return output
+
|
backend.src.routers.users/get_user
|
Modified
|
avgupta456~github-trends
|
a313740875e3dc601f73cb82b87941a4cbbd708f
|
started cards
|
<0>:<del> if not PUBSUB_PUB:
<1>:<del> raise HTTPException(400, "")
<2>:<add> return await _get_user(user_id, start_date, end_date, timezone_str)
<3>:<del> db_user = await get_user_by_user_id(user_id)
<4>:<del> if db_user is None or db_user.access_token == "":
<5>:<del> raise LookupError("Invalid UserId")
<6>:<del>
<7>:<del> if db_user.raw_data is not None and (
<8>:<del> datetime.now() - db_user.last_updated
<9>:<del> ) < timedelta(hours=6):
<10>:<del> return db_user.raw_data
<11>:<del>
<12>:<del> publish_to_topic(
<13>:<del> "user",
<14>:<del> {
<15>:<del> "user_id": user_id,
<16>:<del> "access_token": db_user.access_token,
<17>:<del> "start_date": str(start_date),
<18>:<del> "end_date": str(end_date),
<19>:<del> "timezone_str": timezone_str,
<20>:<del> },
<21>:<del> )
<22>:<del>
<23>:<del> return {}
<24>:<del>
|
# module: backend.src.routers.users
@router.get("/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Dict[str, Any]:
<0> if not PUBSUB_PUB:
<1> raise HTTPException(400, "")
<2>
<3> db_user = await get_user_by_user_id(user_id)
<4> if db_user is None or db_user.access_token == "":
<5> raise LookupError("Invalid UserId")
<6>
<7> if db_user.raw_data is not None and (
<8> datetime.now() - db_user.last_updated
<9> ) < timedelta(hours=6):
<10> return db_user.raw_data
<11>
<12> publish_to_topic(
<13> "user",
<14> {
<15> "user_id": user_id,
<16> "access_token": db_user.access_token,
<17> "start_date": str(start_date),
<18> "end_date": str(end_date),
<19> "timezone_str": timezone_str,
<20> },
<21> )
<22>
<23> return {}
<24>
|
===========unchanged ref 0===========
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: src.constants
PUBSUB_PUB = os.getenv("PUBSUB_PUB", "False") == "True"
at: src.db.functions.get
get_user_by_user_id(user_id: str) -> Optional[UserModel]
at: src.db.models.users.UserModel
user_id: str
access_token: str
last_updated: datetime
raw_data: Optional[Dict[str, Any]]
at: src.external.pubsub.templates
publish_to_topic(topic: str, message: Dict[str, Any]) -> None
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.routers.users
+ def _get_user(
+ user_id: str,
+ start_date: date = date.today() - timedelta(365),
+ end_date: date = date.today(),
+ timezone_str: str = "US/Eastern",
+ ) -> Dict[str, Any]:
+ if not PUBSUB_PUB:
+ raise HTTPException(400, "")
+
+ db_user = await get_user_by_user_id(user_id)
+ if db_user is None or db_user.access_token == "":
+ raise LookupError("Invalid UserId")
+
+ if db_user.raw_data is not None and (
+ datetime.now() - db_user.last_updated
+ ) < timedelta(hours=6):
+ return db_user.raw_data
+
+ publish_to_topic(
+ "user",
+ {
+ "user_id": user_id,
+ "access_token": db_user.access_token,
+ "start_date": str(start_date),
+ "end_date": str(end_date),
+ "timezone_str": timezone_str,
+ },
+ )
+
+ return {}
+
|
backend.src.routers.users/get_user_svg
|
Modified
|
avgupta456~github-trends
|
4c0d26c1d61b16f9294685b15ab66f92d09b441b
|
render just svg, no html
|
<1>:<add> old = """
<del> return """
<3>:<del> <style>
<4>:<del> .header {
<5>:<del> font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
<6>:<del> fill: #2f80ed;
<7>:<del> animation: fadeInAnimation 0.8s ease-in-out forwards;
<8>:<del> }
<9>:<del> .lang-name {
<10>:<del> font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
<11>:<del> fill: #333;
<12>:<del> }
<13>:<del>
<14>:<del> @keyframes fadeInAnimation {
<15>:<del> from {
<16>:<del> opacity: 0;
<17>:<del> }
<18>:<del> to {
<19>:<del> opacity: 1;
<20>:<del> }
<21>:<del> }
<22>:<del> </style>
|
# module: backend.src.routers.users
@router.get(
"/{user_id}/svg", status_code=status.HTTP_200_OK, response_class=HTMLResponse
)
async def get_user_svg(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Any:
<0> # output = await _get_user(user_id, start_date, end_date, timezone_str)
<1> return """
<2> <svg width="300" height="285">
<3> <style>
<4> .header {
<5> font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
<6> fill: #2f80ed;
<7> animation: fadeInAnimation 0.8s ease-in-out forwards;
<8> }
<9> .lang-name {
<10> font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
<11> fill: #333;
<12> }
<13>
<14> @keyframes fadeInAnimation {
<15> from {
<16> opacity: 0;
<17> }
<18> to {
<19> opacity: 1;
<20> }
<21> }
<22> </style>
<23> <rect
<24> x="0.5"
<25> y="0.5"
<26> rx="4.5"
<27> height="99%"
<28> stroke="#e4e2e2"
<29> width="299"
<30> fill="#fffefe"
<31> stroke-opacity="1"
<32> />
<33> <g transform="translate(25, 35)">
<34> <text x="0" y="0" class="header">Most Used Languages</text>
<35> </g>
<36> <g transform="translate(0, 55)">
<37> <svg x="25">
<38> <g transform="translate(0, 0)">
<39> <text x="2" y="15"</s>
|
===========below chunk 0===========
# module: backend.src.routers.users
@router.get(
"/{user_id}/svg", status_code=status.HTTP_200_OK, response_class=HTMLResponse
)
async def get_user_svg(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Any:
# offset: 1
<text x="215" y="34" class="lang-name">73.16%</text>
<svg width="205" x="0" y="25">
<rect rx="5" ry="5" x="0" y="0" width="205" height="8" fill="#ddd" />
<rect height="8" fill="#DA5B0B" rx="5" ry="5" x="0" width="73.16%" />
</svg>
</g>
</svg>
</g>
</svg>
"""
===========unchanged ref 0===========
at: backend.src.routers.users
router = APIRouter()
_get_user(user_id: str, start_date: date=date.today() - timedelta(365), end_date: date=date.today(), timezone_str: str="US/Eastern") -> Dict[str, Any]
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: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.src.routers.users/get_user_svg
|
Modified
|
avgupta456~github-trends
|
2d1d5e9bf6b4e8a9ea5baa2d2ad5a92482416fe5
|
create svg_fail_gracefully
|
<s>.src.routers.users
@router.get(
"/{user_id}/svg", status_code=status.HTTP_200_OK, response_class=HTMLResponse
)
+ @svg_fail_gracefully
async def get_user_svg(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Any:
<0> # output = await _get_user(user_id, start_date, end_date, timezone_str)
<1> old = """
<2> <svg width="300" height="285">
<3> <rect
<4> x="0.5"
<5> y="0.5"
<6> rx="4.5"
<7> height="99%"
<8> stroke="#e4e2e2"
<9> width="299"
<10> fill="#fffefe"
<11> stroke-opacity="1"
<12> />
<13> <g transform="translate(25, 35)">
<14> <text x="0" y="0" class="header">Most Used Languages</text>
<15> </g>
<16> <g transform="translate(0, 55)">
<17> <svg x="25">
<18> <g transform="translate(0, 0)">
<19> <text x="2" y="15" class="lang-name">Jupyter Notebook</text>
<20> <text x="215" y="34" class="lang-name">73.16%</text>
<21> <svg width="205" x="0" y="25">
<22> <rect rx="5" ry="5" x="0" y="0" width="205" height="8" fill="#ddd" />
<23> <rect height="8" fill="#DA5B0B" rx="5" ry="5" x="0" width="73.16%" />
<24> </svg>
<25> </g>
<26> </svg>
<27> </g>
<28> </svg</s>
|
===========below chunk 0===========
<s>.users
@router.get(
"/{user_id}/svg", status_code=status.HTTP_200_OK, response_class=HTMLResponse
)
+ @svg_fail_gracefully
async def get_user_svg(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Any:
# offset: 1
"""
print(old)
style = """
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #2f80ed;
animation: fadeInAnimation 0.8s ease-in-out forwards;
}
.lang-name {
font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #333;
}
@keyframes fadeInAnimation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
d = svgwrite.Drawing(size=(300, 285))
d.defs.add(d.style(style)) # type: ignore
d.add( # type: ignore
d.rect( # type: ignore
size=(299, 284),
insert=(0.5, 0.5),
rx=4.5,
stroke="#e4e2e2",
fill="#fffefe",
)
)
d.add(d.text("Most Used Languages", insert=(25, 35), class_="header")) # type: ignore
sio = io.StringIO()
d.write(sio) # type: ignore
return Response(sio.getvalue(), media_type="image/svg+xml")
===========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
__str__ = isoformat
__radd__ = __add__
at: src.utils
svg_fail_gracefully(func: Callable[..., Any])
===========changed ref 0===========
# module: backend.src.utils
+ def svg_fail_gracefully(func: Callable[..., Any]):
+ @wraps(func) # needed to play nice with FastAPI decorator
+ async def wrapper(
+ response: Response, *args: List[Any], **kwargs: Dict[str, Any]
+ ) -> Any:
+ d: Drawing
+ status_code: int
+ try:
+ d = await func(response, *args, **kwargs)
+ status_code = status.HTTP_200_OK
+ except Exception as e:
+ logging.exception(e)
+ d = Drawing()
+ d.add(d.text("Unknown Error")) # type: ignore
+ status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
+
+ sio = io.StringIO()
+ d.write(sio) # type: ignore
+
+ return Response(
+ sio.getvalue(), media_type="image/svg+xml", status_code=status_code
+ )
+
+ return wrapper
+
|
|
backend.src.routers.users/get_user_svg
|
Modified
|
avgupta456~github-trends
|
80bd0800a2d94198872297a902aaad05ca8b7b5c
|
set up svg folder
|
<0>:<add> output = await _get_user(user_id, start_date, end_date, timezone_str)
<del> # output = await _get_user(user_id, start_date, end_date, timezone_str)
|
<s> backend.src.routers.users
@router.get(
"/{user_id}/svg", status_code=status.HTTP_200_OK, response_class=HTMLResponse
)
@svg_fail_gracefully
async def get_user_svg(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Any:
<0> # output = await _get_user(user_id, start_date, end_date, timezone_str)
<1> old = """
<2> <svg width="300" height="285">
<3> <rect
<4> x="0.5"
<5> y="0.5"
<6> rx="4.5"
<7> height="99%"
<8> stroke="#e4e2e2"
<9> width="299"
<10> fill="#fffefe"
<11> stroke-opacity="1"
<12> />
<13> <g transform="translate(25, 35)">
<14> <text x="0" y="0" class="header">Most Used Languages</text>
<15> </g>
<16> <g transform="translate(0, 55)">
<17> <svg x="25">
<18> <g transform="translate(0, 0)">
<19> <text x="2" y="15" class="lang-name">Jupyter Notebook</text>
<20> <text x="215" y="34" class="lang-name">73.16%</text>
<21> <svg width="205" x="0" y="25">
<22> <rect rx="5" ry="5" x="0" y="0" width="205" height="8" fill="#ddd" />
<23> <rect height="8" fill="#DA5B0B" rx="5" ry="5" x="0" width="73.16%" />
<24> </svg>
<25> </g>
<26> </svg>
<27> </g>
<28> </svg</s>
|
===========below chunk 0===========
<s>ers.users
@router.get(
"/{user_id}/svg", status_code=status.HTTP_200_OK, response_class=HTMLResponse
)
@svg_fail_gracefully
async def get_user_svg(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Any:
# offset: 1
"""
print(old)
style = """
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #2f80ed;
animation: fadeInAnimation 0.8s ease-in-out forwards;
}
.lang-name {
font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #333;
}
@keyframes fadeInAnimation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
d = svgwrite.Drawing(size=(300, 285))
d.defs.add(d.style(style)) # type: ignore
d.add( # type: ignore
d.rect( # type: ignore
size=(299, 284),
insert=(0.5, 0.5),
rx=4.5,
stroke="#e4e2e2",
fill="#fffefe",
)
)
d.add(d.text("Most Used Languages", insert=(25, 35), class_="header")) # type: ignore
return d
===========unchanged ref 0===========
at: backend.src.routers.users
_get_user(user_id: str, start_date: date=date.today() - timedelta(365), end_date: date=date.today(), timezone_str: str="US/Eastern") -> Dict[str, Any]
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.svg.top_langs
get_top_langs_svg(data: Dict[str, Any]) -> Drawing
at: src.utils
svg_fail_gracefully(func: Callable[..., Any])
===========changed ref 0===========
+ # module: backend.src.svg.style
+ style = """
+ .header {
+ font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
+ fill: #2f80ed;
+ animation: fadeInAnimation 0.8s ease-in-out forwards;
+ }
+ .lang-name {
+ font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
+ fill: #333;
+ }
+
+ @keyframes fadeInAnimation {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+ }
+ """
+
|
backend.src.routers.users/get_user_svg
|
Modified
|
avgupta456~github-trends
|
78322c4393b7789f25d114e59ed36393ccb64950
|
show top languages
|
<1>:<del> old = """
<2>:<del> <svg width="300" height="285">
<3>:<del> <rect
<4>:<del> x="0.5"
<5>:<del> y="0.5"
<6>:<del> rx="4.5"
<7>:<del> height="99%"
<8>:<del> stroke="#e4e2e2"
<9>:<del> width="299"
<10>:<del> fill="#fffefe"
<11>:<del> stroke-opacity="1"
<12>:<del> />
<13>:<del> <g transform="translate(25, 35)">
<14>:<del> <text x="0" y="0" class="header">Most Used Languages</text>
<15>:<del> </g>
<16>:<del> <g transform="translate(0, 55)">
<17>:<del> <svg x="25">
<18>:<del> <g transform="translate(0, 0)">
<19>:<del> <text x="2" y="15" class="lang-name">Jupyter Notebook</text>
<20>:<del> <text x="215" y="34" class="lang-name">73.16%</text>
<21>:<del> <svg width="205" x="0" y="25">
<22>:<del> <rect rx="5" ry="5" x="0" y="0" width="205" height="8" fill="#ddd" />
<23>:<del> <rect height="8" fill="#DA5B0B" rx="5" ry="5" x="0" width="73.16%" />
<24>:<del> </svg>
<25>:<del> </g>
<26>:<del> </svg>
<27>:<del> </g>
<28>:<del> </svg>
|
<s> backend.src.routers.users
@router.get(
"/{user_id}/svg", status_code=status.HTTP_200_OK, response_class=HTMLResponse
)
@svg_fail_gracefully
async def get_user_svg(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Any:
<0> output = await _get_user(user_id, start_date, end_date, timezone_str)
<1> old = """
<2> <svg width="300" height="285">
<3> <rect
<4> x="0.5"
<5> y="0.5"
<6> rx="4.5"
<7> height="99%"
<8> stroke="#e4e2e2"
<9> width="299"
<10> fill="#fffefe"
<11> stroke-opacity="1"
<12> />
<13> <g transform="translate(25, 35)">
<14> <text x="0" y="0" class="header">Most Used Languages</text>
<15> </g>
<16> <g transform="translate(0, 55)">
<17> <svg x="25">
<18> <g transform="translate(0, 0)">
<19> <text x="2" y="15" class="lang-name">Jupyter Notebook</text>
<20> <text x="215" y="34" class="lang-name">73.16%</text>
<21> <svg width="205" x="0" y="25">
<22> <rect rx="5" ry="5" x="0" y="0" width="205" height="8" fill="#ddd" />
<23> <rect height="8" fill="#DA5B0B" rx="5" ry="5" x="0" width="73.16%" />
<24> </svg>
<25> </g>
<26> </svg>
<27> </g>
<28> </svg></s>
|
===========below chunk 0===========
<s>ers.users
@router.get(
"/{user_id}/svg", status_code=status.HTTP_200_OK, response_class=HTMLResponse
)
@svg_fail_gracefully
async def get_user_svg(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Any:
# offset: 1
print(old)
return get_top_langs_svg(output)
===========unchanged ref 0===========
at: backend.src.routers.users
router = APIRouter()
_get_user(user_id: str, start_date: date=date.today() - timedelta(365), end_date: date=date.today(), timezone_str: str="US/Eastern") -> Dict[str, Any]
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.svg.top_langs
get_top_langs_svg(data: Dict[str, Any]) -> Drawing
at: src.utils
svg_fail_gracefully(func: Callable[..., Any])
|
backend.src.svg.top_langs/get_top_langs_svg
|
Modified
|
avgupta456~github-trends
|
78322c4393b7789f25d114e59ed36393ccb64950
|
show top languages
|
<13>:<add> d.add(d.text("Most Used Languages", insert=(25, 35), class_="header"))
<del> d.add(d.text("Most Used Languages", insert=(25, 35), class_="header")) # type: ignore
<14>:<add>
<add> langs = Group(transform="translate(25, 55)")
<add>
<add> data_langs = data["top_languages"][1:]
<add> for i in range(min(5, len(data_langs))):
<add> translate = "translate(0, " + str(40 * i) + ")"
<add> percent = data_langs[i]["percent"]
<add> lang1 = Group(transform=translate)
<add> lang1.add(d.text(data_langs[i]["lang"], insert=(2, 15), class_="lang-name"))
<add> lang1.add(d.text(str(percent) + "%", insert=(215, 33), class_="lang-name"))
<add> progress = Drawing(width="205", x="0", y="25")
<add> progress.add(d.rect(size=(205, 8), insert
|
# module: backend.src.svg.top_langs
def get_top_langs_svg(data: Dict[str, Any]) -> Drawing:
<0> d = Drawing(size=(300, 285))
<1> d.defs.add(d.style(style)) # type: ignore
<2>
<3> d.add( # type: ignore
<4> d.rect( # type: ignore
<5> size=(299, 284),
<6> insert=(0.5, 0.5),
<7> rx=4.5,
<8> stroke="#e4e2e2",
<9> fill="#fffefe",
<10> )
<11> )
<12>
<13> d.add(d.text("Most Used Languages", insert=(25, 35), class_="header")) # type: ignore
<14>
<15> return d
<16>
|
===========unchanged ref 0===========
at: src.svg.style
style = """
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #2f80ed;
animation: fadeInAnimation 0.8s ease-in-out forwards;
}
.lang-name {
font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #333;
}
@keyframes fadeInAnimation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
<s> backend.src.routers.users
@router.get(
"/{user_id}/svg", status_code=status.HTTP_200_OK, response_class=HTMLResponse
)
@svg_fail_gracefully
async def get_user_svg(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Any:
output = await _get_user(user_id, start_date, end_date, timezone_str)
- old = """
- <svg width="300" height="285">
- <rect
- x="0.5"
- y="0.5"
- rx="4.5"
- height="99%"
- stroke="#e4e2e2"
- width="299"
- fill="#fffefe"
- stroke-opacity="1"
- />
- <g transform="translate(25, 35)">
- <text x="0" y="0" class="header">Most Used Languages</text>
- </g>
- <g transform="translate(0, 55)">
- <svg x="25">
- <g transform="translate(0, 0)">
- <text x="2" y="15" class="lang-name">Jupyter Notebook</text>
- <text x="215" y="34" class="lang-name">73.16%</text>
- <svg width="205" x="0" y="25">
- <rect rx="5" ry="5" x="0" y="0" width="205" height="8" fill="#ddd" />
- <rect height="8" fill="#DA5B0B" rx="5" ry="5" x="0" width="73.16%" />
- </svg>
- </g>
- </svg>
- </g>
- </svg>
</s>
===========changed ref 1===========
<s>ers.users
@router.get(
"/{user_id}/svg", status_code=status.HTTP_200_OK, response_class=HTMLResponse
)
@svg_fail_gracefully
async def get_user_svg(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Any:
# offset: 1
<s> <del> </svg>
- </g>
- </svg>
- </g>
- </svg>
- """
-
- print(old)
-
return get_top_langs_svg(output)
|
backend.src.analytics.user.commits/get_top_languages
|
Modified
|
avgupta456~github-trends
|
7dd9fdd3921c06100b2e81c07f6d78fcc7014b58
|
bring in color
|
<4>:<add> "color": stats.color,
|
# module: backend.src.analytics.user.commits
def get_top_languages(data: UserPackage) -> List[dict_type]:
<0> raw_languages = data.contribs.total_stats.languages
<1> languages_list: List[dict_type] = [
<2> {
<3> "lang": lang,
<4> "additions": stats.additions,
<5> "deletions": stats.deletions,
<6> }
<7> for lang, stats in raw_languages.items()
<8> ]
<9>
<10> total_additions = sum([int(lang["additions"]) for lang in languages_list])
<11> total_deletions = sum([int(lang["deletions"]) for lang in languages_list])
<12> total_changed = total_additions + total_deletions
<13> total: dict_type = {
<14> "lang": "Total",
<15> "additions": total_additions,
<16> "deletions": total_deletions,
<17> }
<18>
<19> languages_list = sorted(
<20> languages_list,
<21> key=lambda x: int(x["additions"]) + int(x["deletions"]),
<22> reverse=True,
<23> )
<24> other: dict_type = {"lang": "Other", "additions": 0, "deletions": 0}
<25> for language in languages_list[5:]:
<26> other["additions"] = int(other["additions"]) + int(language["additions"])
<27> other["deletions"] = int(other["deletions"]) + int(language["deletions"])
<28>
<29> languages_list = [total] + languages_list[:5] + [other]
<30>
<31> for lang in languages_list:
<32> lang["added"] = int(lang["additions"]) - int(lang["deletions"])
<33> lang["changed"] = int(lang["additions"]) + int(lang["deletions"])
<34> lang["percent"] = float(round(100 * lang["changed"] / total_changed, 2))
<35>
<36> return languages_list
<37>
|
===========unchanged ref 0===========
at: backend.src.analytics.user.commits
dict_type = Dict[str, Union[str, int, float]]
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
additions: int
deletions: int
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
total: List[ContributionDay]
repo_stats: Dict[str, ContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.package.UserPackage
contribs: UserContributions
follows: UserFollows
at: typing
List = _alias(list, 1, inst=False, name='List')
|
backend.src.processing.commit/get_commits_languages
|
Modified
|
avgupta456~github-trends
|
7dd9fdd3921c06100b2e81c07f6d78fcc7014b58
|
bring in color
|
<22>:<add> lang_color = language["node"]["color"]
<32>:<add> "color": lang_color,
|
# module: backend.src.processing.commit
def get_commits_languages(access_token: str, node_ids: List[str], cutoff: int = CUTOFF):
<0> all_data = _get_commits_languages(access_token, node_ids, per_page=NODE_CHUNK_SIZE)
<1>
<2> out: List[Dict[str, Dict[str, int]]] = []
<3> for commit in all_data:
<4> out.append({})
<5> if (
<6> "additions" in commit
<7> and "deletions" in commit
<8> and "changedFiles" in commit
<9> and commit["additions"] + commit["deletions"] < cutoff
<10> ):
<11> languages = [
<12> x
<13> for x in commit["repository"]["languages"]["edges"]
<14> if x["node"]["name"] not in BLACKLIST
<15> ]
<16> num_langs = min(len(languages), commit["changedFiles"])
<17> total_repo_size = sum(
<18> [language["size"] for language in languages[:num_langs]]
<19> )
<20> for language in languages[:num_langs]:
<21> lang_name = language["node"]["name"]
<22> additions = round(
<23> commit["additions"] * language["size"] / total_repo_size
<24> )
<25> deletions = round(
<26> commit["deletions"] * language["size"] / total_repo_size
<27> )
<28> if additions > 0 or deletions > 0:
<29> out[-1][lang_name] = {
<30> "additions": additions,
<31> "deletions": deletions,
<32> }
<33>
<34> return out
<35>
|
===========unchanged ref 0===========
at: backend.src.processing.commit
_get_commits_languages(access_token: str, node_ids: List[str], per_page: int=NODE_CHUNK_SIZE) -> List[Dict[str, Any]]
at: src.constants
NODE_CHUNK_SIZE = 50 # number of nodes (commits) to query (max 100)
CUTOFF = 1000 # if > cutoff lines, assume imported, don't count
BLACKLIST = ["Jupyter Notebook", "HTML"] # languages to ignore
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.analytics.user.commits
def get_top_languages(data: UserPackage) -> List[dict_type]:
raw_languages = data.contribs.total_stats.languages
languages_list: List[dict_type] = [
{
"lang": lang,
+ "color": stats.color,
"additions": stats.additions,
"deletions": stats.deletions,
}
for lang, stats in raw_languages.items()
]
total_additions = sum([int(lang["additions"]) for lang in languages_list])
total_deletions = sum([int(lang["deletions"]) for lang in languages_list])
total_changed = total_additions + total_deletions
total: dict_type = {
"lang": "Total",
"additions": total_additions,
"deletions": total_deletions,
}
languages_list = sorted(
languages_list,
key=lambda x: int(x["additions"]) + int(x["deletions"]),
reverse=True,
)
other: dict_type = {"lang": "Other", "additions": 0, "deletions": 0}
for language in languages_list[5:]:
other["additions"] = int(other["additions"]) + int(language["additions"])
other["deletions"] = int(other["deletions"]) + int(language["deletions"])
languages_list = [total] + languages_list[:5] + [other]
for lang in languages_list:
lang["added"] = int(lang["additions"]) - int(lang["deletions"])
lang["changed"] = int(lang["additions"]) + int(lang["deletions"])
lang["percent"] = float(round(100 * lang["changed"] / total_changed, 2))
return languages_list
|
backend.src.svg.top_langs/get_top_langs_svg
|
Modified
|
avgupta456~github-trends
|
7dd9fdd3921c06100b2e81c07f6d78fcc7014b58
|
bring in color
|
<21>:<add> color = data_langs[i]["color"]
<27>:<add> d.rect(size=(2.05 * percent, 8), insert=(0, 0), rx=5, ry=5, fill=color)
<del> d.rect(size=(2.05 * percent, 8), insert=(0, 0), rx=5, ry=5, fill="#DA5B0B")
|
# module: backend.src.svg.top_langs
def get_top_langs_svg(data: Dict[str, Any]) -> Drawing:
<0> d = Drawing(size=(300, 285))
<1> d.defs.add(d.style(style)) # type: ignore
<2>
<3> d.add( # type: ignore
<4> d.rect( # type: ignore
<5> size=(299, 284),
<6> insert=(0.5, 0.5),
<7> rx=4.5,
<8> stroke="#e4e2e2",
<9> fill="#fffefe",
<10> )
<11> )
<12>
<13> d.add(d.text("Most Used Languages", insert=(25, 35), class_="header"))
<14>
<15> langs = Group(transform="translate(25, 55)")
<16>
<17> data_langs = data["top_languages"][1:]
<18> for i in range(min(5, len(data_langs))):
<19> translate = "translate(0, " + str(40 * i) + ")"
<20> percent = data_langs[i]["percent"]
<21> lang1 = Group(transform=translate)
<22> lang1.add(d.text(data_langs[i]["lang"], insert=(2, 15), class_="lang-name"))
<23> lang1.add(d.text(str(percent) + "%", insert=(215, 33), class_="lang-name"))
<24> progress = Drawing(width="205", x="0", y="25")
<25> progress.add(d.rect(size=(205, 8), insert=(0, 0), rx=5, ry=5, fill="#ddd"))
<26> progress.add(
<27> d.rect(size=(2.05 * percent, 8), insert=(0, 0), rx=5, ry=5, fill="#DA5B0B")
<28> )
<29> lang1.add(progress)
<30> langs.add(lang1)
<31> d.add(langs)
<32>
<33> return</s>
|
===========below chunk 0===========
# module: backend.src.svg.top_langs
def get_top_langs_svg(data: Dict[str, Any]) -> Drawing:
# offset: 1
===========unchanged ref 0===========
at: src.svg.style
style = """
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #2f80ed;
animation: fadeInAnimation 0.8s ease-in-out forwards;
}
.lang-name {
font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #333;
}
@keyframes fadeInAnimation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.processing.commit
def get_commits_languages(access_token: str, node_ids: List[str], cutoff: int = CUTOFF):
all_data = _get_commits_languages(access_token, node_ids, per_page=NODE_CHUNK_SIZE)
out: List[Dict[str, Dict[str, int]]] = []
for commit in all_data:
out.append({})
if (
"additions" in commit
and "deletions" in commit
and "changedFiles" in commit
and commit["additions"] + commit["deletions"] < cutoff
):
languages = [
x
for x in commit["repository"]["languages"]["edges"]
if x["node"]["name"] not in BLACKLIST
]
num_langs = min(len(languages), commit["changedFiles"])
total_repo_size = sum(
[language["size"] for language in languages[:num_langs]]
)
for language in languages[:num_langs]:
lang_name = language["node"]["name"]
+ lang_color = language["node"]["color"]
additions = round(
commit["additions"] * language["size"] / total_repo_size
)
deletions = round(
commit["deletions"] * language["size"] / total_repo_size
)
if additions > 0 or deletions > 0:
out[-1][lang_name] = {
"additions": additions,
"deletions": deletions,
+ "color": lang_color,
}
return out
===========changed ref 1===========
# module: backend.src.analytics.user.commits
def get_top_languages(data: UserPackage) -> List[dict_type]:
raw_languages = data.contribs.total_stats.languages
languages_list: List[dict_type] = [
{
"lang": lang,
+ "color": stats.color,
"additions": stats.additions,
"deletions": stats.deletions,
}
for lang, stats in raw_languages.items()
]
total_additions = sum([int(lang["additions"]) for lang in languages_list])
total_deletions = sum([int(lang["deletions"]) for lang in languages_list])
total_changed = total_additions + total_deletions
total: dict_type = {
"lang": "Total",
"additions": total_additions,
"deletions": total_deletions,
}
languages_list = sorted(
languages_list,
key=lambda x: int(x["additions"]) + int(x["deletions"]),
reverse=True,
)
other: dict_type = {"lang": "Other", "additions": 0, "deletions": 0}
for language in languages_list[5:]:
other["additions"] = int(other["additions"]) + int(language["additions"])
other["deletions"] = int(other["deletions"]) + int(language["deletions"])
languages_list = [total] + languages_list[:5] + [other]
for lang in languages_list:
lang["added"] = int(lang["additions"]) - int(lang["deletions"])
lang["changed"] = int(lang["additions"]) + int(lang["deletions"])
lang["percent"] = float(round(100 * lang["changed"] / total_changed, 2))
return languages_list
|
backend.src.external.github_api.graphql.commit/get_commits
|
Modified
|
avgupta456~github-trends
|
7dd9fdd3921c06100b2e81c07f6d78fcc7014b58
|
bring in color
|
<16>:<add> color
|
# module: backend.src.external.github_api.graphql.commit
def get_commits(
access_token: str, node_ids: List[str]
) -> Union[Dict[str, Any], List[Any]]:
<0> """gets all repository data from graphql"""
<1> query = {
<2> "variables": {"ids": node_ids},
<3> "query": """
<4> query getCommits($ids: [ID!]!) {
<5> nodes(ids: $ids) {
<6> ... on Commit {
<7> additions
<8> deletions
<9> changedFiles
<10> repository{
<11> languages(first: 5, orderBy: {field:SIZE, direction:DESC}){
<12> edges{
<13> size
<14> node{
<15> name
<16> }
<17> }
<18> }
<19> }
<20> }
<21> }
<22> }
<23> """,
<24> }
<25>
<26> return get_template(query, access_token)
<27>
|
===========unchanged ref 0===========
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 Language(BaseModel):
+ color: str
additions: int
deletions: int
===========changed ref 1===========
# module: backend.src.models.user.contribs
class CommitContribution(BaseModel):
timestamp: str
+ languages: Dict[str, Dict[str, Union[int, str]]]
- languages: Dict[str, Dict[str, int]]
===========changed ref 2===========
# module: backend.src.processing.commit
def get_commits_languages(access_token: str, node_ids: List[str], cutoff: int = CUTOFF):
all_data = _get_commits_languages(access_token, node_ids, per_page=NODE_CHUNK_SIZE)
out: List[Dict[str, Dict[str, int]]] = []
for commit in all_data:
out.append({})
if (
"additions" in commit
and "deletions" in commit
and "changedFiles" in commit
and commit["additions"] + commit["deletions"] < cutoff
):
languages = [
x
for x in commit["repository"]["languages"]["edges"]
if x["node"]["name"] not in BLACKLIST
]
num_langs = min(len(languages), commit["changedFiles"])
total_repo_size = sum(
[language["size"] for language in languages[:num_langs]]
)
for language in languages[:num_langs]:
lang_name = language["node"]["name"]
+ lang_color = language["node"]["color"]
additions = round(
commit["additions"] * language["size"] / total_repo_size
)
deletions = round(
commit["deletions"] * language["size"] / total_repo_size
)
if additions > 0 or deletions > 0:
out[-1][lang_name] = {
"additions": additions,
"deletions": deletions,
+ "color": lang_color,
}
return out
===========changed ref 3===========
# module: backend.src.analytics.user.commits
def get_top_languages(data: UserPackage) -> List[dict_type]:
raw_languages = data.contribs.total_stats.languages
languages_list: List[dict_type] = [
{
"lang": lang,
+ "color": stats.color,
"additions": stats.additions,
"deletions": stats.deletions,
}
for lang, stats in raw_languages.items()
]
total_additions = sum([int(lang["additions"]) for lang in languages_list])
total_deletions = sum([int(lang["deletions"]) for lang in languages_list])
total_changed = total_additions + total_deletions
total: dict_type = {
"lang": "Total",
"additions": total_additions,
"deletions": total_deletions,
}
languages_list = sorted(
languages_list,
key=lambda x: int(x["additions"]) + int(x["deletions"]),
reverse=True,
)
other: dict_type = {"lang": "Other", "additions": 0, "deletions": 0}
for language in languages_list[5:]:
other["additions"] = int(other["additions"]) + int(language["additions"])
other["deletions"] = int(other["deletions"]) + int(language["deletions"])
languages_list = [total] + languages_list[:5] + [other]
for lang in languages_list:
lang["added"] = int(lang["additions"]) - int(lang["deletions"])
lang["changed"] = int(lang["additions"]) + int(lang["deletions"])
lang["percent"] = float(round(100 * lang["changed"] / total_changed, 2))
return languages_list
===========changed ref 4===========
# module: backend.src.svg.top_langs
def get_top_langs_svg(data: Dict[str, Any]) -> Drawing:
d = Drawing(size=(300, 285))
d.defs.add(d.style(style)) # type: ignore
d.add( # type: ignore
d.rect( # type: ignore
size=(299, 284),
insert=(0.5, 0.5),
rx=4.5,
stroke="#e4e2e2",
fill="#fffefe",
)
)
d.add(d.text("Most Used Languages", insert=(25, 35), class_="header"))
langs = Group(transform="translate(25, 55)")
data_langs = data["top_languages"][1:]
for i in range(min(5, len(data_langs))):
translate = "translate(0, " + str(40 * i) + ")"
percent = data_langs[i]["percent"]
+ color = data_langs[i]["color"]
lang1 = Group(transform=translate)
lang1.add(d.text(data_langs[i]["lang"], insert=(2, 15), class_="lang-name"))
lang1.add(d.text(str(percent) + "%", insert=(215, 33), class_="lang-name"))
progress = Drawing(width="205", x="0", y="25")
progress.add(d.rect(size=(205, 8), insert=(0, 0), rx=5, ry=5, fill="#ddd"))
progress.add(
+ d.rect(size=(2.05 * percent, 8), insert=(0, 0), rx=5, ry=5, fill=color)
- d.rect(size=(2.05 * percent, 8), insert=(0, 0), rx=5, ry=5, fill="#DA5B0B")
)
lang1.add(progress)
langs.add</s>
===========changed ref 5===========
# module: backend.src.svg.top_langs
def get_top_langs_svg(data: Dict[str, Any]) -> Drawing:
# offset: 1
<s> ry=5, fill="#DA5B0B")
)
lang1.add(progress)
langs.add(lang1)
d.add(langs)
return d
|
backend.src.svg.top_langs/get_top_langs_svg
|
Modified
|
avgupta456~github-trends
|
51cd3a824e3fc921b04417e4b1c91bb15b750137
|
bug fixes
|
<22>:<add> lang = Group(transform=translate)
<del> lang1 = Group(transform=translate)
<23>:<add> lang.add(d.text(data_langs[i]["lang"], insert=(2, 15), class_="lang-name"))
<del> lang1.add(d.text(data_langs[i]["lang"], insert=(2, 15), class_="lang-name"))
<24>:<add> lang.add(d.text(str(percent) + "%", insert=(215, 33), class_="lang-name"))
<del> lang1.add(d.text(str(percent) + "%", insert=(215, 33), class_="lang-name"))
<30>:<add> lang.add(progress)
<del> lang1.add(progress)
<31>:<add> langs.add(lang)
<del> langs.add(lang1)
|
# module: backend.src.svg.top_langs
def get_top_langs_svg(data: Dict[str, Any]) -> Drawing:
<0> d = Drawing(size=(300, 285))
<1> d.defs.add(d.style(style)) # type: ignore
<2>
<3> d.add( # type: ignore
<4> d.rect( # type: ignore
<5> size=(299, 284),
<6> insert=(0.5, 0.5),
<7> rx=4.5,
<8> stroke="#e4e2e2",
<9> fill="#fffefe",
<10> )
<11> )
<12>
<13> d.add(d.text("Most Used Languages", insert=(25, 35), class_="header"))
<14>
<15> langs = Group(transform="translate(25, 55)")
<16>
<17> data_langs = data["top_languages"][1:]
<18> for i in range(min(5, len(data_langs))):
<19> translate = "translate(0, " + str(40 * i) + ")"
<20> percent = data_langs[i]["percent"]
<21> color = data_langs[i]["color"]
<22> lang1 = Group(transform=translate)
<23> lang1.add(d.text(data_langs[i]["lang"], insert=(2, 15), class_="lang-name"))
<24> lang1.add(d.text(str(percent) + "%", insert=(215, 33), class_="lang-name"))
<25> progress = Drawing(width="205", x="0", y="25")
<26> progress.add(d.rect(size=(205, 8), insert=(0, 0), rx=5, ry=5, fill="#ddd"))
<27> progress.add(
<28> d.rect(size=(2.05 * percent, 8), insert=(0, 0), rx=5, ry=5, fill=color)
<29> )
<30> lang1.add(progress)
<31> langs.add(lang1)
<32> d.add</s>
|
===========below chunk 0===========
# module: backend.src.svg.top_langs
def get_top_langs_svg(data: Dict[str, Any]) -> Drawing:
# offset: 1
return d
===========unchanged ref 0===========
at: src.svg.style
style = """
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #2f80ed;
animation: fadeInAnimation 0.8s ease-in-out forwards;
}
.lang-name {
font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #333;
}
@keyframes fadeInAnimation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.src.utils/svg_fail_gracefully
|
Modified
|
avgupta456~github-trends
|
8264e2b02c92dcce28b148da3bdb113e408b518a
|
add default error svg
|
<11>:<del> d = Drawing()
<12>:<del> d.add(d.text("Unknown Error")) # type: ignore
<13>:<add> d = get_error_svg()
<add> status_code = status.HTTP_200_OK
<del> status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
|
# module: backend.src.utils
# 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> status_code: int
<6> try:
<7> d = await func(response, *args, **kwargs)
<8> status_code = status.HTTP_200_OK
<9> except Exception as e:
<10> logging.exception(e)
<11> d = Drawing()
<12> d.add(d.text("Unknown Error")) # type: ignore
<13> status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
<14>
<15> sio = io.StringIO()
<16> d.write(sio) # type: ignore
<17>
<18> return Response(
<19> sio.getvalue(), media_type="image/svg+xml", status_code=status_code
<20> )
<21>
<22> return wrapper
<23>
|
===========unchanged ref 0===========
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.svg.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')
|
backend.src.svg.error/get_error_svg
|
Modified
|
avgupta456~github-trends
|
31c0b22d91c11d323e74e25aa06541c5806378a9
|
use viewbox
|
<0>:<add> d = Drawing(viewBox=("0 0 300 285"))
<del> d = Drawing(size=(300, 285))
<23>:<add> d.add(
<add> d.image(BACKEND_URL + "/assets/error", insert=(85, 100), style="opacity: 50%")
<del> d.add(d.image("../../assets/error", insert=(85, 100), style="opacity: 50%"))
<24>:<add> )
|
# module: backend.src.svg.error
def get_error_svg() -> Drawing:
<0> d = Drawing(size=(300, 285))
<1> d.defs.add(d.style(style))
<2>
<3> d.add(
<4> d.rect(
<5> size=(299, 284),
<6> insert=(0.5, 0.5),
<7> rx=4.5,
<8> stroke="#e4e2e2",
<9> fill="#fffefe",
<10> )
<11> )
<12>
<13> d.add(d.text("Unknown Error", insert=(25, 35), class_="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_="lang-name",
<20> )
<21> )
<22>
<23> d.add(d.image("../../assets/error", insert=(85, 100), style="opacity: 50%"))
<24>
<25> return d
<26>
|
===========unchanged ref 0===========
at: src.constants
BACKEND_URL = (
"https://pub-dot-github-298920.uc.r.appspot.com"
if PROD
else "http://localhost:8000"
)
at: src.svg.style
style = """
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #2f80ed;
animation: fadeInAnimation 0.8s ease-in-out forwards;
}
.lang-name {
font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #333;
}
@keyframes fadeInAnimation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
===========changed ref 0===========
# module: backend.src.constants
# GLOBAL
PROD = os.getenv("PROD", "False") == "True"
PROJECT_ID = "github-298920"
BACKEND_URL = (
+ "https://pub-dot-github-298920.uc.r.appspot.com"
- "https://pub-dot-github-298920.uc.r.appspot.com/"
if PROD
+ else "http://localhost:8000"
- else "http://localhost:8000/"
)
# API
TIMEOUT = 3 # max seconds to wait for api response
NODE_CHUNK_SIZE = 50 # number of nodes (commits) to query (max 100)
NODE_THREADS = 30 # number of node queries simultaneously (avoid blacklisting)
CUTOFF = 1000 # if > cutoff lines, assume imported, don't count
# CUSTOMIZATION
BLACKLIST = ["Jupyter Notebook", "HTML"] # languages to ignore
# OAUTH
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
# PUBSUB
PUBSUB_PUB = os.getenv("PUBSUB_PUB", "False") == "True"
PUBSUB_TOKEN = os.getenv("PUBSUB_TOKEN", "")
LOCAL_SUBSCRIBER = "http://localhost:8001/pubsub/sub/"
# MONGODB
MONGODB_PASSWORD = os.getenv("MONGODB_PASSWORD", "")
# SENTRY
SENTRY_DSN = os.getenv("SENTRY_DSN", "")
# TESTING
TEST_USER_ID = "AshishGupta938" # for testing, previously "avgupta456"
TEST_TOKEN = os.getenv("AUTH_TOKEN", "") # for authentication
|
backend.src.svg.top_langs/get_top_langs_svg
|
Modified
|
avgupta456~github-trends
|
31c0b22d91c11d323e74e25aa06541c5806378a9
|
use viewbox
|
<0>:<add> d = Drawing(viewBox=("0 0 300 285"))
<del> d = Drawing(size=(300, 285))
|
# module: backend.src.svg.top_langs
def get_top_langs_svg(data: Dict[str, Any]) -> Drawing:
<0> d = Drawing(size=(300, 285))
<1> d.defs.add(d.style(style))
<2>
<3> d.add(
<4> d.rect(
<5> size=(299, 284),
<6> insert=(0.5, 0.5),
<7> rx=4.5,
<8> stroke="#e4e2e2",
<9> fill="#fffefe",
<10> )
<11> )
<12>
<13> d.add(d.text("Most Used Languages", insert=(25, 35), class_="header"))
<14>
<15> langs = Group(transform="translate(25, 55)")
<16>
<17> data_langs = data["top_languages"][1:]
<18> for i in range(min(5, len(data_langs))):
<19> translate = "translate(0, " + str(40 * i) + ")"
<20> percent = data_langs[i]["percent"]
<21> color = data_langs[i]["color"]
<22> lang = Group(transform=translate)
<23> lang.add(d.text(data_langs[i]["lang"], insert=(2, 15), class_="lang-name"))
<24> lang.add(d.text(str(percent) + "%", insert=(215, 33), class_="lang-name"))
<25> progress = Drawing(width="205", x="0", y="25")
<26> progress.add(d.rect(size=(205, 8), insert=(0, 0), rx=5, ry=5, fill="#ddd"))
<27> progress.add(
<28> d.rect(size=(2.05 * percent, 8), insert=(0, 0), rx=5, ry=5, fill=color)
<29> )
<30> lang.add(progress)
<31> langs.add(lang)
<32> d.add(langs)
<33>
<34> return d
<35>
|
===========unchanged ref 0===========
at: src.svg.style
style = """
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #2f80ed;
animation: fadeInAnimation 0.8s ease-in-out forwards;
}
.lang-name {
font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #333;
}
@keyframes fadeInAnimation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.svg.error
def get_error_svg() -> Drawing:
+ d = Drawing(viewBox=("0 0 300 285"))
- d = Drawing(size=(300, 285))
d.defs.add(d.style(style))
d.add(
d.rect(
size=(299, 284),
insert=(0.5, 0.5),
rx=4.5,
stroke="#e4e2e2",
fill="#fffefe",
)
)
d.add(d.text("Unknown Error", insert=(25, 35), class_="header"))
d.add(
d.text(
"Please try again later or raise a ticket on GitHub",
insert=(25, 60),
class_="lang-name",
)
)
+ d.add(
+ d.image(BACKEND_URL + "/assets/error", insert=(85, 100), style="opacity: 50%")
- d.add(d.image("../../assets/error", insert=(85, 100), style="opacity: 50%"))
+ )
return d
===========changed ref 1===========
# module: backend.src.constants
# GLOBAL
PROD = os.getenv("PROD", "False") == "True"
PROJECT_ID = "github-298920"
BACKEND_URL = (
+ "https://pub-dot-github-298920.uc.r.appspot.com"
- "https://pub-dot-github-298920.uc.r.appspot.com/"
if PROD
+ else "http://localhost:8000"
- else "http://localhost:8000/"
)
# API
TIMEOUT = 3 # max seconds to wait for api response
NODE_CHUNK_SIZE = 50 # number of nodes (commits) to query (max 100)
NODE_THREADS = 30 # number of node queries simultaneously (avoid blacklisting)
CUTOFF = 1000 # if > cutoff lines, assume imported, don't count
# CUSTOMIZATION
BLACKLIST = ["Jupyter Notebook", "HTML"] # languages to ignore
# OAUTH
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
# PUBSUB
PUBSUB_PUB = os.getenv("PUBSUB_PUB", "False") == "True"
PUBSUB_TOKEN = os.getenv("PUBSUB_TOKEN", "")
LOCAL_SUBSCRIBER = "http://localhost:8001/pubsub/sub/"
# MONGODB
MONGODB_PASSWORD = os.getenv("MONGODB_PASSWORD", "")
# SENTRY
SENTRY_DSN = os.getenv("SENTRY_DSN", "")
# TESTING
TEST_USER_ID = "AshishGupta938" # for testing, previously "avgupta456"
TEST_TOKEN = os.getenv("AUTH_TOKEN", "") # for authentication
|
backend.src.svg.error/get_error_svg
|
Modified
|
avgupta456~github-trends
|
b8a3f924d282e0edd04fad1c9deff930e01754e7
|
set max dim
|
<0>:<add> d = Drawing(viewBox=("0 0 300 285"), class_="svg")
<del> d = Drawing(viewBox=("0 0 300 285"))
|
# module: backend.src.svg.error
def get_error_svg() -> Drawing:
<0> d = Drawing(viewBox=("0 0 300 285"))
<1> d.defs.add(d.style(style))
<2>
<3> d.add(
<4> d.rect(
<5> size=(299, 284),
<6> insert=(0.5, 0.5),
<7> rx=4.5,
<8> stroke="#e4e2e2",
<9> fill="#fffefe",
<10> )
<11> )
<12>
<13> d.add(d.text("Unknown Error", insert=(25, 35), class_="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_="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: src.constants
BACKEND_URL = (
"https://pub-dot-github-298920.uc.r.appspot.com"
if PROD
else "http://localhost:8000"
)
at: src.svg.style
style = """
.svg {
max-width: 300px;
max-height: 285px;
}
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #2f80ed;
animation: fadeInAnimation 0.8s ease-in-out forwards;
}
.lang-name {
font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #333;
}
@keyframes fadeInAnimation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
|
backend.src.svg.top_langs/get_top_langs_svg
|
Modified
|
avgupta456~github-trends
|
b8a3f924d282e0edd04fad1c9deff930e01754e7
|
set max dim
|
<0>:<add> d = Drawing(viewBox=("0 0 300 285"), class_="svg")
<del> d = Drawing(viewBox=("0 0 300 285"))
|
# module: backend.src.svg.top_langs
def get_top_langs_svg(data: Dict[str, Any]) -> Drawing:
<0> d = Drawing(viewBox=("0 0 300 285"))
<1> d.defs.add(d.style(style))
<2>
<3> d.add(
<4> d.rect(
<5> size=(299, 284),
<6> insert=(0.5, 0.5),
<7> rx=4.5,
<8> stroke="#e4e2e2",
<9> fill="#fffefe",
<10> )
<11> )
<12>
<13> d.add(d.text("Most Used Languages", insert=(25, 35), class_="header"))
<14>
<15> langs = Group(transform="translate(25, 55)")
<16>
<17> data_langs = data["top_languages"][1:]
<18> for i in range(min(5, len(data_langs))):
<19> translate = "translate(0, " + str(40 * i) + ")"
<20> percent = data_langs[i]["percent"]
<21> color = data_langs[i]["color"]
<22> lang = Group(transform=translate)
<23> lang.add(d.text(data_langs[i]["lang"], insert=(2, 15), class_="lang-name"))
<24> lang.add(d.text(str(percent) + "%", insert=(215, 33), class_="lang-name"))
<25> progress = Drawing(width="205", x="0", y="25")
<26> progress.add(d.rect(size=(205, 8), insert=(0, 0), rx=5, ry=5, fill="#ddd"))
<27> progress.add(
<28> d.rect(size=(2.05 * percent, 8), insert=(0, 0), rx=5, ry=5, fill=color)
<29> )
<30> lang.add(progress)
<31> langs.add(lang)
<32> d.add(langs)
<33>
<34> return d
<35>
|
===========unchanged ref 0===========
at: src.svg.style
style = """
.svg {
max-width: 300px;
max-height: 285px;
}
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #2f80ed;
animation: fadeInAnimation 0.8s ease-in-out forwards;
}
.lang-name {
font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #333;
}
@keyframes fadeInAnimation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.svg.style
style = """
+ .svg {
+ max-width: 300px;
+ max-height: 285px;
+ }
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #2f80ed;
animation: fadeInAnimation 0.8s ease-in-out forwards;
}
.lang-name {
font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #333;
}
@keyframes fadeInAnimation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
===========changed ref 1===========
# module: backend.src.svg.error
def get_error_svg() -> Drawing:
+ d = Drawing(viewBox=("0 0 300 285"), class_="svg")
- d = Drawing(viewBox=("0 0 300 285"))
d.defs.add(d.style(style))
d.add(
d.rect(
size=(299, 284),
insert=(0.5, 0.5),
rx=4.5,
stroke="#e4e2e2",
fill="#fffefe",
)
)
d.add(d.text("Unknown Error", insert=(25, 35), class_="header"))
d.add(
d.text(
"Please try again later or raise a ticket on GitHub",
insert=(25, 60),
class_="lang-name",
)
)
d.add(
d.image(BACKEND_URL + "/assets/error", insert=(85, 100), style="opacity: 50%")
)
return d
|
backend.src.svg.error/get_error_svg
|
Modified
|
avgupta456~github-trends
|
d47379604a53bcedfcbf4756e38695e05dffe3a7
|
add react-skeleton
|
<0>:<add> d = Drawing(size=(300, 285))
<del> d = Drawing(viewBox=("0 0 300 285"), class_="svg")
|
# module: backend.src.svg.error
def get_error_svg() -> Drawing:
<0> d = Drawing(viewBox=("0 0 300 285"), class_="svg")
<1> d.defs.add(d.style(style))
<2>
<3> d.add(
<4> d.rect(
<5> size=(299, 284),
<6> insert=(0.5, 0.5),
<7> rx=4.5,
<8> stroke="#e4e2e2",
<9> fill="#fffefe",
<10> )
<11> )
<12>
<13> d.add(d.text("Unknown Error", insert=(25, 35), class_="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_="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: src.constants
BACKEND_URL = (
"https://pub-dot-github-298920.uc.r.appspot.com"
if PROD
else "http://localhost:8000"
)
at: src.svg.style
style = """
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #2f80ed;
animation: fadeInAnimation 0.8s ease-in-out forwards;
}
.lang-name {
font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #333;
}
@keyframes fadeInAnimation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
|
backend.src.svg.top_langs/get_top_langs_svg
|
Modified
|
avgupta456~github-trends
|
d47379604a53bcedfcbf4756e38695e05dffe3a7
|
add react-skeleton
|
<0>:<add> d = Drawing(size=(300, 285))
<del> d = Drawing(viewBox=("0 0 300 285"), class_="svg")
|
# module: backend.src.svg.top_langs
def get_top_langs_svg(data: Dict[str, Any]) -> Drawing:
<0> d = Drawing(viewBox=("0 0 300 285"), class_="svg")
<1> d.defs.add(d.style(style))
<2>
<3> d.add(
<4> d.rect(
<5> size=(299, 284),
<6> insert=(0.5, 0.5),
<7> rx=4.5,
<8> stroke="#e4e2e2",
<9> fill="#fffefe",
<10> )
<11> )
<12>
<13> d.add(d.text("Most Used Languages", insert=(25, 35), class_="header"))
<14>
<15> langs = Group(transform="translate(25, 55)")
<16>
<17> data_langs = data["top_languages"][1:]
<18> for i in range(min(5, len(data_langs))):
<19> translate = "translate(0, " + str(40 * i) + ")"
<20> percent = data_langs[i]["percent"]
<21> color = data_langs[i]["color"]
<22> lang = Group(transform=translate)
<23> lang.add(d.text(data_langs[i]["lang"], insert=(2, 15), class_="lang-name"))
<24> lang.add(d.text(str(percent) + "%", insert=(215, 33), class_="lang-name"))
<25> progress = Drawing(width="205", x="0", y="25")
<26> progress.add(d.rect(size=(205, 8), insert=(0, 0), rx=5, ry=5, fill="#ddd"))
<27> progress.add(
<28> d.rect(size=(2.05 * percent, 8), insert=(0, 0), rx=5, ry=5, fill=color)
<29> )
<30> lang.add(progress)
<31> langs.add(lang)
<32> d.add(langs)
<33>
<34> return d</s>
|
===========unchanged ref 0===========
at: src.svg.style
style = """
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #2f80ed;
animation: fadeInAnimation 0.8s ease-in-out forwards;
}
.lang-name {
font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #333;
}
@keyframes fadeInAnimation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.svg.style
style = """
- .svg {
- display: inline-block;
- max-width: 300px;
- height: auto;
- }
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #2f80ed;
animation: fadeInAnimation 0.8s ease-in-out forwards;
}
.lang-name {
font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #333;
}
@keyframes fadeInAnimation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
===========changed ref 1===========
# module: backend.src.svg.error
def get_error_svg() -> Drawing:
+ d = Drawing(size=(300, 285))
- d = Drawing(viewBox=("0 0 300 285"), class_="svg")
d.defs.add(d.style(style))
d.add(
d.rect(
size=(299, 284),
insert=(0.5, 0.5),
rx=4.5,
stroke="#e4e2e2",
fill="#fffefe",
)
)
d.add(d.text("Unknown Error", insert=(25, 35), class_="header"))
d.add(
d.text(
"Please try again later or raise a ticket on GitHub",
insert=(25, 60),
class_="lang-name",
)
)
d.add(
d.image(BACKEND_URL + "/assets/error", insert=(85, 100), style="opacity: 50%")
)
return d
|
backend.src.routers.users/_get_user
|
Modified
|
avgupta456~github-trends
|
d67003171ca301b299c282b11e573dab2a50f0fd
|
add more validation, loading svg
|
<7>:<del> if db_user.raw_data is not None and (
<8>:<add> time_diff = datetime.now() - db_user.last_updated
<del> datetime.now() - db_user.last_updated
<9>:<add> if time_diff > timedelta(hours=6) or not validate_raw_data(db_user.raw_data):
<add> publish_to_topic(
<add> "user",
<add> {
<add> "user_id": user_id,
<add> "access_token": db_user.access_token,
<add> "start_date": str(start_date),
<add> "end_date": str(end_date),
<add> "timezone_str": timezone_str,
<add> },
<add> )
<del> ) < timedelta(hours=6):
<10>:<del> return db_user.raw_data
<12>:<del> publish_to_topic(
<13>:<del> "user",
<14>:<del> {
<15>:<del> "user_id": user_id,
<16>:<del> "access_token": db_user.access_token,
<17>:<del> "start_date": str(start_date),
<18>:<del> "end_date": str(end_date),
<19>:<del> "timezone_str": timezone_str,
<20>:<del> },
<21>:<del> )
<22>:<add> if validate_raw_data(db_user.raw_data):
<add> return db_user.raw_data # type: ignore
|
# module: backend.src.routers.users
def _get_user(
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Dict[str, Any]:
<0> if not PUBSUB_PUB:
<1> raise HTTPException(400, "")
<2>
<3> db_user = await get_user_by_user_id(user_id)
<4> if db_user is None or db_user.access_token == "":
<5> raise LookupError("Invalid UserId")
<6>
<7> if db_user.raw_data is not None and (
<8> datetime.now() - db_user.last_updated
<9> ) < timedelta(hours=6):
<10> return db_user.raw_data
<11>
<12> publish_to_topic(
<13> "user",
<14> {
<15> "user_id": user_id,
<16> "access_token": db_user.access_token,
<17> "start_date": str(start_date),
<18> "end_date": str(end_date),
<19> "timezone_str": timezone_str,
<20> },
<21> )
<22>
<23> return {}
<24>
|
===========unchanged ref 0===========
at: backend.src.routers.users
router = APIRouter()
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: src.constants
PUBSUB_PUB = os.getenv("PUBSUB_PUB", "False") == "True"
at: src.db.functions.get
get_user_by_user_id(user_id: str) -> Optional[UserModel]
at: src.db.models.users.UserModel
user_id: str
access_token: str
last_updated: datetime
raw_data: Optional[Dict[str, Any]]
at: src.utils
async_fail_gracefully(func: Callable[..., Any])
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.routers.assets
+ @router.get("/stopwatch", status_code=status.HTTP_200_OK)
+ async def get_stopwatch_img():
+ return FileResponse("./src/assets/stopwatch.png")
+
===========changed ref 1===========
# module: backend.src.routers.assets
- @router.get("/error", status_code=status.HTTP_200_OK)
- async def main():
- return FileResponse("./src/assets/error.png")
-
===========changed ref 2===========
# module: backend.src.routers.assets
- @router.get("/error", status_code=status.HTTP_200_OK)
- async def main():
- return FileResponse("./src/assets/error.png")
-
===========changed ref 3===========
# module: backend.src.svg.error
+ def get_loading_svg() -> Drawing:
+ d = Drawing(size=(300, 285))
+ d.defs.add(d.style(style))
+
+ d.add(
+ d.rect(
+ size=(299, 284),
+ insert=(0.5, 0.5),
+ rx=4.5,
+ stroke="#e4e2e2",
+ fill="#fffefe",
+ )
+ )
+
+ d.add(d.text("Loading data, hang tight!", insert=(25, 35), class_="header"))
+
+ d.add(
+ d.text(
+ "Please wait a couple seconds and refresh the page.",
+ insert=(25, 60),
+ class_="lang-name",
+ )
+ )
+
+ d.add(
+ d.image(
+ BACKEND_URL + "/assets/stopwatch", insert=(85, 100), style="opacity: 50%"
+ )
+ )
+
+ return d
+
|
backend.src.routers.users/get_user_svg
|
Modified
|
avgupta456~github-trends
|
d67003171ca301b299c282b11e573dab2a50f0fd
|
add more validation, loading svg
|
<1>:<add> if not validate_raw_data(output):
<add> return get_loading_svg()
|
<s> backend.src.routers.users
@router.get(
"/{user_id}/svg", status_code=status.HTTP_200_OK, response_class=HTMLResponse
)
@svg_fail_gracefully
async def get_user_svg(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Any:
<0> output = await _get_user(user_id, start_date, end_date, timezone_str)
<1> return get_top_langs_svg(output)
<2>
|
===========unchanged ref 0===========
at: backend.src.routers.users
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
today() -> _S
at: src.utils
async_fail_gracefully(func: Callable[..., Any])
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.routers.users
+ def validate_raw_data(data: Optional[Dict[str, Any]]) -> bool:
+ # NOTE: add more validation as more fields are required
+ return data is not None and "top_languages" in data
+
===========changed ref 1===========
# module: backend.src.routers.users
def _get_user(
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Dict[str, Any]:
if not PUBSUB_PUB:
raise HTTPException(400, "")
db_user = await get_user_by_user_id(user_id)
if db_user is None or db_user.access_token == "":
raise LookupError("Invalid UserId")
- if db_user.raw_data is not None and (
+ time_diff = datetime.now() - db_user.last_updated
- datetime.now() - db_user.last_updated
+ if time_diff > timedelta(hours=6) or not validate_raw_data(db_user.raw_data):
+ publish_to_topic(
+ "user",
+ {
+ "user_id": user_id,
+ "access_token": db_user.access_token,
+ "start_date": str(start_date),
+ "end_date": str(end_date),
+ "timezone_str": timezone_str,
+ },
+ )
- ) < timedelta(hours=6):
- return db_user.raw_data
- publish_to_topic(
- "user",
- {
- "user_id": user_id,
- "access_token": db_user.access_token,
- "start_date": str(start_date),
- "end_date": str(end_date),
- "timezone_str": timezone_str,
- },
- )
+ if validate_raw_data(db_user.raw_data):
+ return db_user.raw_data # type: ignore
return {}
===========changed ref 2===========
# module: backend.src.routers.assets
+ @router.get("/stopwatch", status_code=status.HTTP_200_OK)
+ async def get_stopwatch_img():
+ return FileResponse("./src/assets/stopwatch.png")
+
===========changed ref 3===========
# module: backend.src.routers.assets
- @router.get("/error", status_code=status.HTTP_200_OK)
- async def main():
- return FileResponse("./src/assets/error.png")
-
===========changed ref 4===========
# module: backend.src.routers.assets
- @router.get("/error", status_code=status.HTTP_200_OK)
- async def main():
- return FileResponse("./src/assets/error.png")
-
===========changed ref 5===========
# module: backend.src.svg.error
+ def get_loading_svg() -> Drawing:
+ d = Drawing(size=(300, 285))
+ d.defs.add(d.style(style))
+
+ d.add(
+ d.rect(
+ size=(299, 284),
+ insert=(0.5, 0.5),
+ rx=4.5,
+ stroke="#e4e2e2",
+ fill="#fffefe",
+ )
+ )
+
+ d.add(d.text("Loading data, hang tight!", insert=(25, 35), class_="header"))
+
+ d.add(
+ d.text(
+ "Please wait a couple seconds and refresh the page.",
+ insert=(25, 60),
+ class_="lang-name",
+ )
+ )
+
+ d.add(
+ d.image(
+ BACKEND_URL + "/assets/stopwatch", insert=(85, 100), style="opacity: 50%"
+ )
+ )
+
+ return d
+
|
backend.src.analytics.user.commits/get_top_languages
|
Modified
|
avgupta456~github-trends
|
37a3a7aa5e96bbb67ca454e3238bbd4d3ccff94a
|
improve language rank logic
|
<13>:<add> total_changed = total_additions + total_deletions + 1 # avoids division by zero
<del> total_changed = total_additions + total_deletions
<25>:<add> other: dict_type = {
<add> "lang": "Other",
<add> "additions": 0,
<add> "deletions": 0,
<add> "color": "#ededed",
<add> }
<del> other: dict_type = {"lang": "Other", "additions": 0, "deletions": 0}
<26>:<add> for language in languages_list[4:]:
<del> for language in languages_list[5:]:
<30>:<add> languages_list = [total] + languages_list[:4] + [other]
<del> languages_list = [total] + languages_list[:5] + [other]
<32>:<add> new_languages_list: List[dict_type] = []
<36>:<add> if lang["percent"] > 0:
<add> new_languages_list.append(lang)
<37>:<add> return new_languages_list
<del> return languages_
|
# module: backend.src.analytics.user.commits
def get_top_languages(data: UserPackage) -> List[dict_type]:
<0> raw_languages = data.contribs.total_stats.languages
<1> languages_list: List[dict_type] = [
<2> {
<3> "lang": lang,
<4> "color": stats.color,
<5> "additions": stats.additions,
<6> "deletions": stats.deletions,
<7> }
<8> for lang, stats in raw_languages.items()
<9> ]
<10>
<11> total_additions = sum([int(lang["additions"]) for lang in languages_list])
<12> total_deletions = sum([int(lang["deletions"]) for lang in languages_list])
<13> total_changed = total_additions + total_deletions
<14> total: dict_type = {
<15> "lang": "Total",
<16> "additions": total_additions,
<17> "deletions": total_deletions,
<18> }
<19>
<20> languages_list = sorted(
<21> languages_list,
<22> key=lambda x: int(x["additions"]) + int(x["deletions"]),
<23> reverse=True,
<24> )
<25> other: dict_type = {"lang": "Other", "additions": 0, "deletions": 0}
<26> for language in languages_list[5:]:
<27> other["additions"] = int(other["additions"]) + int(language["additions"])
<28> other["deletions"] = int(other["deletions"]) + int(language["deletions"])
<29>
<30> languages_list = [total] + languages_list[:5] + [other]
<31>
<32> for lang in languages_list:
<33> lang["added"] = int(lang["additions"]) - int(lang["deletions"])
<34> lang["changed"] = int(lang["additions"]) + int(lang["deletions"])
<35> lang["percent"] = float(round(100 * lang["changed"] / total_changed, 2))
<36>
<37> return languages_</s>
|
===========below chunk 0===========
# module: backend.src.analytics.user.commits
def get_top_languages(data: UserPackage) -> List[dict_type]:
# offset: 1
===========unchanged ref 0===========
at: backend.src.analytics.user.commits
dict_type = Dict[str, Union[str, int, float]]
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: str
additions: int
deletions: int
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
total: List[ContributionDay]
repo_stats: Dict[str, ContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.package.UserPackage
contribs: UserContributions
follows: UserFollows
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.constants
# GLOBAL
PROD = os.getenv("PROD", "False") == "True"
PROJECT_ID = "github-298920"
BACKEND_URL = "https://api.githubtrends.io" if PROD else "http://localhost:8000"
# API
+ TIMEOUT = 10 # max seconds to wait for api response
- TIMEOUT = 3 # max seconds to wait for api response
+ NODE_CHUNK_SIZE = 100 # number of nodes (commits) to query (max 100)
- NODE_CHUNK_SIZE = 50 # number of nodes (commits) to query (max 100)
+ NODE_THREADS = 20 # number of node queries simultaneously (avoid blacklisting)
- NODE_THREADS = 30 # number of node queries simultaneously (avoid blacklisting)
+ CUTOFF = 500 # if > cutoff lines, assume imported, don't count
- CUTOFF = 1000 # if > cutoff lines, assume imported, don't count
# CUSTOMIZATION
BLACKLIST = ["Jupyter Notebook", "HTML"] # languages to ignore
# OAUTH
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
# PUBSUB
PUBSUB_PUB = os.getenv("PUBSUB_PUB", "False") == "True"
PUBSUB_TOKEN = os.getenv("PUBSUB_TOKEN", "")
LOCAL_SUBSCRIBER = "http://localhost:8001/pubsub/sub/"
# MONGODB
MONGODB_PASSWORD = os.getenv("MONGODB_PASSWORD", "")
# SENTRY
SENTRY_DSN = os.getenv("SENTRY_DSN", "")
# TESTING
TEST_USER_ID = "AshishGupta938" # for testing, previously "avgupta456"
TEST_TOKEN = os.getenv("AUTH</s>
===========changed ref 1===========
# module: backend.src.constants
# offset: 1
<s>Gupta938" # for testing, previously "avgupta456"
TEST_TOKEN = os.getenv("AUTH_TOKEN", "") # for authentication
|
backend.src.routers.pubsub/sub_user
|
Modified
|
avgupta456~github-trends
|
b2c22cc7d3cb359e2a12b0eacd17aa02a6ce7b87
|
pubsub_fail_gracefully
|
<1>:<del>
<2>:<del> print(data)
|
# module: backend.src.routers.pubsub
@router.post("/sub/user/{token}", status_code=status.HTTP_200_OK)
+ @pubsub_fail_gracefully
- @async_fail_gracefully
async def sub_user(response: Response, token: str, request: Request) -> Any:
<0> data: Dict[str, Any] = await parse_request(token, request)
<1>
<2> print(data)
<3>
<4> output = await analytics_get_user(
<5> data["user_id"],
<6> data["access_token"],
<7> datetime.strptime(data["start_date"], "%Y-%m-%d").date(),
<8> datetime.strptime(data["end_date"], "%Y-%m-%d").date(),
<9> data["timezone_str"],
<10> )
<11>
<12> await update_user(data["user_id"], output)
<13>
<14> return output
<15>
|
===========unchanged ref 0===========
at: backend.src.routers.pubsub
router = APIRouter()
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
date() -> _date
strptime(date_string: _Text, format: _Text) -> datetime
__radd__ = __add__
at: src.analytics.user.main
get_user(user_id: str, access_token: str, start_date: date=date.today() - timedelta(365), end_date: date=date.today(), timezone_str: str="US/Eastern")
at: src.db.functions.users
update_user(user_id: str, raw_data: Optional[Dict[str, Any]]=None) -> None
at: src.external.pubsub.templates
parse_request(token: str, request: Request) -> Dict[str, Any]
at: src.utils
pubsub_fail_gracefully(func: Callable[..., Any])
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.src.routers.pubsub/sub_user
|
Modified
|
avgupta456~github-trends
|
bff68939355e5680e565cbdc315ad80ad3f07c1d
|
Merge branch 'main' of https://github.com/avgupta456/github-trends into main
|
<1>:<add>
<add> await lock_user(data["user_id"])
<12>:<add> await unlock_user(data["user_id"])
<add>
|
# module: backend.src.routers.pubsub
@router.post("/sub/user/{token}", status_code=status.HTTP_200_OK)
@pubsub_fail_gracefully
async def sub_user(response: Response, token: str, request: Request) -> Any:
<0> data: Dict[str, Any] = await parse_request(token, request)
<1>
<2> output = await analytics_get_user(
<3> data["user_id"],
<4> data["access_token"],
<5> datetime.strptime(data["start_date"], "%Y-%m-%d").date(),
<6> datetime.strptime(data["end_date"], "%Y-%m-%d").date(),
<7> data["timezone_str"],
<8> )
<9>
<10> await update_user(data["user_id"], output)
<11>
<12> return output
<13>
|
===========unchanged ref 0===========
at: backend.src.routers.pubsub
router = APIRouter()
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
date() -> _date
strptime(date_string: _Text, format: _Text) -> datetime
__radd__ = __add__
at: src.analytics.user.main
get_user(user_id: str, access_token: str, start_date: date=date.today() - timedelta(365), end_date: date=date.today(), timezone_str: str="US/Eastern")
at: src.db.functions.users
lock_user(user_id: str) -> None
update_user(user_id: str, raw_data: Optional[Dict[str, Any]]=None) -> None
at: src.external.pubsub.templates
parse_request(token: str, request: Request) -> Dict[str, Any]
at: src.utils
pubsub_fail_gracefully(func: Callable[..., Any])
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.src.routers.users/_get_user
|
Modified
|
avgupta456~github-trends
|
bff68939355e5680e565cbdc315ad80ad3f07c1d
|
Merge branch 'main' of https://github.com/avgupta456/github-trends into main
|
<9>:<add> if not db_user.lock:
<add> publish_to_topic(
<del> publish_to_topic(
<10>:<add> "user",
<del> "user",
<11>:<add> {
<del> {
<12>:<add> "user_id": user_id,
<del> "user_id": user_id,
<13>:<add> "access_token": db_user.access_token,
<del> "access_token": db_user.access_token,
<14>:<add> "start_date": str(start_date),
<del> "start_date": str(start_date),
<15>:<add> "end_date": str(end_date),
<del> "end_date": str(end_date),
<16>:<add> "timezone_str": timezone_str,
<del> "timezone_str": timezone_str,
<17>:<add> },
<add> )
<del> },
<18>:<del> )
|
# module: backend.src.routers.users
def _get_user(
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Dict[str, Any]:
<0> if not PUBSUB_PUB:
<1> raise HTTPException(400, "")
<2>
<3> db_user = await get_user_by_user_id(user_id)
<4> if db_user is None or db_user.access_token == "":
<5> raise LookupError("Invalid UserId")
<6>
<7> time_diff = datetime.now() - db_user.last_updated
<8> if time_diff > timedelta(hours=6) or not validate_raw_data(db_user.raw_data):
<9> publish_to_topic(
<10> "user",
<11> {
<12> "user_id": user_id,
<13> "access_token": db_user.access_token,
<14> "start_date": str(start_date),
<15> "end_date": str(end_date),
<16> "timezone_str": timezone_str,
<17> },
<18> )
<19>
<20> if validate_raw_data(db_user.raw_data):
<21> return db_user.raw_data # type: ignore
<22>
<23> return {}
<24>
|
===========unchanged ref 0===========
at: backend.src.routers.users
validate_raw_data(data: Optional[Dict[str, Any]]) -> bool
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: src.constants
PUBSUB_PUB = os.getenv("PUBSUB_PUB", "False") == "True"
at: src.db.functions.get
get_user_by_user_id(user_id: str) -> Optional[UserModel]
at: src.db.models.users.UserModel
user_id: str
access_token: str
last_updated: datetime
raw_data: Optional[Dict[str, Any]]
lock: bool
at: src.external.pubsub.templates
publish_to_topic(topic: str, message: Dict[str, Any]) -> None
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.routers.pubsub
@router.post("/sub/user/{token}", status_code=status.HTTP_200_OK)
@pubsub_fail_gracefully
async def sub_user(response: Response, token: str, request: Request) -> Any:
data: Dict[str, Any] = await parse_request(token, request)
+
+ await lock_user(data["user_id"])
output = await analytics_get_user(
data["user_id"],
data["access_token"],
datetime.strptime(data["start_date"], "%Y-%m-%d").date(),
datetime.strptime(data["end_date"], "%Y-%m-%d").date(),
data["timezone_str"],
)
await update_user(data["user_id"], output)
+ await unlock_user(data["user_id"])
+
return output
|
backend.src.db.functions.users/login_user
|
Modified
|
avgupta456~github-trends
|
bff68939355e5680e565cbdc315ad80ad3f07c1d
|
Merge branch 'main' of https://github.com/avgupta456/github-trends into main
|
<5>:<add> raw_user["lock"] = False
|
# module: backend.src.db.functions.users
def login_user(user_id: str, access_token: str) -> str:
<0> curr_user: Optional[Dict[str, Any]] = await USERS.find_one({"user_id": user_id}) # type: ignore
<1> raw_user: Dict[str, Any] = {"user_id": user_id, "access_token": access_token}
<2> if curr_user is None:
<3> raw_user["last_updated"] = datetime.now()
<4> raw_user["raw_data"] = None
<5>
<6> await USERS.update_one( # type: ignore
<7> {"user_id": user_id},
<8> {"$set": raw_user},
<9> upsert=True,
<10> )
<11> return user_id
<12>
|
===========unchanged ref 0===========
at: datetime
datetime()
at: datetime.datetime
__slots__ = date.__slots__ + time.__slots__
now(tz: Optional[_tzinfo]=...) -> _S
__radd__ = __add__
at: src.db.mongodb
USERS = DB.users # type: ignore
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: backend.src.routers.pubsub
@router.post("/sub/user/{token}", status_code=status.HTTP_200_OK)
@pubsub_fail_gracefully
async def sub_user(response: Response, token: str, request: Request) -> Any:
data: Dict[str, Any] = await parse_request(token, request)
+
+ await lock_user(data["user_id"])
output = await analytics_get_user(
data["user_id"],
data["access_token"],
datetime.strptime(data["start_date"], "%Y-%m-%d").date(),
datetime.strptime(data["end_date"], "%Y-%m-%d").date(),
data["timezone_str"],
)
await update_user(data["user_id"], output)
+ await unlock_user(data["user_id"])
+
return output
===========changed ref 1===========
# module: backend.src.routers.users
def _get_user(
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Dict[str, Any]:
if not PUBSUB_PUB:
raise HTTPException(400, "")
db_user = await get_user_by_user_id(user_id)
if db_user is None or db_user.access_token == "":
raise LookupError("Invalid UserId")
time_diff = datetime.now() - db_user.last_updated
if time_diff > timedelta(hours=6) or not validate_raw_data(db_user.raw_data):
+ if not db_user.lock:
+ publish_to_topic(
- publish_to_topic(
+ "user",
- "user",
+ {
- {
+ "user_id": user_id,
- "user_id": user_id,
+ "access_token": db_user.access_token,
- "access_token": db_user.access_token,
+ "start_date": str(start_date),
- "start_date": str(start_date),
+ "end_date": str(end_date),
- "end_date": str(end_date),
+ "timezone_str": timezone_str,
- "timezone_str": timezone_str,
+ },
+ )
- },
- )
if validate_raw_data(db_user.raw_data):
return db_user.raw_data # type: ignore
return {}
|
backend.src.analytics.user.commits/get_top_repos
|
Modified
|
avgupta456~github-trends
|
d89908a86634f3a3aba6a031571e95606917e073
|
Create RawDataModel
|
<2>:<add> "repo": repo,
<del> repo: repo,
<3>:<add> "languages": [
<add> {"lang": x[0], "additions": x[1].additions, "deletions": x[1].deletions}
<add> for x in list(repo_stats.languages.items())
<del> "languages": list(repo_stats.languages.keys()),
<4>:<add> ],
|
# module: backend.src.analytics.user.commits
def get_top_repos(data: UserPackage) -> List[Any]:
<0> repos: List[Any] = [
<1> {
<2> repo: repo,
<3> "languages": list(repo_stats.languages.keys()),
<4> "additions": sum([x.additions for x in repo_stats.languages.values()]),
<5> "deletions": sum([x.deletions for x in repo_stats.languages.values()]),
<6> }
<7> for repo, repo_stats in data.contribs.repo_stats.items()
<8> ]
<9>
<10> for repo in repos:
<11> repo["added"] = int(repo["additions"]) - int(repo["deletions"])
<12> repo["changed"] = int(repo["additions"]) + int(repo["deletions"])
<13>
<14> repos = sorted(repos, key=lambda x: x["changed"], reverse=True)
<15>
<16> return repos[:5]
<17>
|
===========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.Language
color: str
additions: int
deletions: int
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
total: List[ContributionDay]
repo_stats: Dict[str, ContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.package.UserPackage
contribs: UserContributions
follows: UserFollows
at: typing
List = _alias(list, 1, inst=False, name='List')
|
backend.src.routers.users/validate_raw_data
|
Modified
|
avgupta456~github-trends
|
d89908a86634f3a3aba6a031571e95606917e073
|
Create RawDataModel
|
<1>:<add> return data is not None and data.top_languages is not None
<del> return data is not None and "top_languages" in data
|
# module: backend.src.routers.users
+ def validate_raw_data(data: Optional[RawDataModel]) -> bool:
- def validate_raw_data(data: Optional[Dict[str, Any]]) -> bool:
<0> # NOTE: add more validation as more fields are required
<1> return data is not None and "top_languages" in data
<2>
|
===========changed ref 0===========
# module: backend.src.analytics.user.commits
def get_top_repos(data: UserPackage) -> List[Any]:
repos: List[Any] = [
{
+ "repo": repo,
- repo: repo,
+ "languages": [
+ {"lang": x[0], "additions": x[1].additions, "deletions": x[1].deletions}
+ for x in list(repo_stats.languages.items())
- "languages": list(repo_stats.languages.keys()),
+ ],
"additions": sum([x.additions for x in repo_stats.languages.values()]),
"deletions": sum([x.deletions for x in repo_stats.languages.values()]),
}
for repo, repo_stats in data.contribs.repo_stats.items()
]
for repo in repos:
repo["added"] = int(repo["additions"]) - int(repo["deletions"])
repo["changed"] = int(repo["additions"]) + int(repo["deletions"])
repos = sorted(repos, key=lambda x: x["changed"], reverse=True)
return repos[:5]
|
backend.src.routers.users/_get_user
|
Modified
|
avgupta456~github-trends
|
d89908a86634f3a3aba6a031571e95606917e073
|
Create RawDataModel
|
<24>:<add> return None
<del> return {}
|
# module: backend.src.routers.users
def _get_user(
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
+ ) -> Optional[RawDataModel]:
- ) -> Dict[str, Any]:
<0> if not PUBSUB_PUB:
<1> raise HTTPException(400, "")
<2>
<3> db_user = await get_user_by_user_id(user_id)
<4> if db_user is None or db_user.access_token == "":
<5> raise LookupError("Invalid UserId")
<6>
<7> time_diff = datetime.now() - db_user.last_updated
<8> if time_diff > timedelta(hours=6) or not validate_raw_data(db_user.raw_data):
<9> if not db_user.lock:
<10> publish_to_topic(
<11> "user",
<12> {
<13> "user_id": user_id,
<14> "access_token": db_user.access_token,
<15> "start_date": str(start_date),
<16> "end_date": str(end_date),
<17> "timezone_str": timezone_str,
<18> },
<19> )
<20>
<21> if validate_raw_data(db_user.raw_data):
<22> return db_user.raw_data # type: ignore
<23>
<24> return {}
<25>
|
===========unchanged ref 0===========
at: backend.src.routers.users
validate_raw_data(data: Optional[RawDataModel]) -> bool
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: src.constants
PUBSUB_PUB = os.getenv("PUBSUB_PUB", "False") == "True"
at: src.db.functions.get
get_user_by_user_id(user_id: str) -> Optional[UserModel]
at: src.db.models.users.UserModel
user_id: str
access_token: str
last_updated: datetime
raw_data: Optional[RawDataModel]
lock: bool
at: src.external.pubsub.templates
publish_to_topic(topic: str, message: Dict[str, Any]) -> None
===========changed ref 0===========
# module: backend.src.routers.users
+ def validate_raw_data(data: Optional[RawDataModel]) -> bool:
- def validate_raw_data(data: Optional[Dict[str, Any]]) -> bool:
# NOTE: add more validation as more fields are required
+ return data is not None and data.top_languages is not None
- return data is not None and "top_languages" in data
===========changed ref 1===========
# module: backend.src.analytics.user.commits
def get_top_repos(data: UserPackage) -> List[Any]:
repos: List[Any] = [
{
+ "repo": repo,
- repo: repo,
+ "languages": [
+ {"lang": x[0], "additions": x[1].additions, "deletions": x[1].deletions}
+ for x in list(repo_stats.languages.items())
- "languages": list(repo_stats.languages.keys()),
+ ],
"additions": sum([x.additions for x in repo_stats.languages.values()]),
"deletions": sum([x.deletions for x in repo_stats.languages.values()]),
}
for repo, repo_stats in data.contribs.repo_stats.items()
]
for repo in repos:
repo["added"] = int(repo["additions"]) - int(repo["deletions"])
repo["changed"] = int(repo["additions"]) + int(repo["deletions"])
repos = sorted(repos, key=lambda x: x["changed"], reverse=True)
return repos[:5]
|
backend.src.svg.top_langs/get_top_langs_svg
|
Modified
|
avgupta456~github-trends
|
d89908a86634f3a3aba6a031571e95606917e073
|
Create RawDataModel
|
<17>:<add> if data.top_languages is None:
<add> raise ValueError("No language data available")
<add> data_langs = data.top_languages[1:]
<del> data_langs = data["top_languages"][1:]
<20>:<add> percent = data_langs[i].percent
<del> percent = data_langs[i]["percent"]
<21>:<add> color = data_langs[i].color or "#ededed"
<del> color = data_langs[i]["color"]
<23>:<add> lang.add(d.text(data_langs[i].lang, insert=(2, 15), class_="lang-name"))
<del> lang.add(d.text(data_langs[i]["lang"], insert=(2, 15), class_="lang-name"))
|
# module: backend.src.svg.top_langs
+ def get_top_langs_svg(data: RawDataModel) -> Drawing:
- def get_top_langs_svg(data: Dict[str, Any]) -> Drawing:
<0> d = Drawing(size=(300, 285))
<1> d.defs.add(d.style(style))
<2>
<3> d.add(
<4> d.rect(
<5> size=(299, 284),
<6> insert=(0.5, 0.5),
<7> rx=4.5,
<8> stroke="#e4e2e2",
<9> fill="#fffefe",
<10> )
<11> )
<12>
<13> d.add(d.text("Most Used Languages", insert=(25, 35), class_="header"))
<14>
<15> langs = Group(transform="translate(25, 55)")
<16>
<17> data_langs = data["top_languages"][1:]
<18> for i in range(min(5, len(data_langs))):
<19> translate = "translate(0, " + str(40 * i) + ")"
<20> percent = data_langs[i]["percent"]
<21> color = data_langs[i]["color"]
<22> lang = Group(transform=translate)
<23> lang.add(d.text(data_langs[i]["lang"], insert=(2, 15), class_="lang-name"))
<24> lang.add(d.text(str(percent) + "%", insert=(215, 33), class_="lang-name"))
<25> progress = Drawing(width="205", x="0", y="25")
<26> progress.add(d.rect(size=(205, 8), insert=(0, 0), rx=5, ry=5, fill="#ddd"))
<27> progress.add(
<28> d.rect(size=(2.05 * percent, 8), insert=(0, 0), rx=5, ry=5, fill=color)
<29> )
<30> lang.add(progress)
<31> langs.add(lang)
<32> d</s>
|
===========below chunk 0===========
# module: backend.src.svg.top_langs
+ def get_top_langs_svg(data: RawDataModel) -> Drawing:
- def get_top_langs_svg(data: Dict[str, Any]) -> Drawing:
# offset: 1
return d
===========unchanged ref 0===========
at: src.models.user.analytics.LanguageStats
lang: str
additions: int
deletions: int
added: int
changed: int
percent: float
color: Optional[str]
at: src.models.user.analytics.RawDataModel
top_languages: Optional[List[LanguageStats]]
top_repos: Optional[List[RepoStats]]
at: src.svg.style
style = """
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #2f80ed;
animation: fadeInAnimation 0.8s ease-in-out forwards;
}
.lang-name {
font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #333;
}
@keyframes fadeInAnimation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
===========changed ref 0===========
# module: backend.src.routers.users
+ def validate_raw_data(data: Optional[RawDataModel]) -> bool:
- def validate_raw_data(data: Optional[Dict[str, Any]]) -> bool:
# NOTE: add more validation as more fields are required
+ return data is not None and data.top_languages is not None
- return data is not None and "top_languages" in data
===========changed ref 1===========
# module: backend.src.routers.users
def _get_user(
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
+ ) -> Optional[RawDataModel]:
- ) -> Dict[str, Any]:
if not PUBSUB_PUB:
raise HTTPException(400, "")
db_user = await get_user_by_user_id(user_id)
if db_user is None or db_user.access_token == "":
raise LookupError("Invalid UserId")
time_diff = datetime.now() - db_user.last_updated
if time_diff > timedelta(hours=6) or not validate_raw_data(db_user.raw_data):
if not db_user.lock:
publish_to_topic(
"user",
{
"user_id": user_id,
"access_token": db_user.access_token,
"start_date": str(start_date),
"end_date": str(end_date),
"timezone_str": timezone_str,
},
)
if validate_raw_data(db_user.raw_data):
return db_user.raw_data # type: ignore
+ return None
- return {}
===========changed ref 2===========
# module: backend.src.analytics.user.commits
def get_top_repos(data: UserPackage) -> List[Any]:
repos: List[Any] = [
{
+ "repo": repo,
- repo: repo,
+ "languages": [
+ {"lang": x[0], "additions": x[1].additions, "deletions": x[1].deletions}
+ for x in list(repo_stats.languages.items())
- "languages": list(repo_stats.languages.keys()),
+ ],
"additions": sum([x.additions for x in repo_stats.languages.values()]),
"deletions": sum([x.deletions for x in repo_stats.languages.values()]),
}
for repo, repo_stats in data.contribs.repo_stats.items()
]
for repo in repos:
repo["added"] = int(repo["additions"]) - int(repo["deletions"])
repo["changed"] = int(repo["additions"]) + int(repo["deletions"])
repos = sorted(repos, key=lambda x: x["changed"], reverse=True)
return repos[:5]
|
backend.src.routers.users/get_user_svg
|
Modified
|
avgupta456~github-trends
|
1781d84eac09ae6508693147b345dc9094f27f54
|
language by lines SVG
|
<3>:<add> return get_top_langs_svg(output, use_percent) # type: ignore
<del> return get_top_langs_svg(output) # type: ignore
|
<s>HTMLResponse
- "/{user_id}/svg", status_code=status.HTTP_200_OK, response_class=HTMLResponse
)
@svg_fail_gracefully
async def get_user_svg(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
+ use_percent: bool = True,
) -> Any:
<0> output = await _get_user(user_id, start_date, end_date, timezone_str)
<1> if not validate_raw_data(output):
<2> return get_loading_svg()
<3> return get_top_langs_svg(output) # type: ignore
<4>
|
===========unchanged ref 0===========
at: backend.src.routers.users
router = APIRouter()
validate_raw_data(data: Optional[RawDataModel]) -> bool
_get_user(user_id: str, start_date: date=date.today() - timedelta(365), end_date: date=date.today(), timezone_str: str="US/Eastern") -> Optional[RawDataModel]
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.svg.error
get_loading_svg() -> Drawing
at: src.utils
svg_fail_gracefully(func: Callable[..., Any])
|
backend.src.svg.top_langs/get_top_langs_svg
|
Modified
|
avgupta456~github-trends
|
1781d84eac09ae6508693147b345dc9094f27f54
|
language by lines SVG
|
<22>:<add> percent = (
<add> data_langs[i].percent
<del> percent = data_langs[i].percent
<23>:<add> if use_percent
<add> else 100 * data_langs[i].changed / data_langs[0].changed
<add> )
<26>:<add> if use_percent:
<add> lang.add(d.text(str(percent) + "%", insert=(215, 33), class_="lang-name"))
<del> lang.add(d.text(str(percent) + "%", insert=(215, 33), class_="lang-name"))
<27>:<add> else:
<add> lang.add(
<add> d.text(
<add> format_number(data_langs[i].changed),
<add> insert=(215, 33),
<add> class_="lang-name",
<add> )
<add> )
<30>:<add> d.rect(
<add> size=(2.05 * percent, 8),
<add> insert=(0, 0),
<add> rx=5,
<add> ry=5,
<add> fill=color,
<add> )
<del> d.rect(size=(2.05 * percent, 8), insert=(0, 0), rx=5, ry=5, fill=color
|
# module: backend.src.svg.top_langs
+ def get_top_langs_svg(data: RawDataModel, use_percent: bool = True) -> Drawing:
- def get_top_langs_svg(data: RawDataModel) -> Drawing:
<0> d = Drawing(size=(300, 285))
<1> d.defs.add(d.style(style))
<2>
<3> d.add(
<4> d.rect(
<5> size=(299, 284),
<6> insert=(0.5, 0.5),
<7> rx=4.5,
<8> stroke="#e4e2e2",
<9> fill="#fffefe",
<10> )
<11> )
<12>
<13> d.add(d.text("Most Used Languages", insert=(25, 35), class_="header"))
<14>
<15> langs = Group(transform="translate(25, 55)")
<16>
<17> if data.top_languages is None:
<18> raise ValueError("No language data available")
<19> data_langs = data.top_languages[1:]
<20> for i in range(min(5, len(data_langs))):
<21> translate = "translate(0, " + str(40 * i) + ")"
<22> percent = data_langs[i].percent
<23> color = data_langs[i].color or "#ededed"
<24> lang = Group(transform=translate)
<25> lang.add(d.text(data_langs[i].lang, insert=(2, 15), class_="lang-name"))
<26> lang.add(d.text(str(percent) + "%", insert=(215, 33), class_="lang-name"))
<27> progress = Drawing(width="205", x="0", y="25")
<28> progress.add(d.rect(size=(205, 8), insert=(0, 0), rx=5, ry=5, fill="#ddd"))
<29> progress.add(
<30> d.rect(size=(2.05 * percent, 8), insert=(0, 0), rx=5, ry=5, fill=color</s>
|
===========below chunk 0===========
# module: backend.src.svg.top_langs
+ def get_top_langs_svg(data: RawDataModel, use_percent: bool = True) -> Drawing:
- def get_top_langs_svg(data: RawDataModel) -> Drawing:
# offset: 1
)
lang.add(progress)
langs.add(lang)
d.add(langs)
return d
===========unchanged ref 0===========
at: src.models.user.analytics.LanguageStats
lang: str
additions: int
deletions: int
added: int
changed: int
percent: float
color: Optional[str]
at: src.models.user.analytics.RawDataModel
top_languages: Optional[List[LanguageStats]]
top_repos: Optional[List[RepoStats]]
at: src.svg.style
style = """
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #2f80ed;
animation: fadeInAnimation 0.8s ease-in-out forwards;
}
.lang-name {
font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #333;
}
@keyframes fadeInAnimation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
===========changed ref 0===========
# module: backend.src.svg.top_langs
+ def format_number(num: int) -> str:
+ if num > 10000:
+ return "~" + str(int(num / 1000)) + "k lines"
+ elif num > 1000:
+ return "~" + str(int(num / 100) / 10) + "k lines"
+ elif num > 100:
+ return "~" + str(int(num / 100) * 100) + " lines"
+ else:
+ return "<100 lines"
+
===========changed ref 1===========
<s>HTMLResponse
- "/{user_id}/svg", status_code=status.HTTP_200_OK, response_class=HTMLResponse
)
@svg_fail_gracefully
async def get_user_svg(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
+ use_percent: bool = True,
) -> Any:
output = await _get_user(user_id, start_date, end_date, timezone_str)
if not validate_raw_data(output):
return get_loading_svg()
+ return get_top_langs_svg(output, use_percent) # type: ignore
- return get_top_langs_svg(output) # type: ignore
|
backend.src.external.github_api.graphql.commit/get_commits
|
Modified
|
avgupta456~github-trends
|
d1366acd2e7db3e56758e52df8f2fafed719b1a8
|
remove repository query in commits
|
<10>:<del> repository{
<11>:<del> languages(first: 5, orderBy: {field:SIZE, direction:DESC}){
<12>:<del> edges{
<13>:<del> size
<14>:<del> node{
<15>:<del> name
<16>:<del> color
<17>:<del> }
<18>:<del> }
<19>:<del> }
<20>:<del> }
<27>:<add> return get_template(query, access_token)["data"]["nodes"]
<del> return get_template(query, access_token)
|
# module: backend.src.external.github_api.graphql.commit
def get_commits(
access_token: str, node_ids: List[str]
) -> Union[Dict[str, Any], List[Any]]:
<0> """gets all repository data from graphql"""
<1> query = {
<2> "variables": {"ids": node_ids},
<3> "query": """
<4> query getCommits($ids: [ID!]!) {
<5> nodes(ids: $ids) {
<6> ... on Commit {
<7> additions
<8> deletions
<9> changedFiles
<10> repository{
<11> languages(first: 5, orderBy: {field:SIZE, direction:DESC}){
<12> edges{
<13> size
<14> node{
<15> name
<16> color
<17> }
<18> }
<19> }
<20> }
<21> }
<22> }
<23> }
<24> """,
<25> }
<26>
<27> return get_template(query, access_token)
<28>
|
===========unchanged ref 0===========
at: src.external.github_api.graphql.template
get_template(query: Dict[str, Any], access_token: str) -> Dict[str, Any]
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.src.external.github_api.graphql.repo/get_repo
|
Modified
|
avgupta456~github-trends
|
f605ccc623bcbe54e587ec011f0ad69e7e951a75
|
separate commit and repo langs
|
<6>:<del> createdAt,
<7>:<del> updatedAt,
<9>:<del> forks(first: 10){
<10>:<del> nodes{
<11>:<del> createdAt,
<12>:<del> },
<13>:<del> },
<15>:<del> stargazers(first: 10){
<16>:<del> nodes{
<17>:<del> createdAt,
<18>:<del> },
<19>:<del> },
<20>:<del> primaryLanguage{
<21>:<del> name
<22>:<del> },
<29>:<add> color,
<38>:<add> return get_template(query, access_token)["data"]["repository"]
<del> return get_template(query, access_token)
|
# module: backend.src.external.github_api.graphql.repo
def get_repo(
access_token: str, owner: str, repo: str
) -> Union[Dict[str, Any], List[Any]]:
<0> """gets all repository data from graphql"""
<1> query = {
<2> "variables": {"owner": owner, "repo": repo},
<3> "query": """
<4> query getRepo($owner: String!, $repo: String!) {
<5> repository(owner: $owner, name: $repo) {
<6> createdAt,
<7> updatedAt,
<8> forkCount,
<9> forks(first: 10){
<10> nodes{
<11> createdAt,
<12> },
<13> },
<14> stargazerCount,
<15> stargazers(first: 10){
<16> nodes{
<17> createdAt,
<18> },
<19> },
<20> primaryLanguage{
<21> name
<22> },
<23> languages(first: 5){
<24> totalCount,
<25> totalSize,
<26> edges{
<27> node {
<28> name,
<29> },
<30> size,
<31> },
<32> },
<33> }
<34> }
<35> """,
<36> }
<37>
<38> return get_template(query, access_token)
<39>
|
===========unchanged ref 0===========
at: src.external.github_api.graphql.template
get_template(query: Dict[str, Any], access_token: str) -> Dict[str, Any]
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
+ # module: backend.src.processing.user.commit
+
+
===========changed ref 1===========
+ # module: backend.src.processing.user.commit
+ def get_all_commit_info(
+ user_id: str,
+ access_token: str,
+ name_with_owner: str,
+ start_date: datetime = datetime.now(),
+ end_date: datetime = datetime.now(),
+ ) -> List[datetime]:
+ """Gets all user's commit times for a given repository"""
+ owner, repo = name_with_owner.split("/")
+ data: List[Any] = []
+ index = 0
+ while index < 10 and len(data) == 100 * index:
+ data.extend(
+ get_repo_commits(
+ access_token=access_token,
+ owner=owner,
+ repo=repo,
+ user=user_id,
+ since=start_date,
+ until=end_date,
+ page=index + 1,
+ )
+ )
+ index += 1
+
+ data = list(
+ map(
+ lambda x: [
+ datetime.strptime(
+ x["commit"]["committer"]["date"], "%Y-%m-%dT%H:%M:%SZ"
+ ),
+ x["node_id"],
+ ],
+ data,
+ )
+ )
+
+ # sort ascending
+ data = sorted(data, key=lambda x: x[0])
+ return data
+
===========changed ref 2===========
+ # module: backend.src.processing.user.commit
+ def _get_commits_languages(
+ access_token: str, node_ids: List[str], per_page: int = NODE_CHUNK_SIZE
+ ) -> List[Dict[str, Any]]:
+ all_data: List[Dict[str, Any]] = []
+ for i in range(0, len(node_ids), per_page):
+ # TODO: alert user/display if some nodes omitted
+ # TODO: figure out why Auth error code appears
+ cutoff = min(len(node_ids), i + per_page)
+ try:
+ all_data.extend(get_commits(access_token, node_ids[i:cutoff])) # type: ignore
+ except GraphQLErrorMissingNode as e:
+ curr = node_ids[i:cutoff]
+ curr.pop(e.node)
+ all_data.extend(_get_commits_languages(access_token, curr))
+ except GraphQLErrorTimeout:
+ length = cutoff - i
+ print("Commit Timeout Exception:", length, " nodes lost")
+ all_data.extend([{} for _ in range(length)])
+ except GraphQLErrorAuth:
+ length = cutoff - i
+ print("Commit Auth Exception:", length, " nodes lost")
+ all_data.extend([{} for _ in range(length)])
+
+ return all_data
+
===========changed ref 3===========
+ # module: backend.src.processing.user.commit
+ def get_commits_languages(
+ access_token: str,
+ node_ids: List[str],
+ commit_repos: List[str],
+ repo_infos: Dict[str, Any],
+ cutoff: int = CUTOFF,
+ ):
+ all_data = _get_commits_languages(access_token, node_ids, per_page=NODE_CHUNK_SIZE)
+
+ out: List[Dict[str, Dict[str, int]]] = []
+ for commit, commit_repo in zip(all_data, commit_repos):
+ out.append({})
+ if (
+ "additions" in commit
+ and "deletions" in commit
+ and "changedFiles" in commit
+ and commit["additions"] + commit["deletions"] < cutoff
+ ):
+ repo_info = repo_infos[commit_repo]
+ languages = [x for x in repo_info if x["node"]["name"] not in BLACKLIST]
+ num_langs = min(len(languages), commit["changedFiles"])
+ total_repo_size = sum(
+ [language["size"] for language in languages[:num_langs]]
+ )
+ for language in languages[:num_langs]:
+ lang_name = language["node"]["name"]
+ lang_color = language["node"]["color"]
+ additions = round(
+ commit["additions"] * language["size"] / total_repo_size
+ )
+ deletions = round(
+ commit["deletions"] * language["size"] / total_repo_size
+ )
+ if additions > 0 or deletions > 0:
+ out[-1][lang_name] = {
+ "additions": additions,
+ "deletions": deletions,
+ "color": lang_color,
+ }
+
+ return out
+
===========changed ref 4===========
# module: backend.src.processing.user.contributions
def get_contributions(
user_id: str,
access_token: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> UserContributions:
tz = pytz.timezone(timezone_str)
# get years for contribution calendar
years = sorted(
filter(
lambda x: start_date.year <= x <= end_date.year,
get_user_contribution_years(user_id, access_token),
)
)
dates = [
[
date_to_datetime(max(date(year, 1, 1), start_date)),
date_to_datetime(
min(date(year, 12, 31), end_date), hour=23, minute=59, second=59
),
]
for year in years
]
# async get contribution calendars
calendars: List[RawCalendar] = await gather(
funcs=[get_user_contribution_calendar for _ in years],
args_dicts=[
{
"user_id": user_id,
"access_token": access_token,
"start_date": dates[i][0],
"end_date": dates[i][1],
}
for i in range(len(years))
],
)
all_events: List[t_stats] = await gather(
funcs=[get_user_all_contribution_events for _ in years],
args_dicts=[
{
"user_id": user_id,
"access_token": access_token,
"start_date": dates[i][0],
"end_date": dates[i][1],
}
for i in range(len(years))
],
)
repos_set: Set[str] = set()
for events_year in all_events:
for repo in events_year</s>
|
backend.src.packaging.user/main
|
Modified
|
avgupta456~github-trends
|
6e71b3c637b0cfbcaf32a2264edea49cfea8fe34
|
disable follows
|
<5>:<add> # follows = get_user_follows(user_id, access_token)
<del> follows = get_user_follows(user_id, access_token)
<6>:<add> return UserPackage(contribs=contribs) # , follows=follows)
<del> return UserPackage(contribs=contribs, follows=follows)
|
# module: backend.src.packaging.user
def main(
user_id: str,
access_token: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> UserPackage:
<0> """packages all processing steps for the user query"""
<1>
<2> contribs = await get_contributions(
<3> user_id, access_token, start_date, end_date, timezone_str
<4> )
<5> follows = get_user_follows(user_id, access_token)
<6> return UserPackage(contribs=contribs, follows=follows)
<7>
|
===========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
__str__ = isoformat
__radd__ = __add__
at: src.processing.user.contributions
get_contributions(user_id: str, access_token: str, start_date: date=date.today() - timedelta(365), end_date: date=date.today(), timezone_str: str="US/Eastern") -> UserContributions
|
backend.src.analytics.user.commits/get_top_repos
|
Modified
|
avgupta456~github-trends
|
4e21010317249a3eee471b83ef5231337798ebd4
|
Merge branch 'main' into top-repos
|
<3>:<add> "langs": [
<del> "languages": [
<4>:<add> {
<add> "lang": x[0],
<add> "color": x[1].color,
<add> "additions": x[1].additions,
<add> "deletions": x[1].deletions,
<add> }
<del> {"lang": x[0], "additions": x[1].additions, "deletions": x[1].deletions}
<16>:<add> repo["langs"] = [
<add> x
<add> for x in repo["langs"]
<add> if x["additions"] + x["deletions"] > 0.05 * repo["changed"]
<add> ]
<19>:<add> repos = [x for x in repos if x["changed"] > 0.05 * repos[0]["changed"]]
<add>
|
# module: backend.src.analytics.user.commits
def get_top_repos(data: UserPackage) -> List[Any]:
<0> repos: List[Any] = [
<1> {
<2> "repo": repo,
<3> "languages": [
<4> {"lang": x[0], "additions": x[1].additions, "deletions": x[1].deletions}
<5> for x in list(repo_stats.languages.items())
<6> ],
<7> "additions": sum([x.additions for x in repo_stats.languages.values()]),
<8> "deletions": sum([x.deletions for x in repo_stats.languages.values()]),
<9> }
<10> for repo, repo_stats in data.contribs.repo_stats.items()
<11> ]
<12>
<13> for repo in repos:
<14> repo["added"] = int(repo["additions"]) - int(repo["deletions"])
<15> repo["changed"] = int(repo["additions"]) + int(repo["deletions"])
<16>
<17> repos = sorted(repos, key=lambda x: x["changed"], reverse=True)
<18>
<19> return repos[:5]
<20>
|
===========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.Language
color: str
additions: int
deletions: int
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
total: List[ContributionDay]
repo_stats: Dict[str, ContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.package.UserPackage
contribs: UserContributions
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
+ # module: backend.src.svg.top_repos
+
+
===========changed ref 1===========
# module: backend.src.models.user.analytics
class RepoLanguage(BaseModel):
lang: str
+ color: str
additions: int
deletions: int
===========changed ref 2===========
# module: backend.src.models.user.analytics
class RepoStats(BaseModel):
repo: str
+ langs: List[RepoLanguage]
- languages: List[RepoLanguage]
additions: int
deletions: int
added: int
changed: int
===========changed ref 3===========
<s>
+ "/{user_id}/svg/repos", status_code=status.HTTP_200_OK, response_class=HTMLResponse
+ )
+ @svg_fail_gracefully
+ async def get_user_repo_svg(
+ response: Response,
+ user_id: str,
+ start_date: date = date.today() - timedelta(365),
+ end_date: date = date.today(),
+ timezone_str: str = "US/Eastern",
+ ) -> Any:
+ output = await _get_user(user_id, start_date, end_date, timezone_str)
+ if not validate_raw_data(output):
+ return get_loading_svg()
+ return get_top_repos_svg(output) # type: ignore
+
===========changed ref 4===========
<s>s", status_code=status.HTTP_200_OK, response_class=HTMLResponse
+ )
+ @svg_fail_gracefully
+ async def get_user_lang_svg(
+ response: Response,
+ user_id: str,
+ start_date: date = date.today() - timedelta(365),
+ end_date: date = date.today(),
+ timezone_str: str = "US/Eastern",
+ use_percent: bool = True,
+ ) -> Any:
+ output = await _get_user(user_id, start_date, end_date, timezone_str)
+ if not validate_raw_data(output):
+ return get_loading_svg()
+ return get_top_langs_svg(output, use_percent) # type: ignore
+
===========changed ref 5===========
<s>/langs", status_code=status.HTTP_200_OK, response_class=HTMLResponse
- )
- @svg_fail_gracefully
- async def get_user_svg(
- response: Response,
- user_id: str,
- start_date: date = date.today() - timedelta(365),
- end_date: date = date.today(),
- timezone_str: str = "US/Eastern",
- use_percent: bool = True,
- ) -> Any:
- output = await _get_user(user_id, start_date, end_date, timezone_str)
- if not validate_raw_data(output):
- return get_loading_svg()
- return get_top_langs_svg(output, use_percent) # type: ignore
-
===========changed ref 6===========
+ # module: backend.src.svg.top_repos
+ def format_number(num: int) -> str:
+ if num > 10000:
+ return "~" + str(int(num / 1000)) + "k lines"
+ elif num > 1000:
+ return "~" + str(int(num / 100) / 10) + "k lines"
+ elif num > 100:
+ return "~" + str(int(num / 100) * 100) + " lines"
+ else:
+ return "<100 lines"
+
===========changed ref 7===========
+ # module: backend.src.svg.top_repos
+ def get_top_repos_svg(data: RawDataModel) -> Drawing:
+ d = Drawing(size=(300, 285))
+ d.defs.add(d.style(style))
+
+ d.add(
+ d.rect(
+ size=(299, 284),
+ insert=(0.5, 0.5),
+ rx=4.5,
+ stroke="#e4e2e2",
+ fill="#fffefe",
+ )
+ )
+
+ d.add(d.text("Most Contributed Repositories", insert=(25, 35), class_="header"))
+
+ repos = Group(transform="translate(25, 55)")
+
+ if data.top_repos is None:
+ raise ValueError("No repository data available")
+ data_repos = data.top_repos
+
+ for i in range(min(5, len(data_repos))):
+ translate = "translate(0, " + str(40 * i) + ")"
+ total = data_repos[0].changed
+ repo = Group(transform=translate)
+ repo.add(d.text(data_repos[i].repo, insert=(2, 15), class_="lang-name"))
+ repo.add(
+ d.text(
+ format_number(data_repos[i].changed),
+ insert=(215, 33),
+ class_="lang-name",
+ )
+ )
+ progress = Drawing(width="205", x="0", y="25")
+ progress.add(d.rect(size=(205, 8), insert=(0, 0), rx=5, ry=5, fill="#ddd"))
+ total_percent = 0
+ for j, lang in enumerate(data_repos[i].langs):
+ percent, color = 100 * (lang.additions + lang.deletions) / total, lang.color
+ box_size, box_insert = (2.05 * percent,</s>
===========changed ref 8===========
+ # module: backend.src.svg.top_repos
+ def get_top_repos_svg(data: RawDataModel) -> Drawing:
# offset: 1
<s> + lang.deletions) / total, lang.color
+ box_size, box_insert = (2.05 * percent, 8), (2.05 * total_percent, 0)
+ progress.add(
+ d.rect(size=box_size, insert=box_insert, rx=5, ry=5, fill=color)
+ )
+
+ box_left, box_right = j > 0, j < len(data_repos[i].langs) - 1
+ box_size = 2.05 * percent - (0 if box_left else 5) - (0 if box_right else 5)
+ box_insert = 2.05 * total_percent + (5 if not box_left else 0)
+ progress.add(
+ d.rect(size=(max(box_size, 3), 8), insert=(box_insert, 0), fill=color)
+ )
+
+ total_percent += percent
+
+ repo.add(progress)
+ repos.add(repo)
+ d.add(repos)
+
+ return d
+
|
backend.src.routers.pubsub/pub_user
|
Modified
|
avgupta456~github-trends
|
2a1966d4f8ae21a74c3b172ef3c4e6adb80c4082
|
store raw_data, not analytics
|
<0>:<del> publish_to_topic(
<1>:<del> "user",
<2>:<del> {
<3>:<del> "user_id": user_id,
<4>:<del> "access_token": access_token,
<5>:<del> "start_date": str(date.today() - timedelta(365)),
<6>:<del> "end_date": str(date.today()),
<7>:<del> "timezone_str": "US/Eastern",
<8>:<del> },
<9>:<del> )
<10>:<add> publish_to_topic("user", {"user_id": user_id, "access_token": access_token})
|
# module: backend.src.routers.pubsub
@router.get("/pub/user/{user_id}/{access_token}", status_code=status.HTTP_200_OK)
@fail_gracefully
def pub_user(response: Response, user_id: str, access_token: str) -> str:
<0> publish_to_topic(
<1> "user",
<2> {
<3> "user_id": user_id,
<4> "access_token": access_token,
<5> "start_date": str(date.today() - timedelta(365)),
<6> "end_date": str(date.today()),
<7> "timezone_str": "US/Eastern",
<8> },
<9> )
<10>
<11> return user_id
<12>
|
===========unchanged ref 0===========
at: backend.src.routers.pubsub
router = APIRouter()
at: src.db.functions.users
lock_user(user_id: str) -> None
at: src.external.pubsub.templates
publish_to_topic(topic: str, message: Dict[str, Any]) -> None
parse_request(token: str, request: Request) -> Dict[str, Any]
at: src.utils
fail_gracefully(func: Callable[..., Any])
pubsub_fail_gracefully(func: Callable[..., Any])
at: typing
Dict = _alias(dict, 2, inst=False, name='Dict')
|
backend.src.routers.pubsub/sub_user
|
Modified
|
avgupta456~github-trends
|
2a1966d4f8ae21a74c3b172ef3c4e6adb80c4082
|
store raw_data, not analytics
|
<4>:<add> # standard policy is to check past five years of data
<add> start_date = date.today() - timedelta(365 * 5)
<add> end_date = date.today()
<add> timezone_str = "US/Eastern"
<add>
<add> # TODO: historical data is never updated,
<add> # don't query full five years each time, instead
<add> # define function to build on previous results
<add>
<add> output = await get_data(
<del> output = await analytics_get_user(
<7>:<add> start_date,
<add> end_date,
<del> datetime.strptime(data["start_date"], "%Y-%m-%d").date(),
<8>:<del> datetime.strptime(data["end_date"], "%Y-%m-%d").date(),
<9>:<add> timezone_str,
<del> data["timezone_str"],
<12>:<add> await update_user(data["user_id"], output.dict())
<del> await update_user(data["user_id"], output)
<16>:<add> return data
<del> return output
|
# module: backend.src.routers.pubsub
@router.post("/sub/user/{token}", status_code=status.HTTP_200_OK)
@pubsub_fail_gracefully
async def sub_user(response: Response, token: str, request: Request) -> Any:
<0> data: Dict[str, Any] = await parse_request(token, request)
<1>
<2> await lock_user(data["user_id"])
<3>
<4> output = await analytics_get_user(
<5> data["user_id"],
<6> data["access_token"],
<7> datetime.strptime(data["start_date"], "%Y-%m-%d").date(),
<8> datetime.strptime(data["end_date"], "%Y-%m-%d").date(),
<9> data["timezone_str"],
<10> )
<11>
<12> await update_user(data["user_id"], output)
<13>
<14> await unlock_user(data["user_id"])
<15>
<16> return output
<17>
|
===========unchanged ref 0===========
at: backend.src.routers.pubsub.sub_user
data: Dict[str, Any] = await parse_request(token, request)
start_date = date.today() - timedelta(365 * 5)
at: datetime
date()
at: datetime.date
__slots__ = '_year', '_month', '_day', '_hashcode'
today() -> _S
__str__ = isoformat
__radd__ = __add__
at: src.db.functions.users
unlock_user(user_id: str) -> None
update_user(user_id: str, raw_data: Optional[Dict[str, Any]]=None) -> None
at: src.packaging.user
main(user_id: str, access_token: str, start_date: date=date.today() - timedelta(365), end_date: date=date.today(), timezone_str: str="US/Eastern") -> UserPackage
===========changed ref 0===========
# module: backend.src.routers.pubsub
@router.get("/pub/user/{user_id}/{access_token}", status_code=status.HTTP_200_OK)
@fail_gracefully
def pub_user(response: Response, user_id: str, access_token: str) -> str:
- publish_to_topic(
- "user",
- {
- "user_id": user_id,
- "access_token": access_token,
- "start_date": str(date.today() - timedelta(365)),
- "end_date": str(date.today()),
- "timezone_str": "US/Eastern",
- },
- )
+ publish_to_topic("user", {"user_id": user_id, "access_token": access_token})
return user_id
|
backend.src.analytics.user.commits/get_top_languages
|
Modified
|
avgupta456~github-trends
|
2a1966d4f8ae21a74c3b172ef3c4e6adb80c4082
|
store raw_data, not analytics
|
<37>:<add> new_languages_list: List[LanguageStats] = []
<del> new_languages_list: List[dict_type] = []
|
# module: backend.src.analytics.user.commits
+ def get_top_languages(data: UserPackage) -> List[LanguageStats]:
- def get_top_languages(data: UserPackage) -> List[dict_type]:
<0> raw_languages = data.contribs.total_stats.languages
<1> languages_list: List[dict_type] = [
<2> {
<3> "lang": lang,
<4> "color": stats.color,
<5> "additions": stats.additions,
<6> "deletions": stats.deletions,
<7> }
<8> for lang, stats in raw_languages.items()
<9> ]
<10>
<11> total_additions = sum([int(lang["additions"]) for lang in languages_list])
<12> total_deletions = sum([int(lang["deletions"]) for lang in languages_list])
<13> total_changed = total_additions + total_deletions + 1 # avoids division by zero
<14> total: dict_type = {
<15> "lang": "Total",
<16> "additions": total_additions,
<17> "deletions": total_deletions,
<18> }
<19>
<20> languages_list = sorted(
<21> languages_list,
<22> key=lambda x: int(x["additions"]) + int(x["deletions"]),
<23> reverse=True,
<24> )
<25> other: dict_type = {
<26> "lang": "Other",
<27> "additions": 0,
<28> "deletions": 0,
<29> "color": "#ededed",
<30> }
<31> for language in languages_list[4:]:
<32> other["additions"] = int(other["additions"]) + int(language["additions"])
<33> other["deletions"] = int(other["deletions"]) + int(language["deletions"])
<34>
<35> languages_list = [total] + languages_list[:4] + [other]
<36>
<37> new_languages_list: List[dict_type] = []
<38> for lang in languages_list:
<39> lang["added"] = int(lang["</s>
|
===========below chunk 0===========
# module: backend.src.analytics.user.commits
+ def get_top_languages(data: UserPackage) -> List[LanguageStats]:
- def get_top_languages(data: UserPackage) -> List[dict_type]:
# offset: 1
lang["changed"] = int(lang["additions"]) + int(lang["deletions"])
lang["percent"] = float(round(100 * lang["changed"] / total_changed, 2))
if lang["percent"] > 0:
new_languages_list.append(lang)
return new_languages_list
===========unchanged ref 0===========
at: backend.src.analytics.user.commits
dict_type = Dict[str, Union[str, int, float]]
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: str
additions: int
deletions: int
at: src.models.user.contribs.UserContributions
total_stats: ContributionStats
total: List[ContributionDay]
repo_stats: Dict[str, ContributionStats]
repos: Dict[str, List[ContributionDay]]
at: src.models.user.package.UserPackage
contribs: UserContributions
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.routers.pubsub
@router.get("/pub/user/{user_id}/{access_token}", status_code=status.HTTP_200_OK)
@fail_gracefully
def pub_user(response: Response, user_id: str, access_token: str) -> str:
- publish_to_topic(
- "user",
- {
- "user_id": user_id,
- "access_token": access_token,
- "start_date": str(date.today() - timedelta(365)),
- "end_date": str(date.today()),
- "timezone_str": "US/Eastern",
- },
- )
+ publish_to_topic("user", {"user_id": user_id, "access_token": access_token})
return user_id
===========changed ref 1===========
# module: backend.src.routers.pubsub
@router.post("/sub/user/{token}", status_code=status.HTTP_200_OK)
@pubsub_fail_gracefully
async def sub_user(response: Response, token: str, request: Request) -> Any:
data: Dict[str, Any] = await parse_request(token, request)
await lock_user(data["user_id"])
+ # standard policy is to check past five years of data
+ start_date = date.today() - timedelta(365 * 5)
+ end_date = date.today()
+ timezone_str = "US/Eastern"
+
+ # TODO: historical data is never updated,
+ # don't query full five years each time, instead
+ # define function to build on previous results
+
+ output = await get_data(
- output = await analytics_get_user(
data["user_id"],
data["access_token"],
+ start_date,
+ end_date,
- datetime.strptime(data["start_date"], "%Y-%m-%d").date(),
- datetime.strptime(data["end_date"], "%Y-%m-%d").date(),
+ timezone_str,
- data["timezone_str"],
)
+ await update_user(data["user_id"], output.dict())
- await update_user(data["user_id"], output)
await unlock_user(data["user_id"])
+ return data
- return output
|
backend.src.analytics.user.commits/get_top_repos
|
Modified
|
avgupta456~github-trends
|
2a1966d4f8ae21a74c3b172ef3c4e6adb80c4082
|
store raw_data, not analytics
|
<29>:<add> new_repos = [
<add> RepoStats.parse_obj(x)
<add> for x in repos
<add> if x["changed"] > 0.05 * repos[0]["changed"]
<del> repos = [x for x in repos if x["changed"] > 0.05 * repos[0]["changed"]]
<30>:<add> ]
<31>:<add> return new_repos[:5]
<del> return repos[:5]
|
# module: backend.src.analytics.user.commits
+ def get_top_repos(data: UserPackage) -> List[RepoStats]:
- def get_top_repos(data: UserPackage) -> List[Any]:
<0> repos: List[Any] = [
<1> {
<2> "repo": repo,
<3> "langs": [
<4> {
<5> "lang": x[0],
<6> "color": x[1].color,
<7> "additions": x[1].additions,
<8> "deletions": x[1].deletions,
<9> }
<10> for x in list(repo_stats.languages.items())
<11> ],
<12> "additions": sum([x.additions for x in repo_stats.languages.values()]),
<13> "deletions": sum([x.deletions for x in repo_stats.languages.values()]),
<14> }
<15> for repo, repo_stats in data.contribs.repo_stats.items()
<16> ]
<17>
<18> for repo in repos:
<19> repo["added"] = int(repo["additions"]) - int(repo["deletions"])
<20> repo["changed"] = int(repo["additions"]) + int(repo["deletions"])
<21> repo["langs"] = [
<22> x
<23> for x in repo["langs"]
<24> if x["additions"] + x["deletions"] > 0.05 * repo["changed"]
<25> ]
<26>
<27> repos = sorted(repos, key=lambda x: x["changed"], reverse=True)
<28>
<29> repos = [x for x in repos if x["changed"] > 0.05 * repos[0]["changed"]]
<30>
<31> return repos[:5]
<32>
|
===========unchanged ref 0===========
at: src.models.user.contribs.ContributionStats
languages: Dict[str, Language]
at: src.models.user.contribs.Language
color: str
additions: int
deletions: int
at: src.models.user.contribs.UserContributions
repo_stats: Dict[str, ContributionStats]
at: src.models.user.package.UserPackage
contribs: UserContributions
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: backend.src.analytics.user.commits
+ def get_top_languages(data: UserPackage) -> List[LanguageStats]:
- def get_top_languages(data: UserPackage) -> List[dict_type]:
raw_languages = data.contribs.total_stats.languages
languages_list: List[dict_type] = [
{
"lang": lang,
"color": stats.color,
"additions": stats.additions,
"deletions": stats.deletions,
}
for lang, stats in raw_languages.items()
]
total_additions = sum([int(lang["additions"]) for lang in languages_list])
total_deletions = sum([int(lang["deletions"]) for lang in languages_list])
total_changed = total_additions + total_deletions + 1 # avoids division by zero
total: dict_type = {
"lang": "Total",
"additions": total_additions,
"deletions": total_deletions,
}
languages_list = sorted(
languages_list,
key=lambda x: int(x["additions"]) + int(x["deletions"]),
reverse=True,
)
other: dict_type = {
"lang": "Other",
"additions": 0,
"deletions": 0,
"color": "#ededed",
}
for language in languages_list[4:]:
other["additions"] = int(other["additions"]) + int(language["additions"])
other["deletions"] = int(other["deletions"]) + int(language["deletions"])
languages_list = [total] + languages_list[:4] + [other]
+ new_languages_list: List[LanguageStats] = []
- new_languages_list: List[dict_type] = []
for lang in languages_list:
lang["added"] = int(lang["additions"]) - int(lang["deletions"])
lang["changed"] = int(lang</s>
===========changed ref 1===========
# module: backend.src.analytics.user.commits
+ def get_top_languages(data: UserPackage) -> List[LanguageStats]:
- def get_top_languages(data: UserPackage) -> List[dict_type]:
# offset: 1
<s>added"] = int(lang["additions"]) - int(lang["deletions"])
lang["changed"] = int(lang["additions"]) + int(lang["deletions"])
lang["percent"] = float(round(100 * lang["changed"] / total_changed, 2))
if lang["percent"] > 0:
+ new_languages_list.append(LanguageStats.parse_obj(lang))
- new_languages_list.append(lang)
return new_languages_list
===========changed ref 2===========
# module: backend.src.routers.pubsub
@router.get("/pub/user/{user_id}/{access_token}", status_code=status.HTTP_200_OK)
@fail_gracefully
def pub_user(response: Response, user_id: str, access_token: str) -> str:
- publish_to_topic(
- "user",
- {
- "user_id": user_id,
- "access_token": access_token,
- "start_date": str(date.today() - timedelta(365)),
- "end_date": str(date.today()),
- "timezone_str": "US/Eastern",
- },
- )
+ publish_to_topic("user", {"user_id": user_id, "access_token": access_token})
return user_id
===========changed ref 3===========
# module: backend.src.routers.pubsub
@router.post("/sub/user/{token}", status_code=status.HTTP_200_OK)
@pubsub_fail_gracefully
async def sub_user(response: Response, token: str, request: Request) -> Any:
data: Dict[str, Any] = await parse_request(token, request)
await lock_user(data["user_id"])
+ # standard policy is to check past five years of data
+ start_date = date.today() - timedelta(365 * 5)
+ end_date = date.today()
+ timezone_str = "US/Eastern"
+
+ # TODO: historical data is never updated,
+ # don't query full five years each time, instead
+ # define function to build on previous results
+
+ output = await get_data(
- output = await analytics_get_user(
data["user_id"],
data["access_token"],
+ start_date,
+ end_date,
- datetime.strptime(data["start_date"], "%Y-%m-%d").date(),
- datetime.strptime(data["end_date"], "%Y-%m-%d").date(),
+ timezone_str,
- data["timezone_str"],
)
+ await update_user(data["user_id"], output.dict())
- await update_user(data["user_id"], output)
await unlock_user(data["user_id"])
+ return data
- return output
|
backend.src.routers.users/validate_raw_data
|
Modified
|
avgupta456~github-trends
|
2a1966d4f8ae21a74c3b172ef3c4e6adb80c4082
|
store raw_data, not analytics
|
<1>:<add> return data is not None and data.contribs is not None
<del> return data is not None and data.top_languages is not None
|
# module: backend.src.routers.users
+ def validate_raw_data(data: Optional[UserPackage]) -> bool:
- def validate_raw_data(data: Optional[RawDataModel]) -> bool:
<0> # NOTE: add more validation as more fields are required
<1> return data is not None and data.top_languages is not None
<2>
|
===========unchanged ref 0===========
at: src.models.user.package.UserPackage
contribs: UserContributions
===========changed ref 0===========
# module: backend.src.models.user.analytics
- class RawDataModel(BaseModel):
- top_languages: Optional[List[LanguageStats]]
- top_repos: Optional[List[RepoStats]]
-
===========changed ref 1===========
# module: backend.src.routers.pubsub
@router.get("/pub/user/{user_id}/{access_token}", status_code=status.HTTP_200_OK)
@fail_gracefully
def pub_user(response: Response, user_id: str, access_token: str) -> str:
- publish_to_topic(
- "user",
- {
- "user_id": user_id,
- "access_token": access_token,
- "start_date": str(date.today() - timedelta(365)),
- "end_date": str(date.today()),
- "timezone_str": "US/Eastern",
- },
- )
+ publish_to_topic("user", {"user_id": user_id, "access_token": access_token})
return user_id
===========changed ref 2===========
# module: backend.src.routers.pubsub
@router.post("/sub/user/{token}", status_code=status.HTTP_200_OK)
@pubsub_fail_gracefully
async def sub_user(response: Response, token: str, request: Request) -> Any:
data: Dict[str, Any] = await parse_request(token, request)
await lock_user(data["user_id"])
+ # standard policy is to check past five years of data
+ start_date = date.today() - timedelta(365 * 5)
+ end_date = date.today()
+ timezone_str = "US/Eastern"
+
+ # TODO: historical data is never updated,
+ # don't query full five years each time, instead
+ # define function to build on previous results
+
+ output = await get_data(
- output = await analytics_get_user(
data["user_id"],
data["access_token"],
+ start_date,
+ end_date,
- datetime.strptime(data["start_date"], "%Y-%m-%d").date(),
- datetime.strptime(data["end_date"], "%Y-%m-%d").date(),
+ timezone_str,
- data["timezone_str"],
)
+ await update_user(data["user_id"], output.dict())
- await update_user(data["user_id"], output)
await unlock_user(data["user_id"])
+ return data
- return output
===========changed ref 3===========
# module: backend.src.analytics.user.commits
+ def get_top_repos(data: UserPackage) -> List[RepoStats]:
- def get_top_repos(data: UserPackage) -> List[Any]:
repos: List[Any] = [
{
"repo": repo,
"langs": [
{
"lang": x[0],
"color": x[1].color,
"additions": x[1].additions,
"deletions": x[1].deletions,
}
for x in list(repo_stats.languages.items())
],
"additions": sum([x.additions for x in repo_stats.languages.values()]),
"deletions": sum([x.deletions for x in repo_stats.languages.values()]),
}
for repo, repo_stats in data.contribs.repo_stats.items()
]
for repo in repos:
repo["added"] = int(repo["additions"]) - int(repo["deletions"])
repo["changed"] = int(repo["additions"]) + int(repo["deletions"])
repo["langs"] = [
x
for x in repo["langs"]
if x["additions"] + x["deletions"] > 0.05 * repo["changed"]
]
repos = sorted(repos, key=lambda x: x["changed"], reverse=True)
+ new_repos = [
+ RepoStats.parse_obj(x)
+ for x in repos
+ if x["changed"] > 0.05 * repos[0]["changed"]
- repos = [x for x in repos if x["changed"] > 0.05 * repos[0]["changed"]]
+ ]
+ return new_repos[:5]
- return repos[:5]
===========changed ref 4===========
# module: backend.src.analytics.user.commits
+ def get_top_languages(data: UserPackage) -> List[LanguageStats]:
- def get_top_languages(data: UserPackage) -> List[dict_type]:
raw_languages = data.contribs.total_stats.languages
languages_list: List[dict_type] = [
{
"lang": lang,
"color": stats.color,
"additions": stats.additions,
"deletions": stats.deletions,
}
for lang, stats in raw_languages.items()
]
total_additions = sum([int(lang["additions"]) for lang in languages_list])
total_deletions = sum([int(lang["deletions"]) for lang in languages_list])
total_changed = total_additions + total_deletions + 1 # avoids division by zero
total: dict_type = {
"lang": "Total",
"additions": total_additions,
"deletions": total_deletions,
}
languages_list = sorted(
languages_list,
key=lambda x: int(x["additions"]) + int(x["deletions"]),
reverse=True,
)
other: dict_type = {
"lang": "Other",
"additions": 0,
"deletions": 0,
"color": "#ededed",
}
for language in languages_list[4:]:
other["additions"] = int(other["additions"]) + int(language["additions"])
other["deletions"] = int(other["deletions"]) + int(language["deletions"])
languages_list = [total] + languages_list[:4] + [other]
+ new_languages_list: List[LanguageStats] = []
- new_languages_list: List[dict_type] = []
for lang in languages_list:
lang["added"] = int(lang["additions"]) - int(lang["deletions"])
lang["changed"] = int(lang</s>
===========changed ref 5===========
# module: backend.src.analytics.user.commits
+ def get_top_languages(data: UserPackage) -> List[LanguageStats]:
- def get_top_languages(data: UserPackage) -> List[dict_type]:
# offset: 1
<s>added"] = int(lang["additions"]) - int(lang["deletions"])
lang["changed"] = int(lang["additions"]) + int(lang["deletions"])
lang["percent"] = float(round(100 * lang["changed"] / total_changed, 2))
if lang["percent"] > 0:
+ new_languages_list.append(LanguageStats.parse_obj(lang))
- new_languages_list.append(lang)
return new_languages_list
|
backend.src.routers.users/_get_user
|
Modified
|
avgupta456~github-trends
|
2a1966d4f8ae21a74c3b172ef3c4e6adb80c4082
|
store raw_data, not analytics
|
<11>:<del> "user",
<12>:<del> {
<13>:<del> "user_id": user_id,
<14>:<add> "user", {"user_id": user_id, "access_token": db_user.access_token}
<del> "access_token": db_user.access_token,
<15>:<del> "start_date": str(start_date),
<16>:<del> "end_date": str(end_date),
<17>:<del> "timezone_str": timezone_str,
<18>:<del> },
|
# module: backend.src.routers.users
- def _get_user(
- user_id: str,
- start_date: date = date.today() - timedelta(365),
- end_date: date = date.today(),
- timezone_str: str = "US/Eastern",
- ) -> Optional[RawDataModel]:
+ @alru_cache()
+ async def _get_user(user_id: str) -> Optional[UserPackage]:
<0> if not PUBSUB_PUB:
<1> raise HTTPException(400, "")
<2>
<3> db_user = await get_user_by_user_id(user_id)
<4> if db_user is None or db_user.access_token == "":
<5> raise LookupError("Invalid UserId")
<6>
<7> time_diff = datetime.now() - db_user.last_updated
<8> if time_diff > timedelta(hours=6) or not validate_raw_data(db_user.raw_data):
<9> if not db_user.lock:
<10> publish_to_topic(
<11> "user",
<12> {
<13> "user_id": user_id,
<14> "access_token": db_user.access_token,
<15> "start_date": str(start_date),
<16> "end_date": str(end_date),
<17> "timezone_str": timezone_str,
<18> },
<19> )
<20>
<21> if validate_raw_data(db_user.raw_data):
<22> return db_user.raw_data # type: ignore
<23>
<24> return None
<25>
|
===========unchanged ref 0===========
at: backend.src.routers.users
router = APIRouter()
validate_raw_data(data: Optional[UserPackage]) -> bool
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: src.constants
PUBSUB_PUB = os.getenv("PUBSUB_PUB", "False") == "True"
at: src.db.functions.get
get_user_by_user_id(user_id: str) -> Optional[UserModel]
at: src.db.models.users.UserModel
user_id: str
access_token: str
last_updated: datetime
raw_data: Optional[UserPackage]
lock: bool
at: src.external.pubsub.templates
publish_to_topic(topic: str, message: Dict[str, Any]) -> None
at: src.utils
async_fail_gracefully(func: Callable[..., Any])
alru_cache(max_size: int=128, ttl: timedelta=timedelta(hours=1))
===========changed ref 0===========
# module: backend.src.routers.users
+ def validate_raw_data(data: Optional[UserPackage]) -> bool:
- def validate_raw_data(data: Optional[RawDataModel]) -> bool:
# NOTE: add more validation as more fields are required
+ return data is not None and data.contribs is not None
- return data is not None and data.top_languages is not None
===========changed ref 1===========
# module: backend.src.models.user.analytics
- class RawDataModel(BaseModel):
- top_languages: Optional[List[LanguageStats]]
- top_repos: Optional[List[RepoStats]]
-
===========changed ref 2===========
# module: backend.src.routers.pubsub
@router.get("/pub/user/{user_id}/{access_token}", status_code=status.HTTP_200_OK)
@fail_gracefully
def pub_user(response: Response, user_id: str, access_token: str) -> str:
- publish_to_topic(
- "user",
- {
- "user_id": user_id,
- "access_token": access_token,
- "start_date": str(date.today() - timedelta(365)),
- "end_date": str(date.today()),
- "timezone_str": "US/Eastern",
- },
- )
+ publish_to_topic("user", {"user_id": user_id, "access_token": access_token})
return user_id
===========changed ref 3===========
# module: backend.src.routers.pubsub
@router.post("/sub/user/{token}", status_code=status.HTTP_200_OK)
@pubsub_fail_gracefully
async def sub_user(response: Response, token: str, request: Request) -> Any:
data: Dict[str, Any] = await parse_request(token, request)
await lock_user(data["user_id"])
+ # standard policy is to check past five years of data
+ start_date = date.today() - timedelta(365 * 5)
+ end_date = date.today()
+ timezone_str = "US/Eastern"
+
+ # TODO: historical data is never updated,
+ # don't query full five years each time, instead
+ # define function to build on previous results
+
+ output = await get_data(
- output = await analytics_get_user(
data["user_id"],
data["access_token"],
+ start_date,
+ end_date,
- datetime.strptime(data["start_date"], "%Y-%m-%d").date(),
- datetime.strptime(data["end_date"], "%Y-%m-%d").date(),
+ timezone_str,
- data["timezone_str"],
)
+ await update_user(data["user_id"], output.dict())
- await update_user(data["user_id"], output)
await unlock_user(data["user_id"])
+ return data
- return output
===========changed ref 4===========
# module: backend.src.analytics.user.commits
+ def get_top_repos(data: UserPackage) -> List[RepoStats]:
- def get_top_repos(data: UserPackage) -> List[Any]:
repos: List[Any] = [
{
"repo": repo,
"langs": [
{
"lang": x[0],
"color": x[1].color,
"additions": x[1].additions,
"deletions": x[1].deletions,
}
for x in list(repo_stats.languages.items())
],
"additions": sum([x.additions for x in repo_stats.languages.values()]),
"deletions": sum([x.deletions for x in repo_stats.languages.values()]),
}
for repo, repo_stats in data.contribs.repo_stats.items()
]
for repo in repos:
repo["added"] = int(repo["additions"]) - int(repo["deletions"])
repo["changed"] = int(repo["additions"]) + int(repo["deletions"])
repo["langs"] = [
x
for x in repo["langs"]
if x["additions"] + x["deletions"] > 0.05 * repo["changed"]
]
repos = sorted(repos, key=lambda x: x["changed"], reverse=True)
+ new_repos = [
+ RepoStats.parse_obj(x)
+ for x in repos
+ if x["changed"] > 0.05 * repos[0]["changed"]
- repos = [x for x in repos if x["changed"] > 0.05 * repos[0]["changed"]]
+ ]
+ return new_repos[:5]
- return repos[:5]
|
backend.src.routers.users/get_user
|
Modified
|
avgupta456~github-trends
|
2a1966d4f8ae21a74c3b172ef3c4e6adb80c4082
|
store raw_data, not analytics
|
<0>:<add> return await _get_user(user_id)
<del> return await _get_user(user_id, start_date, end_date, timezone_str)
|
<s> status_code=status.HTTP_200_OK)
@async_fail_gracefully
- async def get_user(
- response: Response,
- user_id: str,
- start_date: date = date.today() - timedelta(365),
- end_date: date = date.today(),
- timezone_str: str = "US/Eastern",
- ) -> Optional[RawDataModel]:
+ async def get_user(response: Response, user_id: str) -> Optional[UserPackage]:
<0> return await _get_user(user_id, start_date, end_date, timezone_str)
<1>
|
===========unchanged ref 0===========
at: backend.src.routers.users
validate_raw_data(data: Optional[UserPackage]) -> bool
Callable(*args: List[Any], **kwargs: Dict[str, Any]) -> Any
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.svg.error
get_loading_svg() -> Drawing
===========changed ref 0===========
# module: backend.src.routers.users
+ def validate_raw_data(data: Optional[UserPackage]) -> bool:
- def validate_raw_data(data: Optional[RawDataModel]) -> bool:
# NOTE: add more validation as more fields are required
+ return data is not None and data.contribs is not None
- return data is not None and data.top_languages is not None
===========changed ref 1===========
# module: backend.src.routers.users
- def _get_user(
- user_id: str,
- start_date: date = date.today() - timedelta(365),
- end_date: date = date.today(),
- timezone_str: str = "US/Eastern",
- ) -> Optional[RawDataModel]:
+ @alru_cache()
+ async def _get_user(user_id: str) -> Optional[UserPackage]:
if not PUBSUB_PUB:
raise HTTPException(400, "")
db_user = await get_user_by_user_id(user_id)
if db_user is None or db_user.access_token == "":
raise LookupError("Invalid UserId")
time_diff = datetime.now() - db_user.last_updated
if time_diff > timedelta(hours=6) or not validate_raw_data(db_user.raw_data):
if not db_user.lock:
publish_to_topic(
- "user",
- {
- "user_id": user_id,
+ "user", {"user_id": user_id, "access_token": db_user.access_token}
- "access_token": db_user.access_token,
- "start_date": str(start_date),
- "end_date": str(end_date),
- "timezone_str": timezone_str,
- },
)
if validate_raw_data(db_user.raw_data):
return db_user.raw_data # type: ignore
return None
===========changed ref 2===========
# module: backend.src.models.user.analytics
- class RawDataModel(BaseModel):
- top_languages: Optional[List[LanguageStats]]
- top_repos: Optional[List[RepoStats]]
-
===========changed ref 3===========
# module: backend.src.routers.pubsub
@router.get("/pub/user/{user_id}/{access_token}", status_code=status.HTTP_200_OK)
@fail_gracefully
def pub_user(response: Response, user_id: str, access_token: str) -> str:
- publish_to_topic(
- "user",
- {
- "user_id": user_id,
- "access_token": access_token,
- "start_date": str(date.today() - timedelta(365)),
- "end_date": str(date.today()),
- "timezone_str": "US/Eastern",
- },
- )
+ publish_to_topic("user", {"user_id": user_id, "access_token": access_token})
return user_id
===========changed ref 4===========
# module: backend.src.routers.pubsub
@router.post("/sub/user/{token}", status_code=status.HTTP_200_OK)
@pubsub_fail_gracefully
async def sub_user(response: Response, token: str, request: Request) -> Any:
data: Dict[str, Any] = await parse_request(token, request)
await lock_user(data["user_id"])
+ # standard policy is to check past five years of data
+ start_date = date.today() - timedelta(365 * 5)
+ end_date = date.today()
+ timezone_str = "US/Eastern"
+
+ # TODO: historical data is never updated,
+ # don't query full five years each time, instead
+ # define function to build on previous results
+
+ output = await get_data(
- output = await analytics_get_user(
data["user_id"],
data["access_token"],
+ start_date,
+ end_date,
- datetime.strptime(data["start_date"], "%Y-%m-%d").date(),
- datetime.strptime(data["end_date"], "%Y-%m-%d").date(),
+ timezone_str,
- data["timezone_str"],
)
+ await update_user(data["user_id"], output.dict())
- await update_user(data["user_id"], output)
await unlock_user(data["user_id"])
+ return data
- return output
===========changed ref 5===========
# module: backend.src.analytics.user.commits
+ def get_top_repos(data: UserPackage) -> List[RepoStats]:
- def get_top_repos(data: UserPackage) -> List[Any]:
repos: List[Any] = [
{
"repo": repo,
"langs": [
{
"lang": x[0],
"color": x[1].color,
"additions": x[1].additions,
"deletions": x[1].deletions,
}
for x in list(repo_stats.languages.items())
],
"additions": sum([x.additions for x in repo_stats.languages.values()]),
"deletions": sum([x.deletions for x in repo_stats.languages.values()]),
}
for repo, repo_stats in data.contribs.repo_stats.items()
]
for repo in repos:
repo["added"] = int(repo["additions"]) - int(repo["deletions"])
repo["changed"] = int(repo["additions"]) + int(repo["deletions"])
repo["langs"] = [
x
for x in repo["langs"]
if x["additions"] + x["deletions"] > 0.05 * repo["changed"]
]
repos = sorted(repos, key=lambda x: x["changed"], reverse=True)
+ new_repos = [
+ RepoStats.parse_obj(x)
+ for x in repos
+ if x["changed"] > 0.05 * repos[0]["changed"]
- repos = [x for x in repos if x["changed"] > 0.05 * repos[0]["changed"]]
+ ]
+ return new_repos[:5]
- return repos[:5]
|
backend.src.routers.users/get_user_lang_svg
|
Modified
|
avgupta456~github-trends
|
2a1966d4f8ae21a74c3b172ef3c4e6adb80c4082
|
store raw_data, not analytics
|
<0>:<add> output = await _get_user(user_id)
<del> output = await _get_user(user_id, start_date, end_date, timezone_str)
|
<s> "/{user_id}/svg/langs", status_code=status.HTTP_200_OK, response_class=HTMLResponse
)
@svg_fail_gracefully
async def get_user_lang_svg(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
use_percent: bool = True,
) -> Any:
<0> output = await _get_user(user_id, start_date, end_date, timezone_str)
<1> if not validate_raw_data(output):
<2> return get_loading_svg()
<3> return get_top_langs_svg(output, use_percent) # type: ignore
<4>
|
===========unchanged ref 0===========
at: backend.src.routers.users
router = APIRouter()
validate_raw_data(data: Optional[UserPackage]) -> bool
Callable(*args: List[Any], **kwargs: Dict[str, Any]) -> Any
at: datetime
timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...)
date()
at: datetime.date
today() -> _S
at: src.svg.error
get_loading_svg() -> Drawing
at: src.svg.top_repos
get_top_repos_svg(data: Any) -> Drawing
at: src.utils
svg_fail_gracefully(func: Callable[..., Any])
===========changed ref 0===========
# module: backend.src.routers.users
+ def validate_raw_data(data: Optional[UserPackage]) -> bool:
- def validate_raw_data(data: Optional[RawDataModel]) -> bool:
# NOTE: add more validation as more fields are required
+ return data is not None and data.contribs is not None
- return data is not None and data.top_languages is not None
===========changed ref 1===========
# module: backend.src.routers.users
- def _get_user(
- user_id: str,
- start_date: date = date.today() - timedelta(365),
- end_date: date = date.today(),
- timezone_str: str = "US/Eastern",
- ) -> Optional[RawDataModel]:
+ @alru_cache()
+ async def _get_user(user_id: str) -> Optional[UserPackage]:
if not PUBSUB_PUB:
raise HTTPException(400, "")
db_user = await get_user_by_user_id(user_id)
if db_user is None or db_user.access_token == "":
raise LookupError("Invalid UserId")
time_diff = datetime.now() - db_user.last_updated
if time_diff > timedelta(hours=6) or not validate_raw_data(db_user.raw_data):
if not db_user.lock:
publish_to_topic(
- "user",
- {
- "user_id": user_id,
+ "user", {"user_id": user_id, "access_token": db_user.access_token}
- "access_token": db_user.access_token,
- "start_date": str(start_date),
- "end_date": str(end_date),
- "timezone_str": timezone_str,
- },
)
if validate_raw_data(db_user.raw_data):
return db_user.raw_data # type: ignore
return None
===========changed ref 2===========
<s> status_code=status.HTTP_200_OK)
@async_fail_gracefully
- async def get_user(
- response: Response,
- user_id: str,
- start_date: date = date.today() - timedelta(365),
- end_date: date = date.today(),
- timezone_str: str = "US/Eastern",
- ) -> Optional[RawDataModel]:
+ async def get_user(response: Response, user_id: str) -> Optional[UserPackage]:
+ return await _get_user(user_id)
- return await _get_user(user_id, start_date, end_date, timezone_str)
===========changed ref 3===========
# module: backend.src.models.user.analytics
- class RawDataModel(BaseModel):
- top_languages: Optional[List[LanguageStats]]
- top_repos: Optional[List[RepoStats]]
-
===========changed ref 4===========
# module: backend.src.routers.pubsub
@router.get("/pub/user/{user_id}/{access_token}", status_code=status.HTTP_200_OK)
@fail_gracefully
def pub_user(response: Response, user_id: str, access_token: str) -> str:
- publish_to_topic(
- "user",
- {
- "user_id": user_id,
- "access_token": access_token,
- "start_date": str(date.today() - timedelta(365)),
- "end_date": str(date.today()),
- "timezone_str": "US/Eastern",
- },
- )
+ publish_to_topic("user", {"user_id": user_id, "access_token": access_token})
return user_id
===========changed ref 5===========
# module: backend.src.routers.pubsub
@router.post("/sub/user/{token}", status_code=status.HTTP_200_OK)
@pubsub_fail_gracefully
async def sub_user(response: Response, token: str, request: Request) -> Any:
data: Dict[str, Any] = await parse_request(token, request)
await lock_user(data["user_id"])
+ # standard policy is to check past five years of data
+ start_date = date.today() - timedelta(365 * 5)
+ end_date = date.today()
+ timezone_str = "US/Eastern"
+
+ # TODO: historical data is never updated,
+ # don't query full five years each time, instead
+ # define function to build on previous results
+
+ output = await get_data(
- output = await analytics_get_user(
data["user_id"],
data["access_token"],
+ start_date,
+ end_date,
- datetime.strptime(data["start_date"], "%Y-%m-%d").date(),
- datetime.strptime(data["end_date"], "%Y-%m-%d").date(),
+ timezone_str,
- data["timezone_str"],
)
+ await update_user(data["user_id"], output.dict())
- await update_user(data["user_id"], output)
await unlock_user(data["user_id"])
+ return data
- return output
===========changed ref 6===========
# module: backend.src.analytics.user.commits
+ def get_top_repos(data: UserPackage) -> List[RepoStats]:
- def get_top_repos(data: UserPackage) -> List[Any]:
repos: List[Any] = [
{
"repo": repo,
"langs": [
{
"lang": x[0],
"color": x[1].color,
"additions": x[1].additions,
"deletions": x[1].deletions,
}
for x in list(repo_stats.languages.items())
],
"additions": sum([x.additions for x in repo_stats.languages.values()]),
"deletions": sum([x.deletions for x in repo_stats.languages.values()]),
}
for repo, repo_stats in data.contribs.repo_stats.items()
]
for repo in repos:
repo["added"] = int(repo["additions"]) - int(repo["deletions"])
repo["changed"] = int(repo["additions"]) + int(repo["deletions"])
repo["langs"] = [
x
for x in repo["langs"]
if x["additions"] + x["deletions"] > 0.05 * repo["changed"]
]
repos = sorted(repos, key=lambda x: x["changed"], reverse=True)
+ new_repos = [
+ RepoStats.parse_obj(x)
+ for x in repos
+ if x["changed"] > 0.05 * repos[0]["changed"]
- repos = [x for x in repos if x["changed"] > 0.05 * repos[0]["changed"]]
+ ]
+ return new_repos[:5]
- return repos[:5]
|
backend.src.routers.users/get_user_repo_svg
|
Modified
|
avgupta456~github-trends
|
2a1966d4f8ae21a74c3b172ef3c4e6adb80c4082
|
store raw_data, not analytics
|
<0>:<add> output = await _get_user(user_id)
<del> output = await _get_user(user_id, start_date, end_date, timezone_str)
|
<s>routers.users
@router.get(
"/{user_id}/svg/repos", status_code=status.HTTP_200_OK, response_class=HTMLResponse
)
@svg_fail_gracefully
async def get_user_repo_svg(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
) -> Any:
<0> output = await _get_user(user_id, start_date, end_date, timezone_str)
<1> if not validate_raw_data(output):
<2> return get_loading_svg()
<3> return get_top_repos_svg(output) # type: ignore
<4>
|
===========changed ref 0===========
<s> status_code=status.HTTP_200_OK)
@async_fail_gracefully
- async def get_user(
- response: Response,
- user_id: str,
- start_date: date = date.today() - timedelta(365),
- end_date: date = date.today(),
- timezone_str: str = "US/Eastern",
- ) -> Optional[RawDataModel]:
+ async def get_user(response: Response, user_id: str) -> Optional[UserPackage]:
+ return await _get_user(user_id)
- return await _get_user(user_id, start_date, end_date, timezone_str)
===========changed ref 1===========
<s> "/{user_id}/svg/langs", status_code=status.HTTP_200_OK, response_class=HTMLResponse
)
@svg_fail_gracefully
async def get_user_lang_svg(
response: Response,
user_id: str,
start_date: date = date.today() - timedelta(365),
end_date: date = date.today(),
timezone_str: str = "US/Eastern",
use_percent: bool = True,
) -> Any:
+ output = await _get_user(user_id)
- output = await _get_user(user_id, start_date, end_date, timezone_str)
if not validate_raw_data(output):
return get_loading_svg()
return get_top_langs_svg(output, use_percent) # type: ignore
===========changed ref 2===========
# module: backend.src.routers.users
+ def validate_raw_data(data: Optional[UserPackage]) -> bool:
- def validate_raw_data(data: Optional[RawDataModel]) -> bool:
# NOTE: add more validation as more fields are required
+ return data is not None and data.contribs is not None
- return data is not None and data.top_languages is not None
===========changed ref 3===========
# module: backend.src.routers.users
- def _get_user(
- user_id: str,
- start_date: date = date.today() - timedelta(365),
- end_date: date = date.today(),
- timezone_str: str = "US/Eastern",
- ) -> Optional[RawDataModel]:
+ @alru_cache()
+ async def _get_user(user_id: str) -> Optional[UserPackage]:
if not PUBSUB_PUB:
raise HTTPException(400, "")
db_user = await get_user_by_user_id(user_id)
if db_user is None or db_user.access_token == "":
raise LookupError("Invalid UserId")
time_diff = datetime.now() - db_user.last_updated
if time_diff > timedelta(hours=6) or not validate_raw_data(db_user.raw_data):
if not db_user.lock:
publish_to_topic(
- "user",
- {
- "user_id": user_id,
+ "user", {"user_id": user_id, "access_token": db_user.access_token}
- "access_token": db_user.access_token,
- "start_date": str(start_date),
- "end_date": str(end_date),
- "timezone_str": timezone_str,
- },
)
if validate_raw_data(db_user.raw_data):
return db_user.raw_data # type: ignore
return None
===========changed ref 4===========
# module: backend.src.models.user.analytics
- class RawDataModel(BaseModel):
- top_languages: Optional[List[LanguageStats]]
- top_repos: Optional[List[RepoStats]]
-
===========changed ref 5===========
# module: backend.src.routers.pubsub
@router.get("/pub/user/{user_id}/{access_token}", status_code=status.HTTP_200_OK)
@fail_gracefully
def pub_user(response: Response, user_id: str, access_token: str) -> str:
- publish_to_topic(
- "user",
- {
- "user_id": user_id,
- "access_token": access_token,
- "start_date": str(date.today() - timedelta(365)),
- "end_date": str(date.today()),
- "timezone_str": "US/Eastern",
- },
- )
+ publish_to_topic("user", {"user_id": user_id, "access_token": access_token})
return user_id
===========changed ref 6===========
# module: backend.src.routers.pubsub
@router.post("/sub/user/{token}", status_code=status.HTTP_200_OK)
@pubsub_fail_gracefully
async def sub_user(response: Response, token: str, request: Request) -> Any:
data: Dict[str, Any] = await parse_request(token, request)
await lock_user(data["user_id"])
+ # standard policy is to check past five years of data
+ start_date = date.today() - timedelta(365 * 5)
+ end_date = date.today()
+ timezone_str = "US/Eastern"
+
+ # TODO: historical data is never updated,
+ # don't query full five years each time, instead
+ # define function to build on previous results
+
+ output = await get_data(
- output = await analytics_get_user(
data["user_id"],
data["access_token"],
+ start_date,
+ end_date,
- datetime.strptime(data["start_date"], "%Y-%m-%d").date(),
- datetime.strptime(data["end_date"], "%Y-%m-%d").date(),
+ timezone_str,
- data["timezone_str"],
)
+ await update_user(data["user_id"], output.dict())
- await update_user(data["user_id"], output)
await unlock_user(data["user_id"])
+ return data
- return output
===========changed ref 7===========
# module: backend.src.analytics.user.commits
+ def get_top_repos(data: UserPackage) -> List[RepoStats]:
- def get_top_repos(data: UserPackage) -> List[Any]:
repos: List[Any] = [
{
"repo": repo,
"langs": [
{
"lang": x[0],
"color": x[1].color,
"additions": x[1].additions,
"deletions": x[1].deletions,
}
for x in list(repo_stats.languages.items())
],
"additions": sum([x.additions for x in repo_stats.languages.values()]),
"deletions": sum([x.deletions for x in repo_stats.languages.values()]),
}
for repo, repo_stats in data.contribs.repo_stats.items()
]
for repo in repos:
repo["added"] = int(repo["additions"]) - int(repo["deletions"])
repo["changed"] = int(repo["additions"]) + int(repo["deletions"])
repo["langs"] = [
x
for x in repo["langs"]
if x["additions"] + x["deletions"] > 0.05 * repo["changed"]
]
repos = sorted(repos, key=lambda x: x["changed"], reverse=True)
+ new_repos = [
+ RepoStats.parse_obj(x)
+ for x in repos
+ if x["changed"] > 0.05 * repos[0]["changed"]
- repos = [x for x in repos if x["changed"] > 0.05 * repos[0]["changed"]]
+ ]
+ return new_repos[:5]
- return repos[:5]
|
backend.src.utils/alru_cache
|
Modified
|
avgupta456~github-trends
|
523264e3688adaeafb16a08eee5417f617ed1536
|
misc updates
|
<10>:<add> if not value:
<add> return None
|
# module: backend.src.utils
+ # NOTE: return None to avoid caching
def alru_cache(max_size: int = 128, ttl: timedelta = timedelta(hours=1)):
<0> def decorator(func: Callable[..., Any]) -> Any:
<1> cache: Dict[Any, Tuple[datetime, Any]] = {}
<2> keys: List[Any] = []
<3>
<4> @wraps(func)
<5> async def wrapper(*args: List[Any], **kwargs: Dict[str, Any]) -> Any:
<6> now = datetime.now()
<7> key = tuple(args), frozenset(kwargs.items())
<8> if key not in cache or now - cache[key][0] > ttl:
<9> value = await func(*args, **kwargs)
<10> cache[key] = (now, value)
<11> keys.append(key)
<12> if len(keys) > max_size:
<13> del cache[keys.pop(0)]
<14> return cache[key][1]
<15>
<16> return wrapper
<17>
<18> return decorator
<19>
|
===========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.src.constants
# GLOBAL
PROD = os.getenv("PROD", "False") == "True"
PROJECT_ID = "github-298920"
BACKEND_URL = "https://api.githubtrends.io" if PROD else "http://localhost:8000"
# API
TIMEOUT = 15 # max seconds to wait for api response
+ NODE_CHUNK_SIZE = 40 # number of nodes (commits) to query (max 100)
- NODE_CHUNK_SIZE = 25 # number of nodes (commits) to query (max 100)
NODE_THREADS = 40 # number of node queries simultaneously (avoid blacklisting)
CUTOFF = 500 # if > cutoff lines, assume imported, don't count
# CUSTOMIZATION
BLACKLIST = ["Jupyter Notebook", "HTML"] # languages to ignore
# OAUTH
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
# PUBSUB
PUBSUB_PUB = os.getenv("PUBSUB_PUB", "False") == "True"
PUBSUB_TOKEN = os.getenv("PUBSUB_TOKEN", "")
LOCAL_SUBSCRIBER = "http://localhost:8001/pubsub/sub/"
# MONGODB
MONGODB_PASSWORD = os.getenv("MONGODB_PASSWORD", "")
# SENTRY
SENTRY_DSN = os.getenv("SENTRY_DSN", "")
# TESTING
TEST_USER_ID = "AshishGupta938" # for testing, previously "avgupta456"
TEST_TOKEN = os.getenv("AUTH_TOKEN", "") # for authentication
|
backend.src.routers.users/get_user
|
Modified
|
avgupta456~github-trends
|
523264e3688adaeafb16a08eee5417f617ed1536
|
misc updates
|
<0>:<add> output = await _get_user(user_id)
<del> return await _get_user(user_id)
|
# module: backend.src.routers.users
@router.get("/{user_id}", status_code=status.HTTP_200_OK)
@async_fail_gracefully
async def get_user(response: Response, user_id: str) -> Optional[UserPackage]:
<0> return await _get_user(user_id)
<1>
|
===========unchanged ref 0===========
at: backend.src.routers.users
router = APIRouter()
at: src.utils
async_fail_gracefully(func: Callable[..., Any])
===========changed ref 0===========
# module: backend.src.utils
+ # NOTE: return None to avoid caching
def alru_cache(max_size: int = 128, ttl: timedelta = timedelta(hours=1)):
def decorator(func: Callable[..., Any]) -> Any:
cache: Dict[Any, Tuple[datetime, Any]] = {}
keys: List[Any] = []
@wraps(func)
async def wrapper(*args: List[Any], **kwargs: Dict[str, Any]) -> Any:
now = datetime.now()
key = tuple(args), frozenset(kwargs.items())
if key not in cache or now - cache[key][0] > ttl:
value = await func(*args, **kwargs)
+ if not value:
+ return None
cache[key] = (now, value)
keys.append(key)
if len(keys) > max_size:
del cache[keys.pop(0)]
return cache[key][1]
return wrapper
return decorator
===========changed ref 1===========
# module: backend.src.constants
# GLOBAL
PROD = os.getenv("PROD", "False") == "True"
PROJECT_ID = "github-298920"
BACKEND_URL = "https://api.githubtrends.io" if PROD else "http://localhost:8000"
# API
TIMEOUT = 15 # max seconds to wait for api response
+ NODE_CHUNK_SIZE = 40 # number of nodes (commits) to query (max 100)
- NODE_CHUNK_SIZE = 25 # number of nodes (commits) to query (max 100)
NODE_THREADS = 40 # number of node queries simultaneously (avoid blacklisting)
CUTOFF = 500 # if > cutoff lines, assume imported, don't count
# CUSTOMIZATION
BLACKLIST = ["Jupyter Notebook", "HTML"] # languages to ignore
# OAUTH
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
# PUBSUB
PUBSUB_PUB = os.getenv("PUBSUB_PUB", "False") == "True"
PUBSUB_TOKEN = os.getenv("PUBSUB_TOKEN", "")
LOCAL_SUBSCRIBER = "http://localhost:8001/pubsub/sub/"
# MONGODB
MONGODB_PASSWORD = os.getenv("MONGODB_PASSWORD", "")
# SENTRY
SENTRY_DSN = os.getenv("SENTRY_DSN", "")
# TESTING
TEST_USER_ID = "AshishGupta938" # for testing, previously "avgupta456"
TEST_TOKEN = os.getenv("AUTH_TOKEN", "") # for authentication
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.