Skip to content

Commit

Permalink
Merge branch 'master' into all-contributors/add-rahulraikwar00
Browse files Browse the repository at this point in the history
  • Loading branch information
vybhav72954 authored Mar 30, 2021
2 parents e4ce748 + b803e03 commit 34957db
Show file tree
Hide file tree
Showing 12 changed files with 298 additions and 0 deletions.
10 changes: 10 additions & 0 deletions .all-contributorsrc
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,16 @@
"code",
"doc"
]
},
{
"login": "iamakkkhil",
"name": "Akhil Bhalerao",
"avatar_url": "https://avatars.githubusercontent.com/u/55273506?v=4",
"profile": "https://www.linkedin.com/in/akhil-bhalerao-63b47a193/",
"contributions": [
"code",
"doc"
]
}
],
"contributorsPerLine": 7,
Expand Down
23 changes: 23 additions & 0 deletions Python/Distance_Calculator_App/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Distance Calculating App
Calculating distance between two locations is a basic requirement if you are working with raw location data. This app calculates distance between two geo-locations. You can get distance in kilometers between two locations just by entering names of the locations.

## Quick Start:

- Change Directory

``` cd .\Rotten-Scripts\Python\Distance_Calculator_App\ ```

- Install requirememnts

`pip install -r requirements.txt`

- Run python file

`python main.py --firstlocation <enter first location here> --secondlocation <enter second location here>`

## Screenshot

![Screenshot](https://i.imgur.com/r7ImdqE.jpg)

## Author
[Aayush Garg](https://github.com/Aayush-hub)
38 changes: 38 additions & 0 deletions Python/Distance_Calculator_App/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import argparse
from geopy.geocoders import Nominatim
from geopy import distance

def location():
""" A program to calculate distance between two geo-locations
Parameters:
firstlocation (str): The starting location of user
secondlocation (str): The final location of user
"""
geolocator = Nominatim(user_agent="geoapiExercises")
parser = argparse.ArgumentParser()
parser.add_argument('--firstlocation', type=str, required=True)
parser.add_argument('--secondlocation', type=str, required=True)
args = parser.parse_args()

# calculating longitude and latitude of entered locations """
try:
first_location = geolocator.geocode(args.firstlocation)
second_location = geolocator.geocode(args.secondlocation)
Loc1_lat,Loc1_lon = (first_location.latitude),(first_location.longitude)
Loc2_lat,Loc2_lon = (second_location.latitude),(second_location.longitude)

location1=(Loc1_lat,Loc1_lon)
location2=(Loc2_lat,Loc2_lon)

# calculating and printing distance between locations in Kilometers and Miles."""

res = ((distance.distance(location1, location2).km))
distance_miles = float(res)*0.621371
print (f"The total distance is: {res} Km , {distance_miles} Miles")
except:
print("Invalid Location")

if __name__ == "__main__":
location()

Binary file added Python/Distance_Calculator_App/requirements.txt
Binary file not shown.
31 changes: 31 additions & 0 deletions Python/PR_Workflow/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# GitHub CLI

`pwr` is Pull Requests Workflow on the command line. It brings OPEN, CLOSED,MERGED and other PR concepts to the terminal next to where you are already working with `git` and your code.
`prw` is available for repositories hosted on GitHub.com.

## Setup instructions

<b>it requires a Github Personal Access Token (PAT) to verify the user</b>

| Install: | Run: |
| ----------------- | ---------------------------- |
| `bash install.sh` | `Python prw.py --help` |
| | `python prw.py auth <token>` |

## available commands

- `auth <token> `
- `repo <username/repo_name> [options] [mode] `

## Output

![Screenshot](https://i.imgur.com/jV8qgOG.png)

## Author

<b>[Rahul Raikwar](https://github.com/rahulraikwar00)</i>

## Disclaimers, if any

<i>This script requires a Github Personal Access Token (PAT) to verify the user</i>
<i>It does not have a specialized `upgrade` command yet, but the `install` command should work for upgrading to a newer version of GitHub prw.</i>
1 change: 1 addition & 0 deletions Python/PR_Workflow/config.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
c9a6sample-tokena097a9c83f9
93 changes: 93 additions & 0 deletions Python/PR_Workflow/prw.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import click
import requests
from src.extracktor import json_extract
from src.graphqlapi import Queries
from src.prapi import run_query


@click.group()
def main():
"""
Work with GitHub pull requests.\n
prw <command> <argument> [options] [flags]
"""


@main.command()
@click.option('-t', '--tag', type=str, help="Search pull request by tag[case sensitive]")
@click.option('-s', '--state', type=click.Choice(['open', 'closed', 'merged']), required=True, help="Show recent merged pull request")
@click.option('-v', '--verbose', is_flag=True, help="enable verbose mode")
@click.option('-p', '--pages', type=int, default=1, help="Show result up to pages")
@click.argument('repos', type=str, required=True)
def repo(repos, state, pages, tag=None, verbose=False, ):
"""This function checks the valid configuration
and calls the API on the given repository with arguments and options
and also prints the output
"""
if pages > 3:
click.secho("You can not see more than 3 pages.!", fg='red', bold=True)
return
pages = pages*30
state = state.upper()
flag = True
stcolor = {"OPEN": "green", "CLOSED": "red", "MERGED": "yellow"}
try:
#read configuration from config.ini file
with open('config.ini', 'r') as cf:
token = cf.read()
if len(token) != 40:
raise Exception
except:
if flag:
click.secho('Please Verify Your github Token first.!',
bold=True, fg='red')
click.echo('Usage : auth <token> ')
else:
r = repos.split("/")
if len(r) < 2:
click.echo(click.secho("SyntaxError:", fg='red', bold=True) +
click.echo('invalid syntax for repo : username/repo_name'))
return
else:
result = run_query(
Queries(f"{r[0]}", f"{r[1]}", state, tag, pages).pulls(), token)
if verbose:
print("This feature has not been added yet..comming soon")
else:

click.secho(state, fg=stcolor[state], bold=True)
for i in result['data']['repository']['pullRequests']['nodes']:
number = json_extract(i, 'number')
title = json_extract(i, 'title')
totalCount = json_extract(i, 'totalCount')
lname = json_extract(i, 'name')
click.secho(
f"#{number[0]} ", fg=stcolor[state], bold=True, nl=False)
print(
f"Title :{title[0]} ----------> Comments :{totalCount[0]} ---------> labels{lname}")


@main.command()
@click.argument('token')
def auth(token):
""" Verify Api with GitHub token\n
example: prw.py auth <token>
"""
if len(token) == 40:
with open('config.ini', 'w') as cf:
cf.write(token)
click.secho('Verification Successfull πŸ‘', fg='green', bold=True)
else:
click.secho('Incorrect token please retry..!', fg='red', bold=True)


def start():
"""
prw <command> <argument> [options] [flags]
"""

main(obj={})


if __name__ == '__main__':
start()
2 changes: 2 additions & 0 deletions Python/PR_Workflow/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
requests==2.25.1
click==7.1.2
20 changes: 20 additions & 0 deletions Python/PR_Workflow/src/extracktor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

def json_extract(obj, key):
"""Recursively fetch values from nested JSON."""
arr = []

def extract(obj, arr, key):
"""Recursively search for values of key in JSON tree."""
if isinstance(obj, dict):
for k, v in obj.items():
if isinstance(v, (dict, list)):
extract(v, arr, key)
elif k == key:
arr.append(v)
elif isinstance(obj, list):
for item in obj:
extract(item, arr, key)
return arr

values = extract(obj, arr, key)
return values
64 changes: 64 additions & 0 deletions Python/PR_Workflow/src/graphqlapi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@

class Queries:
"""The Queries class defines an object that represents a pull request query"""

def __init__(self, owner, name, state, tag=None, countr=30):
""" initialize query object with state, name, owner, tag and counter."""
self.name = name
self.owner = owner
self.tag = tag
self.state = state
self.countr = countr

def pulls(self):
if self.tag != None:
query = """
{ repository(name: "%s", owner: "%s") {
pullRequests(states: %s, last: %i, orderBy: {field: CREATED_AT, direction: ASC},labels:"%s") {
totalCount
nodes {
title
number
comments {
totalCount
}
closedAt
createdAt
labels(last: 10) {
nodes {
name
}
totalCount
}
}
}
}
}
""" % (self.name, self.owner, self.state, self.countr, self.tag)
return query
else:
query = """
{
repository(name: "%s", owner: "%s") {
pullRequests(states: %s, last: %s, orderBy: {field: CREATED_AT, direction: ASC}) {
totalCount
nodes {
title
number
comments {
totalCount
}
closedAt
createdAt
labels(last: 10) {
nodes {
name
}
totalCount
}
}
}
}
}
""" % (self.name, self.owner, self.state, self.countr)
return query
15 changes: 15 additions & 0 deletions Python/PR_Workflow/src/prapi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@

import requests


def run_query(query, token):
""" A simple function to use requests.post to make the API call. Note the json= section. """

headers = {"Authorization": f"token {token}"}
res = requests.post('https://api.github.com/graphql',
json={'query': query}, headers=headers)
if res.status_code == 200:
return res.json()
else:
raise Exception("Query failed to run by returning code of {}. {}".format(
res.status_code, query))
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
</tr>
<tr>
<td align="center"><a href="http://rahulraikwar.me"><img src="https://avatars.githubusercontent.com/u/54519734?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Rahul raikwar</b></sub></a><br /><a href="https://github.com/HarshCasper/Rotten-Scripts/commits?author=rahulraikwar00" title="Code">πŸ’»</a> <a href="https://github.com/HarshCasper/Rotten-Scripts/commits?author=rahulraikwar00" title="Documentation">πŸ“–</a></td>
<td align="center"><a href="https://www.linkedin.com/in/akhil-bhalerao-63b47a193/"><img src="https://avatars.githubusercontent.com/u/55273506?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Akhil Bhalerao</b></sub></a><br /><a href="https://github.com/HarshCasper/Rotten-Scripts/commits?author=iamakkkhil" title="Documentation">πŸ“–</a></td>
</tr>
</table>

Expand Down

0 comments on commit 34957db

Please sign in to comment.