Get the list of due assignments using Google Classroom API - python

I am trying to get the list of assignments due/coursework for all the courses using the Google Classroom API. I am getting a list of courses using the below code :
results = service.courses().list(pageSize = 10).execute()
courses = results.get('courses',[])
Once I get the list of all the courses, I loop over each the course and try to supply the courseID in order to get the list of coursework using courses.courseWork.list method, but I'm getting an error.
I have written the following code :
for course in courses :
print(course['name'])
print "Assignments you have due in this course : "
print course[u'id']
course_work_results = service.courses().courseWork().list().execute()
print course_work_results
Since I am not supplying the courseID anywhere (which I need to know how to do), I get the following error :
Traceback (most recent call last):
File "classroom.py", line 53, in <module>
course_work_results = service.courses().courseWork().list().execute()
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/discovery.py", line 727, in method
raise TypeError('Missing required parameter "%s"' % name)
TypeError: Missing required parameter "courseId"
The error is caused due to the line
course_work_results = service.courses().courseWork().list().execute()
How to fix this ?

Related

Python getting results from Azure Storage Table with azure-data-tables

I am trying to query an Azure storage table to get all rows to turn into a table on a web site, however I cannot get the entries from the table, I get the same error every time "azure.core.exceptions.HttpResponseError: The requested operation is not implemented on the specified resource."
For code I am following the examples here and it is not working as expected.
from azure.data.tables import TableServiceClient
from azure.core.credentials import AzureNamedKeyCredential
def read_storage_table():
credential = AzureNamedKeyCredential(os.environ["AZ_STORAGE_ACCOUNT"], os.environ["AZ_STORAGE_KEY"])
service = TableServiceClient(endpoint=os.environ["AZ_STORAGE_ENDPOINT"], credential=credential)
client = service.get_table_client(table_name=os.environ["AZ_STORAGE_TABLE"])
entities = client.query_entities(query_filter="PartitionKey eq 'tasksSeattle'")
client.close()
service.close()
return entities
Then calling the function.
table = read_storage_table()
for record in table:
for key in record.keys():
print("Key: {}, Value: {}".format(key, record[key]))
And that returns:
Traceback (most recent call last):
File "C:\Program Files\Python310\Lib\site-packages\azure\data\tables\_models.py", line 363, in _get_next_cb
return self._command(
File "C:\Program Files\Python310\Lib\site-packages\azure\data\tables\_generated\operations\_table_operations.py", line 386, in query_entities
raise HttpResponseError(response=response, model=error)
azure.core.exceptions.HttpResponseError: Operation returned an invalid status 'Not Implemented'
Content: {"odata.error":{"code":"NotImplemented","message":{"lang":"en-US","value":"The requested operation is not implemented on the specified resource.\nRequestId:cd29feda-1002-006b-679c-3d39e8000000\nTime:2022-03-22T03:27:00.5993216Z"}}}
Using a similar function I am able to write to the table. But even trying entities = client.list_entities() I get the same error. I'm at a loss.
KrunkFu thank you for identifying and sharing the solution here. Posting the same into answer section to help other community members.
replacing https://<accountname>.table.core.windows.net/<table>, with
https://<accountname>.table.core.windows.net to the query solved the
issue

Making changes to debug Python script results in error returned for syntax issue

I have a script I found here:
https://n2ws.com/wp-content/uploads/2017/10/ebs-report.py
Running it returns the below error:
Traceback (most recent call last):
File "ebs-report.py", line 194, in <module>
retval = create_ebs_report (args.regions, args.access_key, args.secret_key, args.file)
File "ebs-report.py", line 130, in create_ebs_report
'type' : volume_types_map[vol.type],
KeyError: u'st1'
There is no mapping for st1 (which is a type of volume from aws that perhaps didn't exist when the script was written) so I am trying to resolve this.
I am hoping that the error can be resolved by adding that extra volume type so change the script here:
volume_types_map = { u'standard' : u'Standard/Magnetic', u'io1' : u'Provisioned IOPS (SSD)', u'gp2' : u'General Purpose SSD'}
To this...
volume_types_map = { u'standard' : u'Standard/Magnetic', u'io1' : u'Provisioned IOPS (SSD)', u'gp2' : u'General Purpose SSD', u'Throughput Optimized HDD', u'st1'}
So basically I am adding the st1 part on to the mapping in the hope that it sorts out the issue.
This results in an error. I must have got the syntax wrong within the extra value that I added to the "volume_types_map"...
File "ebs-report2.py", line 102
volume_types_map = { u'standard' : u'Standard/Magnetic', u'io1' : u'Provisioned IOPS (SSD)', u'gp2' : u'General Purpose SSD', u'Throughput Optimized HDD', u'st1'}
^
SyntaxError: invalid syntax
This is the error that results from my change, above.
Can anyone help with what I seem to have incorrectly added and identify where I may have gone wrong, I suspect with the commas colons and spaces.
You should add the st1 (Throughput Optimized) type to the script so it gets recognized
volume_types_map = {u'standard': u'Standard/Magnetic', u'io1':
u'Provisioned IOPS (SSD)', u'gp2': u'General Purpose SSD', u'st1':
u'Throughput Optimized HDD'}

Web2py Error: <type 'exceptions.IndexError'> list index out of range

I am trying a web2py application here and I am getting error message. I tried multiple solutions on StackOverFlow and other web resources but couldn't make it work. I know it is problem with list but little point to right direction would be great help. However I tried few solutions and nothing worked for me.
CODE:
def __edit_survey():
surveys=db(db.survey.code_edit==request.args[0]).select()
if not surveys:
session.flash='survey not found'
redirect(URL('index'))
return surveys[0]
def __take_survey():
surveys=db(db.survey.code_take==request.args[0]).select()
if not surveys:
session.flash='survey not found'
redirect(URL('index'))
return surveys[0]
ERROR:
Error ticket for "SurveyAppFlourish"
Ticket ID
127.0.0.1.2017-09-23.04-40-15.58fadb34-fbc0-4064-b9e1-ecc67362eafa
<type 'exceptions.IndexError'> list index out of range
Version
web2py™
Version 2.15.3-stable+timestamp.2017.08.07.12.51.45
Python
Python 2.7.12: C:\Python27\python.exe (prefix: C:\Python27)
Traceback
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
Traceback (most recent call last):
File "C:\Users\Mudassar\PycharmProjects\web2pydemoproject\web2py\gluon\restricted.py", line 219, in restricted
exec(ccode, environment)
File "C:/Users/Mudassar/PycharmProjects/web2pydemoproject/web2py/applications/SurveyAppFlourish/controllers/survey.py", line 299, in <module>
File "C:\Users\Mudassar\PycharmProjects\web2pydemoproject\web2py\gluon\globals.py", line 409, in <lambda>
self._caller = lambda f: f()
File "C:/Users/Mudassar/PycharmProjects/web2pydemoproject/web2py/applications/SurveyAppFlourish/controllers/survey.py", line 88, in take
survey=__take_survey()
File "C:/Users/Mudassar/PycharmProjects/web2pydemoproject/web2py/applications/SurveyAppFlourish/controllers/survey.py", line 45, in __take_survey
surveys=db(db.survey.code_take==request.args[0]).select()
IndexError: list index out of range
Error is at surveys=db(db.survey.code_edit==request.args[0]).select()
In a URL of the form /app/controller/function/a/b/c, the parts of the path after function (i.e., a, b, and c in this case) are stored as a list in request.args. If request.args[0] is throwing an IndexError, that indicates there are no URL args in the requested URL.
request.args is not a standard Python list but an object of class gluon.storage.List. It is callable and takes some additional arguments to handle special cases. For example, you can specify a default when there are no URL args:
db(db.survey.code_edit == request.args(0, default=my_default)).select()
If you simply want a value of None when the item does not exist, you do not have to explicitly specify a default:
db(db.survey.code_edit == request.args(0)).select()
Above, request.args(0) will return None rather than raise an IndexError.
As an alternative, you can specify a redirect URL when the item is missing:
db(db.survey.code_edit == request.args(0, otherwise=URL('index')).select()
If there is no request.args[0], the above will redirect to the index URL. The otherwise argument can also be a function (so, for example, you could use it to set response.flash and then do a redirect).

TypeError: cannot concatenate 'str' and 'SFType' objects (simple-salesforce)

my project is to extract the contents of all my salesforce tables, including the custom ones. To do this, I need to know the names of the columns (fields), since SOQL does not support "SELECT * from TABLENAME".
With simple-salesforce, I know that the following works:
sf = Salesforce(username='foo#bar.com', password='abcd', security_token='ZCdsdPdE4eI2DZMl5gwCFIGEFU')
field_data = sf.Contact.describe()["fields"]
But my problem is that I need to parameterize the "Contact" string in the actual method call above, so that I can call this method for objects that I do not know the names of (ie not defined in standard salesforce). For example I need to do:
field_data = sf.CustomTableName.describe()["fields"]
When I try and use the SFType class:
contact = SFType('Contact',sf.sessionid,sf.sf_instance)
f = contact.describe()
I get this error:
Traceback (most recent call last):
File "./simple-example.py", line 13, in <module>
f = contact.describe()["fields"]
File "/Library/Python/2.7/site-packages/simple_salesforce/api.py", line 430, in describe
result = self._call_salesforce('GET', self.base_url + 'describe')
File "/Library/Python/2.7/site-packages/simple_salesforce/api.py", line 570, in _call_salesforce
'Authorization': 'Bearer ' + self.session_id,
TypeError: cannot concatenate 'str' and 'SFType' objects
Thanks in advance for any advice.
If you look in the source code for simple-salesforce (as of 2015-11-12) you'll see that in the init() of Salesforce() we set the session to self.session_id and instance to self.sf_instance
In your case, you're using sf.sessionid, and because simple-salesforce is setup to return a SFType() object whenever a method or property does not exist on Salesforce() (and sessionid does not exist on Salesforce()) you're actually inserting a SFType() object into the init of your SFType()
SFType.__init__() doesn't do any form of validation to confirm you're passing in strings as arguments, so the error you're getting is from simple-salesforce trying to use the SFType() object you're passing in as a string.
Try this code:
contact = SFType('Contact', sf.session_id, sf.sf_instance)
f = contact.describe()
I ran into the same issue and seemed to have fixed this by removing the protocol ("https://") from the instance_url. This is weird but seems to work for me now and I can do contact.describe()
Something like this:
contact = SFType(sf_object, session_id, instance_url.replace("https://",''))
contact.describe()

alchemyapi-recipes-twitter -Doesnot work properly

The github link for the code is given below:
https://github.com/AlchemyAPI/alchemyapi-recipes-twitter
I get the following error when I run recipe.py:
Traceback (most recent call last):
File "recipe.py", line 340, in <module>
main(sys.argv[1], int(sys.argv[2]))
File "recipe.py", line 43, in main
print_results()
File "recipe.py", line 303, in print_results
avg_pos_score = mean_results['result'][2]['avgScore']
TypeError: 'CommandCursor' object has no attribute '__getitem__'
I am using python version 2.7.6
Please do help me out to solve this.
Yeah, I finally got the correct output.Thanks to Games Brainiac for helping me to figure it out.
mean_results = list(tweets.aggregate([{"$group" : {"_id": "$sentiment",
"avgScore" : { "$avg" : "$score"}}}]))
avg_pos_score = mean_results[1]['avgScore']
avg_neg_score = mean_results[0]['avgScore']
The mean_results will contain a list of dictionary entities(in this case 3 entities-neg,pos,neutral).
So mean_results[0] refers to the negative entity.
mean_results[1] refers to the positive entity.
and so on.
mean_results[1]['avgScore]=avg score of the positive entity.
and so on...
I think you need to change line 301 to 304 to reflect the new changes in the API.
Firstly, change this line:
mean_results = tweets.aggregate([{"$group" : {"_id": "$sentiment", "avgScore" : { "$avg" : "$score"}}}])
to
mean_results = list(tweets.agg....)
So now, you no longer need to use the result for the CommandCursor.
Instead, what you have to do is this:
list(mean_results[2]['avgScore'])
Instead, and repeat with the next line too. Just remove the result part.

Categories