I am trying to print list of mandatory and elective courses using tkinter
from tkinter import*
window = Tk()
window.title('DEPARTMENT OF PHYISCS POSTGRADUATE COUSRSE CHECKER')
sepcialization = StringVar()
def courses():
if sepcialization == 'Nuclear Physics':
mandatoryCourses = ['Phy801', 'Phy802', 'Phy803', 'Phy804', 'Phy805', 'Phy806', 'Phy807']
electiveCourses = ['Phy818', 'Phy819', 'Phy821']
return f'student must take the following mandatory courses:{mandatoryCourses} and select not more than 9 Units from the elective courses: {electiveCourses}'
if sepcialization == 'Geo-Physics':
mandatoryCourses = ['Phy801', 'Phy802', 'Phy803', 'Phy804', 'Phy805', 'Phy806', 'Phy807']
electiveCourses = ['Phy835', 'Phy834', 'Phy839']
return f'student must take the following mandatory courses:{mandatoryCourses} and select not more than 9 Units from the elective courses: {electiveCourses}'
if sepcialization == 'Atmospheric Physics':
mandatoryCourses = ['Phy801', 'Phy802', 'Phy803', 'Phy804', 'Phy805', 'Phy806', 'Phy807']
electiveCourses = ['Phy840','Phy842','Phy843']
return f'student must take the following mandatory courses:{mandatoryCourses} and select not more than 9 Units from the elective courses: {electiveCourses}'
if sepcialization == 'Renewable Energy':
mandatoryCourses = ['Phy801', 'Phy802', 'Phy803', 'Phy804', 'Phy805', 'Phy806', 'Phy807']
electiveCourses = ['Phy814', 'Phy825', 'Phy830']
return f'student must take the following mandatory courses:{mandatoryCourses} and select not more than 9 Units from the elective courses: {electiveCourses}'
courses = sepcialization.get()
label3.configure(courses)
print(courses)
Related
I'm doing a web scraping data university research project. I started working on a ready GitHub project, but this project does not retrieve all the data.
The project works like this:
Search Google using keywords: example: (accountant 'email me at' Google)
Extract a snippet.
Retrieve data from this snippet.
The issue is:
The snippets extracted are like this: " ... marketing division in 2009. For more information on career opportunities with our company, email me: vicki#productivedentist.com. Neighborhood Smiles, LLC ..."
The snippet does not show all, the "..." hides information like role, location... How can I retrieve all the information with the script?
from googleapiclient.discovery import build #For using Google Custom Search Engine API
import datetime as dt #Importing system date for the naming of the output file.
import sys
from xlwt import Workbook #For working on xls file.
import re #For email search using regex.
if __name__ == '__main__':
# Create an output file name in the format "srch_res_yyyyMMdd_hhmmss.xls in output folder"
now_sfx = dt.datetime.now().strftime('%Y%m%d_%H%M%S')
output_dir = './output/'
output_fname = output_dir + 'srch_res_' + now_sfx + '.xls'
search_term = sys.argv[1]
num_requests = int(sys.argv[2])
my_api_key = "replace_with_you_api_key" #Read readme.md to know how to get you api key.
my_cse_id = "011658049436509675749:gkuaxghjf5u" #Google CSE which searches possible LinkedIn profile according to query.
service = build("customsearch", "v1", developerKey=my_api_key)
wb=Workbook()
sheet1 = wb.add_sheet(search_term[0:15])
wb.save(output_fname)
sheet1.write(0,0,'Name')
sheet1.write(0,1,'Profile Link')
sheet1.write(0,2,'Snippet')
sheet1.write(0,3,'Present Organisation')
sheet1.write(0,4,'Location')
sheet1.write(0,5,'Role')
sheet1.write(0,6,'Email')
sheet1.col(0).width = 256 * 20
sheet1.col(1).width = 256 * 50
sheet1.col(2).width = 256 * 100
sheet1.col(3).width = 256 * 20
sheet1.col(4).width = 256 * 20
sheet1.col(5).width = 256 * 50
sheet1.col(6).width = 256 * 50
wb.save(output_fname)
row = 1 #To insert the data in the next row.
#Function to perform google search.
def google_search(search_term, cse_id, start_val, **kwargs):
res = service.cse().list(q=search_term, cx=cse_id, start=start_val, **kwargs).execute()
return res
for i in range(0, num_requests):
# This is the offset from the beginning to start getting the results from
start_val = 1 + (i * 10)
# Make an HTTP request object
results = google_search(search_term,
my_cse_id,
start_val,
num=10 #num value can be 1 to 10. It will give the no. of results.
)
for profile in range (0, 10):
snippet = results['items'][profile]['snippet']
myList = [item for item in snippet.split('\n')]
newSnippet = ' '.join(myList)
contain = re.search(r'[\w\.-]+#[\w\.-]+', newSnippet)
if contain is not None:
title = results['items'][profile]['title']
link = results['items'][profile]['link']
org = "-NA-"
location = "-NA-"
role = "-NA-"
if 'person' in results['items'][profile]['pagemap']:
if 'org' in results['items'][profile]['pagemap']['person'][0]:
org = results['items'][profile]['pagemap']['person'][0]['org']
if 'location' in results['items'][profile]['pagemap']['person'][0]:
location = results['items'][profile]['pagemap']['person'][0]['location']
if 'role' in results['items'][profile]['pagemap']['person'][0]:
role = results['items'][profile]['pagemap']['person'][0]['role']
print(title[:-23])
sheet1.write(row,0,title[:-23])
sheet1.write(row,1,link)
sheet1.write(row,2,newSnippet)
sheet1.write(row,3,org)
sheet1.write(row,4,location)
sheet1.write(row,5,role)
sheet1.write(row,6,contain[0])
print('Wrote {} search result(s)...'.format(row))
wb.save(output_fname)
row = row + 1
print('Output file "{}" written.'.format(output_fname))
I am working on face recognition system for my academic project. I want to set the first time an employee was recognized as his first active time and the next time he is being recognized should be recorded as his last active time and then calculate the total active hours based on first active and last active time.
I tried with the following code but I'm getting only the current system time as the start time. can someone help me on what I am doing wrong.
Code:
data = pickle.loads(open(args["encodings"], "rb").read())
vs = VideoStream(src=0).start()
writers = None
time.sleep(2.0)
while True:
frame = vs.read()
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
rgb = imutils.resize(frame, width=750)
r = frame.shape[1] / float(rgb.shape[1])
boxes = face_recognition.face_locations(rgb)
encodings = face_recognition.face_encodings(rgb, boxes)
names = []
face_names = []
for encoding in encodings:
matches = face_recognition.compare_faces(data["encodings"],
encoding)
name = "Unknown"
if True in matches:
matchedIdxs = [i for (i, b) in enumerate(matches) if b]
counts = {}
for i in matchedIdxs:
name = data["names"][i]
counts[name] = counts.get(name, 0) + 1
name = max(counts, key=counts.get)
names.append(name)
if names != []:
for i in names:
first_active_time = datetime.now().strftime('%H:%M')
last_active_time = datetime.now().strftime('%H:%M')
difference = datetime.strptime(first_active_time, '%H:%M') - datetime.strptime(last_active_time, '%H:%M')
difference = difference.total_seconds()
total_hours = time.strftime("%H:%M", time.gmtime(difference))
face_names.append([i, first_active_time, last_active_time, total_hours])
I am writing tests for an API with pytest.
The tests are structured like that:
KEEP_BOX_IDS = ["123abc"]
#pytest.fixture(scope="module")
def s():
UID = os.environ.get("MYAPI_UID")
if UID is None:
raise KeyError("UID not set in environment variable")
PWD = os.environ.get("MYAPI_PWD")
if PWD is None:
raise KeyError("PWD not set in environment variable")
return myapi.Session(UID, PWD)
#pytest.mark.parametrize("name,description,count", [
("Normal Box", "Normal Box Description", 1),
("ÄäÖöÜüß!§", "ÄäÖöÜüß!§", 2),
("___--_?'*#", "\n\n1738\n\n", 3),
])
def test_create_boxes(s, name, description, count):
box_info_create = s.create_box(name, description)
assert box_info_create["name"] == name
assert box_info_create["desc"] == description
box_info = s.get_box_info(box_info_create["id"])
assert box_info["name"] == name
assert box_info["desc"] == description
assert len(s.get_box_list()) == count + len(KEEP_BOX_IDS)
def test_update_boxes(s):
bl = s.get_box_list()
for b in bl:
b_id = b['id']
if b_id not in KEEP_BOX_IDS:
new_name = b["name"] + "_updated"
new_desc = b["desc"] + "_updated"
s.update_box(b_id, new_name, new_desc)
box_info = s.get_box_info(b_id)
assert box_info["name"] == new_name
assert get_box_info["desc"] == new_desc
I use a fixture to set up the session (this will keep me connected to the API).
As you can see I am creating 3 boxes at the beginning.
All test that are following do some sort of operations on this 3 boxes. (Boxes are just spaces for folders and files)
For example: update_boxes, create_folders, rename_folders, upload_files, change_file names, etc..
I know it's not good, since all the tests are dependent from each other, but if I execute them in the right order the test is valid and thats enough.
The second issue, which borders me the most, is that all the following tests start with the same lines:
bl = s.get_box_list()
for b in bl:
b_id = b['id']
if b_id not in KEEP_BOX_IDS:
box_info = s.get_box_info(b_id)
I always need to call this for loop to get each boxs id and info.
I've tried to put it in a second fixture, but the problem is that then there will be two fixtures.
Is there a better way of doing this?
Thanks
I'm not sure if the title accurately describes what I'm trying to do. I have a Python3.x script that I wrote that will issue flood warning to my facebook page when the river near my home has reached it's lowest flood stage. Right now the script works, however it only reports data from one measuring station. I would like to be able to process the data from all of the stations in my county (total of 5), so I was thinking that maybe a class method may do the trick but I'm not sure how to implement it. I've been teaching myself Python since January and feel pretty comfortable with the language for the most part, and while I have a good idea of how to build a class object I'm not sure how my flow chart should look. Here is the code now:
#!/usr/bin/env python3
'''
Facebook Flood Warning Alert System - this script will post a notification to
to Facebook whenever the Sabine River # Hawkins reaches flood stage (22.3')
'''
import requests
import facebook
from lxml import html
graph = facebook.GraphAPI(access_token='My_Access_Token')
river_url = 'http://water.weather.gov/ahps2/river.php?wfo=SHV&wfoid=18715&riverid=203413&pt%5B%5D=147710&allpoints=143204%2C147710%2C141425%2C144668%2C141750%2C141658%2C141942%2C143491%2C144810%2C143165%2C145368&data%5B%5D=obs'
ref_url = 'http://water.weather.gov/ahps2/river.php?wfo=SHV&wfoid=18715&riverid=203413&pt%5B%5D=147710&allpoints=143204%2C147710%2C141425%2C144668%2C141750%2C141658%2C141942%2C143491%2C144810%2C143165%2C145368&data%5B%5D=all'
def checkflood():
r = requests.get(river_url)
tree = html.fromstring(r.content)
stage = ''.join(tree.xpath('//div[#class="stage_stage_flow"]//text()'))
warn = ''.join(tree.xpath('//div[#class="current_warns_statmnts_ads"]/text()'))
stage_l = stage.split()
level = float(stage_l[2])
#check if we're at flood level
if level < 22.5:
pass
elif level == 37:
major_diff = level - 23.0
major_r = ('The Sabine River near Hawkins, Tx has reached [Major Flood Stage]: #', stage_l[2], 'Ft. ', str(round(major_diff, 2)), ' Ft. \n Please click the link for more information.\n\n Current Warnings and Alerts:\n ', warn)
major_p = ''.join(major_r)
graph.put_object(parent_object='me', connection_name='feed', message = major_p, link = ref_url)
<--snip-->
checkflood()
Each station has different 5 different catagories for flood stage: Action, Flood, Moderate, Major, each different depths per station. So for Sabine river in Hawkins it will be Action - 22', Flood - 24', Moderate - 28', Major - 32'. For the other statinos those depths are different. So I know that I'll have to start out with something like:
class River:
def __init__(self, id, stage):
self.id = id #station ID
self.stage = stage #river level'
#staticmethod
def check_flood(stage):
if stage < 22.5:
pass
elif stage.....
but from there I'm not sure what to do. Where should it be added in(to?) the code, should I write a class to handle the Facebook postings as well, is this even something that needs a class method to handle, is there any way to clean this up for efficiency? I'm not looking for anyone to write this up for me, but some tips and pointers would sure be helpful. Thanks everyone!
EDIT Here is what I figured out and is working:
class River:
name = ""
stage = ""
action = ""
flood = ""
mod = ""
major = ""
warn = ""
def checkflood(self):
if float(self.stage) < float(self.action):
pass
elif float(self.stage) >= float(self.major):
<--snip-->
mineola = River()
mineola.name = stations[0]
mineola.stage = stages[0]
mineola.action = "13.5"
mineola.flood = "14.0"
mineola.mod = "18.0"
mineola.major = "21.0"
mineola.alert = warn[0]
hawkins = River()
hawkins.name = stations[1]
hawkins.stage = stages[1]
hawkins.action = "22.5"
hawkins.flood = "23.0"
hawkins.mod = "32.0"
hawkins.major = "37.0"
hawkins.alert = warn[1]
<--snip-->
So from here I'm tring to stick all the individual river blocks into one block. What I have tried so far is this:
class River:
... name = ""
... stage = ""
... def testcheck(self):
... return self.name, self.stage
...
>>> for n in range(num_river):
... stations[n] = River()
... stations[n].name = stations[n]
... stations[n].stage = stages[n]
...
>>> for n in range(num_river):
... stations[n].testcheck()
...
<__main__.River object at 0x7fbea469bc50> 4.13
<__main__.River object at 0x7fbea46b4748> 20.76
<__main__.River object at 0x7fbea46b4320> 22.13
<__main__.River object at 0x7fbea46b4898> 16.08
So this doesn't give me the printed results that I was expecting. How can I return the string instead of the object? Will I be able to define the Class variables in this manner or will I have to list them out individually? Thanks again!
After reading many, many, many articles and tutorials on class objects I was able to come up with a solution for creating the objects using list elements.
class River():
def __init__(self, river, stage, flood, action):
self.river = river
self.stage = stage
self.action = action
self.flood = flood
self.action = action
def alerts(self):
if float(self.stage < self.flood):
#alert = "The %s is below Flood Stage (%sFt) # %s Ft. \n" % (self.river, self.flood, self.stage)
pass
elif float(self.stage > self.flood):
alert = "The %s has reached Flood Stage(%sFt) # %sFt. Warnings: %s \n" % (self.river, self.flood, self.stage, self.action)
return alert
'''this is the function that I was trying to create
to build the class objects automagically'''
def riverlist():
river_list = []
for n in range(len(rivers)):
station = River(river[n], stages[n], floods[n], warns[n])
river_list.append(station)
return river_list
if __name__ == '__main__':
for x in riverlist():
print(x.alerts())
Question has been fixed up, sorry if I have forgotten any other important information.
I am struggling with why my program can't calculate the tuition fee.
here is my code.
it is meant to ask the user to input a code type (pyhton, C++ or java) which works fine
it then asks the user to input the number of lessons/additional hours and tests that they would like to sit which is also working fine from what i can tell.
i believe the feecalc function is causing the problem but i get no actual errors when running it besides the fact that when the feecalc function goes to print the results, it prints the string but the variable has no value? or its value has been changed but im not sure as to why this is happening.
i apologise for pasting lots of code but im unsure as to what is causing this problem exactly as it runs 'fine'. is this a logical error or have I made a simple mistake that i am overlooking?
test data
code = python
number of lessons = 2
additional hours = 3
tests = 1
output is as follows
Welcome to Dr Ho Coaching Centre fee calculator
what code do you wish to study?
Python - Java - C++
>python
thank you for choosing python
How many lessons would you like?2
How many additional hours would you like?3
how many tests would you like to sit?1
python
Tuition fee for the lessons is $
Tuition fee for the additional hours is $
Tuition fee for the total tests is $
Total Tuition fee is $
Would you like to calculate the Tuition fee for another student?
as seen there is no calculated price displaying. and i have removed a few printed strings from the test data as i could not format it correctly within this forum, sorry if that changes anything.
.
def body( ):
codeofstudy = ''
tlessons = ''
xhours = ''
tests = ''
totalcost = ''
lessoncost = ''
xhourscost = ''
testscost = ''
print('''
-------------------------------------------------
Welcome to Dr Ho Coaching Centre fee calculator
-------------------------------------------------''')
codeofstudy = codecheck(codeofstudy)
studytime(tlessons, xhours, tests)
print(tlessons)
feecalc(codeofstudy, tlessons, xhours, tests, lessoncost, xhourscost, testscost, totalcost)
print('Tuition fee for the lessons is $',lessoncost)
print('Tuition fee for the additional hours is $', xhourscost)
print('Tuition fee for the total tests is $', testscost)
print('Total Tuition fee is $', totalcost)
rerun()
def codecheck(codeofstudy):
codeofstudy = input('''what code do you wish to study?
Python - Java - C++
>''')
if codeofstudy in {"python", "Python", "Java", "java", "C++", "c++"}:
print('thank you for choosing', codeofstudy)
return codeofstudy
else:
print('That is not a valid answer')
codecheck(codeofstudy)
def studytime(tlessons, xhours, tests):
tlessons = input('How many lessons would you like?')
xhours = input('How many additional hours would you like?')
tests = input('how many tests would you like to sit?')
tlessons = int(tlessons)
xhours = int(xhours)
tests = int(tests)
return tlessons, xhours, test
def feecalc(codeofstudy, tlessons, xhours, tests, lessoncost, xhourcost, testscost, totalcost):
if codeofstudy in ("python", "Python"):
print('python')
lessoncost = tlessons * 300
xhourscost = xhours * 200
testscost = tests * 250
totalcost = lessoncost + xhourscost + testscost
return lessoncost, xhourscost, testscost, totalcost
elif codeofstudy in ("java", "Java"):
print('java')
lessoncost = tlessons * 200
xhourscost = xhours * 150
testscost = tests * 150
totalcost = lessoncost + xhourscost + testscost
return lessoncost, xhourscost, testscost, totalcost
elif codeofstudy in ("c++", "C++"):
print('C++')
lessoncost = tlessons * 175
xhourscost = xhours * 175
testscost = tests * 170
totalcost = lessoncost + xhourscost + testscost
return lessoncost, xhourscost, testscost, totalcost
def rerun():
rerun = ' '
rerun = input('Would you like to calculate the Tuition fee for another student?')
if rerun in ("y", "Y"):
body()
body()
Thanks in advance for any help =]
You declared all your variables with value empty string '', you print them with the default values. studytime() assigning values to 3 local variables(scope belongs to the method only), the variables tlessons, xhours and test that declared outside of studytime() hadn't assigned any new values.
You need to change your code as:
tlessons, xhours, test = studytime(tlessons, xhours, tests)
return the values and assign them to corresponding variables
For example
def test(x):
x = 10
return x
x = 0
test(x)
print(x) # output is 0
x = test(x)
print(x) # output is 10