Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add black lint #483

Merged
merged 10 commits into from
Sep 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
[flake8]
show_source = True
statistics = True

# E501: line to long.
# E203: whitespace before ':' to accept black code style
# W503: line break before binary operator
ignore = E501,E203,W503
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,7 @@ jobs:
pip install -r requirements-dev.txt
- name: Lint
run: flake8 --show-source --statistics
- name: Blint
run: black --check --diff .
- name: Run tests
run: pytest
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ install:

script:
- flake8
- black
- pytest --check-links --ignore=docs/course_materials/reveal
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ name = "pypi"

[dev-packages]

black = "*"
flake8 = "*"
pytest = "*"
pytest-coverage = "*"
Expand Down
20 changes: 10 additions & 10 deletions classroom/connect_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@


# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/classroom.rosters',
'https://www.googleapis.com/auth/classroom.courses',
'https://www.googleapis.com/auth/classroom.topics']
SCOPES = [
"https://www.googleapis.com/auth/classroom.rosters",
"https://www.googleapis.com/auth/classroom.courses",
"https://www.googleapis.com/auth/classroom.topics",
]


def create_service():
Expand All @@ -20,21 +22,19 @@ def create_service():
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
if os.path.exists("token.pickle"):
with open("token.pickle", "rb") as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
with open("token.pickle", "wb") as token:
pickle.dump(creds, token)

service = build('classroom', 'v1', credentials=creds,
cache_discovery=False)
service = build("classroom", "v1", credentials=creds, cache_discovery=False)
return service
14 changes: 7 additions & 7 deletions classroom/content_edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,21 @@
def print_topics(service, course_id):
# Call the Classroom API
results = service.courses().topics().list(courseId=course_id).execute()
topics = results.get('topic', [])
topics = results.get("topic", [])

if not topics:
print('No topics found.')
print("No topics found.")
else:
print('Topics:')
print("Topics:")
for topic in topics:
print(f"Title: {topic['name']}, ID: {topic['topicId']}")


def create_topic(service, title, course_id):
topic = {'name': title}
new_topic = service.courses().topics().create(
courseId=course_id,
body=topic).execute()
topic = {"name": title}
new_topic = (
service.courses().topics().create(courseId=course_id, body=topic).execute()
)
print(f"Topic created: {new_topic['name']} {new_topic['topicId']}")


Expand Down
54 changes: 29 additions & 25 deletions classroom/course_creator.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,39 +6,43 @@
def print_courses(service):
# Call the Classroom API
results = service.courses().list(pageSize=10).execute()
courses = results.get('courses', [])
courses = results.get("courses", [])

if not courses:
print('No courses found.')
print("No courses found.")
else:
print('Courses:')
print("Courses:")
for course in courses:
print(f"Title: {course['name']}, ID: {course['id']}")


def create_course(service, course_name):
course_data = {'name': course_name,
'descriptionHeading': 'Welcome to ' + course_name,
'description': ("We'll be learning about coding from a " +
"combination of lectures, course work, " +
"and home projects. Let's start!"),
'ownerId': 'me',
'courseState': 'PROVISIONED'}
course_data = {
"name": course_name,
"descriptionHeading": "Welcome to " + course_name,
"description": (
"We'll be learning about coding from a "
+ "combination of lectures, course work, "
+ "and home projects. Let's start!"
),
"ownerId": "me",
"courseState": "PROVISIONED",
}
course = service.courses().create(body=course_data).execute()
print(f"Course created: {course.get('name')} {course.get('id')}")
return course.get('id')
return course.get("id")


def load_list(list_path):
'''
"""
Load student/teacher list from csv file.
'''
"""
if not os.path.exists(list_path):
print(f"This path does not exist: {list_path}.")
return None
with open(list_path, mode='r') as csv_file:
with open(list_path, mode="r") as csv_file:
mail_list = []
csv_reader = csv.reader(csv_file, delimiter=',')
csv_reader = csv.reader(csv_file, delimiter=",")
if csv_reader is None:
print("The list is empty.")
return mail_list
Expand All @@ -59,25 +63,25 @@ def create_invitation(service, args, invite_type):
Function:
- Creates invitations using the mail list.
"""
if invite_type == 'STUDENT':
if invite_type == "STUDENT":
list_path = args.student_list
else:
list_path = args.teacher_list
mail_list = load_list(list_path)
if len(mail_list) > 0:
for mail in mail_list:
invitation = {
'courseId': args.id,
'role': invite_type,
'userId': mail,
"courseId": args.id,
"role": invite_type,
"userId": mail,
}
try:
service.invitations().create(body=invitation).execute()
print(f'Invitation was sent to {mail}')
print(f"Invitation was sent to {mail}")
except errors.HttpError as e:
if '409' in str(e):
print(f'Not added, {mail} has a pending invitation.')
elif '400' in str(e):
print(f'Not added, {mail} already listed in course.')
if "409" in str(e):
print(f"Not added, {mail} has a pending invitation.")
elif "400" in str(e):
print(f"Not added, {mail} already listed in course.")
else:
print('No permissions or wrong course ID.')
print("No permissions or wrong course ID.")
112 changes: 67 additions & 45 deletions classroom/rose_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,75 +6,97 @@


def main():
'''
"""
Getting user input and preforming corresponding actions.
Available functions:
- Create course/topic in classroom.
- Print existing courses/topics.
- Update teacher list.
- Update student list.
'''
"""

logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser(description='ROSE Classroom')
parser.add_argument('--course', action='store_true',
help='A flag for course actions, stores True. '
'Has to be followed by an action as --create. '
'If not specified, will be False.')
parser.add_argument('--topic', action='store_true',
help='A flag for topic actions, stores True. '
'Has to be followed by an action as --create. '
'If not specified, will be False.')
parser.add_argument('--create', '-c', dest='name',
help='Creating a new instance using given name. '
'If not specified, cannot be created. '
'Follows an instance type as --course. '
'For creating Topics, Assignments and more '
'please specify the course/topic id using -i.')
parser.add_argument('--print', '-p', action="store_true",
help='Printing existing instances.')
parser.add_argument('--teacher_list', '-t', dest='teacher_list',
help='Adding teachers using a list, '
'expects a csv file. '
'If course exists, '
'please provide course ID using -i.')
parser.add_argument('--student_list', '-s', dest='student_list',
help='Adding students using a list, '
'expects csv file. '
'If course exists, '
'please provide course ID using -i.')
parser.add_argument('--id', '-i',
help='Specifies an instance id. Can be used for '
'adding student lists or teacher lists, adding '
'Topics, Homework and more. '
'Please specify the needed action. '
'Use combined with instance type as --course.')
parser = argparse.ArgumentParser(description="ROSE Classroom")
parser.add_argument(
"--course",
action="store_true",
help="A flag for course actions, stores True. "
"Has to be followed by an action as --create. "
"If not specified, will be False.",
)
parser.add_argument(
"--topic",
action="store_true",
help="A flag for topic actions, stores True. "
"Has to be followed by an action as --create. "
"If not specified, will be False.",
)
parser.add_argument(
"--create",
"-c",
dest="name",
help="Creating a new instance using given name. "
"If not specified, cannot be created. "
"Follows an instance type as --course. "
"For creating Topics, Assignments and more "
"please specify the course/topic id using -i.",
)
parser.add_argument(
"--print", "-p", action="store_true", help="Printing existing instances."
)
parser.add_argument(
"--teacher_list",
"-t",
dest="teacher_list",
help="Adding teachers using a list, "
"expects a csv file. "
"If course exists, "
"please provide course ID using -i.",
)
parser.add_argument(
"--student_list",
"-s",
dest="student_list",
help="Adding students using a list, "
"expects csv file. "
"If course exists, "
"please provide course ID using -i.",
)
parser.add_argument(
"--id",
"-i",
help="Specifies an instance id. Can be used for "
"adding student lists or teacher lists, adding "
"Topics, Homework and more. "
"Please specify the needed action. "
"Use combined with instance type as --course.",
)

args = parser.parse_args()

'''Set up the service to google classroom'''
"""Set up the service to google classroom"""
service = connect_service.create_service()

if args.id and len(args.id) < 12:
print('Please check the ID specified and try again.')
print("Please check the ID specified and try again.")
elif args.course and not args.topic:
if args.name:
args.id = course_creator.create_course(service, args.name)
print(f'The id returned {args.id}')
print(f"The id returned {args.id}")
elif args.print:
course_creator.print_courses(service)
elif not args.id:
print('Please use --help to inspect the possible actions.')
print("Please use --help to inspect the possible actions.")
else:
if args.teacher_list:
course_creator.create_invitation(service, args, 'TEACHER')
course_creator.create_invitation(service, args, "TEACHER")

if args.student_list:
course_creator.create_invitation(service, args, 'STUDENT')
course_creator.create_invitation(service, args, "STUDENT")

no_list = args.student_list is None and args.teacher_list is None
if (no_list):
print('Please use -h to check the available actions.')
if no_list:
print("Please use -h to check the available actions.")
elif args.topic:
if args.course and args.id:
if args.print:
Expand All @@ -83,8 +105,8 @@ def main():
if args.name:
content_edit.create_topic(service, args.name, args.id)
else:
print('Wrong action')
print("Wrong action")


if __name__ == '__main__':
if __name__ == "__main__":
main()
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@

def joing_files(file_name1, file_name2, out_file_name):
"""
Reads the first two files, joins them and writes the data to the third one.
"""
try:
file1 = open(file_name1, 'r').read()
file2 = open(file_name2, 'r').read()
open(out_file_name, 'w').write(file1 + file2)
print('The files were joined successfully!')
file1 = open(file_name1, "r").read()
file2 = open(file_name2, "r").read()
open(out_file_name, "w").write(file1 + file2)
print("The files were joined successfully!")
except Exception as e:
print(e)
print('Reading or writing error with one of the files!')
print("Reading or writing error with one of the files!")


file_name_1 = input("Enter the first file name: ")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
end_of_the_year = datetime(2020, 12, 31)
today = datetime.now()
time_to_the_end_of_the_year = end_of_the_year - today
print('There are {} days left…'.format(time_to_the_end_of_the_year.days))
print("There are {} days left…".format(time_to_the_end_of_the_year.days))
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
exercise_commands = ['mkdir', 'tree']
exercise_commands = ["mkdir", "tree"]

exercise_paths = ['test', 'test/tmp']
exercise_paths = ["test", "test/tmp"]

exercise_deleted_paths = []
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
exercise_commands = ['vim', 'cp']
exercise_commands = ["vim", "cp"]

exercise_paths = ['roses.txt']
exercise_paths = ["roses.txt"]

exercise_deleted_paths = []
Loading